/*
  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 * as icons from './icons';
import { CopyToClipboard } from './copyToClipboard';
import './links.css';
import { linkifyText } from '@web/renderUtils';
import { clsx, useFlash } from '@web/uiUtils';
import { trace } from './icons';
import { Expandable } from './expandable';
import { Label } from './labels';
import { filterWithQuery } from './filter';
import { formatUrl } from './utils';
export function navigate(href) {
    window.history.pushState({}, '', href);
    const navEvent = new PopStateEvent('popstate');
    window.dispatchEvent(navEvent);
}
export const Route = ({ predicate, children }) => {
    return predicate(useSearchParams()) ? children : null;
};
export const Link = ({ click, ctrlClick, children, ...rest }) => {
    return <a {...rest} style={{ textDecoration: 'none', color: 'var(--color-fg-default)', cursor: 'pointer' }} onClick={e => {
            if (click) {
                e.preventDefault();
                navigate(formatUrl(e.metaKey || e.ctrlKey ? ctrlClick || click : click));
            }
        }}>{children}</a>;
};
export const LinkBadge = ({ className, ...props }) => <Link {...props} className={clsx('link-badge', props.dim && 'link-badge-dim', className)}/>;
export const ProjectLink = ({ projectNames, projectName }) => {
    const searchParams = new URLSearchParams(useSearchParams());
    if (searchParams.has('testId'))
        searchParams.delete('speedboard');
    searchParams.delete('testId');
    return <Link click={filterWithQuery(searchParams, `p:${projectName}`, false)} ctrlClick={filterWithQuery(searchParams, `p:${projectName}`, true)}>
    <Label label={projectName} colorIndex={projectNames.indexOf(projectName) % 6}/>
  </Link>;
};
export const AttachmentLink = ({ attachment, result, href, linkName, openInNewTab }) => {
    const [flash, triggerFlash] = useFlash();
    useAnchor('attachment-' + result.attachments.indexOf(attachment), triggerFlash);
    const summaryContent = (<span>
      {attachment.contentType === kMissingContentType ? icons.warning() : icons.attachment()}
      {attachment.path && (openInNewTab
            ? <a href={formatUrl(href || attachment.path)} target='_blank' rel='noreferrer'>{linkName || attachment.name}</a>
            : <a href={formatUrl(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 details */}>
              {attachment.name}
            </a>)
            : <span>{linkifyText(attachment.name)}</span>)}
    </span>);
    if (!attachment.body) {
        return (<div style={{ lineHeight: '32px', whiteSpace: 'nowrap', paddingLeft: 4 }} className={clsx(flash && 'attachment-flash')}>
        <span style={{ visibility: 'hidden' }}>{icons.rightArrow()}</span>
        {summaryContent}
      </div>);
    }
    return (<Expandable style={{ lineHeight: '32px' }} className={clsx(flash && 'attachment-flash')} summary={summaryContent}>
      <div className='attachment-body'>
        <CopyToClipboard value={attachment.body}/>
        {linkifyText(attachment.body)}
      </div>
    </Expandable>);
};
export const TraceLink = ({ 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={formatUrl(generateTraceUrl(firstTraces))} title='View Trace' className='button trace-link' dim={dim}>
        {trace()}
        <span>View Trace</span>
      </LinkBadge>
      {trailingSeparator && <div className='trace-link-separator'>|</div>}
    </>);
};
const SearchParamsContext = React.createContext(new URLSearchParams(window.location.hash.slice(1)));
// Note: make sure you are not mutating the returned URLSearchParams object.
export function useSearchParams() {
    return React.useContext(SearchParamsContext);
}
export const SearchParamsProvider = ({ children }) => {
    const [searchParams, setSearchParams] = React.useState(new URLSearchParams(window.location.hash.slice(1)));
    React.useEffect(() => {
        const listener = () => setSearchParams(new URLSearchParams(window.location.hash.slice(1)));
        window.addEventListener('popstate', listener);
        return () => window.removeEventListener('popstate', listener);
    }, []);
    return <SearchParamsContext.Provider value={searchParams}>{children}</SearchParamsContext.Provider>;
};
function downloadFileNameForAttachment(attachment) {
    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) {
    return `trace/index.html?${traces.map((a, i) => `trace=${new URL(a.path, window.location.href)}`).join('&')}`;
}
const kMissingContentType = 'x-playwright/missing';
export function useAnchor(id, onReveal) {
    const searchParams = useSearchParams();
    const isAnchored = useIsAnchored(id);
    React.useEffect(() => {
        if (isAnchored)
            return onReveal();
    }, [isAnchored, onReveal, searchParams]);
}
export function useIsAnchored(id) {
    const anchor = useSearchParams().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 }) {
    const ref = React.useRef(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 }, searchParams) {
    const params = new URLSearchParams(searchParams);
    if (test)
        params.set('testId', test.testId);
    if (test && result)
        params.set('run', '' + test.results.indexOf(result));
    if (anchor)
        params.set('anchor', anchor);
    return `#?` + params;
}
//# sourceMappingURL=links.js.map