Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e9b99e415 | ||
|
|
8aadbd25fb | ||
|
|
9f341719ef | ||
|
|
5de9272281 | ||
|
|
a6d468bd2c | ||
|
|
b0f2c72b5f | ||
|
|
e586ab9bd9 | ||
|
|
68415f805b | ||
|
|
a4bfa3117f | ||
|
|
8935783371 | ||
|
|
cf56840df9 | ||
|
|
1c5c906cbb | ||
|
|
ac12301818 | ||
|
|
84dba6d670 | ||
|
|
ff83b6c7da | ||
|
|
a328ef5ea7 | ||
|
|
7d366e6368 | ||
|
|
5ea1e38f25 | ||
|
|
d99bb75fc2 | ||
|
|
d79415cbb3 | ||
|
|
1eea4eb8d8 | ||
|
|
385f51f3ba | ||
|
|
540a7ec96b | ||
|
|
4e79d3cd81 | ||
|
|
cbfd4404c1 | ||
|
|
50820b8b40 | ||
|
|
502a3e4f2c | ||
|
|
b57b55f3e1 | ||
|
|
06c662042b | ||
|
|
461669b3fb | ||
|
|
9580a7b2df | ||
|
|
86f9ac5603 | ||
|
|
6a91ce30e3 | ||
|
|
aa3bae9020 | ||
|
|
ba46789226 | ||
|
|
4e494ce4fd | ||
|
|
8c6158e8e3 | ||
|
|
b4cfe050fa | ||
|
|
a199700878 | ||
|
|
2a46b355db | ||
|
|
a50dce2755 | ||
|
|
8dbd319bba | ||
|
|
67e230a647 | ||
|
|
ad155e269c | ||
|
|
f268d0e3eb | ||
|
|
a779ab4667 | ||
|
|
e6aacc899d | ||
|
|
4dab218b75 | ||
|
|
622924ed53 | ||
|
|
6c43b53590 | ||
|
|
e66e53c817 | ||
|
|
a71be39076 | ||
|
|
5ec9fd0bc3 | ||
|
|
80d9af42b5 | ||
|
|
dcb002304b | ||
|
|
196bf4c2e8 | ||
|
|
0e47623a6b | ||
|
|
90be5a5490 | ||
|
|
1a2e786ca8 | ||
|
|
d34ea9e943 | ||
|
|
310997c3ae | ||
|
|
7acd1bc5a1 | ||
|
|
5ba327b745 | ||
|
|
238c52610a | ||
|
|
29e91b0078 | ||
|
|
56d23f913d | ||
|
|
d8ea2d0126 | ||
|
|
7223371fae | ||
|
|
11db983ea6 | ||
|
|
ccce3381c1 | ||
|
|
7444082b65 | ||
|
|
d511c85891 | ||
|
|
fd515ee459 | ||
|
|
b45f95d8cf | ||
|
|
1627733701 | ||
|
|
0e4a2e1819 | ||
|
|
99da7ac891 | ||
|
|
de0cbeef7c | ||
|
|
259dac806e | ||
|
|
673aa0f458 | ||
|
|
1c13e068ad | ||
|
|
2046e64428 | ||
|
|
fd655c3253 | ||
|
|
607abcafc5 |
No files matched your search
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.gitignore
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/.DS_Store
|
||||
**/*.log
|
||||
data
|
||||
keys
|
||||
**/*.tsbuildinfo
|
||||
+36
-12
@@ -1,17 +1,41 @@
|
||||
NODE_ENV=development
|
||||
PORT=3000
|
||||
## Optional overrides: copy to .env and uncomment the settings you need.
|
||||
## Every setting has a default (shown below), so liqa runs without a .env file.
|
||||
##
|
||||
## Lines starting with "##" are descriptions.
|
||||
## Lines starting with "# " are settings: remove the "# " to enable one.
|
||||
|
||||
# Directory (relative to cwd) containing *.json key descriptors
|
||||
KEYS_DIR=keys
|
||||
## production in the Docker image; also selects the default CORS origins
|
||||
# NODE_ENV=development
|
||||
# PORT=3000
|
||||
|
||||
# SQLite database path
|
||||
DB_PATH=data/sessions.db
|
||||
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
||||
## Vite dev server (http://localhost:5173) in development, the compose port
|
||||
## (http://localhost:13000) in production
|
||||
# CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
|
||||
|
||||
# Playwright executable (set in Docker; leave empty to use system default)
|
||||
## SQLite database path
|
||||
# DB_PATH=data/liqa.db
|
||||
|
||||
## Stored scenario files and run artifacts (downloads, failure dumps, traces)
|
||||
# FILES_DIR=data/files
|
||||
## Days to keep run artifacts before they are deleted
|
||||
# FILE_RUN_EXPIRATION_DAYS=7
|
||||
## When expired files are deleted (cron expression)
|
||||
# FILE_CLEANUP_CRON=0 3 * * *
|
||||
|
||||
## Close open sessions that have been idle for longer than this many minutes
|
||||
# SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||
## Delete closed sessions whose updatedAt is older than this many days
|
||||
# SESSION_DELETE_CLOSED_DAYS=7
|
||||
|
||||
## Playwright trace recording for scenario runs: on | retain-on-failure | off
|
||||
## (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
||||
# PLAYWRIGHT_TRACE_MODE=off
|
||||
|
||||
## Chromium binary to use instead of Playwright's own (not needed in Docker,
|
||||
## which ships Playwright's chromium-headless-shell)
|
||||
# PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
|
||||
# Session lifecycle
|
||||
# Close open sessions that have been idle for longer than this many minutes
|
||||
SESSION_IDLE_TIMEOUT_MINUTES=30
|
||||
# Delete closed sessions whose updatedAt is older than this many days
|
||||
SESSION_DELETE_CLOSED_DAYS=7
|
||||
## Directory with the built client to serve at / (the Docker image sets it to
|
||||
## "client"; leave unset to not serve the UI, e.g. when using the Vite dev server)
|
||||
# CLIENT_DIR=client
|
||||
+11
-2
@@ -1,6 +1,6 @@
|
||||
# runtime / secrets
|
||||
/keys
|
||||
# runtime
|
||||
/data
|
||||
server/data/
|
||||
.env
|
||||
*.log
|
||||
|
||||
@@ -13,3 +13,12 @@ server/dist
|
||||
client/dist
|
||||
*storybook.log
|
||||
storybook-static
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
# organization
|
||||
TODO.md
|
||||
|
||||
# IDE/editor
|
||||
.vscode/
|
||||
.idea/
|
||||
.github/
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 1.20.2 - 2026-09-30
|
||||
|
||||
Changes since 1.20.1:
|
||||
|
||||
### Fixed
|
||||
|
||||
- Text contrast now meets WCAG AA (4.5:1) in both themes:
|
||||
- the "Live" refresh label and the table sort icon use a new `--color-primary-text` token (dark lime in the light theme) instead of the light lime brand color;
|
||||
- the idle refresh label is no longer dimmed with opacity;
|
||||
- the light theme's danger button is a little darker, and the dark theme's danger hover is lighter so its dark text stays readable;
|
||||
- syntax highlighting colors are defined per theme (`--hl-*` tokens), darker in the light theme;
|
||||
- muted text is slightly darker in the light theme.
|
||||
|
||||
### Added
|
||||
|
||||
- A Storybook "Accessibility / Contrast" page that measures the contrast of the most contrast-prone components in both themes.
|
||||
- Storybook accessibility checks now fail the tests on violations (`a11y.test: 'error'`). The Colors story shows each token's current value per theme and includes the syntax colors.
|
||||
|
||||
## 1.20.1 - 2026-09-30
|
||||
|
||||
Changes since 1.20.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Storybook stories for AutoRefreshIndicator, CodeBlock, CodeEditor, MarkdownContent, Modal, Notification, Search, Textarea, Toast and UuidBadge, with interaction tests where the component has behavior. The DescriptionList story covers all four layouts.
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated all client and server dependencies to the latest versions within their ranges, including React 19.3, Storybook 10.6, NestJS 11.2, TypeORM 0.3.31 and Playwright 1.63 (the Docker image now ships HeadlessChrome 153).
|
||||
- The Storybook tests are part of the pre-commit checks.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Code flagged by the stricter React hooks lint rules: the runs list no longer writes refs during render, and the scenario list, scenario files and sessions list no longer set state synchronously inside effects.
|
||||
|
||||
## 1.20.0 - 2026-09-30
|
||||
|
||||
Changes since 1.19.3:
|
||||
|
||||
### Added
|
||||
|
||||
- Database migrations: the SQLite schema is now managed by TypeORM migrations (`server/src/database/migrations/`) instead of `synchronize`. The Docker container applies pending migrations before starting the server, and the server refuses to start while migrations are pending.
|
||||
- `npm -w server run migration:run`, `migration:show` and `migration:generate` scripts; the workflow for schema changes is described in `docs/development.md`.
|
||||
- A test that fails when an entity changes without a matching migration.
|
||||
|
||||
### Changed
|
||||
|
||||
- Databases created before migrations (by `synchronize`) are adopted automatically: the initial migration is recorded as applied without changing them.
|
||||
- Tests now build their database from the migrations instead of `synchronize`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Startup failures were logged but the process exited with code 0; they now exit with code 1.
|
||||
|
||||
## 1.19.3 - 2026-09-30
|
||||
|
||||
Changes since 1.19.2:
|
||||
|
||||
### Changed
|
||||
|
||||
- The Docker image runs with `NODE_ENV=production`.
|
||||
- The origins allowed to call the API cross-origin depend on `NODE_ENV`: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) in development, the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) in production. The new `CORS_ORIGINS` setting (comma separated) overrides both. A `NODE_ENV=development` in `.env` overrides the image's production mode.
|
||||
- `.env` is optional: compose loads it only when it exists, and every setting in `.env.example` is commented out and shows its default.
|
||||
|
||||
### Removed
|
||||
|
||||
- The unused `KEYS_DIR` setting and the `./keys` mount in `compose.yaml`.
|
||||
|
||||
## 1.19.2 - 2026-09-30
|
||||
|
||||
Changes since 1.19.1:
|
||||
|
||||
### Fixed
|
||||
|
||||
- Running a scenario from its detail page could preselect the first environment in the list instead of the scenario's default environment, depending on whether the environment list or the scenario loaded first. The default environment is now chosen when the run modal opens.
|
||||
- Made the run status filter test deterministic; it could fail when the scheduler picked up the test's pending run mid-test.
|
||||
|
||||
## 1.19.1 - 2026-09-30
|
||||
|
||||
Changes since 1.19.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- Upgraded to Node.js 24: the Docker image is based on `node:24-slim`, and the root `package.json` declares `"engines": { "node": ">=24" }`.
|
||||
- The server reads the app name and version (startup log, Swagger, MCP server info, `APP_NAME`/`APP_VERSION`) from the workspace root `package.json`. Previously local runs reported the server workspace's own `liqa-server` / `1.0.0`; the server workspace no longer has a version.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Tests using a local HTTP server bind to `127.0.0.1` instead of `localhost`, which could resolve to an unreachable `::1` inside Docker containers.
|
||||
|
||||
## 1.19.0 - 2026-09-30
|
||||
|
||||
Changes since 1.18.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking (deployment):** the whole application now runs from a single image and container. The server serves the built client itself (new `CLIENT_DIR` setting, set by the image) next to the API, MCP and Swagger, so the UI moved from http://localhost:13001 to **http://localhost:13000**. The root `Dockerfile` replaces `server/Dockerfile`, `client/Dockerfile` and `client/nginx.conf`, and `compose.yaml` has a single `liqa` service. When upgrading, run `docker compose up -d --build --remove-orphans` to remove the old `server` and `client` containers.
|
||||
- The image uses Playwright's headless-only Chromium build (`chromium-headless-shell`, always matching the installed Playwright version) with only the libraries it needs, instead of Debian's desktop `chromium` package. Fonts are now DejaVu and Liberation (metric-compatible with Arial/Times) instead of Noto. Together with clearing the npm cache, this shrinks the image from 1.76 GB to 1.07 GB.
|
||||
|
||||
## 1.18.0 - 2026-09-30
|
||||
|
||||
Changes since 1.17.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a central import: `POST /import`, an Import page in the UI, and the `import_yaml` MCP tool. It takes YAML made of `---`-separated documents, each holding one exported item or a list of items (JSON is accepted too), with any mix of environments, credentials, snippets and scenarios. All items are validated before anything is imported, and they are imported in dependency order (environments, credentials, snippets, scenarios), so a scenario can reference an environment or credential from the same file.
|
||||
|
||||
### Changed
|
||||
|
||||
- The Import buttons on the scenario, snippet, credential and environment list pages use the central import. When the file holds exactly one item of the page's kind, that item is opened; otherwise the Import page shows everything that was imported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Scenario exports that included the environment or credentials were not valid YAML (all entities were written into one document). Each entity is now a separate `---` document.
|
||||
|
||||
## 1.17.0 - 2026-09-30
|
||||
|
||||
Changes since 1.16.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Files can be deleted from a run: a delete button (with confirmation) in the Files section of the run detail page, `DELETE /scenarios/:id/runs/:runId/files/:fileId`, and the `delete_run_file` MCP tool. The stored file is removed once no scenario or run references it.
|
||||
|
||||
## 1.16.1 - 2026-09-30
|
||||
|
||||
Changes since 1.16.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- Playwright traces are now off by default (`PLAYWRIGHT_TRACE_MODE` defaults to `off`), since a trace often reaches ~10 MB per run. Traces can still be enabled per run in the run modal, via `traceMode` in `POST /scenarios/:id/run`, or for all runs by setting `PLAYWRIGHT_TRACE_MODE`.
|
||||
|
||||
## 1.16.0 - 2026-09-30
|
||||
|
||||
Changes since 1.15.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenarios and snippets are now versioned, starting at version 1. A scenario's version goes up when its name, description, default environment, timeout or steps change; a snippet's when its alias, title, description or code changes. Saving without changes does not create a new version. Credential assignments and scenario files are not versioned.
|
||||
- Each run records the scenario version it runs. The run modal has a version picker (latest by default), `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `version`, and "Repeat run" reuses the run's version.
|
||||
- `context.runSnippet("alias@N")` pins version N of a snippet; `runSnippet("alias")` keeps using the latest. The scenario page's "Used Snippets" section shows which snippets are pinned.
|
||||
- Version numbers are shown on the scenario, snippet and run pages and in the scenario and run lists.
|
||||
- Added `GET /scenarios/:id/versions[/:version]` and `GET /snippets/:id/versions[/:version]`, and the `list_scenario_versions`, `get_scenario_version`, `list_snippet_versions` and `get_snippet_version` MCP tools.
|
||||
- Scenario and snippet exports accept `?version=N` (the `export_scenario` MCP tool takes `version`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Breaking:** scenario and snippet exports now include `version`, and imports require it. An import restores that exact version by id + version: an existing version is left untouched, and a new one is stored under its number and becomes the latest when it is higher than the current latest. Export files from earlier releases need a `version` field added before they can be imported.
|
||||
- Scenario exports now include scenario and step timeouts.
|
||||
- Runs keep their own copy of the steps they were created with. Editing or deleting a step no longer changes past runs, and deleting a step no longer deletes its results from past runs. Existing run steps are backfilled from the current steps on startup.
|
||||
|
||||
## 1.15.0 - 2026-09-30
|
||||
|
||||
Changes since 1.14.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario runs now record a Playwright trace (screenshots and DOM snapshots) and upload it to the run's files as `trace.zip` when the run finishes. Open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
- Added the `PLAYWRIGHT_TRACE_MODE` setting (`on` (default), `retain-on-failure`, or `off`) that controls which traces are kept.
|
||||
- Added a "Playwright trace" option to the run modal to override the trace mode for a single run. It defaults to the server's `PLAYWRIGHT_TRACE_MODE`, served by the new `GET /scenarios/run-defaults` endpoint.
|
||||
- `POST /scenarios/:id/run` and the `run_scenario` MCP tool accept an optional `traceMode`. The trace mode is stored on the run, shown on the run detail page, and reused by "Repeat run".
|
||||
|
||||
### Changed
|
||||
|
||||
- The run modals on the scenario list and scenario detail pages now share one component.
|
||||
- `server/data/` is now git-ignored.
|
||||
|
||||
## 1.14.0 - 2026-09-30
|
||||
|
||||
Changes since 1.13.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Repeat run" button on the scenario run detail page that starts a new run of the same scenario with the same environment and "save session" setting, then navigates to it. The button is disabled when the run's environment has since been deleted.
|
||||
|
||||
## 1.13.0 - 2026-09-30
|
||||
|
||||
Changes since 1.12.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added credential CRUD tools to the MCP server: `list_credentials`, `get_credential`, `create_credential`, `update_credential`, and `delete_credential`. Combined with the existing `add_scenario_credential` tool, credentials can now be created and attached to scenarios entirely via MCP.
|
||||
|
||||
## 1.12.0 - 2026-09-16
|
||||
|
||||
Changes since 1.11.0:
|
||||
|
||||
### Added
|
||||
|
||||
- When a scenario or snippet step fails, a full-page screenshot and the current page HTML are captured and uploaded as run artifacts, so failures can be diagnosed from the run's file list.
|
||||
|
||||
## 1.11.0 - 2026-09-15
|
||||
|
||||
Changes since 1.10.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added export of a scenario as a standalone, plug-and-play Playwright e2e test project (zip archive with `package.json`, `playwright.config.ts`, `test.spec.ts`, `README.md`, `.env`, `credentials.json`, `snippets/*.js`, and any attached scenario files) that runs entirely independently of the liqa backend. Available as a "Export e2e test" button on the scenario detail page, `GET /scenarios/:id/export-e2e`, and the `export_e2e_test` MCP tool.
|
||||
- The exported test only bundles the credentials, snippets, and attached files actually referenced (directly or transitively) by the scenario's steps.
|
||||
- Added a "Used Snippets" section on the scenario detail page listing the snippets referenced by the scenario's steps, linking to each snippet's detail page. Backed by `GET /scenarios/:id/used-snippets`.
|
||||
|
||||
## 1.10.1 - 2026-09-15
|
||||
|
||||
Changes since 1.10.0:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.runSnippet()` now logs "Snippet started"/"finished"/"failed" entries, matching the automatic step start/pass/fail logging.
|
||||
|
||||
### Changed
|
||||
|
||||
- Reworked the Markdown log export format: each log entry is now its own `## [level] timestamp` section with the message as its body, instead of a single large table.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Run logs could persist out of call order (e.g. a snippet's "started" log appearing after its "finished" log) because writes were fire-and-forget and raced against each other. Log entries now carry a per-run sequence number assigned in call order, and queries/exports sort by it.
|
||||
|
||||
## 1.10.0 - 2026-09-15
|
||||
|
||||
Changes since 1.9.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added a "Download logs" button on the scenario run detail page: opens a modal to choose Markdown (default) or CSV, then downloads the run's logs in that format.
|
||||
- Added `GET /scenarios/:id/run/:runId/logs/export?format=csv|md` backend endpoint to export a run's logs.
|
||||
|
||||
## 1.9.1 - 2026-09-15
|
||||
|
||||
Changes since 1.9.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Scenario run logs now include an automatic entry when a step starts and when it finishes (pass or fail), so step boundaries are visible in run logs even for steps that don't call `context.log`/`context.assert` themselves.
|
||||
|
||||
## 1.9.0 - 2026-09-15
|
||||
|
||||
Changes since 1.8.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added `context.assert(fn, description)` for scenario/snippet script steps: runs the given function, requires it to return `true`, logs the outcome (`log` on success, `error` on failure or exception), and throws to stop the step on failure.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented `context.assert` in `docs/scenario.md`.
|
||||
|
||||
## 1.8.0 - 2026-09-15
|
||||
|
||||
Changes since 1.7.1:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.downloadFile()` now accepts `data:` URIs, so scenario steps can save in-script generated content (e.g. a credential JWT) as a run artifact without a network fetch.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented the full scenario step `context` file API (`getScenarioFiles`, `downloadFile`) in `docs/scenario.md`.
|
||||
|
||||
## 1.7.1 - 2026-04-21
|
||||
|
||||
Changes since 1.7.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Added MCP tools to upload, list, and fetch scenario files using base64 content payloads.
|
||||
- Added MCP tools to list run artifacts and fetch run artifact content with metadata.
|
||||
|
||||
### Changed
|
||||
|
||||
- Documented MCP binary content handling for scenario files and run artifacts.
|
||||
|
||||
## 1.7.0 - 2026-04-21
|
||||
|
||||
Changes since 1.6.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Added scenario file storage and run artifact support on the backend.
|
||||
- Added file management UI for scenarios and run details, including artifact lists.
|
||||
- Added snippet CRUD tools to the MCP server.
|
||||
|
||||
### Changed
|
||||
|
||||
- Added dynamic page titles based on the active client content.
|
||||
- Extended the scenarios list to show the latest run status and timestamp.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Exposed file expiry metadata in scenario and run file responses.
|
||||
- Disabled expired download actions in the UI while keeping the action visible.
|
||||
@@ -0,0 +1,56 @@
|
||||
# liqa
|
||||
|
||||
liqa is a browser automation and QA service for web applications. It stores **scenarios** (ordered Playwright steps), **snippets** (reusable code run via `context.runSnippet`), **environments**, **credentials** and **sessions**, and runs scenarios in headless Chromium. Scenarios and snippets are versioned; each run records the scenario version it executed.
|
||||
|
||||
It is an npm workspace with two packages:
|
||||
|
||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM; the schema is managed by migrations in `server/src/database/migrations/` (see "Database migrations" in `docs/development.md`). Any entity change needs a generated migration - `test/migrations.spec.ts` fails otherwise. REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
||||
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
||||
|
||||
## Docs
|
||||
|
||||
- [README.md](README.md) - overview
|
||||
- [docs/architecture.md](docs/architecture.md) - services and modules
|
||||
- [docs/development.md](docs/development.md) - local setup, running, testing, Docker
|
||||
- [docs/scenario.md](docs/scenario.md) - scenario execution, script `context` API, versioning, export/import, Playwright traces
|
||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [CHANGELOG.md](CHANGELOG.md) - release notes per version
|
||||
- [Dockerfile](Dockerfile) - single image: builds client and server, runtime serves both
|
||||
- [.env.example](.env.example) - all configuration variables (validated in `server/src/config/app.config.ts`)
|
||||
|
||||
## Default deployment (docker compose)
|
||||
|
||||
`compose.yaml` at the repo root runs a single `liqa` container, built from the root `Dockerfile`, at http://localhost:13000. The server serves everything: the UI at `/` (the built client, via `CLIENT_DIR`), the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. It reads `.env` if present (optional - every setting has a default) and mounts `./data` (SQLite DB `data/liqa.db` + stored files).
|
||||
|
||||
Rebuild and restart: `docker compose up -d --build`. Check with `docker compose ps`, `curl localhost:13000/health` and `docker compose logs liqa`.
|
||||
|
||||
The live database is `data/liqa.db`. The container applies pending migrations before starting the server, so back it up before deploying a release with new migrations.
|
||||
|
||||
## Code quality
|
||||
|
||||
Before committing, run and pass all of these (and report the results):
|
||||
|
||||
```bash
|
||||
# server
|
||||
cd server && npm run lint && npx tsc --noEmit -p tsconfig.json && npm test && npm run build
|
||||
# client
|
||||
cd client && npm run lint && npm run build && npm run test:storybook
|
||||
```
|
||||
|
||||
- Lint must stay clean in both packages (no errors, no warnings).
|
||||
- `test:storybook` runs every story in `client/.storybook/stories/` in headless Chromium (needs `npx playwright install --only-shell chromium` once, and again after Playwright updates). Add or update a story when adding or changing a `client/src/ui/` component.
|
||||
- Don't run prettier over whole existing files; several aren't prettier-clean and it produces unrelated diffs. Format only new files or the lines you changed.
|
||||
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
||||
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
||||
|
||||
## Committing a new version
|
||||
|
||||
When asked to commit:
|
||||
|
||||
1. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on the changes: patch for fixes and small behavior/default tweaks, minor for new features, major for breaking changes (e.g. changed API or export/import formats that old clients or files can't use).
|
||||
2. Run the code quality checks above.
|
||||
3. Bump `version` in the root `package.json` and in both places at the top of `package-lock.json` (the root entry and `packages[""]`). `server/package.json` and `client/package.json` keep their own versions; don't bump them.
|
||||
4. Add a `## <version> - <YYYY-MM-DD>` entry at the top of `CHANGELOG.md` ("Changes since <previous version>:", then `### Added` / `### Changed` / `### Fixed`). Mark breaking changes with **Breaking:**.
|
||||
5. Update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions).
|
||||
6. Build the commit message with the `/git-commit` skill if it is available, following its format and rules. Otherwise use a conventional commit message (`type(scope): subject`, then a bullet list body). Either way, put the version bump in the body as a bullet (e.g. `- bump version to <version>`), not in the subject line. This overrides the skill's rule of putting versions in the subject. Then make the commit with that message.
|
||||
7. **After committing, ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
# Single image serving the whole application: the NestJS server (API, MCP,
|
||||
# scheduler) also serves the built client, so one container is enough.
|
||||
|
||||
# ── Client build ──────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS client-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Root lockfile + workspace manifest so npm ci can resolve the full graph
|
||||
COPY package*.json ./
|
||||
COPY client/package.json ./client/
|
||||
RUN npm ci -w client
|
||||
|
||||
COPY client ./client
|
||||
RUN npm run -w client build
|
||||
|
||||
# ── Server build ──────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS server-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci -w server
|
||||
|
||||
COPY server/nest-cli.json ./server/
|
||||
COPY server/tsconfig*.json ./server/
|
||||
COPY server/src ./server/src
|
||||
RUN npm run -w server build
|
||||
|
||||
# ── Runtime ───────────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS runtime
|
||||
|
||||
# Runtime only: in the build stages it would make npm ci skip devDependencies
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Shared libraries chrome-headless-shell links against (from `ldd`), plus
|
||||
# fontconfig and basic fonts for text rendering. Playwright's `--with-deps`
|
||||
# would also pull in xvfb (with Mesa/LLVM) and extra font packages, which
|
||||
# headless-only use doesn't need.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
fontconfig \
|
||||
fonts-dejavu-core \
|
||||
fonts-liberation \
|
||||
libasound2 \
|
||||
libatk-bridge2.0-0 \
|
||||
libatk1.0-0 \
|
||||
libatspi2.0-0 \
|
||||
libdbus-1-3 \
|
||||
libexpat1 \
|
||||
libgbm1 \
|
||||
libglib2.0-0 \
|
||||
libnspr4 \
|
||||
libnss3 \
|
||||
libx11-6 \
|
||||
libxcb1 \
|
||||
libxcomposite1 \
|
||||
libxdamage1 \
|
||||
libxext6 \
|
||||
libxfixes3 \
|
||||
libxkbcommon0 \
|
||||
libxrandr2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
|
||||
# Playwright's headless-only Chromium build, matching the installed Playwright
|
||||
# version. All browser launches are headless, so the full desktop Chromium
|
||||
# (GTK, Mesa/LLVM, icon themes) isn't needed.
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
RUN npm ci --omit=dev -w server \
|
||||
&& npx playwright install --only-shell chromium \
|
||||
&& npm cache clean --force
|
||||
|
||||
COPY --from=server-build /app/server/dist ./dist
|
||||
COPY --from=client-build /app/client/dist ./client
|
||||
|
||||
# Serve the built client at / (see server/src/common/client-static.ts)
|
||||
ENV CLIENT_DIR=client
|
||||
|
||||
# Runtime directory (SQLite DB and stored files, mounted as a volume)
|
||||
RUN mkdir -p data
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# Apply pending database migrations, then start the server (which refuses to
|
||||
# start while migrations are pending)
|
||||
CMD ["sh", "-c", "node dist/database/migrate && exec node dist/main"]
|
||||
@@ -1,46 +1,40 @@
|
||||
# liquio-qa-bot
|
||||
# liqa
|
||||
|
||||
A headless QA automation service for Liquio environments. Exposes an **MCP (Model Context Protocol)** server that lets AI agents define, run, and monitor multi-step browser test scenarios using [Playwright](https://playwright.dev/).
|
||||
A browser automation and QA service for web applications. It stores multi-step browser scenarios, runs them with [Playwright](https://playwright.dev/) in headless Chromium, and keeps their results, logs and artifacts. Scenarios are managed from a web UI, a REST API, or an **MCP (Model Context Protocol)** server that lets AI agents define, run and debug them.
|
||||
|
||||
---
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
||||
|
||||
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The bot manages four core concepts:
|
||||
|
||||
| Concept | Description |
|
||||
|---|---|
|
||||
| **Environment** | A named set of URLs for a deployment target (e.g. `liquio-diia-stg`) |
|
||||
| **Key** | A JSON descriptor in `keys/` that points to an EDS key file + password |
|
||||
| **Session** | Saved browser state (cookies + localStorage) produced by a login |
|
||||
| **Scenario** | An ordered list of steps that run in sequence against a shared browser instance |
|
||||
| **Scenario** | An ordered list of steps (async Playwright JS) that run in sequence in one browser. Versioned: every content change creates a new version |
|
||||
| **Run** | One execution of a scenario version in an environment, with per-step status and output, logs, and run files (downloads, failure screenshots, Playwright traces) |
|
||||
| **Snippet** | Reusable, versioned code called from steps with `context.runSnippet("alias")` (or `"alias@N"` for a specific version) |
|
||||
| **Environment** | A named set of key/value settings for a deployment target (URLs etc.), read with `context.getEnv(key)` |
|
||||
| **Credential** | Secret data (e.g. a key file and password), assigned to scenarios under an alias and read with `context.getCredential(alias)` |
|
||||
| **Session** | Saved browser state (cookies + localStorage), e.g. kept from a run with "save session" |
|
||||
|
||||
Scenarios, snippets, environments and credentials can be exported as YAML and imported back (one file may hold several of them).
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
## Documentation
|
||||
|
||||
See [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
---
|
||||
|
||||
## Key descriptors
|
||||
|
||||
See [docs/key-descriptors.md](docs/key-descriptors.md).
|
||||
|
||||
---
|
||||
|
||||
## MCP tools
|
||||
|
||||
See [docs/mcp.md](docs/mcp.md).
|
||||
|
||||
---
|
||||
|
||||
## Scenario execution
|
||||
|
||||
See [docs/scenario.md](docs/scenario.md).
|
||||
|
||||
---
|
||||
|
||||
## Development
|
||||
|
||||
See [docs/development.md](docs/development.md) for setup, running, testing, linting, and Docker instructions.
|
||||
- [docs/architecture.md](docs/architecture.md) - components, data model, client
|
||||
- [docs/scenario.md](docs/scenario.md) - runs, the script `context` API, versioning, import/export, Playwright traces
|
||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [docs/development.md](docs/development.md) - setup, configuration, running, testing, linting, Docker
|
||||
- [CHANGELOG.md](CHANGELOG.md) - release notes
|
||||
@@ -0,0 +1,3 @@
|
||||
# Frontend API base URL.
|
||||
# Example for local Docker server: backend container is exposed on localhost:13000.
|
||||
VITE_API_URL=http://localhost:13000/api/v1
|
||||
@@ -12,7 +12,7 @@ function getAbsolutePath(value: string) {
|
||||
return dirname(fileURLToPath(import.meta.resolve(`${value}/package.json`)));
|
||||
}
|
||||
const config: StorybookConfig = {
|
||||
stories: ['./stories/**/*.mdx', './stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
|
||||
stories: ['./stories/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
|
||||
addons: [
|
||||
getAbsolutePath('@storybook/addon-vitest'),
|
||||
getAbsolutePath('@storybook/addon-a11y'),
|
||||
|
||||
@@ -37,7 +37,8 @@ const preview: Preview = {
|
||||
},
|
||||
},
|
||||
a11y: {
|
||||
test: 'todo',
|
||||
// Accessibility violations (e.g. color contrast) fail the story's test
|
||||
test: 'error',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, fn, userEvent, within } from 'storybook/test';
|
||||
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
|
||||
|
||||
const meta: Meta<typeof AutoRefreshIndicator> = {
|
||||
title: 'UI/AutoRefreshIndicator',
|
||||
component: AutoRefreshIndicator,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
args: { onClick: fn() },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof AutoRefreshIndicator>;
|
||||
|
||||
export const Active: Story = { args: { active: true, pulseKey: 1 } };
|
||||
export const Idle: Story = { args: { active: false } };
|
||||
export const Errored: Story = { args: { active: false, error: true } };
|
||||
|
||||
export const ClickToRefresh: Story = {
|
||||
args: { active: false },
|
||||
play: async ({ args, canvasElement }) => {
|
||||
await userEvent.click(within(canvasElement).getByRole('button'));
|
||||
await expect(args.onClick).toHaveBeenCalled();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect } from 'storybook/test';
|
||||
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
|
||||
|
||||
const meta: Meta<typeof CodeBlock> = {
|
||||
title: 'UI/CodeBlock',
|
||||
component: CodeBlock,
|
||||
parameters: { layout: 'padded' },
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof CodeBlock>;
|
||||
|
||||
export const JavaScript: Story = {
|
||||
args: {
|
||||
language: 'javascript',
|
||||
code: "const url = context.getEnv('BASE_URL');\nawait context.page.goto(url);\nreturn await context.page.title();",
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
// Highlighting splits the code into many spans: check the whole text and
|
||||
// that highlighting actually happened
|
||||
const code = canvasElement.querySelector('code');
|
||||
await expect(code).toHaveTextContent('await context.page.goto(url);');
|
||||
await expect(code?.querySelector('.hljs-keyword')).not.toBeNull();
|
||||
},
|
||||
};
|
||||
|
||||
export const Json: Story = {
|
||||
args: {
|
||||
language: 'json',
|
||||
code: JSON.stringify({ status: 'pass', output: { title: 'Dashboard' } }, null, 2),
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { CodeEditor, type CodeEditorProps } from '../../src/ui/CodeEditor/CodeEditor';
|
||||
|
||||
// Monaco is loaded from a CDN at runtime, so these stories only check that the
|
||||
// editor mounts; they have no interaction tests.
|
||||
function ControlledEditor(
|
||||
props: Omit<CodeEditorProps, 'value' | 'onChange'> & { initial: string },
|
||||
) {
|
||||
const { initial, ...rest } = props;
|
||||
const [value, setValue] = useState(initial);
|
||||
return <CodeEditor {...rest} value={value} onChange={setValue} />;
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ControlledEditor> = {
|
||||
title: 'UI/CodeEditor',
|
||||
component: ControlledEditor,
|
||||
parameters: { layout: 'padded' },
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ControlledEditor>;
|
||||
|
||||
export const JavaScript: Story = {
|
||||
args: {
|
||||
language: 'javascript',
|
||||
rows: 8,
|
||||
initial:
|
||||
"await context.page.goto(context.getEnv('BASE_URL'));\nreturn await context.page.title();",
|
||||
},
|
||||
};
|
||||
|
||||
export const WithError: Story = {
|
||||
args: { language: 'javascript', rows: 4, error: true, initial: 'await context.page.goto(' },
|
||||
};
|
||||
@@ -1,10 +1,16 @@
|
||||
import React from 'react';
|
||||
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
|
||||
const palette = [
|
||||
{ name: 'Atlantis', token: '--color-primary', hex: '#9DD341', role: 'Primary / Action' },
|
||||
{
|
||||
name: 'Atlantis text',
|
||||
token: '--color-primary-text',
|
||||
hex: '#496904',
|
||||
role: 'Primary as text / icon',
|
||||
},
|
||||
{ name: 'Outer Space', token: '--color-text', hex: '#2D3339', role: 'Text / Surface' },
|
||||
{ name: 'Kimberly', token: '--color-text-muted', hex: '#6650C0', role: 'Muted text / Info' },
|
||||
{ name: 'Kimberly', token: '--color-text-muted', hex: '#634DBD', role: 'Muted text / Info' },
|
||||
{ name: 'Powder Ash', token: '--color-border', hex: '#AFBFB9', role: 'Border / Neutral' },
|
||||
];
|
||||
|
||||
@@ -23,12 +29,23 @@ const semanticColors = [
|
||||
{ name: 'Running fg', token: '--color-running-fg', hex: '#6B4A00' },
|
||||
];
|
||||
|
||||
const syntaxColors = [
|
||||
{ name: 'Comment', token: '--hl-comment', hex: '#4F6557' },
|
||||
{ name: 'Keyword', token: '--hl-keyword', hex: '#764E99' },
|
||||
{ name: 'String / title', token: '--hl-string', hex: '#4F6821' },
|
||||
{ name: 'Number', token: '--hl-number', hex: '#895403' },
|
||||
{ name: 'Function', token: '--hl-function', hex: '#056980' },
|
||||
{ name: 'Variable / params', token: '--hl-variable', hex: '#815354' },
|
||||
{ name: 'Property', token: '--hl-property', hex: '#1D6971' },
|
||||
{ name: 'Meta', token: '--hl-meta', hex: '#615B7E' },
|
||||
];
|
||||
|
||||
const surfaceColors = [
|
||||
{ name: 'Background', token: '--color-bg', hex: '#E6EDEA' },
|
||||
{ name: 'Background subtle', token: '--color-bg-subtle', hex: '#D8E2DE' },
|
||||
{ name: 'Secondary', token: '--color-secondary', hex: '#EDF1EF' },
|
||||
{ name: 'Secondary hover', token: '--color-secondary-hover', hex: '#DFE6E3' },
|
||||
{ name: 'Danger', token: '--color-danger', hex: '#D94F4F' },
|
||||
{ name: 'Danger', token: '--color-danger', hex: '#CE4546' },
|
||||
{ name: 'Primary fg', token: '--color-primary-fg', hex: '#2D3339' },
|
||||
];
|
||||
|
||||
@@ -43,8 +60,27 @@ function Swatch({
|
||||
hex: string;
|
||||
role?: string;
|
||||
}) {
|
||||
// Show the token's current value (per theme) rather than a hard-coded copy
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [value, setValue] = useState(hex);
|
||||
useLayoutEffect(() => {
|
||||
const read = () => {
|
||||
if (!ref.current) return;
|
||||
const resolved = getComputedStyle(ref.current).getPropertyValue(token).trim();
|
||||
if (resolved) setValue(resolved.toUpperCase());
|
||||
};
|
||||
read();
|
||||
// Re-read when the theme toolbar switches data-theme on <html>
|
||||
const observer = new MutationObserver(read);
|
||||
observer.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['data-theme'],
|
||||
});
|
||||
return () => observer.disconnect();
|
||||
}, [token]);
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
@@ -72,7 +108,7 @@ function Swatch({
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
||||
{hex}
|
||||
{value}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, fontFamily: 'monospace', color: 'var(--color-text-muted)' }}>
|
||||
{token}
|
||||
@@ -128,6 +164,11 @@ function ColorPalette() {
|
||||
<Swatch key={c.token} {...c} />
|
||||
))}
|
||||
</Section>
|
||||
<Section title="Syntax highlighting">
|
||||
{syntaxColors.map((c) => (
|
||||
<Swatch key={c.token} {...c} />
|
||||
))}
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export default meta;
|
||||
type Story = StoryObj<typeof ContextMenu>;
|
||||
|
||||
const trigger = (
|
||||
<Button variant="ghost" size="sm">
|
||||
<Button variant="ghost" size="sm" aria-label="Actions">
|
||||
<Settings size={16} />
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { AutoRefreshIndicator } from '../../src/ui/AutoRefreshIndicator/AutoRefreshIndicator';
|
||||
import { Button } from '../../src/ui/Button/Button';
|
||||
import { CodeBlock } from '../../src/ui/CodeBlock/CodeBlock';
|
||||
|
||||
/*
|
||||
* Text contrast review page (WCAG AA: 4.5:1 for normal text, 3:1 for large
|
||||
* text) for the components where contrast is easiest to get wrong: light
|
||||
* brand colors used as text, dimmed labels, colored buttons and syntax
|
||||
* highlighting. Every sample is the real component, shown in both themes, and
|
||||
* the contrast of each piece of text is measured live from the rendered
|
||||
* colors - so this page stays accurate as the design tokens change.
|
||||
*/
|
||||
|
||||
// ── Contrast measurement ─────────────────────────────────────────────────────
|
||||
|
||||
type Rgba = [number, number, number, number];
|
||||
|
||||
function parseColor(value: string): Rgba {
|
||||
const parts = value.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0];
|
||||
return [parts[0], parts[1], parts[2], parts[3] ?? 1];
|
||||
}
|
||||
|
||||
function luminance([r, g, b]: Rgba): number {
|
||||
const channel = (c: number) => {
|
||||
const s = c / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
||||
}
|
||||
|
||||
function contrast(a: Rgba, b: Rgba): number {
|
||||
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||
return (hi + 0.05) / (lo + 0.05);
|
||||
}
|
||||
|
||||
/** Blends `top` over an opaque `bottom`. */
|
||||
function blend(top: Rgba, bottom: Rgba): Rgba {
|
||||
const a = top[3];
|
||||
return [0, 1, 2].map((i) => top[i] * a + bottom[i] * (1 - a)).concat(1) as Rgba;
|
||||
}
|
||||
|
||||
/** Product of the `opacity` of `el` and its ancestors (e.g. a dimmed idle label). */
|
||||
function opacityChain(el: Element): number {
|
||||
let opacity = 1;
|
||||
for (let node: Element | null = el; node; node = node.parentElement) {
|
||||
opacity *= parseFloat(getComputedStyle(node).opacity);
|
||||
}
|
||||
return opacity;
|
||||
}
|
||||
|
||||
/** The opaque color behind `el`, from its own and its ancestors' backgrounds. */
|
||||
function effectiveBackground(el: Element): Rgba {
|
||||
const layers: Rgba[] = [];
|
||||
for (let node: Element | null = el; node; node = node.parentElement) {
|
||||
const bg = parseColor(getComputedStyle(node).backgroundColor);
|
||||
bg[3] *= opacityChain(node);
|
||||
if (bg[3] > 0) layers.push(bg);
|
||||
if (bg[3] >= 1) break;
|
||||
}
|
||||
return layers.reduceRight<Rgba>((under, layer) => blend(layer, under), [255, 255, 255, 1]);
|
||||
}
|
||||
|
||||
const hex = ([r, g, b]: Rgba) =>
|
||||
'#' + [r, g, b].map((c) => Math.round(c).toString(16).padStart(2, '0')).join('');
|
||||
|
||||
interface Measurement {
|
||||
text: string;
|
||||
fg: string;
|
||||
bg: string;
|
||||
ratio: number;
|
||||
required: number;
|
||||
}
|
||||
|
||||
/** Measures every element that directly contains visible text. */
|
||||
function measure(root: HTMLElement): Measurement[] {
|
||||
const seen = new Set<string>();
|
||||
const results: Measurement[] = [];
|
||||
for (const el of Array.from(root.querySelectorAll<HTMLElement>('*'))) {
|
||||
const text = Array.from(el.childNodes)
|
||||
.filter((n) => n.nodeType === Node.TEXT_NODE)
|
||||
.map((n) => n.textContent ?? '')
|
||||
.join('')
|
||||
.trim();
|
||||
if (!text || el.closest('[aria-hidden="true"]')) continue;
|
||||
const style = getComputedStyle(el);
|
||||
const fontSize = parseFloat(style.fontSize);
|
||||
const bold = Number(style.fontWeight) >= 700;
|
||||
// WCAG "large text": at least 24px, or 18.66px bold
|
||||
const required = fontSize >= 24 || (bold && fontSize >= 18.66) ? 3 : 4.5;
|
||||
const bgColor = effectiveBackground(el);
|
||||
const fg = parseColor(style.color);
|
||||
fg[3] *= opacityChain(el);
|
||||
const fgColor = blend(fg, bgColor);
|
||||
const key = `${hex(fgColor)}|${hex(bgColor)}|${required}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
results.push({
|
||||
text: text.length > 28 ? `${text.slice(0, 28)}…` : text,
|
||||
fg: hex(fgColor),
|
||||
bg: hex(bgColor),
|
||||
ratio: contrast(fgColor, bgColor),
|
||||
required,
|
||||
});
|
||||
}
|
||||
return results.sort((a, b) => a.ratio / a.required - b.ratio / b.required);
|
||||
}
|
||||
|
||||
function Readout({ items }: { items: Measurement[] }) {
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 8 }}>
|
||||
<tbody>
|
||||
{items.map((m) => {
|
||||
const pass = m.ratio >= m.required;
|
||||
return (
|
||||
<tr
|
||||
key={`${m.fg}${m.bg}${m.required}`}
|
||||
style={{ borderTop: '1px solid var(--color-border)' }}
|
||||
>
|
||||
<td style={{ padding: '4px 6px' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
padding: '1px 6px',
|
||||
borderRadius: 3,
|
||||
background: m.bg,
|
||||
color: m.fg,
|
||||
fontFamily: 'monospace',
|
||||
}}
|
||||
>
|
||||
{m.text}
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: '4px 6px',
|
||||
fontFamily: 'monospace',
|
||||
color: 'var(--color-text-muted)',
|
||||
}}
|
||||
>
|
||||
{m.fg} on {m.bg}
|
||||
</td>
|
||||
<td
|
||||
style={{
|
||||
padding: '4px 6px',
|
||||
textAlign: 'right',
|
||||
fontWeight: 700,
|
||||
whiteSpace: 'nowrap',
|
||||
color: pass ? 'var(--color-text)' : 'var(--color-danger)',
|
||||
}}
|
||||
>
|
||||
{m.ratio.toFixed(2)}:1 {pass ? '✓' : `✗ needs ${m.required}:1`}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders a sample and measures its text contrast after layout. */
|
||||
function Sample({ children }: { children: React.ReactNode }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [items, setItems] = useState<Measurement[]>([]);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
// Measure after the theme/styles have applied
|
||||
const frame = requestAnimationFrame(() => setItems(measure(el)));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, []);
|
||||
return (
|
||||
<div>
|
||||
<div ref={ref}>{children}</div>
|
||||
<Readout items={items} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Page ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Covers every syntax color: comment, keyword, string, number, function
|
||||
// (title), params, property
|
||||
const JS_CODE = [
|
||||
'// Open the app and wait for the dashboard',
|
||||
'async function openDashboard(context, timeoutMs) {',
|
||||
" const url = context.getEnv('BASE_URL');",
|
||||
' await context.page.goto(url, { timeout: timeoutMs ?? 30000 });',
|
||||
' return context.page.title();',
|
||||
'}',
|
||||
].join('\n');
|
||||
const JSON_CODE = JSON.stringify(
|
||||
{ status: 'pass', attempts: 2, cached: false, output: { title: 'Dashboard' } },
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
interface Issue {
|
||||
title: string;
|
||||
note: string;
|
||||
render: () => React.ReactNode;
|
||||
}
|
||||
|
||||
const ISSUES: Issue[] = [
|
||||
{
|
||||
title: 'AutoRefreshIndicator label',
|
||||
note: 'Active ("Live", --color-primary-text), idle and error labels (runs pages).',
|
||||
render: () => (
|
||||
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
|
||||
<AutoRefreshIndicator active pulseKey={1} />
|
||||
<AutoRefreshIndicator active={false} />
|
||||
<AutoRefreshIndicator active={false} error />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Danger button',
|
||||
note: 'Danger, primary and secondary buttons (text on colored backgrounds).',
|
||||
render: () => (
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<Button variant="danger">Delete</Button>
|
||||
<Button variant="danger" size="sm">
|
||||
Delete
|
||||
</Button>
|
||||
<Button variant="primary">Run</Button>
|
||||
<Button variant="secondary">Cancel</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Code highlighting - JavaScript',
|
||||
note: 'All --hl-* syntax colors on the page background (step code, snippets).',
|
||||
render: () => <CodeBlock language="javascript" code={JS_CODE} />,
|
||||
},
|
||||
{
|
||||
title: 'Code highlighting - JSON',
|
||||
note: 'Keys, strings, numbers and literals in JSON step outputs.',
|
||||
render: () => <CodeBlock language="json" code={JSON_CODE} />,
|
||||
},
|
||||
{
|
||||
title: 'Muted text',
|
||||
note: '--color-text-muted on both background shades (hints, table headers, descriptions).',
|
||||
render: () => (
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
{['var(--color-bg)', 'var(--color-bg-subtle)'].map((bg) => (
|
||||
<span
|
||||
key={bg}
|
||||
style={{
|
||||
background: bg,
|
||||
color: 'var(--color-text-muted)',
|
||||
padding: '4px 8px',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
Last run 2 minutes ago
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
function Panel({ theme }: { theme: 'light' | 'dark' }) {
|
||||
return (
|
||||
<section
|
||||
// The dark tokens apply under [data-theme="dark"]; light is the page default
|
||||
data-theme={theme === 'dark' ? 'dark' : undefined}
|
||||
style={{
|
||||
flex: '1 1 420px',
|
||||
minWidth: 0,
|
||||
padding: 16,
|
||||
borderRadius: 8,
|
||||
background: 'var(--color-bg)',
|
||||
color: 'var(--color-text)',
|
||||
border: '1px solid var(--color-border)',
|
||||
}}
|
||||
>
|
||||
<h2 style={{ margin: '0 0 12px', fontSize: 16 }}>
|
||||
{theme === 'dark' ? 'Dark theme' : 'Light theme'}
|
||||
</h2>
|
||||
{ISSUES.map((issue) => (
|
||||
<div key={issue.title} style={{ marginBottom: 24 }}>
|
||||
<h3 style={{ margin: '0 0 2px', fontSize: 14 }}>{issue.title}</h3>
|
||||
<p style={{ margin: '0 0 8px', fontSize: 12, color: 'var(--color-text-muted)' }}>
|
||||
{issue.note}
|
||||
</p>
|
||||
<Sample>{issue.render()}</Sample>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ContrastPage() {
|
||||
return (
|
||||
<div style={{ padding: 16 }}>
|
||||
<p
|
||||
style={{
|
||||
margin: '0 0 16px',
|
||||
fontSize: 13,
|
||||
color: 'var(--color-text-muted)',
|
||||
maxWidth: 820,
|
||||
}}
|
||||
>
|
||||
Text contrast of the components where it's easiest to get wrong (WCAG AA: 4.5:1 for normal
|
||||
text, 3:1 for large text). Each row is a piece of text in the sample, measured from its
|
||||
rendered colors, worst first.
|
||||
</p>
|
||||
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
|
||||
<Panel theme="light" />
|
||||
<Panel theme="dark" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ContrastPage> = {
|
||||
title: 'Accessibility/Contrast',
|
||||
component: ContrastPage,
|
||||
// a11y checks use the project default ('error' in preview.tsx)
|
||||
parameters: { layout: 'fullscreen' },
|
||||
// The light panel relies on the page default (light) theme
|
||||
globals: { theme: 'light' },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ContrastPage>;
|
||||
|
||||
export const Overview: Story = {};
|
||||
@@ -15,7 +15,7 @@ const meta: Meta<typeof DescriptionList> = {
|
||||
),
|
||||
],
|
||||
argTypes: {
|
||||
layout: { control: 'select', options: ['inline', 'compact'] },
|
||||
layout: { control: 'select', options: ['inline', 'compact', 'comfortable', 'grid'] },
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
@@ -35,6 +35,14 @@ export const Compact: Story = {
|
||||
args: { items: urlItems, layout: 'compact' },
|
||||
};
|
||||
|
||||
export const Comfortable: Story = {
|
||||
args: { items: urlItems, layout: 'comfortable' },
|
||||
};
|
||||
|
||||
export const Grid: Story = {
|
||||
args: { items: urlItems, layout: 'grid' },
|
||||
};
|
||||
|
||||
export const WithLinks: Story = {
|
||||
args: {
|
||||
layout: 'inline',
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, within } from 'storybook/test';
|
||||
import { MarkdownContent } from '../../src/ui/MarkdownContent/MarkdownContent';
|
||||
|
||||
const meta: Meta<typeof MarkdownContent> = {
|
||||
title: 'UI/MarkdownContent',
|
||||
component: MarkdownContent,
|
||||
parameters: { layout: 'padded' },
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof MarkdownContent>;
|
||||
|
||||
export const Description: Story = {
|
||||
args: {
|
||||
content: [
|
||||
'## Login flow',
|
||||
'',
|
||||
'Logs in with the **test user** and checks the dashboard.',
|
||||
'',
|
||||
'- Uses the `BASE_URL` environment value',
|
||||
'- Needs the `user` credential alias',
|
||||
'',
|
||||
'```js',
|
||||
"await context.page.goto(context.getEnv('BASE_URL'));",
|
||||
'```',
|
||||
].join('\n'),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole('heading', { name: 'Login flow' })).toBeInTheDocument();
|
||||
await expect(canvas.getByText('test user').tagName).toBe('STRONG');
|
||||
await expect(canvas.getAllByRole('listitem')).toHaveLength(2);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, userEvent, within } from 'storybook/test';
|
||||
import { Modal } from '../../src/ui/Modal/Modal';
|
||||
import { Button } from '../../src/ui/Button/Button';
|
||||
|
||||
function ModalDemo({ title, body }: { title: string; body: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setOpen(true)}>Open modal</Button>
|
||||
<Modal
|
||||
open={open}
|
||||
title={title}
|
||||
onClose={() => setOpen(false)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => setOpen(false)}>Confirm</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{body}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ModalDemo> = {
|
||||
title: 'UI/Modal',
|
||||
component: ModalDemo,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
args: { title: 'Delete scenario', body: 'This deletes the scenario, its versions and its runs.' },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ModalDemo>;
|
||||
|
||||
export const Default: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||
const dialog = canvas.getByRole('dialog', { name: 'Delete scenario' });
|
||||
await expect(dialog).toHaveTextContent('its versions and its runs');
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
|
||||
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const ClosesOnEscapeAndBackdrop: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||
await userEvent.keyboard('{Escape}');
|
||||
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||
await userEvent.click(canvas.getByRole('presentation'));
|
||||
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { Notification } from '../../src/ui/Notification/Notification';
|
||||
|
||||
const meta: Meta<typeof Notification> = {
|
||||
title: 'UI/Notification',
|
||||
component: Notification,
|
||||
parameters: { layout: 'padded' },
|
||||
tags: ['autodocs'],
|
||||
argTypes: {
|
||||
variant: { control: 'select', options: ['info', 'success', 'error', 'warning', 'note'] },
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof Notification>;
|
||||
|
||||
export const Info: Story = {
|
||||
args: {
|
||||
variant: 'info',
|
||||
title: 'Traces are off',
|
||||
children: 'Enable them per run in the run modal.',
|
||||
},
|
||||
};
|
||||
export const Success: Story = { args: { variant: 'success', children: 'Scenario imported.' } };
|
||||
export const Error: Story = {
|
||||
args: { variant: 'error', title: 'Run failed', children: 'Step 2 timed out after 60s.' },
|
||||
};
|
||||
export const Warning: Story = {
|
||||
args: { variant: 'warning', children: 'The environment of this run no longer exists.' },
|
||||
};
|
||||
export const Note: Story = { args: { variant: 'note', children: 'Pinned snippet version: v3.' } };
|
||||
@@ -0,0 +1,34 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, userEvent, within } from 'storybook/test';
|
||||
import { Search } from '../../src/ui/Search/Search';
|
||||
|
||||
function ControlledSearch({ placeholder }: { placeholder?: string }) {
|
||||
const [value, setValue] = useState('');
|
||||
return (
|
||||
<div>
|
||||
<Search value={value} onChange={setValue} placeholder={placeholder} />
|
||||
<p data-testid="query">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ControlledSearch> = {
|
||||
title: 'UI/Search',
|
||||
component: ControlledSearch,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ControlledSearch>;
|
||||
|
||||
export const Default: Story = {};
|
||||
|
||||
export const Typing: Story = {
|
||||
args: { placeholder: 'Filter logs…' },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.type(canvas.getByPlaceholderText('Filter logs…'), 'timeout');
|
||||
await expect(canvas.getByTestId('query')).toHaveTextContent('timeout');
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, within } from 'storybook/test';
|
||||
import { Textarea } from '../../src/ui/Textarea/Textarea';
|
||||
|
||||
const meta: Meta<typeof Textarea> = {
|
||||
title: 'UI/Textarea',
|
||||
component: Textarea,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div style={{ width: 360 }}>
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof Textarea>;
|
||||
|
||||
export const Default: Story = {
|
||||
args: { label: 'Description', placeholder: 'Describe this scenario', rows: 4 },
|
||||
};
|
||||
|
||||
export const WithHint: Story = {
|
||||
args: { label: 'Description', hint: 'Markdown is supported.', rows: 4 },
|
||||
};
|
||||
|
||||
export const WithError: Story = {
|
||||
args: { label: 'Description', error: 'Description is too long.', rows: 4 },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const textarea = canvas.getByLabelText('Description');
|
||||
await expect(textarea).toHaveAttribute('aria-invalid', 'true');
|
||||
await expect(canvas.getByRole('alert')).toHaveTextContent('Description is too long.');
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, userEvent, within } from 'storybook/test';
|
||||
import { ToastProvider } from '../../src/ui/Toast/ToastProvider';
|
||||
import { useToast } from '../../src/ui/Toast/useToast';
|
||||
import { Button } from '../../src/ui/Button/Button';
|
||||
|
||||
function ToastButtons() {
|
||||
const toast = useToast();
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<Button onClick={() => toast.success('Scenario run started')}>Success</Button>
|
||||
<Button variant="danger" onClick={() => toast.error('Environment not found')}>
|
||||
Error
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => toast.info('Traces are off')}>
|
||||
Info
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ToastProvider> = {
|
||||
title: 'UI/Toast',
|
||||
component: ToastProvider,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
args: { durationMs: 3500, children: <ToastButtons /> },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ToastProvider>;
|
||||
|
||||
export const Default: Story = {};
|
||||
|
||||
export const ShowsToast: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Success' }));
|
||||
await expect(await within(document.body).findByText('Scenario run started')).toBeVisible();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, within } from 'storybook/test';
|
||||
import { UuidBadge } from '../../src/ui/UuidBadge/UuidBadge';
|
||||
|
||||
const meta: Meta<typeof UuidBadge> = {
|
||||
title: 'UI/UuidBadge',
|
||||
component: UuidBadge,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof UuidBadge>;
|
||||
|
||||
export const Default: Story = {
|
||||
args: { id: '61d2b1c2-7664-4dca-974f-436c2ee90b2e' },
|
||||
play: async ({ canvasElement }) => {
|
||||
// Shows a shortened id and keeps the full one in the tooltip
|
||||
const badge = within(canvasElement).getByTitle('61d2b1c2-7664-4dca-974f-436c2ee90b2e');
|
||||
await expect(badge).toHaveTextContent('61d2…0b2e');
|
||||
},
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
# ── Build stage ───────────────────────────────────────────────────────────────
|
||||
FROM node:22-slim AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy root lockfile + workspace manifests so npm ci can resolve the full graph
|
||||
COPY package*.json ./
|
||||
COPY client/package.json ./client/
|
||||
RUN npm ci -w client
|
||||
|
||||
COPY client ./client
|
||||
RUN npm run -w client build
|
||||
|
||||
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
||||
FROM nginx:alpine AS runtime
|
||||
|
||||
COPY --from=builder /app/client/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
@@ -4,23 +4,30 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:compose-api": "VITE_API_URL=http://localhost:13000/api/v1 vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"storybook": "storybook dev -p 6006",
|
||||
"build-storybook": "storybook build",
|
||||
"test:compile": "tsc --noEmit",
|
||||
"test:storybook": "vitest run --project storybook",
|
||||
"lint": "eslint src .storybook",
|
||||
"lint:fix": "eslint src .storybook --fix",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx}\" \".storybook/**/*.{ts,tsx}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@tanstack/react-query": "^5.99.0",
|
||||
"highlight.js": "^11.11.1",
|
||||
"i18next": "^26.0.4",
|
||||
"lucide-react": "^1.7.0",
|
||||
"moment": "^2.30.1",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-i18next": "^17.0.2",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^7.14.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"yaml": "^2.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -30,6 +30,28 @@
|
||||
padding: var(--space-2) 0;
|
||||
}
|
||||
|
||||
.sideContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.sideFooter {
|
||||
margin-top: auto;
|
||||
padding: var(--space-3) var(--space-2) var(--space-2);
|
||||
border-top: var(--border-width) solid var(--color-border);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.version {
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.navItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -73,6 +95,12 @@
|
||||
background: var(--color-secondary-hover);
|
||||
}
|
||||
|
||||
.navSeparator {
|
||||
height: var(--border-width);
|
||||
background: var(--color-border);
|
||||
margin: var(--space-2) var(--space-2);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
|
||||
+152
-75
@@ -1,43 +1,108 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe, KeyRound, Monitor, ClipboardList, Activity, KeySquare, Braces } from 'lucide-react';
|
||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import styles from './App.module.css';
|
||||
import { SidePanel, ThemeSwitcher } from './ui';
|
||||
import liqaLogo from './assets/liqa.svg';
|
||||
import { EnvironmentsPage } from './pages/environment/EnvironmentsPage';
|
||||
import { EnvironmentDetailPage } from './pages/environment/EnvironmentDetailPage';
|
||||
import { CreateEnvironmentPage } from './pages/environment/CreateEnvironmentPage';
|
||||
import { EditEnvironmentPage } from './pages/environment/EditEnvironmentPage';
|
||||
import { KeysPage } from './pages/KeysPage';
|
||||
import { SessionsPage } from './pages/session/SessionsPage';
|
||||
import { SessionDetailPage } from './pages/session/SessionDetailPage';
|
||||
import { ScenariosPage } from './pages/scenario/ScenariosPage';
|
||||
import { ScenarioDetailPage } from './pages/scenario/ScenarioDetailPage';
|
||||
import { CreateScenarioPage } from './pages/scenario/CreateScenarioPage';
|
||||
import { EditScenarioPage } from './pages/scenario/EditScenarioPage';
|
||||
import { CreateStepPage } from './pages/scenario/CreateStepPage';
|
||||
import { EditStepPage } from './pages/scenario/EditStepPage';
|
||||
import { RunsPage } from './pages/run/RunsPage';
|
||||
import { RunDetailPage } from './pages/run/RunDetailPage';
|
||||
import { AllRunsPage } from './pages/run/AllRunsPage';
|
||||
import { CredentialsPage } from './pages/credential/CredentialsPage';
|
||||
import { CreateCredentialPage } from './pages/credential/CreateCredentialPage';
|
||||
import { EditCredentialPage } from './pages/credential/EditCredentialPage';
|
||||
import { CredentialDetailPage } from './pages/credential/CredentialDetailPage';
|
||||
import { SnippetsPage } from './pages/snippet/SnippetsPage';
|
||||
import { CreateSnippetPage } from './pages/snippet/CreateSnippetPage';
|
||||
import { EditSnippetPage } from './pages/snippet/EditSnippetPage';
|
||||
import { SnippetDetailPage } from './pages/snippet/SnippetDetailPage';
|
||||
|
||||
const NAV: { path: string; labelKey: string; Icon: LucideIcon }[] = [
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeySquare },
|
||||
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
|
||||
{ path: '/keys', labelKey: 'nav.keys', Icon: KeyRound },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
const EnvironmentsPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
||||
);
|
||||
const EnvironmentDetailPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentDetailPage').then((m) => ({
|
||||
default: m.EnvironmentDetailPage,
|
||||
})),
|
||||
);
|
||||
const CreateEnvironmentPage = lazy(() =>
|
||||
import('./pages/environment/CreateEnvironmentPage').then((m) => ({
|
||||
default: m.CreateEnvironmentPage,
|
||||
})),
|
||||
);
|
||||
const EditEnvironmentPage = lazy(() =>
|
||||
import('./pages/environment/EditEnvironmentPage').then((m) => ({
|
||||
default: m.EditEnvironmentPage,
|
||||
})),
|
||||
);
|
||||
|
||||
const SessionsPage = lazy(() =>
|
||||
import('./pages/session/SessionsPage').then((m) => ({ default: m.SessionsPage })),
|
||||
);
|
||||
const SessionDetailPage = lazy(() =>
|
||||
import('./pages/session/SessionDetailPage').then((m) => ({ default: m.SessionDetailPage })),
|
||||
);
|
||||
|
||||
const ScenariosPage = lazy(() =>
|
||||
import('./pages/scenario/ScenariosPage').then((m) => ({ default: m.ScenariosPage })),
|
||||
);
|
||||
const ScenarioDetailPage = lazy(() =>
|
||||
import('./pages/scenario/ScenarioDetailPage').then((m) => ({ default: m.ScenarioDetailPage })),
|
||||
);
|
||||
const CreateScenarioPage = lazy(() =>
|
||||
import('./pages/scenario/CreateScenarioPage').then((m) => ({ default: m.CreateScenarioPage })),
|
||||
);
|
||||
const EditScenarioPage = lazy(() =>
|
||||
import('./pages/scenario/EditScenarioPage').then((m) => ({ default: m.EditScenarioPage })),
|
||||
);
|
||||
const CreateStepPage = lazy(() =>
|
||||
import('./pages/scenario/CreateStepPage').then((m) => ({ default: m.CreateStepPage })),
|
||||
);
|
||||
const EditStepPage = lazy(() =>
|
||||
import('./pages/scenario/EditStepPage').then((m) => ({ default: m.EditStepPage })),
|
||||
);
|
||||
|
||||
const RunsPage = lazy(() => import('./pages/run/RunsPage').then((m) => ({ default: m.RunsPage })));
|
||||
const RunDetailPage = lazy(() =>
|
||||
import('./pages/run/RunDetailPage').then((m) => ({ default: m.RunDetailPage })),
|
||||
);
|
||||
const AllRunsPage = lazy(() =>
|
||||
import('./pages/run/AllRunsPage').then((m) => ({ default: m.AllRunsPage })),
|
||||
);
|
||||
|
||||
const CredentialsPage = lazy(() =>
|
||||
import('./pages/credential/CredentialsPage').then((m) => ({ default: m.CredentialsPage })),
|
||||
);
|
||||
const CreateCredentialPage = lazy(() =>
|
||||
import('./pages/credential/CreateCredentialPage').then((m) => ({
|
||||
default: m.CreateCredentialPage,
|
||||
})),
|
||||
);
|
||||
const EditCredentialPage = lazy(() =>
|
||||
import('./pages/credential/EditCredentialPage').then((m) => ({ default: m.EditCredentialPage })),
|
||||
);
|
||||
const CredentialDetailPage = lazy(() =>
|
||||
import('./pages/credential/CredentialDetailPage').then((m) => ({
|
||||
default: m.CredentialDetailPage,
|
||||
})),
|
||||
);
|
||||
|
||||
const SnippetsPage = lazy(() =>
|
||||
import('./pages/snippet/SnippetsPage').then((m) => ({ default: m.SnippetsPage })),
|
||||
);
|
||||
const CreateSnippetPage = lazy(() =>
|
||||
import('./pages/snippet/CreateSnippetPage').then((m) => ({ default: m.CreateSnippetPage })),
|
||||
);
|
||||
const EditSnippetPage = lazy(() =>
|
||||
import('./pages/snippet/EditSnippetPage').then((m) => ({ default: m.EditSnippetPage })),
|
||||
);
|
||||
const SnippetDetailPage = lazy(() =>
|
||||
import('./pages/snippet/SnippetDetailPage').then((m) => ({ default: m.SnippetDetailPage })),
|
||||
);
|
||||
const ImportPage = lazy(() =>
|
||||
import('./pages/import/ImportPage').then((m) => ({ default: m.ImportPage })),
|
||||
);
|
||||
|
||||
const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator: true })[] = [
|
||||
{ path: '/runs', labelKey: 'nav.runs', Icon: Activity },
|
||||
{ path: '/sessions', labelKey: 'nav.sessions', Icon: Monitor },
|
||||
{ separator: true },
|
||||
{ path: '/scenarios', labelKey: 'nav.scenarios', Icon: ClipboardList },
|
||||
{ path: '/snippets', labelKey: 'nav.snippets', Icon: Braces },
|
||||
{ path: '/credentials', labelKey: 'nav.credentials', Icon: KeyRound },
|
||||
{ path: '/environments', labelKey: 'nav.environments', Icon: Globe },
|
||||
{ separator: true },
|
||||
{ path: '/import', labelKey: 'nav.import', Icon: Upload },
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
@@ -49,56 +114,68 @@ export default function App() {
|
||||
header={
|
||||
<div className={styles.header}>
|
||||
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
}
|
||||
width={220}
|
||||
>
|
||||
<nav className={styles.nav}>
|
||||
{NAV.map(({ path, labelKey, Icon }) => (
|
||||
<NavLink
|
||||
key={path}
|
||||
to={path}
|
||||
className={({ isActive }) =>
|
||||
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
|
||||
}
|
||||
>
|
||||
<Icon size={16} className={styles.navIcon} aria-hidden="true" />
|
||||
{t(labelKey)}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<div className={styles.sideContent}>
|
||||
<nav className={styles.nav}>
|
||||
{NAV.map((item, index) =>
|
||||
'separator' in item ? (
|
||||
<div key={`separator-${index}`} className={styles.navSeparator} />
|
||||
) : (
|
||||
<NavLink
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
className={({ isActive }) =>
|
||||
[styles.navItem, isActive ? styles.navItemActive : ''].filter(Boolean).join(' ')
|
||||
}
|
||||
>
|
||||
<item.Icon size={16} className={styles.navIcon} aria-hidden="true" />
|
||||
{t(item.labelKey)}
|
||||
</NavLink>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className={styles.sideFooter}>
|
||||
<ThemeSwitcher />
|
||||
<div className={styles.version}>v{__APP_VERSION__}</div>
|
||||
</div>
|
||||
</div>
|
||||
</SidePanel>
|
||||
|
||||
<main className={styles.main}>
|
||||
<Routes>
|
||||
<Route index element={<Navigate to="/scenarios" replace />} />
|
||||
<Route path="/environments" element={<EnvironmentsPage />} />
|
||||
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
|
||||
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
|
||||
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
|
||||
<Route path="/keys" element={<KeysPage />} />
|
||||
<Route path="/sessions" element={<SessionsPage />} />
|
||||
<Route path="/sessions/:id" element={<SessionDetailPage />} />
|
||||
<Route path="/scenarios" element={<ScenariosPage />} />
|
||||
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
|
||||
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
|
||||
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
|
||||
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
|
||||
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
|
||||
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
|
||||
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
|
||||
<Route path="/credentials" element={<CredentialsPage />} />
|
||||
<Route path="/credentials/new" element={<CreateCredentialPage />} />
|
||||
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
|
||||
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
|
||||
<Route path="/snippets" element={<SnippetsPage />} />
|
||||
<Route path="/snippets/new" element={<CreateSnippetPage />} />
|
||||
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
|
||||
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
|
||||
<Route path="/runs" element={<AllRunsPage />} />
|
||||
<Route path="*" element={<Navigate to="/scenarios" replace />} />
|
||||
</Routes>
|
||||
<Suspense fallback={<p>Loading…</p>}>
|
||||
<Routes>
|
||||
<Route index element={<Navigate to="/scenarios" replace />} />
|
||||
<Route path="/environments" element={<EnvironmentsPage />} />
|
||||
<Route path="/environments/new" element={<CreateEnvironmentPage />} />
|
||||
<Route path="/environments/:id/edit" element={<EditEnvironmentPage />} />
|
||||
<Route path="/environments/:id" element={<EnvironmentDetailPage />} />
|
||||
<Route path="/sessions" element={<SessionsPage />} />
|
||||
<Route path="/sessions/:id" element={<SessionDetailPage />} />
|
||||
<Route path="/scenarios" element={<ScenariosPage />} />
|
||||
<Route path="/scenarios/new" element={<CreateScenarioPage />} />
|
||||
<Route path="/scenarios/:id/edit" element={<EditScenarioPage />} />
|
||||
<Route path="/scenarios/:id/steps/new" element={<CreateStepPage />} />
|
||||
<Route path="/scenarios/:id/steps/:stepId/edit" element={<EditStepPage />} />
|
||||
<Route path="/scenarios/:id/runs" element={<RunsPage />} />
|
||||
<Route path="/scenarios/:id/runs/:runId" element={<RunDetailPage />} />
|
||||
<Route path="/scenarios/:id" element={<ScenarioDetailPage />} />
|
||||
<Route path="/credentials" element={<CredentialsPage />} />
|
||||
<Route path="/credentials/new" element={<CreateCredentialPage />} />
|
||||
<Route path="/credentials/:id/edit" element={<EditCredentialPage />} />
|
||||
<Route path="/credentials/:id" element={<CredentialDetailPage />} />
|
||||
<Route path="/snippets" element={<SnippetsPage />} />
|
||||
<Route path="/import" element={<ImportPage />} />
|
||||
<Route path="/snippets/new" element={<CreateSnippetPage />} />
|
||||
<Route path="/snippets/:id/edit" element={<EditSnippetPage />} />
|
||||
<Route path="/snippets/:id" element={<SnippetDetailPage />} />
|
||||
<Route path="/runs" element={<AllRunsPage />} />
|
||||
<Route path="*" element={<Navigate to="/scenarios" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
+200
-62
@@ -2,7 +2,10 @@ import type {
|
||||
PaginatedResponse,
|
||||
Credential,
|
||||
Environment,
|
||||
KeysResponse,
|
||||
FileMetadata,
|
||||
FileListResponse,
|
||||
ImportResult,
|
||||
RunDefaults,
|
||||
ScenarioCredential,
|
||||
Session,
|
||||
Scenario,
|
||||
@@ -10,27 +13,53 @@ import type {
|
||||
ScenarioRunDetail,
|
||||
ScenarioRunStep,
|
||||
ScenarioStep,
|
||||
ScenarioVersion,
|
||||
Snippet,
|
||||
SnippetVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from './types';
|
||||
import { emitApiErrorToast } from '../lib/toast-events';
|
||||
|
||||
// In dev, Vite proxies /environments /sessions /scenarios /keys to localhost:3000.
|
||||
// In production (or when VITE_API_URL is set) we hit the configured origin directly.
|
||||
const BASE_URL: string = (import.meta.env.VITE_API_URL as string | undefined) ?? '';
|
||||
// API calls are versioned under /api/v1 by default.
|
||||
// Set VITE_API_URL (for example, http://localhost:13000/api/v1) to use a different origin.
|
||||
const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/v1').replace(
|
||||
/\/$/,
|
||||
'',
|
||||
);
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE_URL}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...init?.headers },
|
||||
...init,
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (!(init?.body instanceof FormData) && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message || 'Network request failed';
|
||||
emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
throw new Error(`${res.status} ${text}`);
|
||||
const message = `${res.status} ${text}`;
|
||||
emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
const contentLength = res.headers.get('content-length');
|
||||
if (res.status === 204 || contentLength === '0') return undefined as T;
|
||||
const contentType = res.headers.get('content-type')?.toLowerCase() ?? '';
|
||||
const text = await res.text();
|
||||
if (!text) return undefined as T;
|
||||
return JSON.parse(text) as T;
|
||||
if (contentType.includes('application/json')) {
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
return text as T;
|
||||
}
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||
@@ -60,12 +89,6 @@ export const credentials = {
|
||||
exportCredential(id: string): Promise<unknown> {
|
||||
return request(`/credentials/${id}/export`);
|
||||
},
|
||||
importCredential(payload: unknown): Promise<Credential> {
|
||||
return request('/credentials/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Snippets ──────────────────────────────────────────────────────────────────
|
||||
@@ -77,13 +100,18 @@ export const snippets = {
|
||||
get(id: string): Promise<Snippet> {
|
||||
return request(`/snippets/${id}`);
|
||||
},
|
||||
create(payload: Pick<Snippet, 'name' | 'code'> & { description?: string }): Promise<Snippet> {
|
||||
create(
|
||||
payload: Pick<Snippet, 'alias' | 'title' | 'code'> & { description?: string },
|
||||
): Promise<Snippet> {
|
||||
return request('/snippets', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Snippet, 'name' | 'description' | 'code'>>): Promise<Snippet> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Snippet, 'alias' | 'title' | 'description' | 'code'>>,
|
||||
): Promise<Snippet> {
|
||||
return request(`/snippets/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -92,15 +120,12 @@ export const snippets = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/snippets/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
versions(id: string): Promise<SnippetVersion[]> {
|
||||
return request(`/snippets/${id}/versions`);
|
||||
},
|
||||
exportSnippet(id: string): Promise<unknown> {
|
||||
return request(`/snippets/${id}/export`);
|
||||
},
|
||||
importSnippet(payload: unknown): Promise<Snippet> {
|
||||
return request('/snippets/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Environments ──────────────────────────────────────────────────────────────
|
||||
@@ -112,13 +137,16 @@ export const environments = {
|
||||
get(id: string): Promise<Environment> {
|
||||
return request(`/environments/${id}`);
|
||||
},
|
||||
create(name: string, urls: Environment['urls']): Promise<Environment> {
|
||||
create(name: string, data: Environment['data'], description?: string): Promise<Environment> {
|
||||
return request('/environments', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, urls }),
|
||||
body: JSON.stringify({ name, description, data }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Environment, 'name' | 'description' | 'data'>>,
|
||||
): Promise<Environment> {
|
||||
return request(`/environments/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -127,21 +155,21 @@ export const environments = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/environments/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const keys = {
|
||||
list(): Promise<KeysResponse> {
|
||||
return request('/keys');
|
||||
exportEnvironment(id: string): Promise<unknown> {
|
||||
return request(`/environments/${id}/export`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export const sessions = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'id',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Session>> {
|
||||
return request(`/sessions?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`);
|
||||
},
|
||||
get(id: string): Promise<Session> {
|
||||
return request(`/sessions/${id}`);
|
||||
@@ -154,19 +182,29 @@ export const sessions = {
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarios = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}`);
|
||||
list(
|
||||
page = 1,
|
||||
limit = 50,
|
||||
orderBy = 'updatedAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(
|
||||
`/scenarios?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
|
||||
return request(`/scenarios/${id}`);
|
||||
},
|
||||
create(name: string): Promise<Scenario> {
|
||||
create(name: string, description?: string, environmentId?: string): Promise<Scenario> {
|
||||
return request('/scenarios', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name }),
|
||||
body: JSON.stringify({ name, description, environmentId }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Scenario, 'name'>>): Promise<Scenario> {
|
||||
update(
|
||||
id: string,
|
||||
patch: Partial<Pick<Scenario, 'name' | 'description' | 'environmentId' | 'timeoutSeconds'>>,
|
||||
): Promise<Scenario> {
|
||||
return request(`/scenarios/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -175,8 +213,24 @@ export const scenarios = {
|
||||
remove(id: string): Promise<void> {
|
||||
return request(`/scenarios/${id}`, { method: 'DELETE' });
|
||||
},
|
||||
run(id: string): Promise<ScenarioRun> {
|
||||
return request(`/scenarios/${id}/run`, { method: 'POST' });
|
||||
run(
|
||||
id: string,
|
||||
environmentId: string,
|
||||
saveSession?: boolean,
|
||||
traceMode?: TraceMode,
|
||||
/** Scenario version to run; omit for the latest. */
|
||||
version?: number,
|
||||
): Promise<ScenarioRun> {
|
||||
return request(`/scenarios/${id}/run`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ environmentId, saveSession, traceMode, version }),
|
||||
});
|
||||
},
|
||||
versions(id: string): Promise<ScenarioVersion[]> {
|
||||
return request(`/scenarios/${id}/versions`);
|
||||
},
|
||||
runDefaults(): Promise<RunDefaults> {
|
||||
return request('/scenarios/run-defaults');
|
||||
},
|
||||
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}`);
|
||||
@@ -184,33 +238,66 @@ export const scenarios = {
|
||||
waitForRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}/wait`, { method: 'POST' });
|
||||
},
|
||||
listRuns(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
listRuns(
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
},
|
||||
exportScenario(id: string): Promise<unknown> {
|
||||
return request(`/scenarios/${id}/export`);
|
||||
exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[] } = {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
},
|
||||
): Promise<string> {
|
||||
const params = new URLSearchParams();
|
||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||
for (const cid of options.credentialIds) {
|
||||
params.append('credentialIds', cid);
|
||||
}
|
||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||
},
|
||||
importScenario(payload: unknown): Promise<Scenario> {
|
||||
return request('/scenarios/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
exportE2eTestUrl(id: string): string {
|
||||
return `${BASE_URL}/scenarios/${id}/export-e2e`;
|
||||
},
|
||||
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
||||
return request(`/scenarios/${id}/used-snippets`);
|
||||
},
|
||||
};
|
||||
|
||||
// ── Runs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const runs = {
|
||||
listAll(page = 1, limit = 20, status?: string): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }>> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
listAll(
|
||||
page = 1,
|
||||
limit = 20,
|
||||
status?: string,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { scenario: { id: string; name: string } }>> {
|
||||
const q = new URLSearchParams({ page: String(page), limit: String(limit), orderBy, orderDir });
|
||||
if (status) q.set('status', status);
|
||||
return request(`/scenarios/runs?${q}`);
|
||||
},
|
||||
list(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
list(
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
orderBy = 'createdAt',
|
||||
orderDir: 'ASC' | 'DESC' = 'DESC',
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(
|
||||
`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}&orderBy=${orderBy}&orderDir=${orderDir}`,
|
||||
);
|
||||
},
|
||||
get(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}`);
|
||||
get(scenarioId: string, runId: string, q?: string): Promise<ScenarioRunDetail> {
|
||||
const qs = q?.trim() ? `?q=${encodeURIComponent(q.trim())}` : '';
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}${qs}`);
|
||||
},
|
||||
exportLogs(scenarioId: string, runId: string, format: 'csv' | 'md'): Promise<string> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}/logs/export?format=${format}`);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -236,18 +323,15 @@ export const scenarioCredentials = {
|
||||
// ── Scenario Steps ────────────────────────────────────────────────────────────
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
order: number;
|
||||
type: 'login' | 'exec' | 'sign';
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
type?: 'login' | 'exec' | 'sign';
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
timeoutSeconds?: number | null;
|
||||
}
|
||||
|
||||
export const steps = {
|
||||
@@ -270,3 +354,57 @@ export const steps = {
|
||||
return request(`/scenarios/${scenarioId}/steps/${stepId}`, { method: 'DELETE' });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Scenario Files ────────────────────────────────────────────────────────
|
||||
|
||||
export const scenarioFiles = {
|
||||
upload(scenarioId: string, file: File, expiresAt?: Date): Promise<FileMetadata> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (expiresAt) form.append('expiresAt', expiresAt.toISOString());
|
||||
return request(`/scenarios/${scenarioId}/files`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
},
|
||||
list(scenarioId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/files/${fileId}/content`;
|
||||
},
|
||||
};
|
||||
|
||||
// ── Run Files ─────────────────────────────────────────────────────────────
|
||||
|
||||
export const runFiles = {
|
||||
list(scenarioId: string, runId: string, limit = 20, offset = 0): Promise<FileListResponse> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files?limit=${limit}&offset=${offset}`);
|
||||
},
|
||||
/** Returns a URL that can be used as an <a href> for direct download. */
|
||||
contentUrl(scenarioId: string, runId: string, fileId: string): string {
|
||||
return `${BASE_URL}/scenarios/${scenarioId}/runs/${runId}/files/${fileId}/content`;
|
||||
},
|
||||
remove(scenarioId: string, runId: string, fileId: string): Promise<void> {
|
||||
return request(`/scenarios/${scenarioId}/runs/${runId}/files/${fileId}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// ── Import ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const imports = {
|
||||
/**
|
||||
* Imports any mix of environments, credentials, snippets and scenarios from
|
||||
* YAML (`---`-separated documents, each one item or a list of items).
|
||||
*/
|
||||
yaml(text: string): Promise<ImportResult> {
|
||||
return request('/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/yaml' },
|
||||
body: text,
|
||||
});
|
||||
},
|
||||
};
|
||||
+103
-16
@@ -9,17 +9,15 @@ export interface PaginatedResponse<T> {
|
||||
|
||||
// ── Environments ──────────────────────────────────────────────────────────────
|
||||
|
||||
export interface EnvironmentUrls {
|
||||
id_url?: string;
|
||||
cabinet_url?: string;
|
||||
admin_url?: string;
|
||||
export interface EnvironmentData {
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
|
||||
export interface Environment {
|
||||
id: string;
|
||||
name: string;
|
||||
urls: EnvironmentUrls;
|
||||
description?: string;
|
||||
data: EnvironmentData;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -39,17 +37,31 @@ export interface Credential {
|
||||
|
||||
export interface Snippet {
|
||||
id: string;
|
||||
name: string;
|
||||
alias: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
export interface SnippetVersion {
|
||||
id: string;
|
||||
snippetId: string;
|
||||
version: number;
|
||||
alias: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface KeysResponse {
|
||||
keys: string[];
|
||||
/** A snippet referenced by a scenario's steps. */
|
||||
export interface UsedSnippet extends Snippet {
|
||||
/** Version pinned via runSnippet('alias@N'), or null for the latest. */
|
||||
pinnedVersion: number | null;
|
||||
}
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
@@ -68,17 +80,13 @@ export interface Session {
|
||||
|
||||
// ── Scenarios ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export type StepType = 'login' | 'exec' | 'sign';
|
||||
|
||||
export interface ScenarioStep {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
order: number;
|
||||
type: StepType;
|
||||
title: string | null;
|
||||
sessionName: string | null;
|
||||
execCode: string | null;
|
||||
validateCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -95,14 +103,48 @@ export interface ScenarioCredential {
|
||||
export interface Scenario {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
environmentId?: string | null;
|
||||
timeoutSeconds?: number | null;
|
||||
/** Latest version number. */
|
||||
version: number;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
steps?: ScenarioStep[];
|
||||
scenarioCredentials?: ScenarioCredential[];
|
||||
lastRunStatus?: ScenarioRunStatus | null;
|
||||
lastRunAt?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ScenarioStepSnapshot {
|
||||
id: string | null;
|
||||
order: number;
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
}
|
||||
|
||||
export interface ScenarioVersion {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
version: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
environmentId: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
steps: ScenarioStepSnapshot[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type ScenarioRunStatus = 'pending' | 'in_progress' | 'pass' | 'fail';
|
||||
|
||||
export type TraceMode = 'on' | 'retain-on-failure' | 'off';
|
||||
|
||||
export interface RunDefaults {
|
||||
traceMode: TraceMode;
|
||||
}
|
||||
|
||||
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
|
||||
|
||||
export type LogLevel = 'log' | 'warn' | 'error';
|
||||
@@ -110,7 +152,15 @@ export type LogLevel = 'log' | 'warn' | 'error';
|
||||
export interface ScenarioRun {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
environmentId: string | null;
|
||||
sessionId?: string | null;
|
||||
saveSession: boolean;
|
||||
traceMode: TraceMode | null;
|
||||
/** Scenario version the run executes; null for runs created before versioning. */
|
||||
scenarioVersion: number | null;
|
||||
scenario?: Pick<Scenario, 'id' | 'name'>;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
session?: { id: string; sessionName: string };
|
||||
status: ScenarioRunStatus;
|
||||
stepRuns?: ScenarioRunStep[];
|
||||
createdAt: string;
|
||||
@@ -120,8 +170,12 @@ export interface ScenarioRun {
|
||||
export interface ScenarioRunStep {
|
||||
id: string;
|
||||
runId: string;
|
||||
scenarioStepId: string;
|
||||
scenarioStep: ScenarioStep;
|
||||
/** Live step this run step came from; null once that step is deleted. */
|
||||
scenarioStepId: string | null;
|
||||
// Step content as of the run's scenario version
|
||||
title: string | null;
|
||||
execCode: string | null;
|
||||
timeoutSeconds: number | null;
|
||||
status: RunStepStatus;
|
||||
order: number;
|
||||
description: string | null;
|
||||
@@ -143,3 +197,36 @@ export interface ScenarioRunDetail extends ScenarioRun {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
logs: ScenarioRunLog[];
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface FileMetadata {
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
sha256: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface FileListResponse {
|
||||
items: FileMetadata[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ── Import ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export type ImportKind = 'environment' | 'credential' | 'snippet' | 'scenario';
|
||||
|
||||
export interface ImportedItem {
|
||||
kind: ImportKind;
|
||||
id: string;
|
||||
name: string;
|
||||
/** Version stored for versioned kinds (snippets, scenarios). */
|
||||
version?: number;
|
||||
}
|
||||
|
||||
export interface ImportResult {
|
||||
imported: ImportedItem[];
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Trash2 } from 'lucide-react';
|
||||
import { Modal, Button } from '../../ui';
|
||||
|
||||
export interface DeleteConfirmationModalProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
message: string;
|
||||
onClose: () => void;
|
||||
onConfirm: () => void;
|
||||
isDeleting: boolean;
|
||||
}
|
||||
|
||||
export function DeleteConfirmationModal({
|
||||
open,
|
||||
title,
|
||||
message,
|
||||
onClose,
|
||||
onConfirm,
|
||||
isDeleting,
|
||||
}: DeleteConfirmationModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={title}
|
||||
onClose={() => !isDeleting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isDeleting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={onConfirm} disabled={isDeleting}>
|
||||
<Trash2 size={14} />
|
||||
{t('common.button_delete')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.radioRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.radioRow input[type='radio'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Download } from 'lucide-react';
|
||||
import { Modal, Button } from '../../ui';
|
||||
import styles from './ExportLogsModal.module.css';
|
||||
|
||||
export type LogExportFormat = 'md' | 'csv';
|
||||
|
||||
export interface ExportLogsModalProps {
|
||||
open: boolean;
|
||||
format: LogExportFormat;
|
||||
onFormatChange: (format: LogExportFormat) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportLogsModal({
|
||||
open,
|
||||
format,
|
||||
onFormatChange,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportLogsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('runs.export_logs_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('runs.export_logs_format')}</h4>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'md'}
|
||||
onChange={() => onFormatChange('md')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_md')}</span>
|
||||
</label>
|
||||
<label className={styles.radioRow}>
|
||||
<input
|
||||
type="radio"
|
||||
name="log-export-format"
|
||||
checked={format === 'csv'}
|
||||
onChange={() => onFormatChange('csv')}
|
||||
/>
|
||||
<span>{t('runs.export_logs_format_csv')}</span>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
.exportModal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.scenarioMeta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-primary);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.metaRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.metaLabel {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-primary-fg);
|
||||
opacity: 0.7;
|
||||
min-width: 4rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.metaValue {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-primary-fg);
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted, #888);
|
||||
margin: 0;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.checkboxRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.checkboxRow input[type='checkbox'] {
|
||||
cursor: pointer;
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Upload } from 'lucide-react';
|
||||
import { Modal, Button, UuidBadge } from '../../ui';
|
||||
import type { Scenario, ScenarioCredential } from '../../api';
|
||||
import styles from './ExportScenarioModal.module.css';
|
||||
|
||||
export interface ExportScenarioModalProps {
|
||||
open: boolean;
|
||||
scenario: Scenario | null;
|
||||
scenarioCredentials: ScenarioCredential[];
|
||||
environment: Pick<{ id: string; name: string }, 'id' | 'name'> | null;
|
||||
includeEnvironment: boolean;
|
||||
onIncludeEnvironmentChange: (v: boolean) => void;
|
||||
includedCredentialIds: Set<string>;
|
||||
onCredentialToggle: (id: string, checked: boolean) => void;
|
||||
onClose: () => void;
|
||||
onExport: () => void;
|
||||
isExporting: boolean;
|
||||
}
|
||||
|
||||
export function ExportScenarioModal({
|
||||
open,
|
||||
scenario,
|
||||
scenarioCredentials,
|
||||
environment,
|
||||
includeEnvironment,
|
||||
onIncludeEnvironmentChange,
|
||||
includedCredentialIds,
|
||||
onCredentialToggle,
|
||||
onClose,
|
||||
onExport,
|
||||
isExporting,
|
||||
}: ExportScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.export_modal_title')}
|
||||
onClose={() => !isExporting && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isExporting}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onExport} disabled={isExporting}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{scenario && (
|
||||
<div className={styles.exportModal}>
|
||||
<div className={styles.scenarioMeta}>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_name')}</span>
|
||||
<span className={styles.metaValue}>{scenario.name}</span>
|
||||
</div>
|
||||
<div className={styles.metaRow}>
|
||||
<span className={styles.metaLabel}>{t('scenarios.field_id')}</span>
|
||||
<span className={styles.metaValue}>
|
||||
<UuidBadge id={scenario.id} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{environment && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_environment')}</h4>
|
||||
<label className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeEnvironment}
|
||||
onChange={(e) => onIncludeEnvironmentChange(e.target.checked)}
|
||||
/>
|
||||
<span>{environment.name}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenarioCredentials.length > 0 && (
|
||||
<div className={styles.section}>
|
||||
<h4 className={styles.sectionTitle}>{t('scenarios.export_include_credentials')}</h4>
|
||||
{scenarioCredentials.map((sc) => (
|
||||
<label key={sc.credentialId} className={styles.checkboxRow}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includedCredentialIds.has(sc.credentialId)}
|
||||
onChange={(e) => onCredentialToggle(sc.credentialId, e.target.checked)}
|
||||
/>
|
||||
<span>{sc.credential?.name ?? sc.alias}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Play } from 'lucide-react';
|
||||
import { Modal, Button, Select } from '../../ui';
|
||||
import type { Environment, ScenarioVersion, TraceMode } from '../../api';
|
||||
|
||||
const TRACE_MODES: TraceMode[] = ['on', 'retain-on-failure', 'off'];
|
||||
|
||||
export interface RunScenarioModalProps {
|
||||
open: boolean;
|
||||
environments: Environment[];
|
||||
selectedEnvId: string;
|
||||
onEnvSelect: (envId: string) => void;
|
||||
saveSessionFlag: boolean;
|
||||
onSaveSessionChange: (flag: boolean) => void;
|
||||
/** Scenario versions, newest first; empty while loading. */
|
||||
versions: Pick<ScenarioVersion, 'version' | 'createdAt'>[];
|
||||
/** Selected version, or null for the latest. */
|
||||
selectedVersion: number | null;
|
||||
onVersionChange: (version: number | null) => void;
|
||||
traceMode: TraceMode;
|
||||
defaultTraceMode: TraceMode | null;
|
||||
onTraceModeChange: (mode: TraceMode) => void;
|
||||
onClose: () => void;
|
||||
onRun: () => void;
|
||||
isRunning: boolean;
|
||||
actionLabel?: string;
|
||||
}
|
||||
|
||||
export function RunScenarioModal({
|
||||
open,
|
||||
environments,
|
||||
selectedEnvId,
|
||||
onEnvSelect,
|
||||
saveSessionFlag,
|
||||
onSaveSessionChange,
|
||||
versions,
|
||||
selectedVersion,
|
||||
onVersionChange,
|
||||
traceMode,
|
||||
defaultTraceMode,
|
||||
onTraceModeChange,
|
||||
onClose,
|
||||
onRun,
|
||||
isRunning,
|
||||
actionLabel,
|
||||
}: RunScenarioModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !isRunning && onClose()}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose} disabled={isRunning}>
|
||||
<X size={14} />
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={onRun} disabled={isRunning || !selectedEnvId}>
|
||||
<Play size={14} />
|
||||
{actionLabel || t('scenarios.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{environments.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => onEnvSelect(e.target.value)}
|
||||
options={environments.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_version_label')}
|
||||
value={selectedVersion == null ? '' : String(selectedVersion)}
|
||||
onChange={(e) => onVersionChange(e.target.value ? Number(e.target.value) : null)}
|
||||
options={[
|
||||
{
|
||||
value: '',
|
||||
label: versions[0]
|
||||
? t('scenarios.run_modal_version_latest_n', { version: versions[0].version })
|
||||
: t('scenarios.run_modal_version_latest'),
|
||||
},
|
||||
...versions.map((v) => ({
|
||||
value: String(v.version),
|
||||
label: `v${v.version} — ${new Date(v.createdAt).toLocaleString()}`,
|
||||
})),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
marginTop: '1rem',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => onSaveSessionChange(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
<div style={{ marginTop: '1rem' }}>
|
||||
<Select
|
||||
label={t('scenarios.run_modal_trace_label')}
|
||||
value={traceMode}
|
||||
onChange={(e) => onTraceModeChange(e.target.value as TraceMode)}
|
||||
options={TRACE_MODES.map((mode) => ({
|
||||
value: mode,
|
||||
label:
|
||||
t(`scenarios.trace_mode_${mode.replace(/-/g, '_')}`) +
|
||||
(mode === defaultTraceMode ? ` ${t('scenarios.trace_mode_default_suffix')}` : ''),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
|
||||
export { ExportScenarioModal } from './ExportScenarioModal';
|
||||
export type { ExportScenarioModalProps } from './ExportScenarioModal';
|
||||
export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
export { ExportLogsModal } from './ExportLogsModal';
|
||||
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
|
||||
Vendored
+2
@@ -6,3 +6,5 @@ declare module '*.css' {
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_URL?: string;
|
||||
}
|
||||
|
||||
declare const __APP_VERSION__: string;
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ChangeEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { imports } from '../api';
|
||||
import type { ImportedItem, ImportKind } from '../api';
|
||||
import { useToast } from '../ui';
|
||||
|
||||
/** Detail page path of an imported item. */
|
||||
export function importedItemPath(item: ImportedItem): string {
|
||||
return `/${item.kind}s/${item.id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a file input `onChange` handler that imports the chosen YAML file
|
||||
* through the central import. When the file holds exactly one item of `kind`
|
||||
* (e.g. a scenario export with its environment), opens that item; otherwise
|
||||
* opens the import page with the full result.
|
||||
*/
|
||||
export function useImportFile(kind: ImportKind) {
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const result = await imports.yaml(await file.text());
|
||||
const own = result.imported.filter((item) => item.kind === kind);
|
||||
if (own.length === 1) {
|
||||
if (result.imported.length > 1) {
|
||||
toast.success(t('import.imported_count', { count: result.imported.length }));
|
||||
}
|
||||
navigate(importedItemPath(own[0]));
|
||||
} else {
|
||||
navigate('/import', { state: { results: [{ fileName: file.name, result }] } });
|
||||
}
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const APP_NAME = 'Liqa';
|
||||
|
||||
/**
|
||||
* Sets document.title to "<title> | Liqa" for the current page.
|
||||
* Pass undefined or empty string to fall back to just "Liqa".
|
||||
*/
|
||||
export function usePageTitle(title: string | null | undefined): void {
|
||||
useEffect(() => {
|
||||
const prev = document.title;
|
||||
document.title = title ? `${title} | ${APP_NAME}` : APP_NAME;
|
||||
return () => {
|
||||
document.title = prev;
|
||||
};
|
||||
}, [title]);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { scenarios } from '../api';
|
||||
import type { RunDefaults } from '../api';
|
||||
|
||||
// Server run defaults don't change while the app is open; fetch them once
|
||||
let cached: Promise<RunDefaults> | null = null;
|
||||
|
||||
/**
|
||||
* Returns the server-configured defaults for new scenario runs, or null
|
||||
* while they are loading (or if the request failed).
|
||||
*/
|
||||
export function useRunDefaults(): RunDefaults | null {
|
||||
const [defaults, setDefaults] = useState<RunDefaults | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
cached ??= scenarios.runDefaults().catch((err: unknown) => {
|
||||
cached = null;
|
||||
throw err;
|
||||
});
|
||||
cached.then((d) => !cancelled && setDefaults(d)).catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return defaults;
|
||||
}
|
||||
+142
-21
@@ -1,4 +1,17 @@
|
||||
{
|
||||
"common": {
|
||||
"button_cancel": "Cancel",
|
||||
"button_confirm": "Confirm",
|
||||
"button_delete": "Delete",
|
||||
"confirm_delete_credential": "Are you sure you want to delete this credential?",
|
||||
"confirm_delete_environment": "Are you sure you want to delete this environment?",
|
||||
"confirm_delete_scenario": "Are you sure you want to delete this scenario?",
|
||||
"confirm_delete_step": "Are you sure you want to delete this step?",
|
||||
"confirm_delete_session": "Are you sure you want to delete this session?",
|
||||
"confirm_delete_snippet": "Are you sure you want to delete this snippet?",
|
||||
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
|
||||
"save_session": "Save session"
|
||||
},
|
||||
"errors": {
|
||||
"not_found": "Not found",
|
||||
"not_found_session": "Session {{id}} does not exist or has been deleted.",
|
||||
@@ -15,41 +28,67 @@
|
||||
"keys": "Keys",
|
||||
"sessions": "Sessions",
|
||||
"scenarios": "Scenarios",
|
||||
"runs": "Runs"
|
||||
"runs": "Runs",
|
||||
"import": "Import"
|
||||
},
|
||||
"import": {
|
||||
"title": "Import",
|
||||
"action_choose": "Choose files",
|
||||
"description": "Import exported environments, credentials, snippets and scenarios. Each YAML file may hold several items as ---separated documents, and each document may hold one item or a list of items. JSON files work too.",
|
||||
"description_validation": "Every item in a file is checked before anything is imported: if one item is invalid, nothing from that file is imported. Items are imported in dependency order (environments, credentials, snippets, scenarios), and snippets and scenarios keep the version they were exported with.",
|
||||
"imported_count_one": "Imported {{count}} item",
|
||||
"imported_count_other": "Imported {{count}} items",
|
||||
"col_file": "File",
|
||||
"col_kind": "Kind",
|
||||
"col_name": "Name",
|
||||
"col_version": "Version",
|
||||
"kind_environment": "Environment",
|
||||
"kind_credential": "Credential",
|
||||
"kind_snippet": "Snippet",
|
||||
"kind_scenario": "Scenario"
|
||||
},
|
||||
"environments": {
|
||||
"title": "Environments",
|
||||
"created": "Environment created",
|
||||
"updated": "Environment updated",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_urls": "URLs",
|
||||
"col_description": "Description",
|
||||
"col_data": "Data",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No environments yet.",
|
||||
"loading": "Loading…",
|
||||
"no_urls": "No URLs configured.",
|
||||
"no_data": "No data configured.",
|
||||
"menu_label": "Environment options",
|
||||
"action_view": "View details",
|
||||
"action_delete": "Delete",
|
||||
"action_add": "Add environment",
|
||||
"action_edit": "Edit",
|
||||
"action_export": "Export",
|
||||
"action_import": "Import",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_update": "Save",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Environment",
|
||||
"edit_title": "Edit Environment",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. staging, production",
|
||||
"form_name_required": "Name is required",
|
||||
"form_id_url": "ID URL",
|
||||
"form_cabinet_url": "Cabinet URL",
|
||||
"form_admin_url": "Admin URL",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this environment",
|
||||
"form_data": "Data (JSON)",
|
||||
"form_data_invalid_json": "Must be a valid JSON object",
|
||||
"back": "Environments",
|
||||
"field_id": "ID",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
"section_urls": "URLs"
|
||||
"section_data": "Data"
|
||||
},
|
||||
"credentials": {
|
||||
"title": "Credentials",
|
||||
"created": "Credential created",
|
||||
"updated": "Credential updated",
|
||||
"empty": "No credentials yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Credential options",
|
||||
@@ -57,7 +96,7 @@
|
||||
"action_delete": "Delete",
|
||||
"action_add": "Add credential",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_update": "Save",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Credential",
|
||||
"edit_title": "Edit Credential",
|
||||
@@ -97,9 +136,16 @@
|
||||
"field_updated": "Updated",
|
||||
"field_lastUsed": "Last Used"
|
||||
},
|
||||
"scenarios": { "title": "Scenarios",
|
||||
"scenarios": {
|
||||
"title": "Scenarios",
|
||||
"created": "Scenario created",
|
||||
"updated": "Scenario updated",
|
||||
"run_started": "Scenario run started",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_version": "Version",
|
||||
"col_description": "Description",
|
||||
"col_last_run": "Last Run",
|
||||
"col_updated": "Updated",
|
||||
"empty": "No scenarios yet.",
|
||||
"loading": "Loading…",
|
||||
@@ -107,6 +153,8 @@
|
||||
"action_delete": "Delete",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_version": "Version",
|
||||
"field_description": "Description",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
@@ -120,17 +168,26 @@
|
||||
"action_edit": "Edit",
|
||||
"action_runs": "Runs",
|
||||
"action_export": "Export",
|
||||
"action_export_e2e": "Export e2e test",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import scenario",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_update": "Save",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Scenario",
|
||||
"edit_title": "Edit Scenario",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "Describe this scenario",
|
||||
"form_environment": "Default Environment",
|
||||
"form_environment_none": "None (no default environment)",
|
||||
"field_environment": "Default Environment",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. Login flow",
|
||||
"form_name_required": "Name is required",
|
||||
"credentials_heading": "Credentials",
|
||||
"used_snippets_heading": "Used Snippets",
|
||||
"used_snippet_pinned": "v{{version}} (pinned)",
|
||||
"used_snippet_latest": "Latest (v{{version}})",
|
||||
"cred_empty": "No credentials assigned.",
|
||||
"cred_col_alias": "Alias",
|
||||
"cred_col_name": "Credential",
|
||||
@@ -144,7 +201,27 @@
|
||||
"cred_form_cred_required": "Select a credential",
|
||||
"cred_form_alias": "Alias",
|
||||
"cred_form_alias_placeholder": "e.g. api_key",
|
||||
"cred_form_alias_required": "Alias is required"
|
||||
"cred_form_alias_required": "Alias is required",
|
||||
"run_modal_title": "Select environment",
|
||||
"run_modal_env_label": "Environment",
|
||||
"run_modal_no_env": "No environments found. Create an environment before running a scenario.",
|
||||
"run_modal_env_required": "Please select an environment",
|
||||
"run_modal_version_label": "Version",
|
||||
"run_modal_version_latest": "Latest",
|
||||
"run_modal_version_latest_n": "Latest (v{{version}})",
|
||||
"run_modal_trace_label": "Playwright trace",
|
||||
"trace_mode_on": "Always keep",
|
||||
"trace_mode_retain_on_failure": "Keep on failure",
|
||||
"trace_mode_off": "Off",
|
||||
"trace_mode_default_suffix": "(default)",
|
||||
"export_modal_title": "Export Scenario",
|
||||
"export_include_environment": "Include Environment",
|
||||
"export_include_credentials": "Include Credentials",
|
||||
"form_timeout": "Scenario Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 600",
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
||||
"field_name": "Name",
|
||||
"field_id": "ID"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -160,6 +237,8 @@
|
||||
"page_size": "Items per page"
|
||||
},
|
||||
"steps": {
|
||||
"created": "Step created",
|
||||
"updated": "Step updated",
|
||||
"create_title": "Add Step",
|
||||
"edit_title": "Edit Step #{{order}}",
|
||||
"loading": "Loading…",
|
||||
@@ -167,7 +246,7 @@
|
||||
"action_edit": "Edit",
|
||||
"action_delete": "Delete",
|
||||
"action_save": "Add step",
|
||||
"action_update": "Save changes",
|
||||
"action_update": "Save",
|
||||
"action_cancel": "Cancel",
|
||||
"form_order": "Order",
|
||||
"form_order_invalid": "Order must be a non-negative integer",
|
||||
@@ -179,8 +258,9 @@
|
||||
"form_session_required": "Session name is required",
|
||||
"form_exec_code": "Exec code",
|
||||
"form_exec_code_placeholder": "return await page.title();",
|
||||
"form_validate_code": "Validate code",
|
||||
"form_validate_code_placeholder": "return { success: result !== null, description: \"…\" };"
|
||||
"form_timeout": "Step Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 60",
|
||||
"form_timeout_hint": "Max seconds for this step (default: 60)"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Runs",
|
||||
@@ -191,14 +271,19 @@
|
||||
"col_scenario": "Scenario",
|
||||
"col_status": "Status",
|
||||
"col_steps": "Steps",
|
||||
"col_version": "Version",
|
||||
"col_created": "Started",
|
||||
"field_id": "ID",
|
||||
"field_status": "Status",
|
||||
"field_steps": "Steps",
|
||||
"field_created": "Started",
|
||||
"field_updated": "Updated",
|
||||
"field_trace": "Playwright trace",
|
||||
"field_scenario_version": "Scenario version",
|
||||
"steps_heading": "Step runs",
|
||||
"step_title": "Title",
|
||||
"logs_heading": "Logs",
|
||||
"logs_search_placeholder": "Filter logs…",
|
||||
"step_order": "#",
|
||||
"step_type": "Type",
|
||||
"step_session": "Session",
|
||||
@@ -206,10 +291,20 @@
|
||||
"step_description": "Result",
|
||||
"log_level": "Level",
|
||||
"log_message": "Message",
|
||||
"log_time": "Time"
|
||||
"log_time": "Time",
|
||||
"action_download_logs": "Download logs",
|
||||
"action_repeat": "Repeat run",
|
||||
"repeat_no_environment": "The environment used by this run no longer exists",
|
||||
"export_logs_modal_title": "Export logs",
|
||||
"export_logs_format": "Format",
|
||||
"export_logs_format_md": "Markdown (.md)",
|
||||
"export_logs_format_csv": "CSV (.csv)",
|
||||
"action_export": "Export"
|
||||
},
|
||||
"snippets": {
|
||||
"title": "Snippets",
|
||||
"created": "Snippet created",
|
||||
"updated": "Snippet updated",
|
||||
"empty": "No snippets yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Snippet options",
|
||||
@@ -217,20 +312,25 @@
|
||||
"action_delete": "Delete",
|
||||
"action_add": "Add snippet",
|
||||
"action_save": "Create",
|
||||
"action_update": "Save changes",
|
||||
"action_update": "Save",
|
||||
"action_cancel": "Cancel",
|
||||
"create_title": "New Snippet",
|
||||
"edit_title": "Edit Snippet",
|
||||
"form_name": "Name",
|
||||
"form_name_placeholder": "e.g. clickLoginButton",
|
||||
"form_name_required": "Name is required",
|
||||
"form_alias": "Alias",
|
||||
"form_alias_placeholder": "e.g. clickLoginButton",
|
||||
"form_alias_required": "Alias is required",
|
||||
"form_title": "Title",
|
||||
"form_title_placeholder": "e.g. Click Login Button",
|
||||
"form_title_required": "Title is required",
|
||||
"form_description": "Description",
|
||||
"form_description_placeholder": "What does this snippet do?",
|
||||
"form_code": "Code",
|
||||
"form_code_placeholder": "await page.click('#login-btn');",
|
||||
"form_code_required": "Code is required",
|
||||
"field_id": "ID",
|
||||
"field_name": "Name",
|
||||
"field_alias": "Alias",
|
||||
"field_version": "Version",
|
||||
"field_title": "Title",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
@@ -238,5 +338,26 @@
|
||||
"action_export": "Export",
|
||||
"action_import": "Import",
|
||||
"import_error": "Failed to import snippet"
|
||||
},
|
||||
"files": {
|
||||
"title": "Files",
|
||||
"upload": "Upload",
|
||||
"uploadTitle": "Upload File",
|
||||
"uploadSuccess": "File uploaded successfully",
|
||||
"name": "Name",
|
||||
"mimeType": "MIME Type",
|
||||
"size": "Size",
|
||||
"expiresAt": "Expires At",
|
||||
"expiresAtLabel": "Expires At (optional)",
|
||||
"createdAt": "Created",
|
||||
"download": "Download",
|
||||
"delete": "Delete",
|
||||
"deleteTitle": "Delete file",
|
||||
"confirmDelete": "Are you sure you want to delete \"{{name}}\" from this run?",
|
||||
"deleteSuccess": "File deleted",
|
||||
"expiredTooltip": "File is expired",
|
||||
"empty": "No files uploaded.",
|
||||
"totalCount": "Total: {{count}} file(s)",
|
||||
"artifactsTitle": "Artifacts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import hljs from 'highlight.js/lib/core';
|
||||
import javascript from 'highlight.js/lib/languages/javascript';
|
||||
import json from 'highlight.js/lib/languages/json';
|
||||
|
||||
hljs.registerLanguage('javascript', javascript);
|
||||
hljs.registerLanguage('json', json);
|
||||
|
||||
export default hljs;
|
||||
@@ -0,0 +1,30 @@
|
||||
export const API_ERROR_TOAST_EVENT = 'liqa:api-error-toast';
|
||||
|
||||
export interface ApiErrorToastDetail {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function emitApiErrorToast(message: string): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<ApiErrorToastDetail>(API_ERROR_TOAST_EVENT, {
|
||||
detail: { message },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function subscribeApiErrorToasts(handler: (message: string) => void): () => void {
|
||||
if (typeof window === 'undefined') return () => {};
|
||||
|
||||
const listener = (event: Event) => {
|
||||
const custom = event as CustomEvent<ApiErrorToastDetail>;
|
||||
const message = custom.detail?.message;
|
||||
if (message) handler(message);
|
||||
};
|
||||
|
||||
window.addEventListener(API_ERROR_TOAST_EVENT, listener);
|
||||
return () => {
|
||||
window.removeEventListener(API_ERROR_TOAST_EVENT, listener);
|
||||
};
|
||||
}
|
||||
+12
-4
@@ -1,14 +1,22 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { HashRouter } from 'react-router-dom';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import './i18n';
|
||||
import './ui/tokens.css';
|
||||
import App from './App';
|
||||
import { ToastProvider } from './ui';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<HashRouter>
|
||||
<App />
|
||||
</HashRouter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -1,44 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { keys } from '../api';
|
||||
import { Breadcrumbs, Table, type TableColumn } from '../ui';
|
||||
import styles from './Page.module.css';
|
||||
|
||||
interface KeyRow {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export function KeysPage() {
|
||||
const { t } = useTranslation();
|
||||
const [items, setItems] = useState<KeyRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const columns: TableColumn<KeyRow>[] = [
|
||||
{ key: 'name', header: t('keys.col_name'), render: (k) => k.name },
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
keys
|
||||
.list()
|
||||
.then((res) => setItems(res.keys.map((name) => ({ name }))))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumbs items={[{ label: t('keys.title') }]} className={styles.breadcrumbs} />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(k) => k.name}
|
||||
loading={loading}
|
||||
emptyMessage={t('keys.empty')}
|
||||
pageSize={10}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
}
|
||||
|
||||
.sectionHeading {
|
||||
margin: 0;
|
||||
margin: 0 0 var(--space-3);
|
||||
line-height: 1;
|
||||
font-size: var(--font-size-md);
|
||||
font-weight: 600;
|
||||
@@ -17,6 +17,13 @@
|
||||
margin-top: var(--space-6);
|
||||
}
|
||||
|
||||
.sectionHeadingRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
.breadcrumbs {
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
@@ -92,7 +99,8 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.envCardId {
|
||||
@@ -138,6 +146,35 @@
|
||||
color: var(--color-link-hover);
|
||||
}
|
||||
|
||||
.dragHandle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: grab;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.dragHandle:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary) 18%, transparent);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.dragHandle:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.dragHandleDisabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.dragOverRow {
|
||||
background: color-mix(in srgb, var(--color-primary) 16%, transparent) !important;
|
||||
}
|
||||
|
||||
.envCardHeader button:hover {
|
||||
background: color-mix(in srgb, currentColor 15%, transparent) !important;
|
||||
}
|
||||
@@ -189,6 +226,10 @@
|
||||
max-width: 540px;
|
||||
}
|
||||
|
||||
.formCardFull {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.formFields {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('credentials.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
@@ -33,12 +36,13 @@ export function CreateCredentialPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const credential = await credentials.create(name.trim(), data.trim() || undefined);
|
||||
toast.success(t('credentials.created'));
|
||||
navigate(`/credentials/${credential.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -49,16 +53,18 @@ export function CreateCredentialPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{ label: t('credentials.create_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('credentials.form_name')}
|
||||
@@ -72,24 +78,32 @@ export function CreateCredentialPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Textarea
|
||||
label={t('credentials.form_data')}
|
||||
placeholder={t('credentials.form_data_placeholder')}
|
||||
value={data}
|
||||
onChange={(e) => {
|
||||
setData(e.target.value);
|
||||
setDataError('');
|
||||
}}
|
||||
error={dataError || undefined}
|
||||
rows={6}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('credentials.form_data')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeEditor
|
||||
language="json"
|
||||
value={data}
|
||||
onChange={(v) => {
|
||||
setData(v);
|
||||
setDataError('');
|
||||
}}
|
||||
rows={6}
|
||||
error={!!dataError}
|
||||
/>
|
||||
{dataError && <span className={styles.fieldError}>{dataError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/credentials')}>
|
||||
<X size={14} />
|
||||
{t('credentials.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('credentials.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Pencil, Trash2 } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, KeyRound } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CredentialDetailPage() {
|
||||
@@ -14,21 +17,28 @@ export function CredentialDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(credential?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
credentials
|
||||
.get(id)
|
||||
.then(setCredential)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!credential) return;
|
||||
await credentials.remove(credential.id);
|
||||
navigate('/credentials');
|
||||
setDeleting(true);
|
||||
try {
|
||||
await credentials.remove(credential.id);
|
||||
navigate('/credentials');
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setConfirmDeleteOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
@@ -48,14 +58,18 @@ export function CredentialDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{ label: credential?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{credential && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Download size={14} />
|
||||
<Upload size={14} />
|
||||
{t('credentials.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -66,7 +80,7 @@ export function CredentialDetailPage() {
|
||||
<Pencil size={14} />
|
||||
{t('credentials.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
|
||||
<Trash2 size={14} />
|
||||
{t('credentials.action_delete')}
|
||||
</Button>
|
||||
@@ -74,31 +88,18 @@ export function CredentialDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_credential', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
|
||||
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
|
||||
|
||||
{credential && (
|
||||
<>
|
||||
<div className={styles.detailMeta}>
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('credentials.field_id'), detail: <UuidBadge id={credential.id} /> },
|
||||
{
|
||||
term: t('credentials.field_last_used'),
|
||||
detail: credential.lastUsedAt ? (
|
||||
<Timestamp value={credential.lastUsedAt} />
|
||||
) : (
|
||||
'—'
|
||||
),
|
||||
detail: credential.lastUsedAt ? <Timestamp value={credential.lastUsedAt} /> : '—',
|
||||
},
|
||||
{
|
||||
term: t('credentials.field_created'),
|
||||
@@ -110,26 +111,36 @@ export function CredentialDetailPage() {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{credential.data && (
|
||||
<>
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('credentials.section_data')}</h2>
|
||||
<Card>
|
||||
<pre className={styles.codeBlock}>
|
||||
{(() => {
|
||||
<CodeBlock
|
||||
language="json"
|
||||
code={(() => {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(credential.data), null, 2);
|
||||
} catch {
|
||||
return credential.data;
|
||||
}
|
||||
})()}
|
||||
</pre>
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('credentials.action_delete')}
|
||||
message={t('common.confirm_delete_credential')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Settings, Pencil, Trash2, Plus, Upload } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
ContextMenu,
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function CredentialCard({
|
||||
@@ -91,17 +101,17 @@ function AddCredentialCard() {
|
||||
|
||||
export function CredentialsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
usePageTitle(t('credentials.title'));
|
||||
const [items, setItems] = useState<Credential[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = () => {
|
||||
credentials
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -109,29 +119,28 @@ export function CredentialsPage() {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await credentials.remove(id);
|
||||
setItems((prev) => prev.filter((c) => c.id !== id));
|
||||
const requestDelete = (id: string) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await credentials.importCredential(payload);
|
||||
navigate(`/credentials/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
await credentials.remove(deleteId);
|
||||
setItems((prev) => prev.filter((c) => c.id !== deleteId));
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = useImportFile('credential');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('credentials.title') }]} className={styles.breadcrumbs} />
|
||||
<Breadcrumbs items={[{ label: t('credentials.title'), icon: <KeyRound size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
@@ -141,22 +150,30 @@ export function CredentialsPage() {
|
||||
onChange={handleImport}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload size={14} />
|
||||
<Download size={14} />
|
||||
{t('credentials.action_import')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading ? (
|
||||
<p className={styles.muted}>{t('credentials.loading')}</p>
|
||||
) : (
|
||||
<div className={styles.envGrid}>
|
||||
{items.map((credential) => (
|
||||
<CredentialCard key={credential.id} credential={credential} onDelete={handleDelete} />
|
||||
<CredentialCard key={credential.id} credential={credential} onDelete={requestDelete} />
|
||||
))}
|
||||
<AddCredentialCard />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('credentials.action_delete')}
|
||||
message={t('common.confirm_delete_credential')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,31 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { KeyRound, X, Save } from 'lucide-react';
|
||||
import { credentials } from '../../api';
|
||||
import type { Credential } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditCredentialPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [credential, setCredential] = useState<Credential | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
credential
|
||||
? `${t('credentials.edit_title')} — ${credential.name}`
|
||||
: t('credentials.edit_title'),
|
||||
);
|
||||
const [data, setData] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -29,11 +36,10 @@ export function EditCredentialPage() {
|
||||
setName(c.name);
|
||||
setData(c.data ?? '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
@@ -50,15 +56,16 @@ export function EditCredentialPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await credentials.update(id!, {
|
||||
name: name.trim(),
|
||||
data: data.trim() || null,
|
||||
});
|
||||
toast.success(t('credentials.updated'));
|
||||
navigate(`/credentials/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -69,7 +76,11 @@ export function EditCredentialPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('credentials.title'), onClick: () => navigate('/credentials') },
|
||||
{
|
||||
label: t('credentials.title'),
|
||||
icon: <KeyRound size={14} />,
|
||||
onClick: () => navigate('/credentials'),
|
||||
},
|
||||
{
|
||||
label: credential?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/credentials/${id}`),
|
||||
@@ -79,12 +90,11 @@ export function EditCredentialPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('credentials.loading')}</p>}
|
||||
|
||||
{!loading && credential && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('credentials.form_name')}
|
||||
@@ -98,17 +108,23 @@ export function EditCredentialPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Textarea
|
||||
label={t('credentials.form_data')}
|
||||
placeholder={t('credentials.form_data_placeholder')}
|
||||
value={data}
|
||||
onChange={(e) => {
|
||||
setData(e.target.value);
|
||||
setDataError('');
|
||||
}}
|
||||
error={dataError || undefined}
|
||||
rows={6}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('credentials.form_data')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeEditor
|
||||
language="json"
|
||||
value={data}
|
||||
onChange={(v) => {
|
||||
setData(v);
|
||||
setDataError('');
|
||||
}}
|
||||
rows={6}
|
||||
error={!!dataError}
|
||||
/>
|
||||
{dataError && <span className={styles.fieldError}>{dataError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
@@ -117,9 +133,11 @@ export function EditCredentialPage() {
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/credentials/${id}`)}
|
||||
>
|
||||
<X size={14} />
|
||||
{t('credentials.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('credentials.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,39 +1,60 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateEnvironmentPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('environments.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [idUrl, setIdUrl] = useState('');
|
||||
const [cabinetUrl, setCabinetUrl] = useState('');
|
||||
const [adminUrl, setAdminUrl] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{\n "id": "https://id.example.com"\n}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('environments.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
let parsedData: Record<string, string | undefined>;
|
||||
try {
|
||||
const env = await environments.create(name.trim(), {
|
||||
id_url: idUrl.trim() || undefined,
|
||||
cabinet_url: cabinetUrl.trim() || undefined,
|
||||
admin_url: adminUrl.trim() || undefined,
|
||||
});
|
||||
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
||||
throw new Error('invalid');
|
||||
}
|
||||
parsedData = Object.fromEntries(
|
||||
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
|
||||
k,
|
||||
v == null ? undefined : String(v),
|
||||
]),
|
||||
);
|
||||
setDataError('');
|
||||
} catch {
|
||||
setDataError(t('environments.form_data_invalid_json'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const env = await environments.create(
|
||||
name.trim(),
|
||||
parsedData,
|
||||
description.trim() || undefined,
|
||||
);
|
||||
toast.success(t('environments.created'));
|
||||
navigate(`/environments/${env.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -44,16 +65,18 @@ export function CreateEnvironmentPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{ label: t('environments.create_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('environments.form_name')}
|
||||
@@ -67,34 +90,38 @@ export function CreateEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_id_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={idUrl}
|
||||
onChange={(e) => setIdUrl(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_cabinet_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={cabinetUrl}
|
||||
onChange={(e) => setCabinetUrl(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_admin_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={adminUrl}
|
||||
onChange={(e) => setAdminUrl(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
language="json"
|
||||
value={dataJson}
|
||||
onChange={(v) => {
|
||||
setDataJson(v);
|
||||
setDataError('');
|
||||
}}
|
||||
rows={8}
|
||||
error={!!dataError}
|
||||
/>
|
||||
{dataError && <span className={styles.fieldError}>{dataError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/environments')}>
|
||||
<X size={14} />
|
||||
{t('environments.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('environments.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Globe, Save } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditEnvironmentPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [idUrl, setIdUrl] = useState('');
|
||||
const [cabinetUrl, setCabinetUrl] = useState('');
|
||||
const [adminUrl, setAdminUrl] = useState('');
|
||||
usePageTitle(
|
||||
env ? `${t('environments.edit_title')} — ${env.name}` : t('environments.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [dataJson, setDataJson] = useState('{}');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [dataError, setDataError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -28,34 +33,47 @@ export function EditEnvironmentPage() {
|
||||
.then((data) => {
|
||||
setEnv(data);
|
||||
setName(data.name);
|
||||
setIdUrl(data.urls.id_url ?? '');
|
||||
setCabinetUrl(data.urls.cabinet_url ?? '');
|
||||
setAdminUrl(data.urls.admin_url ?? '');
|
||||
setDescription(data.description || '');
|
||||
setDataJson(JSON.stringify(data.data ?? {}, null, 2));
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('environments.form_name_required'));
|
||||
return;
|
||||
}
|
||||
let parsedData: Record<string, string | undefined>;
|
||||
try {
|
||||
const raw = dataJson.trim() ? JSON.parse(dataJson.trim()) : {};
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
||||
throw new Error('invalid');
|
||||
}
|
||||
parsedData = Object.fromEntries(
|
||||
Object.entries(raw as Record<string, unknown>).map(([k, v]) => [
|
||||
k,
|
||||
v == null ? undefined : String(v),
|
||||
]),
|
||||
);
|
||||
setDataError('');
|
||||
} catch {
|
||||
setDataError(t('environments.form_data_invalid_json'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await environments.update(id!, {
|
||||
name: name.trim(),
|
||||
urls: {
|
||||
id_url: idUrl.trim() || undefined,
|
||||
cabinet_url: cabinetUrl.trim() || undefined,
|
||||
admin_url: adminUrl.trim() || undefined,
|
||||
},
|
||||
description: description.trim() || undefined,
|
||||
data: parsedData,
|
||||
});
|
||||
toast.success(t('environments.updated'));
|
||||
navigate(`/environments/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -66,7 +84,11 @@ export function EditEnvironmentPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{
|
||||
label: env?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/environments/${id}`),
|
||||
@@ -76,12 +98,11 @@ export function EditEnvironmentPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
|
||||
|
||||
{!loading && env && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('environments.form_name')}
|
||||
@@ -95,27 +116,29 @@ export function EditEnvironmentPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_id_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={idUrl}
|
||||
onChange={(e) => setIdUrl(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_cabinet_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={cabinetUrl}
|
||||
onChange={(e) => setCabinetUrl(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label={t('environments.form_admin_url')}
|
||||
type="url"
|
||||
placeholder="https://…"
|
||||
value={adminUrl}
|
||||
onChange={(e) => setAdminUrl(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('environments.form_data')}</label>
|
||||
<CodeEditor
|
||||
language="json"
|
||||
value={dataJson}
|
||||
onChange={(v) => {
|
||||
setDataJson(v);
|
||||
setDataError('');
|
||||
}}
|
||||
rows={8}
|
||||
error={!!dataError}
|
||||
/>
|
||||
{dataError && <span className={styles.fieldError}>{dataError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
@@ -124,9 +147,11 @@ export function EditEnvironmentPage() {
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/environments/${id}`)}
|
||||
>
|
||||
<X size={14} />
|
||||
{t('environments.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('environments.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,33 +1,67 @@
|
||||
import { Globe, Pencil, Trash2, Upload } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { environments } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp } from '../../ui';
|
||||
import { environments } from '../../api';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EnvironmentDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [env, setEnv] = useState<Environment | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(env?.name ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const dataEntries = Object.entries(env?.data ?? {}).filter(([, v]) => v);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
environments
|
||||
.get(id)
|
||||
.then(setEnv)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.catch((err: Error) => toast.error((err as Error).message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
}, [id, toast]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!env) return;
|
||||
await environments.remove(env.id);
|
||||
navigate('/environments');
|
||||
setDeleting(true);
|
||||
try {
|
||||
await environments.remove(env.id);
|
||||
navigate('/environments');
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setConfirmDeleteOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!env) return;
|
||||
const data = await environments.exportEnvironment(env.id);
|
||||
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `environment-${env.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -35,12 +69,20 @@ export function EnvironmentDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('environments.title'), onClick: () => navigate('/environments') },
|
||||
{
|
||||
label: t('environments.title'),
|
||||
icon: <Globe size={14} />,
|
||||
onClick: () => navigate('/environments'),
|
||||
},
|
||||
{ label: env?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{env && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Upload size={14} />
|
||||
{t('environments.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
@@ -49,7 +91,7 @@ export function EnvironmentDetailPage() {
|
||||
<Pencil size={14} />
|
||||
{t('environments.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
|
||||
<Trash2 size={14} />
|
||||
{t('environments.action_delete')}
|
||||
</Button>
|
||||
@@ -57,24 +99,15 @@ export function EnvironmentDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_environment', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
|
||||
{loading && <p className={styles.muted}>{t('environments.loading')}</p>}
|
||||
|
||||
{env && (
|
||||
<>
|
||||
<div className={styles.detailMeta}>
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('environments.field_id'), detail: env.id },
|
||||
{ term: t('environments.field_id'), detail: <UuidBadge id={env.id} /> },
|
||||
{
|
||||
term: t('environments.field_created'),
|
||||
detail: <Timestamp value={env.createdAt} />,
|
||||
@@ -85,18 +118,28 @@ export function EnvironmentDetailPage() {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<h2 className={styles.sectionHeading}>{t('environments.section_urls')}</h2>
|
||||
<Card>
|
||||
{Object.entries(env.urls).filter(([, v]) => v).length === 0 ? (
|
||||
<p className={styles.muted}>{t('environments.no_urls')}</p>
|
||||
) : (
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
items={Object.entries(env.urls)
|
||||
.filter(([, v]) => v)
|
||||
.map(([key, value]) => ({
|
||||
{env.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={env.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('environments.section_data')}</h2>
|
||||
<Card>
|
||||
{dataEntries.length === 0 ? (
|
||||
<p className={styles.muted}>{t('environments.no_data')}</p>
|
||||
) : (
|
||||
<DescriptionList
|
||||
layout="grid"
|
||||
items={dataEntries.map(([key, value]) => ({
|
||||
term: key,
|
||||
detail: (
|
||||
<a href={value} target="_blank" rel="noopener noreferrer">
|
||||
@@ -104,11 +147,21 @@ export function EnvironmentDetailPage() {
|
||||
</a>
|
||||
),
|
||||
}))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('environments.action_delete')}
|
||||
message={t('common.confirm_delete_environment')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,39 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Settings, ExternalLink, Pencil, Trash2, Plus } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, ContextMenu, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
ContextMenu,
|
||||
DescriptionList,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: string) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const urlEntries = Object.entries(env.urls).filter(([, v]) => v);
|
||||
const dataEntries = Object.entries(env.data ?? {}).filter(([, v]) => v);
|
||||
|
||||
const handleExport = async () => {
|
||||
const data = await environments.exportEnvironment(env.id);
|
||||
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `environment-${env.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const header = (
|
||||
<div className={styles.envCardHeader}>
|
||||
@@ -34,6 +57,11 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
|
||||
icon: <Pencil size={14} />,
|
||||
onClick: () => navigate(`/environments/${env.id}/edit`),
|
||||
},
|
||||
{
|
||||
label: t('environments.action_export'),
|
||||
icon: <Download size={14} />,
|
||||
onClick: () => void handleExport(),
|
||||
},
|
||||
{
|
||||
label: t('environments.action_delete'),
|
||||
icon: <Trash2 size={14} />,
|
||||
@@ -61,15 +89,15 @@ function EnvironmentCard({ env, onDelete }: { env: Environment; onDelete: (id: s
|
||||
footer={footer}
|
||||
onClick={() => navigate(`/environments/${env.id}`)}
|
||||
>
|
||||
{urlEntries.length > 0 && (
|
||||
{dataEntries.length > 0 && (
|
||||
<DescriptionList
|
||||
layout="compact"
|
||||
truncate
|
||||
items={urlEntries.map(([key, value]) => ({ term: key, detail: value }))}
|
||||
items={dataEntries.map(([key, value]) => ({ term: key, detail: value }))}
|
||||
/>
|
||||
)}
|
||||
{urlEntries.length === 0 && (
|
||||
<p className={styles.envCardEmpty}>{t('environments.no_urls')}</p>
|
||||
{dataEntries.length === 0 && (
|
||||
<p className={styles.envCardEmpty}>{t('environments.no_data')}</p>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
@@ -90,15 +118,17 @@ function AddEnvironmentCard() {
|
||||
|
||||
export function EnvironmentsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('environments.title'));
|
||||
const [items, setItems] = useState<Environment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = () => {
|
||||
environments
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -106,25 +136,61 @@ export function EnvironmentsPage() {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await environments.remove(id);
|
||||
setItems((prev) => prev.filter((e) => e.id !== id));
|
||||
const requestDelete = (id: string) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await environments.remove(deleteId);
|
||||
setItems((prev) => prev.filter((e) => e.id !== deleteId));
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = useImportFile('environment');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumbs items={[{ label: t('environments.title') }]} className={styles.breadcrumbs} />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('environments.title'), icon: <Globe size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".yaml,.yml,.json"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleImport}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Download size={14} />
|
||||
{t('environments.action_import')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{loading ? (
|
||||
<p className={styles.muted}>{t('environments.loading')}</p>
|
||||
) : (
|
||||
<div className={styles.envGrid}>
|
||||
{items.map((env) => (
|
||||
<EnvironmentCard key={env.id} env={env} onDelete={handleDelete} />
|
||||
<EnvironmentCard key={env.id} env={env} onDelete={requestDelete} />
|
||||
))}
|
||||
<AddEnvironmentCard />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('environments.action_delete')}
|
||||
message={t('common.confirm_delete_environment')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useRef, useState, type ChangeEvent } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Upload } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { importedItemPath } from '../../hooks/useImportFile';
|
||||
import { imports } from '../../api';
|
||||
import type { ImportedItem, ImportResult } from '../../api';
|
||||
import { Badge, Breadcrumbs, Button, Card, Table, type TableColumn } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
interface FileResult {
|
||||
fileName: string;
|
||||
result: ImportResult;
|
||||
}
|
||||
|
||||
type Row = ImportedItem & { fileName: string; rowKey: string };
|
||||
|
||||
export function ImportPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('import.title'));
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
// List pages hand over the result of an import they ran
|
||||
const [results, setResults] = useState<FileResult[]>(
|
||||
() => (location.state as { results?: FileResult[] } | null)?.results ?? [],
|
||||
);
|
||||
const [importing, setImporting] = useState(false);
|
||||
|
||||
const handleFiles = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
e.target.value = '';
|
||||
if (files.length === 0) return;
|
||||
setImporting(true);
|
||||
const next: FileResult[] = [];
|
||||
try {
|
||||
for (const file of files) {
|
||||
try {
|
||||
next.push({ fileName: file.name, result: await imports.yaml(await file.text()) });
|
||||
} catch {
|
||||
// error toast is already emitted by the API client; nothing from
|
||||
// this file was imported, continue with the next one
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setResults(next);
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const rows: Row[] = results.flatMap(({ fileName, result }) =>
|
||||
result.imported.map((item, i) => ({ ...item, fileName, rowKey: `${fileName}-${i}` })),
|
||||
);
|
||||
|
||||
const columns: TableColumn<Row>[] = [
|
||||
{ key: 'fileName', header: t('import.col_file'), render: (r) => r.fileName },
|
||||
{
|
||||
key: 'kind',
|
||||
header: t('import.col_kind'),
|
||||
width: 120,
|
||||
render: (r) => <Badge variant="neutral">{t(`import.kind_${r.kind}`)}</Badge>,
|
||||
},
|
||||
{ key: 'name', header: t('import.col_name'), render: (r) => r.name },
|
||||
{
|
||||
key: 'version',
|
||||
header: t('import.col_version'),
|
||||
width: 90,
|
||||
render: (r) =>
|
||||
r.version != null ? `v${r.version}` : <span className={styles.muted}>–</span>,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('import.title'), icon: <Upload size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".yaml,.yml,.json"
|
||||
multiple
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFiles}
|
||||
/>
|
||||
<Button size="sm" onClick={() => fileInputRef.current?.click()} disabled={importing}>
|
||||
<Upload size={14} />
|
||||
{t('import.action_choose')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<p>{t('import.description')}</p>
|
||||
<p className={styles.muted}>{t('import.description_validation')}</p>
|
||||
</Card>
|
||||
|
||||
{rows.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>
|
||||
{t('import.imported_count', { count: rows.length })}
|
||||
</h2>
|
||||
<Table<Row>
|
||||
columns={columns}
|
||||
data={rows}
|
||||
rowKey={(r) => r.rowKey}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
onRowClick={(r) => navigate(importedItemPath(r))}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,21 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Activity } from 'lucide-react';
|
||||
import { runs } from '../../api';
|
||||
import type { ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
|
||||
import { AutoRefreshIndicator, Badge, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
|
||||
import type { ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
@@ -22,45 +34,49 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
};
|
||||
|
||||
type AllRunRow = ScenarioRun & {
|
||||
stepRuns: ScenarioRunStep[];
|
||||
scenario: { id: number; name: string };
|
||||
scenario: { id: string; name: string };
|
||||
};
|
||||
|
||||
export function AllRunsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('runs.title'));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [items, setItems] = useState<AllRunRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
|
||||
const load = () => {
|
||||
runs
|
||||
.listAll()
|
||||
.then((res) => {
|
||||
setItems(res.data as AllRunRow[]);
|
||||
setPulseKey((k) => k + 1);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
const { data, isLoading, error, refetch } = useQuery({
|
||||
queryKey: ['runs', sortBy, sortDir, page, pageSize],
|
||||
queryFn: () =>
|
||||
runs.listAll(page, pageSize, undefined, sortBy, sortDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const items = (data?.data ?? []) as AllRunRow[];
|
||||
const total = data?.total ?? 0;
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, []);
|
||||
const handlePageChange = (p: number) => setPage(p);
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const columns: TableColumn<AllRunRow>[] = [
|
||||
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
|
||||
{
|
||||
key: 'scenario',
|
||||
key: 'scenario.name',
|
||||
header: t('runs.col_scenario'),
|
||||
sortable: true,
|
||||
render: (r) => (
|
||||
<span
|
||||
className={styles.linkCell}
|
||||
@@ -77,20 +93,25 @@ export function AllRunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 110,
|
||||
render: (r) => (
|
||||
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
|
||||
),
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -98,20 +119,31 @@ export function AllRunsPage() {
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<h1 className={styles.pageTitle}>{t('runs.title')}</h1>
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} />
|
||||
<Breadcrumbs items={[{ label: t('runs.title'), icon: <Activity size={14} /> }]} />
|
||||
<AutoRefreshIndicator
|
||||
active
|
||||
pulseKey={items.length}
|
||||
error={!!error}
|
||||
onClick={() => refetch()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
loading={isLoading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${r.scenarioId}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { runs } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { runs, runFiles } from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioRunDetail,
|
||||
@@ -10,21 +11,40 @@ import type {
|
||||
ScenarioRunStatus,
|
||||
RunStepStatus,
|
||||
LogLevel,
|
||||
FileMetadata,
|
||||
} from '../../api';
|
||||
import { scenarios } from '../../api';
|
||||
import {
|
||||
DeleteConfirmationModal,
|
||||
ExportLogsModal,
|
||||
type LogExportFormat,
|
||||
} from '../../components/modals';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Button,
|
||||
Breadcrumbs,
|
||||
Card,
|
||||
CodeBlock,
|
||||
DescriptionList,
|
||||
Notification,
|
||||
Pagination,
|
||||
Search,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Activity,
|
||||
Download,
|
||||
Trash2,
|
||||
RotateCcw,
|
||||
} from 'lucide-react';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
@@ -56,21 +76,45 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
|
||||
error: 'error',
|
||||
};
|
||||
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
export function RunDetailPage() {
|
||||
const { runId } = useParams<{ runId: string }>();
|
||||
// Remount per run so "Repeat run" navigation starts from a clean state
|
||||
return <RunDetail key={runId} />;
|
||||
}
|
||||
|
||||
function RunDetail() {
|
||||
const { t } = useTranslation();
|
||||
const { id, runId } = useParams<{ id: string; runId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [polling, setPolling] = useState(false);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const [logPage, setLogPage] = useState(1);
|
||||
const [logSearch, setLogSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
const [expandedStepIds, setExpandedStepIds] = useState<Set<string>>(new Set());
|
||||
const [artifacts, setArtifacts] = useState<FileMetadata[]>([]);
|
||||
const [artifactsTotal, setArtifactsTotal] = useState(0);
|
||||
const [artifactsLoading, setArtifactsLoading] = useState(false);
|
||||
const [exportLogsOpen, setExportLogsOpen] = useState(false);
|
||||
const [exportLogsFormat, setExportLogsFormat] = useState<LogExportFormat>('md');
|
||||
const [exportingLogs, setExportingLogs] = useState(false);
|
||||
const [pendingDeleteFile, setPendingDeleteFile] = useState<FileMetadata | null>(null);
|
||||
const [deletingFile, setDeletingFile] = useState(false);
|
||||
const [repeating, setRepeating] = useState(false);
|
||||
const logSearchRef = useRef('');
|
||||
const LOG_PAGE_SIZE = 25;
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
const stopPolling = () => {
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
@@ -79,6 +123,117 @@ export function RunDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
const handleExportLogs = async () => {
|
||||
if (!id || !runId) return;
|
||||
setExportingLogs(true);
|
||||
try {
|
||||
const content = await runs.exportLogs(id, runId, exportLogsFormat);
|
||||
const mimeType = exportLogsFormat === 'csv' ? 'text/csv' : 'text/markdown';
|
||||
const blob = new Blob([content], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `run-${runId}-logs.${exportLogsFormat}`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportLogsOpen(false);
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setExportingLogs(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepeatRun = async () => {
|
||||
if (!id || !run?.environmentId) return;
|
||||
setRepeating(true);
|
||||
try {
|
||||
const newRun = await scenarios.run(
|
||||
id,
|
||||
run.environmentId,
|
||||
run.saveSession,
|
||||
run.traceMode ?? undefined,
|
||||
run.scenarioVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${newRun.id}`);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRepeating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFile = async () => {
|
||||
if (!id || !runId || !pendingDeleteFile) return;
|
||||
setDeletingFile(true);
|
||||
try {
|
||||
await runFiles.remove(id, runId, pendingDeleteFile.id);
|
||||
toast.success(t('files.deleteSuccess'));
|
||||
setPendingDeleteFile(null);
|
||||
await loadArtifacts();
|
||||
} catch {
|
||||
// error toast is already emitted by the API client
|
||||
} finally {
|
||||
setDeletingFile(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manualRefresh = () => {
|
||||
if (!id || !runId) return;
|
||||
runs
|
||||
.get(id, runId, logSearchRef.current)
|
||||
.then((r) => {
|
||||
setRun(r);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message));
|
||||
};
|
||||
|
||||
const loadArtifacts = useCallback(async () => {
|
||||
if (!id || !runId) return;
|
||||
setArtifactsLoading(true);
|
||||
try {
|
||||
const result = await runFiles.list(id, runId);
|
||||
setArtifacts(result.items);
|
||||
setArtifactsTotal(result.total);
|
||||
} catch {
|
||||
// Silently fail - artifacts are not critical
|
||||
setArtifacts([]);
|
||||
setArtifactsTotal(0);
|
||||
} finally {
|
||||
setArtifactsLoading(false);
|
||||
}
|
||||
}, [id, runId]);
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
setDebouncedSearch(logSearch);
|
||||
logSearchRef.current = logSearch;
|
||||
setLogPage(1);
|
||||
}, 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [logSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !runId || polling) return;
|
||||
runs
|
||||
.get(id, runId, debouncedSearch)
|
||||
.then(setRun)
|
||||
.catch(() => undefined);
|
||||
}, [id, runId, polling, debouncedSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !runId) return;
|
||||
let cancelled = false;
|
||||
@@ -88,37 +243,45 @@ export function RunDetailPage() {
|
||||
if (cancelled) return;
|
||||
setScenario(sc);
|
||||
setRun(r);
|
||||
loadArtifacts();
|
||||
if (!FINAL.includes(r.status)) {
|
||||
setPolling(true);
|
||||
pollRef.current = setInterval(async () => {
|
||||
try {
|
||||
const updated = await runs.get(id, runId);
|
||||
const updated = await runs.get(id, runId, logSearchRef.current);
|
||||
if (cancelled) return;
|
||||
setRun(updated);
|
||||
setPulseKey((k) => k + 1);
|
||||
if (FINAL.includes(updated.status)) stopPolling();
|
||||
if (FINAL.includes(updated.status)) {
|
||||
stopPolling();
|
||||
await loadArtifacts();
|
||||
}
|
||||
} catch {
|
||||
stopPolling();
|
||||
}
|
||||
}, 1000);
|
||||
}
|
||||
})
|
||||
.catch((err: Error) => { if (!cancelled) setError(err.message); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
.catch((err: Error) => {
|
||||
if (!cancelled) setError(err.message);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
stopPolling();
|
||||
};
|
||||
}, [id, runId]);
|
||||
}, [id, runId, loadArtifacts]);
|
||||
|
||||
const stepColumns: TableColumn<ScenarioRunStep>[] = [
|
||||
{ key: 'order', header: t('runs.step_order'), render: (s) => s.order, width: 50 },
|
||||
{
|
||||
key: 'type',
|
||||
header: t('runs.step_type'),
|
||||
width: 80,
|
||||
render: (s) => <Badge variant="neutral">{s.scenarioStep?.type ?? '–'}</Badge>,
|
||||
key: 'title',
|
||||
header: t('runs.step_title'),
|
||||
width: 220,
|
||||
render: (s) => s.title ?? <span className={styles.muted}>–</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
@@ -130,8 +293,110 @@ export function RunDetailPage() {
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: t('runs.step_description'),
|
||||
render: (s) => s.description ?? <span className={styles.muted}>–</span>,
|
||||
header: (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
gap: '8px',
|
||||
}}
|
||||
>
|
||||
<span>{t('runs.step_description')}</span>
|
||||
{run?.stepRuns.some((s) => s.output) && (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (expandAll) {
|
||||
setExpandAll(false);
|
||||
setExpandedStepIds(new Set());
|
||||
} else {
|
||||
setExpandAll(true);
|
||||
setExpandedStepIds(
|
||||
new Set(run?.stepRuns.filter((s) => s.output).map((s) => s.id) ?? []),
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: '0 4px',
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
color: 'inherit',
|
||||
}}
|
||||
title={expandAll ? 'Collapse all' : 'Expand all'}
|
||||
>
|
||||
{expandAll ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
render: (s) => {
|
||||
const isExpanded = expandAll || expandedStepIds.has(s.id);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: '8px',
|
||||
marginBottom: isExpanded && s.output ? '8px' : 0,
|
||||
}}
|
||||
>
|
||||
{s.output && (
|
||||
<button
|
||||
onClick={() => {
|
||||
const newSet = new Set(expandedStepIds);
|
||||
if (newSet.has(s.id)) {
|
||||
newSet.delete(s.id);
|
||||
} else {
|
||||
newSet.add(s.id);
|
||||
}
|
||||
setExpandedStepIds(newSet);
|
||||
}}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: 0,
|
||||
cursor: 'pointer',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
flexShrink: 0,
|
||||
marginTop: '2px',
|
||||
}}
|
||||
>
|
||||
{isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</button>
|
||||
)}
|
||||
<code style={{ wordBreak: 'break-word' }}>
|
||||
{s.description ? (
|
||||
s.description
|
||||
) : s.output ? (
|
||||
<span title={`${s.output.length} bytes`}>{s.output.length} bytes</span>
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
)}
|
||||
</code>
|
||||
</div>
|
||||
{isExpanded && s.output && (
|
||||
<div style={{ marginLeft: '24px' }}>
|
||||
<CodeBlock
|
||||
code={(() => {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(s.output), null, 2);
|
||||
} catch {
|
||||
return s.output;
|
||||
}
|
||||
})()}
|
||||
language="json"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -142,7 +407,11 @@ export function RunDetailPage() {
|
||||
width: 70,
|
||||
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
|
||||
},
|
||||
{ key: 'message', header: t('runs.log_message'), render: (l) => l.message },
|
||||
{
|
||||
key: 'message',
|
||||
header: t('runs.log_message'),
|
||||
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
|
||||
},
|
||||
{
|
||||
key: 'time',
|
||||
header: t('runs.log_time'),
|
||||
@@ -156,47 +425,109 @@ export function RunDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{
|
||||
label: t('runs.title'),
|
||||
icon: <Activity size={14} />,
|
||||
onClick: () => navigate(`/scenarios/${id}/runs`),
|
||||
},
|
||||
{ label: `#${runId}` },
|
||||
{ label: `${runId}` },
|
||||
]}
|
||||
/>
|
||||
<AutoRefreshIndicator active={polling} pulseKey={pulseKey} />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
{run && (
|
||||
<span title={run.environmentId ? undefined : t('runs.repeat_no_environment')}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={handleRepeatRun}
|
||||
disabled={!run.environmentId || repeating}
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
{t('runs.action_repeat')}
|
||||
</Button>
|
||||
</span>
|
||||
)}
|
||||
<AutoRefreshIndicator
|
||||
active={polling}
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={manualRefresh}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification variant="error">
|
||||
{error.startsWith('404') ? t('errors.not_found') : error}
|
||||
</Notification>
|
||||
)}
|
||||
{loading && <p className={styles.muted}>{t('runs.loading')}</p>}
|
||||
|
||||
{run && (
|
||||
<>
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
items={[
|
||||
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
|
||||
{
|
||||
term: t('runs.field_status'),
|
||||
detail: (
|
||||
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
|
||||
{RUN_STATUS_LABEL[run.status]}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{ term: t('runs.field_steps'), detail: run.stepRuns.length },
|
||||
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
|
||||
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
|
||||
]}
|
||||
layout="grid"
|
||||
items={(() => {
|
||||
const items = [
|
||||
{ term: t('runs.field_id'), detail: <UuidBadge id={run.id} /> },
|
||||
{
|
||||
term: t('runs.field_status'),
|
||||
detail: (
|
||||
<Badge variant={RUN_STATUS_VARIANT[run.status]}>
|
||||
{RUN_STATUS_LABEL[run.status]}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{ term: t('runs.field_created'), detail: <Timestamp value={run.createdAt} /> },
|
||||
{ term: t('runs.field_updated'), detail: <Timestamp value={run.updatedAt} /> },
|
||||
];
|
||||
if (run.scenarioVersion != null) {
|
||||
items.push({
|
||||
term: t('runs.field_scenario_version'),
|
||||
detail: <span>v{run.scenarioVersion}</span>,
|
||||
});
|
||||
}
|
||||
if (run.traceMode) {
|
||||
items.push({
|
||||
term: t('runs.field_trace'),
|
||||
detail: (
|
||||
<span>{t(`scenarios.trace_mode_${run.traceMode.replace(/-/g, '_')}`)}</span>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (run.environment) {
|
||||
items.push({
|
||||
term: 'Environment',
|
||||
detail: (
|
||||
<Link
|
||||
to={`/environments/${run.environment.id}`}
|
||||
style={{ color: 'var(--color-link)' }}
|
||||
>
|
||||
{run.environment.name}
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
}
|
||||
if (run.session) {
|
||||
items.push({
|
||||
term: 'Session',
|
||||
detail: (
|
||||
<Link
|
||||
to={`/sessions/${run.session.id}`}
|
||||
style={{ color: 'var(--color-link)' }}
|
||||
>
|
||||
{run.session.sessionName}
|
||||
</Link>
|
||||
),
|
||||
});
|
||||
}
|
||||
return items;
|
||||
})()}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
@@ -215,18 +546,134 @@ export function RunDetailPage() {
|
||||
|
||||
{run.logs.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => setExportLogsOpen(true)}>
|
||||
<Download size={14} />
|
||||
{t('runs.action_download_logs')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={logColumns}
|
||||
data={run.logs}
|
||||
data={run.logs.slice((logPage - 1) * LOG_PAGE_SIZE, logPage * LOG_PAGE_SIZE)}
|
||||
rowKey={(l) => l.id}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
/>
|
||||
{run.logs.length > LOG_PAGE_SIZE && (
|
||||
<Pagination
|
||||
page={logPage}
|
||||
pageSize={LOG_PAGE_SIZE}
|
||||
total={run.logs.length}
|
||||
onPageChange={setLogPage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(artifactsTotal > 0 || artifactsLoading) && (
|
||||
<div className={styles.stepsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.artifactsTitle')}</h2>
|
||||
<Table<FileMetadata>
|
||||
loading={artifactsLoading}
|
||||
data={artifacts}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{ key: 'name', header: t('files.name'), render: (f) => f.name },
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(runFiles.contentUrl(id!, runId!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
header: '',
|
||||
render: (f) => (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={t('files.delete')}
|
||||
aria-label={t('files.delete')}
|
||||
onClick={() => setPendingDeleteFile(f)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<ExportLogsModal
|
||||
open={exportLogsOpen}
|
||||
format={exportLogsFormat}
|
||||
onFormatChange={setExportLogsFormat}
|
||||
onClose={() => setExportLogsOpen(false)}
|
||||
onExport={handleExportLogs}
|
||||
isExporting={exportingLogs}
|
||||
/>
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={pendingDeleteFile != null}
|
||||
title={t('files.deleteTitle')}
|
||||
message={t('files.confirmDelete', { name: pendingDeleteFile?.name ?? '' })}
|
||||
onClose={() => setPendingDeleteFile(null)}
|
||||
onConfirm={handleDeleteFile}
|
||||
isDeleting={deletingFile}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play } from 'lucide-react';
|
||||
import { scenarios, runs } from '../../api';
|
||||
import type { Scenario, ScenarioRun, ScenarioRunStep, ScenarioRunStatus } from '../../api';
|
||||
import { AutoRefreshIndicator, Badge, Breadcrumbs, Button, Table, Timestamp, UuidBadge, type TableColumn } from '../../ui';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Play, ClipboardList, Activity } from 'lucide-react';
|
||||
import { environments, scenarios, runs } from '../../api';
|
||||
import type { Environment, Scenario, ScenarioRun, ScenarioRunStatus } from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
@@ -22,44 +36,122 @@ const STATUS_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
type RunRow = ScenarioRun & { stepRuns: ScenarioRunStep[] };
|
||||
type RunRow = ScenarioRun;
|
||||
|
||||
export function RunsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [items, setItems] = useState<RunRow[]>([]);
|
||||
usePageTitle(scenario ? `${t('runs.title')} — ${scenario.name}` : t('runs.title'));
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const [runModalOpen, setRunModalOpen] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const hasDataRef = useRef(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
Promise.all([scenarios.get(id!), runs.list(id!)])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setPulseKey((k) => k + 1);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
const [sortBy, setSortBy] = useState('createdAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
// Keep refs so the poll interval always reads current values
|
||||
const sortByRef = useRef(sortBy);
|
||||
const sortDirRef = useRef(sortDir);
|
||||
const pageRef = useRef(page);
|
||||
const pageSizeRef = useRef(pageSize);
|
||||
useEffect(() => {
|
||||
sortByRef.current = sortBy;
|
||||
sortDirRef.current = sortDir;
|
||||
pageRef.current = page;
|
||||
pageSizeRef.current = pageSize;
|
||||
}, [sortBy, sortDir, page, pageSize]);
|
||||
|
||||
const load = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
if (!id) return;
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([
|
||||
scenarios.get(id!),
|
||||
runs.list(id!, p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
load('createdAt', 'desc', 1, 20);
|
||||
pollRef.current = setInterval(
|
||||
() => load(sortByRef.current, sortDirRef.current, pageRef.current, pageSizeRef.current),
|
||||
10_000,
|
||||
);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((res) => {
|
||||
setEnvs(res.data);
|
||||
setSelectedEnvId((prev) => prev || res.data[0]?.id || '');
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleRun = async () => {
|
||||
const run = await scenarios.run(id!);
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
if (!selectedEnvId) {
|
||||
toast.error(t('scenarios.run_modal_env_required'));
|
||||
return;
|
||||
}
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(id!, selectedEnvId);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
setRunModalOpen(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: TableColumn<RunRow>[] = [
|
||||
@@ -68,20 +160,25 @@ export function RunsPage() {
|
||||
key: 'status',
|
||||
header: t('runs.col_status'),
|
||||
width: 100,
|
||||
render: (r) => (
|
||||
<Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>
|
||||
),
|
||||
sortable: true,
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
header: t('runs.col_steps'),
|
||||
key: 'scenarioVersion',
|
||||
header: t('runs.col_version'),
|
||||
width: 80,
|
||||
render: (r) => r.stepRuns.length,
|
||||
render: (r) =>
|
||||
r.scenarioVersion != null ? (
|
||||
`v${r.scenarioVersion}`
|
||||
) : (
|
||||
<span className={styles.muted}>–</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created',
|
||||
key: 'createdAt',
|
||||
header: t('runs.col_created'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (r) => <Timestamp value={r.createdAt} />,
|
||||
},
|
||||
];
|
||||
@@ -91,34 +188,76 @@ export function RunsPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{ label: t('runs.title') },
|
||||
{ label: t('runs.title'), icon: <Activity size={14} /> },
|
||||
]}
|
||||
/>
|
||||
<div className={styles.toolbarActions}>
|
||||
<AutoRefreshIndicator active pulseKey={pulseKey} />
|
||||
<Button size="sm" onClick={handleRun}>
|
||||
<AutoRefreshIndicator
|
||||
active
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={() => load(sortBy, sortDir, page, pageSize)}
|
||||
/>
|
||||
<Button size="sm" onClick={() => setRunModalOpen(true)}>
|
||||
<Play size={14} />
|
||||
{t('runs.action_run')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(r) => r.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('runs.empty')}
|
||||
pageSize={20}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={runModalOpen}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunModalOpen(false)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunModalOpen(false)} disabled={running}>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('runs.action_run')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{envs.length === 0 ? (
|
||||
<p>{t('scenarios.run_modal_no_env')}</p>
|
||||
) : (
|
||||
<Select
|
||||
label={t('scenarios.run_modal_env_label')}
|
||||
value={selectedEnvId}
|
||||
onChange={(e) => setSelectedEnvId(e.target.value)}
|
||||
options={envs.map((env) => ({ value: env.id, label: env.name }))}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,51 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { scenarios } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateScenarioPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
useEffect(() => {
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const scenario = await scenarios.create(name.trim());
|
||||
const scenario = await scenarios.create(
|
||||
name.trim(),
|
||||
description.trim() || undefined,
|
||||
environmentId || undefined,
|
||||
);
|
||||
toast.success(t('scenarios.created'));
|
||||
navigate(`/scenarios/${scenario.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -37,14 +56,16 @@ export function CreateScenarioPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{ label: t('scenarios.create_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<div className={styles.formFields}>
|
||||
@@ -60,13 +81,33 @@ export function CreateScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/scenarios')}>
|
||||
<X size={14} />
|
||||
{t('scenarios.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('scenarios.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,57 +1,48 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, StepType } from '../../api';
|
||||
import type { CreateStepPayload } from '../../api/client';
|
||||
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
|
||||
|
||||
export function CreateStepPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [order, setOrder] = useState('0');
|
||||
usePageTitle(t('steps.create_title'));
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [validateCode, setValidateCode] = useState('');
|
||||
const [errors, setErrors] = useState<Partial<Record<keyof CreateStepPayload, string>>>({});
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
scenarios.get(id).then(setScenario).catch(() => null);
|
||||
scenarios
|
||||
.get(id)
|
||||
.then(setScenario)
|
||||
.catch(() => null);
|
||||
}, [id]);
|
||||
|
||||
const validate = (): boolean => {
|
||||
const next: typeof errors = {};
|
||||
if (isNaN(Number(order)) || Number(order) < 0) next.order = t('steps.form_order_invalid');
|
||||
setErrors(next);
|
||||
return Object.keys(next).length === 0;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await steps.create(id!, {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
execCode: execCode.trim() || undefined,
|
||||
validateCode: validateCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : undefined,
|
||||
});
|
||||
toast.success(t('steps.created'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -62,7 +53,11 @@ export function CreateStepPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
@@ -72,60 +67,37 @@ export function CreateStepPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('steps.form_order')}
|
||||
type="number"
|
||||
min={0}
|
||||
value={order}
|
||||
onChange={(e) => setOrder(e.target.value)}
|
||||
error={errors.order}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_title')}
|
||||
placeholder={t('steps.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
label={t('steps.form_type')}
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as StepType)}
|
||||
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
rows={6}
|
||||
value={execCode}
|
||||
onChange={(e) => setExecCode(e.target.value)}
|
||||
placeholder={t('steps.form_exec_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
rows={6}
|
||||
value={validateCode}
|
||||
onChange={(e) => setValidateCode(e.target.value)}
|
||||
placeholder={t('steps.form_validate_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate(`/scenarios/${id}`)}>
|
||||
<X size={14} />
|
||||
{t('steps.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('steps.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,22 +1,31 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, environments } from '../../api';
|
||||
import type { Scenario, Environment } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, Select, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditScenarioPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
usePageTitle(
|
||||
scenario ? `${t('scenarios.edit_title')} — ${scenario.name}` : t('scenarios.edit_title'),
|
||||
);
|
||||
const [description, setDescription] = useState('');
|
||||
const [environmentId, setEnvironmentId] = useState<string>('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -25,24 +34,36 @@ export function EditScenarioPage() {
|
||||
.then((data) => {
|
||||
setScenario(data);
|
||||
setName(data.name);
|
||||
setDescription(data.description || '');
|
||||
setEnvironmentId(data.environmentId ?? '');
|
||||
setTimeoutSeconds(data.timeoutSeconds != null ? String(data.timeoutSeconds) : '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => setEnvs(r?.data ?? []))
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!name.trim()) {
|
||||
setNameError(t('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await scenarios.update(id!, { name: name.trim() });
|
||||
await scenarios.update(id!, {
|
||||
name: name.trim(),
|
||||
description: description.trim() || undefined,
|
||||
environmentId: environmentId || null,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('scenarios.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -53,7 +74,11 @@ export function EditScenarioPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
@@ -63,7 +88,6 @@ export function EditScenarioPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
|
||||
|
||||
{!loading && scenario && (
|
||||
@@ -82,6 +106,33 @@ export function EditScenarioPage() {
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('scenarios.form_description')}</label>
|
||||
<CodeEditor
|
||||
language="markdown"
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
<Select
|
||||
label={t('scenarios.form_environment')}
|
||||
value={environmentId}
|
||||
onChange={(e) => setEnvironmentId(e.target.value)}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.form_environment_none') },
|
||||
...envs.map((env) => ({ value: env.id, label: env.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.form_timeout')}
|
||||
placeholder={t('scenarios.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('scenarios.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
@@ -90,9 +141,11 @@ export function EditScenarioPage() {
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/scenarios/${id}`)}
|
||||
>
|
||||
<X size={14} />
|
||||
{t('scenarios.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('scenarios.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep, StepType } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Select } from '../../ui';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const STEP_TYPES: StepType[] = ['login', 'exec', 'sign'];
|
||||
|
||||
export function EditStepPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id, stepId } = useParams<{ id: string; stepId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [step, setStep] = useState<ScenarioStep | null>(null);
|
||||
const [order, setOrder] = useState('');
|
||||
usePageTitle(
|
||||
step ? t('steps.edit_title', { order: step.order }) : t('steps.edit_title', { order: '' }),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [validateCode, setValidateCode] = useState('');
|
||||
const [orderError, setOrderError] = useState('');
|
||||
const [timeoutSeconds, setTimeoutSeconds] = useState<string>('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !stepId) return;
|
||||
@@ -31,41 +31,27 @@ export function EditStepPage() {
|
||||
.then(([sc, st]) => {
|
||||
setScenario(sc);
|
||||
setStep(st);
|
||||
setOrder(String(st.order));
|
||||
setTitle(st.title ?? '');
|
||||
setType(st.type);
|
||||
setExecCode(st.execCode ?? '');
|
||||
setValidateCode(st.validateCode ?? '');
|
||||
setTimeoutSeconds(st.timeoutSeconds != null ? String(st.timeoutSeconds) : '');
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id, stepId]);
|
||||
|
||||
const validate = (): boolean => {
|
||||
let valid = true;
|
||||
if (isNaN(Number(order)) || Number(order) < 0) {
|
||||
setOrderError(t('steps.form_order_invalid'));
|
||||
valid = false;
|
||||
}
|
||||
return valid;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!validate()) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await steps.update(id!, stepId!, {
|
||||
order: Number(order),
|
||||
title: title.trim() || undefined,
|
||||
type,
|
||||
execCode: execCode.trim() || undefined,
|
||||
validateCode: validateCode.trim() || undefined,
|
||||
timeoutSeconds: timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
|
||||
});
|
||||
toast.success(t('steps.updated'));
|
||||
navigate(`/scenarios/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -76,68 +62,45 @@ export function EditStepPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{
|
||||
label: scenario?.name ?? `#${id}`,
|
||||
onClick: () => navigate(`/scenarios/${id}`),
|
||||
},
|
||||
{ label: t('steps.edit_title', { order: step?.order ?? stepId }) },
|
||||
{ label: t('steps.edit_title', { order: step ? step.order : stepId }) },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('steps.loading')}</p>}
|
||||
|
||||
{!loading && step && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('steps.form_order')}
|
||||
type="number"
|
||||
min={0}
|
||||
value={order}
|
||||
onChange={(e) => {
|
||||
setOrder(e.target.value);
|
||||
setOrderError('');
|
||||
}}
|
||||
error={orderError || undefined}
|
||||
/>
|
||||
<Input
|
||||
label={t('steps.form_title')}
|
||||
placeholder={t('steps.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
label={t('steps.form_type')}
|
||||
value={type}
|
||||
onChange={(e) => setType(e.target.value as StepType)}
|
||||
options={STEP_TYPES.map((v) => ({ value: v, label: v }))}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
rows={6}
|
||||
value={execCode}
|
||||
onChange={(e) => setExecCode(e.target.value)}
|
||||
placeholder={t('steps.form_exec_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_validate_code')}</label>
|
||||
<textarea
|
||||
className={styles.textarea}
|
||||
rows={6}
|
||||
value={validateCode}
|
||||
onChange={(e) => setValidateCode(e.target.value)}
|
||||
placeholder={t('steps.form_validate_code_placeholder')}
|
||||
spellCheck={false}
|
||||
/>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
label={t('steps.form_timeout')}
|
||||
placeholder={t('steps.form_timeout_placeholder')}
|
||||
type="number"
|
||||
min={1}
|
||||
value={timeoutSeconds}
|
||||
onChange={(e) => setTimeoutSeconds(e.target.value)}
|
||||
hint={t('steps.form_timeout_hint')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.formActions}>
|
||||
@@ -146,9 +109,11 @@ export function EditStepPage() {
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/scenarios/${id}`)}
|
||||
>
|
||||
<X size={14} />
|
||||
{t('steps.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" loading={saving}>
|
||||
<Save size={14} />
|
||||
{t('steps.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,39 +1,65 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, useCallback, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play, Pencil, Plus, History, Trash2, Download } from 'lucide-react';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { scenarios, steps, scenarioCredentials, credentials as credentialsApi } from '../../api';
|
||||
import type { Scenario, ScenarioStep, ScenarioCredential, Credential } from '../../api';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import {
|
||||
Play,
|
||||
Pencil,
|
||||
Plus,
|
||||
History,
|
||||
Download,
|
||||
Trash2,
|
||||
Upload,
|
||||
GripVertical,
|
||||
ClipboardList,
|
||||
FileArchive,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
environments,
|
||||
scenarios,
|
||||
steps,
|
||||
scenarioCredentials,
|
||||
scenarioFiles,
|
||||
credentials as credentialsApi,
|
||||
} from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioStep,
|
||||
ScenarioCredential,
|
||||
Credential,
|
||||
Environment,
|
||||
FileMetadata,
|
||||
ScenarioVersion,
|
||||
TraceMode,
|
||||
UsedSnippet,
|
||||
} from '../../api';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Input,
|
||||
Notification,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
MarkdownContent,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import { ExportScenarioModal, RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const STEP_TYPE_VARIANT: Record<string, 'info' | 'warning' | 'success'> = {
|
||||
login: 'success',
|
||||
exec: 'info',
|
||||
sign: 'warning',
|
||||
};
|
||||
|
||||
export function ScenarioDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const [scenario, setScenario] = useState<(Scenario & { steps: ScenarioStep[] }) | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(scenario?.name ?? null);
|
||||
|
||||
// Credentials state
|
||||
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
|
||||
@@ -44,27 +70,138 @@ export function ScenarioDetailPage() {
|
||||
const [addCredError, setAddCredError] = useState('');
|
||||
const [addAliasError, setAddAliasError] = useState('');
|
||||
const [addCredSaving, setAddCredSaving] = useState(false);
|
||||
const [draggedStepId, setDraggedStepId] = useState<string | null>(null);
|
||||
const [dragOverStepId, setDragOverStepId] = useState<string | null>(null);
|
||||
const [reorderingSteps, setReorderingSteps] = useState(false);
|
||||
const [runModalOpen, setRunModalOpen] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
const [pendingDelete, setPendingDelete] = useState<
|
||||
{ type: 'scenario' } | { type: 'step'; id: string } | { type: 'credential'; id: string } | null
|
||||
>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
// Export modal state
|
||||
const [exportModalOpen, setExportModalOpen] = useState(false);
|
||||
const [includeEnvironment, setIncludeEnvironment] = useState(true);
|
||||
const [includedCredentialIds, setIncludedCredentialIds] = useState<Set<string>>(new Set());
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
// Files state
|
||||
const [files, setFiles] = useState<FileMetadata[]>([]);
|
||||
const [filesLoading, setFilesLoading] = useState(true);
|
||||
const [uploadOpen, setUploadOpen] = useState(false);
|
||||
const [uploadFile, setUploadFile] = useState<File | null>(null);
|
||||
const [uploadExpiresAt, setUploadExpiresAt] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const [usedSnippets, setUsedSnippets] = useState<UsedSnippet[]>([]);
|
||||
|
||||
// Fetches the files; `filesLoading` starts as true for the fetch from the
|
||||
// load effect, and `loadFiles` sets it for reloads (e.g. after an upload)
|
||||
const fetchFiles = useCallback(async () => {
|
||||
if (!id) return;
|
||||
try {
|
||||
const result = await scenarioFiles.list(id);
|
||||
setFiles(result.items);
|
||||
} finally {
|
||||
setFilesLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
const loadFiles = async () => {
|
||||
setFilesLoading(true);
|
||||
await fetchFiles();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
scenarios
|
||||
void scenarios
|
||||
.get(id)
|
||||
.then((s) => {
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
void fetchFiles();
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
credentialsApi
|
||||
.list(1, 200)
|
||||
.then((r) => setAllCredentials(r.data))
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => {
|
||||
setEnvs(r.data);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [id, fetchFiles]);
|
||||
|
||||
const openRunModal = () => {
|
||||
// Preselect the scenario's default environment (or the first one) when the
|
||||
// modal opens: by then both are loaded, and it follows default env edits
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : (envs[0]?.id ?? ''));
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
if (id) {
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
}
|
||||
setRunModalOpen(true);
|
||||
};
|
||||
|
||||
const reloadScenario = async () => {
|
||||
if (!id) return;
|
||||
const s = await scenarios.get(id);
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
scenarios
|
||||
.usedSnippets(id)
|
||||
.then(setUsedSnippets)
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!scenario) return;
|
||||
const run = await scenarios.run(scenario.id);
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
if (!selectedEnvId) {
|
||||
toast.error(t('scenarios.run_modal_env_required'));
|
||||
return;
|
||||
}
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(
|
||||
scenario.id,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
setRunModalOpen(false);
|
||||
setSaveSessionFlag(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
@@ -73,30 +210,100 @@ export function ScenarioDetailPage() {
|
||||
navigate('/scenarios');
|
||||
};
|
||||
|
||||
const handleOpenExportModal = () => {
|
||||
if (!scenario) return;
|
||||
// Initialise all credential checkboxes to checked
|
||||
setIncludedCredentialIds(new Set(scenarioCreds.map((sc) => sc.credentialId)));
|
||||
setIncludeEnvironment(true);
|
||||
setExportModalOpen(true);
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!scenario) return;
|
||||
const data = await scenarios.exportScenario(scenario.id);
|
||||
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const credIds = Array.from(includedCredentialIds);
|
||||
const yamlContent = await scenarios.exportScenario(scenario.id, {
|
||||
includeEnvironment,
|
||||
credentialIds: credIds,
|
||||
});
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportModalOpen(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileDownload = (url: string, filename: string) => {
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
};
|
||||
|
||||
const isFileExpired = (file: FileMetadata) =>
|
||||
file.expiresAt != null && new Date(file.expiresAt).getTime() <= Date.now();
|
||||
|
||||
async function handleUpload(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
if (!id || !uploadFile) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
await scenarioFiles.upload(
|
||||
id,
|
||||
uploadFile,
|
||||
uploadExpiresAt ? new Date(uploadExpiresAt) : undefined,
|
||||
);
|
||||
setUploadOpen(false);
|
||||
setUploadFile(null);
|
||||
setUploadExpiresAt('');
|
||||
await loadFiles();
|
||||
toast.success(t('files.uploadSuccess'));
|
||||
} catch {
|
||||
// error toast already emitted by API client
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteStep = async (stepId: string) => {
|
||||
await steps.remove(id!, stepId);
|
||||
setScenario((prev) =>
|
||||
prev ? { ...prev, steps: prev.steps.filter((s) => s.id !== stepId) } : prev,
|
||||
);
|
||||
await reloadScenario();
|
||||
};
|
||||
|
||||
const handleAddCredential = async (e: React.FormEvent) => {
|
||||
const handleMoveStep = async (fromStepId: string, toStepId: string) => {
|
||||
if (!scenario || reorderingSteps) return;
|
||||
setReorderingSteps(true);
|
||||
try {
|
||||
const orderedSteps = [...scenario.steps].sort((a, b) => a.order - b.order);
|
||||
const toIndex = orderedSteps.findIndex((step) => step.id === toStepId);
|
||||
if (toIndex < 0) return;
|
||||
await steps.update(id!, fromStepId, { order: toIndex });
|
||||
await reloadScenario();
|
||||
} finally {
|
||||
setReorderingSteps(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddCredential = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!addCredId) { setAddCredError(t('scenarios.cred_form_cred_required')); valid = false; }
|
||||
if (!addAlias.trim()) { setAddAliasError(t('scenarios.cred_form_alias_required')); valid = false; }
|
||||
if (!addCredId) {
|
||||
setAddCredError(t('scenarios.cred_form_cred_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!addAlias.trim()) {
|
||||
setAddAliasError(t('scenarios.cred_form_alias_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!valid) return;
|
||||
setAddCredSaving(true);
|
||||
try {
|
||||
@@ -120,18 +327,73 @@ export function ScenarioDetailPage() {
|
||||
setScenarioCreds((prev) => prev.filter((sc) => sc.id !== scCredId));
|
||||
};
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!pendingDelete) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
if (pendingDelete.type === 'scenario') {
|
||||
await handleDelete();
|
||||
return;
|
||||
}
|
||||
if (pendingDelete.type === 'step') {
|
||||
await handleDeleteStep(pendingDelete.id);
|
||||
}
|
||||
if (pendingDelete.type === 'credential') {
|
||||
await handleRemoveCredential(pendingDelete.id);
|
||||
}
|
||||
setPendingDelete(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const stepColumns: TableColumn<ScenarioStep>[] = [
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
key: 'type',
|
||||
header: t('scenarios.step_type'),
|
||||
width: 90,
|
||||
render: (s) => <Badge variant={STEP_TYPE_VARIANT[s.type] ?? 'neutral'}>{s.type}</Badge>,
|
||||
key: 'drag',
|
||||
header: '',
|
||||
width: 44,
|
||||
align: 'center',
|
||||
render: (s) => (
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label="Drag to reorder step"
|
||||
className={[styles.dragHandle, reorderingSteps ? styles.dragHandleDisabled : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
draggable={!reorderingSteps}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onDragStart={(e) => {
|
||||
if (reorderingSteps) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
setDraggedStepId(s.id);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
e.dataTransfer.setData('text/plain', s.id);
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
setDraggedStepId(null);
|
||||
setDragOverStepId(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<GripVertical size={14} />
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ key: 'order', header: t('scenarios.step_order'), render: (s) => s.order, width: 60 },
|
||||
{
|
||||
key: 'title',
|
||||
header: t('scenarios.step_title'),
|
||||
render: (s) => s.title ?? <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>,
|
||||
render: (s) =>
|
||||
s.title ?? (
|
||||
<span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>{'—'}</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'updated',
|
||||
@@ -163,7 +425,7 @@ export function ScenarioDetailPage() {
|
||||
title={t('steps.action_delete')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDeleteStep(s.id);
|
||||
setPendingDelete({ type: 'step', id: s.id });
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
@@ -198,7 +460,7 @@ export function ScenarioDetailPage() {
|
||||
title={t('scenarios.cred_action_remove')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleRemoveCredential(sc.id);
|
||||
setPendingDelete({ type: 'credential', id: sc.id });
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
@@ -212,13 +474,17 @@ export function ScenarioDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('scenarios.title'), onClick: () => navigate('/scenarios') },
|
||||
{
|
||||
label: t('scenarios.title'),
|
||||
icon: <ClipboardList size={14} />,
|
||||
onClick: () => navigate('/scenarios'),
|
||||
},
|
||||
{ label: scenario?.name ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{scenario && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button size="sm" onClick={handleRun}>
|
||||
<Button size="sm" onClick={openRunModal}>
|
||||
<Play size={14} />
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
@@ -226,15 +492,29 @@ export function ScenarioDetailPage() {
|
||||
<History size={14} />
|
||||
{t('scenarios.action_runs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Download size={14} />
|
||||
<Button variant="secondary" size="sm" onClick={handleOpenExportModal}>
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
|
||||
}
|
||||
>
|
||||
<FileArchive size={14} />
|
||||
{t('scenarios.action_export_e2e')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={() => navigate(`/scenarios/${id}/edit`)}>
|
||||
<Pencil size={14} />
|
||||
{t('scenarios.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => setPendingDelete({ type: 'scenario' })}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
{t('scenarios.action_delete')}
|
||||
</Button>
|
||||
@@ -242,25 +522,35 @@ export function ScenarioDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_scenario', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
|
||||
|
||||
{scenario && (
|
||||
<>
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('scenarios.field_id'), detail: <UuidBadge id={scenario.id} /> },
|
||||
{ term: t('scenarios.field_name'), detail: scenario.name },
|
||||
{ term: t('scenarios.field_steps'), detail: scenario.steps.length },
|
||||
{ term: t('scenarios.field_version'), detail: `v${scenario.version}` },
|
||||
...(scenario.environment
|
||||
? [
|
||||
{
|
||||
term: t('scenarios.field_environment'),
|
||||
detail: (
|
||||
<a
|
||||
href={`/environments/${scenario.environment.id}`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
navigate(`/environments/${scenario.environment!.id}`);
|
||||
}}
|
||||
>
|
||||
{scenario.environment.name}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
term: t('scenarios.field_created'),
|
||||
detail: <Timestamp value={scenario.createdAt} />,
|
||||
@@ -273,6 +563,17 @@ export function ScenarioDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{scenario.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={scenario.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{scenario.steps.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
@@ -288,6 +589,30 @@ export function ScenarioDetailPage() {
|
||||
rowKey={(s) => s.id}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
getRowProps={(s) => ({
|
||||
className: dragOverStepId === s.id ? styles.dragOverRow : undefined,
|
||||
onDragOver: (e) => {
|
||||
if (reorderingSteps) return;
|
||||
e.preventDefault();
|
||||
if (draggedStepId && draggedStepId !== s.id) {
|
||||
setDragOverStepId(s.id);
|
||||
}
|
||||
},
|
||||
onDragLeave: () => {
|
||||
if (dragOverStepId === s.id) {
|
||||
setDragOverStepId(null);
|
||||
}
|
||||
},
|
||||
onDrop: async (e) => {
|
||||
if (reorderingSteps) return;
|
||||
e.preventDefault();
|
||||
const fromId = draggedStepId ?? e.dataTransfer.getData('text/plain');
|
||||
setDragOverStepId(null);
|
||||
setDraggedStepId(null);
|
||||
if (!fromId || fromId === s.id) return;
|
||||
await handleMoveStep(fromId, s.id);
|
||||
},
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -315,42 +640,52 @@ export function ScenarioDetailPage() {
|
||||
|
||||
{addCredOpen && (
|
||||
<div style={{ marginBottom: 'var(--space-4)' }}>
|
||||
<Card className={styles.formCard}>
|
||||
<form onSubmit={handleAddCredential} noValidate>
|
||||
<div className={styles.formFields}>
|
||||
<Select
|
||||
label={t('scenarios.cred_form_cred')}
|
||||
value={addCredId}
|
||||
onChange={(e) => { setAddCredId(e.target.value); setAddCredError(''); }}
|
||||
error={addCredError || undefined}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
|
||||
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.cred_form_alias')}
|
||||
placeholder={t('scenarios.cred_form_alias_placeholder')}
|
||||
value={addAlias}
|
||||
onChange={(e) => { setAddAlias(e.target.value); setAddAliasError(''); }}
|
||||
error={addAliasError || undefined}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => { setAddCredOpen(false); setAddCredId(''); setAddAlias(''); }}
|
||||
>
|
||||
{t('scenarios.cred_action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" loading={addCredSaving}>
|
||||
{t('scenarios.cred_action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
<Card className={styles.formCard}>
|
||||
<form onSubmit={handleAddCredential} noValidate>
|
||||
<div className={styles.formFields}>
|
||||
<Select
|
||||
label={t('scenarios.cred_form_cred')}
|
||||
value={addCredId}
|
||||
onChange={(e) => {
|
||||
setAddCredId(e.target.value);
|
||||
setAddCredError('');
|
||||
}}
|
||||
error={addCredError || undefined}
|
||||
options={[
|
||||
{ value: '', label: t('scenarios.cred_form_cred_placeholder') },
|
||||
...allCredentials.map((c) => ({ value: String(c.id), label: c.name })),
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
label={t('scenarios.cred_form_alias')}
|
||||
placeholder={t('scenarios.cred_form_alias_placeholder')}
|
||||
value={addAlias}
|
||||
onChange={(e) => {
|
||||
setAddAlias(e.target.value);
|
||||
setAddAliasError('');
|
||||
}}
|
||||
error={addAliasError || undefined}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setAddCredOpen(false);
|
||||
setAddCredId('');
|
||||
setAddAlias('');
|
||||
}}
|
||||
>
|
||||
{t('scenarios.cred_action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" loading={addCredSaving}>
|
||||
{t('scenarios.cred_action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -366,8 +701,208 @@ export function ScenarioDetailPage() {
|
||||
<p className={styles.muted}>{t('scenarios.cred_empty')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Used snippets section ───────────────────────────────────────── */}
|
||||
{usedSnippets.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('scenarios.used_snippets_heading')}</h2>
|
||||
</div>
|
||||
<Table<UsedSnippet>
|
||||
data={usedSnippets}
|
||||
rowKey={(s) => `${s.id}@${s.pinnedVersion ?? 'latest'}`}
|
||||
loading={false}
|
||||
emptyMessage=""
|
||||
onRowClick={(s) => navigate(`/snippets/${s.id}`)}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'alias',
|
||||
header: t('snippets.field_alias'),
|
||||
render: (s) => s.alias,
|
||||
},
|
||||
{
|
||||
key: 'title',
|
||||
header: t('snippets.field_title'),
|
||||
render: (s) => s.title,
|
||||
},
|
||||
{
|
||||
key: 'version',
|
||||
header: t('snippets.field_version'),
|
||||
render: (s) =>
|
||||
s.pinnedVersion != null
|
||||
? t('scenarios.used_snippet_pinned', { version: s.pinnedVersion })
|
||||
: t('scenarios.used_snippet_latest', { version: s.version }),
|
||||
},
|
||||
] satisfies TableColumn<UsedSnippet>[]
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Files section ───────────────────────────────────────────────── */}
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionToolbar}>
|
||||
<h2 className={styles.sectionHeading}>{t('files.title')}</h2>
|
||||
<Button size="sm" onClick={() => setUploadOpen(true)}>
|
||||
<Upload size={14} /> {t('files.upload')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table<FileMetadata>
|
||||
loading={filesLoading}
|
||||
data={files}
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{
|
||||
key: 'name',
|
||||
header: t('files.name'),
|
||||
render: (f) => f.name,
|
||||
},
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
render: (f) => f.mimeType,
|
||||
},
|
||||
{
|
||||
key: 'size',
|
||||
header: t('files.size'),
|
||||
render: (f) => `${(f.size / 1024).toFixed(1)} KB`,
|
||||
},
|
||||
{
|
||||
key: 'expiresAt',
|
||||
header: t('files.expiresAt'),
|
||||
render: (f) => (f.expiresAt ? <Timestamp value={f.expiresAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
key: 'createdAt',
|
||||
header: t('files.createdAt'),
|
||||
render: (f) => <Timestamp value={f.createdAt} />,
|
||||
},
|
||||
{
|
||||
key: 'download',
|
||||
header: '',
|
||||
render: (f) => {
|
||||
const expired = isFileExpired(f);
|
||||
const tooltip = expired ? t('files.expiredTooltip') : t('files.download');
|
||||
|
||||
return (
|
||||
<span title={tooltip}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
title={tooltip}
|
||||
aria-label={tooltip}
|
||||
disabled={expired}
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarioFiles.contentUrl(id!, f.id), f.name)
|
||||
}
|
||||
>
|
||||
<Download size={14} />
|
||||
</Button>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
] satisfies TableColumn<FileMetadata>[]
|
||||
}
|
||||
emptyMessage={t('files.empty')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Upload modal ─────────────────────────────────────────────── */}
|
||||
<Modal
|
||||
open={uploadOpen}
|
||||
title={t('files.uploadTitle')}
|
||||
onClose={() => setUploadOpen(false)}
|
||||
>
|
||||
<form onSubmit={handleUpload}>
|
||||
<input
|
||||
type="file"
|
||||
required
|
||||
onChange={(e) => setUploadFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
<Input
|
||||
label={t('files.expiresAtLabel')}
|
||||
type="datetime-local"
|
||||
value={uploadExpiresAt}
|
||||
onChange={(e) => setUploadExpiresAt(e.target.value)}
|
||||
/>
|
||||
<Button type="submit" loading={uploading} disabled={!uploadFile}>
|
||||
{t('files.upload')}
|
||||
</Button>
|
||||
</form>
|
||||
</Modal>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={pendingDelete != null}
|
||||
title={
|
||||
pendingDelete?.type === 'step'
|
||||
? t('steps.action_delete')
|
||||
: pendingDelete?.type === 'credential'
|
||||
? t('scenarios.cred_action_remove')
|
||||
: t('scenarios.action_delete')
|
||||
}
|
||||
onClose={() => !deleting && setPendingDelete(null)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setPendingDelete(null)} disabled={deleting}>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={confirmDelete} disabled={deleting}>
|
||||
{t('common.button_confirm')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{pendingDelete?.type === 'step' && t('common.confirm_delete_step')}
|
||||
{pendingDelete?.type === 'credential' && t('common.confirm_remove_credential')}
|
||||
{pendingDelete?.type === 'scenario' && t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<RunScenarioModal
|
||||
open={runModalOpen}
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunModalOpen(false)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
|
||||
<ExportScenarioModal
|
||||
open={exportModalOpen}
|
||||
scenario={scenario}
|
||||
scenarioCredentials={scenarioCreds}
|
||||
environment={
|
||||
scenario?.environment ?? envs.find((e) => e.id === scenario?.environmentId) ?? null
|
||||
}
|
||||
includeEnvironment={includeEnvironment}
|
||||
onIncludeEnvironmentChange={setIncludeEnvironment}
|
||||
includedCredentialIds={includedCredentialIds}
|
||||
onCredentialToggle={(credId, checked) => {
|
||||
setIncludedCredentialIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (checked) next.add(credId);
|
||||
else next.delete(credId);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
onClose={() => setExportModalOpen(false)}
|
||||
onExport={handleExport}
|
||||
isExporting={isExporting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +1,204 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play, Plus, Trash2, Upload } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Play, Plus, Trash2, Download, ClipboardList } from 'lucide-react';
|
||||
import { environments, scenarios } from '../../api';
|
||||
import type { Environment, Scenario, ScenarioVersion, TraceMode } from '../../api';
|
||||
import { RunScenarioModal } from '../../components/modals';
|
||||
import { useRunDefaults } from '../../hooks/useRunDefaults';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import type { ScenarioRunStatus } from '../../api';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const LAST_RUN_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
pending: 'neutral',
|
||||
in_progress: 'info',
|
||||
pass: 'success',
|
||||
fail: 'error',
|
||||
};
|
||||
|
||||
const LAST_RUN_LABEL: Record<ScenarioRunStatus, string> = {
|
||||
pending: 'Pending',
|
||||
in_progress: 'Running',
|
||||
pass: 'Pass',
|
||||
fail: 'Fail',
|
||||
};
|
||||
|
||||
export function ScenariosPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('scenarios.title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const [items, setItems] = useState<Scenario[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [runScenarioId, setRunScenarioId] = useState<string | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [saveSessionFlag, setSaveSessionFlag] = useState(false);
|
||||
// null = use the server's configured default
|
||||
const [traceModeOverride, setTraceModeOverride] = useState<TraceMode | null>(null);
|
||||
const runDefaults = useRunDefaults();
|
||||
const [runVersions, setRunVersions] = useState<ScenarioVersion[]>([]);
|
||||
// null = latest
|
||||
const [runVersion, setRunVersion] = useState<number | null>(null);
|
||||
const traceMode = traceModeOverride ?? runDefaults?.traceMode ?? 'off';
|
||||
const [envs, setEnvs] = useState<Environment[]>([]);
|
||||
const [selectedEnvId, setSelectedEnvId] = useState('');
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(() => {
|
||||
scenarios
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
const [sortBy, setSortBy] = useState('updatedAt');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
// Fetches a page; `loading` starts as true for the initial fetch from the
|
||||
// effect, and `load` sets it for later ones (no setState inside the effect)
|
||||
const fetchPage = useCallback(
|
||||
(orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
Promise.all([
|
||||
scenarios.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC'),
|
||||
environments.list(1, 200),
|
||||
])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setTotal(scenarioRes?.total ?? 0);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error((err as Error).message);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
},
|
||||
[toast],
|
||||
);
|
||||
|
||||
const load = (orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
setLoading(true);
|
||||
fetchPage(orderBy, orderDir, p, limit);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
fetchPage('updatedAt', 'desc', 1, 10);
|
||||
}, [fetchPage]);
|
||||
|
||||
const handleRun = async (id: string) => {
|
||||
const run = await scenarios.run(id);
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
const handleSort = (key: string, dir: SortDirection) => {
|
||||
setSortBy(key);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
load(key, dir, 1, pageSize);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await scenarios.remove(id);
|
||||
setLoading(true);
|
||||
load();
|
||||
const handlePageChange = (p: number) => {
|
||||
setPage(p);
|
||||
load(sortBy, sortDir, p, pageSize);
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
load(sortBy, sortDir, 1, size);
|
||||
};
|
||||
|
||||
const openRunModal = (id: string) => {
|
||||
setRunScenarioId(id);
|
||||
setTraceModeOverride(null);
|
||||
setRunVersion(null);
|
||||
setRunVersions([]);
|
||||
scenarios
|
||||
.versions(id)
|
||||
.then(setRunVersions)
|
||||
.catch(() => undefined);
|
||||
const scenario = items.find((s) => s.id === id);
|
||||
const preferred = scenario?.environmentId ?? null;
|
||||
const exists = preferred ? envs.some((e) => e.id === preferred) : false;
|
||||
setSelectedEnvId(exists ? preferred! : envs[0]?.id || '');
|
||||
};
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!runScenarioId || !selectedEnvId) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await scenarios.importScenario(payload);
|
||||
navigate(`/scenarios/${imported.id}`);
|
||||
const run = await scenarios.run(
|
||||
runScenarioId,
|
||||
selectedEnvId,
|
||||
saveSessionFlag,
|
||||
traceModeOverride ?? undefined,
|
||||
runVersion ?? undefined,
|
||||
);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
|
||||
setRunScenarioId(null);
|
||||
setSaveSessionFlag(false);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await scenarios.remove(deleteId);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = useImportFile('scenario');
|
||||
|
||||
const columns: TableColumn<Scenario>[] = [
|
||||
{ key: 'id', header: t('scenarios.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name },
|
||||
{ key: 'name', header: t('scenarios.col_name'), render: (s) => s.name, sortable: true },
|
||||
{
|
||||
key: 'updated',
|
||||
key: 'version',
|
||||
header: t('scenarios.col_version'),
|
||||
width: 80,
|
||||
render: (s) => `v${s.version}`,
|
||||
},
|
||||
{
|
||||
key: 'lastRunStatus',
|
||||
header: t('scenarios.col_last_run'),
|
||||
width: 160,
|
||||
render: (s) =>
|
||||
s.lastRunStatus ? (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ display: 'inline-flex', minWidth: 62 }}>
|
||||
<Badge variant={LAST_RUN_VARIANT[s.lastRunStatus]}>
|
||||
{LAST_RUN_LABEL[s.lastRunStatus]}
|
||||
</Badge>
|
||||
</span>
|
||||
{s.lastRunAt && <Timestamp value={s.lastRunAt} />}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ color: 'var(--color-text-muted)', fontSize: '0.8em' }}>—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'updatedAt',
|
||||
header: t('scenarios.col_updated'),
|
||||
width: 140,
|
||||
sortable: true,
|
||||
render: (s) => <Timestamp value={s.updatedAt} />,
|
||||
},
|
||||
{
|
||||
@@ -70,14 +208,24 @@ export function ScenariosPage() {
|
||||
align: 'right',
|
||||
render: (s) => (
|
||||
<span style={{ display: 'inline-flex', gap: 6 }}>
|
||||
<Button size="sm" title={t('scenarios.action_run')} onClick={() => handleRun(s.id)}>
|
||||
<Button
|
||||
size="sm"
|
||||
title={t('scenarios.action_run')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openRunModal(s.id);
|
||||
}}
|
||||
>
|
||||
<Play size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
title={t('scenarios.action_delete')}
|
||||
onClick={() => handleDelete(s.id)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeleteId(s.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
@@ -89,7 +237,7 @@ export function ScenariosPage() {
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('scenarios.title') }]} className={styles.breadcrumbs} />
|
||||
<Breadcrumbs items={[{ label: t('scenarios.title'), icon: <ClipboardList size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
@@ -99,7 +247,7 @@ export function ScenariosPage() {
|
||||
onChange={handleImport}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload size={14} />
|
||||
<Download size={14} />
|
||||
{t('scenarios.action_import')}
|
||||
</Button>
|
||||
<Button size="sm" onClick={() => navigate('/scenarios/new')}>
|
||||
@@ -108,16 +256,58 @@ export function ScenariosPage() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('scenarios.empty')}
|
||||
pageSize={10}
|
||||
pageSize={pageSize}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={handlePageChange}
|
||||
onPageSizeChange={handlePageSizeChange}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
open={deleteId != null}
|
||||
title={t('scenarios.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('scenarios.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{t('common.confirm_delete_scenario')}
|
||||
</Modal>
|
||||
|
||||
<RunScenarioModal
|
||||
open={runScenarioId != null}
|
||||
environments={envs}
|
||||
selectedEnvId={selectedEnvId}
|
||||
onEnvSelect={setSelectedEnvId}
|
||||
saveSessionFlag={saveSessionFlag}
|
||||
onSaveSessionChange={setSaveSessionFlag}
|
||||
versions={runVersions}
|
||||
selectedVersion={runVersion}
|
||||
onVersionChange={setRunVersion}
|
||||
traceMode={traceMode}
|
||||
defaultTraceMode={runDefaults?.traceMode ?? null}
|
||||
onTraceModeChange={setTraceModeOverride}
|
||||
onClose={() => setRunScenarioId(null)}
|
||||
onRun={handleRun}
|
||||
isRunning={running}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
|
||||
import { Badge, Breadcrumbs, Button, Card, DescriptionList, Timestamp, UuidBadge } from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SessionDetailPage() {
|
||||
@@ -13,21 +15,28 @@ export function SessionDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [session, setSession] = useState<Session | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(session?.sessionName ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
sessions
|
||||
.get(id)
|
||||
.then(setSession)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!session) return;
|
||||
await sessions.remove(session.id);
|
||||
navigate('/sessions');
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(session.id);
|
||||
navigate('/sessions');
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setConfirmDeleteOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -35,32 +44,28 @@ export function SessionDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('sessions.title'), onClick: () => navigate('/sessions') },
|
||||
{
|
||||
label: t('sessions.title'),
|
||||
icon: <Monitor size={14} />,
|
||||
onClick: () => navigate('/sessions'),
|
||||
},
|
||||
{ label: session?.sessionName ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{session && (
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
|
||||
<Trash2 size={14} />
|
||||
{t('sessions.action_delete')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_session', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
{loading && <p className={styles.muted}>{t('sessions.loading')}</p>}
|
||||
|
||||
{session && (
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('sessions.field_id'), detail: <UuidBadge id={session.id} /> },
|
||||
{ term: t('sessions.field_name'), detail: session.sessionName },
|
||||
@@ -92,6 +97,15 @@ export function SessionDetailPage() {
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('sessions.action_delete')}
|
||||
message={t('common.confirm_delete_session')}
|
||||
onClose={() => setConfirmDeleteOpen(false)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +1,95 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Trash2, Monitor } from 'lucide-react';
|
||||
import { sessions } from '../../api';
|
||||
import type { Session } from '../../api';
|
||||
import { Badge, Breadcrumbs, Button, Table, type TableColumn, Timestamp, UuidBadge } from '../../ui';
|
||||
import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Table,
|
||||
type TableColumn,
|
||||
type SortDirection,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SessionsPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('sessions.title'));
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Session[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// Loading until the current query's result has arrived (derived, so the
|
||||
// loading effect doesn't have to set state synchronously)
|
||||
const [loadedQuery, setLoadedQuery] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [sortBy, setSortBy] = useState('id');
|
||||
const [sortDir, setSortDir] = useState<SortDirection>('desc');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [total, setTotal] = useState(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
const query = `${sortBy}|${sortDir}|${page}|${pageSize}`;
|
||||
const loading = loadedQuery !== query;
|
||||
|
||||
const load = useCallback((orderBy: string, orderDir: SortDirection, p: number, limit: number) => {
|
||||
const key = `${orderBy}|${orderDir}|${p}|${limit}`;
|
||||
sessions
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
.list(p, limit, orderBy, orderDir === 'asc' ? 'ASC' : 'DESC')
|
||||
.then((res) => {
|
||||
setItems(res.data);
|
||||
setTotal(res.total);
|
||||
})
|
||||
.finally(() => setLoadedQuery(key));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
}, [load, sortBy, sortDir, page, pageSize]);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await sessions.remove(id);
|
||||
setLoading(true);
|
||||
load();
|
||||
const handleSort = (col: string, dir: SortDirection) => {
|
||||
setSortBy(col);
|
||||
setSortDir(dir);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(deleteId);
|
||||
load(sortBy, sortDir, page, pageSize);
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: TableColumn<Session>[] = [
|
||||
{ key: 'id', header: t('sessions.col_id'), render: (s) => <UuidBadge id={s.id} />, width: 60 },
|
||||
{ key: 'name', header: t('sessions.col_name'), render: (s) => s.sessionName },
|
||||
{
|
||||
key: 'sessionName',
|
||||
header: t('sessions.col_name'),
|
||||
sortable: true,
|
||||
render: (s) => s.sessionName,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: t('sessions.col_status'),
|
||||
width: 100,
|
||||
sortable: true,
|
||||
render: (s) => <Badge variant={s.status === 'open' ? 'success' : 'error'}>{s.status}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'lastUsed',
|
||||
key: 'lastUsedAt',
|
||||
header: t('sessions.col_lastUsed'),
|
||||
width: 160,
|
||||
sortable: true,
|
||||
render: (s) => (s.lastUsedAt ? <Timestamp value={s.lastUsedAt} /> : '—'),
|
||||
},
|
||||
{
|
||||
@@ -57,7 +102,10 @@ export function SessionsPage() {
|
||||
variant="danger"
|
||||
size="sm"
|
||||
title={t('sessions.action_delete')}
|
||||
onClick={() => handleDelete(s.id)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setDeleteId(s.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
@@ -67,18 +115,37 @@ export function SessionsPage() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumbs items={[{ label: t('sessions.title') }]} className={styles.breadcrumbs} />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('sessions.title'), icon: <Monitor size={14} /> }]} />
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
rowKey={(s) => s.id}
|
||||
loading={loading}
|
||||
emptyMessage={t('sessions.empty')}
|
||||
pageSize={10}
|
||||
sortBy={sortBy}
|
||||
sortDir={sortDir}
|
||||
onSort={handleSort}
|
||||
total={total}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
onPageSizeChange={(s) => {
|
||||
setPageSize(s);
|
||||
setPage(1);
|
||||
}}
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/sessions/${s.id}`)}
|
||||
/>
|
||||
|
||||
<DeleteConfirmationModal
|
||||
open={deleteId != null}
|
||||
title={t('sessions.action_delete')}
|
||||
message={t('common.confirm_delete_session')}
|
||||
onClose={() => setDeleteId(null)}
|
||||
onConfirm={handleDelete}
|
||||
isDeleting={deleting}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,27 +1,36 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, Textarea } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('snippets.create_title'));
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [aliasError, setAliasError] = useState('');
|
||||
const [titleError, setTitleError] = useState('');
|
||||
const [codeError, setCodeError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
setNameError(t('snippets.form_name_required'));
|
||||
if (!alias.trim()) {
|
||||
setAliasError(t('snippets.form_alias_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!title.trim()) {
|
||||
setTitleError(t('snippets.form_title_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
@@ -30,16 +39,18 @@ export function CreateSnippetPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const snippet = await snippets.create({
|
||||
name: name.trim(),
|
||||
alias: alias.trim(),
|
||||
title: title.trim(),
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
toast.success(t('snippets.created'));
|
||||
navigate(`/snippets/${snippet.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -50,59 +61,75 @@ export function CreateSnippetPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{ label: t('snippets.create_title') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('snippets.form_name')}
|
||||
placeholder={t('snippets.form_name_placeholder')}
|
||||
value={name}
|
||||
label={t('snippets.form_alias')}
|
||||
placeholder={t('snippets.form_alias_placeholder')}
|
||||
value={alias}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
setAlias(e.target.value);
|
||||
setAliasError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
error={aliasError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('snippets.form_description')}
|
||||
placeholder={t('snippets.form_description_placeholder')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
label={t('snippets.form_title')}
|
||||
placeholder={t('snippets.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => {
|
||||
setTitle(e.target.value);
|
||||
setTitleError('');
|
||||
}}
|
||||
error={titleError || undefined}
|
||||
required
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
|
||||
<CodeEditor
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
language="markdown"
|
||||
rows={10}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<textarea
|
||||
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
|
||||
rows={14}
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(e) => {
|
||||
setCode(e.target.value);
|
||||
onChange={(v) => {
|
||||
setCode(v);
|
||||
setCodeError('');
|
||||
}}
|
||||
placeholder={t('snippets.form_code_placeholder')}
|
||||
spellCheck={false}
|
||||
rows={14}
|
||||
error={!!codeError}
|
||||
/>
|
||||
{codeError && <span className={styles.fieldError}>{codeError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate('/snippets')}>
|
||||
<X size={14} />
|
||||
{t('snippets.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
<Save size={14} />
|
||||
{t('snippets.action_save')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditSnippetPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
usePageTitle(
|
||||
snippet ? `${t('snippets.edit_title')} — ${snippet.title}` : t('snippets.edit_title'),
|
||||
);
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [code, setCode] = useState('');
|
||||
const [nameError, setNameError] = useState('');
|
||||
const [aliasError, setAliasError] = useState('');
|
||||
const [titleError, setTitleError] = useState('');
|
||||
const [codeError, setCodeError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -27,19 +34,23 @@ export function EditSnippetPage() {
|
||||
.get(id)
|
||||
.then((s) => {
|
||||
setSnippet(s);
|
||||
setName(s.name);
|
||||
setAlias(s.alias);
|
||||
setTitle(s.title);
|
||||
setDescription(s.description ?? '');
|
||||
setCode(s.code);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
const handleSubmit = async (e: SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
let valid = true;
|
||||
if (!name.trim()) {
|
||||
setNameError(t('snippets.form_name_required'));
|
||||
if (!alias.trim()) {
|
||||
setAliasError(t('snippets.form_alias_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!title.trim()) {
|
||||
setTitleError(t('snippets.form_title_required'));
|
||||
valid = false;
|
||||
}
|
||||
if (!code.trim()) {
|
||||
@@ -48,16 +59,18 @@ export function EditSnippetPage() {
|
||||
}
|
||||
if (!valid) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await snippets.update(id!, {
|
||||
name: name.trim(),
|
||||
alias: alias.trim(),
|
||||
title: title.trim(),
|
||||
description: description.trim() || undefined,
|
||||
code: code.trim(),
|
||||
});
|
||||
toast.success(t('snippets.updated'));
|
||||
navigate(`/snippets/${id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
const message = (err as Error).message;
|
||||
toast.error(message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
@@ -68,9 +81,13 @@ export function EditSnippetPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{
|
||||
label: snippet?.name ?? `#${id}`,
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{
|
||||
label: snippet?.title ?? `#${id}`,
|
||||
onClick: () => navigate(`/snippets/${id}`),
|
||||
},
|
||||
{ label: t('snippets.edit_title') },
|
||||
@@ -78,59 +95,68 @@ export function EditSnippetPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{!loading && snippet && (
|
||||
<form onSubmit={handleSubmit} noValidate>
|
||||
<Card className={styles.formCard}>
|
||||
<Card className={styles.formCardFull}>
|
||||
<div className={styles.formFields}>
|
||||
<Input
|
||||
label={t('snippets.form_name')}
|
||||
placeholder={t('snippets.form_name_placeholder')}
|
||||
value={name}
|
||||
label={t('snippets.form_alias')}
|
||||
placeholder={t('snippets.form_alias_placeholder')}
|
||||
value={alias}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setNameError('');
|
||||
setAlias(e.target.value);
|
||||
setAliasError('');
|
||||
}}
|
||||
error={nameError || undefined}
|
||||
error={aliasError || undefined}
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
label={t('snippets.form_description')}
|
||||
placeholder={t('snippets.form_description_placeholder')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
label={t('snippets.form_title')}
|
||||
placeholder={t('snippets.form_title_placeholder')}
|
||||
value={title}
|
||||
onChange={(e) => {
|
||||
setTitle(e.target.value);
|
||||
setTitleError('');
|
||||
}}
|
||||
error={titleError || undefined}
|
||||
required
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('snippets.form_description')}</label>
|
||||
<CodeEditor
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
language="markdown"
|
||||
rows={10}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<textarea
|
||||
className={[styles.textarea, codeError ? styles.textareaError : ''].filter(Boolean).join(' ')}
|
||||
rows={14}
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(e) => {
|
||||
setCode(e.target.value);
|
||||
onChange={(v) => {
|
||||
setCode(v);
|
||||
setCodeError('');
|
||||
}}
|
||||
placeholder={t('snippets.form_code_placeholder')}
|
||||
spellCheck={false}
|
||||
rows={14}
|
||||
error={!!codeError}
|
||||
/>
|
||||
{codeError && <span className={styles.fieldError}>{codeError}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.formActions}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => navigate(`/snippets/${id}`)}
|
||||
>
|
||||
<Button type="button" variant="secondary" onClick={() => navigate(`/snippets/${id}`)}>
|
||||
<X size={14} />
|
||||
{t('snippets.action_cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
<Save size={14} />
|
||||
{t('snippets.action_update')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Pencil, Trash2 } from 'lucide-react';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { Upload, Pencil, Trash2, Braces } from 'lucide-react';
|
||||
import { CodeBlock } from '../../ui';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, DescriptionList, Notification, Timestamp, UuidBadge } from '../../ui';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
MarkdownContent,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SnippetDetailPage() {
|
||||
@@ -14,21 +25,28 @@ export function SnippetDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const [snippet, setSnippet] = useState<Snippet | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
usePageTitle(snippet?.title ?? null);
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
snippets
|
||||
.get(id)
|
||||
.then(setSnippet)
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!snippet) return;
|
||||
await snippets.remove(snippet.id);
|
||||
navigate('/snippets');
|
||||
setDeleting(true);
|
||||
try {
|
||||
await snippets.remove(snippet.id);
|
||||
navigate('/snippets');
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setConfirmDeleteOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async () => {
|
||||
@@ -38,7 +56,7 @@ export function SnippetDetailPage() {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `snippet-${snippet.name}.yaml`;
|
||||
a.download = `snippet-${snippet.alias}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
@@ -48,14 +66,18 @@ export function SnippetDetailPage() {
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs
|
||||
items={[
|
||||
{ label: t('snippets.title'), onClick: () => navigate('/snippets') },
|
||||
{ label: snippet?.name ?? `#${id}` },
|
||||
{
|
||||
label: t('snippets.title'),
|
||||
icon: <Braces size={14} />,
|
||||
onClick: () => navigate('/snippets'),
|
||||
},
|
||||
{ label: snippet?.title ?? `#${id}` },
|
||||
]}
|
||||
/>
|
||||
{snippet && (
|
||||
<div className={styles.toolbarActions}>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Download size={14} />
|
||||
<Upload size={14} />
|
||||
{t('snippets.action_export')}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -66,7 +88,7 @@ export function SnippetDetailPage() {
|
||||
<Pencil size={14} />
|
||||
{t('snippets.action_edit')}
|
||||
</Button>
|
||||
<Button variant="danger" size="sm" onClick={handleDelete}>
|
||||
<Button variant="danger" size="sm" onClick={() => setConfirmDeleteOpen(true)}>
|
||||
<Trash2 size={14} />
|
||||
{t('snippets.action_delete')}
|
||||
</Button>
|
||||
@@ -74,29 +96,18 @@ export function SnippetDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Notification
|
||||
variant="error"
|
||||
title={error.startsWith('404') ? t('errors.not_found') : undefined}
|
||||
>
|
||||
{error.startsWith('404') ? t('errors.not_found_snippet', { id }) : error}
|
||||
</Notification>
|
||||
)}
|
||||
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{snippet && (
|
||||
<>
|
||||
<div className={styles.detailMeta}>
|
||||
<Card>
|
||||
<DescriptionList
|
||||
layout="comfortable"
|
||||
layout="grid"
|
||||
items={[
|
||||
{ term: t('snippets.field_id'), detail: <UuidBadge id={snippet.id} /> },
|
||||
{ term: t('snippets.field_name'), detail: snippet.name },
|
||||
{
|
||||
term: t('snippets.field_description'),
|
||||
detail: snippet.description ?? '—',
|
||||
},
|
||||
{ term: t('snippets.field_alias'), detail: snippet.alias },
|
||||
{ term: t('snippets.field_title'), detail: snippet.title },
|
||||
{ term: t('snippets.field_version'), detail: `v${snippet.version}` },
|
||||
{
|
||||
term: t('snippets.field_created'),
|
||||
detail: <Timestamp value={snippet.createdAt} />,
|
||||
@@ -107,18 +118,51 @@ export function SnippetDetailPage() {
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{snippet.description && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('snippets.field_description')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<MarkdownContent content={snippet.description} />
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeader}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('snippets.section_code')}</h2>
|
||||
</div>
|
||||
<Card>
|
||||
<pre className={styles.codeBlock}>{snippet.code}</pre>
|
||||
<CodeBlock code={snippet.code} />
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={confirmDeleteOpen}
|
||||
title={t('snippets.action_delete')}
|
||||
onClose={() => !deleting && setConfirmDeleteOpen(false)}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setConfirmDeleteOpen(false)}
|
||||
disabled={deleting}
|
||||
>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('snippets.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{t('common.confirm_delete_snippet')}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,52 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Code, Pencil, Trash2, Plus, Upload } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { useImportFile } from '../../hooks/useImportFile';
|
||||
import { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, ContextMenu, Timestamp, UuidBadge } from '../../ui';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
ContextMenu,
|
||||
MarkdownContent,
|
||||
Modal,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
function SnippetCard({
|
||||
snippet,
|
||||
onDelete,
|
||||
}: {
|
||||
snippet: Snippet;
|
||||
onDelete: (id: string) => void;
|
||||
}) {
|
||||
function firstParagraphBlocks(
|
||||
markdown: string,
|
||||
limit = 2,
|
||||
): { preview: string; truncated: boolean } {
|
||||
const blocks = markdown
|
||||
.split(/\n\s*\n/g)
|
||||
.map((block) => block.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const sliced = blocks.slice(0, limit);
|
||||
return {
|
||||
preview: sliced.join('\n\n'),
|
||||
truncated: blocks.length > limit,
|
||||
};
|
||||
}
|
||||
|
||||
function SnippetCard({ snippet, onDelete }: { snippet: Snippet; onDelete: (id: string) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const header = (
|
||||
<div className={styles.envCardHeader}>
|
||||
<span className={styles.envCardName}>{snippet.name}</span>
|
||||
<span className={styles.envCardName}>{snippet.title}</span>
|
||||
<div onClick={(e) => e.stopPropagation()}>
|
||||
<ContextMenu
|
||||
align="right"
|
||||
trigger={
|
||||
<Button variant="ghost" size="sm" aria-label={t('snippets.menu_label')}>
|
||||
<Code size={14} />
|
||||
<Settings size={14} />
|
||||
</Button>
|
||||
}
|
||||
items={[
|
||||
@@ -62,9 +82,21 @@ function SnippetCard({
|
||||
footer={footer}
|
||||
onClick={() => navigate(`/snippets/${snippet.id}`)}
|
||||
>
|
||||
{snippet.description && (
|
||||
<p className={styles.muted}>{snippet.description}</p>
|
||||
)}
|
||||
<p className={styles.muted}>
|
||||
{t('snippets.field_alias')}: <code className={styles.codeInline}>{snippet.alias}</code>
|
||||
{' · '}v{snippet.version}
|
||||
</p>
|
||||
{snippet.description &&
|
||||
(() => {
|
||||
const { preview, truncated } = firstParagraphBlocks(snippet.description, 2);
|
||||
if (!preview) return null;
|
||||
return (
|
||||
<>
|
||||
<MarkdownContent content={preview} />
|
||||
{truncated && <p className={styles.muted}>...</p>}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -84,17 +116,17 @@ function AddSnippetCard() {
|
||||
|
||||
export function SnippetsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
usePageTitle(t('snippets.title'));
|
||||
const [items, setItems] = useState<Snippet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = () => {
|
||||
snippets
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
@@ -102,29 +134,28 @@ export function SnippetsPage() {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await snippets.remove(id);
|
||||
load();
|
||||
const requestDelete = (id: string) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await snippets.importSnippet(payload);
|
||||
navigate(`/snippets/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
await snippets.remove(deleteId);
|
||||
load();
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = useImportFile('snippet');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
<Breadcrumbs items={[{ label: t('snippets.title') }]} />
|
||||
<Breadcrumbs items={[{ label: t('snippets.title'), icon: <Braces size={14} /> }]} />
|
||||
<div className={styles.toolbarActions}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
@@ -134,26 +165,41 @@ export function SnippetsPage() {
|
||||
onChange={handleImport}
|
||||
/>
|
||||
<Button variant="secondary" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload size={14} />
|
||||
<Download size={14} />
|
||||
{t('snippets.action_import')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('snippets.loading')}</p>}
|
||||
|
||||
{!loading && (
|
||||
<div className={styles.envGrid}>
|
||||
{items.map((s) => (
|
||||
<SnippetCard key={s.id} snippet={s} onDelete={handleDelete} />
|
||||
<SnippetCard key={s.id} snippet={s} onDelete={requestDelete} />
|
||||
))}
|
||||
{items.length === 0 && (
|
||||
<p className={styles.muted}>{t('snippets.empty')}</p>
|
||||
)}
|
||||
{items.length === 0 && <p className={styles.muted}>{t('snippets.empty')}</p>}
|
||||
<AddSnippetCard />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={deleteId != null}
|
||||
title={t('snippets.action_delete')}
|
||||
onClose={() => !deleting && setDeleteId(null)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleteId(null)} disabled={deleting}>
|
||||
{t('common.button_cancel')}
|
||||
</Button>
|
||||
<Button variant="danger" onClick={handleDelete} disabled={deleting}>
|
||||
{t('snippets.action_delete')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{t('common.confirm_delete_snippet')}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -45,6 +45,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Clickable / hover ────────────────────────────────────── */
|
||||
|
||||
.clickable {
|
||||
cursor: pointer;
|
||||
border-radius: 99px;
|
||||
padding: 2px 6px;
|
||||
margin: -2px -6px;
|
||||
transition: background var(--transition);
|
||||
}
|
||||
|
||||
.clickable:hover {
|
||||
background: color-mix(in srgb, var(--color-text) 8%, transparent);
|
||||
}
|
||||
|
||||
.clickable:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ── Active state ─────────────────────────────────────────── */
|
||||
|
||||
.active .dot::before {
|
||||
@@ -52,7 +71,7 @@
|
||||
}
|
||||
|
||||
.active .label {
|
||||
color: var(--color-primary);
|
||||
color: var(--color-primary-text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@@ -64,6 +83,21 @@
|
||||
}
|
||||
|
||||
.inactive .label {
|
||||
/* Not dimmed with opacity: muted text already reads as inactive and keeps 4.5:1 */
|
||||
color: var(--color-text-muted);
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
/* ── Error state ──────────────────────────────────────────── */
|
||||
|
||||
.error .dot::before {
|
||||
background: var(--color-error-fg);
|
||||
}
|
||||
|
||||
.error .ring {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.error .label {
|
||||
color: var(--color-error-fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -4,22 +4,39 @@ export interface AutoRefreshIndicatorProps {
|
||||
active: boolean;
|
||||
pulseKey?: number;
|
||||
label?: string;
|
||||
error?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export function AutoRefreshIndicator({ active, pulseKey, label = 'Live' }: AutoRefreshIndicatorProps) {
|
||||
export function AutoRefreshIndicator({
|
||||
active,
|
||||
pulseKey,
|
||||
label = 'Live',
|
||||
error = false,
|
||||
onClick,
|
||||
}: AutoRefreshIndicatorProps) {
|
||||
const stateClass = error ? styles.error : active ? styles.active : styles.inactive;
|
||||
const titleText = error
|
||||
? 'Refresh failed — click to retry'
|
||||
: active
|
||||
? 'Auto-refreshing'
|
||||
: 'Auto-refresh stopped';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[styles.root, active ? styles.active : styles.inactive].join(' ')}
|
||||
title={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
|
||||
aria-label={active ? 'Auto-refreshing' : 'Auto-refresh stopped'}
|
||||
className={[styles.root, stateClass, onClick ? styles.clickable : ''].join(' ')}
|
||||
title={titleText}
|
||||
aria-label={titleText}
|
||||
aria-live="polite"
|
||||
role={onClick ? 'button' : undefined}
|
||||
tabIndex={onClick ? 0 : undefined}
|
||||
onClick={onClick}
|
||||
onKeyDown={onClick ? (e) => (e.key === 'Enter' || e.key === ' ') && onClick() : undefined}
|
||||
>
|
||||
<span className={styles.dot}>
|
||||
{pulseKey !== undefined && pulseKey > 0 && (
|
||||
<span key={pulseKey} className={styles.ring} />
|
||||
)}
|
||||
{pulseKey !== undefined && pulseKey > 0 && <span key={pulseKey} className={styles.ring} />}
|
||||
</span>
|
||||
<span className={styles.label}>{label}</span>
|
||||
<span className={styles.label}>{error ? 'Error' : label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
border-radius: var(--radius-full);
|
||||
white-space: nowrap;
|
||||
line-height: 1.6;
|
||||
box-shadow: var(--shadow-xs);
|
||||
}
|
||||
|
||||
.dot {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-family: var(--font-family);
|
||||
}
|
||||
|
||||
@@ -19,6 +21,9 @@
|
||||
}
|
||||
|
||||
.link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
font-size: var(--font-size-sm);
|
||||
color: var(--color-text-muted);
|
||||
text-decoration: none;
|
||||
@@ -42,6 +47,9 @@
|
||||
}
|
||||
|
||||
.current {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
|
||||
@@ -3,6 +3,7 @@ import styles from './Breadcrumbs.module.css';
|
||||
|
||||
export interface BreadcrumbItem {
|
||||
label: string;
|
||||
icon?: React.ReactNode;
|
||||
href?: string;
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
}
|
||||
@@ -35,14 +36,17 @@ export function Breadcrumbs({ items, separator, className }: BreadcrumbsProps) {
|
||||
<li key={i} className={styles.item}>
|
||||
{isLast ? (
|
||||
<span className={styles.current} aria-current="page">
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</span>
|
||||
) : item.href ? (
|
||||
<a href={item.href} className={styles.link} onClick={item.onClick}>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</a>
|
||||
) : (
|
||||
<button type="button" className={styles.link} onClick={item.onClick}>
|
||||
{item.icon}
|
||||
{item.label}
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
white-space: nowrap;
|
||||
outline: none;
|
||||
text-decoration: none;
|
||||
box-shadow: var(--shadow-xs);
|
||||
transition:
|
||||
background var(--transition),
|
||||
border-color var(--transition),
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-6);
|
||||
font-weight: 600;
|
||||
font-size: var(--font-size-sm);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
.pre {
|
||||
margin: 0;
|
||||
overflow-x: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.code {
|
||||
font-family: var(--font-mono, ui-monospace, 'Cascadia Code', 'Fira Code', monospace);
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: 1.6;
|
||||
display: block;
|
||||
background: transparent !important;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* ── highlight.js token overrides (theme-aware) ─────────────────────── */
|
||||
|
||||
.code :global(.hljs-comment),
|
||||
.code :global(.hljs-quote) {
|
||||
color: var(--hl-comment);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.code :global(.hljs-keyword),
|
||||
.code :global(.hljs-selector-tag),
|
||||
.code :global(.hljs-built_in),
|
||||
.code :global(.hljs-name),
|
||||
.code :global(.hljs-tag) {
|
||||
color: var(--hl-keyword);
|
||||
}
|
||||
|
||||
.code :global(.hljs-string),
|
||||
.code :global(.hljs-title),
|
||||
.code :global(.hljs-section),
|
||||
.code :global(.hljs-attribute),
|
||||
.code :global(.hljs-literal),
|
||||
.code :global(.hljs-template-tag),
|
||||
.code :global(.hljs-template-variable),
|
||||
.code :global(.hljs-type),
|
||||
.code :global(.hljs-addition) {
|
||||
color: var(--hl-string);
|
||||
}
|
||||
|
||||
.code :global(.hljs-number),
|
||||
.code :global(.hljs-regexp),
|
||||
.code :global(.hljs-link) {
|
||||
color: var(--hl-number);
|
||||
}
|
||||
|
||||
.code :global(.hljs-function),
|
||||
.code :global(.hljs-title.hljs-function_) {
|
||||
color: var(--hl-function);
|
||||
}
|
||||
|
||||
.code :global(.hljs-variable),
|
||||
.code :global(.hljs-params) {
|
||||
color: var(--hl-variable);
|
||||
}
|
||||
|
||||
.code :global(.hljs-property) {
|
||||
color: var(--hl-property);
|
||||
}
|
||||
|
||||
.code :global(.hljs-deletion),
|
||||
.code :global(.hljs-meta) {
|
||||
color: var(--hl-meta);
|
||||
}
|
||||
|
||||
.code :global(.hljs-emphasis) {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.code :global(.hljs-strong) {
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useMemo } from 'react';
|
||||
import hljs from '../../lib/hljs';
|
||||
import styles from './CodeBlock.module.css';
|
||||
|
||||
export interface CodeBlockProps {
|
||||
code: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export function CodeBlock({ code, language = 'javascript' }: CodeBlockProps) {
|
||||
const highlighted = useMemo(() => {
|
||||
try {
|
||||
return hljs.highlight(code, { language }).value;
|
||||
} catch {
|
||||
return code.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
}, [code, language]);
|
||||
|
||||
return (
|
||||
<pre className={styles.pre}>
|
||||
<code
|
||||
className={`${styles.code} hljs language-${language}`}
|
||||
dangerouslySetInnerHTML={{ __html: highlighted }}
|
||||
/>
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
.wrapper {
|
||||
width: 100%;
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: hidden;
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
}
|
||||
|
||||
.focused {
|
||||
border-color: var(--color-primary);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-primary) 20%, transparent);
|
||||
}
|
||||
|
||||
.hasError {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import Editor, { OnMount } from '@monaco-editor/react';
|
||||
import styles from './CodeEditor.module.css';
|
||||
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
language?: string;
|
||||
rows?: number;
|
||||
error?: boolean;
|
||||
}
|
||||
|
||||
function useMonacoTheme() {
|
||||
const [theme, setTheme] = useState(() =>
|
||||
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new MutationObserver(() => {
|
||||
setTheme(
|
||||
document.documentElement.getAttribute('data-theme') === 'dark' ? 'vs-dark' : 'vs-light',
|
||||
);
|
||||
});
|
||||
observer.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ['data-theme'],
|
||||
});
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return theme;
|
||||
}
|
||||
|
||||
export function CodeEditor({
|
||||
value,
|
||||
onChange,
|
||||
language = 'javascript',
|
||||
rows = 6,
|
||||
error = false,
|
||||
}: CodeEditorProps) {
|
||||
const theme = useMonacoTheme();
|
||||
const [focused, setFocused] = useState(false);
|
||||
const height = rows * 20 + 16;
|
||||
|
||||
const handleMount: OnMount = (editor) => {
|
||||
editor.onDidFocusEditorWidget(() => setFocused(true));
|
||||
editor.onDidBlurEditorWidget(() => setFocused(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[styles.wrapper, focused ? styles.focused : '', error ? styles.hasError : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
style={{ height }}
|
||||
>
|
||||
<Editor
|
||||
height="100%"
|
||||
theme={theme}
|
||||
language={language}
|
||||
value={value}
|
||||
onChange={(v) => onChange(v ?? '')}
|
||||
onMount={handleMount}
|
||||
options={{
|
||||
minimap: { enabled: false },
|
||||
scrollBeyondLastLine: false,
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
wordWrap: 'on',
|
||||
padding: { top: 8, bottom: 8 },
|
||||
folding: false,
|
||||
renderLineHighlight: 'line',
|
||||
scrollbar: { vertical: 'auto', horizontal: 'hidden' },
|
||||
automaticLayout: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -45,7 +45,26 @@
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* ── Layout modifiers ───────────────────────────────────────── */
|
||||
/* ── Grid layout ───────────────────────────────────────────── */
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
gap: var(--space-4) var(--space-6);
|
||||
}
|
||||
|
||||
.grid .row {
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.grid .term {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.grid .detail {
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.inline .row {
|
||||
flex-direction: row;
|
||||
|
||||
@@ -16,8 +16,8 @@ export interface DescriptionListItem {
|
||||
|
||||
export interface DescriptionListProps {
|
||||
items: DescriptionListItem[];
|
||||
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default) */
|
||||
layout?: 'inline' | 'compact' | 'comfortable';
|
||||
/** 'compact' stacks term above detail; 'inline' places them side by side; 'comfortable' adds generous spacing with dividers (default); 'grid' flows items into a responsive multi-column grid */
|
||||
layout?: 'inline' | 'compact' | 'comfortable' | 'grid';
|
||||
/** Truncate detail values with ellipsis; full value shown in a tooltip on hover */
|
||||
truncate?: boolean;
|
||||
className?: string;
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
height: 36px;
|
||||
width: 100%;
|
||||
outline: none;
|
||||
box-shadow: var(--shadow-xs);
|
||||
transition: border-color var(--transition), box-shadow var(--transition);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
.markdown {
|
||||
color: var(--color-text);
|
||||
line-height: 1.65;
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.markdown > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.markdown > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown h1,
|
||||
.markdown h2,
|
||||
.markdown h3,
|
||||
.markdown h4,
|
||||
.markdown h5,
|
||||
.markdown h6 {
|
||||
line-height: 1.25;
|
||||
margin: var(--space-5) 0 var(--space-3);
|
||||
}
|
||||
|
||||
.markdown h1 {
|
||||
font-size: var(--font-size-lg);
|
||||
}
|
||||
|
||||
.markdown h2 {
|
||||
font-size: var(--font-size-md);
|
||||
}
|
||||
|
||||
.markdown h3,
|
||||
.markdown h4,
|
||||
.markdown h5,
|
||||
.markdown h6 {
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.markdown p {
|
||||
margin: 0 0 var(--space-3);
|
||||
}
|
||||
|
||||
.markdown ul,
|
||||
.markdown ol {
|
||||
margin: 0 0 var(--space-3);
|
||||
padding-left: 1.35rem;
|
||||
}
|
||||
|
||||
.markdown li + li {
|
||||
margin-top: var(--space-1);
|
||||
}
|
||||
|
||||
.markdown blockquote {
|
||||
margin: 0 0 var(--space-3);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-left: 3px solid var(--color-primary);
|
||||
background: color-mix(in srgb, var(--color-primary) 8%, transparent);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.markdown pre {
|
||||
margin: 0 0 var(--space-3);
|
||||
padding: var(--space-3);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-code-bg, var(--color-bg-raised));
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.markdown code {
|
||||
font-family: var(--font-mono, ui-monospace, monospace);
|
||||
font-size: 0.92em;
|
||||
}
|
||||
|
||||
.markdown :not(pre) > code {
|
||||
padding: 0.12em 0.4em;
|
||||
border-radius: var(--radius-sm);
|
||||
background: color-mix(in srgb, var(--color-bg-raised) 60%, var(--color-secondary) 40%);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 0 0 var(--space-3);
|
||||
}
|
||||
|
||||
.markdown th,
|
||||
.markdown td {
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.markdown th {
|
||||
background: color-mix(in srgb, var(--color-bg-raised) 85%, var(--color-secondary) 15%);
|
||||
}
|
||||
|
||||
.markdown a {
|
||||
color: var(--color-link);
|
||||
}
|
||||
|
||||
.markdown a:hover {
|
||||
color: var(--color-link-hover);
|
||||
}
|
||||
|
||||
.markdown hr {
|
||||
border: 0;
|
||||
border-top: var(--border-width) solid var(--color-border);
|
||||
margin: var(--space-4) 0;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import styles from './MarkdownContent.module.css';
|
||||
|
||||
export interface MarkdownContentProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MarkdownContent({ content, className }: MarkdownContentProps) {
|
||||
return (
|
||||
<div className={`${styles.markdown}${className ? ` ${className}` : ''}`}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2000;
|
||||
background: color-mix(in srgb, #000 45%, transparent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
.dialog {
|
||||
width: min(520px, 100%);
|
||||
background-color: var(--color-bg-subtle, #ffffff);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: var(--space-4) var(--space-5) var(--space-2);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-md);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.body {
|
||||
padding: var(--space-2) var(--space-5) var(--space-4);
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: var(--space-3) var(--space-5) var(--space-4);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useEffect } from 'react';
|
||||
import styles from './Modal.module.css';
|
||||
|
||||
export interface ModalProps {
|
||||
open: boolean;
|
||||
title: string;
|
||||
children?: React.ReactNode;
|
||||
onClose: () => void;
|
||||
footer?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') onClose();
|
||||
};
|
||||
window.addEventListener('keydown', onKeyDown);
|
||||
return () => window.removeEventListener('keydown', onKeyDown);
|
||||
}, [open, onClose]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className={styles.overlay} role="presentation" onClick={onClose}>
|
||||
<div
|
||||
className={styles.dialog}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className={styles.header}>
|
||||
<h3 className={styles.title}>{title}</h3>
|
||||
</div>
|
||||
<div className={styles.body}>{children}</div>
|
||||
{footer && <div className={styles.footer}>{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
.root {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 5px var(--space-3);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-full);
|
||||
background: var(--color-bg-subtle);
|
||||
transition: border-color var(--transition), background var(--transition);
|
||||
}
|
||||
|
||||
.root:focus-within {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--color-bg);
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: var(--color-text-muted);
|
||||
flex-shrink: 0;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.input {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-family);
|
||||
font-size: var(--font-size-xs);
|
||||
outline: none;
|
||||
width: 180px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.input::placeholder {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Search as SearchIcon } from 'lucide-react';
|
||||
import styles from './Search.module.css';
|
||||
|
||||
export interface SearchProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function Search({ value, onChange, placeholder = 'Search…' }: SearchProps) {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<SearchIcon size={13} className={styles.icon} />
|
||||
<input
|
||||
className={styles.input}
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -79,10 +79,11 @@
|
||||
/* ── Chevron rotation ────────────────────────────────────── */
|
||||
.chevron {
|
||||
transition: transform 220ms ease;
|
||||
/* Points right (→) by default = collapse direction */
|
||||
transform: rotate(180deg);
|
||||
/* Points left (←) by default = collapse direction */
|
||||
}
|
||||
|
||||
.collapsed .chevron {
|
||||
transform: rotate(180deg);
|
||||
/* Points left (←) = expand direction */
|
||||
transform: rotate(0deg);
|
||||
/* Points right (→) = expand direction */
|
||||
}
|
||||
@@ -27,11 +27,40 @@
|
||||
background: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.thContent {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.thSortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary-fg) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
.sortIcon {
|
||||
opacity: 0.4;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sortIconActive {
|
||||
opacity: 1;
|
||||
color: var(--color-primary-text);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .th {
|
||||
background: var(--color-secondary);
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .thSortable:hover {
|
||||
background: color-mix(in srgb, var(--color-secondary) 80%, var(--color-secondary-border) 20%);
|
||||
}
|
||||
|
||||
/* Rounded top corners on first/last header cells */
|
||||
.th:first-child { border-radius: var(--radius-lg) 0 0 0; }
|
||||
.th:last-child { border-radius: 0 var(--radius-lg) 0 0; }
|
||||
|
||||
+150
-45
@@ -1,13 +1,18 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
|
||||
import { ArrowUp, ArrowDown, ArrowUpDown } from 'lucide-react';
|
||||
import { Pagination } from '../Pagination/Pagination';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
export interface TableColumn<T> {
|
||||
key: string;
|
||||
header: ReactNode;
|
||||
render: (row: T) => ReactNode;
|
||||
width?: string | number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
/** If true, a sort icon is shown and clicking the header triggers onSort */
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface TableProps<T> {
|
||||
@@ -17,12 +22,32 @@ export interface TableProps<T> {
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
/** Enable built-in client-side pagination with this default page size */
|
||||
/**
|
||||
* Client-side pagination: pass a default page size to enable.
|
||||
* For server-side pagination use `total` + `page` + `onPageChange` instead.
|
||||
*/
|
||||
pageSize?: number;
|
||||
/** Offer a page-size selector when pagination is enabled */
|
||||
pageSizeOptions?: number[];
|
||||
/** Called when a row is clicked */
|
||||
onRowClick?: (row: T) => void;
|
||||
/** Optional per-row props, useful for drag-and-drop and row-level attributes */
|
||||
getRowProps?: (row: T) => HTMLAttributes<HTMLTableRowElement>;
|
||||
/** Currently sorted column key (controlled) */
|
||||
sortBy?: string;
|
||||
/** Current sort direction (controlled) */
|
||||
sortDir?: SortDirection;
|
||||
/** Called when the user clicks a sortable column header */
|
||||
onSort?: (key: string, dir: SortDirection) => void;
|
||||
// ── Server-side pagination (controlled) ──────────────────────────────────
|
||||
/** Total record count from server. Presence switches to server-side pagination mode. */
|
||||
total?: number;
|
||||
/** Controlled current page (1-based). Required when `total` is set. */
|
||||
page?: number;
|
||||
/** Called when the user navigates to a new page. Required when `total` is set. */
|
||||
onPageChange?: (page: number) => void;
|
||||
/** Called when the user changes page size. Optional for server-side pagination. */
|
||||
onPageSizeChange?: (size: number) => void;
|
||||
}
|
||||
|
||||
export function Table<T>({
|
||||
@@ -35,34 +60,75 @@ export function Table<T>({
|
||||
pageSize: defaultPageSize,
|
||||
pageSizeOptions,
|
||||
onRowClick,
|
||||
getRowProps,
|
||||
sortBy,
|
||||
sortDir,
|
||||
onSort,
|
||||
total,
|
||||
page: controlledPage,
|
||||
onPageChange,
|
||||
onPageSizeChange,
|
||||
}: TableProps<T>) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
|
||||
const [internalPage, setInternalPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 10);
|
||||
|
||||
const paginated = defaultPageSize !== undefined && !loading;
|
||||
const visibleData = paginated ? data.slice((page - 1) * pageSize, page * pageSize) : data;
|
||||
const serverMode = total !== undefined;
|
||||
|
||||
// Reset to page 1 when data changes and current page would be empty
|
||||
const lastPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safePage = Math.min(page, Math.max(1, lastPage));
|
||||
const handleSortClick = (key: string) => {
|
||||
if (!onSort) return;
|
||||
const nextDir: SortDirection = sortBy === key && sortDir === 'asc' ? 'desc' : 'asc';
|
||||
onSort(key, nextDir);
|
||||
};
|
||||
|
||||
// Client-side pagination
|
||||
const clientPaginated = !serverMode && defaultPageSize !== undefined && !loading;
|
||||
const visibleData = clientPaginated
|
||||
? data.slice((internalPage - 1) * pageSize, internalPage * pageSize)
|
||||
: data;
|
||||
|
||||
const lastClientPage = pageSize > 0 ? Math.ceil(data.length / pageSize) : 1;
|
||||
const safeInternalPage = Math.min(internalPage, Math.max(1, lastClientPage));
|
||||
|
||||
// Server-side pagination display values
|
||||
const serverPage = controlledPage ?? 1;
|
||||
const serverTotal = total ?? 0;
|
||||
|
||||
return (
|
||||
<div className={`${styles.wrapper} ${className ?? ''}`}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={styles.th}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
>
|
||||
{col.header}
|
||||
</th>
|
||||
))}
|
||||
{columns.map((col) => {
|
||||
const isSorted = col.sortable && sortBy === col.key;
|
||||
const SortIcon = isSorted ? (sortDir === 'asc' ? ArrowUp : ArrowDown) : ArrowUpDown;
|
||||
|
||||
return (
|
||||
<th
|
||||
key={col.key}
|
||||
className={[styles.th, col.sortable ? styles.thSortable : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
style={{
|
||||
width: col.width,
|
||||
textAlign: col.align ?? 'left',
|
||||
}}
|
||||
onClick={col.sortable ? () => handleSortClick(col.key) : undefined}
|
||||
>
|
||||
<span className={styles.thContent}>
|
||||
{col.header}
|
||||
{col.sortable && (
|
||||
<SortIcon
|
||||
size={12}
|
||||
className={[styles.sortIcon, isSorted ? styles.sortIconActive : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</th>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -79,40 +145,79 @@ export function Table<T>({
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
visibleData.map((row) => (
|
||||
<tr
|
||||
key={rowKey(row)}
|
||||
className={[styles.tr, onRowClick ? styles.clickable : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
onClick={onRowClick ? () => onRowClick(row) : undefined}
|
||||
>
|
||||
{columns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
className={styles.td}
|
||||
style={{ textAlign: col.align ?? 'left' }}
|
||||
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
|
||||
>
|
||||
{col.render(row)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))
|
||||
visibleData.map((row) => {
|
||||
const rowProps = getRowProps?.(row);
|
||||
const mergedClassName = [
|
||||
styles.tr,
|
||||
onRowClick ? styles.clickable : '',
|
||||
rowProps?.className ?? '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
|
||||
const handleClick = (event: MouseEvent<HTMLTableRowElement>) => {
|
||||
rowProps?.onClick?.(event);
|
||||
if (!event.defaultPrevented) {
|
||||
onRowClick?.(row);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={rowKey(row)}
|
||||
{...rowProps}
|
||||
className={mergedClassName}
|
||||
onClick={onRowClick || rowProps?.onClick ? handleClick : undefined}
|
||||
>
|
||||
{columns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
className={styles.td}
|
||||
style={{ textAlign: col.align ?? 'left' }}
|
||||
onClick={col.key === 'actions' ? (e) => e.stopPropagation() : undefined}
|
||||
>
|
||||
{col.render(row)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{paginated && data.length > 0 && (
|
||||
{serverMode && serverTotal > 0 && onPageChange && (
|
||||
<Pagination
|
||||
page={safePage}
|
||||
page={serverPage}
|
||||
pageSize={pageSize}
|
||||
total={serverTotal}
|
||||
onPageChange={onPageChange}
|
||||
onPageSizeChange={
|
||||
onPageSizeChange
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageSizeChange(size);
|
||||
}
|
||||
: pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
onPageChange(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
pageSizeOptions={pageSizeOptions}
|
||||
/>
|
||||
)}
|
||||
{clientPaginated && data.length > 0 && (
|
||||
<Pagination
|
||||
page={safeInternalPage}
|
||||
pageSize={pageSize}
|
||||
total={data.length}
|
||||
onPageChange={setPage}
|
||||
onPageChange={setInternalPage}
|
||||
onPageSizeChange={
|
||||
pageSizeOptions
|
||||
? (size) => {
|
||||
setPageSize(size);
|
||||
setPage(1);
|
||||
setInternalPage(1);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React, { useId } from 'react';
|
||||
import styles from './Textarea.module.css';
|
||||
|
||||
export interface TextareaProps
|
||||
extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'id'> {
|
||||
export interface TextareaProps extends Omit<
|
||||
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
|
||||
'id'
|
||||
> {
|
||||
label?: string;
|
||||
hint?: string;
|
||||
error?: string;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
.viewport {
|
||||
position: fixed;
|
||||
top: var(--space-4);
|
||||
right: var(--space-4);
|
||||
z-index: 2000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
width: min(380px, calc(100vw - (var(--space-4) * 2)));
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-3);
|
||||
border-radius: var(--radius-md);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
background: var(--color-bg-subtle);
|
||||
box-shadow: var(--shadow-md);
|
||||
pointer-events: auto;
|
||||
opacity: 1;
|
||||
transform: translateX(0) scale(1);
|
||||
transition: opacity 100ms ease, transform 100ms ease;
|
||||
}
|
||||
|
||||
.leaving {
|
||||
opacity: 0;
|
||||
transform: translateX(8px) scale(0.98);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-top: 1px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin: 0;
|
||||
font-size: var(--font-size-sm);
|
||||
line-height: 1.4;
|
||||
color: var(--color-text);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--color-text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.close:hover {
|
||||
background: var(--color-secondary);
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.success {
|
||||
border-color: color-mix(in srgb, var(--color-primary) 50%, var(--color-border));
|
||||
background: var(--color-success-bg);
|
||||
}
|
||||
|
||||
.error {
|
||||
border-color: color-mix(in srgb, var(--color-danger) 50%, var(--color-border));
|
||||
background: var(--color-error-bg);
|
||||
}
|
||||
|
||||
.info {
|
||||
border-color: color-mix(in srgb, var(--color-secondary-fg) 35%, var(--color-border));
|
||||
background: var(--color-info-bg);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AlertCircle, CheckCircle2, Info, X } from 'lucide-react';
|
||||
import styles from './ToastProvider.module.css';
|
||||
import { subscribeApiErrorToasts } from '../../lib/toast-events';
|
||||
import { ToastContext, type ToastApi, type ToastVariant } from './toast-context';
|
||||
|
||||
interface ToastItem {
|
||||
id: number;
|
||||
message: string;
|
||||
variant: ToastVariant;
|
||||
closing: boolean;
|
||||
}
|
||||
|
||||
const ICONS: Record<ToastVariant, React.ReactNode> = {
|
||||
success: <CheckCircle2 size={16} />,
|
||||
error: <AlertCircle size={16} />,
|
||||
info: <Info size={16} />,
|
||||
};
|
||||
|
||||
export interface ToastProviderProps {
|
||||
children: React.ReactNode;
|
||||
durationMs?: number;
|
||||
}
|
||||
|
||||
export function ToastProvider({ children, durationMs = 3500 }: ToastProviderProps) {
|
||||
const EXIT_ANIMATION_MS = 100;
|
||||
const [items, setItems] = useState<ToastItem[]>([]);
|
||||
const lastShownAtRef = useRef<Map<string, number>>(new Map());
|
||||
|
||||
const remove = useCallback((id: number) => {
|
||||
setItems((prev) => prev.filter((item) => item.id !== id));
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback(
|
||||
(id: number) => {
|
||||
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, closing: true } : item)));
|
||||
window.setTimeout(() => remove(id), EXIT_ANIMATION_MS);
|
||||
},
|
||||
[remove],
|
||||
);
|
||||
|
||||
const show = useCallback(
|
||||
(message: string, variant: ToastVariant = 'info') => {
|
||||
const now = Date.now();
|
||||
const dedupeKey = `${variant}:${message}`;
|
||||
const previousTs = lastShownAtRef.current.get(dedupeKey) ?? 0;
|
||||
if (now - previousTs < 600) return;
|
||||
lastShownAtRef.current.set(dedupeKey, now);
|
||||
|
||||
const id = Date.now() + Math.floor(Math.random() * 1000);
|
||||
setItems((prev) => [...prev, { id, message, variant, closing: false }]);
|
||||
window.setTimeout(() => dismiss(id), durationMs);
|
||||
},
|
||||
[dismiss, durationMs],
|
||||
);
|
||||
|
||||
const api = useMemo<ToastApi>(
|
||||
() => ({
|
||||
show,
|
||||
success: (message: string) => show(message, 'success'),
|
||||
error: (message: string) => show(message, 'error'),
|
||||
info: (message: string) => show(message, 'info'),
|
||||
}),
|
||||
[show],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeApiErrorToasts((message) => api.error(message));
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={api}>
|
||||
{children}
|
||||
<div className={styles.viewport} aria-live="polite" aria-atomic="true">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className={[styles.toast, styles[item.variant], item.closing ? styles.leaving : '']
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
role="status"
|
||||
>
|
||||
<div className={styles.content}>
|
||||
<span className={styles.icon} aria-hidden="true">
|
||||
{ICONS[item.variant]}
|
||||
</span>
|
||||
<p className={styles.message}>{item.message}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.close}
|
||||
aria-label="Dismiss notification"
|
||||
onClick={() => dismiss(item.id)}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export type ToastVariant = 'success' | 'error' | 'info';
|
||||
|
||||
export interface ToastApi {
|
||||
show: (message: string, variant?: ToastVariant) => void;
|
||||
success: (message: string) => void;
|
||||
error: (message: string) => void;
|
||||
info: (message: string) => void;
|
||||
}
|
||||
|
||||
export const ToastContext = createContext<ToastApi | null>(null);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useContext } from 'react';
|
||||
import { ToastContext, type ToastApi } from './toast-context';
|
||||
|
||||
export function useToast(): ToastApi {
|
||||
const ctx = useContext(ToastContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useToast must be used within ToastProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
+20
-1
@@ -27,12 +27,28 @@ export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs
|
||||
|
||||
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
|
||||
|
||||
export { ToastProvider } from './Toast/ToastProvider';
|
||||
export type { ToastProviderProps } from './Toast/ToastProvider';
|
||||
export { useToast } from './Toast/useToast';
|
||||
|
||||
export { Timestamp } from './Timestamp/Timestamp';
|
||||
export type { TimestampProps } from './Timestamp/Timestamp';
|
||||
|
||||
export { Pagination } from './Pagination/Pagination';
|
||||
export type { PaginationProps } from './Pagination/Pagination';
|
||||
|
||||
export { Search } from './Search/Search';
|
||||
export type { SearchProps } from './Search/Search';
|
||||
|
||||
export { CodeBlock } from './CodeBlock/CodeBlock';
|
||||
export type { CodeBlockProps } from './CodeBlock/CodeBlock';
|
||||
|
||||
export { CodeEditor } from './CodeEditor/CodeEditor';
|
||||
export type { CodeEditorProps } from './CodeEditor/CodeEditor';
|
||||
|
||||
export { MarkdownContent } from './MarkdownContent/MarkdownContent';
|
||||
export type { MarkdownContentProps } from './MarkdownContent/MarkdownContent';
|
||||
|
||||
export { ContextMenu } from './ContextMenu/ContextMenu';
|
||||
export type { ContextMenuProps, ContextMenuItem } from './ContextMenu/ContextMenu';
|
||||
|
||||
@@ -42,8 +58,11 @@ export type { DescriptionListProps, DescriptionListItem } from './DescriptionLis
|
||||
export { Notification } from './Notification/Notification';
|
||||
export type { NotificationProps, NotificationVariant } from './Notification/Notification';
|
||||
|
||||
export { Modal } from './Modal/Modal';
|
||||
export type { ModalProps } from './Modal/Modal';
|
||||
|
||||
export { Table } from './Table/Table';
|
||||
export type { TableProps, TableColumn } from './Table/Table';
|
||||
export type { TableProps, TableColumn, SortDirection } from './Table/Table';
|
||||
|
||||
export { UuidBadge } from './UuidBadge/UuidBadge';
|
||||
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
|
||||
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user