@digital-commons-official/codeceptjs-storyboard 0.0.0-stage ā 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -2
- package/package.json +62 -4
- package/src/gallery.js +77 -0
- package/src/index.d.ts +114 -0
- package/src/index.js +912 -0
package/README.md
CHANGED
|
@@ -1,3 +1,142 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- cspell:ignore storyboardStep addStoryboardFrame capturePageFrame captureElementFrame -->
|
|
2
|
+
# š¬ codeceptjs-storyboard
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
[](https://gitlab.com/digital-commons/software/libraries/npm/codeceptjs-storyboard/-/commits/main)
|
|
5
|
+
|
|
6
|
+
A [CodeceptJS](https://codecept.io) plugin that turns one Gherkin scenario into one human-readable SVG storyboard, straight from the real screenshots the test captures.
|
|
7
|
+
|
|
8
|
+
ONE Gherkin sentence = ONE card = ONE pixel baseline, asserted inside its step at `tolerance: 0`: a visual regression fails on the exact sentence whose image drifted.
|
|
9
|
+
When the scenario ends the plugin assembles the whole story into one SVG: the frames stay bitmap, but every caption, note and reproduce-command around them is real selectable text you can copy from the SVG (Chromium/Safari).
|
|
10
|
+
|
|
11
|
+
## Installation š¦
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install --save-dev @digital-commons-official/codeceptjs-storyboard @digital-commons-official/codeceptjs-visual-helper
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Peer dependencies: `codeceptjs >= 4` and [`@digital-commons-official/codeceptjs-visual-helper`](https://gitlab.com/digital-commons/software/libraries/npm/codeceptjs-visual-helper) (the plugin captures and asserts through `I.takeScreenshot`, `I.captureScreenshot` and `I.assertVisualMatch`).
|
|
18
|
+
|
|
19
|
+
## Configuration āļø
|
|
20
|
+
|
|
21
|
+
Register the plugin next to the visual helper in `codecept.conf.js`, and point Gherkin at your step files:
|
|
22
|
+
|
|
23
|
+
```javascript
|
|
24
|
+
exports.config = {
|
|
25
|
+
output: './_output',
|
|
26
|
+
helpers: {
|
|
27
|
+
Playwright: { browser: 'chromium', url: 'http://localhost:8080', show: false, windowSize: '1280x720' },
|
|
28
|
+
VisualHelper: {
|
|
29
|
+
require: '@digital-commons-official/codeceptjs-visual-helper',
|
|
30
|
+
baselineDir: './screenshots/base/',
|
|
31
|
+
diffDir: './screenshots/diff/',
|
|
32
|
+
actualDir: './_output/',
|
|
33
|
+
tolerance: 0,
|
|
34
|
+
captureBaseline: false
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
gherkin: {
|
|
38
|
+
features: './features/**/*.feature',
|
|
39
|
+
steps: ['./steps/first-run.js']
|
|
40
|
+
},
|
|
41
|
+
plugins: {
|
|
42
|
+
storyboard: {
|
|
43
|
+
require: '@digital-commons-official/codeceptjs-storyboard',
|
|
44
|
+
enabled: true
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Nothing configures paths: everything is derived from the feature file location.
|
|
51
|
+
Frames land in `_output/storyboard-frames/`, baselines in `screenshots/base/<feature-dir>/<scenario-tag>/`, the committed SVG in `storyboards/<feature-dir>/<scenario-tag>.svg`.
|
|
52
|
+
A scenario that never calls `addStoryboardFrame` renders no SVG, so plain Gherkin tests are left untouched.
|
|
53
|
+
|
|
54
|
+
When the run ends, open `_output/index.html` to browse its storyboards. The page groups scenarios by feature directory, puts failed groups and scenarios first, and shows the failed sentence with its replay command. Links open the actual SVGs.
|
|
55
|
+
|
|
56
|
+
A filtered run lists only the scenarios it ran. In baseline-update mode, `storyboards/index.html` lists the passing scenarios from that update; failed scenarios never replace reviewed storyboards. Run the full suite in update mode to rebuild the complete reviewed gallery.
|
|
57
|
+
|
|
58
|
+
## Usage š
|
|
59
|
+
|
|
60
|
+
### The `.feature` is the single human-authored source
|
|
61
|
+
|
|
62
|
+
Attach structured comments to the sentence just below them. The feature file carries the story, the step file only drives and captures:
|
|
63
|
+
|
|
64
|
+
- `# Chapter: Title` opens a full-width chapter band before that card.
|
|
65
|
+
- `# Note: text` is the card's explanation: what to look at, why it matters. Repeat the line to stack paragraphs.
|
|
66
|
+
- `# Copy: command` is the exact command shown one-click-copyable under the card.
|
|
67
|
+
|
|
68
|
+
The scenario's LAST tag names the baseline directory and the replay command printed on the board.
|
|
69
|
+
|
|
70
|
+
```gherkin
|
|
71
|
+
@e2e @first-run
|
|
72
|
+
Feature: A developer opens their new project
|
|
73
|
+
Scenario: The project home shows the framework
|
|
74
|
+
# Chapter: The empty project
|
|
75
|
+
# Note: The project as GitLab shows it, before anything is installed.
|
|
76
|
+
# Copy: http://gitlab/<user>/<project>
|
|
77
|
+
Given a fresh project with only a README on its main branch
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### The step file drives and captures
|
|
81
|
+
|
|
82
|
+
```javascript
|
|
83
|
+
/* global inject Given */
|
|
84
|
+
const { I } = inject()
|
|
85
|
+
const storyboard = require('@digital-commons-official/codeceptjs-storyboard')
|
|
86
|
+
|
|
87
|
+
storyboard.storyboardStep(Given, 'a fresh project with only a README on its main branch', async () => {
|
|
88
|
+
await I.amOnPage('/my/project')
|
|
89
|
+
await storyboard.addStoryboardFrame(I, await storyboard.capturePageFrame(I, 'project-home'))
|
|
90
|
+
})
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- `storyboardStep(register, sentence, fn)` registers the step and escapes cucumber-expression metacharacters, so `CI/CD` or `(y/N)` in a sentence never breaks the match. Cards open automatically for every sentence.
|
|
94
|
+
- `capturePageFrame(I, name)` captures the full viewport; `captureElementFrame(I, name, selector)` crops the frame to one element, so a short verdict yields a short card.
|
|
95
|
+
- `addStoryboardFrame(I, png)` refuses a blank frame, attaches the frame to the open card and asserts it against its own baseline at once. On drift the error names the frame, the pixel diff, the failure storyboard and the command that regenerates the baseline.
|
|
96
|
+
- `annotate({ note, copy })` overrides the feature comments for a value only known at runtime.
|
|
97
|
+
|
|
98
|
+
### What you get
|
|
99
|
+
|
|
100
|
+
- On every run the SVG of the scenario is written under `_output/<feature-dir>/<scenario-tag>.svg`.
|
|
101
|
+
- On a failed run that SVG shows, in place of the drifted card, a red band with the expected image, the changed pixels and the actual image, each over its copyable path, then lists the sentences the run never reached.
|
|
102
|
+
- In baseline-update mode the plugin asserts first and rewrites a baseline only when its assert fails, then rebuilds the committed SVG under `storyboards/` from the reviewed baselines:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
TASK_E2E_UPDATE_BASELINES=1 npx codeceptjs run
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Every baseline written this way must be inspected by a human, which is why the mode throws when `CI` is set.
|
|
109
|
+
|
|
110
|
+
## API š
|
|
111
|
+
|
|
112
|
+
| Function | Purpose |
|
|
113
|
+
|------------------------------------------|--------------------------------------------------------------------------|
|
|
114
|
+
| `storyboardStep(register, sentence, fn)` | Register a sentence literally through `Given`, `When` or `Then` |
|
|
115
|
+
| `capturePageFrame(I, name)` | Full-viewport frame, returns the PNG path |
|
|
116
|
+
| `captureElementFrame(I, name, selector)` | Element-cropped frame, returns the PNG path |
|
|
117
|
+
| `addStoryboardFrame(I, png)` | Attach the frame to the open card and assert it at `tolerance: 0` |
|
|
118
|
+
| `annotate({ note, copy })` | Runtime override of the open card's note and copyable command |
|
|
119
|
+
| `assertOrUpdateBaseline(I, name)` | The assert-or-rewrite primitive `addStoryboardFrame` relies on |
|
|
120
|
+
| `render(outFile, { imageDir, failure })` | Write the SVG of the cards captured so far |
|
|
121
|
+
| `parseScenarioLines(featureFile, title)` | Every sentence of a scenario with its `# Chapter` / `# Note` / `# Copy` |
|
|
122
|
+
| `begin`, `panel`, `frame`, `panels` | The board primitives the plugin drives (useful for standalone rendering) |
|
|
123
|
+
|
|
124
|
+
Type definitions ship in `src/index.d.ts`.
|
|
125
|
+
|
|
126
|
+
## Development š ļø
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
task build # install dependencies + build the e2e runner image
|
|
130
|
+
task test # unit tests, then the e2e storyboard suite
|
|
131
|
+
task project:test:storyboard # unit tests only (vitest)
|
|
132
|
+
task project:test:storyboard:e2e # e2e storyboard suite only, inside the pinned Playwright runner
|
|
133
|
+
task project:test:storyboard:e2e -- --grep "@storyboard-happy-path"
|
|
134
|
+
TASK_E2E_UPDATE_BASELINES=1 task project:test:storyboard:e2e # regenerate drifted baselines + committed SVGs, then LOOK at them
|
|
135
|
+
task code # linters (MegaLinter)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The e2e suite is the plugin's own dogfood: every scenario is a storyboard rendered by the plugin under test, committed under `tests/e2e/storyboards/`.
|
|
139
|
+
|
|
140
|
+
## Licence š
|
|
141
|
+
|
|
142
|
+
EUPL-1.2
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@digital-commons-official/codeceptjs-storyboard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Storyboard plugin for CodeceptJS: one Gherkin sentence = one card = one pixel baseline, and every scenario renders itself as a single SVG storyboard",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "src/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./src/index.d.ts",
|
|
10
|
+
"import": "./src/index.js",
|
|
11
|
+
"require": "./src/index.js",
|
|
12
|
+
"default": "./src/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src/**/*"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "vitest run"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://gitlab.com/digital-commons/software/libraries/npm/codeceptjs-storyboard.git"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"pngjs": "^7.0.0"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@digital-commons-official/codeceptjs-visual-helper": ">=1.3.0",
|
|
30
|
+
"codeceptjs": ">=4.0.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@digital-commons-official/codeceptjs-visual-helper": "1.3.4",
|
|
34
|
+
"codeceptjs": "4.2.0",
|
|
35
|
+
"playwright": "1.63.0",
|
|
36
|
+
"standard": "^17.1.2",
|
|
37
|
+
"vitest": "^5.0.0"
|
|
38
|
+
},
|
|
39
|
+
"overrides": {
|
|
40
|
+
"axios": "^1.18.0",
|
|
41
|
+
"uuid": "^14.0.0",
|
|
42
|
+
"joi": "^18.2.1",
|
|
43
|
+
"diff": "^9.0.0",
|
|
44
|
+
"serialize-javascript": "^7.0.5",
|
|
45
|
+
"undici": "^8.0.0",
|
|
46
|
+
"@xmldom/xmldom": "^0.9.12"
|
|
47
|
+
},
|
|
48
|
+
"keywords": [
|
|
49
|
+
"codeceptjs",
|
|
50
|
+
"storyboard",
|
|
51
|
+
"visual-testing",
|
|
52
|
+
"visual-regression",
|
|
53
|
+
"gherkin",
|
|
54
|
+
"bdd",
|
|
55
|
+
"e2e-testing",
|
|
56
|
+
"playwright",
|
|
57
|
+
"svg"
|
|
58
|
+
],
|
|
59
|
+
"author": "Digital Commons",
|
|
60
|
+
"license": "EUPL-1.2",
|
|
61
|
+
"engines": {
|
|
62
|
+
"node": ">=18.0.0"
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/gallery.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
|
|
4
|
+
function escape (value) {
|
|
5
|
+
return String(value || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function entryHtml (entry) {
|
|
9
|
+
const href = entry.baseDir.split(path.sep).map(encodeURIComponent).join('/') + '.svg'
|
|
10
|
+
return `<li class="${entry.passed ? 'passed' : 'failed'}">
|
|
11
|
+
<span class="status">${entry.passed ? 'Passed' : 'Failed'}</span>
|
|
12
|
+
<h3><a href="${escape(href)}">${escape(entry.scenario)}</a></h3>
|
|
13
|
+
${entry.sentence ? ` <p class="failure">${escape(entry.sentence)}</p>` : ''}
|
|
14
|
+
${entry.rerun ? ` <pre><code>${escape(entry.rerun)}</code></pre>` : ''}
|
|
15
|
+
</li>`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Entries come from this run's test events, never from a directory listing:
|
|
19
|
+
// a filtered rerun must not make yesterday's pictures look freshly checked.
|
|
20
|
+
module.exports = function writeGallery (directory, entries) {
|
|
21
|
+
const groups = new Map()
|
|
22
|
+
for (const entry of entries) {
|
|
23
|
+
const group = path.dirname(entry.baseDir)
|
|
24
|
+
if (!groups.has(group)) groups.set(group, [])
|
|
25
|
+
groups.get(group).push(entry)
|
|
26
|
+
}
|
|
27
|
+
const hasFailure = entries => entries.some(entry => !entry.passed)
|
|
28
|
+
const ordered = [...groups].sort(([a, aa], [b, bb]) => Number(hasFailure(bb)) - Number(hasFailure(aa)) || a.localeCompare(b))
|
|
29
|
+
const content = ordered.map(([group, stories]) => {
|
|
30
|
+
const rows = [...stories].sort((a, b) => Number(a.passed) - Number(b.passed) || a.scenario.localeCompare(b.scenario)).map(entryHtml).join('\n')
|
|
31
|
+
return `<section>\n<h2>${escape(group === '.' ? 'Scenarios' : group)}</h2>\n<ul>${rows}</ul>\n</section>`
|
|
32
|
+
}).join('\n')
|
|
33
|
+
const html = `<!DOCTYPE html>
|
|
34
|
+
<html lang="en">
|
|
35
|
+
<head>
|
|
36
|
+
<meta charset="utf-8">
|
|
37
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
38
|
+
<meta name="description" content="Browse this test run's storyboards and replay failed scenarios.">
|
|
39
|
+
<title>Storyboards</title>
|
|
40
|
+
<style>
|
|
41
|
+
:root { color-scheme: dark; font-family: system-ui, sans-serif; background: #0f1017; color: #e8e8ec; }
|
|
42
|
+
* { box-sizing: border-box; }
|
|
43
|
+
body { margin: 0; }
|
|
44
|
+
main { max-width: 960px; margin: auto; padding: 32px; }
|
|
45
|
+
h1 { margin: 0 0 8px; font-size: 36px; }
|
|
46
|
+
header p, h2 { color: #98a0b3; }
|
|
47
|
+
header p { margin: 0; line-height: 1.6; }
|
|
48
|
+
h2 { margin: 32px 0 12px; font-size: 18px; font-weight: 500; }
|
|
49
|
+
h3 { margin: 4px 0 12px; font-size: 20px; line-height: 1.4; }
|
|
50
|
+
ul { list-style: none; padding: 0; margin: 0; }
|
|
51
|
+
li { padding: 20px 24px; margin-bottom: 12px; background: #181a24; border-left: 4px solid #9ece6a; }
|
|
52
|
+
li.failed { border-color: #f7768e; }
|
|
53
|
+
.status { color: #9ece6a; font-size: 14px; }
|
|
54
|
+
.failed .status, .failure { color: #f7768e; }
|
|
55
|
+
.failure { overflow-wrap: anywhere; }
|
|
56
|
+
a { color: #7aa2f7; text-underline-offset: 4px; }
|
|
57
|
+
a:hover { color: #e8e8ec; }
|
|
58
|
+
a:focus-visible { outline: 2px solid #e8e8ec; outline-offset: 4px; }
|
|
59
|
+
pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
60
|
+
code { font-size: 13px; line-height: 1.6; }
|
|
61
|
+
@media (max-width: 600px) { main { padding: 20px; } li { padding: 16px; } }
|
|
62
|
+
</style>
|
|
63
|
+
</head>
|
|
64
|
+
<body>
|
|
65
|
+
<main>
|
|
66
|
+
<header>
|
|
67
|
+
<h1>Storyboards</h1>
|
|
68
|
+
<p>Open a scenario to review its pictures. Copy its command to run it again.</p>
|
|
69
|
+
</header>
|
|
70
|
+
${content || '<p>No storyboards in this run.</p>'}
|
|
71
|
+
</main>
|
|
72
|
+
</body>
|
|
73
|
+
</html>
|
|
74
|
+
`
|
|
75
|
+
fs.mkdirSync(directory, { recursive: true })
|
|
76
|
+
fs.writeFileSync(path.join(directory, 'index.html'), html)
|
|
77
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for @digital-commons-official/codeceptjs-storyboard.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** A CodeceptJS actor extended by codeceptjs-visual-helper. */
|
|
6
|
+
export interface StoryboardActor {
|
|
7
|
+
takeScreenshot: (name: string) => Promise<void>
|
|
8
|
+
captureScreenshot: (name: string, target?: string, elementSelector?: string) => Promise<void>
|
|
9
|
+
assertVisualMatch: (name: string, options?: Record<string, unknown>) => Promise<void>
|
|
10
|
+
[method: string]: unknown
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Runtime overrides of a card's note and copyable command. */
|
|
14
|
+
export interface Annotation {
|
|
15
|
+
note?: string
|
|
16
|
+
copy?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** One sentence of the scenario, read verbatim from the .feature source. */
|
|
20
|
+
export interface ScenarioLine {
|
|
21
|
+
keyword: 'Given' | 'When' | 'Then' | 'And' | 'But'
|
|
22
|
+
group: 'given' | 'when' | 'then' | null
|
|
23
|
+
text: string
|
|
24
|
+
chapter: string | null
|
|
25
|
+
note: string | null
|
|
26
|
+
copy: string | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One frame attached to a card. */
|
|
30
|
+
export interface Frame {
|
|
31
|
+
file: string
|
|
32
|
+
note?: string
|
|
33
|
+
copy?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** One card: a Gherkin sentence and the frames captured inside its step. */
|
|
37
|
+
export interface Panel {
|
|
38
|
+
title: string
|
|
39
|
+
note: string
|
|
40
|
+
copy: string
|
|
41
|
+
images: Frame[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Header metadata of the storyboard about to be built. */
|
|
45
|
+
export interface BoardMeta {
|
|
46
|
+
feature?: string
|
|
47
|
+
scenario?: string
|
|
48
|
+
file?: string
|
|
49
|
+
rerun?: string
|
|
50
|
+
baseDir?: string
|
|
51
|
+
featureFile?: string
|
|
52
|
+
lines?: ScenarioLine[]
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The drifted frame the plugin marks on a failed run. */
|
|
56
|
+
export interface FailureFrame {
|
|
57
|
+
name: string
|
|
58
|
+
step: number
|
|
59
|
+
sentence: string
|
|
60
|
+
keyword: string
|
|
61
|
+
baseline: string
|
|
62
|
+
actual: string
|
|
63
|
+
diff: string | null
|
|
64
|
+
paths: { expected: string, diff: string, actual: string }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface RenderOptions {
|
|
68
|
+
/** Substitute every frame with the same-named PNG inside this directory (the reviewed baselines). */
|
|
69
|
+
imageDir?: string
|
|
70
|
+
/** Marks the drifted card in red, adds the expected/diff/actual band and the sentences never reached. */
|
|
71
|
+
failure?: { frame: FailureFrame | null, notReached: ScenarioLine[] } | null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type StepRegister = (pattern: string, fn: (...args: any[]) => unknown) => void
|
|
75
|
+
type StepFunction = (...args: any[]) => Promise<unknown> | unknown
|
|
76
|
+
|
|
77
|
+
/** The CodeceptJS plugin factory: `plugins: { storyboard: { require: '@digital-commons-official/codeceptjs-storyboard', enabled: true } }`. */
|
|
78
|
+
declare function storyboardPlugin (config?: Record<string, unknown>): void
|
|
79
|
+
|
|
80
|
+
declare namespace storyboardPlugin {
|
|
81
|
+
/** Fill the header for the scenario about to run (the plugin calls it on test.before). */
|
|
82
|
+
function begin (meta: BoardMeta): void
|
|
83
|
+
/** Baseline directory of the running scenario, `<feature-dir>/<scenario-tag>`. */
|
|
84
|
+
function baseDir (): string
|
|
85
|
+
/** Every sentence of a scenario, verbatim, with its attached # Chapter / # Note / # Copy comments. */
|
|
86
|
+
function parseScenarioLines (featureFile: string, scenarioTitle: string): ScenarioLine[]
|
|
87
|
+
/** Open a card (the plugin does it on bddStep.before). */
|
|
88
|
+
function panel (title: string, opts?: Annotation): void
|
|
89
|
+
/** Attach a PNG to the open card without asserting it. */
|
|
90
|
+
function frame (pngPath: string, opts?: Annotation): void
|
|
91
|
+
/** Merge a runtime note/copy into the open card. */
|
|
92
|
+
function annotate (opts: Annotation): void
|
|
93
|
+
/** The cards captured so far. */
|
|
94
|
+
function panels (): Panel[]
|
|
95
|
+
/** Register a Gherkin sentence literally (cucumber-expression metacharacters escaped). */
|
|
96
|
+
function storyboardStep (register: StepRegister, pattern: string, fn: StepFunction): void
|
|
97
|
+
function storyboardStep (register: StepRegister, pattern: string, opts: Annotation | null, fn: StepFunction): void
|
|
98
|
+
/** Full-viewport capture into _output/storyboard-frames/<name>.png; returns the absolute path. */
|
|
99
|
+
function capturePageFrame (I: StoryboardActor, frameName: string): Promise<string>
|
|
100
|
+
/** Element-cropped capture; the frame is exactly the selector's box. */
|
|
101
|
+
function captureElementFrame (I: StoryboardActor, frameName: string, selector: string): Promise<string>
|
|
102
|
+
/** Absolute path a frame of that name is written to. */
|
|
103
|
+
function frameOutputPath (frameName: string): string
|
|
104
|
+
/** Assert _output/<name>.png against screenshots/base/<name>.png, or rewrite the baseline in update mode. */
|
|
105
|
+
function assertOrUpdateBaseline (I: StoryboardActor, baselineName: string): Promise<void>
|
|
106
|
+
/** Attach the frame to the open card and assert it against its own baseline at tolerance 0. */
|
|
107
|
+
function addStoryboardFrame (I: StoryboardActor, png: string): Promise<void>
|
|
108
|
+
/** Write the storyboard SVG of the cards captured so far; returns outFile. */
|
|
109
|
+
function render (outFile: string, options?: RenderOptions): string
|
|
110
|
+
/** Re-export of codeceptjs/effects tryTo. */
|
|
111
|
+
function tryTo (fn: () => unknown): Promise<boolean>
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export = storyboardPlugin
|
package/src/index.js
ADDED
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* codeceptjs-storyboard ā ONE SVG per scenario, built from the real frames
|
|
3
|
+
* captured during the journey. ONE Gherkin sentence = ONE card = ONE pixel
|
|
4
|
+
* baseline.
|
|
5
|
+
*
|
|
6
|
+
* Why SVG and not PNG: every piece of text drawn AROUND the frames (the
|
|
7
|
+
* feature title, the re-run command, the file path, the per-card captions
|
|
8
|
+
* and reproduce commands) is real selectable text ā a reader can copy/paste
|
|
9
|
+
* the command that replays the scenario, which a PNG can never offer. The
|
|
10
|
+
* frames themselves stay bitmap (embedded as data URIs): they are genuine
|
|
11
|
+
* captures and each one is ALSO asserted pixel-perfect against its own
|
|
12
|
+
* baseline, inside the step that captured it ā the SVG is the human
|
|
13
|
+
* artifact, the per-frame PNGs are the regression gate. Open the SVG
|
|
14
|
+
* locally in a browser: one click selects a whole command (Chromium/Safari;
|
|
15
|
+
* inert in Firefox and in GitLab's image-based preview).
|
|
16
|
+
*
|
|
17
|
+
* Register the plugin in codecept.conf.js next to the VisualHelper it relies
|
|
18
|
+
* on (I.takeScreenshot / I.captureScreenshot / I.assertVisualMatch come from
|
|
19
|
+
* @digital-commons-official/codeceptjs-visual-helper):
|
|
20
|
+
*
|
|
21
|
+
* plugins: {
|
|
22
|
+
* storyboard: { require: '@digital-commons-official/codeceptjs-storyboard', enabled: true }
|
|
23
|
+
* }
|
|
24
|
+
*
|
|
25
|
+
* The .feature file is then the single human-authored source ā the
|
|
26
|
+
* sentences, plus structured comments attached to the sentence below them:
|
|
27
|
+
*
|
|
28
|
+
* # Chapter: a full-width band opens here
|
|
29
|
+
* # Note: why this step matters, what to look at
|
|
30
|
+
* # Copy: exact command shown one-click-copyable under the card
|
|
31
|
+
* When the developer starts the installer
|
|
32
|
+
*
|
|
33
|
+
* Cards open automatically for every Gherkin sentence (bddStep.before). The
|
|
34
|
+
* step file only drives the app and captures the proof:
|
|
35
|
+
*
|
|
36
|
+
* const storyboard = require('@digital-commons-official/codeceptjs-storyboard')
|
|
37
|
+
* storyboard.storyboardStep(When, 'the developer starts the installer', async () => {
|
|
38
|
+
* ...drive the app...
|
|
39
|
+
* await storyboard.addStoryboardFrame(I, await storyboard.capturePageFrame(I, 'frame-name'))
|
|
40
|
+
* })
|
|
41
|
+
*
|
|
42
|
+
* (storyboardStep = plain Given/When/Then registration + escaping of
|
|
43
|
+
* cucumber-expression metacharacters, so "CI/CD" or "(y/N)" in a sentence
|
|
44
|
+
* never breaks the match. Runtime-only annotations ā e.g. a URL known only
|
|
45
|
+
* mid-step ā still go through storyboard.annotate({ note, copy }).)
|
|
46
|
+
*
|
|
47
|
+
* Every path is derived from global.codecept_dir (the codecept.conf.js
|
|
48
|
+
* directory): frames land in _output/storyboard-frames/, per-frame baselines
|
|
49
|
+
* in screenshots/base/<feature-dir>/<scenario>/, the committed SVG in
|
|
50
|
+
* storyboards/<feature-dir>/<scenario>.svg ā all mirrored from the feature
|
|
51
|
+
* file path, zero configuration.
|
|
52
|
+
*/
|
|
53
|
+
|
|
54
|
+
const fs = require('fs')
|
|
55
|
+
const path = require('path')
|
|
56
|
+
const { PNG } = require('pngjs')
|
|
57
|
+
const { tryTo } = require('codeceptjs/effects')
|
|
58
|
+
|
|
59
|
+
let board = null
|
|
60
|
+
|
|
61
|
+
function stripTags (title) {
|
|
62
|
+
return String(title || '').replace(/\s*@[\w:-]+/g, '').trim()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function e2eDir () {
|
|
66
|
+
if (!global.codecept_dir) throw new Error('storyboard: global.codecept_dir is not set ā run under codeceptjs')
|
|
67
|
+
return global.codecept_dir
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Every line of the scenario, verbatim from the .feature source, so each
|
|
71
|
+
// card can carry its exact keyword (Given/When/Then/And/But ā the And/But
|
|
72
|
+
// resolution the step registry cannot provide).
|
|
73
|
+
// ponytail: single flat Scenario only ā no Background/Examples resolution;
|
|
74
|
+
// extend when a storyboard scenario first uses them.
|
|
75
|
+
function parseScenarioLines (featureFile, scenarioTitle) {
|
|
76
|
+
let source
|
|
77
|
+
try {
|
|
78
|
+
source = fs.readFileSync(featureFile, 'utf8')
|
|
79
|
+
} catch (_) {
|
|
80
|
+
return []
|
|
81
|
+
}
|
|
82
|
+
const lines = source.split('\n').map(line => line.trim())
|
|
83
|
+
const start = lines.findIndex(line =>
|
|
84
|
+
/^Scenario( Outline)?:/.test(line) && line.replace(/^Scenario( Outline)?:\s*/, '') === scenarioTitle
|
|
85
|
+
)
|
|
86
|
+
if (start === -1) return []
|
|
87
|
+
const out = []
|
|
88
|
+
let group = null
|
|
89
|
+
let chapter = null
|
|
90
|
+
let note = null
|
|
91
|
+
let copy = null
|
|
92
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
93
|
+
const line = lines[i]
|
|
94
|
+
if (line.startsWith('#')) {
|
|
95
|
+
// Structured comments make the .feature the single human-authored
|
|
96
|
+
// source: they all attach to the NEXT sentence.
|
|
97
|
+
// # Chapter: Title -> full-width chapter band before that card
|
|
98
|
+
// # Note: text -> the card's explanation (why this step, what to see)
|
|
99
|
+
// # Copy: command -> the card's one-click-copyable command
|
|
100
|
+
const mark = line.match(/^#\s*(Chapter|Note|Copy)\s*:\s*(.+)$/i)
|
|
101
|
+
if (mark) {
|
|
102
|
+
const kind = mark[1].toLowerCase()
|
|
103
|
+
if (kind === 'chapter') chapter = mark[2].trim()
|
|
104
|
+
// Several `# Note:` lines stack into paragraphs: a long explanation
|
|
105
|
+
// reads as a few short blocks instead of one dense wall of text.
|
|
106
|
+
if (kind === 'note') note = note ? `${note}\n${mark[2].trim()}` : mark[2].trim()
|
|
107
|
+
if (kind === 'copy') copy = mark[2].trim()
|
|
108
|
+
}
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
if (line === '' || line.startsWith('@')) continue
|
|
112
|
+
if (/^(Scenario|Feature|Examples|Background)/.test(line)) break
|
|
113
|
+
const step = line.match(/^(Given|When|Then|And|But)\s+(.*)$/)
|
|
114
|
+
if (!step) continue
|
|
115
|
+
if (step[1] === 'Given' || step[1] === 'When' || step[1] === 'Then') group = step[1].toLowerCase()
|
|
116
|
+
out.push({ keyword: step[1], group, text: step[2], chapter, note, copy })
|
|
117
|
+
chapter = null
|
|
118
|
+
note = null
|
|
119
|
+
copy = null
|
|
120
|
+
}
|
|
121
|
+
return out
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Fill the header from a scenario about to run. Exposed for the plugin AND
|
|
125
|
+
// for direct calls (standalone rendering, tests).
|
|
126
|
+
function begin (meta) {
|
|
127
|
+
board = {
|
|
128
|
+
feature: meta.feature || '',
|
|
129
|
+
scenario: meta.scenario || '',
|
|
130
|
+
file: meta.file || '',
|
|
131
|
+
rerun: meta.rerun || '',
|
|
132
|
+
baseDir: meta.baseDir || '',
|
|
133
|
+
lines: meta.featureFile ? parseScenarioLines(meta.featureFile, meta.scenario || '') : (meta.lines || []),
|
|
134
|
+
panels: []
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Where this scenario's frames live, relative to _output/ and to
|
|
139
|
+
// screenshots/base/ ā derived by the plugin from the feature file path
|
|
140
|
+
// (features/<dir>/<name>.feature -> <dir>/<name>), so the baseline layout
|
|
141
|
+
// always mirrors the feature tree with zero configuration.
|
|
142
|
+
function baseDir () {
|
|
143
|
+
if (!board || !board.baseDir) throw new Error('storyboard.baseDir() called before the plugin saw the scenario')
|
|
144
|
+
return board.baseDir
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function panel (title, opts = {}) {
|
|
148
|
+
if (!board) begin({})
|
|
149
|
+
board.panels.push({ title, note: opts.note || '', copy: opts.copy || '', images: [] })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function frame (pngPath, opts = {}) {
|
|
153
|
+
const current = board && board.panels[board.panels.length - 1]
|
|
154
|
+
if (!current) throw new Error('storyboard.frame() called with no open panel')
|
|
155
|
+
current.images.push({ file: pngPath, note: opts.note, copy: opts.copy })
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Merge late annotations (e.g. a URL only known mid-step) into the open panel.
|
|
159
|
+
function annotate (opts = {}) {
|
|
160
|
+
const current = board && board.panels[board.panels.length - 1]
|
|
161
|
+
if (!current) throw new Error('storyboard.annotate() called with no open panel')
|
|
162
|
+
if (opts.note) current.note = opts.note
|
|
163
|
+
if (opts.copy) current.copy = opts.copy
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function panels () {
|
|
167
|
+
return board ? board.panels : []
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
// Step-side API ā register a sentence as a card, capture and assert frames.
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
// Storyboard sentences are LITERAL: a cucumber-expression would reinterpret
|
|
175
|
+
// "CI/CD" as an alternation and "(...)" as optional text. Escape the
|
|
176
|
+
// metacharacters at registration so the .feature line, the registered step
|
|
177
|
+
// and the card title stay the exact same verbatim string.
|
|
178
|
+
function escapeCucumberExpression (sentence) {
|
|
179
|
+
return sentence.replace(/[\\/(){}]/g, '\\$&')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Register a Gherkin step through its Given/When/Then function. The card
|
|
183
|
+
// itself opens AUTOMATICALLY (the plugin listens to bddStep.before), so this
|
|
184
|
+
// wrapper only (1) escapes cucumber-expression metacharacters so the .feature
|
|
185
|
+
// line and the pattern stay the exact same verbatim string, and (2) applies
|
|
186
|
+
// legacy JS note/copy options ā new scenarios should prefer `# Note:` /
|
|
187
|
+
// `# Copy:` comments in the .feature instead. `opts` is optional.
|
|
188
|
+
function storyboardStep (register, pattern, opts, fn) {
|
|
189
|
+
if (typeof opts === 'function') {
|
|
190
|
+
fn = opts
|
|
191
|
+
opts = null
|
|
192
|
+
}
|
|
193
|
+
register(escapeCucumberExpression(pattern), async (...args) => {
|
|
194
|
+
if (opts && (opts.note || opts.copy)) annotate(opts)
|
|
195
|
+
await fn(...args)
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function frameOutputPath (frameName) {
|
|
200
|
+
return path.join(e2eDir(), '_output', 'storyboard-frames', frameName + '.png')
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Full-page snapshot of the CURRENT page (mask its volatile content first)
|
|
204
|
+
// into the frames dir; returns the PNG's absolute path.
|
|
205
|
+
async function capturePageFrame (I, frameName) {
|
|
206
|
+
fs.mkdirSync(path.dirname(frameOutputPath(frameName)), { recursive: true })
|
|
207
|
+
await I.takeScreenshot(`storyboard-frames/${frameName}`)
|
|
208
|
+
return frameOutputPath(frameName)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Element-cropped snapshot: the frame is EXACTLY the selector's box, never
|
|
212
|
+
// the whole viewport ā a short verdict yields a short frame, not a mostly
|
|
213
|
+
// empty page. Use for rendered <pre> verdicts and any focused element.
|
|
214
|
+
async function captureElementFrame (I, frameName, selector) {
|
|
215
|
+
fs.mkdirSync(path.dirname(frameOutputPath(frameName)), { recursive: true })
|
|
216
|
+
await I.captureScreenshot(`storyboard-frames/${frameName}`, 'actual', selector)
|
|
217
|
+
return frameOutputPath(frameName)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Guarantee the capture actually rendered: a frame whose sampled pixels are
|
|
221
|
+
// ~one single colour is a blank/unfinished capture (page not loaded, empty
|
|
222
|
+
// render) and must fail LOUD at capture time, not survive into a baseline.
|
|
223
|
+
function assertFrameNotEmpty (png) {
|
|
224
|
+
const img = PNG.sync.read(fs.readFileSync(png))
|
|
225
|
+
const { width, height, data } = img
|
|
226
|
+
const step = Math.max(1, Math.floor(Math.sqrt((width * height) / 20000)))
|
|
227
|
+
const counts = new Map()
|
|
228
|
+
let sampled = 0
|
|
229
|
+
for (let y = 0; y < height; y += step) {
|
|
230
|
+
for (let x = 0; x < width; x += step) {
|
|
231
|
+
const i = (width * y + x) << 2
|
|
232
|
+
// Quantize to 4 bits per channel so soft gradients still count as one colour.
|
|
233
|
+
const key = ((data[i] >> 4) << 8) | ((data[i + 1] >> 4) << 4) | (data[i + 2] >> 4)
|
|
234
|
+
counts.set(key, (counts.get(key) || 0) + 1)
|
|
235
|
+
sampled++
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
const dominant = Math.max(...counts.values())
|
|
239
|
+
const ratio = dominant / sampled
|
|
240
|
+
if (ratio > 0.985) {
|
|
241
|
+
throw new Error(
|
|
242
|
+
`storyboard frame "${path.basename(png)}" looks empty ā ${(ratio * 100).toFixed(1)}% of its pixels are a single colour. ` +
|
|
243
|
+
'The capture probably fired before the content rendered (or the element crop missed). Fix the capture; do not baseline a blank frame.'
|
|
244
|
+
)
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Assert `_output/<baselineName>.png` against its committed baseline, or ā in
|
|
250
|
+
* baseline-update mode (TASK_E2E_UPDATE_BASELINES=1) ā assert first and only
|
|
251
|
+
* when the assert FAILS persist the freshly captured actual as the baseline:
|
|
252
|
+
* green baselines stay byte-identical, so a regeneration run produces no
|
|
253
|
+
* churn. Each baseline produced this way MUST be inspected by a human, which
|
|
254
|
+
* is why the mode is refused in CI ā there it would silently swallow every
|
|
255
|
+
* visual regression.
|
|
256
|
+
*/
|
|
257
|
+
async function assertOrUpdateBaseline (I, baselineName) {
|
|
258
|
+
if (process.env.TASK_E2E_UPDATE_BASELINES && process.env.CI) {
|
|
259
|
+
throw new Error('TASK_E2E_UPDATE_BASELINES is forbidden in CI ā baselines must be regenerated and inspected locally')
|
|
260
|
+
}
|
|
261
|
+
if (process.env.TASK_E2E_UPDATE_BASELINES) {
|
|
262
|
+
// tryTo: the recorder marks the test failed on a plain try/catch around
|
|
263
|
+
// an actor call; tryTo is the supported way to probe an assert. Since
|
|
264
|
+
// CodeceptJS 4 it is no longer a plugin exposing a global ā it is an
|
|
265
|
+
// effect imported from the package, and only this directory can resolve
|
|
266
|
+
// it (node_modules lives here, not in the test tree), which is why the
|
|
267
|
+
// module re-exports it below.
|
|
268
|
+
const matches = await tryTo(() => I.assertVisualMatch(baselineName, { captureActual: false }))
|
|
269
|
+
if (!matches) {
|
|
270
|
+
const actualPath = path.join(e2eDir(), '_output', baselineName + '.png')
|
|
271
|
+
const baselinePath = path.join(e2eDir(), 'screenshots', 'base', baselineName + '.png')
|
|
272
|
+
fs.mkdirSync(path.dirname(baselinePath), { recursive: true })
|
|
273
|
+
fs.copyFileSync(actualPath, baselinePath)
|
|
274
|
+
}
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
await I.assertVisualMatch(baselineName, { captureActual: false })
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// Attach the frame to the current card and assert it against its own
|
|
281
|
+
// baseline immediately (tolerance: 0, update-mode aware): a visual
|
|
282
|
+
// regression fails on the exact sentence whose image drifted, and the error
|
|
283
|
+
// message carries everything a human needs to act on it.
|
|
284
|
+
async function addStoryboardFrame (I, png) {
|
|
285
|
+
assertFrameNotEmpty(png)
|
|
286
|
+
frame(png)
|
|
287
|
+
const name = `${baseDir()}/${path.basename(png, '.png')}`
|
|
288
|
+
const actualPath = path.join(e2eDir(), '_output', `${name}.png`)
|
|
289
|
+
fs.mkdirSync(path.dirname(actualPath), { recursive: true })
|
|
290
|
+
fs.copyFileSync(png, actualPath)
|
|
291
|
+
try {
|
|
292
|
+
await assertOrUpdateBaseline(I, name)
|
|
293
|
+
} catch (err) {
|
|
294
|
+
// Exact marker of WHICH frame failed its visual assert ā the failure band
|
|
295
|
+
// trusts this, never a heuristic (a diff PNG may not even exist, e.g. on
|
|
296
|
+
// an "Image dimensions do not match" error).
|
|
297
|
+
if (board) board.visualFailure = path.basename(png)
|
|
298
|
+
if (err && typeof err.message === 'string') {
|
|
299
|
+
err.message +=
|
|
300
|
+
`\n storyboard frame : ${name}.png` +
|
|
301
|
+
`\n pixel diff : screenshots/diff/${path.dirname(name)}/Diff_${path.basename(name)}.png` +
|
|
302
|
+
`\n failure storyboard : _output/${board && board.baseDir ? board.baseDir : '<scenario>'}.svg` +
|
|
303
|
+
(board && board.rerun
|
|
304
|
+
? `\n deliberate change? regenerate locally, then inspect: TASK_E2E_UPDATE_BASELINES=1 ${board.rerun}`
|
|
305
|
+
: '')
|
|
306
|
+
}
|
|
307
|
+
throw err
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ---------------------------------------------------------------------------
|
|
312
|
+
// SVG rendering ā pure Node, no dependencies.
|
|
313
|
+
// ---------------------------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
// PNG dimensions live in the header chunk: width/height big-endian at bytes 16/20.
|
|
316
|
+
function pngSize (file) {
|
|
317
|
+
const buf = Buffer.alloc(24)
|
|
318
|
+
const fd = fs.openSync(file, 'r')
|
|
319
|
+
fs.readSync(fd, buf, 0, 24, 0)
|
|
320
|
+
fs.closeSync(fd)
|
|
321
|
+
return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function esc (text) {
|
|
325
|
+
return String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// SVG has no text auto-wrap: break on words against an estimated glyph width.
|
|
329
|
+
function wrap (text, maxWidth, charWidth) {
|
|
330
|
+
const perLine = Math.max(8, Math.floor(maxWidth / charWidth))
|
|
331
|
+
const lines = []
|
|
332
|
+
// A newline is a deliberate paragraph break (several `# Note:` lines), kept
|
|
333
|
+
// as one blank line so the card breathes instead of reading as a wall.
|
|
334
|
+
String(text).split('\n').forEach((paragraph, index) => {
|
|
335
|
+
if (index > 0) lines.push('')
|
|
336
|
+
let line = ''
|
|
337
|
+
for (const word of paragraph.split(/\s+/).filter(Boolean)) {
|
|
338
|
+
const candidate = line ? line + ' ' + word : word
|
|
339
|
+
if (candidate.length > perLine && line) {
|
|
340
|
+
lines.push(line)
|
|
341
|
+
line = word
|
|
342
|
+
} else {
|
|
343
|
+
line = candidate
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (line) lines.push(line)
|
|
347
|
+
})
|
|
348
|
+
return lines
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const THEME = {
|
|
352
|
+
bg: '#0f1017',
|
|
353
|
+
card: '#181a24',
|
|
354
|
+
slot: '#0b0c12',
|
|
355
|
+
text: '#e8e8ec',
|
|
356
|
+
dim: '#98a0b3',
|
|
357
|
+
accent: '#7aa2f7',
|
|
358
|
+
badge: '#3b82f6',
|
|
359
|
+
codeBg: '#1c1e2a',
|
|
360
|
+
given: '#9ece6a',
|
|
361
|
+
when: '#7aa2f7',
|
|
362
|
+
then: '#bb9af7',
|
|
363
|
+
fail: '#f7768e',
|
|
364
|
+
sans: 'ui-sans-serif, system-ui, sans-serif',
|
|
365
|
+
mono: "ui-monospace, 'JetBrains Mono', 'Fira Code', monospace"
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Two-column grid of uniform cards, one card per frame: the image sits
|
|
369
|
+
// full-width at the top of the card in a fixed-height slot (scaled to fit,
|
|
370
|
+
// letterboxed on the slot colour), the texts below. 700x438 keeps the
|
|
371
|
+
// 1024x640 GitLab pages at their exact aspect ratio.
|
|
372
|
+
const GRID = {
|
|
373
|
+
cols: 2,
|
|
374
|
+
cardW: 700,
|
|
375
|
+
pagePad: 32,
|
|
376
|
+
gap: 24,
|
|
377
|
+
textPad: 18
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Write the storyboard SVG. options.imageDir substitutes every frame with the
|
|
382
|
+
* same-named PNG inside that directory ā used to build the COMMITTED SVG from
|
|
383
|
+
* the reviewed baselines instead of the run's actuals. options.failure (built
|
|
384
|
+
* by the plugin on a failed test) marks the drifted card in red, embeds its
|
|
385
|
+
* pixel-diff image as an extra card, and lists the sentences the journey
|
|
386
|
+
* never reached ā one downloadable artifact tells the whole debugging story.
|
|
387
|
+
*/
|
|
388
|
+
function render (outFile, options = {}) {
|
|
389
|
+
if (!board || !board.panels.length) {
|
|
390
|
+
throw new Error('storyboard.render() called with no panels')
|
|
391
|
+
}
|
|
392
|
+
const t = THEME
|
|
393
|
+
const g = GRID
|
|
394
|
+
const failure = options.failure || null
|
|
395
|
+
const resolveImage = (file) =>
|
|
396
|
+
options.imageDir ? path.join(options.imageDir, path.basename(file)) : file
|
|
397
|
+
|
|
398
|
+
// One card per frame; a multi-frame panel repeats its number and title so
|
|
399
|
+
// every card still reads as its Gherkin line. The card whose pixels drifted
|
|
400
|
+
// is flagged (red chrome) ā the full-width comparison band above the grid
|
|
401
|
+
// carries its expected / diff / actual triptych.
|
|
402
|
+
// Verbatim Gherkin keyword of a sentence (And/But included), coloured by
|
|
403
|
+
// its resolved group so the grid scans as stage / actions / proofs.
|
|
404
|
+
const lineOf = (title) => (board.lines || []).find(l => l.text === title)
|
|
405
|
+
|
|
406
|
+
const failName = failure && failure.frame && failure.frame.name
|
|
407
|
+
// note/copy precedence: per-frame value > JS panel value (opts/annotate,
|
|
408
|
+
// e.g. a URL only known at runtime) > `# Note:` / `# Copy:` comment in the
|
|
409
|
+
// .feature ā the feature file is the default source of the human text.
|
|
410
|
+
const cards = board.panels.flatMap((p, pi) => {
|
|
411
|
+
const line = lineOf(p.title)
|
|
412
|
+
return p.images.map((img, fi) => ({
|
|
413
|
+
n: pi + 1,
|
|
414
|
+
first: fi === 0,
|
|
415
|
+
title: p.title,
|
|
416
|
+
note: img.note !== undefined ? img.note : (fi === 0 ? (p.note || (line && line.note) || '') : ''),
|
|
417
|
+
copy: img.copy !== undefined ? img.copy : (fi === 0 ? (p.copy || (line && line.copy) || '') : ''),
|
|
418
|
+
file: resolveImage(img.file),
|
|
419
|
+
failed: failName === path.basename(img.file)
|
|
420
|
+
}))
|
|
421
|
+
})
|
|
422
|
+
const keywordColor = { given: t.given, when: t.when, then: t.then }
|
|
423
|
+
|
|
424
|
+
const width = 2 * g.pagePad + g.cols * g.cardW + (g.cols - 1) * g.gap
|
|
425
|
+
const textW = g.cardW - 2 * g.textPad
|
|
426
|
+
const parts = []
|
|
427
|
+
|
|
428
|
+
const text = (str, x, yy, { size = 14, fill = t.text, font = t.sans, weight = 'normal', anchor = 'start', cls = '' } = {}) => {
|
|
429
|
+
parts.push(
|
|
430
|
+
`<text x="${x}" y="${yy}" font-family="${font}" font-size="${size}" fill="${fill}"` +
|
|
431
|
+
(weight !== 'normal' ? ` font-weight="${weight}"` : '') +
|
|
432
|
+
(anchor !== 'start' ? ` text-anchor="${anchor}"` : '') +
|
|
433
|
+
(cls ? ` class="${cls}"` : '') +
|
|
434
|
+
`>${esc(str)}</text>`
|
|
435
|
+
)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// A copyable command: ONE <text class="copy"> so a single click selects the
|
|
439
|
+
// WHOLE command (user-select:all ā Chromium/Safari; inert elsewhere). Each
|
|
440
|
+
// wrapped line is a <tspan>; tspans concatenate with NO separator on copy,
|
|
441
|
+
// so every line but the last keeps a trailing space (xml:space preserves it).
|
|
442
|
+
const copyText = (str, x, yy, { size = 12.5, fill = t.accent } = {}) => {
|
|
443
|
+
const lines = wrap(str, textW, 7.6)
|
|
444
|
+
const tspans = lines.map((line, i) =>
|
|
445
|
+
`<tspan x="${x}" dy="${i === 0 ? 0 : 18}">${esc(line + (i < lines.length - 1 ? ' ' : ''))}</tspan>`
|
|
446
|
+
).join('')
|
|
447
|
+
parts.push(
|
|
448
|
+
`<text x="${x}" y="${yy}" font-family="${t.mono}" font-size="${size}" fill="${fill}"` +
|
|
449
|
+
` class="copy" xml:space="preserve">${tspans}</text>`
|
|
450
|
+
)
|
|
451
|
+
return lines.length
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Draw an image letterboxed inside a box (scaled to fit, centred on the
|
|
455
|
+
// slot colour), with an optional native <title> tooltip.
|
|
456
|
+
const drawImage = (file, x, y, boxW, boxH, tooltip) => {
|
|
457
|
+
const { w, h } = pngSize(file)
|
|
458
|
+
const data = fs.readFileSync(file).toString('base64')
|
|
459
|
+
const scale = Math.min(boxW / w, boxH / h)
|
|
460
|
+
const dw = w * scale
|
|
461
|
+
const dh = h * scale
|
|
462
|
+
parts.push(`<rect x="${x}" y="${y}" width="${boxW}" height="${boxH}" fill="${t.slot}"/>`)
|
|
463
|
+
parts.push(
|
|
464
|
+
`<image x="${(x + (boxW - dw) / 2).toFixed(1)}" y="${(y + (boxH - dh) / 2).toFixed(1)}"` +
|
|
465
|
+
` width="${dw.toFixed(1)}" height="${dh.toFixed(1)}" href="data:image/png;base64,${data}">` +
|
|
466
|
+
(tooltip ? `<title>${esc(tooltip)}</title>` : '') + '</image>'
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// Full-width failure band, rendered IN PLACE of the drifted card (which is
|
|
471
|
+
// always the last one ā the assert throws there and stops the run): the
|
|
472
|
+
// expected / diff / actual triptych read leftāright (what it should be,
|
|
473
|
+
// exactly which pixels changed, what this run produced), each image over
|
|
474
|
+
// its full, copyable file path ā zero ambiguity, all in one artifact.
|
|
475
|
+
// Wrap a filesystem path onto up to `maxLines` lines, breaking on '/' (kept
|
|
476
|
+
// attached to its segment) so no line overflows its slot. Path segments have
|
|
477
|
+
// no spaces, so tspans concatenate back to the exact path on copy.
|
|
478
|
+
const pathLines = (str, slotW, maxLines = 2) => {
|
|
479
|
+
const perLine = Math.max(8, Math.floor(slotW / 6.6))
|
|
480
|
+
const segments = String(str).split('/').map((s, i, a) => i < a.length - 1 ? s + '/' : s)
|
|
481
|
+
const lines = []
|
|
482
|
+
let line = ''
|
|
483
|
+
for (const segment of segments) {
|
|
484
|
+
if ((line + segment).length > perLine && line) { lines.push(line); line = segment } else { line += segment }
|
|
485
|
+
}
|
|
486
|
+
if (line) lines.push(line)
|
|
487
|
+
return lines.slice(0, maxLines)
|
|
488
|
+
}
|
|
489
|
+
const bandPathH = 32
|
|
490
|
+
const failBandHeight = () => 46 + 12 + 22 + 300 + bandPathH + 16
|
|
491
|
+
const drawFailureBand = (frame, top) => {
|
|
492
|
+
const bandW = width - 2 * g.pagePad
|
|
493
|
+
const slotH = 300
|
|
494
|
+
const headerH = 46
|
|
495
|
+
const bandH = failBandHeight()
|
|
496
|
+
parts.push(`<rect x="${g.pagePad}" y="${top}" width="${bandW}" height="${bandH}" rx="12" fill="${t.card}" stroke="${t.fail}" stroke-width="3"/>`)
|
|
497
|
+
|
|
498
|
+
// Red header: which step and sentence regressed.
|
|
499
|
+
parts.push(`<rect x="${g.pagePad}" y="${top}" width="${bandW}" height="${headerH}" rx="12" fill="${t.fail}"/>`)
|
|
500
|
+
parts.push(`<rect x="${g.pagePad}" y="${top + headerH - 12}" width="${bandW}" height="12" fill="${t.fail}"/>`)
|
|
501
|
+
text(`ā Visual regression ā step ${frame.step}: ${frame.keyword ? frame.keyword + ' ' : ''}${frame.sentence}`,
|
|
502
|
+
g.pagePad + 18, top + 30, { size: 16, fill: '#ffffff', weight: '700' })
|
|
503
|
+
text(frame.name, width - g.pagePad - 18, top + 30, { size: 12.5, fill: '#ffffff', font: t.mono, anchor: 'end' })
|
|
504
|
+
|
|
505
|
+
const p = frame.paths || {}
|
|
506
|
+
const gap = 16
|
|
507
|
+
const slotW = (bandW - 2 * gap) / 3
|
|
508
|
+
const cols = [
|
|
509
|
+
{ file: frame.baseline, label: 'Expected (baseline)', pathText: p.expected },
|
|
510
|
+
{ file: frame.diff, label: 'Diff ā changed pixels', pathText: p.diff },
|
|
511
|
+
{ file: frame.actual, label: 'Actual (this run)', pathText: p.actual }
|
|
512
|
+
]
|
|
513
|
+
cols.forEach((col, ci) => {
|
|
514
|
+
const x = g.pagePad + ci * (slotW + gap)
|
|
515
|
+
const ly = top + headerH + 12 + 15
|
|
516
|
+
text(col.label, x + 2, ly, { size: 13, fill: ci === 1 ? t.fail : t.dim, weight: '600' })
|
|
517
|
+
if (col.file && fs.existsSync(col.file)) {
|
|
518
|
+
drawImage(col.file, x, ly + 8, slotW, slotH, col.pathText)
|
|
519
|
+
} else {
|
|
520
|
+
parts.push(`<rect x="${x}" y="${ly + 8}" width="${slotW}" height="${slotH}" fill="${t.slot}"/>`)
|
|
521
|
+
text('(not generated)', x + slotW / 2, ly + 8 + slotH / 2, { size: 13, fill: t.dim, anchor: 'middle' })
|
|
522
|
+
}
|
|
523
|
+
// Full, one-click-copyable path to the file ā open it or hand it to a
|
|
524
|
+
// command without retyping. Wrapped on '/' so it never overflows.
|
|
525
|
+
if (col.pathText) {
|
|
526
|
+
const pl = pathLines(col.pathText, slotW)
|
|
527
|
+
const tspans = pl.map((line, li) =>
|
|
528
|
+
`<tspan x="${x + 2}" dy="${li === 0 ? 0 : 13}">${esc(line)}</tspan>`
|
|
529
|
+
).join('')
|
|
530
|
+
parts.push(
|
|
531
|
+
`<text x="${x + 2}" y="${ly + 8 + slotH + 14}" font-family="${t.mono}" font-size="11" fill="${t.accent}"` +
|
|
532
|
+
` class="copy" xml:space="preserve">${tspans}</text>`
|
|
533
|
+
)
|
|
534
|
+
}
|
|
535
|
+
})
|
|
536
|
+
return bandH
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Text block of a card. Glyph-width estimates are deliberately generous
|
|
540
|
+
// (bold sans ā 9.3px/char at 15.5px) ā an over-wrap is invisible, an
|
|
541
|
+
// under-wrap bleeds into the next card.
|
|
542
|
+
const layoutOf = (card) => {
|
|
543
|
+
const line = lineOf(card.title)
|
|
544
|
+
const keyword = line ? line.keyword : ''
|
|
545
|
+
const title = wrap(`${keyword ? keyword + ' ' : ''}${card.title}`, textW, 9.3)
|
|
546
|
+
const note = card.note ? wrap(card.note, textW, 7.2) : []
|
|
547
|
+
const copy = card.copy ? wrap(card.copy, textW, 8.0) : []
|
|
548
|
+
return { keyword, group: line ? line.group : '', title, note, copy, h: 16 + title.length * 21 + note.length * 18 + (copy.length ? 6 + copy.length * 18 : 0) + 16 }
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// ADAPTIVE slots: the image is shown at natural size (downscaled only when
|
|
552
|
+
// wider than the card or taller than MAX_SLOT_H ā never upscaled, terminal
|
|
553
|
+
// text must stay crisp) and the slot HUGS it: a 3-line verdict gets a short
|
|
554
|
+
// card, a 90-line one gets a tall card. Cards on the same ROW share the
|
|
555
|
+
// row's tallest slot/text so the grid stays aligned without drowning short
|
|
556
|
+
// frames in letterbox.
|
|
557
|
+
const MAX_SLOT_H = 1100
|
|
558
|
+
const slotOf = (card) => {
|
|
559
|
+
const { w, h } = pngSize(card.file)
|
|
560
|
+
const scale = Math.min(1, g.cardW / w, MAX_SLOT_H / h)
|
|
561
|
+
return { scale, dispW: w * scale, dispH: h * scale }
|
|
562
|
+
}
|
|
563
|
+
// Cards flow in READING ORDER, two per row, and the two cards of a row are
|
|
564
|
+
// fully UNIFORM: one shared image slot (as tall as the row's tallest frame ā
|
|
565
|
+
// a smaller frame is centred inside it) and one shared text zone starting at
|
|
566
|
+
// the same height in both cards. The top BADGE_BAND of every card is
|
|
567
|
+
// reserved for the number badge so it never covers the first line of a
|
|
568
|
+
// frame. A `# Chapter:` comment in the .feature closes the current row and
|
|
569
|
+
// inserts a full-width chapter band ā that is how a 20-card story keeps a
|
|
570
|
+
// beginning, a middle and an end.
|
|
571
|
+
const BADGE_BAND = 28
|
|
572
|
+
const CHAPTER_BAND = 56
|
|
573
|
+
const slots2d = []
|
|
574
|
+
const chapterBands = []
|
|
575
|
+
let rowTop = 0
|
|
576
|
+
let row = []
|
|
577
|
+
const flushRow = () => {
|
|
578
|
+
if (!row.length) return
|
|
579
|
+
const rowSlot = Math.max(...row.map(i => BADGE_BAND + Math.ceil(slotOf(cards[i]).dispH)))
|
|
580
|
+
const rowText = Math.max(...row.map(i => Math.ceil(layoutOf(cards[i]).h)))
|
|
581
|
+
row.forEach((cardIndex, col) => {
|
|
582
|
+
slots2d[cardIndex] = { col, top: rowTop, slotH: rowSlot, h: rowSlot + rowText }
|
|
583
|
+
})
|
|
584
|
+
rowTop += rowSlot + rowText + g.gap
|
|
585
|
+
row = []
|
|
586
|
+
}
|
|
587
|
+
cards.forEach((card, i) => {
|
|
588
|
+
const line = lineOf(card.title)
|
|
589
|
+
if (card.first && line && line.chapter) {
|
|
590
|
+
flushRow()
|
|
591
|
+
chapterBands.push({ title: line.chapter, top: rowTop, n: chapterBands.length + 1 })
|
|
592
|
+
rowTop += CHAPTER_BAND + g.gap
|
|
593
|
+
}
|
|
594
|
+
if (row.length === g.cols) flushRow()
|
|
595
|
+
row.push(i)
|
|
596
|
+
})
|
|
597
|
+
flushRow()
|
|
598
|
+
const gridHeight = cards.length ? rowTop - g.gap : 0
|
|
599
|
+
|
|
600
|
+
// --- Header: feature left (wrapped, never under the right column), the
|
|
601
|
+
// scenario under it, file path top-right, then the rerun bar. ---
|
|
602
|
+
const drawHeader = () => {
|
|
603
|
+
const rightZone = 470
|
|
604
|
+
const titleW = width - 2 * g.pagePad - rightZone
|
|
605
|
+
let hy = 54
|
|
606
|
+
for (const line of wrap(board.feature, titleW, 16.8)) {
|
|
607
|
+
text(line, g.pagePad, hy, { size: 28, weight: '700' })
|
|
608
|
+
hy += 34
|
|
609
|
+
}
|
|
610
|
+
for (const line of wrap('Scenario: ' + board.scenario, titleW, 8.7)) {
|
|
611
|
+
text(line, g.pagePad, hy - 6, { size: 15, fill: t.dim })
|
|
612
|
+
hy += 20
|
|
613
|
+
}
|
|
614
|
+
if (board.file) {
|
|
615
|
+
text(board.file, width - g.pagePad, 44, { size: 12, fill: t.dim, font: t.mono, anchor: 'end' })
|
|
616
|
+
text('e2e storyboard Ā· baseline', width - g.pagePad, 62, { size: 12, fill: t.dim, anchor: 'end' })
|
|
617
|
+
}
|
|
618
|
+
hy = Math.max(hy + 8, 104)
|
|
619
|
+
if (board.rerun) {
|
|
620
|
+
parts.push(`<rect x="${g.pagePad}" y="${hy}" width="${width - 2 * g.pagePad}" height="36" rx="8" fill="${t.codeBg}"/>`)
|
|
621
|
+
text('replay this scenario', g.pagePad + 16, hy + 23, { size: 12.5, fill: t.dim })
|
|
622
|
+
copyText(board.rerun, g.pagePad + 170, hy + 23, { size: 13 })
|
|
623
|
+
hy += 36
|
|
624
|
+
}
|
|
625
|
+
return hy + 28
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// --- Footer: failure band (in place of the drifted card), the sentences
|
|
629
|
+
// never reached, the verdict line and the colour legend. ---
|
|
630
|
+
const drawFooter = (fy) => {
|
|
631
|
+
if (failure && failure.frame) {
|
|
632
|
+
if (cards.length) fy += g.gap
|
|
633
|
+
fy += drawFailureBand(failure.frame, fy)
|
|
634
|
+
}
|
|
635
|
+
if (failure && failure.notReached && failure.notReached.length) {
|
|
636
|
+
fy += 34
|
|
637
|
+
for (const line of failure.notReached) {
|
|
638
|
+
text('ā', g.pagePad + 4, fy, { size: 13, fill: t.dim, weight: '600' })
|
|
639
|
+
text(`${line.keyword} ${line.text} ā not reached`, g.pagePad + 26, fy, { size: 13.5, fill: t.dim })
|
|
640
|
+
fy += 20
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
fy += 30
|
|
644
|
+
const proven = board.panels.filter(p => p.images.length).length
|
|
645
|
+
const verdict = failure
|
|
646
|
+
? `FAILED ā ${proven} of ${(board.lines || []).length || board.panels.length} sentences proven Ā· the red band shows where it broke (expected / diff / actual)`
|
|
647
|
+
: `Storyboard e2e Ā· ${board.panels.length} steps Ā· ${cards.length} frames Ā· every frame is its own pixel baseline (tolerance: 0)`
|
|
648
|
+
text(verdict, g.pagePad, fy, { size: failure ? 12.5 : 12, fill: failure ? t.fail : t.dim, weight: failure ? '600' : 'normal' })
|
|
649
|
+
parts.push(
|
|
650
|
+
`<text x="${width - g.pagePad}" y="${fy}" font-family="${t.sans}" font-size="12" fill="${t.dim}" text-anchor="end">` +
|
|
651
|
+
`<tspan fill="${t.given}">ā</tspan> Given ā stage <tspan fill="${t.when}">ā</tspan> When ā actions ` +
|
|
652
|
+
`<tspan fill="${t.then}">ā</tspan> Then ā proofs</text>`
|
|
653
|
+
)
|
|
654
|
+
return fy
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
let y = drawHeader()
|
|
658
|
+
|
|
659
|
+
// --- Chapter bands: full-width titled strips between rows. ---
|
|
660
|
+
chapterBands.forEach((band) => {
|
|
661
|
+
const bw = width - 2 * g.pagePad
|
|
662
|
+
parts.push(`<rect x="${g.pagePad}" y="${y + band.top}" width="${bw}" height="${CHAPTER_BAND}" rx="10" fill="${t.codeBg}"/>`)
|
|
663
|
+
parts.push(`<rect x="${g.pagePad}" y="${y + band.top}" width="6" height="${CHAPTER_BAND}" fill="${t.accent}"/>`)
|
|
664
|
+
text(`Chapter ${band.n}`, g.pagePad + 26, y + band.top + 35, { size: 17, fill: t.accent, weight: '700' })
|
|
665
|
+
text(band.title, g.pagePad + 26 + 9.5 * `Chapter ${band.n}`.length + 18, y + band.top + 35, { size: 17, weight: '600' })
|
|
666
|
+
})
|
|
667
|
+
|
|
668
|
+
// --- Cards (every captured frame, the drifted one red-outlined). Rows have
|
|
669
|
+
// their own heights; inside a row every card is top-aligned. ---
|
|
670
|
+
cards.forEach((card, i) => {
|
|
671
|
+
const { scale, dispW, dispH } = slotOf(card)
|
|
672
|
+
const slotH = slots2d[i].slotH
|
|
673
|
+
const cardH = slots2d[i].h
|
|
674
|
+
const cx = g.pagePad + slots2d[i].col * (g.cardW + g.gap)
|
|
675
|
+
const cy = y + slots2d[i].top
|
|
676
|
+
|
|
677
|
+
parts.push(`<clipPath id="card${i}"><rect x="${cx}" y="${cy}" width="${g.cardW}" height="${cardH}" rx="12"/></clipPath>`)
|
|
678
|
+
parts.push(
|
|
679
|
+
`<rect x="${cx}" y="${cy}" width="${g.cardW}" height="${cardH}" rx="12" fill="${t.card}"` +
|
|
680
|
+
(card.failed ? ` stroke="${t.fail}" stroke-width="3"` : '') + '/>'
|
|
681
|
+
)
|
|
682
|
+
parts.push(`<g clip-path="url(#card${i})">`)
|
|
683
|
+
// The image at NATURAL size (downscaled only when oversized), centred both
|
|
684
|
+
// ways inside the ROW's shared slot: the two cards of a row keep the same
|
|
685
|
+
// image zone and the same text zone, whatever each frame's own size.
|
|
686
|
+
parts.push(`<rect x="${cx}" y="${cy}" width="${g.cardW}" height="${slotH}" fill="${t.slot}"/>`)
|
|
687
|
+
const data = fs.readFileSync(card.file).toString('base64')
|
|
688
|
+
const iy = cy + BADGE_BAND + (slotH - BADGE_BAND - Math.ceil(dispH)) / 2
|
|
689
|
+
parts.push(
|
|
690
|
+
`<image x="${(cx + (g.cardW - dispW) / 2).toFixed(1)}" y="${iy.toFixed(1)}"` +
|
|
691
|
+
` width="${dispW.toFixed(1)}" height="${dispH.toFixed(1)}" href="data:image/png;base64,${data}">` +
|
|
692
|
+
`<title>${esc(path.basename(card.file))}${scale < 1 ? ` (shown at ${(scale * 100).toFixed(0)}%)` : ''}</title></image>`
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
const layout = layoutOf(card)
|
|
696
|
+
let ty = cy + slotH + 16 + 15
|
|
697
|
+
layout.title.forEach((line, li) => {
|
|
698
|
+
if (li === 0 && layout.keyword && line.startsWith(layout.keyword)) {
|
|
699
|
+
// Verbatim keyword coloured by its group ā the only chrome that also
|
|
700
|
+
// survives GitLab's image-based preview.
|
|
701
|
+
const rest = line.slice(layout.keyword.length)
|
|
702
|
+
parts.push(
|
|
703
|
+
`<text x="${cx + g.textPad}" y="${ty}" font-family="${t.sans}" font-size="15.5" font-weight="600"` +
|
|
704
|
+
` fill="${t.text}" xml:space="preserve"><tspan fill="${keywordColor[layout.group] || t.dim}">${esc(layout.keyword)}</tspan>${esc(rest)}</text>`
|
|
705
|
+
)
|
|
706
|
+
} else {
|
|
707
|
+
text(line, cx + g.textPad, ty, { size: 15.5, weight: '600' })
|
|
708
|
+
}
|
|
709
|
+
ty += 21
|
|
710
|
+
})
|
|
711
|
+
for (const line of layout.note) {
|
|
712
|
+
text(line, cx + g.textPad, ty, { size: 12.8, fill: t.dim })
|
|
713
|
+
ty += 18
|
|
714
|
+
}
|
|
715
|
+
if (layout.copy.length) {
|
|
716
|
+
ty += 6
|
|
717
|
+
copyText(card.copy, cx + g.textPad, ty)
|
|
718
|
+
ty += layout.copy.length * 18
|
|
719
|
+
}
|
|
720
|
+
parts.push('</g>')
|
|
721
|
+
|
|
722
|
+
// Number badge astride the card's TOP-LEFT CORNER ā on the chrome, never
|
|
723
|
+
// over the captured pixels.
|
|
724
|
+
parts.push(`<circle cx="${cx + 4}" cy="${cy + 4}" r="16" fill="${card.failed ? t.fail : t.badge}"/>`)
|
|
725
|
+
text(String(card.n), cx + 4, cy + 9, { size: 15, fill: '#ffffff', weight: '700', anchor: 'middle' })
|
|
726
|
+
})
|
|
727
|
+
|
|
728
|
+
if (cards.length) y += gridHeight
|
|
729
|
+
y = drawFooter(y)
|
|
730
|
+
|
|
731
|
+
const height = y + g.pagePad
|
|
732
|
+
const svg =
|
|
733
|
+
// The W3C namespace is an identifier, not a network request.
|
|
734
|
+
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"` + // DevSkim: ignore DS137138
|
|
735
|
+
' role="img" aria-labelledby="sb-title sb-desc">\n' +
|
|
736
|
+
`<title id="sb-title">${esc(board.feature)} ā ${esc(board.scenario)}</title>\n` +
|
|
737
|
+
`<desc id="sb-desc">e2e storyboard Ā· ${esc(board.file)} Ā· replay: ${esc(board.rerun)}</desc>\n` +
|
|
738
|
+
'<style>.copy{user-select:all;-webkit-user-select:all;cursor:text}.copy:hover{text-decoration:underline}</style>\n' +
|
|
739
|
+
`<rect width="${width}" height="${height}" fill="${t.bg}"/>\n` +
|
|
740
|
+
parts.join('\n') +
|
|
741
|
+
'\n</svg>\n'
|
|
742
|
+
|
|
743
|
+
fs.mkdirSync(path.dirname(outFile), { recursive: true })
|
|
744
|
+
fs.writeFileSync(outFile, svg)
|
|
745
|
+
return outFile
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// Build the failure descriptor for a failed test: the drifted frame (marked
|
|
749
|
+
// exactly by addStoryboardFrame via board.visualFailure) with its
|
|
750
|
+
// expected/diff/actual paths, plus the sentences never reached. Returns null
|
|
751
|
+
// when nothing was marked.
|
|
752
|
+
function buildFailure (board) {
|
|
753
|
+
const dir = global.codecept_dir
|
|
754
|
+
const marked = board.panels.find(p => p.images.some(img => path.basename(img.file) === board.visualFailure))
|
|
755
|
+
const notReached = (board.lines || []).filter(line =>
|
|
756
|
+
!board.panels.some(p => p.title === line.text && p.images.length)
|
|
757
|
+
)
|
|
758
|
+
if (!board.visualFailure || !marked) return { frame: null, notReached }
|
|
759
|
+
|
|
760
|
+
const name = board.visualFailure
|
|
761
|
+
const diffPath = path.join(dir, 'screenshots', 'diff', board.baseDir, `Diff_${name}`)
|
|
762
|
+
const hasDiff = fs.existsSync(diffPath)
|
|
763
|
+
const baseline = path.join(dir, 'screenshots', 'base', board.baseDir, name)
|
|
764
|
+
const actual = path.join(dir, '_output', board.baseDir, name)
|
|
765
|
+
const line = (board.lines || []).find(l => l.text === marked.title)
|
|
766
|
+
const rel = (abs) => path.relative(process.cwd(), abs)
|
|
767
|
+
return {
|
|
768
|
+
frame: {
|
|
769
|
+
name,
|
|
770
|
+
step: board.panels.indexOf(marked) + 1,
|
|
771
|
+
sentence: marked.title,
|
|
772
|
+
keyword: line ? line.keyword : '',
|
|
773
|
+
baseline,
|
|
774
|
+
actual,
|
|
775
|
+
diff: hasDiff ? diffPath : null,
|
|
776
|
+
paths: {
|
|
777
|
+
expected: rel(baseline),
|
|
778
|
+
diff: hasDiff ? rel(diffPath) : '(no pixel diff ā see the error message, e.g. image dimensions differ)',
|
|
779
|
+
actual: rel(actual)
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
notReached
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// One unmissable block in the runner output: WHERE to look. The path is
|
|
787
|
+
// repo-relative ā valid on the host once the artifact sync (end of the run)
|
|
788
|
+
// has copied _output back.
|
|
789
|
+
function logVisualRegression (frame, outputSvg) {
|
|
790
|
+
console.error(
|
|
791
|
+
'\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n' +
|
|
792
|
+
`ā VISUAL REGRESSION ā step ${frame.step}: ${frame.keyword} ${frame.sentence}\n` +
|
|
793
|
+
' The failure storyboard sums it all up (expected / diff / actual):\n' +
|
|
794
|
+
` š¬ open in a browser: ${path.relative(process.cwd(), outputSvg)}\n` +
|
|
795
|
+
'āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n'
|
|
796
|
+
)
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// ---------------------------------------------------------------------------
|
|
800
|
+
// CodeceptJS plugin ā fills the header from the Gherkin metadata of every
|
|
801
|
+
// scenario before it runs (and drops stale panels from a previous test),
|
|
802
|
+
// then renders the SVG when the test ends: to _output on every outcome (a
|
|
803
|
+
// failing run's partial board shows exactly how far the journey got), and ā
|
|
804
|
+
// only on a PASSED run in baseline-update mode ā the committed copy under
|
|
805
|
+
// storyboards/, rebuilt FROM the reviewed baselines so it never embeds
|
|
806
|
+
// unreviewed pixels.
|
|
807
|
+
// codeceptjs 3.7.8 sets test.title / test.tags / test.file / test.parent.title
|
|
808
|
+
// (feature name) in lib/mocha/gherkin.js; titles carry the tags appended.
|
|
809
|
+
// ---------------------------------------------------------------------------
|
|
810
|
+
module.exports = function storyboardPlugin () {
|
|
811
|
+
const { event } = require('codeceptjs')
|
|
812
|
+
const writeGallery = require('./gallery')
|
|
813
|
+
const entries = new Map()
|
|
814
|
+
event.dispatcher.on(event.all.before, () => entries.clear())
|
|
815
|
+
event.dispatcher.on(event.test.before, (test) => {
|
|
816
|
+
const tags = test.tags || []
|
|
817
|
+
const tag = tags.length ? tags[tags.length - 1] : ''
|
|
818
|
+
let file = ''
|
|
819
|
+
let base = ''
|
|
820
|
+
if (test.file && global.codecept_dir) {
|
|
821
|
+
// Display path relative to the process cwd (the repo root in the
|
|
822
|
+
// container), correct wherever the suite lives in a given project.
|
|
823
|
+
file = path.relative(process.cwd(), test.file)
|
|
824
|
+
const fromFeatures = path.relative(path.join(global.codecept_dir, 'features'), test.file)
|
|
825
|
+
if (!fromFeatures.startsWith('..')) {
|
|
826
|
+
// FLAT per-scenario layout: <feature-dir>/<scenario-tag> ā the film
|
|
827
|
+
// reads as acts/stories with no per-feature nesting. Scenario tags are
|
|
828
|
+
// grep filters, unique by construction, so they key the baselines and
|
|
829
|
+
// the SVG unambiguously.
|
|
830
|
+
const scenarioKey = tag
|
|
831
|
+
? tag.replace(/^@/, '')
|
|
832
|
+
: stripTags(test.title).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
|
833
|
+
base = path.join(path.dirname(fromFeatures), scenarioKey)
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
begin({
|
|
837
|
+
feature: stripTags(test.parent && test.parent.title),
|
|
838
|
+
scenario: stripTags(test.title),
|
|
839
|
+
file,
|
|
840
|
+
featureFile: test.file,
|
|
841
|
+
baseDir: base,
|
|
842
|
+
rerun: tag ? `task test -- --grep "${tag}"` : ''
|
|
843
|
+
})
|
|
844
|
+
})
|
|
845
|
+
|
|
846
|
+
// Every Gherkin sentence opens its own card AUTOMATICALLY, in scenario
|
|
847
|
+
// order, right before its step function runs ā frames captured inside the
|
|
848
|
+
// step attach to it. Step files never do panel bookkeeping.
|
|
849
|
+
event.dispatcher.on(event.bddStep.before, (step) => {
|
|
850
|
+
if (!board) return
|
|
851
|
+
panel(step.text)
|
|
852
|
+
})
|
|
853
|
+
|
|
854
|
+
const finish = (passed) => {
|
|
855
|
+
// Only scenarios that actually captured frames are storyboards ā plain
|
|
856
|
+
// Gherkin tests (no addStoryboardFrame call) must not render empty boards.
|
|
857
|
+
if (!board || !board.panels.some(p => p.images.length) || !board.baseDir || !global.codecept_dir) return
|
|
858
|
+
try {
|
|
859
|
+
// The drifted frame was marked exactly by addStoryboardFrame; on a
|
|
860
|
+
// diff-less failure (e.g. "Image dimensions do not match") the band's
|
|
861
|
+
// middle slot reads "(not generated)".
|
|
862
|
+
const failure = passed ? null : buildFailure(board)
|
|
863
|
+
const outputSvg = render(path.join(global.codecept_dir, '_output', `${board.baseDir}.svg`), { failure })
|
|
864
|
+
entries.set(board.baseDir, {
|
|
865
|
+
baseDir: board.baseDir,
|
|
866
|
+
scenario: board.scenario,
|
|
867
|
+
rerun: board.rerun,
|
|
868
|
+
passed,
|
|
869
|
+
sentence: failure && failure.frame ? failure.frame.sentence : ''
|
|
870
|
+
})
|
|
871
|
+
if (failure && failure.frame) logVisualRegression(failure.frame, outputSvg)
|
|
872
|
+
if (passed && process.env.TASK_E2E_UPDATE_BASELINES) {
|
|
873
|
+
render(path.join(global.codecept_dir, 'storyboards', `${board.baseDir}.svg`), {
|
|
874
|
+
imageDir: path.join(global.codecept_dir, 'screenshots', 'base', board.baseDir)
|
|
875
|
+
})
|
|
876
|
+
}
|
|
877
|
+
} catch (err) {
|
|
878
|
+
// Rendering must never mask the test outcome.
|
|
879
|
+
console.error(`storyboard: SVG rendering failed: ${err.message}`)
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
event.dispatcher.on(event.test.passed, () => finish(true))
|
|
883
|
+
event.dispatcher.on(event.test.failed, () => finish(false))
|
|
884
|
+
event.dispatcher.on(event.all.after, () => {
|
|
885
|
+
if (!global.codecept_dir) return
|
|
886
|
+
try {
|
|
887
|
+
const stories = [...entries.values()]
|
|
888
|
+
writeGallery(path.join(global.codecept_dir, '_output'), stories)
|
|
889
|
+
if (process.env.TASK_E2E_UPDATE_BASELINES && !process.env.CI) {
|
|
890
|
+
writeGallery(path.join(global.codecept_dir, 'storyboards'), stories.filter(entry => entry.passed))
|
|
891
|
+
}
|
|
892
|
+
} catch (err) {
|
|
893
|
+
console.error(`storyboard: gallery rendering failed: ${err.message}`)
|
|
894
|
+
}
|
|
895
|
+
})
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
module.exports.begin = begin
|
|
899
|
+
module.exports.baseDir = baseDir
|
|
900
|
+
module.exports.parseScenarioLines = parseScenarioLines
|
|
901
|
+
module.exports.panel = panel
|
|
902
|
+
module.exports.frame = frame
|
|
903
|
+
module.exports.annotate = annotate
|
|
904
|
+
module.exports.panels = panels
|
|
905
|
+
module.exports.storyboardStep = storyboardStep
|
|
906
|
+
module.exports.capturePageFrame = capturePageFrame
|
|
907
|
+
module.exports.captureElementFrame = captureElementFrame
|
|
908
|
+
module.exports.frameOutputPath = frameOutputPath
|
|
909
|
+
module.exports.assertOrUpdateBaseline = assertOrUpdateBaseline
|
|
910
|
+
module.exports.addStoryboardFrame = addStoryboardFrame
|
|
911
|
+
module.exports.render = render
|
|
912
|
+
module.exports.tryTo = tryTo
|