Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore: merge contextRecorder into recorder (#36487)

Pavel Feldmancdd1f752368a
diff --git a/packages/playwright-core/src/server/DEPS.list b/packages/playwright-core/src/server/DEPS.list
index 724f460fbf..19cdfd5eec 100644
--- a/packages/playwright-core/src/server/DEPS.list
+++ b/packages/playwright-core/src/server/DEPS.list
@@ -6,6 +6,8 @@
../utilsBundle.ts
../zipBundle.ts
./
+./codegen/language.ts
+./codegen/languages.ts
./isomorphic/
./har/
./recorder/
diff --git a/packages/playwright-core/src/server/recorder.ts b/packages/playwright-core/src/server/recorder.ts
index 9e015163e8..52a2fd94c1 100644
--- a/packages/playwright-core/src/server/recorder.ts
+++ b/packages/playwright-core/src/server/recorder.ts
@@ -19,29 +19,42 @@ import fs from 'fs';
import { isUnderTest } from '../utils';
import { BrowserContext } from './browserContext';
import { Debugger } from './debugger';
-import { ContextRecorder, generateFrameSelector } from './recorder/contextRecorder';
-import { buildFullSelector, metadataToCallLog } from './recorder/recorderUtils';
+import { buildFullSelector, generateFrameSelector, metadataToCallLog } from './recorder/recorderUtils';
import { locatorOrSelectorAsSelector } from '../utils/isomorphic/locatorParser';
import { stringifySelector } from '../utils/isomorphic/selectorParser';
import { ProgressController } from './progress';
import { serverSideCallMetadata } from './instrumentation';
-
-import type { Language } from './codegen/types';
-import type { Frame } from './frames';
+import { RecorderSignalProcessor } from './recorder/recorderSignalProcessor';
+import * as rawRecorderSource from './../generated/pollingRecorderSource';
+import { eventsHelper, monotonicTime } from './../utils';
+import { languageSet } from './codegen/languages';
+import { Frame } from './frames';
+import { Page } from './page';
+import { ThrottledFile } from './recorder/throttledFile';
+import { generateCode } from './codegen/language';
+import { performAction } from './recorder/recorderRunner';
+import { collapseActions } from './recorder/recorderUtils';
+
+
+import type { Language, LanguageGenerator, LanguageGeneratorOptions } from './codegen/types';
import type { CallMetadata, InstrumentationListener, SdkObject } from './instrumentation';
-import type { Page } from './page';
import type { IRecorder, IRecorderApp, IRecorderAppFactory } from './recorder/recorderFrontend';
import type { Point } from '../utils/isomorphic/types';
import type { AriaTemplateNode } from '@isomorphic/ariaSnapshot';
import type * as channels from '@protocol/channels';
import type * as actions from '@recorder/actions';
import type { CallLog, CallLogStatus, ElementInfo, EventData, Mode, OverlayState, Source, UIState } from '@recorder/recorderTypes';
+import type { RegisteredListener } from '../utils';
+import type { Signal } from '../../../recorder/src/actions';
const recorderSymbol = Symbol('recorderSymbol');
+type BindingSource = { frame: Frame, page: Page };
+
export class Recorder implements InstrumentationListener, IRecorder {
readonly handleSIGINT: boolean | undefined;
private _context: BrowserContext;
+ private _params: channels.BrowserContextEnableRecorderParams;
private _mode: Mode;
private _highlightedElement: { selector?: string, ariaTemplate?: AriaTemplateNode } = {};
private _overlayState: OverlayState = { offsetX: 0 };
@@ -50,11 +63,22 @@ export class Recorder implements InstrumentationListener, IRecorder {
private _recorderSources: Source[] = [];
private _userSources = new Map<string, Source>();
private _debugger: Debugger;
- private _contextRecorder: ContextRecorder;
private _omitCallTracking = false;
private _currentLanguage: Language;
private _recorderMode: 'record' | 'perform';
+ private _signalProcessor: RecorderSignalProcessor;
+ private _pageAliases = new Map<Page, string>();
+ private _lastPopupOrdinal = 0;
+ private _lastDialogOrdinal = -1;
+ private _lastDownloadOrdinal = -1;
+ private _throttledOutputFile: ThrottledFile | null = null;
+ private _orderedLanguages: LanguageGenerator[] = [];
+ private _listeners: RegisteredListener[] = [];
+ private _actions: actions.ActionInContext[] = [];
+ private _languageGeneratorOptions: LanguageGeneratorOptions;
+ private _enabled: boolean = false;
+
static async showInspector(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams, recorderAppFactory: IRecorderAppFactory) {
if (isUnderTest())
params.language = process.env.TEST_INSPECTOR_LANGUAGE;
@@ -82,15 +106,52 @@ export class Recorder implements InstrumentationListener, IRecorder {
}
constructor(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams) {
+ this._context = context;
+ this._params = params;
this._mode = params.mode || 'none';
this._recorderMode = params.recorderMode ?? 'perform';
this.handleSIGINT = params.handleSIGINT;
- this._contextRecorder = new ContextRecorder(context, params, {});
- this._context = context;
+
+ // Make a copy of options to modify them later.
+ this._languageGeneratorOptions = {
+ browserName: context._browser.options.name,
+ launchOptions: { headless: false, ...params.launchOptions, tracesDir: undefined },
+ contextOptions: { ...params.contextOptions },
+ deviceName: params.device,
+ saveStorage: params.saveStorage,
+ };
+
+ this._signalProcessor = new RecorderSignalProcessor();
+ this._signalProcessor.on('action', (actionInContext: actions.ActionInContext) => {
+ if (!this._enabled)
+ return;
+ this._actions.push(actionInContext);
+ this._updateActions();
+ });
+ this._signalProcessor.on('signal', (signal: Signal) => {
+ if (!this._enabled)
+ return;
+ const lastAction = this._actions[this._actions.length - 1];
+ if (lastAction)
+ lastAction.action.signals.push(signal);
+ this._updateActions();
+ });
+
+ context.on(BrowserContext.Events.BeforeClose, () => {
+ this._throttledOutputFile?.flush();
+ });
+ this._listeners.push(eventsHelper.addEventListener(process, 'exit', () => {
+ this._throttledOutputFile?.flush();
+ }));
+
+ const language = params.language || context._browser.sdkLanguage();
+ this._innerSetOutput(language, params.outputFile);
+ this._setEnabled(params.mode === 'recording');
+
this._omitCallTracking = !!params.omitCallTracking;
this._debugger = context.debugger();
context.instrumentation.addListener(this, context);
- this._currentLanguage = this._contextRecorder.languageName();
+ this._currentLanguage = this._languageName();
if (isUnderTest()) {
// Most of our tests put elements at the top left, so get out of the way.
@@ -121,7 +182,7 @@ export class Recorder implements InstrumentationListener, IRecorder {
return;
}
if (data.event === 'fileChanged') {
- this._currentLanguage = this._contextRecorder.languageName(data.params.file);
+ this._currentLanguage = this._languageName(data.params.file);
this._refreshOverlay();
return;
}
@@ -134,11 +195,7 @@ export class Recorder implements InstrumentationListener, IRecorder {
return;
}
if (data.event === 'clear') {
- this._contextRecorder.clearScript();
- return;
- }
- if (data.event === 'runTask') {
- this._contextRecorder.runTask(data.params.task);
+ this._clearScript();
return;
}
});
@@ -150,18 +207,11 @@ export class Recorder implements InstrumentationListener, IRecorder {
]);
this._context.once(BrowserContext.Events.Close, () => {
- this._contextRecorder.dispose();
+ eventsHelper.removeEventListeners(this._listeners);
this._context.instrumentation.removeListener(this);
this._recorderApp?.close().catch(() => {});
});
- this._contextRecorder.on(ContextRecorder.Events.Change, (data: { sources: Source[], actions: actions.ActionInContext[] }) => {
- this._recorderSources = data.sources;
- recorderApp.setActions(data.actions, data.sources);
- recorderApp.setRunningFile(undefined);
- this._pushAllSources();
- });
-
const controller = new ProgressController(serverSideCallMetadata(), this._context);
await controller.run(async progress => {
await this._context.exposeBinding(progress, '__pw_recorderState', false, async source => {
@@ -184,7 +234,7 @@ export class Recorder implements InstrumentationListener, IRecorder {
actionSelector,
ariaTemplate: this._highlightedElement.ariaTemplate,
language: this._currentLanguage,
- testIdAttributeName: this._contextRecorder.testIdAttributeName(),
+ testIdAttributeName: this._testIdAttributeName(),
overlay: this._overlayState,
};
return uiState;
@@ -210,7 +260,26 @@ export class Recorder implements InstrumentationListener, IRecorder {
await this._context.exposeBinding(progress, '__pw_resume', false, () => {
this._debugger.resume(false);
});
- await this._contextRecorder.install(progress);
+
+ this._context.on(BrowserContext.Events.Page, (page: Page) => this._onPage(page));
+ for (const page of this._context.pages())
+ this._onPage(page);
+ this._context.dialogManager.addDialogHandler(dialog => {
+ this._onDialog(dialog.page());
+ // Not handling the dialog, let it automatically close.
+ return false;
+ });
+
+ // Input actions that potentially lead to navigation are intercepted on the page and are
+ // performed by the Playwright.
+ await this._context.exposeBinding(progress, '__pw_recorderPerformAction', false,
+ (source: BindingSource, action: actions.PerformOnRecordAction) => this._performAction(source.frame, action));
+
+ // Other non-essential actions are simply being recorded.
+ await this._context.exposeBinding(progress, '__pw_recorderRecordAction', false,
+ (source: BindingSource, action: actions.Action) => this._recordAction(source.frame, action));
+
+ await this._context.extendInjectedScript(rawRecorderSource.source);
});
if (this._debugger.isPaused())
@@ -220,7 +289,7 @@ export class Recorder implements InstrumentationListener, IRecorder {
(this._context as any).recorderAppForTest = this._recorderApp;
}
- _pausedStateChanged() {
+ private _pausedStateChanged() {
// If we are called upon page.pause, we don't have metadatas, populate them.
for (const { metadata, sdkObject } of this._debugger.pausedDetails()) {
if (!this._currentCallsMetadata.has(metadata))
@@ -237,7 +306,7 @@ export class Recorder implements InstrumentationListener, IRecorder {
this._highlightedElement = {};
this._mode = mode;
this._recorderApp?.setMode(this._mode);
- this._contextRecorder.setEnabled(this._isRecording());
+ this._setEnabled(this._isRecording());
this._debugger.setMuted(this._isRecording());
if (this._mode !== 'none' && this._mode !== 'standby' && this._context.pages().length === 1)
this._context.pages()[0].bringToFront().catch(() => {});
@@ -293,7 +362,18 @@ export class Recorder implements InstrumentationListener, IRecorder {
}
setOutput(codegenId: string, outputFile: string | undefined) {
- this._contextRecorder.setOutput(codegenId, outputFile);
+ this._innerSetOutput(codegenId, outputFile);
+ this._resetActions();
+ }
+
+ private _innerSetOutput(codegenId: string, outputFile: string | undefined) {
+ const languages = languageSet();
+ const primaryLanguage = [...languages].find(l => l.id === codegenId);
+ if (!primaryLanguage)
+ throw new Error(`\n===============================\nUnsupported language: '${codegenId}'\n===============================\n`);
+ languages.delete(primaryLanguage);
+ this._orderedLanguages = [primaryLanguage, ...languages];
+ this._throttledOutputFile = outputFile ? new ThrottledFile(outputFile) : null;
}
private _refreshOverlay() {
@@ -394,6 +474,162 @@ export class Recorder implements InstrumentationListener, IRecorder {
return '// No source available';
}
}
+
+ private _resetActions() {
+ this._actions = [];
+ this._updateActions();
+ }
+
+ private _updateActions() {
+ const actions = collapseActions(this._actions);
+ const recorderSources = [];
+ for (const languageGenerator of this._orderedLanguages) {
+ const { header, footer, actionTexts, text } = generateCode(actions, languageGenerator, this._languageGeneratorOptions);
+ const source: Source = {
+ isRecorded: true,
+ label: languageGenerator.name,
+ group: languageGenerator.groupName,
+ id: languageGenerator.id,
+ text,
+ header,
+ footer,
+ actions: actionTexts,
+ language: languageGenerator.highlighter,
+ highlight: []
+ };
+ source.revealLine = text.split('\n').length - 1;
+ recorderSources.push(source);
+ if (languageGenerator === this._orderedLanguages[0])
+ this._throttledOutputFile?.setContent(source.text);
+ }
+
+ this._recorderSources = recorderSources;
+ this._recorderApp?.setActions(actions, recorderSources);
+ this._recorderApp?.setRunningFile(undefined);
+ this._pushAllSources();
+ }
+
+ private _languageName(id?: string): Language {
+ for (const lang of this._orderedLanguages) {
+ if (!id || lang.id === id)
+ return lang.highlighter;
+ }
+ return 'javascript';
+ }
+
+ private _setEnabled(enabled: boolean) {
+ this._enabled = enabled;
+ }
+
+ private async _onPage(page: Page) {
+ // First page is called page, others are called popup1, popup2, etc.
+ const frame = page.mainFrame();
+ page.on('close', () => {
+ this._signalProcessor.addAction({
+ frame: this._describeMainFrame(page),
+ action: {
+ name: 'closePage',
+ signals: [],
+ },
+ startTime: monotonicTime()
+ });
+ this._pageAliases.delete(page);
+ });
+ frame.on(Frame.Events.InternalNavigation, event => {
+ if (event.isPublic)
+ this._onFrameNavigated(frame, page);
+ });
+ page.on(Page.Events.Download, () => this._onDownload(page));
+ const suffix = this._pageAliases.size ? String(++this._lastPopupOrdinal) : '';
+ const pageAlias = 'page' + suffix;
+ this._pageAliases.set(page, pageAlias);
+
+ if (page.opener()) {
+ this._onPopup(page.opener()!, page);
+ } else {
+ this._signalProcessor.addAction({
+ frame: this._describeMainFrame(page),
+ action: {
+ name: 'openPage',
+ url: page.mainFrame().url(),
+ signals: [],
+ },
+ startTime: monotonicTime()
+ });
+ }
+ }
+
+ private _clearScript(): void {
+ this._resetActions();
+ if (this._params.mode === 'recording') {
+ for (const page of this._context.pages())
+ this._onFrameNavigated(page.mainFrame(), page);
+ }
+ }
+
+ private _describeMainFrame(page: Page): actions.FrameDescription {
+ return {
+ pageAlias: this._pageAliases.get(page)!,
+ framePath: [],
+ };
+ }
+
+ private async _describeFrame(frame: Frame): Promise<actions.FrameDescription> {
+ return {
+ pageAlias: this._pageAliases.get(frame._page)!,
+ framePath: await generateFrameSelector(frame),
+ };
+ }
+
+ private _testIdAttributeName(): string {
+ return this._params.testIdAttributeName || this._context.selectors().testIdAttributeName() || 'data-testid';
+ }
+
+ private async _createActionInContext(frame: Frame, action: actions.Action): Promise<actions.ActionInContext> {
+ const frameDescription = await this._describeFrame(frame);
+ const actionInContext: actions.ActionInContext = {
+ frame: frameDescription,
+ action,
+ description: undefined,
+ startTime: monotonicTime()
+ };
+ return actionInContext;
+ }
+
+ private async _performAction(frame: Frame, action: actions.PerformOnRecordAction) {
+ const actionInContext = await this._createActionInContext(frame, action);
+ this._signalProcessor.addAction(actionInContext);
+ if (actionInContext.action.name !== 'openPage' && actionInContext.action.name !== 'closePage')
+ await performAction(this._pageAliases, actionInContext);
+ actionInContext.endTime = monotonicTime();
+ }
+
+ private async _recordAction(frame: Frame, action: actions.Action) {
+ this._signalProcessor.addAction(await this._createActionInContext(frame, action));
+ }
+
+ private _onFrameNavigated(frame: Frame, page: Page) {
+ const pageAlias = this._pageAliases.get(page);
+ this._signalProcessor.signal(pageAlias!, frame, { name: 'navigation', url: frame.url() });
+ }
+
+ private _onPopup(page: Page, popup: Page) {
+ const pageAlias = this._pageAliases.get(page)!;
+ const popupAlias = this._pageAliases.get(popup)!;
+ this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: 'popup', popupAlias });
+ }
+
+ private _onDownload(page: Page) {
+ const pageAlias = this._pageAliases.get(page)!;
+ ++this._lastDownloadOrdinal;
+ this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: 'download', downloadAlias: this._lastDownloadOrdinal ? String(this._lastDownloadOrdinal) : '' });
+ }
+
+ private _onDialog(page: Page) {
+ const pageAlias = this._pageAliases.get(page)!;
+ ++this._lastDialogOrdinal;
+ this._signalProcessor.signal(pageAlias, page.mainFrame(), { name: 'dialog', dialogAlias: this._lastDialogOrdinal ? String(this._lastDialogOrdinal) : '' });
+ }
}
function isScreenshotCommand(metadata: CallMetadata) {
diff --git a/packages/playwright-core/src/server/recorder/contextRecorder.ts b/packages/playwright-core/src/server/recorder/contextRecorder.ts
deleted file mode 100644
index d00bed9f6e..0000000000
--- a/packages/playwright-core/src/server/recorder/contextRecorder.ts
+++ /dev/null
@@ -1,343 +0,0 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { EventEmitter } from 'events';
-
-import { RecorderSignalProcessor } from './recorderSignalProcessor';
-import * as rawRecorderSource from '../../generated/pollingRecorderSource';
-import { eventsHelper, monotonicTime, quoteCSSAttributeValue } from '../../utils';
-import { raceAgainstDeadline } from '../../utils/isomorphic/timeoutRunner';
-import { BrowserContext } from '../browserContext';
-import { languageSet } from '../codegen/languages';
-import { Frame } from '../frames';
-import { Page } from '../page';
-import { ThrottledFile } from './throttledFile';
-import { generateCode } from '../codegen/language';
-import { performAction } from './recorderRunner';
-import { collapseActions } from './recorderUtils';
-
-import type { RegisteredListener } from '../../utils';
-import type { Language, LanguageGenerator, LanguageGeneratorOptions } from '../codegen/types';
-import type * as channels from '@protocol/channels';
-import type * as actions from '@recorder/actions';
-import type { Source } from '@recorder/recorderTypes';
-import type { Progress } from '@protocol/progress';
-import type { Signal } from '../../../../recorder/src/actions';
-
-type BindingSource = { frame: Frame, page: Page };
-
-export interface ContextRecorderDelegate {
- rewriteActionInContext?(pageAliases: Map<Page, string>, actionInContext: actions.ActionInContext): Promise<void>;
-}
-
-export class ContextRecorder extends EventEmitter {
- static Events = {
- Change: 'change'
- };
-
- private _collection: RecorderSignalProcessor;
- private _pageAliases = new Map<Page, string>();
- private _lastPopupOrdinal = 0;
- private _lastDialogOrdinal = -1;
- private _lastDownloadOrdinal = -1;
- private _context: BrowserContext;
- private _params: channels.BrowserContextEnableRecorderParams;
- private _delegate: ContextRecorderDelegate;
- private _recorderSources: Source[];
- private _throttledOutputFile: ThrottledFile | null = null;
- private _orderedLanguages: LanguageGenerator[] = [];
- private _listeners: RegisteredListener[] = [];
- private _actions: actions.ActionInContext[] = [];
- private _languageGeneratorOptions: LanguageGeneratorOptions;
- private _enabled: boolean = false;
-
- constructor(context: BrowserContext, params: channels.BrowserContextEnableRecorderParams, delegate: ContextRecorderDelegate) {
- super();
- this._context = context;
- this._params = params;
- this._delegate = delegate;
- this._recorderSources = [];
- const language = params.language || context._browser.sdkLanguage();
-
- // Make a copy of options to modify them later.
- this._languageGeneratorOptions = {
- browserName: context._browser.options.name,
- launchOptions: { headless: false, ...params.launchOptions, tracesDir: undefined },
- contextOptions: { ...params.contextOptions },
- deviceName: params.device,
- saveStorage: params.saveStorage,
- };
-
- this._collection = new RecorderSignalProcessor();
- this._collection.on('action', (actionInContext: actions.ActionInContext) => {
- if (!this._enabled)
- return;
- this._actions.push(actionInContext);
- this._updateActions();
- });
- this._collection.on('signal', (signal: Signal) => {
- if (!this._enabled)
- return;
- const lastAction = this._actions[this._actions.length - 1];
- if (lastAction)
- lastAction.action.signals.push(signal);
- this._updateActions();
- });
-
- context.on(BrowserContext.Events.BeforeClose, () => {
- this._throttledOutputFile?.flush();
- });
- this._listeners.push(eventsHelper.addEventListener(process, 'exit', () => {
- this._throttledOutputFile?.flush();
- }));
-
- this.setOutput(language, params.outputFile);
- this.setEnabled(params.mode === 'recording');
- }
-
- private _resetActions() {
- this._actions = [];
- this._updateActions();
- }
-
- private _updateActions() {
- const actions = collapseActions(this._actions);
- this._recorderSources = [];
- for (const languageGenerator of this._orderedLanguages) {
- const { header, footer, actionTexts, text } = generateCode(actions, languageGenerator, this._languageGeneratorOptions);
- const source: Source = {
- isRecorded: true,
- label: languageGenerator.name,
- group: languageGenerator.groupName,
- id: languageGenerator.id,
- text,
- header,
- footer,
- actions: actionTexts,
- language: languageGenerator.highlighter,
- highlight: []
- };
- source.revealLine = text.split('\n').length - 1;
- this._recorderSources.push(source);
- if (languageGenerator === this._orderedLanguages[0])
- this._throttledOutputFile?.setContent(source.text);
- }
- this.emit(ContextRecorder.Events.Change, {
- sources: this._recorderSources,
- actions
- });
- }
-
- setOutput(codegenId: string, outputFile?: string) {
- const languages = languageSet();
- const primaryLanguage = [...languages].find(l => l.id === codegenId);
- if (!primaryLanguage)
- throw new Error(`\n===============================\nUnsupported language: '${codegenId}'\n===============================\n`);
- languages.delete(primaryLanguage);
- this._orderedLanguages = [primaryLanguage, ...languages];
- this._throttledOutputFile = outputFile ? new ThrottledFile(outputFile) : null;
- this._resetActions();
- }
-
- languageName(id?: string): Language {
- for (const lang of this._orderedLanguages) {
- if (!id || lang.id === id)
- return lang.highlighter;
- }
- return 'javascript';
- }
-
- async install(progress: Progress) {
- this._context.on(BrowserContext.Events.Page, (page: Page) => this._onPage(page));
- for (const page of this._context.pages())
- this._onPage(page);
- this._context.dialogManager.addDialogHandler(dialog => {
- this._onDialog(dialog.page());
- // Not handling the dialog, let it automatically close.
- return false;
- });
-
- // Input actions that potentially lead to navigation are intercepted on the page and are
- // performed by the Playwright.
- await this._context.exposeBinding(progress, '__pw_recorderPerformAction', false,
- (source: BindingSource, action: actions.PerformOnRecordAction) => this._performAction(source.frame, action));
-
- // Other non-essential actions are simply being recorded.
- await this._context.exposeBinding(progress, '__pw_recorderRecordAction', false,
- (source: BindingSource, action: actions.Action) => this._recordAction(source.frame, action));
-
- await this._context.extendInjectedScript(rawRecorderSource.source);
- }
-
- setEnabled(enabled: boolean) {
- this._enabled = enabled;
- }
-
- dispose() {
- eventsHelper.removeEventListeners(this._listeners);
- }
-
- private async _onPage(page: Page) {
- // First page is called page, others are called popup1, popup2, etc.
- const frame = page.mainFrame();
- page.on('close', () => {
- this._collection.addAction({
- frame: this._describeMainFrame(page),
- action: {
- name: 'closePage',
- signals: [],
- },
- startTime: monotonicTime()
- });
- this._pageAliases.delete(page);
- });
- frame.on(Frame.Events.InternalNavigation, event => {
- if (event.isPublic)
- this._onFrameNavigated(frame, page);
- });
- page.on(Page.Events.Download, () => this._onDownload(page));
- const suffix = this._pageAliases.size ? String(++this._lastPopupOrdinal) : '';
- const pageAlias = 'page' + suffix;
- this._pageAliases.set(page, pageAlias);
-
- if (page.opener()) {
- this._onPopup(page.opener()!, page);
- } else {
- this._collection.addAction({
- frame: this._describeMainFrame(page),
- action: {
- name: 'openPage',
- url: page.mainFrame().url(),
- signals: [],
- },
- startTime: monotonicTime()
- });
- }
- }
-
- clearScript(): void {
- this._resetActions();
- if (this._params.mode === 'recording') {
- for (const page of this._context.pages())
- this._onFrameNavigated(page.mainFrame(), page);
- }
- }
-
- runTask(task: string): void {
- // TODO: implement
- }
-
- private _describeMainFrame(page: Page): actions.FrameDescription {
- return {
- pageAlias: this._pageAliases.get(page)!,
- framePath: [],
- };
- }
-
- private async _describeFrame(frame: Frame): Promise<actions.FrameDescription> {
- return {
- pageAlias: this._pageAliases.get(frame._page)!,
- framePath: await generateFrameSelector(frame),
- };
- }
-
- testIdAttributeName(): string {
- return this._params.testIdAttributeName || this._context.selectors().testIdAttributeName() || 'data-testid';
- }
-
- private async _createActionInContext(frame: Frame, action: actions.Action): Promise<actions.ActionInContext> {
- const frameDescription = await this._describeFrame(frame);
- const actionInContext: actions.ActionInContext = {
- frame: frameDescription,
- action,
- description: undefined,
- startTime: monotonicTime()
- };
- await this._delegate.rewriteActionInContext?.(this._pageAliases, actionInContext);
- return actionInContext;
- }
-
- private async _performAction(frame: Frame, action: actions.PerformOnRecordAction) {
- const actionInContext = await this._createActionInContext(frame, action);
- this._collection.addAction(actionInContext);
- if (actionInContext.action.name !== 'openPage' && actionInContext.action.name !== 'closePage')
- await performAction(this._pageAliases, actionInContext);
- actionInContext.endTime = monotonicTime();
- }
-
- private async _recordAction(frame: Frame, action: actions.Action) {
- this._collection.addAction(await this._createActionInContext(frame, action));
- }
-
- private _onFrameNavigated(frame: Frame, page: Page) {
- const pageAlias = this._pageAliases.get(page);
- this._collection.signal(pageAlias!, frame, { name: 'navigation', url: frame.url() });
- }
-
- private _onPopup(page: Page, popup: Page) {
- const pageAlias = this._pageAliases.get(page)!;
- const popupAlias = this._pageAliases.get(popup)!;
- this._collection.signal(pageAlias, page.mainFrame(), { name: 'popup', popupAlias });
- }
-
- private _onDownload(page: Page) {
- const pageAlias = this._pageAliases.get(page)!;
- ++this._lastDownloadOrdinal;
- this._collection.signal(pageAlias, page.mainFrame(), { name: 'download', downloadAlias: this._lastDownloadOrdinal ? String(this._lastDownloadOrdinal) : '' });
- }
-
- private _onDialog(page: Page) {
- const pageAlias = this._pageAliases.get(page)!;
- ++this._lastDialogOrdinal;
- this._collection.signal(pageAlias, page.mainFrame(), { name: 'dialog', dialogAlias: this._lastDialogOrdinal ? String(this._lastDialogOrdinal) : '' });
- }
-}
-
-export async function generateFrameSelector(frame: Frame): Promise<string[]> {
- const selectorPromises: Promise<string>[] = [];
- while (frame) {
- const parent = frame.parentFrame();
- if (!parent)
- break;
- selectorPromises.push(generateFrameSelectorInParent(parent, frame));
- frame = parent;
- }
- const result = await Promise.all(selectorPromises);
- return result.reverse();
-}
-
-async function generateFrameSelectorInParent(parent: Frame, frame: Frame): Promise<string> {
- const result = await raceAgainstDeadline(async () => {
- try {
- const frameElement = await frame.frameElement();
- if (!frameElement || !parent)
- return;
- const utility = await parent._utilityContext();
- const injected = await utility.injectedScript();
- const selector = await injected.evaluate((injected, element) => {
- return injected.generateSelectorSimple(element as Element);
- }, frameElement);
- return selector;
- } catch (e) {
- }
- }, monotonicTime() + 2000);
- if (!result.timedOut && result.result)
- return result.result;
-
- if (frame.name())
- return `iframe[name=${quoteCSSAttributeValue(frame.name())}]`;
- return `iframe[src=${quoteCSSAttributeValue(frame.url())}]`;
-}
diff --git a/packages/playwright-core/src/server/recorder/recorderUtils.ts b/packages/playwright-core/src/server/recorder/recorderUtils.ts
index 1487ae1c39..7694cb5208 100644
--- a/packages/playwright-core/src/server/recorder/recorderUtils.ts
+++ b/packages/playwright-core/src/server/recorder/recorderUtils.ts
@@ -15,8 +15,10 @@
*/
import { renderTitleForCall } from '../../utils/isomorphic/protocolFormatter';
+import { monotonicTime, quoteCSSAttributeValue } from '../../utils';
+import { raceAgainstDeadline } from '../../utils/isomorphic/timeoutRunner';
+import { Frame } from '../frames';
-import type { Frame } from '../frames';
import type { CallMetadata } from '../instrumentation';
import type { Page } from '../page';
import type * as actions from '@recorder/actions';
@@ -88,3 +90,39 @@ export function collapseActions(actions: actions.ActionInContext[]): actions.Act
}
return result;
}
+
+export async function generateFrameSelector(frame: Frame): Promise<string[]> {
+ const selectorPromises: Promise<string>[] = [];
+ while (frame) {
+ const parent = frame.parentFrame();
+ if (!parent)
+ break;
+ selectorPromises.push(generateFrameSelectorInParent(parent, frame));
+ frame = parent;
+ }
+ const result = await Promise.all(selectorPromises);
+ return result.reverse();
+}
+
+async function generateFrameSelectorInParent(parent: Frame, frame: Frame): Promise<string> {
+ const result = await raceAgainstDeadline(async () => {
+ try {
+ const frameElement = await frame.frameElement();
+ if (!frameElement || !parent)
+ return;
+ const utility = await parent._utilityContext();
+ const injected = await utility.injectedScript();
+ const selector = await injected.evaluate((injected, element) => {
+ return injected.generateSelectorSimple(element as Element);
+ }, frameElement);
+ return selector;
+ } catch (e) {
+ }
+ }, monotonicTime() + 2000);
+ if (!result.timedOut && result.result)
+ return result.result;
+
+ if (frame.name())
+ return `iframe[name=${quoteCSSAttributeValue(frame.name())}]`;
+ return `iframe[src=${quoteCSSAttributeValue(frame.url())}]`;
+}