-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathlocator.ts
More file actions
474 lines (400 loc) · 15.6 KB
/
Copy pathlocator.ts
File metadata and controls
474 lines (400 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import sharp from 'sharp';
import type { MobilewrightDriver, ViewNode, Bounds, SwipeDirection, ScreenSize } from '@mobilewright/protocol';
import { queryAll, type LocatorStrategy, type Role } from './query-engine.js';
import { sleep } from './sleep.js';
import { runStep, type StepLocation } from './stackTrace.js';
export type StepFn = (title: string, fn: () => Promise<unknown>, location: StepLocation | undefined) => Promise<unknown>;
export interface LocatorOptions {
timeout?: number;
pollInterval?: number;
stabilityDelay?: number;
/** Default timeout for expect() assertions on this locator, in ms. */
expectTimeout?: number;
}
export interface FilterOptions {
/** Keep only elements whose subtree contains this text. */
hasText?: string | RegExp;
/** Keep only elements whose subtree does NOT contain this text. */
hasNotText?: string | RegExp;
/** Keep only elements that contain an element matching this locator. */
has?: Locator;
/** Keep only elements that do NOT contain an element matching this locator. */
hasNot?: Locator;
}
export interface ScrollIntoViewOptions {
/** Maximum number of swipe attempts before giving up (default: 10) */
maxSwipes?: number;
/** Swipe gesture direction — 'up' swipes up (scrolls content down), 'down' swipes down (scrolls content up). Default: 'up' */
direction?: 'up' | 'down';
}
const DEFAULT_TIMEOUT = 5_000;
const DEFAULT_POLL_INTERVAL = 100;
const DEFAULT_STABILITY_DELAY = 50;
export class Locator {
/** Create a root locator that searches the entire view hierarchy. */
static root(driver: MobilewrightDriver, options: LocatorOptions = {}): Locator {
return new Locator(driver, { kind: 'root' }, options);
}
_stepFn: StepFn | null = null;
constructor(
protected readonly driver: MobilewrightDriver,
protected readonly strategy: LocatorStrategy,
protected readonly options: LocatorOptions = {},
) {}
get expectTimeout(): number | undefined {
return this.options.expectTimeout;
}
protected async _step<T>(title: string, fn: () => Promise<T>): Promise<T> {
return runStep(this._stepFn, title, fn);
}
// ─── Chaining ────────────────────────────────────────────────
getByLabel(label: string, opts?: { exact?: boolean }): Locator {
return this.child({ kind: 'label', value: label, exact: opts?.exact });
}
getByTestId(testId: string): Locator {
return this.child({ kind: 'testId', value: testId });
}
getByText(text: string | RegExp, opts?: { exact?: boolean }): Locator {
return this.child({ kind: 'text', value: text, exact: opts?.exact });
}
getByType(type: string): Locator {
return this.child({ kind: 'type', value: type });
}
getByRole(role: Role, opts?: { name?: string | RegExp }): Locator {
return this.child({ kind: 'role', value: role, name: opts?.name });
}
getByPlaceholder(placeholder: string, opts?: { exact?: boolean }): Locator {
return this.child({ kind: 'placeholder', value: placeholder, exact: opts?.exact });
}
protected child(childStrategy: LocatorStrategy): Locator {
return this.withStrategy({ kind: 'chain', parent: this.strategy, child: childStrategy });
}
/** Build a sibling locator that shares this one's driver, options, and step fn. */
protected withStrategy(strategy: LocatorStrategy): Locator {
const loc = new Locator(this.driver, strategy, this.options);
loc._stepFn = this._stepFn;
return loc;
}
// ─── Narrowing & combining ───────────────────────────────────
/** Narrow this locator to elements matching the given conditions. */
filter(opts?: FilterOptions): Locator {
return this.withStrategy({
kind: 'filter',
parent: this.strategy,
hasText: opts?.hasText,
hasNotText: opts?.hasNotText,
has: opts?.has?.strategy,
hasNot: opts?.hasNot?.strategy,
});
}
/** Match elements that satisfy both this locator and the given locator. */
and(locator: Locator): Locator {
return this.withStrategy({ kind: 'and', left: this.strategy, right: locator.strategy });
}
/** Match elements that satisfy either this locator or the given locator. */
or(locator: Locator): Locator {
return this.withStrategy({ kind: 'or', left: this.strategy, right: locator.strategy });
}
// ─── Collection ──────────────────────────────────────────────
first(): Locator {
return this.nth(0);
}
last(): Locator {
return this.nth(-1);
}
nth(index: number): Locator {
return this.withStrategy({ kind: 'nth', parent: this.strategy, index });
}
async count(): Promise<number> {
const roots = await this.driver.getViewHierarchy();
return queryAll(roots, this.strategy).length;
}
async all(): Promise<Locator[]> {
const roots = await this.driver.getViewHierarchy();
const matches = queryAll(roots, this.strategy);
return matches.map((_, i) => {
const loc = new Locator(
this.driver,
{ kind: 'nth', parent: this.strategy, index: i },
this.options,
);
loc._stepFn = this._stepFn;
return loc;
});
}
// ─── Actions ─────────────────────────────────────────────────
async tap(opts?: { timeout?: number }): Promise<void> {
return this._step('locator.tap()', async () => {
const node = await this.resolveActionable(opts?.timeout);
const { x, y } = centerOf(node.bounds);
await this.driver.tap(x, y);
});
}
async doubleTap(opts?: { timeout?: number }): Promise<void> {
return this._step('locator.doubleTap()', async () => {
const node = await this.resolveActionable(opts?.timeout);
const { x, y } = centerOf(node.bounds);
await this.driver.doubleTap(x, y);
});
}
async longPress(opts?: { timeout?: number; duration?: number }): Promise<void> {
return this._step('locator.longPress()', async () => {
const node = await this.resolveActionable(opts?.timeout);
const { x, y } = centerOf(node.bounds);
await this.driver.longPress(x, y, opts?.duration);
});
}
async fill(text: string, opts?: { timeout?: number }): Promise<void> {
return this._step(`locator.fill(${JSON.stringify(text)})`, async () => {
const node = await this.resolveActionable(opts?.timeout);
const { x, y } = centerOf(node.bounds);
await this.driver.tap(x, y);
await this.driver.typeText(text);
});
}
async screenshot(opts?: { timeout?: number }): Promise<Buffer> {
return this._step('locator.screenshot()', async () => {
const node = await this.resolveVisible(opts?.timeout);
const fullScreenshot = await this.driver.screenshot();
return cropToElement(fullScreenshot, node.bounds, await this.driver.getScreenSize());
});
}
async swipe(opts: { direction: SwipeDirection; timeout?: number }): Promise<void> {
return this._step(`locator.swipe(${opts.direction})`, async () => {
const node = await this.resolveActionable(opts.timeout);
const { x, y } = centerOf(node.bounds);
await this.driver.swipe(opts.direction, { startX: x, startY: y });
});
}
async scrollIntoViewIfNeeded(opts?: ScrollIntoViewOptions): Promise<void> {
return this._step('locator.scrollIntoViewIfNeeded()', async () => {
const maxSwipes = opts?.maxSwipes ?? 10;
const direction: SwipeDirection = opts?.direction ?? 'up';
const screenSize = await this.driver.getScreenSize();
const POST_SWIPE_SETTLE = 200;
for (let i = 0; i < maxSwipes; i++) {
const roots = await this.driver.getViewHierarchy();
const node = queryAll(roots, this.strategy)[0] ?? null;
if (node && isWithinViewport(node.bounds, screenSize)) {
return;
}
const swipeDirection = node ? swipeDirectionToReveal(node.bounds, screenSize) : direction;
await this.driver.swipe(swipeDirection);
await sleep(POST_SWIPE_SETTLE);
}
throw new LocatorError(
`Element not scrolled into view after ${maxSwipes} swipes`,
this.strategy,
);
});
}
// ─── Queries (with auto-wait for visibility) ─────────────────
async exists(): Promise<boolean> {
const node = await this.resolve(0);
return node !== null;
}
async isVisible(opts?: { timeout?: number }): Promise<boolean> {
try {
await this.waitFor({ state: 'visible', timeout: opts?.timeout ?? 0 });
return true;
} catch (error) {
if (!(error instanceof LocatorError)) {
throw error;
}
return false;
}
}
async isEnabled(opts?: { timeout?: number }): Promise<boolean> {
const node = await this.resolve(opts?.timeout ?? 0);
return node !== null && node.isEnabled;
}
async isSelected(opts?: { timeout?: number }): Promise<boolean> {
const node = await this.resolve(opts?.timeout ?? 0);
return node !== null && node.isSelected === true;
}
async isFocused(opts?: { timeout?: number }): Promise<boolean> {
const node = await this.resolve(opts?.timeout ?? 0);
return node !== null && node.isFocused === true;
}
async isChecked(opts?: { timeout?: number }): Promise<boolean> {
const node = await this.resolve(opts?.timeout ?? 0);
return node !== null && node.isChecked === true;
}
async boundingBox(opts?: { timeout?: number }): Promise<{ x: number; y: number; width: number; height: number }> {
const node = await this.resolveVisible(opts?.timeout);
return { x: node.bounds.x, y: node.bounds.y, width: node.bounds.width, height: node.bounds.height };
}
async getText(opts?: { timeout?: number }): Promise<string> {
const node = await this.resolveVisible(opts?.timeout);
return node.text ?? node.label ?? node.value ?? '';
}
async getValue(opts?: { timeout?: number }): Promise<string> {
const node = await this.resolveVisible(opts?.timeout);
return node.value ?? '';
}
async waitFor(opts?: {
state?: 'visible' | 'hidden' | 'enabled' | 'disabled';
timeout?: number;
}): Promise<void> {
await this.pollUntilState(opts?.state ?? 'visible', opts?.timeout);
}
// ─── Internal resolution ─────────────────────────────────────
/** Wait for a visible node and return it. Used by getText, screenshot. */
private async resolveVisible(timeout?: number): Promise<ViewNode> {
const node = await this.pollUntilState('visible', timeout);
return node!;
}
/** Poll until the given state is satisfied. Returns the matched node (or null for hidden/disabled). */
private async pollUntilState(
state: 'visible' | 'hidden' | 'enabled' | 'disabled',
timeout?: number,
): Promise<ViewNode | null> {
const effectiveTimeout = timeout ?? this.options.timeout ?? DEFAULT_TIMEOUT;
const pollInterval = this.options.pollInterval ?? DEFAULT_POLL_INTERVAL;
const deadline = Date.now() + effectiveTimeout;
while (true) {
const roots = await this.driver.getViewHierarchy();
const node = queryAll(roots, this.strategy)[0] ?? null;
if (checkState(node, state)) {
return node;
}
if (Date.now() >= deadline) {
throw new LocatorError(
`Locator timed out waiting for state "${state}" after ${effectiveTimeout}ms`,
this.strategy,
);
}
await sleep(pollInterval);
}
}
/** Resolve to a single actionable node (visible, enabled, stable bounds) */
private async resolveActionable(
timeout?: number,
): Promise<ViewNode> {
const effectiveTimeout =
timeout ?? this.options.timeout ?? DEFAULT_TIMEOUT;
const pollInterval =
this.options.pollInterval ?? DEFAULT_POLL_INTERVAL;
const stabilityDelay =
this.options.stabilityDelay ?? DEFAULT_STABILITY_DELAY;
const deadline = Date.now() + effectiveTimeout;
let previousBounds: Bounds | null = null;
let lastReason = 'no matching element found';
while (true) {
const roots = await this.driver.getViewHierarchy();
const node = queryAll(roots, this.strategy)[0];
if (!node) {
lastReason = 'no matching element found';
} else if (!node.isVisible) {
lastReason = 'element found but not visible';
} else if (!node.isEnabled) {
lastReason = 'element found but not enabled';
} else {
// Stability check: bounds haven't changed since last poll
if (previousBounds && boundsEqual(previousBounds, node.bounds)) {
return node;
}
previousBounds = { ...node.bounds };
if (Date.now() >= deadline) {
return node; // accept without stability
}
await sleep(stabilityDelay);
continue;
}
if (Date.now() >= deadline) {
throw new LocatorError(
`Locator: ${lastReason} after ${effectiveTimeout}ms`,
this.strategy,
);
}
await sleep(pollInterval);
}
}
/** Resolve without waiting — returns null if not found */
private async resolve(timeout: number): Promise<ViewNode | null> {
const deadline = Date.now() + timeout;
const pollInterval =
this.options.pollInterval ?? DEFAULT_POLL_INTERVAL;
do {
const roots = await this.driver.getViewHierarchy();
const matches = queryAll(roots, this.strategy);
if (matches.length > 0) {
return matches[0];
}
if (timeout <= 0) {
return null;
}
await sleep(pollInterval);
} while (Date.now() < deadline);
return null;
}
}
async function cropToElement(
screenshot: Buffer,
bounds: Bounds,
screenSize: { width: number; height: number },
): Promise<Buffer> {
const metadata = await sharp(screenshot).metadata();
const scale = (metadata.width ?? 1) / screenSize.width;
return sharp(screenshot)
.extract({
left: Math.round(bounds.x * scale),
top: Math.round(bounds.y * scale),
width: Math.round(bounds.width * scale),
height: Math.round(bounds.height * scale),
})
.toBuffer();
}
function centerOf(bounds: Bounds): { x: number; y: number } {
return {
x: Math.round(bounds.x + bounds.width / 2),
y: Math.round(bounds.y + bounds.height / 2),
};
}
function boundsEqual(a: Bounds, b: Bounds): boolean {
return (
a.x === b.x &&
a.y === b.y &&
a.width === b.width &&
a.height === b.height
);
}
function checkState(
node: ViewNode | null,
state: 'visible' | 'hidden' | 'enabled' | 'disabled',
): boolean {
switch (state) {
case 'visible':
return node !== null && node.isVisible;
case 'hidden':
return node === null || !node.isVisible;
case 'enabled':
return node !== null && node.isEnabled;
case 'disabled':
return node !== null && !node.isEnabled;
}
}
function isWithinViewport(bounds: Bounds, screen: ScreenSize): boolean {
return bounds.y >= 0
&& bounds.y + bounds.height <= screen.height
&& bounds.x >= 0
&& bounds.x + bounds.width <= screen.width;
}
function swipeDirectionToReveal(bounds: Bounds, screen: ScreenSize): SwipeDirection {
const centerY = bounds.y + bounds.height / 2;
// Element is below the viewport → swipe up to reveal it
if (centerY > screen.height) {
return 'up';
}
// Element is above the viewport → swipe down to reveal it
return 'down';
}
export class LocatorError extends Error {
constructor(
message: string,
public readonly strategy: LocatorStrategy,
) {
super(message);
this.name = 'LocatorError';
}
}