webship-js 2.0.1 → 2.0.3

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.
Files changed (194) hide show
  1. package/AGENTS.md +109 -0
  2. package/CLAUDE.md +317 -0
  3. package/bin/generate-reports.js +363 -0
  4. package/bin/init-webship.js +343 -0
  5. package/bin/postinstall.js +8 -74
  6. package/cucumber.js +66 -2
  7. package/docs/00-quick-start.md +102 -0
  8. package/docs/01-getting-started.md +102 -0
  9. package/docs/02-bbr-smart-waits.md +77 -0
  10. package/docs/03-selector-registry.md +95 -0
  11. package/docs/04-step-reference.md +728 -0
  12. package/docs/05-web-first-assertions.md +91 -0
  13. package/docs/06-network-and-dialogs.md +83 -0
  14. package/docs/07-auth-state.md +75 -0
  15. package/docs/08-clock-mocking.md +59 -0
  16. package/docs/09-api-testing.md +114 -0
  17. package/docs/10-accessibility.md +167 -0
  18. package/docs/11-debugging.md +129 -0
  19. package/docs/12-ai-agent-guide.md +338 -0
  20. package/docs/13-faq.md +236 -0
  21. package/docs/14-recipes-cookbook.md +255 -0
  22. package/docs/15-tag-conventions.md +76 -0
  23. package/docs/advanced-screenshots/then-i-save-fullscreen-screenshot.md +36 -0
  24. package/docs/advanced-screenshots/then-i-save-width-x-height-screenshot.md +34 -0
  25. package/docs/advanced-screenshots/when-i-save-screenshot-name-filename.md +45 -0
  26. package/docs/advanced-screenshots.md +52 -0
  27. package/docs/advanced-selectors.md +18 -0
  28. package/docs/api-step-definitions.md +45 -0
  29. package/docs/diffy-step-definitions/then-compare-diffy-env1-env2.md +30 -0
  30. package/docs/diffy-step-definitions/then-create-diffy-comparison-name-value.md +21 -0
  31. package/docs/diffy-step-definitions/then-create-diffy-comparison.md +25 -0
  32. package/docs/diffy-step-definitions/then-create-diffy-screenshot-environment-name.md +35 -0
  33. package/docs/diffy-step-definitions/then-i-take-screenshot.md +21 -0
  34. package/docs/diffy-step-definitions/then-i-take-screenshots-all-breakpoints.md +27 -0
  35. package/docs/diffy-step-definitions/then-send-screenshots-diffy-name-value.md +27 -0
  36. package/docs/diffy-step-definitions/then-upload-folder-url-diffy-snapshotname.md +28 -0
  37. package/docs/diffy-step-definitions/then-wait-diffy-comparison-complete.md +21 -0
  38. package/docs/diffy-step-definitions/when-i-resize-window-number.md +29 -0
  39. package/docs/diffy-step-definitions.md +21 -0
  40. package/docs/global-settings.md +244 -0
  41. package/docs/index.md +104 -0
  42. package/docs/install-webship-js/ddev-webship-js.md +52 -0
  43. package/docs/install-webship-js.md +35 -0
  44. package/docs/overview.md +41 -0
  45. package/docs/step-definitions/given-i-am-anonymous-user.md +67 -0
  46. package/docs/step-definitions/given-i-am-homepage.md +68 -0
  47. package/docs/step-definitions/given-i-am-specific-page.md +72 -0
  48. package/docs/step-definitions/then-i-should-be.md +56 -0
  49. package/docs/step-definitions/then-i-should-see.md +62 -0
  50. package/docs/step-definitions/then-item-checkbox.md +54 -0
  51. package/docs/step-definitions/then-item-link-should-contain-url.md +84 -0
  52. package/docs/step-definitions/then-item-should-contain.md +67 -0
  53. package/docs/step-definitions/then-radio-button-value-should-be-selected.md +68 -0
  54. package/docs/step-definitions/then-response-status-code-should-be-number.md +69 -0
  55. package/docs/step-definitions/then-value-radio-button-selected.md +62 -0
  56. package/docs/step-definitions/when-i-attach-file-file-name-element.md +71 -0
  57. package/docs/step-definitions/when-i-check-checkbox.md +60 -0
  58. package/docs/step-definitions/when-i-click-link.md +51 -0
  59. package/docs/step-definitions/when-i-click-operation-text-row.md +71 -0
  60. package/docs/step-definitions/when-i-fill.md +59 -0
  61. package/docs/step-definitions/when-i-go-homepage.md +60 -0
  62. package/docs/step-definitions/when-i-go-specific-page.md +67 -0
  63. package/docs/step-definitions/when-i-move-backward-one-page.md +49 -0
  64. package/docs/step-definitions/when-i-move-forward-one-page.md +58 -0
  65. package/docs/step-definitions/when-i-press-button.md +58 -0
  66. package/docs/step-definitions/when-i-reload-page.md +51 -0
  67. package/docs/step-definitions/when-i-scroll.md +73 -0
  68. package/docs/step-definitions/when-i-select-option-select-list.md +53 -0
  69. package/docs/step-definitions/when-i-select-radio-button-value.md +62 -0
  70. package/docs/step-definitions/when-i-uncheck-checkbox.md +57 -0
  71. package/docs/step-definitions/when-i-wait-ajax-finish.md +64 -0
  72. package/docs/step-definitions/when-i-wait.md +62 -0
  73. package/docs/step-definitions.md +50 -0
  74. package/examples/a11y.html +31 -0
  75. package/examples/cookies.html +10 -0
  76. package/examples/date.html +12 -0
  77. package/examples/diffy/baseline.html +54 -0
  78. package/examples/diffy/changed.html +63 -0
  79. package/examples/diffy/index.html +52 -0
  80. package/examples/element.html +11 -0
  81. package/examples/field.html +24 -0
  82. package/examples/index.html +6 -0
  83. package/examples/keyboard.html +11 -0
  84. package/examples/links.html +9 -0
  85. package/examples/modal.html +14 -0
  86. package/examples/path.html +3 -0
  87. package/examples/table.html +13 -0
  88. package/examples/test--when--i-additionally-select.html +27 -0
  89. package/package.json +19 -6
  90. package/playwright.config.ts +3 -2
  91. package/tests/features/a11y.feature +39 -0
  92. package/tests/features/cookie.feature +13 -0
  93. package/tests/features/date.feature +11 -0
  94. package/tests/features/diffy/test--diffy-01-example-demo.feature +22 -0
  95. package/tests/features/diffy/test--diffy-02-all-steps.feature +52 -0
  96. package/tests/features/diffy/test--diffy-03-real-api.feature +21 -0
  97. package/tests/features/element.feature +16 -0
  98. package/tests/features/field.feature +25 -0
  99. package/tests/features/keyboard.feature +10 -0
  100. package/tests/features/link.feature +11 -0
  101. package/tests/features/modal-advanced-example.feature +1 -1
  102. package/tests/features/modal.feature +11 -0
  103. package/tests/features/path.feature +16 -0
  104. package/tests/features/response.feature +8 -0
  105. package/tests/features/responsive.feature +10 -0
  106. package/tests/features/table.feature +18 -0
  107. package/tests/features/test--then--i-save-screenshot.feature +33 -0
  108. package/tests/features/test--then--i-see-locator.feature +320 -0
  109. package/tests/features/test--then--i-should-see-n-elements.feature +24 -0
  110. package/tests/features/test--then--print-current-url-and-response.feature +21 -0
  111. package/tests/features/test--when--i-additionally-select.feature +30 -0
  112. package/tests/features/test--when--i-follow.feature +22 -0
  113. package/tests/features/wait.feature +7 -0
  114. package/tests/features/yaml.feature +102 -0
  115. package/tests/reports/README.md +55 -0
  116. package/tests/selectors/_canonical-keys.json +113 -0
  117. package/tests/selectors/back-end-selectors.json +19 -0
  118. package/tests/selectors/cms-contentful-admin.json +35 -0
  119. package/tests/selectors/cms-craft-admin.json +39 -0
  120. package/tests/selectors/cms-drupal-cms-gin.json +56 -0
  121. package/tests/selectors/cms-drupal-core-claro.json +50 -0
  122. package/tests/selectors/cms-generic-admin.json +34 -0
  123. package/tests/selectors/cms-ghost-admin.json +34 -0
  124. package/tests/selectors/cms-joomla-admin.json +41 -0
  125. package/tests/selectors/cms-magento2-admin.json +32 -0
  126. package/tests/selectors/cms-prestashop-admin.json +38 -0
  127. package/tests/selectors/cms-shopify-admin.json +25 -0
  128. package/tests/selectors/cms-strapi-admin.json +42 -0
  129. package/tests/selectors/cms-typo3-admin.json +41 -0
  130. package/tests/selectors/cms-woocommerce-front.json +50 -0
  131. package/tests/selectors/cms-wordpress-admin.json +31 -0
  132. package/tests/selectors/framework-ant-design.json +80 -0
  133. package/tests/selectors/framework-bootstrap.json +86 -0
  134. package/tests/selectors/framework-bulma.json +74 -0
  135. package/tests/selectors/framework-chakra.json +58 -0
  136. package/tests/selectors/framework-foundation.json +51 -0
  137. package/tests/selectors/framework-material-ui.json +72 -0
  138. package/tests/selectors/framework-shadcn.json +51 -0
  139. package/tests/selectors/framework-tailwind.json +40 -0
  140. package/tests/selectors/framework-vuetify.json +61 -0
  141. package/tests/selectors/front-end-selectors.json +16 -0
  142. package/tests/selectors/homepage-selectors.json +13 -0
  143. package/tests/step-definitions/a11y.steps.js +798 -0
  144. package/tests/step-definitions/action.steps.js +167 -0
  145. package/tests/step-definitions/{webship-api.js → api.steps.js} +254 -44
  146. package/tests/step-definitions/assertion.steps.js +352 -0
  147. package/tests/step-definitions/auth.steps.js +124 -0
  148. package/tests/step-definitions/clock.steps.js +128 -0
  149. package/tests/step-definitions/cookie.steps.js +216 -0
  150. package/tests/step-definitions/debug.steps.js +31 -0
  151. package/tests/step-definitions/dialog.steps.js +193 -0
  152. package/tests/step-definitions/element.steps.js +314 -0
  153. package/tests/step-definitions/field.steps.js +653 -0
  154. package/tests/step-definitions/file-download.steps.js +193 -0
  155. package/tests/step-definitions/form.steps.js +333 -0
  156. package/tests/step-definitions/iframe.steps.js +178 -0
  157. package/tests/step-definitions/input.steps.js +163 -0
  158. package/tests/step-definitions/javascript.steps.js +71 -0
  159. package/tests/step-definitions/keyboard.steps.js +78 -0
  160. package/tests/step-definitions/link.steps.js +142 -0
  161. package/tests/step-definitions/metatag.steps.js +91 -0
  162. package/tests/step-definitions/modal.steps.js +219 -0
  163. package/tests/step-definitions/navigation.steps.js +218 -0
  164. package/tests/step-definitions/network.steps.js +238 -0
  165. package/tests/step-definitions/path.steps.js +141 -0
  166. package/tests/step-definitions/response.steps.js +98 -0
  167. package/tests/step-definitions/responsive.steps.js +123 -0
  168. package/tests/step-definitions/rest.steps.js +111 -0
  169. package/tests/step-definitions/screenshot.steps.js +423 -0
  170. package/tests/step-definitions/scroll.steps.js +189 -0
  171. package/tests/step-definitions/selectors.steps.js +996 -0
  172. package/tests/step-definitions/storage.steps.js +194 -0
  173. package/tests/step-definitions/table.steps.js +181 -0
  174. package/tests/step-definitions/wait.steps.js +400 -0
  175. package/tests/step-definitions/web-first.steps.js +296 -0
  176. package/tests/step-definitions/webship.js +567 -923
  177. package/tests/step-definitions/xml.steps.js +409 -0
  178. package/tests/step-definitions/yaml.steps.js +911 -0
  179. package/tests/step-definitions-diffy/README.md +329 -0
  180. package/tests/step-definitions-diffy/mock-diffy-api/server.js +84 -0
  181. package/tests/step-definitions-diffy/webship-diffy-mock.js +31 -0
  182. package/tests/step-definitions-diffy/webship-diffy.js +459 -0
  183. package/tsconfig.json +19 -3
  184. package/generate-reports.js +0 -22
  185. package/required/cucumber.js +0 -37
  186. package/required/generate-reports.js +0 -22
  187. package/required/package.json +0 -18
  188. package/required/playwright.config.ts +0 -37
  189. package/required/tests/features/README.md +0 -1
  190. package/required/tests/features/check-homepage.feature +0 -8
  191. package/required/tests/reports/README.md +0 -1
  192. package/required/tests/step-definitions/README.md +0 -1
  193. package/required/tests/step-definitions/custom.js +0 -4
  194. package/required/tsconfig.json +0 -12
@@ -0,0 +1,996 @@
1
+ 'use strict';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Webship-JS — Selectors step definitions
5
+ //
6
+ // Uses Playwright Locator API (locator.boundingBox, locator.isVisible,
7
+ // locator.isHidden, locator.click) to assert named page components are
8
+ // positioned relative to each other: above, below, left, right, inside,
9
+ // outside, over, not over. Also asserts visibility, focus, and click.
10
+ //
11
+ // Advanced selector system: named CSS and XPath selectors + layout components
12
+ // + viewport breakpoints — all configured under one `selectors` block, loaded
13
+ // from worldParameters, JSON files, or registered inline via steps.
14
+ //
15
+ // Configuration: resolved per-scenario with this priority:
16
+ // 1. process.env.WEBSHIP_SELECTORS_* (CI / shell — highest)
17
+ // 2. cucumber.js worldParameters.selectors.* (project-level defaults)
18
+ // 3. built-in defaults
19
+ //
20
+ // Supported env vars / worldParameters keys:
21
+ // WEBSHIP_SELECTORS_OFFSET offset scroll offset in px, default 60
22
+ // WEBSHIP_SELECTORS_BREAKPOINTS (JSON string) named breakpoints
23
+ //
24
+ // Unified config block (worldParameters.selectors):
25
+ // selectors: {
26
+ // filesPath: './tests/selectors/', // base path for selector files
27
+ // files: ['front-end-selectors.json', 'back-end-selectors.json'],
28
+ // css: {
29
+ // 'page header': 'header.page-header',
30
+ // 'main nav': 'nav[role="navigation"]',
31
+ // },
32
+ // xpath: {
33
+ // 'page title': '//h1[contains(@class,"page-title")]',
34
+ // },
35
+ // offset: 60, // scroll offset (px)
36
+ // breakpoints: {
37
+ // xs: { width: 375, height: 667 }, // phone portrait
38
+ // sm: { width: 576, height: 800 }, // large phone / phablet
39
+ // md: { width: 768, height: 1024 }, // tablet portrait
40
+ // lg: { width: 992, height: 768 }, // small laptop / tablet landscape
41
+ // xl: { width: 1200, height: 900, default: true }, // desktop
42
+ // xxl: { width: 1400, height: 900 }, // wide desktop / HD
43
+ // xxxl: { width: 1920, height: 1080 }, // Full HD / large monitor
44
+ // },
45
+ // }
46
+ //
47
+ // Selector files (JSON only) have the structure:
48
+ // {
49
+ // "css": { "breadcrumb": ".breadcrumb", "logo": "header .logo" },
50
+ // "xpath": { "page title": "//h1[contains(@class,'title')]" }
51
+ // }
52
+ //
53
+ // One unified CSS registry: layout components and element locators share
54
+ // worldParameters.selectors.css. Register in bulk via "Given I define css selectors:"
55
+ // or one-at-a-time via "When I add ... css selector". Same for XPath via `xpath`.
56
+ // ---------------------------------------------------------------------------
57
+
58
+ const { Given, When, Then, Before } = require('@cucumber/cucumber');
59
+ const fs = require('fs');
60
+ const path = require('path');
61
+
62
+ function parseFile(filePath) {
63
+ const ext = path.extname(filePath).toLowerCase();
64
+ if (ext !== '.json') {
65
+ throw new Error(`Selector files must be JSON (got "${ext}" for "${filePath}").`);
66
+ }
67
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Config
72
+ // ---------------------------------------------------------------------------
73
+ function pick(envVal, paramVal, fallback) {
74
+ if (envVal !== undefined && envVal !== '') return envVal;
75
+ if (paramVal !== undefined && paramVal !== '' && paramVal !== null) return paramVal;
76
+ return fallback;
77
+ }
78
+
79
+ function resolveConfig(parameters) {
80
+ const s = (parameters && parameters.selectors) || {};
81
+
82
+ let breakpoints = s.breakpoints || {
83
+ xs: { width: 375, height: 667 },
84
+ sm: { width: 576, height: 800 },
85
+ md: { width: 768, height: 1024 },
86
+ lg: { width: 992, height: 768 },
87
+ xl: { width: 1200, height: 900, default: true },
88
+ xxl: { width: 1400, height: 900 },
89
+ xxxl: { width: 1920, height: 1080 },
90
+ };
91
+
92
+ if (process.env.WEBSHIP_SELECTORS_BREAKPOINTS) {
93
+ try { breakpoints = JSON.parse(process.env.WEBSHIP_SELECTORS_BREAKPOINTS); } catch { /* ignore */ }
94
+ }
95
+
96
+ return {
97
+ offset: parseInt(pick(process.env.WEBSHIP_SELECTORS_OFFSET, s.offset, '60'), 10),
98
+ breakpoints,
99
+ filesPath: s.filesPath || '',
100
+ files: Array.isArray(s.files) ? s.files : [],
101
+ css: Object.assign({}, s.css || {}),
102
+ xpath: Object.assign({}, s.xpath || {}),
103
+ };
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // Per-scenario registries
108
+ // ---------------------------------------------------------------------------
109
+ Before(function () {
110
+ const cfg = resolveConfig(this.parameters);
111
+ this.__selectorsConfig = cfg;
112
+ this.__selectorsCss = Object.assign({}, cfg.css);
113
+ this.__selectorsXpath = Object.assign({}, cfg.xpath);
114
+
115
+ // Auto-load selector files specified in worldParameters.
116
+ for (const file of cfg.files) {
117
+ const filePath = cfg.filesPath ? path.join(cfg.filesPath, file) : file;
118
+ try {
119
+ const parsed = parseFile(filePath);
120
+ if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
121
+ if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
122
+ } catch (e) {
123
+ throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
124
+ }
125
+ }
126
+ });
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Selector resolution helpers
130
+ // ---------------------------------------------------------------------------
131
+
132
+ /**
133
+ * Resolve a named selector to a Playwright-compatible selector string.
134
+ * Priority: css registry → xpath registry.
135
+ */
136
+ function resolveSelector(world, name) {
137
+ const trimmed = name.trim();
138
+
139
+ if (world.__selectorsCss && world.__selectorsCss[trimmed]) {
140
+ return world.__selectorsCss[trimmed];
141
+ }
142
+
143
+ if (world.__selectorsXpath && world.__selectorsXpath[trimmed]) {
144
+ const xp = world.__selectorsXpath[trimmed];
145
+ return xp.startsWith('xpath=') ? xp : `xpath=${xp}`;
146
+ }
147
+
148
+ // Suggest the closest registered name when one exists. Cheap Levenshtein
149
+ // by character — good enough for short selector names.
150
+ const known = [
151
+ ...Object.keys(world.__selectorsCss || {}),
152
+ ...Object.keys(world.__selectorsXpath || {}),
153
+ ];
154
+ let best = null; let bestDist = Infinity;
155
+ for (const k of known) {
156
+ const dist = (function lev(a, b) {
157
+ const m = a.length, n = b.length;
158
+ if (!m) return n; if (!n) return m;
159
+ const d = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
160
+ for (let i = 0; i <= m; i++) d[i][0] = i;
161
+ for (let j = 0; j <= n; j++) d[0][j] = j;
162
+ for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
163
+ d[i][j] = a[i - 1] === b[j - 1] ? d[i - 1][j - 1] : 1 + Math.min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]);
164
+ }
165
+ return d[m][n];
166
+ })(trimmed.toLowerCase(), k.toLowerCase());
167
+ if (dist < bestDist) { bestDist = dist; best = k; }
168
+ }
169
+ const suggestion = best && bestDist <= Math.max(2, Math.floor(trimmed.length / 3))
170
+ ? `\n Did you mean "${best}"?`
171
+ : '';
172
+ const examples = known.length
173
+ ? `\n Registered names: ${known.slice(0, 8).join(', ')}${known.length > 8 ? ', ...' : ''}`
174
+ : '\n No selectors registered yet.';
175
+
176
+ throw new Error(
177
+ `Unknown selector "${trimmed}".${suggestion}${examples}\n` +
178
+ ` Register one with:\n` +
179
+ ` Given I define css selectors:\n` +
180
+ ` | name | css |\n` +
181
+ ` When I add "${trimmed}" selector for "<css>" css selector\n` +
182
+ ` or load a JSON preset via worldParameters.selectors.files.`
183
+ );
184
+ }
185
+
186
+ function parseNames(text) {
187
+ return text.split(/\s*(?:,|and)\s*/).map(s => s.trim()).filter(Boolean);
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Geometry helpers using Playwright locator.boundingBox()
192
+ // ---------------------------------------------------------------------------
193
+ async function getGeometry(page, selector) {
194
+ const loc = page.locator(selector).first();
195
+ try { await loc.scrollIntoViewIfNeeded({ timeout: 3000 }); } catch { /* may already be visible */ }
196
+
197
+ const box = await loc.boundingBox();
198
+ if (!box) return null;
199
+
200
+ const scroll = await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }));
201
+
202
+ // z-index still requires evaluate — no native Playwright API for computed style.
203
+ const zIndex = await loc.evaluate(el => {
204
+ let z = 0;
205
+ let node = el;
206
+ while (node && node !== document.body) {
207
+ const cs = window.getComputedStyle(node);
208
+ if (cs.position !== 'static' && cs.zIndex !== 'auto') {
209
+ const n = parseInt(cs.zIndex, 10);
210
+ if (!isNaN(n)) z = n;
211
+ }
212
+ node = node.parentElement;
213
+ }
214
+ return z;
215
+ });
216
+
217
+ return { top: box.y + scroll.y, left: box.x + scroll.x, width: box.width, height: box.height, zIndex };
218
+ }
219
+
220
+ async function assertPosition(page, position, c1Name, c1Sel, c2Name, c2Sel) {
221
+ const g1 = await getGeometry(page, c1Sel);
222
+ if (!g1) throw new Error(`Cannot get bounding box for "${c1Name}" (${c1Sel}) — element not visible`);
223
+ const g2 = await getGeometry(page, c2Sel);
224
+ if (!g2) throw new Error(`Cannot get bounding box for "${c2Name}" (${c2Sel}) — element not visible`);
225
+
226
+ let pass = false;
227
+ switch (position) {
228
+ case 'above': pass = g2.top >= g1.top + g1.height; break;
229
+ case 'below': pass = g1.top >= g2.top + g2.height; break;
230
+ case 'left': pass = g1.left + g1.width <= g2.left; break;
231
+ case 'right': pass = g1.left >= g2.left + g2.width; break;
232
+ case 'inside':
233
+ pass = g1.top >= g2.top && g1.top + g1.height <= g2.top + g2.height &&
234
+ g1.left >= g2.left && g1.left + g1.width <= g2.left + g2.width;
235
+ break;
236
+ case 'outside':
237
+ pass = g1.top <= g2.top && g1.top + g1.height >= g2.top + g2.height &&
238
+ g1.left <= g2.left && g1.left + g1.width >= g2.left + g2.width;
239
+ break;
240
+ case 'over': {
241
+ const intersects = !(g1.left >= g2.left + g2.width || g1.left + g1.width <= g2.left ||
242
+ g1.top >= g2.top + g2.height || g1.top + g1.height <= g2.top);
243
+ pass = intersects && g1.zIndex <= g2.zIndex;
244
+ break;
245
+ }
246
+ }
247
+ return pass;
248
+ }
249
+
250
+ async function dispatcher(world, position, subjectText, othersText, negate = false) {
251
+ const subjects = parseNames(subjectText);
252
+ const others = parseNames(othersText);
253
+ const errors = [];
254
+ for (const subjectName of subjects) {
255
+ const subjectSel = resolveSelector(world, subjectName);
256
+ for (const otherName of others) {
257
+ const otherSel = resolveSelector(world, otherName);
258
+ try {
259
+ const pass = await assertPosition(world.page, position, subjectName, subjectSel, otherName, otherSel);
260
+ if (!pass && !negate) errors.push(`"${subjectName}" is not ${position} "${otherName}"`);
261
+ else if (pass && negate) errors.push(`"${subjectName}" is ${position} "${otherName}" (expected not to be)`);
262
+ } catch (e) { errors.push(e.message); }
263
+ }
264
+ }
265
+ if (errors.length > 0) throw new Error(errors.join('\n'));
266
+ }
267
+
268
+ // ===========================================================================
269
+ // STEP DEFINITIONS — Advanced selector system
270
+ // ===========================================================================
271
+
272
+ /**
273
+ * Register a named CSS selector at runtime.
274
+ *
275
+ * Example #1: When I add "mobile logo" selector for "header img#logo" css selector
276
+ * Example #2: When I add "breadcrumb" selector for ".breadcrumb" css selector
277
+ * Example #3: When I add "breadcrumb first link" selector for ".breadcrumb li:nth-child(1) a" css selector
278
+ * Example #4: When I add "cta button" selector for ".cta .btn-primary" css selector
279
+ * Example #5: When I add "page header" selector for "header.page-header" css selector
280
+ * Example #6: When I add "main nav" selector for "nav[role='navigation']" css selector
281
+ * Example #7: When I add "hero image" selector for ".hero img" css selector
282
+ * Example #8: When I add "footer links" selector for "footer a" css selector
283
+ * Example #9: When I add "search field" selector for "input[type='search']" css selector
284
+ * Example #10: When I add "submit button" selector for "button[type='submit']" css selector
285
+ *
286
+ * Advanced:
287
+ * Example #11: Later override same name → latest wins:
288
+ * When I add "target" selector for "h1" css selector
289
+ * And I add "target" selector for "ul" css selector
290
+ * Example #12: Component (CSS) takes precedence over CSS registry with same name:
291
+ * When I add "shared" selector for "ul" css selector
292
+ * And I define css selectors:
293
+ * | shared | h1 |
294
+ * Example #13: Combine with XPath registration and use together:
295
+ * When I add "cta" selector for ".cta" css selector
296
+ * And I add "cta link" selector for "//a[contains(@class,'cta')]" xpath selector
297
+ */
298
+ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" css selector$/, function (pronounCase, selectorName, cssSelector) {
299
+ if (!selectorName || !cssSelector) throw new Error('Selectors: selector name and CSS selector must not be empty.');
300
+ this.__selectorsCss[selectorName.trim()] = cssSelector.trim();
301
+ });
302
+
303
+ /**
304
+ * Register a named XPath selector at runtime.
305
+ *
306
+ * Example #1: When I add "page title" selector for "//h1[contains(@class,'page-header')]" xpath selector
307
+ * Example #2: When I add "Dashboard" selector for "//*[@id='navbar-link-admin-dashboard']" xpath selector
308
+ * Example #3: When I add "Vertical orientation" selector for "//*[@id='navbar-item--2-tray']/div/div[2]/div/button" xpath selector
309
+ * Example #4: When I add "admin menu" selector for "//nav[contains(@class,'admin-menu')]" xpath selector
310
+ * Example #5: When I add "first table row" selector for "//table/tbody/tr[1]" xpath selector
311
+ * Example #6: When I add "active tab" selector for "//li[contains(@class,'active')]/a" xpath selector
312
+ * Example #7: When I add "error message" selector for "//*[contains(@class,'error')]" xpath selector
313
+ * Example #8: When I add "site name" selector for "//a[contains(@class,'site-name')]" xpath selector
314
+ * Example #9: When I add "user menu" selector for "//*[@id='user-menu']" xpath selector
315
+ * Example #10: When I add "language switcher" selector for "//ul[contains(@class,'language-switcher')]" xpath selector
316
+ *
317
+ * Advanced:
318
+ * Example #11: Axis predicates — first match only (locator.first() is applied):
319
+ * When I add "first row" selector for "//table//tr[1]" xpath selector
320
+ * Example #12: Text contains — name by rendered label:
321
+ * When I add "login link" selector for "//a[contains(normalize-space(.),'Login')]" xpath selector
322
+ * Example #13: Attribute + position — last nav item:
323
+ * When I add "last nav item" selector for "//nav[@role='navigation']//a[last()]" xpath selector
324
+ */
325
+ When(/^(I |we )*add "([^"]*)" selector for "([^"]*)" xpath selector$/, function (pronounCase, selectorName, xpathSelector) {
326
+ if (!selectorName || !xpathSelector) throw new Error('Selectors: selector name and XPath selector must not be empty.');
327
+ this.__selectorsXpath[selectorName.trim()] = xpathSelector.trim();
328
+ });
329
+
330
+ /**
331
+ * Load CSS and XPath selectors from a JSON file.
332
+ * File path is relative to worldParameters.selectors.filesPath.
333
+ *
334
+ * Example #1: When I add selectors from "selectors.json" file
335
+ * Example #2: When I add selectors from "admin-selectors.json" file
336
+ * Example #3: When I add selectors from "frontend.json" file
337
+ * Example #4: When I add selectors from "theme-selectors.json" file
338
+ * Example #5: When I add selectors from "components.json" file
339
+ * Example #6: When we add selectors from "shared.json" file
340
+ * Example #7: When add selectors from "backend.json" file
341
+ * Example #8: When I add selectors from "page-selectors.json" file
342
+ * Example #9: When I add selectors from "module-selectors.json" file
343
+ * Example #10: When we add selectors from "mobile.json" file
344
+ *
345
+ * Advanced:
346
+ * Example #11: Load a file then override a single entry inline:
347
+ * When I add selectors from "homepage-selectors.json" file
348
+ * And I add "homepage heading" selector for "header h1" css selector
349
+ * Example #12: Load multiple files — later files override earlier keys:
350
+ * When I add selectors from "front-end-selectors.json" file
351
+ * And I add selectors from "back-end-selectors.json" file
352
+ * Example #13: File + inline xpath + component — all three registries merged:
353
+ * When I add selectors from "homepage-selectors.json" file
354
+ * And I add "extra link" selector for "//a[@rel='canonical']" xpath selector
355
+ * And I define css selectors:
356
+ * | wrapper | #main |
357
+ */
358
+ When(/^(I |we )*add selectors from "([^"]*)" file$/, function (pronounCase, fileName) {
359
+ const cfg = this.__selectorsConfig;
360
+ if (!fileName) throw new Error('Selectors: file name must not be empty.');
361
+ if (!cfg.filesPath) throw new Error('Selectors: worldParameters.selectors.filesPath must be set to load selector files.');
362
+ const filePath = path.join(cfg.filesPath, fileName);
363
+ let parsed;
364
+ try { parsed = parseFile(filePath); } catch (e) {
365
+ throw new Error(`Selectors: failed to load selector file "${filePath}": ${e.message}`);
366
+ }
367
+ if (parsed && parsed.css) Object.assign(this.__selectorsCss, parsed.css);
368
+ if (parsed && parsed.xpath) Object.assign(this.__selectorsXpath, parsed.xpath);
369
+ });
370
+
371
+ /**
372
+ * Print all registered CSS selectors to console (debug/inspection).
373
+ *
374
+ * Example #1: Then I print css selectors
375
+ * Example #2: When I print css selectors
376
+ * Example #3: Then we print css selectors
377
+ * Example #4: When we print css selectors
378
+ * Example #5: Then print css selectors
379
+ * Example #6: When print css selectors
380
+ * Example #7: And I print css selectors
381
+ * Example #8: And we print css selectors
382
+ * Example #9: Given I print css selectors
383
+ * Example #10: But I print css selectors
384
+ */
385
+ Then(/^(I |we )*print css selectors$/, function (_pronounCase) {
386
+ console.log('\n--- CSS Selectors ---');
387
+ for (const [name, sel] of Object.entries(this.__selectorsCss || {})) {
388
+ console.log(` "${name}": ${sel}`);
389
+ }
390
+ });
391
+
392
+ /**
393
+ * Print all registered XPath selectors to console (debug/inspection).
394
+ *
395
+ * Example #1: Then I print xpath selectors
396
+ * Example #2: When I print xpath selectors
397
+ * Example #3: Then we print xpath selectors
398
+ * Example #4: When we print xpath selectors
399
+ * Example #5: Then print xpath selectors
400
+ * Example #6: When print xpath selectors
401
+ * Example #7: And I print xpath selectors
402
+ * Example #8: And we print xpath selectors
403
+ * Example #9: Given I print xpath selectors
404
+ * Example #10: But I print xpath selectors
405
+ */
406
+ Then(/^(I |we )*print xpath selectors$/, function (_pronounCase) {
407
+ console.log('\n--- XPath Selectors ---');
408
+ for (const [name, sel] of Object.entries(this.__selectorsXpath || {})) {
409
+ console.log(` "${name}": ${sel}`);
410
+ }
411
+ });
412
+
413
+ // ===========================================================================
414
+ // STEP DEFINITIONS — Layout components
415
+ // ===========================================================================
416
+
417
+ /**
418
+ * Define named CSS selectors in bulk for the current scenario.
419
+ *
420
+ * Example #1:
421
+ * Given I define css selectors:
422
+ * | header | #header |
423
+ * | nav | nav.primary |
424
+ * | footer | footer |
425
+ *
426
+ * Example #2:
427
+ * Given I define css selectors:
428
+ * | logo | .site-logo |
429
+ * | search | #search-input |
430
+ *
431
+ * Example #3:
432
+ * Given I define css selectors:
433
+ * | hero | .hero-banner |
434
+ * | content | .main-content |
435
+ * | sidebar | .sidebar |
436
+ *
437
+ * Example #4:
438
+ * Given I define css selectors:
439
+ * | menu | ul.menu |
440
+ * | button | .cta-button |
441
+ *
442
+ * Example #5:
443
+ * Given I define css selectors:
444
+ * | top bar | .top-bar |
445
+ * | page | #page-wrapper |
446
+ * | footer | .site-footer |
447
+ *
448
+ * Example #6:
449
+ * Given we define css selectors:
450
+ * | modal | .modal-dialog |
451
+ * | overlay | .modal-backdrop |
452
+ *
453
+ * Example #7:
454
+ * When I define css selectors:
455
+ * | input | input[name=q] |
456
+ * | button | button[type=submit] |
457
+ *
458
+ * Example #8:
459
+ * And I define css selectors:
460
+ * | card | .card |
461
+ * | title | .card-title |
462
+ *
463
+ * Example #9:
464
+ * Given define css selectors:
465
+ * | heading | h1 |
466
+ * | list | ul |
467
+ *
468
+ * Example #10:
469
+ * Given I define css selectors:
470
+ * | left | .col-left |
471
+ * | center | .col-center |
472
+ * | right | .col-right |
473
+ *
474
+ * Advanced:
475
+ * Example #11: Later entry with same name overrides earlier:
476
+ * When I add "shared" selector for "ul" css selector
477
+ * Given I define css selectors:
478
+ * | shared | h1 |
479
+ * Then I see visible shared # resolves to h1 (latest wins).
480
+ *
481
+ * Example #12: Define + use in position + visibility asserts:
482
+ * Given I define css selectors:
483
+ * | heading | h1 |
484
+ * | list | ul |
485
+ * Then I see visible heading, list
486
+ * And I see heading above list
487
+ *
488
+ * Example #13: Layered page-shell selectors:
489
+ * Given I define css selectors:
490
+ * | topbar | .topbar |
491
+ * | header | header.site |
492
+ * | nav | nav[role=navigation] |
493
+ * | main | main |
494
+ * | footer | footer |
495
+ */
496
+ Given(/^(I |we )*define css selectors:$/, function (pronounCase, dataTable) {
497
+ for (const [name, selector] of dataTable.raw()) {
498
+ if (name && selector) this.__selectorsCss[name.trim()] = selector.trim();
499
+ }
500
+ });
501
+
502
+ /**
503
+ * Define named XPath selectors in bulk for the current scenario.
504
+ *
505
+ * Example #1:
506
+ * Given I define xpath selectors:
507
+ * | first heading | //h1[1] |
508
+ * | first subline | //h3[1] |
509
+ * Example #2:
510
+ * Given we define xpath selectors:
511
+ * | active tab | //li[contains(@class,'active')]/a |
512
+ * Example #3:
513
+ * Given define xpath selectors:
514
+ * | last nav item | //nav//a[last()] |
515
+ * Example #4:
516
+ * And I define xpath selectors:
517
+ * | login link | //a[contains(normalize-space(.),'Login')] |
518
+ * Example #5:
519
+ * When I define xpath selectors:
520
+ * | error message | //*[contains(@class,'error')] |
521
+ * Example #6:
522
+ * Given I define xpath selectors:
523
+ * | first table row | //table/tbody/tr[1] |
524
+ * | first table cell| //table/tbody/tr[1]/td[1] |
525
+ * Example #7:
526
+ * Given I define xpath selectors:
527
+ * | page title | //h1[contains(@class,'page-header')] |
528
+ * Example #8:
529
+ * Given I define xpath selectors:
530
+ * | admin menu | //nav[contains(@class,'admin-menu')] |
531
+ * Example #9:
532
+ * Given I define xpath selectors:
533
+ * | language switcher | //ul[contains(@class,'language-switcher')] |
534
+ * Example #10:
535
+ * Given I define xpath selectors:
536
+ * | user menu | //*[@id='user-menu'] |
537
+ */
538
+ Given(/^(I |we )*define xpath selectors:$/, function (pronounCase, dataTable) {
539
+ for (const [name, selector] of dataTable.raw()) {
540
+ if (name && selector) this.__selectorsXpath[name.trim()] = selector.trim();
541
+ }
542
+ });
543
+
544
+ /**
545
+ * Resize viewport to a named breakpoint.
546
+ * Built-in names: xs, sm, md, lg, xl, xxl, xxxl.
547
+ *
548
+ * xs 375 x 667 phone portrait
549
+ * sm 576 x 800 large phone / phablet
550
+ * md 768 x 1024 tablet portrait
551
+ * lg 992 x 768 small laptop / tablet landscape
552
+ * xl 1200 x 900 desktop (default)
553
+ * xxl 1400 x 900 wide desktop / HD
554
+ * xxxl 1920 x 1080 Full HD / large monitor
555
+ *
556
+ * Example #1: Given I am viewing the site on a xl screen
557
+ * Example #2: Given I am viewing the site on a xs screen
558
+ * Example #3: Given I am viewing the site on a md screen
559
+ * Example #4: Given I am viewing the site on a "xl" screen
560
+ * Example #5: Given I am viewing the site on a lg device
561
+ * Example #6: Given I am viewing the site on a "sm" device
562
+ * Example #7: Given I am viewing the site on a xxl screen
563
+ * Example #8: Given I am viewing the site on a "xxxl" screen
564
+ * Example #9: Given I am viewing the site on a xxxl device
565
+ * Example #10: Given I am viewing the site on a "xxl" device
566
+ * Example #11: Given we are viewing the site on a xs screen
567
+ * Example #12: Given viewing the site on a lg screen
568
+ */
569
+ Given(/^(I am |we are )?viewing the site on a (?:"([^"]+)"|([a-zA-Z0-9 _,]+)) (?:screen|device)$/, async function (pronounCase, quoted, bare) {
570
+ const name = (quoted || bare || '').trim();
571
+ const cfg = this.__selectorsConfig;
572
+ if (!cfg.breakpoints[name]) throw new Error(`Selectors: breakpoint "${name}" not defined in worldParameters.selectors.breakpoints.`);
573
+ const { width, height } = cfg.breakpoints[name];
574
+ await this.page.setViewportSize({ width, height });
575
+ });
576
+
577
+ // ===========================================================================
578
+ // STEP DEFINITIONS — Relative position assertions
579
+ // ===========================================================================
580
+
581
+ /**
582
+ * Assert a subject locator is above one or more others (absolute page coordinates).
583
+ *
584
+ * Example #1: Then I see header above footer
585
+ * Example #2: Then I see logo above search
586
+ * Example #3: Then I see nav above content, footer
587
+ * Example #4: Then I see hero above sidebar and footer
588
+ * Example #5: Then I see top bar above nav, content and footer
589
+ * Example #6: Then I see heading above subline
590
+ * Example #7: Then I see nav above content
591
+ * Example #8: Then I see search above results
592
+ * Example #9: Then I see banner above body
593
+ * Example #10: Then I see menu above page
594
+ *
595
+ * Advanced — multi-subject / multi-target dispatch:
596
+ * Example #11: Single subject, many targets (comma + "and"):
597
+ * Then I see heading above subline, list and footer
598
+ * Example #12: Many subjects, single target:
599
+ * Then I see heading, subline above list
600
+ * Example #13: Cartesian — many subjects × many targets:
601
+ * Then I see heading, subline above list, footer
602
+ * Example #14: Combined with inline xpath registration:
603
+ * When I add "first heading xp" selector for "//h1[1]" xpath selector
604
+ * Then I see first heading xp above list
605
+ */
606
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) above ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
607
+ await dispatcher(this, 'above', subject, others);
608
+ });
609
+
610
+ /**
611
+ * Assert a subject locator is below one or more others.
612
+ *
613
+ * Example #1: Then I see footer below header
614
+ * Example #2: Then I see content below nav
615
+ * Example #3: Then I see footer below header, nav and content
616
+ * Example #4: Then I see results below search
617
+ * Example #5: Then I see sidebar below hero
618
+ * Example #6: Then I see list below heading
619
+ * Example #7: Then I see nav below top bar
620
+ * Example #8: Then I see content below logo
621
+ * Example #9: Then I see page below menu
622
+ * Example #10: Then I see body below banner
623
+ */
624
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) below ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
625
+ await dispatcher(this, 'below', subject, others);
626
+ });
627
+
628
+ /**
629
+ * Assert a subject locator is to the left of one or more others.
630
+ *
631
+ * Example #1: Then I see logo to the left of nav
632
+ * Example #2: Then I see sidebar to left of content
633
+ * Example #3: Then I see search to the left of search button
634
+ * Example #4: Then I see menu to the left of cta
635
+ * Example #5: Then I see label to left of input
636
+ * Example #6: Then I see icon to the left of title
637
+ * Example #7: Then I see thumbnail to the left of description
638
+ * Example #8: Then I see avatar to left of username
639
+ * Example #9: Then I see back button to the left of forward button
640
+ * Example #10: Then I see flag to left of country name
641
+ */
642
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) to (?:the )?left of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
643
+ await dispatcher(this, 'left', subject, others);
644
+ });
645
+
646
+ /**
647
+ * Assert a subject locator is to the right of one or more others.
648
+ *
649
+ * Example #1: Then I see nav to the right of logo
650
+ * Example #2: Then I see content to right of sidebar
651
+ * Example #3: Then I see search button to the right of search
652
+ * Example #4: Then I see cta to the right of menu
653
+ * Example #5: Then I see input to right of label
654
+ * Example #6: Then I see title to the right of icon
655
+ * Example #7: Then I see description to the right of thumbnail
656
+ * Example #8: Then I see username to right of avatar
657
+ * Example #9: Then I see forward button to the right of back button
658
+ * Example #10: Then I see country name to right of flag
659
+ */
660
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) to (?:the )?right of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
661
+ await dispatcher(this, 'right', subject, others);
662
+ });
663
+
664
+ /**
665
+ * Assert a subject locator's bounding box is fully inside another's.
666
+ *
667
+ * Example #1: Then I see logo inside of header
668
+ * Example #2: Then I see nav inside of header
669
+ * Example #3: Then I see search inside of header
670
+ * Example #4: Then I see cta inside of hero
671
+ * Example #5: Then I see label inside of form
672
+ * Example #6: Then I see icon inside of button
673
+ * Example #7: Then I see title inside of banner
674
+ * Example #8: Then I see content inside of page
675
+ * Example #9: Then I see sidebar inside of page
676
+ * Example #10: Then I see footer inside of page
677
+ */
678
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) inside of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
679
+ await dispatcher(this, 'inside', subject, others);
680
+ });
681
+
682
+ /**
683
+ * Assert a subject locator's bounding box fully contains another's.
684
+ *
685
+ * Example #1: Then I see header outside of logo
686
+ * Example #2: Then I see header outside of nav
687
+ * Example #3: Then I see hero outside of cta
688
+ * Example #4: Then I see form outside of label
689
+ * Example #5: Then I see button outside of icon
690
+ * Example #6: Then I see banner outside of title
691
+ * Example #7: Then I see page outside of content
692
+ * Example #8: Then I see page outside of sidebar
693
+ * Example #9: Then I see page outside of footer
694
+ * Example #10: Then I see wrapper outside of inner
695
+ */
696
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) outside of ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
697
+ await dispatcher(this, 'outside', subject, others);
698
+ });
699
+
700
+ /**
701
+ * Assert a subject locator overlaps another via intersection and z-index.
702
+ *
703
+ * Example #1: Then I see modal over content
704
+ * Example #2: Then I see dropdown over nav
705
+ * Example #3: Then I see tooltip over label
706
+ * Example #4: Then I see overlay over page
707
+ * Example #5: Then I see popup over hero
708
+ * Example #6: Then I see sticky header over content
709
+ * Example #7: Then I see cookie banner over footer
710
+ * Example #8: Then I see dialog over sidebar
711
+ * Example #9: Then I see notification over header
712
+ * Example #10: Then I see lightbox over page
713
+ */
714
+ Then(/^(I |we )*see ((?:[a-zA-Z0-9 ,\-](?!not))+) over ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
715
+ await dispatcher(this, 'over', subject, others);
716
+ });
717
+
718
+ /**
719
+ * Assert a subject locator does NOT overlap another element.
720
+ *
721
+ * Example #1: Then I see header not over content
722
+ * Example #2: Then I see nav not over sidebar
723
+ * Example #3: Then I see footer not over content
724
+ * Example #4: Then I see logo not over search
725
+ * Example #5: Then I see sidebar not over footer
726
+ * Example #6: Then I see menu not over hero
727
+ * Example #7: Then I see label not over input
728
+ * Example #8: Then I see icon not over title
729
+ * Example #9: Then I see button not over form
730
+ * Example #10: Then I see nav not over page
731
+ */
732
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) not over ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subject, others) {
733
+ await dispatcher(this, 'over', subject, others, true);
734
+ });
735
+
736
+ // ===========================================================================
737
+ // STEP DEFINITIONS — Visibility and focus (uses locator.isVisible / isHidden)
738
+ // ===========================================================================
739
+
740
+ /**
741
+ * Assert one or more named locators are visible.
742
+ *
743
+ * Example #1: Then I see visible header
744
+ * Example #2: Then I see visible nav, footer
745
+ * Example #3: Then I see visible logo and search
746
+ * Example #4: Then I see visible cta
747
+ * Example #5: Then I see visible hero, content and sidebar
748
+ * Example #6: Then I see visible menu
749
+ * Example #7: Then I see visible search button
750
+ * Example #8: Then I see visible banner
751
+ * Example #9: Then I see visible footer
752
+ * Example #10: Then I see visible top bar, nav and content
753
+ *
754
+ * Advanced:
755
+ * Example #11: Mix of components, inline CSS, inline XPath — all resolve:
756
+ * When I add "page heading" selector for "h1" css selector
757
+ * And I add "first para" selector for "//p[1]" xpath selector
758
+ * Then I see visible page heading, first para
759
+ * Example #12: After breakpoint resize — assert still visible:
760
+ * Given I am viewing the site on a xs screen
761
+ * Then I see visible heading, list
762
+ * Example #13: After loading a selector file — names from file are visible:
763
+ * When I add selectors from "homepage-selectors.json" file
764
+ * Then I see visible homepage heading, homepage first heading
765
+ */
766
+ Then(/^(I |we )*see visible ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subjectsText) {
767
+ const names = parseNames(subjectsText);
768
+ const errors = [];
769
+ for (const name of names) {
770
+ const sel = resolveSelector(this, name);
771
+ // Playwright native auto-retrying assertion — waits until the locator becomes visible.
772
+ try { await this.page.locator(sel).first().waitFor({ state: 'visible', timeout: 5000 }); }
773
+ catch { errors.push(`"${name}" (${sel}) is not visible`); }
774
+ }
775
+ if (errors.length > 0) throw new Error(errors.join('\n'));
776
+ });
777
+
778
+ /**
779
+ * Assert one or more named locators are hidden.
780
+ *
781
+ * Example #1: Then I don't see modal
782
+ * Example #2: Then I don't see dropdown, tooltip
783
+ * Example #3: Then I don't see overlay
784
+ * Example #4: Then I don't see cookie banner
785
+ * Example #5: Then I don't see popup
786
+ * Example #6: Then I don't see notification
787
+ * Example #7: Then I don't see lightbox
788
+ * Example #8: Then I don't see sticky header
789
+ * Example #9: Then I don't see dialog
790
+ * Example #10: Then I don't see sidebar, overlay and popup
791
+ */
792
+ Then(/^(I |we )*(don't|do not) see ([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, negation, subjectsText) {
793
+ const names = parseNames(subjectsText);
794
+ const errors = [];
795
+ for (const name of names) {
796
+ const sel = resolveSelector(this, name);
797
+ // Playwright native auto-retrying assertion — waits until the locator is detached or hidden.
798
+ try { await this.page.locator(sel).first().waitFor({ state: 'hidden', timeout: 5000 }); }
799
+ catch { errors.push(`"${name}" (${sel}) is visible (expected hidden)`); }
800
+ }
801
+ if (errors.length > 0) throw new Error(errors.join('\n'));
802
+ });
803
+
804
+ /**
805
+ * Assert a named locator has keyboard focus.
806
+ *
807
+ * Example #1: Then I see search has focus
808
+ * Example #2: Then I see email input has focus
809
+ * Example #3: Then we see submit button has focus
810
+ * Example #4: Then I see username has focus
811
+ * Example #5: Then I see password has focus
812
+ * Example #6: Then we see search button has focus
813
+ * Example #7: Then I see first link has focus
814
+ * Example #8: Then I see skip link has focus
815
+ * Example #9: Then I see close button has focus
816
+ * Example #10: Then I see modal heading has focus
817
+ */
818
+ Then(/^(I |we )*see ([a-zA-Z0-9 ,\-]+) has focus$/, async function (pronounCase, subjectText) {
819
+ const name = subjectText.trim();
820
+ const sel = resolveSelector(this, name);
821
+ const loc = this.page.locator(sel).first();
822
+ // Playwright native auto-retrying focus check via waitForFunction.
823
+ try {
824
+ await loc.waitFor({ state: 'attached', timeout: 5000 });
825
+ const handle = await loc.elementHandle();
826
+ await this.page.waitForFunction((el) => el === document.activeElement, handle, { timeout: 5000 });
827
+ } catch {
828
+ throw new Error(`"${name}" (${sel}) does not have focus`);
829
+ }
830
+ });
831
+
832
+ // ===========================================================================
833
+ // STEP DEFINITIONS — Focus and text selection
834
+ // ===========================================================================
835
+
836
+ /**
837
+ * Resolve a form field by label → placeholder → role=textbox → [name]/#id.
838
+ * Uses Playwright's ready-made semantic locators (getByLabel, getByPlaceholder,
839
+ * getByRole) with .or() fallbacks — matches the accessibility-first lookup
840
+ * chain recommended by https://playwright.dev/docs/locators.
841
+ */
842
+ function resolveField(page, field) {
843
+ return page.getByLabel(field).or(
844
+ page.getByPlaceholder(field)
845
+ ).or(
846
+ page.getByRole('textbox', { name: field })
847
+ ).or(
848
+ page.locator(`[name="${field}"], #${field}`)
849
+ ).first();
850
+ }
851
+
852
+ /**
853
+ * Move keyboard focus to a field by label, name, or id.
854
+ *
855
+ * Example #1: When I move focus to "Title" field
856
+ * Example #2: When I move focus to "Body" field
857
+ * Example #3: When I move focus to "Email" field
858
+ * Example #4: When I move focus to "Search" field
859
+ * Example #5: When I move focus to "Username" field
860
+ * Example #6: When I move focus to "Password" field
861
+ * Example #7: When I move focus to "First name" field
862
+ * Example #8: When I move focus to "Last name" field
863
+ * Example #9: When I move focus to "Description" field
864
+ * Example #10: When I move focus to "Phone" field
865
+ */
866
+ When(/^(I |we )*move focus to "([^"]*)" field$/, async function (pronounCase, fieldLabel) {
867
+ const loc = resolveField(this.page, fieldLabel);
868
+ await loc.focus();
869
+ });
870
+
871
+ /**
872
+ * Select all text inside a field by label, name, or id.
873
+ *
874
+ * Example #1: When I select all text in "Title" field
875
+ * Example #2: When I select all text in "Description" field
876
+ * Example #3: When I select all text in "Body" field
877
+ * Example #4: When I select all text in "Email" field
878
+ * Example #5: When I select all text in "Username" field
879
+ * Example #6: When I select all text in "Search" field
880
+ * Example #7: When I select all text in "Name" field
881
+ * Example #8: When I select all text in "Notes" field
882
+ * Example #9: When I select all text in "Address" field
883
+ * Example #10: When I select all text in "Message" field
884
+ */
885
+ When(/^(I |we )*select all text in "([^"]*)" field$/, async function (pronounCase, fieldLabel) {
886
+ const loc = resolveField(this.page, fieldLabel);
887
+ await loc.focus();
888
+ await loc.selectText();
889
+ });
890
+
891
+ /**
892
+ * Select a character range (from..to) inside a field.
893
+ *
894
+ * Example #1: When I select from 0 to 5 text in "Title" field
895
+ * Example #2: When I select from 0 to 10 text in "Body" field
896
+ * Example #3: When I select from 3 to 8 text in "Description" field
897
+ * Example #4: When I select from 0 to 5 text in "Email" field
898
+ * Example #5: When I select from 2 to 6 text in "Username" field
899
+ * Example #6: When we select from 0 to 4 text in "Name" field
900
+ * Example #7: When select from 1 to 7 text in "Search" field
901
+ * Example #8: When I select from 0 to 20 text in "Notes" field
902
+ * Example #9: When I select from 5 to 15 text in "Address" field
903
+ * Example #10: When we select from 0 to 3 text in "Phone" field
904
+ *
905
+ * Advanced:
906
+ * Example #11: Select first word after fill:
907
+ * And I fill in "Title" with "Release 2.0 notes"
908
+ * When I select from 0 to 7 text in "Title" field
909
+ * Example #12: Select middle substring by index range:
910
+ * And I fill in "Body" with "abcdefghij"
911
+ * When I select from 3 to 6 text in "Body" field
912
+ * Example #13: Chain — fill, focus, range-select, assert focus:
913
+ * And I fill in "Notes" with "hello world"
914
+ * When I move focus to "Notes" field
915
+ * And I select from 0 to 5 text in "Notes" field
916
+ * Then I see Notes has focus
917
+ */
918
+ When(/^(I |we )*select from (\d+) to (\d+) text in "([^"]*)" field$/, async function (pronounCase, from, to, fieldLabel) {
919
+ const start = parseInt(from, 10);
920
+ const end = parseInt(to, 10);
921
+ const loc = resolveField(this.page, fieldLabel);
922
+ await loc.focus();
923
+ await loc.evaluate((el, [s, e]) => {
924
+ if (typeof el.setSelectionRange === 'function') el.setSelectionRange(s, e);
925
+ }, [start, end]);
926
+ });
927
+
928
+ /**
929
+ * Select a specific substring of text inside a field.
930
+ *
931
+ * Example #1: When I select "title name" text in "Title" field
932
+ * Example #2: When I select "some content" text in "Description" field
933
+ * Example #3: When I select "hello" text in "Body" field
934
+ * Example #4: When I select "admin" text in "Username" field
935
+ * Example #5: When I select "example" text in "Email" field
936
+ * Example #6: When we select "webship" text in "Search" field
937
+ * Example #7: When select "lorem" text in "Notes" field
938
+ * Example #8: When I select "street" text in "Address" field
939
+ * Example #9: When we select "555" text in "Phone" field
940
+ * Example #10: When I select "summary" text in "Message" field
941
+ */
942
+ When(/^(I |we )*select "([^"]*)" text in "([^"]*)" field$/, async function (pronounCase, selectedText, fieldLabel) {
943
+ const loc = resolveField(this.page, fieldLabel);
944
+
945
+ const value = await loc.inputValue();
946
+ const start = value.indexOf(selectedText);
947
+ if (start === -1) throw new Error(`Text "${selectedText}" not found in field "${fieldLabel}"`);
948
+ const end = start + selectedText.length;
949
+
950
+ await loc.focus();
951
+ await loc.evaluate((el, [s, e]) => {
952
+ if (typeof el.setSelectionRange === 'function') el.setSelectionRange(s, e);
953
+ }, [start, end]);
954
+ });
955
+
956
+ // ===========================================================================
957
+ // STEP DEFINITIONS — Click by named component/selector
958
+ // ===========================================================================
959
+
960
+ /**
961
+ * Click one or more named components — uses locator.click() which auto-scrolls.
962
+ *
963
+ * Example #1: When I click nav
964
+ * Example #2: When I click search button
965
+ * Example #3: When click cta
966
+ * Example #4: When I click on logo
967
+ * Example #5: When I click menu
968
+ * Example #6: When I click on submit button
969
+ * Example #7: When I click close button
970
+ * Example #8: When click back button
971
+ * Example #9: When I click on forward button
972
+ * Example #10: When I click hero, cta
973
+ *
974
+ * Advanced:
975
+ * Example #11: Click via XPath-registered selector:
976
+ * When I add "login link xp" selector for "//a[contains(.,'Login')]" xpath selector
977
+ * And I click login link xp
978
+ * Example #12: Click a sequence — comma-separated names:
979
+ * Given I define css selectors:
980
+ * | tab 1 | [data-tab='1'] |
981
+ * | tab 2 | [data-tab='2'] |
982
+ * When I click tab 1, tab 2
983
+ * Example #13: Register with CSS then click — no components needed:
984
+ * When I add "cta primary" selector for ".cta .btn-primary" css selector
985
+ * And I click cta primary
986
+ */
987
+ When(/^(I |we )*click (?:on |a )?([a-zA-Z0-9 ,\-]+)$/, async function (pronounCase, subjectsText) {
988
+ const names = parseNames(subjectsText);
989
+ const errors = [];
990
+ for (const name of names) {
991
+ const sel = resolveSelector(this, name);
992
+ try { await this.page.locator(sel).first().click(); }
993
+ catch (e) { errors.push(`Cannot click "${name}" (${sel}): ${e.message}`); }
994
+ }
995
+ if (errors.length > 0) throw new Error(errors.join('\n'));
996
+ });