Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(trace-viewer): embedded mode support PoC #30885

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
7 changes: 5 additions & 2 deletions packages/playwright-core/src/cli/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type { Command } from '../utilsBundle';
import { program } from '../utilsBundle';
export { program } from '../utilsBundle';
import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver';
import { runTraceInBrowser, runTraceViewerApp } from '../server/trace/viewer/traceViewer';
import { runTraceInBrowser, runTraceViewerApp, runTraceViewerServer } from '../server/trace/viewer/traceViewer';
import type { TraceViewerServerOptions } from '../server/trace/viewer/traceViewer';
import * as playwright from '../..';
import type { BrowserContext } from '../client/browserContext';
Expand Down Expand Up @@ -296,6 +296,7 @@ program
.option('-h, --host <host>', 'Host to serve trace on; specifying this option opens trace in a browser tab')
.option('-p, --port <port>', 'Port to serve trace on, 0 for any free port; specifying this option opens trace in a browser tab')
.option('--stdin', 'Accept trace URLs over stdin to update the viewer')
.option('--server-only', 'Run server only')
.description('show trace viewer')
.action(function(traces, options) {
if (options.browser === 'cr')
Expand All @@ -311,7 +312,9 @@ program
isServer: !!options.stdin,
};

if (options.port !== undefined || options.host !== undefined)
if (options.serverOnly)
runTraceViewerServer(traces, openOptions).catch(logErrorAndExit);
else if (options.port !== undefined || options.host !== undefined)
runTraceInBrowser(traces, openOptions).catch(logErrorAndExit);
else
runTraceViewerApp(traces, options.browser, openOptions, true).catch(logErrorAndExit);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,15 @@ export async function installRootRedirect(server: HttpServer, traceUrls: string[
});
}

export async function runTraceViewerServer(traceUrls: string[], options: TraceViewerServerOptions & { headless?: boolean }, exitOnClose?: boolean) {
ruifigueira marked this conversation as resolved.
Show resolved Hide resolved
validateTraceUrls(traceUrls);
const server = await startTraceViewerServer(options);
await installRootRedirect(server, traceUrls, { ...options, webApp: 'embedded.html' });
const url = server.urlPrefix('human-readable').replace('0.0.0.0', 'localhost');
process.stdout.write(url + '\n');
return server;
}

export async function runTraceViewerApp(traceUrls: string[], browserName: string, options: TraceViewerServerOptions & { headless?: boolean }, exitOnClose?: boolean) {
validateTraceUrls(traceUrls);
const server = await startTraceViewerServer(options);
Expand Down
27 changes: 27 additions & 0 deletions packages/trace-viewer/embedded.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!--
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.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Playwright Trace Viewer for VS Code</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/embedded.tsx"></script>
</body>
</html>
77 changes: 77 additions & 0 deletions packages/trace-viewer/src/embedded.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* 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 '@web/common.css';
import { applyTheme, currentTheme, toggleTheme } from '@web/theme';
import '@web/third_party/vscode/codicon.css';
import React from 'react';
import * as ReactDOM from 'react-dom';
import { WorkbenchLoader } from './ui/workbenchLoader';
import { setPopoutFunction } from './ui/popout';

(async () => {
applyTheme();

// must run before awaits
window.addEventListener('message', ({ data }) => {
if (!data.theme)
return;
if (currentTheme() !== data.theme)
toggleTheme();
});
// workaround to send keystrokes back to vscode webview to keep triggering key bindings there
const handleKeyEvent = (e: KeyboardEvent) => {
if (!e.isTrusted)
return;
window.parent?.postMessage({
type: e.type,
key: e.key,
keyCode: e.keyCode,
code: e.code,
shiftKey: e.shiftKey,
altKey: e.altKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
repeat: e.repeat,
}, '*');
};
window.addEventListener('keydown', handleKeyEvent);
window.addEventListener('keyup', handleKeyEvent);

if (window.location.protocol !== 'file:') {
if (window.location.href.includes('isUnderTest=true'))
await new Promise(f => setTimeout(f, 1000));
if (!navigator.serviceWorker)
throw new Error(`Service workers are not supported.\nMake sure to serve the Trace Viewer (${window.location}) via HTTPS or localhost.`);
navigator.serviceWorker.register('sw.bundle.js');
if (!navigator.serviceWorker.controller) {
await new Promise<void>(f => {
navigator.serviceWorker.oncontrollerchange = () => f();
});
}

// Keep SW running.
setInterval(function() { fetch('ping'); }, 10000);
}

setPopoutFunction((url: string, target?: string) => {
if (!url)
return;
window.parent.postMessage({ command: 'openExternal', url, target }, '*');
});

ReactDOM.render(<WorkbenchLoader hideHeader />, document.querySelector('#root'));
})();
27 changes: 27 additions & 0 deletions packages/trace-viewer/src/ui/popout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* 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.
*/

type PopoutFunction = (url: string, target?: string) => Window | any;

let popoutFn: PopoutFunction = window.open;
export function setPopoutFunction(fn: PopoutFunction) {
popoutFn = fn;
}

export function popout(url: string, target?: string): Window | undefined {
const win = popoutFn(url, target);
return win instanceof Window ? win : undefined;
}
3 changes: 2 additions & 1 deletion packages/trace-viewer/src/ui/snapshotTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import type { Language } from '@isomorphic/locatorGenerators';
import { locatorOrSelectorAsSelector } from '@isomorphic/locatorParser';
import { TabbedPaneTab } from '@web/components/tabbedPane';
import { BrowserFrame } from './browserFrame';
import { popout } from './popout';

export const SnapshotTab: React.FunctionComponent<{
action: ActionTraceEvent | undefined,
Expand Down Expand Up @@ -190,7 +191,7 @@ export const SnapshotTab: React.FunctionComponent<{
})}
<div style={{ flex: 'auto' }}></div>
<ToolbarButton icon='link-external' title='Open snapshot in a new tab' disabled={!popoutUrl} onClick={() => {
const win = window.open(popoutUrl || '', '_blank');
const win = popout(popoutUrl || '', '_blank');
win?.addEventListener('DOMContentLoaded', () => {
const injectedScript = new InjectedScript(win as any, false, sdkLanguage, testIdAttributeName, 1, 'chromium', []);
new ConsoleAPI(injectedScript);
Expand Down
5 changes: 4 additions & 1 deletion packages/trace-viewer/src/ui/workbenchLoader.css
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,13 @@ body.dark-mode .drop-target {
flex: none;
width: 100%;
height: 3px;
margin-top: -3px;
z-index: 10;
}

.header + .progress {
margin-top: -3px;
}

.inner-progress {
background-color: var(--vscode-progressBar-background);
height: 100%;
Expand Down
7 changes: 4 additions & 3 deletions packages/trace-viewer/src/ui/workbenchLoader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import { Workbench } from './workbench';
import { TestServerConnection } from '@testIsomorphic/testServerConnection';

export const WorkbenchLoader: React.FunctionComponent<{
}> = () => {
hideHeader?: boolean
}> = ({ hideHeader }) => {
const [isServer, setIsServer] = React.useState<boolean>(false);
const [traceURLs, setTraceURLs] = React.useState<string[]>([]);
const [uploadedTraceNames, setUploadedTraceNames] = React.useState<string[]>([]);
Expand Down Expand Up @@ -138,15 +139,15 @@ export const WorkbenchLoader: React.FunctionComponent<{
const showFileUploadDropArea = !!(!isServer && !dragOver && !fileForLocalModeError && (!traceURLs.length || processingErrorMessage));

return <div className='vbox workbench-loader' onDragOver={event => { event.preventDefault(); setDragOver(true); }}>
<div className='hbox header' {...(showFileUploadDropArea ? { inert: 'true' } : {})}>
{!hideHeader && <div className='hbox header' {...(showFileUploadDropArea ? { inert: 'true' } : {})}>
<div className='logo'>
<img src='playwright-logo.svg' alt='Playwright logo' />
</div>
<div className='product'>Playwright</div>
{model.title && <div className='title'>{model.title}</div>}
<div className='spacer'></div>
<ToolbarButton icon='color-mode' title='Toggle color mode' toggled={false} onClick={() => toggleTheme()}></ToolbarButton>
</div>
</div>}
<div className='progress'>
<div className='inner-progress' style={{ width: progress.total ? (100 * progress.done / progress.total) + '%' : 0 }}></div>
</div>
Expand Down
1 change: 1 addition & 0 deletions packages/trace-viewer/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export default defineConfig({
input: {
index: path.resolve(__dirname, 'index.html'),
uiMode: path.resolve(__dirname, 'uiMode.html'),
embedded: path.resolve(__dirname, 'embedded.html'),
snapshot: path.resolve(__dirname, 'snapshot.html'),
},
output: {
Expand Down