Skip to content
Closed
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
53 changes: 53 additions & 0 deletions packages/html-reporter/src/anchor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* 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 * as React from 'react';
import { SearchParamsContext } from './links';

export type AnchorID = string | string[] | ((id: string) => boolean) | undefined;

export function useAnchor(id: AnchorID, onReveal: React.EffectCallback) {
const searchParams = React.useContext(SearchParamsContext);
const isAnchored = useIsAnchored(id);
React.useEffect(() => {
if (isAnchored)
return onReveal();
}, [isAnchored, onReveal, searchParams]);
}

export function useIsAnchored(id: AnchorID) {
const searchParams = React.useContext(SearchParamsContext);
const anchor = searchParams.get('anchor');
if (anchor === null)
return false;
if (typeof id === 'undefined')
return false;
if (typeof id === 'string')
return id === anchor;
if (Array.isArray(id))
return id.includes(anchor);
return id(anchor);
}

export function Anchor({ id, children }: React.PropsWithChildren<{ id: AnchorID }>) {
const ref = React.useRef<HTMLDivElement>(null);
const onAnchorReveal = React.useCallback(() => {
ref.current?.scrollIntoView({ block: 'start', inline: 'start' });
}, []);
useAnchor(id, onAnchorReveal);

return <div ref={ref}>{children}</div>;
}
2 changes: 1 addition & 1 deletion packages/html-reporter/src/chip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import './colors.css';
import './common.css';
import * as icons from './icons';
import { clsx } from '@web/uiUtils';
import { type AnchorID, useAnchor } from './links';
import { AnchorID, useAnchor } from './anchor';

export const Chip: React.FC<{
header: JSX.Element | string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,12 @@
fill: var(--color-fg-muted);
}

.trace-link {
.link-trace {
/* Trace link button has 1px border and 4px padding, so we need 3px right margin to match content on the other side of divider */
margin-right: 3px;
}

.trace-link-separator {
.link-trace-separator {
color: var(--color-fg-muted);
user-select: none;
}
108 changes: 108 additions & 0 deletions packages/html-reporter/src/linkVariants.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* 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 * as React from 'react';
import { Link, LinkProps } from './links';
import { clsx, useFlash } from '@web/uiUtils';
import type { TestAttachment, TestCaseSummary, TestResult } from './types';
import { TreeItem } from './treeItem';
import * as icons from './icons';
import { useAnchor } from './anchor';
import { linkifyText } from '@web/renderUtils';
import { CopyToClipboard } from './copyToClipboard';
import { generateTraceUrl } from './url';
import './colors.css';
import './linkVariants.css';

export const LinkBadge: React.FunctionComponent<LinkProps & { dim?: boolean }> = ({ className, ...props }) => <Link {...props} className={clsx('link-badge', props.dim && 'link-badge-dim', className)} />;

export const ProjectLink: React.FunctionComponent<{
projectNames: string[],
projectName: string,
}> = ({ projectNames, projectName }) => {
const encoded = encodeURIComponent(projectName);
const value = projectName === encoded ? projectName : `"${encoded.replace(/%22/g, '%5C%22')}"`;
return <Link href={`#?q=p:${value}`}>
<span className={clsx('label', `label-color-${projectNames.indexOf(projectName) % 6}`)} style={{ margin: '6px 0 0 6px' }}>
{projectName}
</span>
</Link>;
};

const kMissingContentType = 'x-playwright/missing';

export const AttachmentLink: React.FunctionComponent<{
attachment: TestAttachment,
result: TestResult,
href?: string,
linkName?: string,
openInNewTab?: boolean,
}> = ({ attachment, result, href, linkName, openInNewTab }) => {
const [flash, triggerFlash] = useFlash();
useAnchor('attachment-' + result.attachments.indexOf(attachment), triggerFlash);
return <TreeItem title={<span>
{attachment.contentType === kMissingContentType ? icons.warning() : icons.attachment()}
{attachment.path && (
openInNewTab
? <a href={href || attachment.path} target='_blank' rel='noreferrer'>{linkName || attachment.name}</a>
: <a href={href || attachment.path} download={downloadFileNameForAttachment(attachment)}>{linkName || attachment.name}</a>
)}
{!attachment.path && (
openInNewTab
? (
<a
href={URL.createObjectURL(new Blob([attachment.body!], { type: attachment.contentType }))}
target='_blank' rel='noreferrer'
onClick={e => e.stopPropagation() /* dont expand the tree item */}
>
{attachment.name}
</a>
)
: <span>{linkifyText(attachment.name)}</span>
)}
</span>} loadChildren={attachment.body ? () => {
return [<div key={1} className='attachment-body'><CopyToClipboard value={attachment.body!}/>{linkifyText(attachment.body!)}</div>];
} : undefined} depth={0} style={{ lineHeight: '32px' }} flash={flash}></TreeItem>;
};

export const TraceLink: React.FC<{ test: TestCaseSummary, trailingSeparator?: boolean, dim?: boolean }> = ({ test, trailingSeparator, dim }) => {
const firstTraces = test.results.map(result => result.attachments.filter(attachment => attachment.name === 'trace')).filter(traces => traces.length > 0)[0];
if (!firstTraces)
return undefined;

return (
<>
<LinkBadge
href={generateTraceUrl(firstTraces)}
title='View Trace'
className='button link-trace'
dim={dim}>
{icons.trace()}
<span>View Trace</span>
</LinkBadge>
{trailingSeparator && <div className='link-trace-separator'>|</div>}
</>
);
};

function downloadFileNameForAttachment(attachment: TestAttachment): string {
if (attachment.name.includes('.') || !attachment.path)
return attachment.name;
const firstDotIndex = attachment.path.indexOf('.');
if (firstDotIndex === -1)
return attachment.name;
return attachment.name + attachment.path.slice(firstDotIndex, attachment.path.length);
}
140 changes: 1 addition & 139 deletions packages/html-reporter/src/links.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,7 @@
limitations under the License.
*/

import type { TestAttachment, TestCase, TestCaseSummary, TestResult, TestResultSummary } from './types';
import * as React from 'react';
import * as icons from './icons';
import { TreeItem } from './treeItem';
import { CopyToClipboard } from './copyToClipboard';
import './links.css';
import { linkifyText } from '@web/renderUtils';
import { clsx, useFlash } from '@web/uiUtils';
import { trace } from './icons';

export function navigate(href: string | URL) {
window.history.pushState({}, '', href);
Expand All @@ -38,7 +30,7 @@ export const Route: React.FunctionComponent<{
return predicate(searchParams) ? children : null;
};

type LinkProps = React.PropsWithChildren<{
export type LinkProps = React.PropsWithChildren<{
href?: string,
click?: string,
ctrlClick?: string,
Expand All @@ -55,75 +47,6 @@ export const Link: React.FunctionComponent<LinkProps> = ({ click, ctrlClick, chi
}}>{children}</a>;
};

export const LinkBadge: React.FunctionComponent<LinkProps & { dim?: boolean }> = ({ className, ...props }) => <Link {...props} className={clsx('link-badge', props.dim && 'link-badge-dim', className)} />;

export const ProjectLink: React.FunctionComponent<{
projectNames: string[],
projectName: string,
}> = ({ projectNames, projectName }) => {
const encoded = encodeURIComponent(projectName);
const value = projectName === encoded ? projectName : `"${encoded.replace(/%22/g, '%5C%22')}"`;
return <Link href={`#?q=p:${value}`}>
<span className={clsx('label', `label-color-${projectNames.indexOf(projectName) % 6}`)} style={{ margin: '6px 0 0 6px' }}>
{projectName}
</span>
</Link>;
};

export const AttachmentLink: React.FunctionComponent<{
attachment: TestAttachment,
result: TestResult,
href?: string,
linkName?: string,
openInNewTab?: boolean,
}> = ({ attachment, result, href, linkName, openInNewTab }) => {
const [flash, triggerFlash] = useFlash();
useAnchor('attachment-' + result.attachments.indexOf(attachment), triggerFlash);
return <TreeItem title={<span>
{attachment.contentType === kMissingContentType ? icons.warning() : icons.attachment()}
{attachment.path && (
openInNewTab
? <a href={href || attachment.path} target='_blank' rel='noreferrer'>{linkName || attachment.name}</a>
: <a href={href || attachment.path} download={downloadFileNameForAttachment(attachment)}>{linkName || attachment.name}</a>
)}
{!attachment.path && (
openInNewTab
? (
<a
href={URL.createObjectURL(new Blob([attachment.body!], { type: attachment.contentType }))}
target='_blank' rel='noreferrer'
onClick={e => e.stopPropagation() /* dont expand the tree item */}
>
{attachment.name}
</a>
)
: <span>{linkifyText(attachment.name)}</span>
)}
</span>} loadChildren={attachment.body ? () => {
return [<div key={1} className='attachment-body'><CopyToClipboard value={attachment.body!}/>{linkifyText(attachment.body!)}</div>];
} : undefined} depth={0} style={{ lineHeight: '32px' }} flash={flash}></TreeItem>;
};

export const TraceLink: React.FC<{ test: TestCaseSummary, trailingSeparator?: boolean, dim?: boolean }> = ({ test, trailingSeparator, dim }) => {
const firstTraces = test.results.map(result => result.attachments.filter(attachment => attachment.name === 'trace')).filter(traces => traces.length > 0)[0];
if (!firstTraces)
return undefined;

return (
<>
<LinkBadge
href={generateTraceUrl(firstTraces)}
title='View Trace'
className='button trace-link'
dim={dim}>
{trace()}
<span>View Trace</span>
</LinkBadge>
{trailingSeparator && <div className='trace-link-separator'>|</div>}
</>
);
};

export const SearchParamsContext = React.createContext<URLSearchParams>(new URLSearchParams(window.location.hash.slice(1)));

export const SearchParamsProvider: React.FunctionComponent<React.PropsWithChildren> = ({ children }) => {
Expand All @@ -137,64 +60,3 @@ export const SearchParamsProvider: React.FunctionComponent<React.PropsWithChildr

return <SearchParamsContext.Provider value={searchParams}>{children}</SearchParamsContext.Provider>;
};

function downloadFileNameForAttachment(attachment: TestAttachment): string {
if (attachment.name.includes('.') || !attachment.path)
return attachment.name;
const firstDotIndex = attachment.path.indexOf('.');
if (firstDotIndex === -1)
return attachment.name;
return attachment.name + attachment.path.slice(firstDotIndex, attachment.path.length);
}

export function generateTraceUrl(traces: TestAttachment[]) {
return `trace/index.html?${traces.map((a, i) => `trace=${new URL(a.path!, window.location.href)}`).join('&')}`;
}

const kMissingContentType = 'x-playwright/missing';

export type AnchorID = string | string[] | ((id: string) => boolean) | undefined;

export function useAnchor(id: AnchorID, onReveal: React.EffectCallback) {
const searchParams = React.useContext(SearchParamsContext);
const isAnchored = useIsAnchored(id);
React.useEffect(() => {
if (isAnchored)
return onReveal();
}, [isAnchored, onReveal, searchParams]);
}

export function useIsAnchored(id: AnchorID) {
const searchParams = React.useContext(SearchParamsContext);
const anchor = searchParams.get('anchor');
if (anchor === null)
return false;
if (typeof id === 'undefined')
return false;
if (typeof id === 'string')
return id === anchor;
if (Array.isArray(id))
return id.includes(anchor);
return id(anchor);
}

export function Anchor({ id, children }: React.PropsWithChildren<{ id: AnchorID }>) {
const ref = React.useRef<HTMLDivElement>(null);
const onAnchorReveal = React.useCallback(() => {
ref.current?.scrollIntoView({ block: 'start', inline: 'start' });
}, []);
useAnchor(id, onAnchorReveal);

return <div ref={ref}>{children}</div>;
}

export function testResultHref({ test, result, anchor }: { test?: TestCase | TestCaseSummary, result?: TestResult | TestResultSummary, anchor?: string }) {
const params = new URLSearchParams();
if (test)
params.set('testId', test.testId);
if (test && result)
params.set('run', '' + test.results.indexOf(result as any));
if (anchor)
params.set('anchor', anchor);
return `#?` + params;
}
4 changes: 3 additions & 1 deletion packages/html-reporter/src/testCaseView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as React from 'react';
import { TabbedPane } from './tabbedPane';
import { AutoChip } from './chip';
import './common.css';
import { Link, ProjectLink, SearchParamsContext, testResultHref, TraceLink } from './links';
import { Link, SearchParamsContext } from './links';
import { statusIcon } from './statusIcon';
import './testCaseView.css';
import { TestResultView } from './testResultView';
Expand All @@ -30,6 +30,8 @@ import { clsx } from '@web/uiUtils';
import { CopyToClipboardContainer } from './copyToClipboard';
import { HeaderView } from './headerView';
import type { MetadataWithCommitInfo } from '@playwright/isomorphic/types';
import { testResultHref } from './url';
import { ProjectLink, TraceLink } from './linkVariants';

export const TestCaseView: React.FC<{
projectNames: string[],
Expand Down
4 changes: 3 additions & 1 deletion packages/html-reporter/src/testFileView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ import * as React from 'react';
import { hashStringToInt, msToString } from './utils';
import { Chip } from './chip';
import { filterWithToken } from './filter';
import { Link, LinkBadge, navigate, ProjectLink, SearchParamsContext, testResultHref, TraceLink } from './links';
import { Link, navigate, SearchParamsContext } from './links';
import { statusIcon } from './statusIcon';
import './testFileView.css';
import { video, image } from './icons';
import { clsx } from '@web/uiUtils';
import { testResultHref } from './url';
import { LinkBadge, ProjectLink, TraceLink } from './linkVariants';

export const TestFileView: React.FC<React.PropsWithChildren<{
file: TestFileSummary;
Expand Down
Loading
Loading