Skip to content

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

fix(codegen): auto-select the right source (#37004)

Dmitry Gozman68a6b1d863d7
diff --git a/packages/playwright-core/src/server/codegen/languages.ts b/packages/playwright-core/src/server/codegen/languages.ts
index 4eb5beb081..730293396e 100644
--- a/packages/playwright-core/src/server/codegen/languages.ts
+++ b/packages/playwright-core/src/server/codegen/languages.ts
@@ -21,6 +21,8 @@ import { JsonlLanguageGenerator } from './jsonl';
import { PythonLanguageGenerator } from './python';
export function languageSet() {
+ // Note: generators are ordered in the order of preference for each language.
+ // For example, 'playwright-test' comes before 'javascript'.
return new Set([
new JavaScriptLanguageGenerator(/* isPlaywrightTest */true),
new JavaScriptLanguageGenerator(/* isPlaywrightTest */false),
diff --git a/packages/playwright-core/src/server/recorder.ts b/packages/playwright-core/src/server/recorder.ts
index 359583f071..930bb422f9 100644
--- a/packages/playwright-core/src/server/recorder.ts
+++ b/packages/playwright-core/src/server/recorder.ts
@@ -61,7 +61,7 @@ export type RecorderEventMap = {
[RecorderEvent.ModeChanged]: [mode: Mode];
[RecorderEvent.ElementPicked]: [elementInfo: ElementInfo, userGesture?: boolean];
[RecorderEvent.CallLogsUpdated]: [callLogs: CallLog[]];
- [RecorderEvent.UserSourcesChanged]: [sources: Source[]];
+ [RecorderEvent.UserSourcesChanged]: [sources: Source[], pausedSourceId?: string];
[RecorderEvent.ActionAdded]: [action: actions.ActionInContext];
[RecorderEvent.SignalAdded]: [signal: actions.SignalInContext];
[RecorderEvent.PageNavigated]: [url: string];
@@ -305,6 +305,17 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
this._refreshOverlay();
}
+ pausedSourceId() {
+ for (const { metadata } of this._debugger.pausedDetails()) {
+ if (!metadata.location)
+ continue;
+ const source = this._userSources.get(metadata.location.file);
+ if (!source)
+ continue;
+ return source.id;
+ }
+ }
+
userSources() {
return [...this._userSources.values()];
}
@@ -368,7 +379,6 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
private _updateUserSources() {
// Remove old decorations.
- const timestamp = monotonicTime();
for (const source of this._userSources.values()) {
source.highlight = [];
source.revealLine = undefined;
@@ -381,7 +391,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
const { file, line } = metadata.location;
let source = this._userSources.get(file);
if (!source) {
- source = { isPrimary: false, isRecorded: false, label: file, id: file, text: this._readSource(file), highlight: [], language: languageForFile(file), timestamp };
+ source = { isRecorded: false, label: file, id: file, text: this._readSource(file), highlight: [], language: languageForFile(file) };
this._userSources.set(file, source);
}
if (line) {
@@ -390,7 +400,7 @@ export class Recorder extends EventEmitter<RecorderEventMap> implements Instrume
source.revealLine = line;
}
}
- this.emit(RecorderEvent.UserSourcesChanged, this.userSources());
+ this.emit(RecorderEvent.UserSourcesChanged, this.userSources(), this.pausedSourceId());
}
async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata) {
diff --git a/packages/playwright-core/src/server/recorder/recorderApp.ts b/packages/playwright-core/src/server/recorder/recorderApp.ts
index 17508cd039..233260ed98 100644
--- a/packages/playwright-core/src/server/recorder/recorderApp.ts
+++ b/packages/playwright-core/src/server/recorder/recorderApp.ts
@@ -27,7 +27,6 @@ import { languageSet } from '../codegen/languages';
import { collapseActions, shouldMergeAction } from './recorderUtils';
import { generateCode } from '../codegen/language';
import { Recorder, RecorderEvent } from '../recorder';
-import { monotonicTime } from '../../utils/isomorphic/time';
import { BrowserContext } from '../browserContext';
import type { Page } from '../page';
@@ -54,6 +53,7 @@ export class RecorderApp {
private _userSources: Source[] = [];
private _recorderSources: Source[] = [];
private _primaryLanguage: string;
+ private _selectedLanguageId: string;
private constructor(recorder: Recorder, params: RecorderAppParams, page: Page, wsEndpointForTest: string | undefined) {
this._page = page;
@@ -70,7 +70,8 @@ export class RecorderApp {
};
this._throttledOutputFile = params.outputFile ? new ThrottledFile(params.outputFile) : null;
- this._primaryLanguage = process.env.TEST_INSPECTOR_LANGUAGE || params.language || params.sdkLanguage;
+ this._primaryLanguage = process.env.TEST_INSPECTOR_LANGUAGE || params.language || determinePrimaryLanguage(params.sdkLanguage);
+ this._selectedLanguageId = this._primaryLanguage;
}
private async _init(inspectedContext: BrowserContext) {
@@ -114,24 +115,27 @@ export class RecorderApp {
this._onPageNavigated(url);
this._onModeChanged(this._recorder.mode());
this._onPausedStateChanged(this._recorder.paused());
- this._onUserSourcesChanged(this._recorder.userSources());
+ this._updateActions('reveal');
+ // Update paused sources *after* generated ones, to reveal the currently paused source if any.
+ this._onUserSourcesChanged(this._recorder.userSources(), this._recorder.pausedSourceId());
this._onCallLogsUpdated(this._recorder.callLog());
this._wireListeners(this._recorder);
-
- this._updateActions(true);
}
private _handleUIEvent(data: any) {
if (data.event === 'clear') {
this._actions = [];
- this._updateActions();
+ this._updateActions('reveal');
this._recorder.clear();
return;
}
if (data.event === 'fileChanged') {
const source = [...this._recorderSources, ...this._userSources].find(s => s.id === data.params.fileId);
- if (source)
+ if (source) {
+ if (source.isRecorded)
+ this._selectedLanguageId = source.id;
this._recorder.setLanguage(source.language);
+ }
return;
}
if (data.event === 'setMode') {
@@ -248,8 +252,8 @@ export class RecorderApp {
this._onPausedStateChanged(paused);
});
- recorder.on(RecorderEvent.UserSourcesChanged, (sources: Source[]) => {
- this._onUserSourcesChanged(sources);
+ recorder.on(RecorderEvent.UserSourcesChanged, (sources: Source[], pausedSourceId?: string) => {
+ this._onUserSourcesChanged(sources, pausedSourceId);
});
recorder.on(RecorderEvent.ElementPicked, (elementInfo: ElementInfo, userGesture?: boolean) => {
@@ -263,7 +267,7 @@ export class RecorderApp {
private _onActionAdded(action: actions.ActionInContext) {
this._actions.push(action);
- this._updateActions();
+ this._updateActions('reveal');
}
private _onSignalAdded(signal: actions.SignalInContext) {
@@ -296,11 +300,12 @@ export class RecorderApp {
}).toString(), { isFunction: true }, paused).catch(() => {});
}
- private _onUserSourcesChanged(sources: Source[]) {
+ private _onUserSourcesChanged(sources: Source[], pausedSourceId: string | undefined) {
if (!sources.length && !this._userSources.length)
return;
this._userSources = sources;
this._pushAllSources();
+ this._revealSource(pausedSourceId);
}
private _onElementPicked(elementInfo: ElementInfo, userGesture?: boolean) {
@@ -317,23 +322,29 @@ export class RecorderApp {
}).toString(), { isFunction: true }, callLogs).catch(() => {});
}
- private async _pushAllSources() {
+ private _pushAllSources() {
const sources = [...this._userSources, ...this._recorderSources];
this._page.mainFrame().evaluateExpression((({ sources }: { sources: Source[] }) => {
window.playwrightSetSources(sources);
}).toString(), { isFunction: true }, { sources }).catch(() => {});
}
- private _updateActions(initial: boolean = false) {
- const timestamp = initial ? 0 : monotonicTime();
+ private _revealSource(sourceId: string | undefined) {
+ if (!sourceId)
+ return;
+ this._page.mainFrame().evaluateExpression((({ sourceId }: { sourceId: string }) => {
+ window.playwrightSelectSource(sourceId);
+ }).toString(), { isFunction: true }, { sourceId }).catch(() => {});
+ }
+
+ private _updateActions(reveal?: 'reveal') {
const recorderSources = [];
const actions = collapseActions(this._actions);
+ let revealSourceId: string | undefined;
for (const languageGenerator of languageSet()) {
const { header, footer, actionTexts, text } = generateCode(actions, languageGenerator, this._languageGeneratorOptions);
const source: Source = {
- isPrimary: languageGenerator.id === this._primaryLanguage,
- timestamp,
isRecorded: true,
label: languageGenerator.name,
group: languageGenerator.groupName,
@@ -349,11 +360,23 @@ export class RecorderApp {
recorderSources.push(source);
if (languageGenerator.id === this._primaryLanguage)
this._throttledOutputFile?.setContent(source.text);
+ if (reveal === 'reveal' && source.id === this._selectedLanguageId)
+ revealSourceId = source.id;
}
this._recorderSources = recorderSources;
this._pushAllSources();
+ this._revealSource(revealSourceId);
+ }
+}
+
+// For example, if the SDK language is 'javascript', we return 'playwright-test' as the primary language.
+function determinePrimaryLanguage(sdkLanguage: Language): string {
+ for (const language of languageSet()) {
+ if (language.highlighter === sdkLanguage)
+ return language.id;
}
+ return sdkLanguage;
}
export class ProgrammaticRecorderApp {
diff --git a/packages/recorder/src/recorder.tsx b/packages/recorder/src/recorder.tsx
index 2630357086..fa8b6c09d9 100644
--- a/packages/recorder/src/recorder.tsx
+++ b/packages/recorder/src/recorder.tsx
@@ -48,22 +48,7 @@ export const Recorder: React.FC<RecorderProps> = ({
const [selectedTab, setSelectedTab] = useSetting<string>('recorderPropertiesTab', 'log');
const [ariaSnapshot, setAriaSnapshot] = React.useState<string | undefined>();
const [ariaSnapshotErrors, setAriaSnapshotErrors] = React.useState<SourceHighlight[]>();
-
- React.useEffect(() => {
- if (!sources.length)
- return;
- // When no selected file id present, pick the primary source (target language).
- let fileId = selectedFileId ?? sources.find(s => s.isPrimary)?.id;
- const selectedSource = sources.find(s => s.id === fileId);
- const newestSource = sources.sort((a, b) => b.timestamp - a.timestamp)[0];
- if (!selectedSource || newestSource.isRecorded !== selectedSource.isRecorded) {
- // When debugger kicks in, or recording is resumed switch the selection to the newest source.
- fileId = newestSource.id;
- }
- // If changes above force the selection to change, update the state.
- if (fileId !== selectedFileId)
- setSelectedFileId(fileId);
- }, [sources, selectedFileId]);
+ window.playwrightSelectSource = selectedSourceId => setSelectedFileId(selectedSourceId);
const source = React.useMemo(() => {
const source = sources.find(s => s.id === selectedFileId);
diff --git a/packages/recorder/src/recorderTypes.d.ts b/packages/recorder/src/recorderTypes.d.ts
index 9d46447c17..2f5b0ffe4e 100644
--- a/packages/recorder/src/recorderTypes.d.ts
+++ b/packages/recorder/src/recorderTypes.d.ts
@@ -83,14 +83,12 @@ export type SourceHighlight = {
};
export type Source = {
- isPrimary: boolean;
isRecorded: boolean;
id: string;
label: string;
text: string;
language: Language;
highlight: SourceHighlight[];
- timestamp: number;
revealLine?: number;
// used to group the language generators
group?: string;
@@ -104,6 +102,7 @@ declare global {
playwrightSetMode: (mode: Mode) => void;
playwrightSetPaused: (paused: boolean) => void;
playwrightSetSources: (sources: Source[]) => void;
+ playwrightSelectSource: (sourceId: string) => void;
playwrightSetPageURL: (url: string | undefined) => void;
playwrightSetOverlayVisible: (visible: boolean) => void;
playwrightUpdateLogs: (callLogs: CallLog[]) => void;
diff --git a/packages/web/src/components/sourceChooser.tsx b/packages/web/src/components/sourceChooser.tsx
index 12b127df6c..091dce8f98 100644
--- a/packages/web/src/components/sourceChooser.tsx
+++ b/packages/web/src/components/sourceChooser.tsx
@@ -53,8 +53,6 @@ function renderSourceOptions(sources: Source[]): React.ReactNode {
export function emptySource(): Source {
return {
id: 'default',
- timestamp: 0,
- isPrimary: false,
isRecorded: false,
text: '',
language: 'javascript',
diff --git a/tests/library/inspector/pause-helper.ts b/tests/library/inspector/pause-helper.ts
new file mode 100644
index 0000000000..5d1626b92a
--- /dev/null
+++ b/tests/library/inspector/pause-helper.ts
@@ -0,0 +1,21 @@
+/**
+ * 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 type { Page } from 'playwright-core';
+
+export async function pauseHelper(page: Page) {
+ await page.setContent('<div>here we go</div>');
+}
diff --git a/tests/library/inspector/pause.spec.ts b/tests/library/inspector/pause.spec.ts
index c4c92d84ee..550fd5fa8d 100644
--- a/tests/library/inspector/pause.spec.ts
+++ b/tests/library/inspector/pause.spec.ts
@@ -19,6 +19,7 @@ import { test as it, expect, Recorder } from './inspectorTest';
import { waitForTestLog } from '../../config/utils';
import { roundBox } from '../../page/pageTest';
import type { BoundingBox } from '../../page/pageTest';
+import { pauseHelper } from './pause-helper';
it('should resume when closing inspector', async ({ page, recorderPageGetter, closeRecorder, mode }) => {
it.skip(mode !== 'default');
@@ -106,11 +107,16 @@ it.describe('pause', () => {
const scriptPromise = (async () => {
// @ts-ignore
await page.pause({ __testHookKeepTestTimeout: true });
+ await pauseHelper(page);
})();
const recorderPage = await recorderPageGetter();
await expect(recorderPage.getByRole('combobox', { name: 'Source chooser' })).toHaveValue(/pause\.spec\.ts/);
- const source = await recorderPage.textContent('.source-line-paused');
- expect(source).toContain('page.pause({ __testHookKeepTestTimeout: true })');
+ await expect(recorderPage.locator('.source-line-paused')).toContainText('page.pause({ __testHookKeepTestTimeout: true })');
+
+ await recorderPage.click('[title="Step over (F10)"]');
+ await expect(recorderPage.getByRole('combobox', { name: 'Source chooser' })).toHaveValue(/pause-helper\.ts/);
+ await expect(recorderPage.locator('.source-line-paused')).toContainText('page.setContent(\'<div>here we go</div>\')');
+
await recorderPage.click('[title="Resume (F8)"]');
await scriptPromise;
});