Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(trace-viewer): add action filtering functionality (#39412)
Emanuele Minotto1ad1f55faad4
diff --git a/docs/src/trace-viewer.md b/docs/src/trace-viewer.mdindex ed5a855e5c..2192b98d60 100644--- a/docs/src/trace-viewer.md+++ b/docs/src/trace-viewer.md@@ -686,7 +686,9 @@ public class WithTestNameAttribute : BeforeAfterTestAttribute## Trace Viewer features### Actions-In the Actions tab you can see what locator was used for every action and how long each one took to run. Hover over each action of your test and visually see the change in the DOM snapshot. Go back and forward in time and click an action to inspect and debug. Use the Before and After tabs to visually see what happened before and after the action.+In the Actions tab you can see what locator was used for every action and how long each one took to run. Use the **Filter actions** search field at the top of the list to filter the action hierarchy by text; only actions whose title matches the search (and their parent actions) are shown. Clear the filter to show all actions again; expanded nodes are preserved when the filter is removed.++Hover over each action of your test and visually see the change in the DOM snapshot. Go back and forward in time and click an action to inspect and debug. Use the Before and After tabs to visually see what happened before and after the action.<img src="https://github.com/microsoft/playwright/assets/13063165/948b65cd-f0fd-4c7f-8e53-2c632b5a07f1" alt="actions tab in trace viewer" width="3598" height="2218" />diff --git a/packages/trace-viewer/src/ui/actionList.tsx b/packages/trace-viewer/src/ui/actionList.tsxindex 08c2977169..8ca6955798 100644--- a/packages/trace-viewer/src/ui/actionList.tsx+++ b/packages/trace-viewer/src/ui/actionList.tsx@@ -29,19 +29,106 @@ import { testStatusIcon } from './testUtils';import { methodMetainfo } from '@isomorphic/protocolMetainfo';import { formatProtocolParam } from '@isomorphic/protocolFormatter';+function getTitleFormat(action: ActionTraceEvent): string {+ const metaTitle = methodMetainfo.get(`${action.class}.${action.method}`)?.title;+ const raw = action.title ?? metaTitle ?? action.method ?? '';+ return String(raw).replace(/\n/g, ' ');+}++function expandPlaceholders(format: string, params: Record<string, any>): string {+ return format.replace(/\{([^}]+)\}/g, (fullMatch, paramKey) => {+ const value = formatProtocolParam(params, paramKey);+ return value === undefined ? fullMatch : String(value);+ });+}++export function getActionSearchText(action: ActionTraceEvent): string {+ try {+ const titleFormat = getTitleFormat(action);+ return expandPlaceholders(titleFormat, action.params ?? {});+ } catch {+ return String(action.title ?? action.method ?? '');+ }+}++function computeVisibleCallIds(+ actionFilterText: string | undefined,+ itemMap: Map<string, ActionTreeItem>,+): Set<string> | null {+ const query = actionFilterText?.trim().toLowerCase();+ if (!query)+ return null;++ const matchingCallIds = new Set<string>();+ for (const item of itemMap.values()) {+ const callId = item.action.callId;+ if (!callId)+ continue;++ const searchText = getActionSearchText(item.action).toLowerCase();+ if (searchText.includes(query))+ matchingCallIds.add(callId);+ }++ const visibleCallIds = new Set<string>();++ const addAncestors = (item: ActionTreeItem | undefined) => {+ if (!item)+ return;++ const callId = item.action.callId;+ if (callId && visibleCallIds.has(callId))+ return;++ if (callId)+ visibleCallIds.add(callId);++ if (item.parent)+ addAncestors(item.parent);+ };++ for (const callId of matchingCallIds)+ addAncestors(itemMap.get(callId));++ for (const callId of matchingCallIds)+ visibleCallIds.add(callId);++ return visibleCallIds;+}++function expandTreeForCallIds(+ callIdsToExpand: Set<string>,+ itemMap: Map<string, ActionTreeItem>,+ previousState: TreeState,+): TreeState {+ const expandedItems = new Map(previousState.expandedItems);++ for (const callId of callIdsToExpand) {+ const item = itemMap.get(callId);+ if (!item)+ continue;++ for (let parent: ActionTreeItem | undefined = item.parent; parent && parent.action.callId; parent = parent.parent)+ expandedItems.set(parent.action.callId, true);+ }++ return { ...previousState, expandedItems };+}+export interface ActionListProps {actions: ActionTraceEventInContext[],selectedAction: ActionTraceEventInContext | undefined,selectedTime: Boundaries | undefined,setSelectedTime: (time: Boundaries | undefined) => void,treeState: TreeState,- setTreeState: (treeState: TreeState) => void,+ setTreeState: React.Dispatch<React.SetStateAction<TreeState>>,sdkLanguage: Language | undefined;onSelected?: (action: ActionTraceEventInContext) => void,onHighlighted?: (action: ActionTraceEventInContext | undefined) => void,revealConsole?: () => void,revealActionAttachment?(callId: string): void,isLive?: boolean,+ actionFilterText?: string,}const ActionTreeView = TreeView<ActionTreeItem>;@@ -59,6 +146,7 @@ export const ActionList: React.FC<ActionListProps> = ({revealConsole,revealActionAttachment,isLive,+ actionFilterText,}) => {const { rootItem, itemMap } = React.useMemo(() => buildActionTree(actions), [actions]);@@ -67,6 +155,27 @@ export const ActionList: React.FC<ActionListProps> = ({return { selectedItem };}, [itemMap, selectedAction]);+ const visibleCallIds = React.useMemo(() => {+ return computeVisibleCallIds(actionFilterText, itemMap);+ }, [itemMap, actionFilterText]);++ const prevVisibleCallIdsRef = React.useRef<Set<string> | null>(null);+ React.useEffect(() => {+ if (visibleCallIds) {+ prevVisibleCallIdsRef.current = visibleCallIds;+ return;+ }++ const previousVisibleCallIds = prevVisibleCallIdsRef.current;+ if (!previousVisibleCallIds)+ return;++ prevVisibleCallIdsRef.current = null;+ setTreeState(previousState =>+ expandTreeForCallIds(previousVisibleCallIds, itemMap, previousState),+ );+ }, [visibleCallIds, itemMap, setTreeState]);+const isError = React.useCallback((item: ActionTreeItem) => {return !!item.action.error?.message;}, []);@@ -81,8 +190,13 @@ export const ActionList: React.FC<ActionListProps> = ({}, [isLive, revealConsole, revealActionAttachment, sdkLanguage]);const isVisible = React.useCallback((item: ActionTreeItem) => {- return !selectedTime || !item.action || (item.action.startTime <= selectedTime.maximum && item.action.endTime >= selectedTime.minimum);- }, [selectedTime]);+ const timeVisible = !selectedTime || !item.action || (item.action.startTime <= selectedTime.maximum && item.action.endTime >= selectedTime.minimum);+ if (!timeVisible)+ return false;+ if (!visibleCallIds || !item.action.callId)+ return true;+ return visibleCallIds.has(item.action.callId);+ }, [selectedTime, visibleCallIds]);const onSelectedAction = React.useCallback((item: ActionTreeItem) => {onSelected?.(item.action);@@ -92,7 +206,7 @@ export const ActionList: React.FC<ActionListProps> = ({onHighlighted?.(item?.action);}, [onHighlighted]);- return <div className='vbox'>+ return <div className='vbox action-list-container'>{selectedTime && <div className='action-list-show-all' onClick={() => setSelectedTime(undefined)}><span className='codicon codicon-triangle-left'></span>Show all</div>}<ActionTreeViewname='actions'@@ -106,6 +220,7 @@ export const ActionList: React.FC<ActionListProps> = ({isError={isError}isVisible={isVisible}render={render}+ autoExpandDepth={actionFilterText?.trim() ? 5 : 0}/></div>;};diff --git a/packages/trace-viewer/src/ui/workbench.css b/packages/trace-viewer/src/ui/workbench.cssindex 03084c7c11..b557d7aa03 100644--- a/packages/trace-viewer/src/ui/workbench.css+++ b/packages/trace-viewer/src/ui/workbench.css@@ -44,3 +44,32 @@user-select: none;color: var(--vscode-editorCodeLens-foreground);}++.workbench-action-filter {+ flex: none;+ padding: 4px;+ border-bottom: 1px solid var(--vscode-panel-border);+}++.workbench-action-filter input[type=search] {+ width: 100%;+ box-sizing: border-box;+ padding: 4px 8px;+ line-height: 20px;+ outline: none;+ border: 1px solid var(--vscode-input-border);+ border-radius: 2px;+ color: var(--vscode-input-foreground);+ background-color: var(--vscode-input-background);+}++.workbench-action-filter input[type=search]:focus {+ border-color: var(--vscode-focusBorder);+}++.action-list-container {+ min-height: 0;+ flex: auto;+ display: flex;+ flex-direction: column;+}diff --git a/packages/trace-viewer/src/ui/workbench.tsx b/packages/trace-viewer/src/ui/workbench.tsxindex 98175a3d11..59ca7c7819 100644--- a/packages/trace-viewer/src/ui/workbench.tsx+++ b/packages/trace-viewer/src/ui/workbench.tsx@@ -88,6 +88,7 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partitionconst [revealedAttachmentCallId, setRevealedAttachmentCallId] = usePartitionedState<{ callId: string } | undefined>('revealedAttachmentCallId');const [highlightedResourceKey, setHighlightedResourceKey] = usePartitionedState<string | undefined>('highlightedResourceKey');const [treeState, setTreeState] = usePartitionedState<TreeState>('treeState', { expandedItems: new Map() });+ const [actionFilterText, setActionFilterText] = React.useState('');togglePartition(partition);@@ -321,6 +322,16 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partition<div className='spacer'></div><div className='workbench-run-duration'>{time ? msToString(time) : ''}</div></div>}+ <div className='workbench-action-filter'>+ <input+ type='search'+ placeholder='Filter actions'+ aria-label='Filter actions'+ spellCheck={false}+ value={actionFilterText}+ onChange={e => setActionFilterText(e.target.value)}+ />+ </div><ActionListsdkLanguage={sdkLanguage}actions={actions || []}@@ -334,6 +345,7 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partitionrevealActionAttachment={revealActionAttachment}revealConsole={() => selectPropertiesTab('console')}isLive={isLive}+ actionFilterText={actionFilterText}/></div>};diff --git a/tests/library/trace-viewer.spec.ts b/tests/library/trace-viewer.spec.tsindex c09c020cd5..d3d12eb247 100644--- a/tests/library/trace-viewer.spec.ts+++ b/tests/library/trace-viewer.spec.ts@@ -191,6 +191,20 @@ test('should open simple trace viewer', async ({ showTraceViewer }) => {]);});+test('should filter actions by text', async ({ showTraceViewer }) => {+ const traceViewer = await showTraceViewer(traceFile);+ const filterInput = traceViewer.page.getByRole('searchbox', { name: 'Filter actions' });+ await expect(filterInput).toBeVisible();++ const fullCount = await traceViewer.actionTitles.count();+ await filterInput.fill('Click');+ await expect(traceViewer.actionTitles.filter({ hasText: 'Click' }).first()).toBeVisible();+ expect(await traceViewer.actionTitles.count()).toBeLessThan(fullCount);++ await filterInput.fill('');+ await expect(traceViewer.actionTitles).toHaveCount(fullCount);+});+test('should open uncompressed trace directory', async ({ showTraceViewer }) => {const traceDir = test.info().outputPath('unzipped-trace');await extractZip(traceFile, { dir: traceDir });diff --git a/tests/playwright-test/ui-mode-test-filters.spec.ts b/tests/playwright-test/ui-mode-test-filters.spec.tsindex dd59c334b2..0f9a1b8737 100644--- a/tests/playwright-test/ui-mode-test-filters.spec.ts+++ b/tests/playwright-test/ui-mode-test-filters.spec.ts@@ -37,7 +37,7 @@ const basicTestTree = {test('should filter by title', async ({ runUITest }) => {const { page } = await runUITest(basicTestTree);- await page.getByPlaceholder('Filter').fill('inner');+ await page.getByPlaceholder('Filter (e.g. text, @tag)').fill('inner');await expect.poll(dumpTestTree(page)).toBe(`▼ ◯ a.test.ts▼ ◯ suite@@ -48,7 +48,7 @@ test('should filter by title', async ({ runUITest }) => {test('should filter by explicit tags', async ({ runUITest }) => {const { page } = await runUITest(basicTestTree);- await page.getByPlaceholder('Filter').fill('@smoke inner');+ await page.getByPlaceholder('Filter (e.g. text, @tag)').fill('@smoke inner');await expect.poll(dumpTestTree(page)).toBe(`▼ ◯ a.test.ts▼ ◯ suite@@ -65,7 +65,7 @@ test('should display native tags and filter by them on click', async ({ runUITes`,});await page.locator('.ui-mode-tree-item-title').getByText('smoke').click();- await expect(page.getByPlaceholder('Filter')).toHaveValue('@smoke');+ await expect(page.getByPlaceholder('Filter (e.g. text, @tag)')).toHaveValue('@smoke');await expect.poll(dumpTestTree(page)).toBe(`▼ ◯ a.test.ts◯ pwt