gz-laya-pilot 0.1.1 → 0.1.2

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.
@@ -1,12 +1,25 @@
1
- import { inspectForm, findFormItem } from './form.mjs';
2
- import { waitForReady } from './readiness.mjs';
1
+ import { inspectForm, findFormItem, inspectLooseRequired, invalidExampleValue } from './form.mjs';
2
+ import { assertPageIdentity, activity, waitForVisibleStep } from './page-session.mjs';
3
+ import { settle } from './dom.mjs';
4
+ import {
5
+ sameRegion,
6
+ expandCollection,
7
+ revealTreeActions,
8
+ recordTrees,
9
+ validateTreeTarget,
10
+ } from './page-capabilities.mjs';
3
11
 
4
12
  const SEARCH = /搜索|查询|search|query/i;
5
13
  const RESET = /^(重置|清空|reset|clear)$/i;
6
14
  const CREATE = /新增|新建|创建|添加|\badd\b|\bnew\b|\bcreate\b/i;
7
15
  const CANCEL = /^(取消|关闭|cancel|close)$/i;
8
16
  const searchField = /名称|姓名|用户名|账号|账户|name|account|搜索|查询|search/i;
9
- const target = ({ name, role }) => ({ name, role });
17
+ const target = ({ name, role, region, treePath }) => ({
18
+ name,
19
+ role,
20
+ ...(region ? { region } : {}),
21
+ ...(treePath ? { treePath } : {}),
22
+ });
10
23
  const keyOf = (c) => `${c.role}:${c.name}`;
11
24
 
12
25
  export function discoveryCandidates(snapshot, form) {
@@ -14,12 +27,27 @@ export function discoveryCandidates(snapshot, form) {
14
27
  const unique = (items) =>
15
28
  items.filter((c) => items.filter((x) => keyOf(x) === keyOf(c)).length === 1);
16
29
  const fields = unique(
17
- controls.filter((c) => c.role === 'textbox' && !c.readonly && searchField.test(c.name)),
30
+ controls.filter(
31
+ (c) =>
32
+ c.role === 'textbox' &&
33
+ !c.readonly &&
34
+ searchField.test(c.name) &&
35
+ !c.regionAmbiguous &&
36
+ !['banner', 'navigation'].includes(c.region?.role),
37
+ ),
18
38
  );
19
39
  let searches = unique(controls.filter((c) => c.role === 'button' && SEARCH.test(c.name)));
40
+ if (fields.length === 1) searches = searches.filter((c) => sameRegion(c, fields[0]));
20
41
  const explicitSearch = searches.filter((c) => /^(搜索|查询|search|query)$/i.test(c.name));
21
42
  if (explicitSearch.length === 1) searches = explicitSearch;
22
- const resets = unique(controls.filter((c) => c.role === 'button' && RESET.test(c.name)));
43
+ const resets = unique(
44
+ controls.filter(
45
+ (c) =>
46
+ c.role === 'button' &&
47
+ RESET.test(c.name) &&
48
+ (fields.length !== 1 || sameRegion(c, fields[0])),
49
+ ),
50
+ );
23
51
  const candidates = [];
24
52
  const query =
25
53
  fields.length === 1 && searches.length <= 1
@@ -89,14 +117,17 @@ export function discoveryCandidates(snapshot, form) {
89
117
  return candidates;
90
118
  }
91
119
 
92
- export function validateDiscovery(step) {
120
+ export function validateDiscovery(step, { readOnly = false } = {}) {
93
121
  const c = step.spec;
122
+ if (c?.create?.treePath) validateTreeTarget(c.create.treePath, { allowRoot: true });
94
123
  if (
95
124
  step.kind !== 'assert-discovery' ||
96
125
  !c ||
97
126
  !['filter-empty', 'filter-reset', 'cancel-create', 'field-invalid'].includes(c.check)
98
127
  )
99
128
  throw Error('不支持的补充测试步骤');
129
+ if (readOnly && !['filter-empty', 'filter-reset'].includes(c.check))
130
+ throw Error('只读探索只允许筛选及恢复验证,不能打开新增表单');
100
131
  const named = (t, role, pattern) =>
101
132
  t?.role === role &&
102
133
  typeof t.name === 'string' &&
@@ -151,20 +182,76 @@ export async function selectDiscovery(laya, candidate) {
151
182
  }
152
183
 
153
184
  async function control(w, t) {
154
- const snap = await w.snapshot();
155
- return (
156
- await w.chooseFromSnapshot(
157
- snap,
158
- snap.controls.filter((c) => c.name === t.name && c.role === t.role && !c.disabled),
159
- `${['textbox', 'spinbutton'].includes(t.role) ? '填写' : '点击'}「${t.name}」`,
160
- )
161
- ).locator;
185
+ return w.withAttempts('定位恢复控件', async () => {
186
+ const treeAction = t.treePath ? await revealTreeActions(w.page, t) : null;
187
+ const snap = await w.snapshot();
188
+ const treeRef = treeAction ? await treeAction.getAttribute('data-laya-live-ref') : null;
189
+ return (
190
+ await w.chooseFromSnapshot(
191
+ snap,
192
+ snap.controls.filter(
193
+ (c) =>
194
+ c.name === t.name &&
195
+ c.role === t.role &&
196
+ !c.disabled &&
197
+ (!treeAction || c.ref === treeRef) &&
198
+ (!t.region || sameRegion(c, t)),
199
+ ),
200
+ `${['textbox', 'spinbutton'].includes(t.role) ? '填写' : '点击'}「${t.name}」`,
201
+ )
202
+ ).locator;
203
+ });
162
204
  }
163
- async function reload(w) {
164
- await w.page.reload({ waitUntil: 'domcontentloaded' });
165
- await waitForReady(w.page, { timeout: w.config.pageTimeout });
205
+ async function setFilter(w, c, value) {
206
+ await assertPageIdentity(w.page, w.identity);
207
+ const input = await control(w, c.field);
208
+ if ((await input.inputValue()) !== value) {
209
+ await input.fill(value);
210
+ await settle(w.page, 180);
211
+ }
212
+ if ((await (await control(w, c.field)).inputValue()) !== value)
213
+ throw Error('筛选条件没有恢复到预期值');
214
+ if (c.search) await (await control(w, c.search)).click();
215
+ await w.pendingWrites.wait(w.config.pageTimeout || 8000);
216
+ await expandCollection(w, { record: false });
217
+ }
218
+
219
+ const sameRows = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
220
+
221
+ async function restoreDiscovery(w, c, original, baseline) {
222
+ activity(w, '正在恢复当前子应用的表单和筛选条件,不刷新主应用');
223
+ try {
224
+ await assertPageIdentity(w.page, w.identity);
225
+ if (await w.editorPresent()) {
226
+ if (!c.cancel) throw Error('没有已确认的取消入口,无法恢复编辑区');
227
+ await (await control(w, c.cancel)).click();
228
+ await w.waitModalClosed();
229
+ }
230
+ if (c.field) await setFilter(w, c, original);
231
+ await waitTable(w, (rows) => sameRows(rows, baseline));
232
+ await waitForVisibleStep(w);
233
+ } catch (error) {
234
+ // Do not turn an assertion failure into success by refreshing. The next
235
+ // case must not run against an unknown child-app state either.
236
+ w.restorationFailure = `当前子应用状态恢复失败,已停止后续探索:${error.message}`;
237
+ throw Error(w.restorationFailure, { cause: error });
238
+ } finally {
239
+ activity(w, '');
240
+ }
166
241
  }
167
242
  async function tableState(w) {
243
+ const trees = recordTrees(w.page);
244
+ if (await trees.count()) {
245
+ if ((await trees.count()) !== 1) throw Error('补充测试无法确定唯一记录树');
246
+ return trees
247
+ .getByRole('treeitem')
248
+ .filter({ visible: true })
249
+ .evaluateAll((items) =>
250
+ items
251
+ .filter((item) => !item.hasAttribute('aria-expanded'))
252
+ .map((item) => item.getAttribute('aria-label') || item.innerText),
253
+ );
254
+ }
168
255
  const table = w.page.locator('table:visible,[role="grid"]:visible');
169
256
  // Fixed-column copies are not independent tables. Require a single main table.
170
257
  const main = table
@@ -201,15 +288,24 @@ async function waitTable(w, check) {
201
288
  // This bounded grammar never submits a form. Replay uses the recorded recipe;
202
289
  // the model cannot introduce selectors, scripts, URLs or write operations.
203
290
  export async function executeDiscovery(w, step) {
204
- const c = validateDiscovery(step);
205
- await reload(w);
291
+ if (w.restorationFailure) throw Error(w.restorationFailure);
292
+ const c = validateDiscovery(step, { readOnly: w.config.readOnly });
293
+ await assertPageIdentity(w.page, w.identity);
294
+ // The recipe's precondition is an unfiltered list in both generation and
295
+ // replay. A preceding delete may leave its run-owned keyword in the field.
296
+ if (c.field && (await (await control(w, c.field)).inputValue()) !== '')
297
+ await setFilter(w, c, '');
298
+ await expandCollection(w, { record: false });
299
+ const baseline = await tableState(w);
300
+ const original = c.field ? await (await control(w, c.field)).inputValue() : null;
301
+ let failure;
206
302
  try {
207
303
  if (c.check.startsWith('filter-')) {
208
- const baseline = await tableState(w);
209
304
  if (!baseline.length) throw Error('列表原本为空,无法验证筛选及恢复');
210
305
  await (await control(w, c.field)).fill(`no_match_${w.variables.recordAccount}`);
211
306
  if (c.search) await (await control(w, c.search)).click();
212
307
  await waitTable(w, (rows) => rows.length === 0);
308
+ await waitForVisibleStep(w);
213
309
  if (c.check === 'filter-reset') {
214
310
  await (await control(w, c.reset)).click();
215
311
  if ((await (await control(w, c.field)).inputValue()) !== '')
@@ -220,8 +316,10 @@ export async function executeDiscovery(w, step) {
220
316
  );
221
317
  }
222
318
  } else {
319
+ if (!c.create.treePath) await revealTreeActions(w.page, c.create);
223
320
  await (await control(w, c.create)).click();
224
- await w.waitForModal();
321
+ await w.waitForEditor();
322
+ await waitForVisibleStep(w);
225
323
  if (w.mode === 'execute') await w.matchFormTarget(c.label);
226
324
  const { info, item } = await findFormItem(w.page, c.label);
227
325
  const input = item.locator('input:visible,textarea:visible');
@@ -229,12 +327,32 @@ export async function executeDiscovery(w, step) {
229
327
  throw Error('补充测试字段已变化');
230
328
  if (c.check === 'cancel-create') {
231
329
  await input.fill(w.variables.recordAccount);
330
+ await waitForVisibleStep(w);
232
331
  await (await control(w, c.cancel)).click();
233
332
  await w.waitModalClosed();
234
- await reload(w);
333
+ await waitForVisibleStep(w);
235
334
  await (await control(w, c.field)).fill(w.variables.recordAccount);
236
335
  if (c.search) await (await control(w, c.search)).click();
237
336
  await waitTable(w, (rows) => rows.length === 0);
337
+ await w.assertPersisted('${recordAccount}', false, {
338
+ record: false,
339
+ query: [
340
+ {
341
+ kind: 'fill',
342
+ target: { ...c.field, scope: 'page' },
343
+ value: '${recordAccount}',
344
+ },
345
+ ...(c.search
346
+ ? [
347
+ {
348
+ kind: 'click',
349
+ purpose: 'search',
350
+ target: { ...c.search, scope: 'page' },
351
+ },
352
+ ]
353
+ : []),
354
+ ],
355
+ });
238
356
  } else {
239
357
  const observed = info.inputs[0];
240
358
  if (
@@ -261,17 +379,25 @@ export async function executeDiscovery(w, step) {
261
379
  c.constraint,
262
380
  );
263
381
  if (!invalid) throw Error('字段未按声明的约束拒绝非法值');
382
+ await waitForVisibleStep(w);
264
383
  await (await control(w, c.cancel)).click();
265
384
  await w.waitModalClosed();
266
385
  }
267
386
  }
268
- } finally {
269
- await reload(w);
387
+ } catch (error) {
388
+ failure = error;
389
+ }
390
+ try {
391
+ await restoreDiscovery(w, c, original, baseline);
392
+ } catch (error) {
393
+ if (!failure) throw error;
394
+ throw Error(`${failure.message};${error.message}`, { cause: failure });
270
395
  }
396
+ if (failure) throw failure;
271
397
  w.record(step);
272
398
  }
273
399
 
274
- export async function discoverTests(w) {
400
+ export async function discoverTests(w, { readOnly = w.config.readOnly } = {}) {
275
401
  if (w.pendingWrite || w.created) {
276
402
  w.discovery = {
277
403
  status: 'blocked',
@@ -280,9 +406,21 @@ export async function discoverTests(w) {
280
406
  };
281
407
  return;
282
408
  }
283
- await reload(w);
284
- const snapshot = await w.snapshot();
285
- const candidates = discoveryCandidates(snapshot, w.formEvidence);
409
+ await assertPageIdentity(w.page, w.identity);
410
+ if (await w.editorPresent()) throw Error('编辑区未关闭,停止补充探索');
411
+ let snapshot = await w.snapshot();
412
+ const query = discoveryCandidates(snapshot, null).find((c) => c.check === 'filter-empty');
413
+ if (query && (await (await control(w, query.field)).inputValue()) !== '') {
414
+ activity(w, '正在清除本轮查询条件,保留主应用及其他子应用状态');
415
+ try {
416
+ await setFilter(w, query, '');
417
+ } finally {
418
+ activity(w, '');
419
+ }
420
+ }
421
+ await expandCollection(w, { record: false });
422
+ snapshot = await w.snapshot();
423
+ const candidates = discoveryCandidates(snapshot, readOnly ? null : w.formEvidence);
286
424
  w.discovery = {
287
425
  status: 'completed',
288
426
  candidates: [],
@@ -297,13 +435,23 @@ export async function discoverTests(w) {
297
435
  const entry = { ...c, ...decision };
298
436
  w.discovery.candidates.push(entry);
299
437
  if (!decision.selected) continue;
300
- const result = await w.runCase(`discover-${i + 1}`, c.title, 'discover', async () => {
301
- await executeDiscovery(w, { kind: 'assert-discovery', spec: c });
302
- });
438
+ const result = await w.runCase(
439
+ `discover-${i + 1}`,
440
+ c.title,
441
+ readOnly ? 'filters' : 'discover',
442
+ async () => {
443
+ await executeDiscovery(w, { kind: 'assert-discovery', spec: c });
444
+ },
445
+ );
303
446
  entry.status = result.status;
304
447
  entry.reason = result.reason;
305
448
  w.completeCase(result);
306
449
  console.log(`${result.status} ${result.id}: ${result.reason}`);
450
+ if (w.restorationFailure) {
451
+ w.discovery.status = 'blocked';
452
+ w.discovery.reason = w.restorationFailure;
453
+ break;
454
+ }
307
455
  }
308
456
  w.discovery.truncated = Math.max(0, candidates.length - 12);
309
457
  }
@@ -319,5 +467,8 @@ export async function observeFormEvidence(w, create) {
319
467
  create: target(create),
320
468
  cancel: cancel.length === 1 ? target(cancel[0]) : null,
321
469
  fields: await inspectForm(w.page),
470
+ hasRangeFormatInput: (await inspectLooseRequired(w.page)).some((input) =>
471
+ invalidExampleValue(input.placeholder),
472
+ ),
322
473
  };
323
474
  }
@@ -12,20 +12,72 @@ export async function observe(page) {
12
12
  const visible = (e) => {
13
13
  const s = getComputedStyle(e),
14
14
  r = e.getBoundingClientRect();
15
+ let left = r.left,
16
+ right = r.right,
17
+ top = r.top,
18
+ bottom = r.bottom;
19
+ // Collapsed disclosure content may retain nonzero boxes.
20
+ // Do not offer controls clipped by overflow:hidden/clip;
21
+ // scrollable containers remain usable by Playwright.
22
+ for (let p = e.parentElement; p; p = p.parentElement) {
23
+ const style = getComputedStyle(p),
24
+ box = p.getBoundingClientRect();
25
+ if (['hidden', 'clip'].includes(style.overflowX)) {
26
+ left = Math.max(left, box.left);
27
+ right = Math.min(right, box.right);
28
+ }
29
+ if (['hidden', 'clip'].includes(style.overflowY)) {
30
+ top = Math.max(top, box.top);
31
+ bottom = Math.min(bottom, box.bottom);
32
+ }
33
+ }
15
34
  return (
16
35
  s.display !== 'none' &&
17
36
  s.visibility !== 'hidden' &&
18
37
  r.width > 0 &&
19
38
  r.height > 0 &&
39
+ right > left &&
40
+ bottom > top &&
20
41
  !e.closest('[inert],[aria-hidden="true"]')
21
42
  );
22
43
  };
23
44
  const text = (e) =>
24
45
  (e?.innerText || e?.textContent || '').replace(/\s+/g, ' ').trim();
46
+ const regionSelector =
47
+ 'aside,[role="complementary"],section[aria-label],section[aria-labelledby],[role="region"],main,[role="main"],header,[role="banner"],nav,[role="navigation"]';
48
+ const describeRegion = (e) =>
49
+ e
50
+ ? {
51
+ role:
52
+ e.getAttribute('role') ||
53
+ {
54
+ aside: 'complementary',
55
+ main: 'main',
56
+ header: 'banner',
57
+ nav: 'navigation',
58
+ section: 'region',
59
+ }[e.tagName.toLowerCase()],
60
+ name: (
61
+ (e.getAttribute('aria-labelledby') || '')
62
+ .split(/\s+/)
63
+ .map((id) => text(e.getRootNode().getElementById(id)))
64
+ .join(' ')
65
+ .trim() ||
66
+ e.getAttribute('aria-label') ||
67
+ ''
68
+ )
69
+ .replace(/\s+/g, ' ')
70
+ .trim(),
71
+ }
72
+ : null;
25
73
  const roots = [document];
26
74
  for (let i = 0; i < roots.length; i++)
27
75
  for (const e of roots[i].querySelectorAll('*'))
28
76
  if (e.shadowRoot) roots.push(e.shadowRoot);
77
+ const regions = roots
78
+ .flatMap((root) => [...root.querySelectorAll(regionSelector)])
79
+ .filter(visible)
80
+ .map(describeRegion);
29
81
  const selector =
30
82
  'button,a[href],input:not([type="hidden"]),textarea,select,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="option"],[role="combobox"],[role="checkbox"],[role="radio"],[role="switch"],[tabindex],[contenteditable="true"],summary';
31
83
  let elements = roots
@@ -72,7 +124,7 @@ export async function observe(page) {
72
124
  const modals = roots
73
125
  .flatMap((root) => [
74
126
  ...root.querySelectorAll(
75
- 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog',
127
+ 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog,[data-laya-editor-root]',
76
128
  ),
77
129
  ])
78
130
  .filter(visible);
@@ -175,8 +227,14 @@ export async function observe(page) {
175
227
  )
176
228
  .replace(/^\*\s*/, '')
177
229
  .slice(0, 130);
178
- const row = e.closest('tr,[role="row"]'),
230
+ const row = e.closest('tr,[role="row"],[role="treeitem"]'),
179
231
  group = e.closest('fieldset,[role="group"],form');
232
+ const region = describeRegion(e.closest(regionSelector));
233
+ const regionAmbiguous =
234
+ !!region &&
235
+ regions.filter(
236
+ (r) => r.role === region.role && r.name === region.name,
237
+ ).length !== 1;
180
238
  const rowKey = row?.getAttribute('data-row-key') || '';
181
239
  // Fixed operation columns have rows containing only icons. Join their live
182
240
  // data-row-key to the main table, rather than mistaking all icons for one row.
@@ -205,6 +263,11 @@ export async function observe(page) {
205
263
  rowKey,
206
264
  placeholder: e.getAttribute('placeholder') || '',
207
265
  context,
266
+ region,
267
+ regionAmbiguous,
268
+ expanded: e.hasAttribute('aria-expanded')
269
+ ? e.getAttribute('aria-expanded') === 'true'
270
+ : null,
208
271
  inPanel: !!e.closest('[role="tabpanel"]'),
209
272
  disabled:
210
273
  e.matches(':disabled') ||
@@ -1,9 +1,9 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ import { FORM_ROOT } from './page-capabilities.mjs';
2
3
 
3
4
  const REF = 'data-laya-form-ref';
4
5
  // 弹窗根选择器:与 dom.mjs / workflow.mjs 的模态判定同族,使用标准语义与已支持的组件容器
5
- const ROOT_SEL =
6
- 'dialog[open],[role="dialog"],[role="alertdialog"],[data-slot="dialog-content"],[data-slot="alert-dialog-content"],.ant-drawer-open .ant-drawer-content,.el-dialog';
6
+ const ROOT_SEL = FORM_ROOT;
7
7
  const visible = (e) => {
8
8
  const r = e.getBoundingClientRect(),
9
9
  s = getComputedStyle(e);
@@ -52,7 +52,7 @@ export async function inspectForm(page) {
52
52
  ? text(nativeSelect.selectedOptions[0])
53
53
  : text(
54
54
  item.querySelector(
55
- '.ant-select-selection-selected-value,.ant-select-selection-item,.ant-select-selection__choice__content,.tntd-rc-select-selection-item,.tntd-select-selection-item',
55
+ '.ant-select-content-has-value:not(.ant-select-content-has-search-value),.ant-select-selection-selected-value,.ant-select-selection-item,.ant-select-selection__choice__content,.tntd-rc-select-selection-item,.tntd-select-selection-item',
56
56
  ),
57
57
  );
58
58
  return {