Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,9 @@
|
||||
.git
|
||||
.gitignore
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/.DS_Store
|
||||
**/*.log
|
||||
data
|
||||
keys
|
||||
+2
-2
@@ -1,5 +1,4 @@
|
||||
# runtime / secrets
|
||||
/keys
|
||||
# runtime
|
||||
/data
|
||||
.env
|
||||
*.log
|
||||
@@ -13,3 +12,4 @@ server/dist
|
||||
client/dist
|
||||
*storybook.log
|
||||
storybook-static
|
||||
tsconfig.tsbuildinfo
|
||||
@@ -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
|
||||
@@ -15,5 +15,6 @@ RUN npm run -w client build
|
||||
FROM nginx:alpine AS runtime
|
||||
|
||||
COPY --from=builder /app/client/dist /usr/share/nginx/html
|
||||
COPY client/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,17 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://server:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+149
-75
@@ -1,43 +1,106 @@
|
||||
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 } 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 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 },
|
||||
];
|
||||
|
||||
export default function App() {
|
||||
@@ -49,56 +112,67 @@ 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="/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>
|
||||
);
|
||||
|
||||
+73
-36
@@ -2,7 +2,6 @@ import type {
|
||||
PaginatedResponse,
|
||||
Credential,
|
||||
Environment,
|
||||
KeysResponse,
|
||||
ScenarioCredential,
|
||||
Session,
|
||||
Scenario,
|
||||
@@ -12,25 +11,42 @@ import type {
|
||||
ScenarioStep,
|
||||
Snippet,
|
||||
} 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 {
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...init?.headers },
|
||||
...init,
|
||||
});
|
||||
} 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 ───────────────────────────────────────────────────────────────
|
||||
@@ -77,13 +93,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),
|
||||
@@ -112,13 +133,13 @@ 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']): Promise<Environment> {
|
||||
return request('/environments', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, urls }),
|
||||
body: JSON.stringify({ name, data }),
|
||||
});
|
||||
},
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'urls'>>): Promise<Environment> {
|
||||
update(id: string, patch: Partial<Pick<Environment, 'name' | 'data'>>): Promise<Environment> {
|
||||
return request(`/environments/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(patch),
|
||||
@@ -127,13 +148,14 @@ 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`);
|
||||
},
|
||||
importEnvironment(payload: unknown): Promise<Environment> {
|
||||
return request('/environments/import', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@@ -155,7 +177,7 @@ export const sessions = {
|
||||
|
||||
export const scenarios = {
|
||||
list(page = 1, limit = 50): Promise<PaginatedResponse<Scenario>> {
|
||||
return request(`/scenarios?page=${page}&limit=${limit}`);
|
||||
return request(`/scenarios?page=${page}&limit=${limit}&orderBy=updatedAt&orderDir=DESC`);
|
||||
},
|
||||
get(id: string): Promise<Scenario & { steps: ScenarioStep[] }> {
|
||||
return request(`/scenarios/${id}`);
|
||||
@@ -175,8 +197,11 @@ 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): Promise<ScenarioRun> {
|
||||
return request(`/scenarios/${id}/run`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ environmentId, saveSession }),
|
||||
});
|
||||
},
|
||||
getRun(scenarioId: string, runId: string): Promise<ScenarioRunDetail> {
|
||||
return request(`/scenarios/${scenarioId}/run/${runId}`);
|
||||
@@ -184,10 +209,14 @@ 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> {
|
||||
exportScenario(id: string): Promise<string> {
|
||||
return request(`/scenarios/${id}/export`);
|
||||
},
|
||||
importScenario(payload: unknown): Promise<Scenario> {
|
||||
@@ -201,16 +230,29 @@ export const scenarios = {
|
||||
// ── Runs ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export const runs = {
|
||||
listAll(page = 1, limit = 20, status?: string): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[]; scenario: { id: string; name: string } }>> {
|
||||
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) });
|
||||
if (status) q.set('status', status);
|
||||
return request(`/scenarios/runs?${q}`);
|
||||
},
|
||||
list(scenarioId: string, page = 1, limit = 20): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
list(
|
||||
scenarioId: string,
|
||||
page = 1,
|
||||
limit = 20,
|
||||
): Promise<PaginatedResponse<ScenarioRun & { stepRuns: ScenarioRunStep[] }>> {
|
||||
return request(`/scenarios/${scenarioId}/runs?page=${page}&limit=${limit}`);
|
||||
},
|
||||
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}`);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -236,18 +278,13 @@ export const scenarioCredentials = {
|
||||
// ── Scenario Steps ────────────────────────────────────────────────────────────
|
||||
export interface CreateStepPayload {
|
||||
title?: string;
|
||||
order: number;
|
||||
type: 'login' | 'exec' | 'sign';
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
}
|
||||
|
||||
export interface UpdateStepPayload {
|
||||
title?: string;
|
||||
order?: number;
|
||||
type?: 'login' | 'exec' | 'sign';
|
||||
execCode?: string;
|
||||
validateCode?: string;
|
||||
}
|
||||
|
||||
export const steps = {
|
||||
|
||||
+9
-17
@@ -9,17 +9,14 @@ 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;
|
||||
data: EnvironmentData;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -39,19 +36,14 @@ export interface Credential {
|
||||
|
||||
export interface Snippet {
|
||||
id: string;
|
||||
name: string;
|
||||
alias: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface KeysResponse {
|
||||
keys: string[];
|
||||
}
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type SessionStatus = 'open' | 'closed';
|
||||
@@ -68,17 +60,12 @@ 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;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -110,7 +97,12 @@ export type LogLevel = 'log' | 'warn' | 'error';
|
||||
export interface ScenarioRun {
|
||||
id: string;
|
||||
scenarioId: string;
|
||||
environmentId: string;
|
||||
sessionId?: string | null;
|
||||
saveSession: boolean;
|
||||
scenario?: Pick<Scenario, 'id' | 'name'>;
|
||||
environment?: Pick<Environment, 'id' | 'name'>;
|
||||
session?: { id: string; sessionName: string };
|
||||
status: ScenarioRunStatus;
|
||||
stepRuns?: ScenarioRunStep[];
|
||||
createdAt: string;
|
||||
|
||||
@@ -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,80 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Play } from 'lucide-react';
|
||||
import { Modal, Button, Select } from '../../ui';
|
||||
import type { Environment } from '../../api';
|
||||
|
||||
export interface RunScenarioModalProps {
|
||||
open: boolean;
|
||||
environments: Environment[];
|
||||
selectedEnvId: string;
|
||||
onEnvSelect: (envId: string) => void;
|
||||
saveSessionFlag: boolean;
|
||||
onSaveSessionChange: (flag: boolean) => void;
|
||||
onClose: () => void;
|
||||
onRun: () => void;
|
||||
isRunning: boolean;
|
||||
actionLabel?: string;
|
||||
}
|
||||
|
||||
export function RunScenarioModal({
|
||||
open,
|
||||
environments,
|
||||
selectedEnvId,
|
||||
onEnvSelect,
|
||||
saveSessionFlag,
|
||||
onSaveSessionChange,
|
||||
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 }))}
|
||||
/>
|
||||
<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>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { DeleteConfirmationModal } from './DeleteConfirmationModal';
|
||||
export type { DeleteConfirmationModalProps } from './DeleteConfirmationModal';
|
||||
export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
Vendored
+2
@@ -6,3 +6,5 @@ declare module '*.css' {
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_URL?: string;
|
||||
}
|
||||
|
||||
declare const __APP_VERSION__: string;
|
||||
@@ -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.",
|
||||
@@ -19,37 +32,42 @@
|
||||
},
|
||||
"environments": {
|
||||
"title": "Environments",
|
||||
"created": "Environment created",
|
||||
"updated": "Environment updated",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_urls": "URLs",
|
||||
"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_data": "Data (JSON)",
|
||||
"form_data_invalid_json": "Must be a valid JSON object",
|
||||
"back": "Environments",
|
||||
"field_id": "ID",
|
||||
"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 +75,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",
|
||||
@@ -98,6 +116,9 @@
|
||||
"field_lastUsed": "Last Used"
|
||||
},
|
||||
"scenarios": { "title": "Scenarios",
|
||||
"created": "Scenario created",
|
||||
"updated": "Scenario updated",
|
||||
"run_started": "Scenario run started",
|
||||
"col_id": "ID",
|
||||
"col_name": "Name",
|
||||
"col_updated": "Updated",
|
||||
@@ -123,7 +144,7 @@
|
||||
"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",
|
||||
@@ -144,7 +165,11 @@
|
||||
"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"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -160,6 +185,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 +194,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",
|
||||
@@ -178,9 +205,7 @@
|
||||
"form_session_placeholder": "e.g. my-session",
|
||||
"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_exec_code_placeholder": "return await page.title();"
|
||||
},
|
||||
"runs": {
|
||||
"title": "Runs",
|
||||
@@ -198,7 +223,9 @@
|
||||
"field_created": "Started",
|
||||
"field_updated": "Updated",
|
||||
"steps_heading": "Step runs",
|
||||
"step_title": "Title",
|
||||
"logs_heading": "Logs",
|
||||
"logs_search_placeholder": "Filter logs…",
|
||||
"step_order": "#",
|
||||
"step_type": "Type",
|
||||
"step_session": "Session",
|
||||
@@ -210,6 +237,8 @@
|
||||
},
|
||||
"snippets": {
|
||||
"title": "Snippets",
|
||||
"created": "Snippet created",
|
||||
"updated": "Snippet updated",
|
||||
"empty": "No snippets yet.",
|
||||
"loading": "Loading…",
|
||||
"menu_label": "Snippet options",
|
||||
@@ -217,20 +246,24 @@
|
||||
"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_title": "Title",
|
||||
"field_description": "Description",
|
||||
"field_created": "Created",
|
||||
"field_updated": "Updated",
|
||||
|
||||
@@ -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,23 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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();
|
||||
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 +34,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 +51,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 +76,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,13 @@
|
||||
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 { 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 +16,27 @@ 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);
|
||||
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 +56,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 +78,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 +86,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 +109,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,20 @@
|
||||
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 { Settings, Pencil, Trash2, Plus, Download, KeyRound } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
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({
|
||||
@@ -94,14 +103,14 @@ export function CredentialsPage() {
|
||||
const navigate = useNavigate();
|
||||
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,9 +118,20 @@ 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 handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await credentials.remove(deleteId);
|
||||
setItems((prev) => prev.filter((c) => c.id !== deleteId));
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -123,15 +143,15 @@ export function CredentialsPage() {
|
||||
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));
|
||||
} catch {
|
||||
// Import errors are silently ignored
|
||||
}
|
||||
};
|
||||
|
||||
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 +161,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,15 +1,17 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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('');
|
||||
@@ -18,7 +20,6 @@ export function EditCredentialPage() {
|
||||
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 +30,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 +50,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 +70,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 +84,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 +102,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 +127,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,53 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [idUrl, setIdUrl] = useState('');
|
||||
const [cabinetUrl, setCabinetUrl] = useState('');
|
||||
const [adminUrl, setAdminUrl] = 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);
|
||||
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 +58,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 +83,29 @@ 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_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,25 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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('');
|
||||
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 +28,45 @@ 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 ?? '');
|
||||
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,
|
||||
},
|
||||
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 +77,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 +91,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 +109,20 @@ 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_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 +131,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,64 @@
|
||||
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 { 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,
|
||||
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);
|
||||
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 +66,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 +88,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 +96,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 +115,17 @@ 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]) => ({
|
||||
<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 +133,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,38 @@
|
||||
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 { Settings, ExternalLink, Pencil, Trash2, Plus, Globe, Download } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
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 +56,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 +88,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 +117,17 @@ function AddEnvironmentCard() {
|
||||
|
||||
export function EnvironmentsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
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 +135,73 @@ 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 = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
e.target.value = '';
|
||||
try {
|
||||
const text = await file.text();
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await environments.importEnvironment(payload);
|
||||
navigate(`/environments/${imported.id}`);
|
||||
} catch {
|
||||
// Import errors are silently ignored
|
||||
}
|
||||
};
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,18 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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 {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
@@ -30,31 +39,20 @@ export function AllRunsPage() {
|
||||
const { t } = useTranslation();
|
||||
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 load = () => {
|
||||
runs
|
||||
.listAll()
|
||||
.then((res) => {
|
||||
setItems(res.data as AllRunRow[]);
|
||||
setPulseKey((k) => k + 1);
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
load();
|
||||
pollRef.current = setInterval(load, 10_000);
|
||||
return () => {
|
||||
if (pollRef.current) clearInterval(pollRef.current);
|
||||
};
|
||||
}, []);
|
||||
const {
|
||||
data: items = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = useQuery<AllRunRow[]>({
|
||||
queryKey: ['runs'],
|
||||
queryFn: async () => {
|
||||
const res = await runs.listAll();
|
||||
return res.data as AllRunRow[];
|
||||
},
|
||||
refetchInterval: 10_000,
|
||||
staleTime: 0,
|
||||
});
|
||||
|
||||
const columns: TableColumn<AllRunRow>[] = [
|
||||
{ key: 'id', header: t('runs.col_id'), render: (r) => <UuidBadge id={r.id} />, width: 60 },
|
||||
@@ -77,9 +75,7 @@ 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>
|
||||
),
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
@@ -98,16 +94,20 @@ 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}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { runs } from '../../api';
|
||||
import type {
|
||||
@@ -17,14 +17,17 @@ import {
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Card,
|
||||
CodeBlock,
|
||||
DescriptionList,
|
||||
Notification,
|
||||
Pagination,
|
||||
Search,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import { ChevronDown, ChevronRight, ClipboardList, Activity } from 'lucide-react';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
const RUN_STATUS_VARIANT: Record<ScenarioRunStatus, BadgeVariant> = {
|
||||
@@ -56,6 +59,8 @@ const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
|
||||
error: 'error',
|
||||
};
|
||||
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
export function RunDetailPage() {
|
||||
const { t } = useTranslation();
|
||||
const { id, runId } = useParams<{ id: string; runId: string }>();
|
||||
@@ -67,10 +72,15 @@ export function RunDetailPage() {
|
||||
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 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 +89,35 @@ export function RunDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
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));
|
||||
};
|
||||
|
||||
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;
|
||||
@@ -92,7 +131,7 @@ export function RunDetailPage() {
|
||||
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);
|
||||
@@ -103,8 +142,12 @@ export function RunDetailPage() {
|
||||
}, 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;
|
||||
@@ -115,10 +158,10 @@ export function RunDetailPage() {
|
||||
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.scenarioStep?.title ?? <span className={styles.muted}>–</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
@@ -130,8 +173,109 @@ 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 +286,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 +304,80 @@ 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} />
|
||||
<AutoRefreshIndicator
|
||||
active={polling}
|
||||
pulseKey={pulseKey}
|
||||
error={!!error}
|
||||
onClick={manualRefresh}
|
||||
/>
|
||||
</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.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,14 +396,29 @@ 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>
|
||||
<Search
|
||||
value={logSearch}
|
||||
onChange={setLogSearch}
|
||||
placeholder={t('runs.logs_search_placeholder')}
|
||||
/>
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
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 { Play, ClipboardList, Activity } from 'lucide-react';
|
||||
import { environments, scenarios, runs } from '../../api';
|
||||
import type {
|
||||
Environment,
|
||||
Scenario,
|
||||
ScenarioRun,
|
||||
ScenarioRunStep,
|
||||
ScenarioRunStatus,
|
||||
} from '../../api';
|
||||
import {
|
||||
AutoRefreshIndicator,
|
||||
Badge,
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
import type { BadgeVariant } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
@@ -28,22 +46,30 @@ 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[]>([]);
|
||||
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);
|
||||
if (!hasDataRef.current) setLoading(true);
|
||||
Promise.all([scenarios.get(id!), runs.list(id!)])
|
||||
.then(([sc, res]) => {
|
||||
setScenario(sc);
|
||||
setItems(res.data);
|
||||
setError(null);
|
||||
setPulseKey((k) => k + 1);
|
||||
hasDataRef.current = true;
|
||||
})
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
@@ -57,9 +83,32 @@ export function RunsPage() {
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
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,9 +117,7 @@ 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>
|
||||
),
|
||||
render: (r) => <Badge variant={STATUS_VARIANT[r.status]}>{STATUS_LABEL[r.status]}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'steps',
|
||||
@@ -91,24 +138,27 @@ 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} />
|
||||
<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}
|
||||
@@ -119,6 +169,33 @@ export function RunsPage() {
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
onRowClick={(r) => navigate(`/scenarios/${id}/runs/${r.id}`)}
|
||||
/>
|
||||
|
||||
<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,34 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, useToast } from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateScenarioPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [nameError, setNameError] = 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('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const scenario = await scenarios.create(name.trim());
|
||||
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 +39,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}>
|
||||
@@ -64,9 +68,11 @@ export function CreateScenarioPage() {
|
||||
|
||||
<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,44 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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');
|
||||
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 [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,
|
||||
});
|
||||
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 +49,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 +63,28 @@ 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>
|
||||
</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,23 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input } from '../../ui';
|
||||
import { Breadcrumbs, Button, Card, Input, 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('');
|
||||
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;
|
||||
@@ -26,23 +27,23 @@ export function EditScenarioPage() {
|
||||
setScenario(data);
|
||||
setName(data.name);
|
||||
})
|
||||
.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('scenarios.form_name_required'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await scenarios.update(id!, { name: name.trim() });
|
||||
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 +54,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 +68,6 @@ export function EditScenarioPage() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
{loading && <p className={styles.muted}>{t('scenarios.loading')}</p>}
|
||||
|
||||
{!loading && scenario && (
|
||||
@@ -90,9 +94,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,24 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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('');
|
||||
const [title, setTitle] = useState('');
|
||||
const [type, setType] = useState<StepType>('exec');
|
||||
const [execCode, setExecCode] = useState('');
|
||||
const [validateCode, setValidateCode] = useState('');
|
||||
const [orderError, setOrderError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id || !stepId) return;
|
||||
@@ -31,41 +26,25 @@ 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 ?? '');
|
||||
})
|
||||
.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,
|
||||
});
|
||||
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,67 +55,35 @@ 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 + 1 : 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>
|
||||
</div>
|
||||
|
||||
@@ -146,9 +93,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,54 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, 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 {
|
||||
Badge,
|
||||
Play,
|
||||
Pencil,
|
||||
Plus,
|
||||
History,
|
||||
Trash2,
|
||||
Upload,
|
||||
GripVertical,
|
||||
ClipboardList,
|
||||
} from 'lucide-react';
|
||||
import { stringify as yamlStringify } from 'yaml';
|
||||
import {
|
||||
environments,
|
||||
scenarios,
|
||||
steps,
|
||||
scenarioCredentials,
|
||||
credentials as credentialsApi,
|
||||
} from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioStep,
|
||||
ScenarioCredential,
|
||||
Credential,
|
||||
Environment,
|
||||
} from '../../api';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionList,
|
||||
Input,
|
||||
Notification,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
type TableColumn,
|
||||
} from '../../ui';
|
||||
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);
|
||||
|
||||
// Credentials state
|
||||
const [scenarioCreds, setScenarioCreds] = useState<ScenarioCredential[]>([]);
|
||||
@@ -44,27 +59,66 @@ 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);
|
||||
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);
|
||||
|
||||
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));
|
||||
credentialsApi
|
||||
.list(1, 200)
|
||||
.then((r) => setAllCredentials(r.data))
|
||||
.catch(() => {});
|
||||
environments
|
||||
.list(1, 200)
|
||||
.then((r) => {
|
||||
setEnvs(r.data);
|
||||
setSelectedEnvId((prev) => prev || r.data[0]?.id || '');
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
const reloadScenario = async () => {
|
||||
if (!id) return;
|
||||
const s = await scenarios.get(id);
|
||||
setScenario(s);
|
||||
setScenarioCreds(s.scenarioCredentials ?? []);
|
||||
};
|
||||
|
||||
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);
|
||||
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 () => {
|
||||
@@ -76,7 +130,8 @@ export function ScenarioDetailPage() {
|
||||
const handleExport = async () => {
|
||||
if (!scenario) return;
|
||||
const data = await scenarios.exportScenario(scenario.id);
|
||||
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||
const yamlContent = typeof data === 'string' ? data : yamlStringify(data);
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
@@ -87,16 +142,34 @@ export function ScenarioDetailPage() {
|
||||
|
||||
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 +193,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 + 1, 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 +291,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 +326,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 +340,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={() => setRunModalOpen(true)}>
|
||||
<Play size={14} />
|
||||
{t('scenarios.action_run')}
|
||||
</Button>
|
||||
@@ -227,14 +359,18 @@ export function ScenarioDetailPage() {
|
||||
{t('scenarios.action_runs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleExport}>
|
||||
<Download size={14} />
|
||||
<Upload size={14} />
|
||||
{t('scenarios.action_export')}
|
||||
</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 +378,16 @@ 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_created'),
|
||||
detail: <Timestamp value={scenario.createdAt} />,
|
||||
@@ -288,6 +415,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 +466,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>
|
||||
)}
|
||||
|
||||
@@ -368,6 +529,71 @@ export function ScenarioDetailPage() {
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<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>
|
||||
|
||||
<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('scenarios.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 }))}
|
||||
/>
|
||||
<label
|
||||
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => setSaveSessionFlag(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +1,89 @@
|
||||
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 { Play, Plus, Trash2, Download, ClipboardList } 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 { environments, scenarios } from '../../api';
|
||||
import type { Environment, Scenario } from '../../api';
|
||||
import {
|
||||
Breadcrumbs,
|
||||
Button,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
type TableColumn,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
useToast,
|
||||
} from '../../ui';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function ScenariosPage() {
|
||||
const { t } = useTranslation();
|
||||
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);
|
||||
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))
|
||||
Promise.all([scenarios.list(), environments.list(1, 200)])
|
||||
.then(([scenarioRes, envRes]) => {
|
||||
setItems(scenarioRes?.data ?? []);
|
||||
setEnvs(envRes?.data ?? []);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error((err as Error).message);
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
}, [toast]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const handleRun = async (id: string) => {
|
||||
const run = await scenarios.run(id);
|
||||
navigate(`/scenarios/${id}/runs/${run.id}`);
|
||||
const openRunModal = (id: string) => {
|
||||
setRunScenarioId(id);
|
||||
if (!selectedEnvId && envs.length > 0) {
|
||||
setSelectedEnvId(envs[0].id);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await scenarios.remove(id);
|
||||
setLoading(true);
|
||||
load();
|
||||
const handleRun = async () => {
|
||||
if (!runScenarioId || !selectedEnvId) return;
|
||||
setRunning(true);
|
||||
try {
|
||||
const run = await scenarios.run(runScenarioId, selectedEnvId, saveSessionFlag);
|
||||
toast.success(t('scenarios.run_started'));
|
||||
navigate(`/scenarios/${runScenarioId}/runs/${run.id}`);
|
||||
setRunScenarioId(null);
|
||||
setSaveSessionFlag(false);
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await scenarios.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -49,8 +95,8 @@ export function ScenariosPage() {
|
||||
const payload = yamlParse(text) as unknown;
|
||||
const imported = await scenarios.importScenario(payload);
|
||||
navigate(`/scenarios/${imported.id}`);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} catch {
|
||||
// Import errors are silently ignored
|
||||
}
|
||||
};
|
||||
|
||||
@@ -70,14 +116,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 +145,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 +155,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,7 +164,6 @@ export function ScenariosPage() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={items}
|
||||
@@ -119,6 +174,63 @@ export function ScenariosPage() {
|
||||
pageSizeOptions={[10, 25, 50]}
|
||||
onRowClick={(s) => navigate(`/scenarios/${s.id}`)}
|
||||
/>
|
||||
|
||||
<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>
|
||||
|
||||
<Modal
|
||||
open={runScenarioId != null}
|
||||
title={t('scenarios.run_modal_title')}
|
||||
onClose={() => !running && setRunScenarioId(null)}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRunScenarioId(null)} disabled={running}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleRun} disabled={running || !selectedEnvId}>
|
||||
{t('scenarios.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 }))}
|
||||
/>
|
||||
<label
|
||||
style={{ display: 'flex', alignItems: 'center', marginTop: '1rem', gap: '0.5rem' }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveSessionFlag}
|
||||
onChange={(e) => setSaveSessionFlag(e.target.checked)}
|
||||
/>
|
||||
<span>{t('common.save_session')}</span>
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
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 +14,27 @@ 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);
|
||||
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 +42,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 +95,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,10 +1,19 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
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,
|
||||
Timestamp,
|
||||
UuidBadge,
|
||||
} from '../../ui';
|
||||
import { DeleteConfirmationModal } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function SessionsPage() {
|
||||
@@ -12,13 +21,13 @@ export function SessionsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [items, setItems] = useState<Session[]>([]);
|
||||
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 load = useCallback(() => {
|
||||
sessions
|
||||
.list()
|
||||
.then((res) => setItems(res.data))
|
||||
.catch((err: Error) => setError(err.message))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
@@ -26,10 +35,17 @@ export function SessionsPage() {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await sessions.remove(id);
|
||||
setLoading(true);
|
||||
load();
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await sessions.remove(deleteId);
|
||||
setLoading(true);
|
||||
load();
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: TableColumn<Session>[] = [
|
||||
@@ -57,7 +73,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,8 +86,9 @@ 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}
|
||||
@@ -79,6 +99,15 @@ export function SessionsPage() {
|
||||
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,34 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, SubmitEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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();
|
||||
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 +37,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 +59,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,28 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, SubmitEvent } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
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('');
|
||||
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 +30,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 +55,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 +77,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 +91,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,21 @@
|
||||
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 { 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 +24,27 @@ 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);
|
||||
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 +54,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 +64,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 +86,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 +94,17 @@ 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_created'),
|
||||
detail: <Timestamp value={snippet.createdAt} />,
|
||||
@@ -107,18 +115,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,51 @@
|
||||
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 { Settings, Pencil, Trash2, Plus, Download, Braces } from 'lucide-react';
|
||||
import { parse as yamlParse } from 'yaml';
|
||||
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 +81,20 @@ 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>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -87,14 +117,14 @@ export function SnippetsPage() {
|
||||
const navigate = useNavigate();
|
||||
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,9 +132,20 @@ export function SnippetsPage() {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
await snippets.remove(id);
|
||||
load();
|
||||
const requestDelete = (id: string) => {
|
||||
setDeleteId(id);
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
await snippets.remove(deleteId);
|
||||
load();
|
||||
setDeleteId(null);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -116,15 +157,15 @@ export function SnippetsPage() {
|
||||
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));
|
||||
} catch {
|
||||
// Import errors are silently ignored
|
||||
}
|
||||
};
|
||||
|
||||
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 +175,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 {
|
||||
@@ -67,3 +86,18 @@
|
||||
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, #6A8072);
|
||||
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, #A67DCC);
|
||||
}
|
||||
|
||||
.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, #9BB870);
|
||||
}
|
||||
|
||||
.code :global(.hljs-number),
|
||||
.code :global(.hljs-regexp),
|
||||
.code :global(.hljs-link) {
|
||||
color: var(--hl-number, #E8A85F);
|
||||
}
|
||||
|
||||
.code :global(.hljs-function),
|
||||
.code :global(.hljs-title.hljs-function_) {
|
||||
color: var(--hl-function, #5BB8D4);
|
||||
}
|
||||
|
||||
.code :global(.hljs-variable),
|
||||
.code :global(.hljs-params) {
|
||||
color: var(--hl-variable, #D4A0A0);
|
||||
}
|
||||
|
||||
.code :global(.hljs-property) {
|
||||
color: var(--hl-property, #79C0C8);
|
||||
}
|
||||
|
||||
.code :global(.hljs-deletion),
|
||||
.code :global(.hljs-meta) {
|
||||
color: var(--hl-meta, #A9A3C9);
|
||||
}
|
||||
|
||||
.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 */
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useState, type HTMLAttributes, type MouseEvent, type ReactNode } from 'react';
|
||||
import { Pagination } from '../Pagination/Pagination';
|
||||
import styles from './Table.module.css';
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface TableProps<T> {
|
||||
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>;
|
||||
}
|
||||
|
||||
export function Table<T>({
|
||||
@@ -35,6 +37,7 @@ export function Table<T>({
|
||||
pageSize: defaultPageSize,
|
||||
pageSizeOptions,
|
||||
onRowClick,
|
||||
getRowProps,
|
||||
}: TableProps<T>) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(defaultPageSize ?? 0);
|
||||
@@ -79,26 +82,43 @@ 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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,6 +58,9 @@ 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';
|
||||
|
||||
|
||||
@@ -74,7 +74,8 @@
|
||||
--border-width: 1.5px;
|
||||
|
||||
/* Shadows */
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.06);
|
||||
--shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.08), 0 0px 1px rgba(0, 0, 0, 0.04);
|
||||
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.10), 0 1px 2px rgba(0, 0, 0, 0.06);
|
||||
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.07), 0 2px 4px -1px rgba(0, 0, 0, 0.04);
|
||||
|
||||
/* Transitions */
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"root":["./src/App.tsx","./src/main.tsx"],"version":"5.8.3"}
|
||||
+81
-8
@@ -1,23 +1,96 @@
|
||||
/// <reference types="vitest/config" />
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
|
||||
import { playwright } from '@vitest/browser-playwright';
|
||||
const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
|
||||
const rootPackageJsonPath = path.resolve(dirname, '../package.json');
|
||||
const APP_VERSION = (() => {
|
||||
try {
|
||||
const json = JSON.parse(fs.readFileSync(rootPackageJsonPath, 'utf8')) as {
|
||||
version?: string;
|
||||
};
|
||||
return json.version ?? 'dev';
|
||||
} catch {
|
||||
return 'dev';
|
||||
}
|
||||
})();
|
||||
|
||||
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
|
||||
export default defineConfig({
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(APP_VERSION),
|
||||
},
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/environments': 'http://localhost:13000',
|
||||
'/credentials': 'http://localhost:13000', '/snippets': 'http://localhost:13000', '/snippets': 'http://localhost:13000',
|
||||
'/sessions': 'http://localhost:13000',
|
||||
'/scenarios': 'http://localhost:13000',
|
||||
'/keys': 'http://localhost:13000',
|
||||
'/login': 'http://localhost:13000',
|
||||
build: {
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id) {
|
||||
if (!id.includes('/client/src/') && !id.includes('/node_modules/')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (id.includes('/node_modules/lucide-react')) {
|
||||
return 'icons';
|
||||
}
|
||||
if (id.includes('/node_modules/monaco-editor') || id.includes('/node_modules/@monaco-editor')) {
|
||||
return 'editor';
|
||||
}
|
||||
if (
|
||||
id.includes('/node_modules/react-markdown')
|
||||
|| id.includes('/node_modules/remark-')
|
||||
|| id.includes('/node_modules/rehype-')
|
||||
|| id.includes('/node_modules/unified')
|
||||
|| id.includes('/node_modules/micromark')
|
||||
|| id.includes('/node_modules/mdast-')
|
||||
|| id.includes('/node_modules/hast-')
|
||||
|| id.includes('/node_modules/unist-')
|
||||
|| id.includes('/node_modules/vfile')
|
||||
) {
|
||||
return 'markdown';
|
||||
}
|
||||
if (
|
||||
id.includes('/node_modules/i18next')
|
||||
|| id.includes('/node_modules/react-i18next')
|
||||
) {
|
||||
return 'i18n';
|
||||
}
|
||||
if (id.includes('/node_modules/moment')) {
|
||||
return 'datetime';
|
||||
}
|
||||
if (id.includes('/node_modules/yaml')) {
|
||||
return 'yaml';
|
||||
}
|
||||
if (id.includes('/node_modules/')) {
|
||||
return 'vendor';
|
||||
}
|
||||
|
||||
if (id.includes('/src/pages/environment/')) {
|
||||
return 'environments';
|
||||
}
|
||||
if (id.includes('/src/pages/scenario/')) {
|
||||
return 'scenarios';
|
||||
}
|
||||
if (id.includes('/src/pages/run/')) {
|
||||
return 'runs';
|
||||
}
|
||||
if (id.includes('/src/pages/snippet/')) {
|
||||
return 'snippets';
|
||||
}
|
||||
if (id.includes('/src/pages/credential/')) {
|
||||
return 'credentials';
|
||||
}
|
||||
if (id.includes('/src/pages/session/')) {
|
||||
return 'sessions';
|
||||
}
|
||||
if (id.includes('/src/api/')) {
|
||||
return 'api';
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
services:
|
||||
server:
|
||||
build:
|
||||
context: ./server
|
||||
dockerfile: Dockerfile
|
||||
context: .
|
||||
dockerfile: server/Dockerfile
|
||||
ports:
|
||||
- "13000:3000"
|
||||
env_file:
|
||||
|
||||
+35
-35
@@ -1,45 +1,43 @@
|
||||
# Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Browser (React SPA — client/) │
|
||||
│ │
|
||||
│ EnvironmentsPage KeysPage │
|
||||
│ SessionsPage ScenariosPage │
|
||||
└───────────────────┬─────────────────────┘
|
||||
│ HTTP REST (:13000)
|
||||
│
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ Browser (React SPA - client/) │
|
||||
│ │
|
||||
│ Environments Credentials Snippets │
|
||||
│ Sessions Scenarios Runs │
|
||||
└─────────────────────────────┬────────────────────────┘
|
||||
│ HTTP REST (:13000)
|
||||
│
|
||||
MCP client (AI agent / VS Code Copilot)
|
||||
│ HTTP /mcp (Streamable MCP)
|
||||
│ HTTP /mcp (Streamable MCP)
|
||||
▼
|
||||
┌──────────────────────────────────────┐
|
||||
│ NestJS app (server/src/) │
|
||||
│ │
|
||||
│ McpService ← all MCP tools │
|
||||
│ │
|
||||
│ AuthService login + sessions │
|
||||
│ SessionService session CRUD │
|
||||
│ EnvironmentService environment CRUD │
|
||||
│ BrowserService ad-hoc browsing │
|
||||
│ CodeExecutorService sandboxed JS │
|
||||
│ │
|
||||
│ ScenarioService scenario CRUD │
|
||||
│ ScenarioSchedulerService │
|
||||
│ └─ @Interval(1 s) tick loop │
|
||||
└──────────────────┬───────────────────┘
|
||||
│ better-sqlite3 (TypeORM)
|
||||
▼
|
||||
data/sessions.db
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ NestJS app (server/src/) │
|
||||
│ │
|
||||
│ McpService all MCP tools │
|
||||
│ SessionService session persistence │
|
||||
│ SessionContextService live browser contexts │
|
||||
│ EnvironmentService environment CRUD + import │
|
||||
│ CredentialService credential CRUD + import │
|
||||
│ SnippetService snippet CRUD + import │
|
||||
│ BrowserService ad-hoc open/exec │
|
||||
│ CodeExecutorService sandboxed JS runtime │
|
||||
│ ScenarioService scenarios/steps/runs CRUD │
|
||||
│ ScenarioSchedulerService @Interval(1 s) run worker │
|
||||
└───────────────────────┬──────────────────────────────┘
|
||||
│ better-sqlite3 (TypeORM)
|
||||
▼
|
||||
data/sessions.db
|
||||
```
|
||||
|
||||
- **McpService** — registers every MCP tool and delegates to domain services.
|
||||
- **AuthService** — drives a Playwright browser to log in via a key descriptor; saves cookies + localStorage as a `Session`.
|
||||
- **SessionService** — stores and retrieves saved browser sessions.
|
||||
- **EnvironmentService** — stores named environments (URL maps) used by auth and scenarios.
|
||||
- **BrowserService** — ad-hoc, stateless `open_url` / `exec_code` operations outside the scenario scheduler.
|
||||
- **CodeExecutorService** — compiles and runs user-supplied Playwright JS inside a sandboxed `async` function with `page`, `context`, and `helpers` in scope.
|
||||
- **ScenarioService** — CRUD for scenarios, steps, runs, and run logs; import/export.
|
||||
- **ScenarioSchedulerService** — polls for pending step runs every second and executes them. All steps in the same run share **one browser instance** (see [scenario.md](scenario.md)).
|
||||
- **McpService** registers MCP tools and delegates to session, environment, browser, and scenario services.
|
||||
- **SessionService** persists session records in SQLite. **SessionContextService** manages live Playwright contexts for open sessions.
|
||||
- **EnvironmentService**, **CredentialService**, and **SnippetService** provide CRUD plus import/export upserts.
|
||||
- **BrowserService** handles stateless ad-hoc automation (`/open`, `/exec`) and session-aware browsing.
|
||||
- **CodeExecutorService** validates and executes user JS with `page`, `context`, and helper APIs.
|
||||
- **ScenarioService** manages scenarios, steps, credential aliases, runs, logs, and scenario import/export.
|
||||
- **ScenarioSchedulerService** polls pending runs every second and executes step runs to completion.
|
||||
|
||||
## Client (`client/`)
|
||||
|
||||
@@ -47,4 +45,6 @@ A React 19 + TypeScript SPA served separately by Vite during development. In Doc
|
||||
|
||||
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses HashRouter so the Vite proxy and server-side routes are never ambiguous.
|
||||
|
||||
The sidebar footer contains the theme switcher and the app version (injected from the workspace root `package.json` at build time).
|
||||
|
||||
See [development.md](development.md) for the full client tech stack and directory layout.
|
||||
+20
-8
@@ -26,8 +26,10 @@ Copy `.env.example` to `.env` and fill in the required values before running.
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `PORT` | `3000` | HTTP port |
|
||||
| `KEYS_DIR` | `keys` | Directory containing `*.json` key descriptors |
|
||||
| `KEYS_DIR` | `keys` | Directory for key material used by credential/snippet workflows |
|
||||
| `DB_PATH` | `data/sessions.db` | SQLite database file |
|
||||
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
|
||||
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to Chromium binary. Set automatically in Docker (`/usr/bin/chromium`). |
|
||||
|
||||
---
|
||||
@@ -59,7 +61,13 @@ The server listens on port **3000** by default.
|
||||
npm -w client run dev
|
||||
```
|
||||
|
||||
The Vite dev server runs on **http://localhost:5173** and proxies all API paths (`/environments`, `/sessions`, `/scenarios`, `/keys`, `/login`, `/mcp`) to the server at `localhost:3000`.
|
||||
The Vite dev server runs on **http://localhost:5173** and proxies these API prefixes to `localhost:13000` (or `localhost:3000` when running server locally):
|
||||
|
||||
- `/environments`
|
||||
- `/credentials`
|
||||
- `/snippets`
|
||||
- `/sessions`
|
||||
- `/scenarios`
|
||||
|
||||
**Production build**:
|
||||
|
||||
@@ -201,7 +209,7 @@ docker compose logs -f
|
||||
|
||||
## Client overview
|
||||
|
||||
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, sessions, keys, and scenarios.
|
||||
The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provides a browser UI for managing environments, credentials, snippets, sessions, scenarios, and runs.
|
||||
|
||||
### Tech stack
|
||||
|
||||
@@ -221,11 +229,11 @@ The client (`client/`) is a React 19 + TypeScript SPA built with Vite. It provid
|
||||
```
|
||||
client/
|
||||
src/
|
||||
api/ API client modules (environments, keys, sessions, scenarios)
|
||||
api/ API client modules (environments, credentials, snippets, sessions, scenarios)
|
||||
hooks/ useTheme (light/dark persistence)
|
||||
i18n/ i18next bootstrap + locales/en.json
|
||||
pages/ EnvironmentsPage, KeysPage, SessionsPage, ScenariosPage
|
||||
ui/ Reusable component library
|
||||
pages/ Environment/Credential/Snippet/Session/Scenario/Run pages
|
||||
ui/ Reusable component library
|
||||
Badge, Breadcrumbs, Button, Card, Input, Select,
|
||||
SidePanel, Table, ThemeSwitcher, Timestamp
|
||||
.storybook/
|
||||
@@ -239,10 +247,14 @@ Hash-based routing (`/#/path`) avoids conflicts with the Vite dev-server proxy.
|
||||
| Route | Page |
|
||||
|---|---|
|
||||
| `/#/environments` | Environment list |
|
||||
| `/#/keys` | Key list |
|
||||
| `/#/credentials` | Credential list |
|
||||
| `/#/snippets` | Snippet list |
|
||||
| `/#/sessions` | Session list |
|
||||
| `/#/scenarios` | Scenario list |
|
||||
| `/#/runs` | Cross-scenario runs list |
|
||||
|
||||
### Theming
|
||||
|
||||
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar header. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
|
||||
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar footer. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
|
||||
|
||||
The sidebar footer also shows the app version read from the workspace root `package.json` and injected via Vite `define`.
|
||||
@@ -1,20 +0,0 @@
|
||||
# Key descriptors
|
||||
|
||||
Each file in `KEYS_DIR` is named `<keyId>.json` and takes one of two forms:
|
||||
|
||||
**File key (EDS):**
|
||||
```json
|
||||
{
|
||||
"keyFile": "path/to/key.dat",
|
||||
"password": "secret"
|
||||
}
|
||||
```
|
||||
`keyFile` is resolved relative to `KEYS_DIR`.
|
||||
|
||||
**Login + password:**
|
||||
```json
|
||||
{
|
||||
"login": "user@example.com",
|
||||
"password": "secret"
|
||||
}
|
||||
```
|
||||
+35
-28
@@ -1,49 +1,56 @@
|
||||
# MCP tools
|
||||
|
||||
## Auth / session
|
||||
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport).
|
||||
|
||||
The server currently registers the following tools.
|
||||
|
||||
## Sessions
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_keys` | List available key IDs from `KEYS_DIR` |
|
||||
| `login` | Log in with a key against an environment; stores resulting session |
|
||||
| `list_sessions` | Paginated list of saved sessions |
|
||||
| `delete_session` | Delete a session by ID |
|
||||
| `list_sessions` | List stored sessions (paginated) |
|
||||
| `delete_session` | Delete a session by UUID |
|
||||
|
||||
## Environments
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_environments` | Paginated list of environments |
|
||||
| `get_environment` | Get one environment by ID |
|
||||
| `create_environment` | Create an environment (`name` + `urls` map) |
|
||||
| `update_environment` | Update name / urls |
|
||||
| `delete_environment` | Delete by ID |
|
||||
| `list_environments` | List environments (paginated) |
|
||||
| `get_environment` | Get one environment by UUID |
|
||||
| `create_environment` | Create environment (`name`, `urls`) |
|
||||
| `update_environment` | Update environment (`id`, optional `name`/`urls`) |
|
||||
| `delete_environment` | Delete environment by UUID |
|
||||
|
||||
`urls` is a free-form map. Recognised keys: `id_url` (auth server), `cabinet_url` (cabinet redirect target), `admin_url`.
|
||||
`urls` is a free-form key/value map. Common keys: `id_url`, `cabinet_url`, `admin_url`.
|
||||
|
||||
## Browser (ad-hoc, stateless)
|
||||
## Browser (ad-hoc)
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `open_url` | Navigate to a URL and return page content / reader-mode text |
|
||||
| `exec_code` | Run Playwright JS in a session's browser context |
|
||||
| `open_url` | Open URL with optional `sessionName`, return page/title/content |
|
||||
| `exec_code` | Execute Playwright JS — script receives a single `context` argument (see `scenario.md`). Optional `environmentId` (UUID) resolves environment from DB for `context.getEnv()`. Optional `credentials` (`{ alias: credentialUUID }`) resolves credentials from DB for `context.getCredential(alias)`. |
|
||||
|
||||
## Scenarios
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `list_scenarios` | Paginated list |
|
||||
| `get_scenario` | Fetch scenario with all steps |
|
||||
| `create_scenario` | Create a new scenario by name |
|
||||
| `update_scenario` | Rename |
|
||||
| `delete_scenario` | Delete (cascades to steps and runs) |
|
||||
| `create_scenario_step` | Add a step |
|
||||
| `get_scenario_step` | Fetch one step |
|
||||
| `list_scenarios` | List scenarios (paginated) |
|
||||
| `get_scenario` | Get scenario with steps |
|
||||
| `create_scenario` | Create scenario by `name` |
|
||||
| `update_scenario` | Rename scenario |
|
||||
| `delete_scenario` | Delete scenario |
|
||||
| `create_scenario_step` | Add step to scenario |
|
||||
| `get_scenario_step` | Get one step |
|
||||
| `update_scenario_step` | Update step fields |
|
||||
| `delete_scenario_step` | Remove a step |
|
||||
| `list_scenario_runs` | Paginated run history (with optional status filter) |
|
||||
| `run_scenario` | Trigger an immediate run |
|
||||
| `get_scenario_run` | Get a run with all step runs and their outputs |
|
||||
| `wait_for_scenario_run` | Block until run reaches `pass`/`fail`, return full run |
|
||||
| `export_scenario` | Export scenario as a portable JSON payload |
|
||||
| `import_scenario` | Import a scenario from an export payload |
|
||||
| `delete_scenario_step` | Delete step |
|
||||
| `list_scenario_runs` | List runs for a scenario |
|
||||
| `run_scenario` | Trigger run for scenario |
|
||||
| `get_scenario_run` | Get run with step runs and logs |
|
||||
| `wait_for_scenario_run` | Wait until run is `pass` or `fail` |
|
||||
| `export_scenario` | Export scenario payload |
|
||||
| `import_scenario` | Import scenario payload |
|
||||
|
||||
## Notes
|
||||
|
||||
- Tool IDs and entity IDs are UUIDs.
|
||||
- `create_scenario_step` schema still accepts legacy `type`/`sessionName` fields for compatibility. Current scheduler executes `execCode` plus optional `validateCode` and does not branch by step type.
|
||||
+60
-54
@@ -1,80 +1,86 @@
|
||||
# Scenario execution
|
||||
|
||||
When a scenario is run, the scheduler creates a `ScenarioRun` with one `ScenarioRunStep` per step. Steps are executed **in order** (by `step.order`), one per scheduler tick.
|
||||
When a scenario run is created, the server creates one `ScenarioRunStep` per scenario step.
|
||||
|
||||
**All steps in the same run share a single Playwright browser instance.** The browser is created on the first `exec` or `sign` step (using session cookies + localStorage), reused for every subsequent step, and closed when the run finishes (pass or fail).
|
||||
- Step runs are ordered by `step.order`.
|
||||
- First step run starts as `pending`; the rest start as `waiting`.
|
||||
- Scheduler tick (`@Interval(1000)`) picks pending runs and processes steps in order.
|
||||
- Steps in the same run share one Playwright browser/context/page.
|
||||
|
||||
## Step types
|
||||
## Execution model
|
||||
|
||||
### `login`
|
||||
Current scheduler behavior is exec-centric:
|
||||
|
||||
Authenticates in a **separate, ephemeral browser** and saves the resulting session to the database. Subsequent exec/sign steps load that session into the shared browser.
|
||||
- `execCode` is required for a step to pass.
|
||||
- `validateCode` is optional and runs after `execCode`.
|
||||
- Legacy step type metadata may still appear in MCP payloads, but run execution is not branched by step type.
|
||||
|
||||
`execCode` must be a JSON object:
|
||||
```json
|
||||
{ "keyId": "3137411915", "environmentName": "liquio-diia-stg" }
|
||||
```
|
||||
## Script runtime
|
||||
|
||||
### `exec`
|
||||
|
||||
Runs arbitrary Playwright JS on the **shared page**. The page carries over state from the previous step (URL, form inputs, cookies, etc.).
|
||||
|
||||
`execCode` is executed as the body of an `async` function with these variables in scope:
|
||||
|
||||
- `page` — current Playwright `Page`
|
||||
- `context` — current Playwright `BrowserContext`
|
||||
- `helpers.dumpDom(selector?)` — returns a simplified DOM string
|
||||
- `helpers.getStepOutput(order)` — returns the JSON-parsed `output` of a previous step. Positive values are absolute step orders; negative values are relative to the current step (`-1` = previous step).
|
||||
|
||||
Any value returned from `execCode` is JSON-serialised and stored as the `output` field on the `ScenarioRunStep` record. Subsequent steps can read it via `helpers.getStepOutput()`.
|
||||
`execCode` and `validateCode` execute as async JavaScript with a single `context` argument:
|
||||
|
||||
```js
|
||||
// example execCode
|
||||
await page.goto('https://cabinet.example.com/tasks/create/987825');
|
||||
await page.locator('input[name="institution"]').fill('caltech');
|
||||
await page.locator('button:has-text("Далі")').click();
|
||||
await page.waitForLoadState('networkidle');
|
||||
return page.url(); // stored in ScenarioRunStep.output
|
||||
async (context) => {
|
||||
// your code here
|
||||
}
|
||||
```
|
||||
|
||||
### `sign`
|
||||
Available in scope:
|
||||
|
||||
Performs EDS signing on the **current shared page** using a key from `KEYS_DIR`. The step clicks the sign widget, selects the file key method, uploads the key file, enters the password, and submits — all without requiring the step author to handle key material in their code.
|
||||
- `context.page`: Playwright `Page`
|
||||
- `context.browser`: Playwright `BrowserContext`
|
||||
- `context.env`: shallow copy of environment key/value map
|
||||
- `context.getEnv(key)`: required environment value lookup (throws if missing)
|
||||
- `context.getCredential(alias)`: credential payload assigned to the scenario alias
|
||||
- `context.getStepOutput(order)`: prior step output by absolute order (`1`, `2`, ...) or relative (`-1` = previous step)
|
||||
- `context.dumpDom(selector?)`: simplified DOM snapshot
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: structured step logs
|
||||
- `context.runSnippet(name, ...args)`: execute stored snippet code with the same context
|
||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||
|
||||
`execCode` must be a JSON object:
|
||||
```json
|
||||
{ "keyId": "3137411915" }
|
||||
```
|
||||
`validateCode` additionally receives `result` in scope, which is the value returned by `execCode`.
|
||||
|
||||
## Validation code
|
||||
## Validation contract
|
||||
|
||||
Any step type optionally accepts `validateCode` — Playwright JS that runs on the shared page **after** the main action and must return a result evaluated as:
|
||||
`validateCode` may return:
|
||||
|
||||
```js
|
||||
return { success: true, description: 'Application created' };
|
||||
return { success: true, description: 'ok' };
|
||||
// or
|
||||
return { success: false, description: 'Expected success banner not found' };
|
||||
// or simply
|
||||
return someBoolean;
|
||||
return false;
|
||||
```
|
||||
|
||||
If `success` is false the step (and the whole run) fails with the provided `description`.
|
||||
Interpretation:
|
||||
|
||||
## Run statuses
|
||||
- Boolean: `true` = pass, `false` = fail
|
||||
- Object: `success` controls pass/fail; `description` is persisted as step description
|
||||
|
||||
`pending` → `in_progress` → `pass` | `fail`
|
||||
On validation failure, the step fails and the run is marked `fail`.
|
||||
|
||||
Individual step runs also expose `waiting` (not yet reached) and `cancelled` (run failed before this step).
|
||||
## Statuses
|
||||
|
||||
## Adding a new scenario (example workflow)
|
||||
Run status:
|
||||
|
||||
```
|
||||
1. create_environment (if not already present)
|
||||
2. create_scenario → get scenarioId
|
||||
3. create_scenario_step type=login, order=0
|
||||
4. create_scenario_step type=exec, order=1 (navigate + fill form)
|
||||
5. create_scenario_step type=sign, order=2
|
||||
6. create_scenario_step type=exec, order=3 (validateCode checks success banner)
|
||||
7. run_scenario → get runId
|
||||
8. wait_for_scenario_run (blocks until pass/fail, returns full run with outputs)
|
||||
```
|
||||
- `pending`
|
||||
- `in_progress`
|
||||
- `pass`
|
||||
- `fail`
|
||||
|
||||
Run-step status:
|
||||
|
||||
- `waiting`
|
||||
- `pending`
|
||||
- `in_progress`
|
||||
- `pass`
|
||||
- `fail`
|
||||
- `cancelled`
|
||||
|
||||
## Example workflow
|
||||
|
||||
1. Create environment
|
||||
2. Create credentials and snippets (optional but common)
|
||||
3. Create scenario
|
||||
4. Add ordered steps (`execCode`, optional `validateCode`)
|
||||
5. Assign credentials to scenario aliases when needed
|
||||
6. Run scenario
|
||||
7. Wait for run completion and inspect run logs/outputs
|
||||
Generated
+1565
-9
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.4.0",
|
||||
"version": "1.6.0",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"server",
|
||||
|
||||
+9
-6
@@ -4,11 +4,13 @@ FROM node:22-slim AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci -w server
|
||||
|
||||
COPY nest-cli.json tsconfig*.json ./
|
||||
COPY src ./src
|
||||
RUN npm run build
|
||||
COPY server/nest-cli.json ./server/
|
||||
COPY server/tsconfig*.json ./server/
|
||||
COPY server/src ./server/src
|
||||
RUN npm run -w server build
|
||||
|
||||
# ── Runtime stage ─────────────────────────────────────────────────────────────
|
||||
FROM node:22-slim AS runtime
|
||||
@@ -27,9 +29,10 @@ ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev
|
||||
COPY server/package.json ./server/
|
||||
RUN npm ci --omit=dev -w server
|
||||
|
||||
COPY --from=builder /app/dist ./dist
|
||||
COPY --from=builder /app/server/dist ./dist
|
||||
|
||||
# Runtime directories (keys and SQLite DB mounted via volumes)
|
||||
RUN mkdir -p data keys
|
||||
|
||||
Generated
-11239
File diff suppressed because it is too large.
Load diff
@@ -27,6 +27,7 @@
|
||||
"@nestjs/schedule": "^6.1.1",
|
||||
"@nestjs/swagger": "^11.2.6",
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"@playwright/test": "^1.59.1",
|
||||
"acorn": "^8.16.0",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
@@ -37,6 +38,7 @@
|
||||
"rxjs": "^7.8.2",
|
||||
"swagger-ui-express": "^5.0.1",
|
||||
"typeorm": "^0.3.28",
|
||||
"yaml": "^2.8.3",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
+11
-13
@@ -1,24 +1,23 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { ScheduleModule } from "@nestjs/schedule";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { AuthModule } from "./auth/auth.module";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { BrowserModule } from "./browser/browser.module";
|
||||
import { SessionEntity } from "./session/session.entity";
|
||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||
import { CredentialEntity } from "./credential/credential.entity";
|
||||
import { CredentialModule } from "./credential/credential.module";
|
||||
import { EnvironmentEntity } from "./environment/environment.entity";
|
||||
import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { McpModule } from "./mcp/mcp.module";
|
||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
||||
import { ScenarioCredentialEntity } from "./scenario/scenario-credential.entity";
|
||||
import { ScenarioRunLogEntity } from "./scenario/scenario-run-log.entity";
|
||||
import { ScenarioRunStepEntity } from "./scenario/scenario-run-step.entity";
|
||||
import { ScenarioRunEntity } from "./scenario/scenario-run.entity";
|
||||
import { ScenarioStepEntity } from "./scenario/scenario-step.entity";
|
||||
import { ScenarioEntity } from "./scenario/scenario.entity";
|
||||
import { ScenarioModule } from "./scenario/scenario.module";
|
||||
import { SessionEntity } from "./session/session.entity";
|
||||
import { SnippetEntity } from "./snippet/snippet.entity";
|
||||
import { SnippetModule } from "./snippet/snippet.module";
|
||||
|
||||
@@ -50,7 +49,6 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
synchronize: true,
|
||||
}),
|
||||
}),
|
||||
AuthModule,
|
||||
BrowserModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Body, Controller, Get, Post } from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { AuthService } from "./auth.service";
|
||||
import { LoginDto } from "./dto/login.dto";
|
||||
|
||||
@ApiTags("auth")
|
||||
@Controller()
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Get("keys")
|
||||
@ApiOperation({
|
||||
summary: "List available key identifiers from the keys directory",
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: "List of key names",
|
||||
schema: {
|
||||
properties: { keys: { type: "array", items: { type: "string" } } },
|
||||
},
|
||||
})
|
||||
listKeys(): { keys: string[] } {
|
||||
return { keys: this.authService.listKeys() };
|
||||
}
|
||||
|
||||
@Post("login")
|
||||
@ApiOperation({
|
||||
summary: "Log in using a file key and return the session token",
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 201,
|
||||
description: "Login successful",
|
||||
schema: {
|
||||
properties: {
|
||||
token: { type: "string" },
|
||||
sessionName: { type: "string" },
|
||||
},
|
||||
},
|
||||
})
|
||||
@ApiResponse({ status: 400, description: "Key not found or invalid" })
|
||||
@ApiResponse({ status: 500, description: "Automation failed" })
|
||||
login(
|
||||
@Body() dto: LoginDto,
|
||||
): Promise<{ token: string; sessionName: string }> {
|
||||
return this.authService.login(
|
||||
dto.key,
|
||||
dto.environmentName,
|
||||
dto.sessionName,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthController } from "./auth.controller";
|
||||
import { AuthService } from "./auth.service";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
|
||||
@Module({
|
||||
imports: [SessionModule, EnvironmentModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
exports: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -1,265 +0,0 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
InternalServerErrorException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { AppConfig } from "../config/app.config";
|
||||
import { chromium } from "playwright";
|
||||
import type { Page } from "playwright";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import * as crypto from "crypto";
|
||||
import { SessionService } from "../session/session.service";
|
||||
import { SessionContextService } from "../session/session-context.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
|
||||
interface KeyDescriptor {
|
||||
keyFile?: string;
|
||||
login?: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
private readonly logger = new TraceLogger(AuthService.name);
|
||||
private readonly keysDir: string;
|
||||
|
||||
constructor(
|
||||
private readonly config: ConfigService<AppConfig, true>,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
) {
|
||||
this.keysDir = path.resolve(this.config.get("KEYS_DIR"));
|
||||
}
|
||||
|
||||
listKeys(): string[] {
|
||||
if (!fs.existsSync(this.keysDir)) return [];
|
||||
return fs
|
||||
.readdirSync(this.keysDir)
|
||||
.filter((f) => f.endsWith(".json"))
|
||||
.map((f) => path.basename(f, ".json"));
|
||||
}
|
||||
|
||||
private loadKeyDescriptor(keyId: string): KeyDescriptor {
|
||||
const keyJsonPath = path.join(this.keysDir, `${keyId}.json`);
|
||||
if (!fs.existsSync(keyJsonPath)) {
|
||||
throw new BadRequestException(`Key not found: ${keyId}`);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(keyJsonPath, "utf-8")) as KeyDescriptor;
|
||||
} catch (err) {
|
||||
throw new BadRequestException(`Cannot read key descriptor: ${keyId}`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async login(
|
||||
keyId: string,
|
||||
environmentName: string,
|
||||
sessionName?: string,
|
||||
): Promise<{ token: string; sessionName: string }> {
|
||||
const resolvedSession = sessionName ?? crypto.randomUUID();
|
||||
|
||||
const env = await this.environmentService
|
||||
.findAll()
|
||||
.then(({ data }) => data.find((e) => e.name === environmentName));
|
||||
if (!env)
|
||||
throw new NotFoundException(`Environment "${environmentName}" not found`);
|
||||
|
||||
const loginUrl = env.urls.id_url;
|
||||
const cabinetUrl = env.urls.cabinet_url;
|
||||
if (!loginUrl)
|
||||
throw new BadRequestException(
|
||||
`Environment "${environmentName}" is missing id_url`,
|
||||
);
|
||||
if (!cabinetUrl)
|
||||
throw new BadRequestException(
|
||||
`Environment "${environmentName}" is missing cabinet_url`,
|
||||
);
|
||||
|
||||
const descriptor = this.loadKeyDescriptor(keyId);
|
||||
const useLoginPassword = !!descriptor.login;
|
||||
|
||||
if (!useLoginPassword) {
|
||||
if (!descriptor.keyFile) {
|
||||
throw new BadRequestException(
|
||||
`Key descriptor for "${keyId}" must have either "login" or "keyFile"`,
|
||||
);
|
||||
}
|
||||
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
|
||||
if (!fs.existsSync(keyFilePath)) {
|
||||
throw new BadRequestException(
|
||||
`Key file not found: ${descriptor.keyFile}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
this.logger.log(`Navigating to ${loginUrl}`);
|
||||
await page.goto(loginUrl, { waitUntil: "networkidle" });
|
||||
|
||||
if (useLoginPassword) {
|
||||
// Click "Логін і пароль" auth method
|
||||
await page.locator('p[aria-label="Логін і пароль"]').click();
|
||||
|
||||
// Fill login and password
|
||||
await page.getByLabel("Електронна пошта").fill(descriptor.login!);
|
||||
await page.getByLabel("Пароль").fill(descriptor.password);
|
||||
|
||||
// Click "Увійти"
|
||||
await page.locator('button:has-text("Увійти")').click();
|
||||
} else {
|
||||
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile!);
|
||||
|
||||
// Click "Файловий ключ" button
|
||||
await page.getByText("Файловий ключ").click();
|
||||
|
||||
// Upload key file via hidden file input
|
||||
const fileInput = page.locator(
|
||||
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
|
||||
);
|
||||
await fileInput.setInputFiles(keyFilePath);
|
||||
|
||||
// Enter password
|
||||
await page
|
||||
.locator("#id-app-login-file-key-password")
|
||||
.fill(descriptor.password);
|
||||
|
||||
// Click "Продовжити"
|
||||
await page.locator("#id-app-login-file-key-sign-button").click();
|
||||
}
|
||||
|
||||
// Wait until redirected to cabinet
|
||||
this.logger.log(`Waiting for redirect to ${cabinetUrl}`);
|
||||
await page.waitForURL(cabinetUrl, { timeout: 30000 });
|
||||
|
||||
// Extract token from localStorage
|
||||
const token = await page.evaluate(() => localStorage.getItem("token"));
|
||||
|
||||
if (!token) {
|
||||
throw new InternalServerErrorException(
|
||||
"Login succeeded but token was not found in localStorage",
|
||||
);
|
||||
}
|
||||
|
||||
// Capture all cookies and localStorage from the browser context
|
||||
const cookies = await context.cookies();
|
||||
const localStorageData = await page.evaluate(() => {
|
||||
const entries: Record<string, string> = {};
|
||||
for (let i = 0; i < window.localStorage.length; i++) {
|
||||
const k = window.localStorage.key(i);
|
||||
if (k !== null) entries[k] = window.localStorage.getItem(k) ?? "";
|
||||
}
|
||||
return entries;
|
||||
});
|
||||
|
||||
await this.sessionService.upsert(
|
||||
resolvedSession,
|
||||
token,
|
||||
cookies,
|
||||
localStorageData,
|
||||
);
|
||||
|
||||
// Register the live Playwright context — browser stays open for reuse
|
||||
this.sessionContextService.register(
|
||||
resolvedSession,
|
||||
browser,
|
||||
context,
|
||||
page,
|
||||
);
|
||||
|
||||
this.logger.log(
|
||||
`Login successful for key ${keyId}, session: ${resolvedSession}`,
|
||||
);
|
||||
return { token, sessionName: resolvedSession };
|
||||
} catch (err) {
|
||||
// Close browser only on failure — on success it is kept alive in SessionContextService
|
||||
await browser.close().catch(() => {});
|
||||
if (
|
||||
err instanceof BadRequestException ||
|
||||
err instanceof InternalServerErrorException
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
this.logger.error(`Login failed: ${(err as Error).message}`);
|
||||
throw new InternalServerErrorException(
|
||||
`Login automation failed: ${(err as Error).message}`,
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async signWithKey(keyId: string, page: Page): Promise<void> {
|
||||
const descriptor = this.loadKeyDescriptor(keyId);
|
||||
|
||||
if (!descriptor.keyFile) {
|
||||
throw new BadRequestException(
|
||||
`Key descriptor for "${keyId}" must have "keyFile" to sign`,
|
||||
);
|
||||
}
|
||||
|
||||
const keyFilePath = path.resolve(this.keysDir, descriptor.keyFile);
|
||||
if (!fs.existsSync(keyFilePath)) {
|
||||
throw new BadRequestException(
|
||||
`Key file not found: ${descriptor.keyFile}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.log(`Signing with key ${keyId} on page: ${page.url()}`);
|
||||
|
||||
// Open the EDS sign widget (skip if it's already open)
|
||||
const isSignDialogOpen = await page
|
||||
.locator('input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]')
|
||||
.isVisible()
|
||||
.catch(() => false);
|
||||
if (!isSignDialogOpen) {
|
||||
await page
|
||||
.locator("button")
|
||||
.filter({ hasText: /підпис|sign/i })
|
||||
.first()
|
||||
.click();
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
// Select the file key tab inside the widget
|
||||
await page
|
||||
.locator('button, [role="tab"], li')
|
||||
.filter({ hasText: /файлов|file key/i })
|
||||
.first()
|
||||
.click();
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// Upload the key file
|
||||
const fileInput = page.locator(
|
||||
'input[accept=".dat,.pfx,.pk8,.zs2,.jks"][type="file"]',
|
||||
);
|
||||
await fileInput.setInputFiles(keyFilePath);
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// Enter password
|
||||
await page.locator('input[type="password"]').fill(descriptor.password);
|
||||
await page.waitForTimeout(200);
|
||||
|
||||
// Submit
|
||||
await page
|
||||
.locator("button")
|
||||
.filter({ hasText: /підпис|sign|підтвер/i })
|
||||
.last()
|
||||
.click();
|
||||
await page.waitForLoadState("networkidle");
|
||||
|
||||
this.logger.log(`Sign completed for key ${keyId}`);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({
|
||||
description:
|
||||
"Key identifier — filename (without extension) from the keys/ directory",
|
||||
example: "3273334361",
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
key: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: "Environment name to resolve login/cabinet URLs from",
|
||||
example: "liquio-diia-stg",
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
environmentName: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Session name to store credentials under. Auto-generated UUID if omitted.",
|
||||
example: "my-test-session",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sessionName?: string;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Body, Controller, Post } from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { OpenDto } from "./dto/open.dto";
|
||||
import { CredentialService } from "../credential/credential.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
import { BrowserService, ExecResult, OpenResult } from "./browser.service";
|
||||
import { ExecDto } from "./dto/exec.dto";
|
||||
import { OpenDto } from "./dto/open.dto";
|
||||
|
||||
@ApiTags("browser")
|
||||
@Controller()
|
||||
@@ -11,6 +13,8 @@ export class BrowserController {
|
||||
constructor(
|
||||
private readonly browserService: BrowserService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly credentialService: CredentialService,
|
||||
) {}
|
||||
|
||||
@Post("open")
|
||||
@@ -54,8 +58,32 @@ export class BrowserController {
|
||||
@ApiResponse({ status: 400, description: "Invalid input" })
|
||||
@ApiResponse({ status: 404, description: "Session not found" })
|
||||
@ApiResponse({ status: 500, description: "Execution failed" })
|
||||
exec(@Body() dto: ExecDto): Promise<ExecResult> {
|
||||
async exec(@Body() dto: ExecDto): Promise<ExecResult> {
|
||||
this.codeExecutor.validate(dto.code);
|
||||
return this.browserService.exec(dto.sessionName, dto.code, dto.url);
|
||||
|
||||
// Resolve environment from DB
|
||||
let environment: Record<string, string | undefined> | undefined;
|
||||
if (dto.environmentId) {
|
||||
const env = await this.environmentService.findOne(dto.environmentId);
|
||||
environment = env.data;
|
||||
}
|
||||
|
||||
// Resolve credentials from DB (alias → payload)
|
||||
let credentials: Record<string, unknown> | undefined;
|
||||
if (dto.credentials && Object.keys(dto.credentials).length > 0) {
|
||||
credentials = {};
|
||||
for (const [alias, credId] of Object.entries(dto.credentials)) {
|
||||
const cred = await this.credentialService.findOne(credId);
|
||||
credentials[alias] = cred.data ? JSON.parse(cred.data) : {};
|
||||
}
|
||||
}
|
||||
|
||||
return this.browserService.exec(
|
||||
dto.sessionName,
|
||||
dto.code,
|
||||
dto.url,
|
||||
environment,
|
||||
credentials,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
import { CredentialModule } from "../credential/credential.module";
|
||||
import { EnvironmentModule } from "../environment/environment.module";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { SnippetModule } from "../snippet/snippet.module";
|
||||
import { BrowserController } from "./browser.controller";
|
||||
import { BrowserService } from "./browser.service";
|
||||
import { SessionModule } from "../session/session.module";
|
||||
import { CodeExecutorModule } from "../code-executor/code-executor.module";
|
||||
|
||||
@Module({
|
||||
imports: [SessionModule, CodeExecutorModule],
|
||||
imports: [
|
||||
SessionModule,
|
||||
CodeExecutorModule,
|
||||
SnippetModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
],
|
||||
controllers: [BrowserController],
|
||||
providers: [BrowserService],
|
||||
exports: [BrowserService],
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
} from "@nestjs/common";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { chromium } from "playwright";
|
||||
import type { BrowserContext } from "playwright";
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import { JSDOM } from "jsdom";
|
||||
import { SessionContextService } from "../session/session-context.service";
|
||||
import type { BrowserContext, Cookie } from "playwright";
|
||||
import { chromium } from "playwright";
|
||||
import type {
|
||||
ExecResult,
|
||||
ScriptLogger,
|
||||
} from "../code-executor/code-executor.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import type { ExecResult } from "../code-executor/code-executor.service";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import { SessionContextService } from "../session/session-context.service";
|
||||
import { SessionService } from "../session/session.service";
|
||||
import { SnippetService } from "../snippet/snippet.service";
|
||||
|
||||
export type { ExecResult } from "../code-executor/code-executor.service";
|
||||
|
||||
@@ -26,9 +32,55 @@ export class BrowserService {
|
||||
|
||||
constructor(
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
private readonly sessionService: SessionService,
|
||||
private readonly codeExecutor: CodeExecutorService,
|
||||
private readonly snippetService: SnippetService,
|
||||
) {}
|
||||
|
||||
private parseCookies(raw: string | null | undefined): Cookie[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return Array.isArray(parsed) ? (parsed as Cookie[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private async getOrCreateNamedHandle(sessionName: string) {
|
||||
try {
|
||||
return await this.sessionContextService.getHandle(sessionName);
|
||||
} catch {
|
||||
this.logger.log(
|
||||
`[${sessionName}] creating session context automatically`,
|
||||
);
|
||||
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
const existing = await this.sessionService.findBySessionName(sessionName);
|
||||
const cookies = this.parseCookies(existing?.cookies);
|
||||
if (cookies.length > 0) {
|
||||
await context.addCookies(cookies);
|
||||
}
|
||||
|
||||
this.sessionContextService.register(sessionName, browser, context, page);
|
||||
|
||||
await this.sessionService.upsert(
|
||||
sessionName,
|
||||
existing?.token ?? `auto:${sessionName}`,
|
||||
await context.cookies(),
|
||||
{},
|
||||
);
|
||||
|
||||
return { browser, context, page };
|
||||
}
|
||||
}
|
||||
|
||||
private rethrow(err: unknown, label: string, operation: string): never {
|
||||
if (err instanceof HttpException) {
|
||||
throw err;
|
||||
@@ -90,8 +142,7 @@ export class BrowserService {
|
||||
this.logger.log(`[${label}] open: ${url}`);
|
||||
|
||||
if (sessionName) {
|
||||
const { context } =
|
||||
await this.sessionContextService.getHandle(sessionName);
|
||||
const { context } = await this.getOrCreateNamedHandle(sessionName);
|
||||
try {
|
||||
return await this.extractContent(context, url, readerMode, selector);
|
||||
} catch (err) {
|
||||
@@ -118,20 +169,34 @@ export class BrowserService {
|
||||
sessionName: string | undefined,
|
||||
code: string,
|
||||
url?: string,
|
||||
environment?: EnvironmentData,
|
||||
credentials?: Record<string, unknown>,
|
||||
): Promise<ExecResult> {
|
||||
const label = sessionName ?? "anonymous";
|
||||
|
||||
if (sessionName) {
|
||||
const { page, context } =
|
||||
await this.sessionContextService.getHandle(sessionName);
|
||||
const { page, context } = await this.getOrCreateNamedHandle(sessionName);
|
||||
this.logger.log(`[${label}] exec: using persistent context`);
|
||||
const snippets = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
try {
|
||||
if (url) {
|
||||
this.logger.log(`[${label}] exec: navigating to ${url}`);
|
||||
await page.goto(url, { waitUntil: "networkidle" });
|
||||
}
|
||||
this.logger.log(`[${label}] exec: running user code`);
|
||||
const result = await this.codeExecutor.execute(page, context, code);
|
||||
const scriptLogger: ScriptLogger = (level, msg) =>
|
||||
this.logger[level](`[${label}] script: ${msg}`);
|
||||
const result = await this.codeExecutor.execute({
|
||||
page,
|
||||
browser: context,
|
||||
code,
|
||||
log: scriptLogger,
|
||||
credentials,
|
||||
environment,
|
||||
snippets,
|
||||
});
|
||||
this.logger.log(`[${label}] exec: done`);
|
||||
return result;
|
||||
} catch (err) {
|
||||
@@ -140,13 +205,20 @@ export class BrowserService {
|
||||
}
|
||||
|
||||
// Anonymous — ephemeral browser
|
||||
const snippetMap = await this.snippetService
|
||||
.buildSnippetMap()
|
||||
.catch(() => ({}) as Record<string, string>);
|
||||
|
||||
// TODO: instantiate one browser per server instance and reuse contexts for anonymous sessions,
|
||||
// instead of launching a new browser for each request.
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
|
||||
});
|
||||
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const browserContext = await browser.newContext();
|
||||
const page = await browserContext.newPage();
|
||||
|
||||
if (url) {
|
||||
this.logger.log(`[${label}] exec: navigating to ${url}`);
|
||||
@@ -154,7 +226,17 @@ export class BrowserService {
|
||||
}
|
||||
|
||||
this.logger.log(`[${label}] exec: running user code`);
|
||||
const result = await this.codeExecutor.execute(page, context, code);
|
||||
const scriptLogger: ScriptLogger = (level, msg) =>
|
||||
this.logger[level](`[${label}] script: ${msg}`);
|
||||
const result = await this.codeExecutor.execute({
|
||||
page,
|
||||
browser: browserContext,
|
||||
code,
|
||||
log: scriptLogger,
|
||||
credentials,
|
||||
environment,
|
||||
snippets: snippetMap,
|
||||
});
|
||||
this.logger.log(`[${label}] exec: done`);
|
||||
return result;
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsOptional, IsString, IsUrl } from "class-validator";
|
||||
import { IsObject, IsOptional, IsString, IsUUID, IsUrl } from "class-validator";
|
||||
|
||||
export class ExecDto {
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Session name previously created by POST /login. If omitted, executes without a stored session.",
|
||||
"Optional named browser session. If it does not exist yet, it is created automatically.",
|
||||
example: "test-session-1",
|
||||
})
|
||||
@IsOptional()
|
||||
@@ -22,9 +22,27 @@ export class ExecDto {
|
||||
|
||||
@ApiProperty({
|
||||
description:
|
||||
"JavaScript code to execute. Receives `page` (Playwright Page) and `context` (BrowserContext) as arguments. May be async. Return value is serialised and returned.",
|
||||
example: "return await page.title();",
|
||||
"Async JavaScript body. Use `context.page` for Playwright, `context.getEnv(key)`, `context.getCredential(alias)`, `context.runSnippet(name, ...args)`.",
|
||||
example: "return await context.page.title();",
|
||||
})
|
||||
@IsString()
|
||||
code: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"UUID of an existing environment entity. Its key/value data is available via `context.env` and `context.getEnv()` in the script.",
|
||||
example: "a6a1fca5-0f61-48ed-ae97-011dc7236387",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
environmentId?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Map of alias → credential UUID. Each credential is loaded from the DB and available via `context.getCredential(alias)` in the script.",
|
||||
example: { pkcs_key: "e3b0c442-98fc-11d8-9669-0800200c9a66" },
|
||||
})
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
credentials?: Record<string, string>;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { IsBoolean, IsOptional, IsString, IsUrl } from "class-validator";
|
||||
export class OpenDto {
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Session name previously created by POST /login. If omitted, opens the URL without a stored session.",
|
||||
"Optional named browser session. If it does not exist yet, it is created automatically.",
|
||||
example: "test-session-1",
|
||||
})
|
||||
@IsOptional()
|
||||
|
||||
@@ -3,11 +3,13 @@ import {
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
} from "@nestjs/common";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { expect as playwrightExpect } from "@playwright/test";
|
||||
import { parse } from "acorn";
|
||||
import type { Page, BrowserContext } from "playwright";
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { DomNode } from "./dom-helpers";
|
||||
import { dumpDom } from "./dom-helpers";
|
||||
import type { EnvironmentUrls } from "../environment/environment.entity";
|
||||
|
||||
export interface ExecResult {
|
||||
result: unknown;
|
||||
@@ -18,6 +20,41 @@ export type ScriptLogger = (
|
||||
message: string,
|
||||
) => void;
|
||||
|
||||
/** The `context` object available inside user scripts as the sole argument. */
|
||||
export interface ScriptContext {
|
||||
/** Playwright Page for the current session. */
|
||||
page: Page;
|
||||
/** Playwright BrowserContext for the current session. */
|
||||
browser: BrowserContext;
|
||||
/** All environment values for the current run (empty object if none set). */
|
||||
env: Record<string, string | undefined>;
|
||||
/** Returns the environment value for `key`, or throws if not defined. */
|
||||
getEnv: (key: string) => string;
|
||||
/** Returns the credential value for `alias`, or throws if not found. */
|
||||
getCredential: (alias: string) => unknown;
|
||||
/** Returns the serialised output of a previous step by order index (negative = relative). */
|
||||
getStepOutput: (order: number) => Promise<unknown>;
|
||||
/** Dumps the DOM of the current page, optionally scoped to a CSS selector. */
|
||||
dumpDom: (selector?: string) => Promise<DomNode>;
|
||||
log: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
/** Runs a named snippet with the same context, plus any extra positional args. */
|
||||
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface ExecContext {
|
||||
page: Page;
|
||||
browser: BrowserContext;
|
||||
code: string;
|
||||
log?: ScriptLogger;
|
||||
getStepOutput?: (order: number) => Promise<unknown>;
|
||||
credentials?: Record<string, unknown>;
|
||||
environment?: EnvironmentData | null;
|
||||
snippets?: Record<string, string> | null;
|
||||
result?: unknown;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CodeExecutorService {
|
||||
private readonly logger = new TraceLogger(CodeExecutorService.name);
|
||||
@@ -27,7 +64,7 @@ export class CodeExecutorService {
|
||||
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
|
||||
*/
|
||||
validate(code: string): void {
|
||||
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
|
||||
const wrapped = `async function __validate__(context) { ${code} }`;
|
||||
try {
|
||||
parse(wrapped, { ecmaVersion: 2022 });
|
||||
} catch (err) {
|
||||
@@ -39,20 +76,22 @@ export class CodeExecutorService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes `code` as an async function body with `page` and `context` in
|
||||
* scope. Always call `validate()` before this method.
|
||||
* Executes `code` as an async function body with a single `context` argument
|
||||
* that exposes page, browser, env helpers, credentials, snippets, and logging.
|
||||
* Always call `validate()` before this method.
|
||||
*/
|
||||
async execute(
|
||||
page: Page,
|
||||
context: BrowserContext,
|
||||
code: string,
|
||||
log?: ScriptLogger,
|
||||
getStepOutput?: (order: number) => Promise<unknown>,
|
||||
credentials?: Record<string, unknown>,
|
||||
environment?: EnvironmentUrls | null,
|
||||
snippets?: Record<string, string> | null,
|
||||
result?: unknown,
|
||||
): Promise<ExecResult> {
|
||||
async execute(ctx: ExecContext): Promise<ExecResult> {
|
||||
const {
|
||||
page,
|
||||
browser,
|
||||
code,
|
||||
log,
|
||||
getStepOutput,
|
||||
credentials,
|
||||
environment,
|
||||
snippets,
|
||||
result,
|
||||
} = ctx;
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
const toStr = (args: unknown[]) =>
|
||||
@@ -61,12 +100,11 @@ export class CodeExecutorService {
|
||||
.join(" ");
|
||||
|
||||
const credMap: Record<string, unknown> = credentials ?? {};
|
||||
const envUrls: EnvironmentUrls = environment ?? {};
|
||||
const envData: EnvironmentData = environment ?? {};
|
||||
const snippetMap: Record<string, string> = snippets ?? {};
|
||||
|
||||
// pageHelpers is referenced by runSnippet, so we declare it as a var first.
|
||||
// eslint-disable-next-line prefer-const
|
||||
let pageHelpers: Record<string, unknown>;
|
||||
// scriptContext is referenced by runSnippet, so we declare it first.
|
||||
let scriptContext: ScriptContext;
|
||||
|
||||
const fakeConsole = {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
@@ -77,7 +115,9 @@ export class CodeExecutorService {
|
||||
};
|
||||
|
||||
try {
|
||||
pageHelpers = {
|
||||
scriptContext = {
|
||||
page,
|
||||
browser,
|
||||
dumpDom: (selector?: string) => dumpDom(page, selector),
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
@@ -91,52 +131,51 @@ export class CodeExecutorService {
|
||||
}
|
||||
return credMap[alias];
|
||||
},
|
||||
/** All URLs defined for the current environment (may be empty if no environment is set). */
|
||||
env: { ...envUrls },
|
||||
/** Returns the URL for the given key, or throws if it is not defined. */
|
||||
getEnvUrl: (key: string): string => {
|
||||
const value = envUrls[key];
|
||||
env: { ...envData },
|
||||
getEnv: (key: string): string => {
|
||||
const value = envData[key];
|
||||
if (value == null) {
|
||||
throw new Error(
|
||||
`Environment URL "${key}" is not defined for this environment`,
|
||||
`Environment value "${key}" is not defined for this environment`,
|
||||
);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
/**
|
||||
* Runs a named snippet by name. Snippets receive the same page/context/helpers
|
||||
* as regular exec code, plus any positional args you pass.
|
||||
*
|
||||
* Example: await helpers.runSnippet('clickLoginButton', '#submit')
|
||||
*/
|
||||
runSnippet: async (name: string, ...args: unknown[]): Promise<unknown> => {
|
||||
const snippetCode = snippetMap[name];
|
||||
runSnippet: async (
|
||||
alias: string,
|
||||
...args: unknown[]
|
||||
): Promise<unknown> => {
|
||||
const snippetCode = snippetMap[alias];
|
||||
if (snippetCode == null) {
|
||||
throw new Error(`Snippet "${name}" not found`);
|
||||
throw new Error(`Snippet alias "${alias}" not found`);
|
||||
}
|
||||
const snippetFn = new Function(
|
||||
"page",
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"snippetArgs",
|
||||
`return (async (page, context, helpers, ...args) => { ${snippetCode} })(page, context, helpers, ...snippetArgs)`,
|
||||
"expect",
|
||||
`return (async (context, ...args) => { ${snippetCode} })(context, ...snippetArgs)`,
|
||||
);
|
||||
return snippetFn(page, context, pageHelpers, fakeConsole, args);
|
||||
return snippetFn(scriptContext, fakeConsole, args, playwrightExpect);
|
||||
},
|
||||
};
|
||||
|
||||
// Passing `console` as a named parameter shadows the global in the script scope.
|
||||
// `console`, `result`, and `expect` are injected as named parameters so
|
||||
// existing scripts that reference them directly still work.
|
||||
const fn = new Function(
|
||||
"page",
|
||||
"context",
|
||||
"helpers",
|
||||
"console",
|
||||
"result",
|
||||
`return (async (page, context, helpers) => { ${code} })(page, context, helpers)`,
|
||||
"expect",
|
||||
`return (async (context) => { ${code} })(context)`,
|
||||
);
|
||||
this.logger.debug("Executing user code");
|
||||
const execResult = await fn(page, context, pageHelpers, fakeConsole, result);
|
||||
const execResult = await fn(
|
||||
scriptContext,
|
||||
fakeConsole,
|
||||
result,
|
||||
playwrightExpect,
|
||||
);
|
||||
return { result: execResult };
|
||||
} catch (err) {
|
||||
throw new InternalServerErrorException(
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { ExecContext, ScriptLogger } from "./code-executor.service";
|
||||
|
||||
export class ExecContextBuilder {
|
||||
private readonly ctx: Partial<ExecContext> = {};
|
||||
|
||||
page(page: Page): this {
|
||||
this.ctx.page = page;
|
||||
return this;
|
||||
}
|
||||
|
||||
browser(browser: BrowserContext): this {
|
||||
this.ctx.browser = browser;
|
||||
return this;
|
||||
}
|
||||
|
||||
code(code: string): this {
|
||||
this.ctx.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
log(log: ScriptLogger): this {
|
||||
this.ctx.log = log;
|
||||
return this;
|
||||
}
|
||||
|
||||
getStepOutput(fn: (order: number) => Promise<unknown>): this {
|
||||
this.ctx.getStepOutput = fn;
|
||||
return this;
|
||||
}
|
||||
|
||||
credentials(credentials: Record<string, unknown>): this {
|
||||
this.ctx.credentials = credentials;
|
||||
return this;
|
||||
}
|
||||
|
||||
environment(environment: EnvironmentData | null): this {
|
||||
this.ctx.environment = environment;
|
||||
return this;
|
||||
}
|
||||
|
||||
snippets(snippets: Record<string, string> | null): this {
|
||||
this.ctx.snippets = snippets;
|
||||
return this;
|
||||
}
|
||||
|
||||
result(result: unknown): this {
|
||||
this.ctx.result = result;
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): ExecContext {
|
||||
if (!this.ctx.page) throw new Error("ExecContextBuilder: page is required");
|
||||
if (!this.ctx.browser)
|
||||
throw new Error("ExecContextBuilder: browser is required");
|
||||
if (this.ctx.code === undefined)
|
||||
throw new Error("ExecContextBuilder: code is required");
|
||||
return this.ctx as ExecContext;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { IsInt, IsString, Min, Max } from "class-validator";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
import { IsInt, IsString, Max, Min, validateSync } from "class-validator";
|
||||
|
||||
import pkg from "../../package.json";
|
||||
|
||||
@@ -23,7 +22,7 @@ export class AppConfig {
|
||||
KEYS_DIR: string = "keys";
|
||||
|
||||
@IsString()
|
||||
DB_PATH: string = "data/sessions.db";
|
||||
DB_PATH: string = "data/liqa.db";
|
||||
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
|
||||
@@ -11,12 +11,11 @@ import {
|
||||
Query,
|
||||
} from "@nestjs/common";
|
||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import { CredentialService } from "./credential.service";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
import { CredentialExportDto } from "./dto/credential-export.dto";
|
||||
import { PaginationQueryDto } from "../common/dto/pagination.dto";
|
||||
import { CredentialOrderBy } from "./credential.service";
|
||||
import { CredentialOrderBy, CredentialService } from "./credential.service";
|
||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||
import { CredentialExportDto } from "./dto/credential-export.dto";
|
||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||
|
||||
@ApiTags("credentials")
|
||||
@Controller("credentials")
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from "typeorm";
|
||||
|
||||
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user