Merge pull request 'feat(client): add code reference modal to step and snippet editors' (#4) from feat/code-context-help into master
Reviewed-on: #4
This commit was merged in pull request #4.
This commit is contained in:
commit
e3c2c0cebb
14 files changed
+344
-5
No files matched your search
@@ -4,13 +4,22 @@ import { expect, userEvent, within } from 'storybook/test';
|
||||
import { Modal } from '../../src/ui/Modal/Modal';
|
||||
import { Button } from '../../src/ui/Button/Button';
|
||||
|
||||
function ModalDemo({ title, body }: { title: string; body: string }) {
|
||||
function ModalDemo({
|
||||
title,
|
||||
body,
|
||||
size,
|
||||
}: {
|
||||
title: string;
|
||||
body: React.ReactNode;
|
||||
size?: 'md' | 'lg';
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setOpen(true)}>Open modal</Button>
|
||||
<Modal
|
||||
open={open}
|
||||
size={size}
|
||||
title={title}
|
||||
onClose={() => setOpen(false)}
|
||||
footer={
|
||||
@@ -61,3 +70,29 @@ export const ClosesOnEscapeAndBackdrop: Story = {
|
||||
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const Large: Story = {
|
||||
args: {
|
||||
title: 'Code reference',
|
||||
size: 'lg',
|
||||
body: (
|
||||
<>
|
||||
{Array.from({ length: 60 }, (_, i) => (
|
||||
<p key={i}>Paragraph {i + 1} of a long, document-like modal body.</p>
|
||||
))}
|
||||
</>
|
||||
),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||
const dialog = canvas.getByRole('dialog', { name: 'Code reference' });
|
||||
// The dialog stays within the viewport; its body scrolls instead.
|
||||
await expect(dialog.getBoundingClientRect().height).toBeLessThanOrEqual(window.innerHeight);
|
||||
const body = within(dialog).getByText(
|
||||
'Paragraph 1 of a long, document-like modal body.',
|
||||
).parentElement!;
|
||||
await expect(body.scrollHeight).toBeGreaterThan(body.clientHeight);
|
||||
await expect(within(dialog).getByRole('button', { name: 'Confirm' })).toBeVisible();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
.helpButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--color-text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.helpButton:hover {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.helpButton:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.35);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CircleHelp, X } from 'lucide-react';
|
||||
import { Modal, Button, MarkdownContent } from '../../ui';
|
||||
import content from './code-help.md?raw';
|
||||
import styles from './CodeHelpModal.module.css';
|
||||
|
||||
export interface CodeHelpModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Reference for the script runtime (`context`, `expect`, ...) available to step and snippet code. */
|
||||
export function CodeHelpModal({ open, onClose }: CodeHelpModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
size="lg"
|
||||
title={t('code_help.title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
<X size={14} />
|
||||
{t('code_help.close')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<MarkdownContent content={content} />
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** A (?) button that opens the {@link CodeHelpModal}; place it next to a code field label. */
|
||||
export function CodeHelpButton() {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.helpButton}
|
||||
onClick={() => setOpen(true)}
|
||||
aria-label={t('code_help.open')}
|
||||
title={t('code_help.open')}
|
||||
>
|
||||
<CircleHelp size={16} />
|
||||
</button>
|
||||
<CodeHelpModal open={open} onClose={() => setOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
Step code and snippet code are the **body of an async function**. Use `await` freely; whatever you `return` becomes the step (or snippet) output.
|
||||
|
||||
```js
|
||||
async (context) => {
|
||||
// your code here
|
||||
}
|
||||
```
|
||||
|
||||
All steps of a run share one browser, one browser context and one page, so state carries over from step to step: the current URL, cookies, local storage, open dialogs.
|
||||
|
||||
A step **passes** when its code returns, and **fails** when it throws or exceeds its timeout. When a step fails, the remaining steps are cancelled, and a screenshot and the page HTML are saved to the run's files.
|
||||
|
||||
## Globals
|
||||
|
||||
| Name | Description |
|
||||
| --- | --- |
|
||||
| `context` | The run context, described below. |
|
||||
| `expect` | Playwright's [`expect`](https://playwright.dev/docs/test-assertions), with auto-retrying web assertions. |
|
||||
| `console` | Writes to the run log: `log`/`info` → `log`, plus `warn`, `error` and `debug`. |
|
||||
| `args` | **Snippets only.** The extra arguments passed to `context.runSnippet(name, ...args)`. |
|
||||
|
||||
Code runs in the server process with Node.js. It is trusted code, not sandboxed.
|
||||
|
||||
## Browser
|
||||
|
||||
### `context.page`
|
||||
|
||||
The Playwright [`Page`](https://playwright.dev/docs/api/class-page) of the run.
|
||||
|
||||
```js
|
||||
await context.page.goto(context.getEnv("base_url"));
|
||||
await context.page.getByRole("button", { name: "Sign in" }).click();
|
||||
await expect(context.page.locator("h1")).toHaveText("Dashboard");
|
||||
```
|
||||
|
||||
### `context.browser`
|
||||
|
||||
The Playwright [`BrowserContext`](https://playwright.dev/docs/api/class-browsercontext) the page belongs to. Use it for cookies, storage state, extra pages and HTTP requests that share the browser's cookies.
|
||||
|
||||
```js
|
||||
const cookies = await context.browser.cookies();
|
||||
const res = await context.browser.request.get(context.getEnv("api_url") + "/me");
|
||||
```
|
||||
|
||||
### `context.dumpDom(selector?)` → `Promise<DomNode>`
|
||||
|
||||
Returns a simplified tree of the live DOM, starting at `selector` (default `"body"`). Decorative and layout elements are filtered out. The tree keeps landmarks, interactive elements, and elements with `role`, `data-testid`, `data-qa`, `data-action` or `data-element-id`. Each node has `tag` and `children`, plus `role`, `testid`, `id`, `name`, `type`, `text`, `href`, `checked`, `disabled`, etc. when they are present. This is useful for finding selectors without a screenshot.
|
||||
|
||||
If nothing matches `selector`, it returns a node with `tag: "ERROR"` instead of throwing.
|
||||
|
||||
```js
|
||||
context.log("Login form:", await context.dumpDom("form"));
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
### `context.env`
|
||||
|
||||
A copy of the selected environment's key/value map, `{}` when there is none. A missing key reads as `undefined`.
|
||||
|
||||
### `context.getEnv(key)` → `string`
|
||||
|
||||
Returns the environment value for `key`, and **throws** if it is not defined. Prefer it over `context.env[key]` for required settings: the step then fails with a clear message.
|
||||
|
||||
```js
|
||||
const baseUrl = context.getEnv("base_url");
|
||||
const locale = context.env.locale ?? "en";
|
||||
```
|
||||
|
||||
## Credentials
|
||||
|
||||
### `context.getCredential(alias)` → `unknown`
|
||||
|
||||
Returns the payload of the credential assigned to this scenario under `alias` (see **Credentials** on the scenario page). JSON data is returned parsed, anything else as a string. **Throws** if no credential has that alias.
|
||||
|
||||
```js
|
||||
const { username, password } = context.getCredential("admin");
|
||||
await context.page.getByLabel("Username").fill(username);
|
||||
await context.page.getByLabel("Password").fill(password);
|
||||
```
|
||||
|
||||
## Step outputs
|
||||
|
||||
### `context.getStepOutput(order)` → `Promise<unknown>`
|
||||
|
||||
Returns the output (the return value) of another step in the same run. **It is async, so `await` it.**
|
||||
|
||||
- A positive `order` is absolute: `1` is the first step.
|
||||
- A negative `order` is relative: `-1` is the previous step.
|
||||
|
||||
Returns `null` if that step does not exist, has not run, or returned nothing. A step's output is stored as JSON, so only JSON-serializable values come back as they were returned (no functions, `Date` becomes a string, Playwright objects are not usable).
|
||||
|
||||
```js
|
||||
// step 2
|
||||
return { orderId: await context.page.locator("#order-id").textContent() };
|
||||
|
||||
// step 3
|
||||
const { orderId } = await context.getStepOutput(-1);
|
||||
```
|
||||
|
||||
## Logging
|
||||
|
||||
### `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`
|
||||
|
||||
Write an entry with that level to the run log. `console.*` does the same. Strings, numbers and booleans are joined with spaces into the message. Objects and arrays are kept separate as structured **data**, shown pretty-printed under the message: one object is stored as is, several are stored as an array.
|
||||
|
||||
```js
|
||||
context.log("Created user", user.id, user); // message "Created user 42", data = user
|
||||
```
|
||||
|
||||
Every entry is tagged with where it came from: `step:<N>`, or `snippet:<alias>` while a snippet runs.
|
||||
|
||||
## Assertions
|
||||
|
||||
### `context.assert(fn, description)` → `Promise<void>`
|
||||
|
||||
Runs `fn` (sync or async) and requires it to return exactly `true`.
|
||||
|
||||
- On success, it logs `description` (tagged `assertion:pass`).
|
||||
- If `fn` returns anything else or throws, it logs `Assertion failed: <description>` as an error (tagged `assertion:fail`) and throws, which fails the step.
|
||||
|
||||
Await it, or a failure will not stop the step.
|
||||
|
||||
```js
|
||||
await context.assert(
|
||||
async () => (await context.page.locator(".cart-item").count()) === 3,
|
||||
"Cart contains 3 items",
|
||||
);
|
||||
```
|
||||
|
||||
Use `expect` instead for assertions that wait and retry until the page matches, e.g. `await expect(locator).toBeVisible()`.
|
||||
|
||||
## Snippets
|
||||
|
||||
### `context.runSnippet(name, ...args)` → `Promise<unknown>`
|
||||
|
||||
Runs a stored snippet with the same `context` (same page, environment and credentials) and returns the snippet's return value. Extra arguments are available inside the snippet as `args`.
|
||||
|
||||
- `name` is the snippet alias, which runs its latest version.
|
||||
- `alias@<version>` (e.g. `login@3`) pins a specific version.
|
||||
|
||||
Start, finish and failure are logged. If the snippet throws, the error propagates and fails the calling step unless you catch it. Snippets can call other snippets.
|
||||
|
||||
```js
|
||||
// step code
|
||||
const user = await context.runSnippet("login", "admin", { remember: true });
|
||||
|
||||
// snippet "login"
|
||||
const [alias, opts] = args;
|
||||
const { username, password } = context.getCredential(alias);
|
||||
// ...
|
||||
return { username };
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
### `context.getScenarioFiles(opts?)` → `Promise<{ items, total }>`
|
||||
|
||||
Lists the files uploaded to this scenario (see **Files** on the scenario page). `opts` takes `limit` and `offset` for paging. Each item has `id`, `name`, `mimeType`, `size`, `sha256` and `path`, the absolute path on the server's disk, which you can pass to Playwright:
|
||||
|
||||
```js
|
||||
const { items } = await context.getScenarioFiles();
|
||||
const doc = items.find((f) => f.name === "contract.pdf");
|
||||
await context.page.locator("input[type=file]").setInputFiles(doc.path);
|
||||
```
|
||||
|
||||
### `context.downloadFile(url, opts?)` → `Promise<FileInfo>`
|
||||
|
||||
Fetches `url` on the server and saves the response as a file of the current run. It returns the same fields as a scenario file (`id`, `name`, `mimeType`, `size`, `sha256`, `path`).
|
||||
|
||||
- `opts`: `method`, `headers`, `body` (a string) and `filename`. Without `filename`, the last segment of the URL path is used, and the MIME type is derived from the file extension.
|
||||
- Redirects are followed. Any final status other than 200 throws. The limits are 100 MB and a 30 s timeout.
|
||||
- `url` may be a `data:` URI (`data:<type>;base64,<data>` or `data:<type>,<percent-encoded>`), which saves content generated in the script without a network request. Pass `filename` in this case.
|
||||
- Only works during a real scenario run. It throws in ad-hoc execution such as the `exec_code` MCP tool.
|
||||
- This is a server-side request: it does **not** send the browser's cookies. Pass them in `headers` if the URL needs a session.
|
||||
|
||||
```js
|
||||
await context.downloadFile(
|
||||
"data:application/json;base64," + btoa(JSON.stringify(report)),
|
||||
{ filename: "report.json" },
|
||||
);
|
||||
```
|
||||
|
||||
## Timeouts
|
||||
|
||||
Each step has its own timeout, or else the scenario's timeout, or else 60 s. The whole run fails once it exceeds the scenario's timeout (600 s by default). That check happens between steps.
|
||||
@@ -6,3 +6,5 @@ export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
export { ExportLogsModal } from './ExportLogsModal';
|
||||
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
|
||||
export { CodeHelpModal, CodeHelpButton } from './CodeHelpModal';
|
||||
export type { CodeHelpModalProps } from './CodeHelpModal';
|
||||
@@ -12,6 +12,11 @@
|
||||
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
|
||||
"save_session": "Save session"
|
||||
},
|
||||
"code_help": {
|
||||
"open": "Code reference",
|
||||
"title": "Code reference",
|
||||
"close": "Close"
|
||||
},
|
||||
"errors": {
|
||||
"not_found": "Not found",
|
||||
"not_found_session": "Session {{id}} does not exist or has been deleted.",
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.labelRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateStepPage() {
|
||||
@@ -77,7 +78,10 @@ export function CreateStepPage() {
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditStepPage() {
|
||||
@@ -89,7 +90,10 @@ export function EditStepPage() {
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
|
||||
@@ -5,6 +5,7 @@ import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
@@ -107,10 +108,13 @@ export function CreateSnippetPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(v) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditSnippetPage() {
|
||||
@@ -134,10 +135,13 @@ export function EditSnippetPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(v) => {
|
||||
|
||||
@@ -16,6 +16,13 @@
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.lg {
|
||||
width: min(880px, 100%);
|
||||
}
|
||||
|
||||
.header {
|
||||
@@ -31,6 +38,7 @@
|
||||
.body {
|
||||
padding: var(--space-2) var(--space-5) var(--space-4);
|
||||
color: var(--color-text-muted);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.footer {
|
||||
|
||||
@@ -7,9 +7,11 @@ export interface ModalProps {
|
||||
children?: React.ReactNode;
|
||||
onClose: () => void;
|
||||
footer?: React.ReactNode;
|
||||
/** `lg` widens the dialog for long, document-like content. */
|
||||
size?: 'md' | 'lg';
|
||||
}
|
||||
|
||||
export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
export function Modal({ open, title, children, onClose, footer, size = 'md' }: ModalProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -24,7 +26,7 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
return (
|
||||
<div className={styles.overlay} role="presentation" onClick={onClose}>
|
||||
<div
|
||||
className={styles.dialog}
|
||||
className={size === 'lg' ? `${styles.dialog} ${styles.lg}` : styles.dialog}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
@@ -33,7 +35,10 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
<div className={styles.header}>
|
||||
<h3 className={styles.title}>{title}</h3>
|
||||
</div>
|
||||
<div className={styles.body}>{children}</div>
|
||||
{/* Long (lg) content scrolls; make it focusable so the keyboard can scroll it. */}
|
||||
<div className={styles.body} tabIndex={size === 'lg' ? 0 : undefined}>
|
||||
{children}
|
||||
</div>
|
||||
{footer && <div className={styles.footer}>{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+3
-1
@@ -32,7 +32,7 @@ Available on `context`:
|
||||
- `context.env`: shallow copy of the environment's key/value map
|
||||
- `context.getEnv(key)`: environment value lookup (throws if missing)
|
||||
- `context.getCredential(alias)`: payload of the credential assigned to the scenario under `alias` (parsed JSON when the data is JSON; throws if missing)
|
||||
- `context.getStepOutput(order)`: output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||
- `context.getStepOutput(order)`: async (`await` it); output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||
- `context.dumpDom(selector?)`: simplified DOM snapshot of the page (or of one element)
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`: run log entries
|
||||
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
||||
@@ -47,6 +47,8 @@ Also in scope:
|
||||
|
||||
Code is syntax-checked before it runs, and executes in the server process: it's trusted code, not sandboxed.
|
||||
|
||||
The step and snippet editors have a (?) button next to the Code label that opens a reference of this runtime in the UI. Its content is [client/src/components/modals/code-help.md](../client/src/components/modals/code-help.md): keep it in sync with this section when the `context` API changes.
|
||||
|
||||
## Run logs
|
||||
|
||||
Each run log entry (`level`, `message`, `createdAt`) also carries a `context`: where the message was generated. Contexts:
|
||||
|
||||
Reference in new issue
Block a user