Skip to content

Commit

Permalink
chore: migrate from timeouts to deadlines internally
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Apr 7, 2020
1 parent 362b72c commit 9d559e3
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 95 deletions.
14 changes: 11 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ Emitted when attachment is downloaded. User can access basic file operations on
- `element` <[ElementHandle]> handle to the input element that was clicked
- `multiple` <[boolean]> Whether file chooser allow for [multiple](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple) file selection.

Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can respond to it via setting the input files using [`elementHandle.setInputFiles`](#elementhandlesetinputfilesfiles) which can be uploaded in the end.
Emitted when a file chooser is supposed to appear, such as after clicking the `<input type=file>`. Playwright can respond to it via setting the input files using [`elementHandle.setInputFiles`](#elementhandlesetinputfilesfiles-options) which can be uploaded in the end.

```js
page.on('filechooser', async ({element, multiple}) => {
Expand Down Expand Up @@ -2498,7 +2498,7 @@ ElementHandle instances can be used as an argument in [`page.$eval()`](#pageeval
- [elementHandle.screenshot([options])](#elementhandlescreenshotoptions)
- [elementHandle.scrollIntoViewIfNeeded()](#elementhandlescrollintoviewifneeded)
- [elementHandle.selectOption(values[, options])](#elementhandleselectoptionvalues-options)
- [elementHandle.setInputFiles(files)](#elementhandlesetinputfilesfiles)
- [elementHandle.setInputFiles(files[, options])](#elementhandlesetinputfilesfiles-options)
- [elementHandle.toString()](#elementhandletostring)
- [elementHandle.type(text[, options])](#elementhandletypetext-options)
- [elementHandle.uncheck([options])](#elementhandleuncheckoptions)
Expand Down Expand Up @@ -2759,11 +2759,19 @@ handle.selectOption('red', 'green', 'blue');
handle.selectOption({ value: 'blue' }, { index: 2 }, 'red');
```

#### elementHandle.setInputFiles(files)
#### elementHandle.setInputFiles(files[, options])
- `files` <[string]|[Array]<[string]>|[Object]|[Array]<[Object]>>
- `name` <[string]> [File] name **required**
- `type` <[string]> [File] type **required**
- `data` <[string]> Base64-encoded data **required**
- `options` <[Object]>
- `waitUntil` <"load"|"domcontentloaded"|"networkidle0"|"networkidle2"|"nowait"> Actions that cause navigations are waiting for those navigations to fire `domcontentloaded` by default. This behavior can be changed to either wait for another load phase or to omit the waiting altogether using `nowait`:
- `'domcontentloaded'` - consider navigation to be finished when the `DOMContentLoaded` event is fired.
- `'load'` - consider navigation to be finished when the `load` event is fired.
- `'networkidle0'` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.
- `'networkidle2'` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.
- `'nowait'` - do not wait.
- `timeout` <[number]> Maximum time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [browserContext.setDefaultTimeout(timeout)](#browsercontextsetdefaulttimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.
- returns: <[Promise]>

This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
Expand Down
4 changes: 2 additions & 2 deletions src/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ export abstract class BrowserContextBase extends ExtendedEventEmitter implements
return event === Events.BrowserContext.Close ? super._abortPromiseForEvent(event) : this._closePromise;
}

protected _timeoutForEvent(event: string): number {
return this._timeoutSettings.timeout();
protected _computeDeadline(options?: types.TimeoutOptions): number {
return this._timeoutSettings.computeDeadline(options);
}

_browserClosed() {
Expand Down
43 changes: 25 additions & 18 deletions src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export class FrameExecutionContext extends js.ExecutionContext {
async _doEvaluateInternal(returnByValue: boolean, waitForNavigations: boolean, pageFunction: string | Function, ...args: any[]): Promise<any> {
return await this.frame._page._frameManager.waitForNavigationsCreatedBy(async () => {
return this._delegate.evaluate(this, returnByValue, pageFunction, ...args);
}, waitForNavigations ? undefined : { waitUntil: 'nowait' });
}, Number.MAX_SAFE_INTEGER, waitForNavigations ? undefined : { waitUntil: 'nowait' });
}

_createHandle(remoteObject: any): js.JSHandle {
Expand Down Expand Up @@ -181,19 +181,21 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
return point;
}

async _performPointerAction(action: (point: types.Point) => Promise<void>, options?: PointerActionOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions): Promise<void> {
async _performPointerAction(action: (point: types.Point) => Promise<void>, options: PointerActionOptions & types.PointerActionWaitOptions & types.NavigatingActionWaitOptions = {}): Promise<void> {
const deadline = this._page._timeoutSettings.computeDeadline(options);
const { force = false } = (options || {});
if (!force)
await this._waitForDisplayedAtStablePosition(options);
await this._waitForDisplayedAtStablePosition(deadline);
const position = options ? options.position : undefined;
await this._scrollRectIntoViewIfNeeded(position ? { x: position.x, y: position.y, width: 0, height: 0 } : undefined);
const point = position ? await this._offsetPoint(position) : await this._clickablePoint();
if (!force)
await this._waitForHitTargetAt(point, options);

point.x = (point.x * 100 | 0) / 100;
point.y = (point.y * 100 | 0) / 100;

if (!force)
await this._waitForHitTargetAt(point, deadline);

await this._page._frameManager.waitForNavigationsCreatedBy(async () => {
let restoreModifiers: input.Modifier[] | undefined;
if (options && options.modifiers)
Expand All @@ -203,7 +205,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
debugInput('...done');
if (restoreModifiers)
await this._page.keyboard._ensureModifiers(restoreModifiers);
}, options, true);
}, deadline, options, true);
}

hover(options?: PointerActionOptions & types.PointerActionWaitOptions): Promise<void> {
Expand All @@ -219,6 +221,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}

async selectOption(values: string | ElementHandle | types.SelectOption | string[] | ElementHandle[] | types.SelectOption[], options?: types.NavigatingActionWaitOptions): Promise<string[]> {
const deadline = this._page._timeoutSettings.computeDeadline(options);
let vals: string[] | ElementHandle[] | types.SelectOption[];
if (!Array.isArray(values))
vals = [ values ] as (string[] | ElementHandle[] | types.SelectOption[]);
Expand All @@ -237,11 +240,12 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
return await this._page._frameManager.waitForNavigationsCreatedBy<string[]>(async () => {
return this._evaluateInUtility(({ injected, node }, selectOptions) => injected.selectOptions(node, selectOptions), selectOptions);
}, options);
}, deadline, options);
}

async fill(value: string, options?: types.NavigatingActionWaitOptions): Promise<void> {
assert(helper.isString(value), 'Value must be string. Found value "' + value + '" of type "' + (typeof value) + '"');
const deadline = this._page._timeoutSettings.computeDeadline(options);
await this._page._frameManager.waitForNavigationsCreatedBy(async () => {
const errorOrNeedsInput = await this._evaluateInUtility(({ injected, node }, value) => injected.fill(node, value), value);
if (typeof errorOrNeedsInput === 'string')
Expand All @@ -252,10 +256,11 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
else
await this._page.keyboard.press('Delete');
}
}, options, true);
}, deadline, options, true);
}

async setInputFiles(files: string | types.FilePayload | string[] | types.FilePayload[]) {
async setInputFiles(files: string | types.FilePayload | string[] | types.FilePayload[], options?: types.NavigatingActionWaitOptions) {
const deadline = this._page._timeoutSettings.computeDeadline(options);
const multiple = await this._evaluateInUtility(({ node }) => {
if (node.nodeType !== Node.ELEMENT_NODE || (node as Node as Element).tagName !== 'INPUT')
throw new Error('Node is not an HTMLInputElement');
Expand Down Expand Up @@ -283,7 +288,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
await this._page._frameManager.waitForNavigationsCreatedBy(async () => {
await this._page._delegate.setInputFiles(this as any as ElementHandle<HTMLInputElement>, filePayloads);
});
}, deadline, options);
}

async focus() {
Expand All @@ -298,17 +303,19 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}

async type(text: string, options?: { delay?: number } & types.NavigatingActionWaitOptions) {
const deadline = this._page._timeoutSettings.computeDeadline(options);
await this._page._frameManager.waitForNavigationsCreatedBy(async () => {
await this.focus();
await this._page.keyboard.type(text, options);
}, options, true);
}, deadline, options, true);
}

async press(key: string, options?: { delay?: number } & types.NavigatingActionWaitOptions) {
const deadline = this._page._timeoutSettings.computeDeadline(options);
await this._page._frameManager.waitForNavigationsCreatedBy(async () => {
await this.focus();
await this._page.keyboard.press(key, options);
}, options, true);
}, deadline, options, true);
}

async check(options?: types.PointerActionWaitOptions & types.NavigatingActionWaitOptions) {
Expand Down Expand Up @@ -367,16 +374,16 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
return result;
}

async _waitForDisplayedAtStablePosition(options: types.TimeoutOptions = {}): Promise<void> {
async _waitForDisplayedAtStablePosition(deadline: number): Promise<void> {
debugInput('waiting for element to be displayed and not moving...');
const stablePromise = this._evaluateInUtility(({ injected, node }, timeout) => {
return injected.waitForDisplayedAtStablePosition(node, timeout);
}, options.timeout || 0);
await helper.waitWithTimeout(stablePromise, 'element to be displayed and not moving', options.timeout || 0);
}, helper.timeUntilDeadline(deadline));
await helper.waitWithDeadline(stablePromise, 'element to be displayed and not moving', deadline);
debugInput('...done');
}

async _waitForHitTargetAt(point: types.Point, options: types.TimeoutOptions = {}): Promise<void> {
async _waitForHitTargetAt(point: types.Point, deadline: number): Promise<void> {
debugInput(`waiting for element to receive pointer events at (${point.x},${point.y}) ...`);
const frame = await this.ownerFrame();
if (frame && frame.parentFrame()) {
Expand All @@ -389,8 +396,8 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
const hitTargetPromise = this._evaluateInUtility(({ injected, node }, { timeout, point }) => {
return injected.waitForHitTargetAt(node, timeout, point);
}, { timeout: options.timeout || 0, point });
await helper.waitWithTimeout(hitTargetPromise, 'element to receive pointer events', options.timeout || 0);
}, { timeout: helper.timeUntilDeadline(deadline), point });
await helper.waitWithDeadline(hitTargetPromise, 'element to receive pointer events', deadline);
debugInput('...done');
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/extendedEventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,22 @@

import { EventEmitter } from 'events';
import { helper } from './helper';
import { TimeoutOptions } from './types';

export class ExtendedEventEmitter extends EventEmitter {
protected _abortPromiseForEvent(event: string) {
return new Promise<Error>(() => void 0);
}

protected _timeoutForEvent(event: string): number {
protected _computeDeadline(options?: TimeoutOptions): number {
throw new Error('unimplemented');
}

async waitForEvent(event: string, optionsOrPredicate: Function|{ predicate?: Function, timeout?: number } = {}): Promise<any> {
const deadline = this._computeDeadline(typeof optionsOrPredicate === 'function' ? undefined : optionsOrPredicate);
const {
predicate = () => true,
timeout = this._timeoutForEvent(event)
} = typeof optionsOrPredicate === 'function' ? {predicate: optionsOrPredicate} : optionsOrPredicate;
return helper.waitForEvent(this, event, predicate, timeout, this._abortPromiseForEvent(event));
return helper.waitForEvent(this, event, predicate, deadline, this._abortPromiseForEvent(event));
}
}
Loading

0 comments on commit 9d559e3

Please sign in to comment.