Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/src/api/class-page.md
Original file line number Diff line number Diff line change
Expand Up @@ -2845,6 +2845,12 @@ the place it was paused.
This method requires Playwright to be started in a headed mode, with a falsy [`option: BrowserType.launch.headless`] option.
:::

## async method: Page.cancelPickLocator
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder whether we want page.recorder namespace for things like this one?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do it in a separate pr.

* since: v1.59

Cancels an ongoing [`method: Page.pickLocator`] call by deactivating pick locator mode.
If no pick locator mode is active, this method is a no-op.

## async method: Page.pickLocator
* since: v1.59
- returns: <[Locator]>
Expand Down
6 changes: 6 additions & 0 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2187,6 +2187,12 @@ export interface Page {
*/
bringToFront(): Promise<void>;

/**
* Cancels an ongoing [page.pickLocator()](https://playwright.dev/docs/api/class-page#page-pick-locator) call by
* deactivating pick locator mode. If no pick locator mode is active, this method is a no-op.
*/
cancelPickLocator(): Promise<void>;

/**
* **NOTE** Use locator-based [locator.check([options])](https://playwright.dev/docs/api/class-locator#locator-check) instead.
* Read more about [locators](https://playwright.dev/docs/locators).
Expand Down
4 changes: 4 additions & 0 deletions packages/playwright-core/src/client/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,10 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Page
return this.locator(selector);
}

async cancelPickLocator(): Promise<void> {
await this._channel.cancelPickLocator({});
}

async pdf(options: PDFOptions = {}): Promise<Buffer> {
const transportOptions: channels.PagePdfParams = { ...options } as channels.PagePdfParams;
if (transportOptions.margin)
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/protocol/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1534,6 +1534,8 @@ scheme.PagePickLocatorParams = tOptional(tObject({}));
scheme.PagePickLocatorResult = tObject({
selector: tString,
});
scheme.PageCancelPickLocatorParams = tOptional(tObject({}));
scheme.PageCancelPickLocatorResult = tOptional(tObject({}));
scheme.PageVideoStartParams = tObject({
size: tOptional(tObject({
width: tInt,
Expand Down
18 changes: 12 additions & 6 deletions packages/playwright-core/src/server/debugController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,12 @@ export class DebugController extends SdkObject {
this._generateAutoExpect = !!params.generateAutoExpect;

if (params.mode === 'none') {
const promises = [];
for (const recorder of await progress.race(this._allRecorders())) {
recorder.hideHighlightedSelector();
recorder.setMode('none');
promises.push(recorder.hideHighlightedSelector());
promises.push(recorder.setMode('none'));
}
await Promise.all(promises);
return;
}

Expand Down Expand Up @@ -112,20 +114,24 @@ export class DebugController extends SdkObject {
if (params.selector)
unsafeLocatorOrSelectorAsSelector(this._sdkLanguage, params.selector, 'data-testid');
const ariaTemplate = params.ariaTemplate ? parseAriaSnapshotUnsafe(yaml, params.ariaTemplate) : undefined;
const promises = [];
for (const recorder of await progress.race(this._allRecorders())) {
if (ariaTemplate)
recorder.setHighlightedAriaTemplate(ariaTemplate);
promises.push(recorder.setHighlightedAriaTemplate(ariaTemplate));
else if (params.selector)
recorder.setHighlightedSelector(params.selector);
promises.push(recorder.setHighlightedSelector(params.selector));
}
await Promise.all(promises);
}

async hideHighlight(progress: Progress) {
const promises = [];
// Hide all active recorder highlights.
for (const recorder of await progress.race(this._allRecorders()))
recorder.hideHighlightedSelector();
promises.push(recorder.hideHighlightedSelector());
// Hide all locator.highlight highlights.
await Promise.all(this._playwright.allPages().map(p => p.hideHighlight().catch(() => {})));
promises.push(...this._playwright.allPages().map(p => p.hideHighlight().catch(() => {})));
await Promise.all(promises);
}

async resume(progress: Progress) {
Expand Down
18 changes: 10 additions & 8 deletions packages/playwright-core/src/server/devtoolsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,20 +257,22 @@ class DevToolsConnection implements Transport, DevToolsChannel {
await page.screencast.startScreencast(this, { width: 1280, height: 800, quality: 90 });
}

private _deselectPage() {
private async _deselectPage() {
if (!this.selectedPage)
return;
this._cancelPicking();
const promises = [];
promises.push(this._cancelPicking());
eventsHelper.removeEventListeners(this._pageListeners);
this._pageListeners = [];
this.selectedPage.screencast.stopScreencast(this);
promises.push(this.selectedPage.screencast.stopScreencast(this));
this.selectedPage = null;
this._lastFrameData = null;
this._lastViewportSize = null;
await Promise.all(promises);
}

async pickLocator() {
this._cancelPicking();
await this._cancelPicking();
const recorder = await Recorder.forContext(this._context, { omitCallTracking: true, hideToolbar: true });
this._recorder = recorder;
this._recorderListeners.push(
Expand All @@ -279,18 +281,18 @@ class DevToolsConnection implements Transport, DevToolsChannel {
this._cancelPicking();
}),
);
recorder.setMode('inspecting');
await recorder.setMode('inspecting');
}

async cancelPickLocator() {
this._cancelPicking();
await this._cancelPicking();
}

private _cancelPicking() {
private async _cancelPicking() {
eventsHelper.removeEventListeners(this._recorderListeners);
this._recorderListeners = [];
if (this._recorder) {
this._recorder.setMode('none');
await this._recorder.setMode('none');
this._recorder = null;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,7 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel

async disableRecorder(params: channels.BrowserContextDisableRecorderParams, progress: Progress): Promise<void> {
const recorder = await Recorder.existingForContext(this._context);
if (recorder)
recorder.setMode('none');
await recorder?.setMode('none');
}

async exposeConsoleApi(params: channels.BrowserContextExposeConsoleApiParams, progress: Progress): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import { SdkObject } from '../instrumentation';
import { deserializeURLMatch, urlMatches } from '../../utils/isomorphic/urlMatch';
import { PageAgentDispatcher } from './pageAgentDispatcher';
import { Recorder } from '../recorder';
import { isUnderTest } from '../utils/debug';

import type { Artifact } from '../artifact';
import type { BrowserContext } from '../browserContext';
Expand Down Expand Up @@ -347,13 +346,16 @@ export class PageDispatcher extends Dispatcher<Page, channels.PageChannel, Brows
}

async pickLocator(params: channels.PagePickLocatorParams, progress: Progress): Promise<channels.PagePickLocatorResult> {
if (!this._page.browserContext._browser.options.headful && !isUnderTest())
throw new Error('pickLocator() is only available in headed mode');
const recorder = await Recorder.forContext(this._page.browserContext, { omitCallTracking: true, hideToolbar: true });
const selector = await recorder.pickLocator(progress);
return { selector };
}

async cancelPickLocator(params: channels.PageCancelPickLocatorParams, progress: Progress): Promise<void> {
const recorder = await Recorder.existingForContext(this._page.browserContext);
await recorder?.setMode('none');
}

async videoStart(params: channels.PageVideoStartParams, progress: Progress): Promise<channels.PageVideoStartResult> {
const artifact = await this._page.screencast.startExplicitVideoRecording(params);
return { artifact: createVideoDispatcher(this.parentScope(), artifact) };
Expand Down
46 changes: 24 additions & 22 deletions packages/playwright-core/src/server/recorder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
await this._context.exposeBinding(progress, '__pw_recorderSetMode', false, async ({ frame }, mode: Mode) => {
if (frame.parentFrame())
return;
this.setMode(mode);
await this.setMode(mode);
});

await this._context.exposeBinding(progress, '__pw_recorderSetOverlayState', false, async ({ frame }, state: OverlayState) => {
Expand Down Expand Up @@ -252,7 +252,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
return this._mode;
}

setMode(mode: Mode) {
async setMode(mode: Mode) {
if (this._mode === mode)
return;
this._highlightedElement = {};
Expand All @@ -262,7 +262,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
this._debugger.setMuted(this._isRecording());
if (this._mode !== 'none' && this._mode !== 'standby' && this._context.pages().length === 1)
this._context.pages()[0].bringToFront().catch(() => {});
this._refreshOverlay();
await this._refreshOverlay();
}

async pickLocator(progress: Progress): Promise<string> {
Expand All @@ -272,28 +272,32 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
selectorPromise.resolve(elementInfo.selector);
};
const onModeChanged = () => {
if (this._mode === 'inspecting')
return;
recorderChangedState = true;
selectorPromise.reject(new Error('Locator picking was cancelled'));
};
const onContextClosed = () => {
recorderChangedState = true;
selectorPromise.reject(new Error('Context was closed'));
};
// Register listeners after setMode() to avoid consuming the ModeChanged
// event that fires synchronously from our own setMode('inspecting') call.
this.setMode('inspecting');
const listeners: RegisteredListener[] = [
eventsHelper.addEventListener(this, RecorderEvent.ElementPicked, onElementPicked),
eventsHelper.addEventListener(this, RecorderEvent.ModeChanged, onModeChanged),
eventsHelper.addEventListener(this, RecorderEvent.ContextClosed, onContextClosed),
];
try {
return await progress.race(selectorPromise);
const doPickLocator = async () => {
// Prevent unhandled rejection in case of cancellation during setMode
selectorPromise.catch(() => {});
await this.setMode('inspecting');
return await selectorPromise;
};
return await progress.race(doPickLocator());
} finally {
// Remove listeners before setMode('none') to avoid triggering onModeChanged.
eventsHelper.removeEventListeners(listeners);
if (!recorderChangedState)
this.setMode('none');
await this.setMode('none');
}
}

Expand All @@ -302,23 +306,23 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
return page?.mainFrame().url();
}

setHighlightedSelector(selector: string) {
async setHighlightedSelector(selector: string) {
this._highlightedElement = { selector: locatorOrSelectorAsSelector(this._currentLanguage, selector, this._context.selectors().testIdAttributeName()) };
this._refreshOverlay();
await this._refreshOverlay();
}

setHighlightedAriaTemplate(ariaTemplate: AriaTemplateNode) {
async setHighlightedAriaTemplate(ariaTemplate: AriaTemplateNode) {
this._highlightedElement = { ariaTemplate };
this._refreshOverlay();
await this._refreshOverlay();
}

step() {
this._debugger.resume(true);
}

setLanguage(language: Language) {
async setLanguage(language: Language) {
this._currentLanguage = language;
this._refreshOverlay();
await this._refreshOverlay();
}

resume() {
Expand All @@ -337,9 +341,9 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
this._debugger.resume(false);
}

hideHighlightedSelector() {
async hideHighlightedSelector() {
this._highlightedElement = {};
this._refreshOverlay();
await this._refreshOverlay();
}

pausedSourceId() {
Expand Down Expand Up @@ -386,11 +390,9 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
}
}

private _refreshOverlay() {
for (const page of this._context.pages()) {
for (const frame of page.frames())
frame.evaluateExpression('window.__pw_refreshOverlay()').catch(() => {});
}
private async _refreshOverlay() {
await Promise.all(this._context.pages().map(
page => page.safeNonStallingEvaluateInAllFrames('window.__pw_refreshOverlay()', 'main')));
}

async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata) {
Expand Down
8 changes: 4 additions & 4 deletions packages/playwright-core/src/server/recorder/recorderApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,15 @@ export class RecorderApp {
if (source) {
if (source.isRecorded)
this._selectedGeneratorId = source.id;
this._recorder.setLanguage(source.language);
await this._recorder.setLanguage(source.language);
}
},
setAutoExpect: async (params: { autoExpect: boolean }) => {
this._languageGeneratorOptions.generateAutoExpect = params.autoExpect;
this._updateActions();
},
setMode: async (params: { mode: Mode }) => {
this._recorder.setMode(params.mode);
await this._recorder.setMode(params.mode);
},
resume: async () => {
this._recorder.resume();
Expand All @@ -163,9 +163,9 @@ export class RecorderApp {
},
highlightRequested: async (params: { selector?: string; ariaTemplate?: AriaTemplateNode }) => {
if (params.selector)
this._recorder.setHighlightedSelector(params.selector);
await this._recorder.setHighlightedSelector(params.selector);
if (params.ariaTemplate)
this._recorder.setHighlightedAriaTemplate(params.ariaTemplate);
await this._recorder.setHighlightedAriaTemplate(params.ariaTemplate);
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ export const methodMetainfo = new Map<string, { internal?: boolean, title?: stri
['Page.startCSSCoverage', { title: 'Start CSS coverage', group: 'configuration', }],
['Page.stopCSSCoverage', { title: 'Stop CSS coverage', group: 'configuration', }],
['Page.bringToFront', { title: 'Bring to front', }],
['Page.pickLocator', { title: 'Pick locator', }],
['Page.pickLocator', { title: 'Pick locator', group: 'configuration', }],
['Page.cancelPickLocator', { title: 'Cancel pick locator', group: 'configuration', }],
['Page.videoStart', { title: 'Start video recording', group: 'configuration', }],
['Page.videoStop', { title: 'Stop video recording', group: 'configuration', }],
['Page.updateSubscription', { internal: true, }],
Expand Down
6 changes: 6 additions & 0 deletions packages/playwright-core/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2187,6 +2187,12 @@ export interface Page {
*/
bringToFront(): Promise<void>;

/**
* Cancels an ongoing [page.pickLocator()](https://playwright.dev/docs/api/class-page#page-pick-locator) call by
* deactivating pick locator mode. If no pick locator mode is active, this method is a no-op.
*/
cancelPickLocator(): Promise<void>;

/**
* **NOTE** Use locator-based [locator.check([options])](https://playwright.dev/docs/api/class-locator#locator-check) instead.
* Read more about [locators](https://playwright.dev/docs/locators).
Expand Down
4 changes: 4 additions & 0 deletions packages/protocol/src/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2147,6 +2147,7 @@ export interface PageChannel extends PageEventTarget, EventTargetChannel {
stopCSSCoverage(params?: PageStopCSSCoverageParams, progress?: Progress): Promise<PageStopCSSCoverageResult>;
bringToFront(params?: PageBringToFrontParams, progress?: Progress): Promise<PageBringToFrontResult>;
pickLocator(params?: PagePickLocatorParams, progress?: Progress): Promise<PagePickLocatorResult>;
cancelPickLocator(params?: PageCancelPickLocatorParams, progress?: Progress): Promise<PageCancelPickLocatorResult>;
videoStart(params: PageVideoStartParams, progress?: Progress): Promise<PageVideoStartResult>;
videoStop(params?: PageVideoStopParams, progress?: Progress): Promise<PageVideoStopResult>;
updateSubscription(params: PageUpdateSubscriptionParams, progress?: Progress): Promise<PageUpdateSubscriptionResult>;
Expand Down Expand Up @@ -2658,6 +2659,9 @@ export type PagePickLocatorOptions = {};
export type PagePickLocatorResult = {
selector: string,
};
export type PageCancelPickLocatorParams = {};
export type PageCancelPickLocatorOptions = {};
export type PageCancelPickLocatorResult = void;
export type PageVideoStartParams = {
size?: {
width: number,
Expand Down
5 changes: 5 additions & 0 deletions packages/protocol/src/protocol.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2066,9 +2066,14 @@ Page:

pickLocator:
title: Pick locator
group: configuration
returns:
selector: string

cancelPickLocator:
title: Cancel pick locator
group: configuration

videoStart:
title: Start video recording
group: configuration
Expand Down
Loading
Loading