hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 4, "code_window": [ "type ReactComponent = Component | FunctionComponent<any>;\n", "type ReactReturnType = StoryFnReactReturnType;\n", "\n", "export type Decorator = DecoratorFunction<ReactReturnType>;\n", "\n", "export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &\n", " Annotations<ArgsType, ReactReturnType>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> &\n", " Annotations<Args, ReactReturnType>;\n" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 31 }
import React from 'react'; // We would need to add this in config.js idiomatically however that would make this file a bit confusing import { addDecorator } from '@storybook/react'; addDecorator((s, { kind }) => kind === 'Core/Decorators' ? ( <> <p>Global Decorator</p> {s()} </> ) : ( s() ) ); export default { title: 'Core/Decorators', decorators: [ (s) => ( <> <p>Kind Decorator</p> {s()} </> ), ], }; export const All = () => <p>Story</p>; All.decorators = [ (s) => ( <> <p>Local Decorator</p> {s()} </> ), ];
examples/official-storybook/stories/core/decorators.stories.js
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.7883747220039368, 0.19743168354034424, 0.00016767064516898245, 0.000592182797845453, 0.34118130803108215 ]
{ "id": 4, "code_window": [ "type ReactComponent = Component | FunctionComponent<any>;\n", "type ReactReturnType = StoryFnReactReturnType;\n", "\n", "export type Decorator = DecoratorFunction<ReactReturnType>;\n", "\n", "export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> &\n", " Annotations<ArgsType, ReactReturnType>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ "export type Meta<Args = DefaultArgs> = BaseMeta<ReactComponent> &\n", " Annotations<Args, ReactReturnType>;\n" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 31 }
export { INITIAL_VIEWPORTS, DEFAULT_VIEWPORT, MINIMAL_VIEWPORTS } from './defaults';
addons/viewport/src/preview.ts
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.0001583009143359959, 0.0001583009143359959, 0.0001583009143359959, 0.0001583009143359959, 0 ]
{ "id": 5, "code_window": [ "\n", "export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &\n", " Annotations<ArgsType, ReactReturnType>;\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> &\n", " Annotations<Args, ReactReturnType>;" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 34 }
import { Component, FunctionComponent } from 'react'; import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons'; import { StoryFnReactReturnType } from './types'; // Base types interface Annotations<ArgsType, StoryFnReturnType> { args?: ArgsType; argTypes?: ArgTypes; parameters?: Parameters; decorators?: DecoratorFunction<StoryFnReturnType>[]; } interface BaseMeta<ComponentType> { title: string; component?: ComponentType; subcomponents?: Record<string, ComponentType>; } interface BaseStory<ArgsType, StoryFnReturnType> { (args: ArgsType, context: StoryContext): StoryFnReturnType; } // Re-export generic types export { Args, ArgTypes, Parameters, StoryContext }; // React specific types type ReactComponent = Component | FunctionComponent<any>; type ReactReturnType = StoryFnReactReturnType; export type Decorator = DecoratorFunction<ReactReturnType>; export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> & Annotations<ArgsType, ReactReturnType>; export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> & Annotations<ArgsType, ReactReturnType>;
app/react/src/client/preview/csf.ts
1
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.9983614087104797, 0.4677938222885132, 0.0028706465382128954, 0.4349716305732727, 0.4666077494621277 ]
{ "id": 5, "code_window": [ "\n", "export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &\n", " Annotations<ArgsType, ReactReturnType>;\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> &\n", " Annotations<Args, ReactReturnType>;" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 34 }
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
examples/angular-cli/src/main.ts
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017717573791742325, 0.00017714753630571067, 0.00017711932014208287, 0.00017714753630571067, 2.820888944654598e-8 ]
{ "id": 5, "code_window": [ "\n", "export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &\n", " Annotations<ArgsType, ReactReturnType>;\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> &\n", " Annotations<Args, ReactReturnType>;" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 34 }
export function managerEntries(entry: any[] = []) { return [...entry, require.resolve('../register')]; }
addons/toolbars/src/preset/index.ts
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017160440620500594, 0.00017160440620500594, 0.00017160440620500594, 0.00017160440620500594, 0 ]
{ "id": 5, "code_window": [ "\n", "export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> &\n", " Annotations<ArgsType, ReactReturnType>;\n" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [ "export type Story<Args = DefaultArgs> = BaseStory<Args, ReactReturnType> &\n", " Annotations<Args, ReactReturnType>;" ], "file_path": "app/react/src/client/preview/csf.ts", "type": "replace", "edit_start_line_idx": 34 }
import React, { FC, ChangeEvent } from 'react'; import { styled } from '@storybook/theming'; import { Form } from '../form'; import { ControlProps, TextValue, TextConfig } from './types'; export type TextProps = ControlProps<TextValue | undefined> & TextConfig; const Wrapper = styled.label({ display: 'flex', }); const format = (value?: TextValue) => value || ''; export const TextControl: FC<TextProps> = ({ name, value, onChange, onFocus, onBlur }) => { const handleChange = (event: ChangeEvent<HTMLTextAreaElement>) => { onChange(event.target.value); }; return ( <Wrapper> <Form.Textarea id={name} onChange={handleChange} size="flex" placeholder="Adjust string dynamically" {...{ name, value: format(value), onFocus, onBlur }} /> </Wrapper> ); };
lib/components/src/controls/Text.tsx
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.0003258869401179254, 0.00021247626864351332, 0.00017244735499843955, 0.0001757854042807594, 0.00006552226841449738 ]
{ "id": 6, "code_window": [ "import './header.css';\n", "\n", "export interface HeaderProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Header: React.FC<HeaderProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <header>\n", " <div className=\"wrapper\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Header.tsx", "type": "replace", "edit_start_line_idx": 7 }
import { Component, FunctionComponent } from 'react'; import { Args, ArgTypes, Parameters, DecoratorFunction, StoryContext } from '@storybook/addons'; import { StoryFnReactReturnType } from './types'; // Base types interface Annotations<ArgsType, StoryFnReturnType> { args?: ArgsType; argTypes?: ArgTypes; parameters?: Parameters; decorators?: DecoratorFunction<StoryFnReturnType>[]; } interface BaseMeta<ComponentType> { title: string; component?: ComponentType; subcomponents?: Record<string, ComponentType>; } interface BaseStory<ArgsType, StoryFnReturnType> { (args: ArgsType, context: StoryContext): StoryFnReturnType; } // Re-export generic types export { Args, ArgTypes, Parameters, StoryContext }; // React specific types type ReactComponent = Component | FunctionComponent<any>; type ReactReturnType = StoryFnReactReturnType; export type Decorator = DecoratorFunction<ReactReturnType>; export type Meta<ArgsType = Args> = BaseMeta<ReactComponent> & Annotations<ArgsType, ReactReturnType>; export type Story<ArgsType = Args> = BaseStory<ArgsType, ReactReturnType> & Annotations<ArgsType, ReactReturnType>;
app/react/src/client/preview/csf.ts
1
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.0001734248799039051, 0.0001709569914964959, 0.00016725980094633996, 0.00017157163529191166, 0.0000024585897335782647 ]
{ "id": 6, "code_window": [ "import './header.css';\n", "\n", "export interface HeaderProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Header: React.FC<HeaderProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <header>\n", " <div className=\"wrapper\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Header.tsx", "type": "replace", "edit_start_line_idx": 7 }
{ "name": "html-kitchen-sink", "version": "6.0.0-rc.26", "private": true, "description": "", "keywords": [], "license": "MIT", "author": "", "main": "index.js", "scripts": { "build-storybook": "build-storybook", "generate-addon-jest-testresults": "jest --config=tests/addon-jest.config.json --json --outputFile=stories/addon-jest.testresults.json", "storybook": "start-storybook -p 9006" }, "devDependencies": { "@storybook/addon-a11y": "6.0.0-rc.26", "@storybook/addon-actions": "6.0.0-rc.26", "@storybook/addon-backgrounds": "6.0.0-rc.26", "@storybook/addon-controls": "6.0.0-rc.26", "@storybook/addon-docs": "6.0.0-rc.26", "@storybook/addon-events": "6.0.0-rc.26", "@storybook/addon-jest": "6.0.0-rc.26", "@storybook/addon-knobs": "6.0.0-rc.26", "@storybook/addon-links": "6.0.0-rc.26", "@storybook/addon-storyshots": "6.0.0-rc.26", "@storybook/addon-storysource": "6.0.0-rc.26", "@storybook/addon-viewport": "6.0.0-rc.26", "@storybook/addons": "6.0.0-rc.26", "@storybook/client-api": "6.0.0-rc.26", "@storybook/core": "6.0.0-rc.26", "@storybook/core-events": "6.0.0-rc.26", "@storybook/html": "6.0.0-rc.26", "@storybook/source-loader": "6.0.0-rc.26", "eventemitter3": "^4.0.0", "format-json": "^1.0.3", "global": "^4.3.2", "postcss-color-rebeccapurple": "^6.0.0" }, "storybook": { "chromatic": { "projectToken": "e8zolxoyg8o" } } }
examples/html-kitchen-sink/package.json
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017436701455153525, 0.00017306514200754464, 0.00017145297897513956, 0.00017325578664895147, 0.0000011583825880734366 ]
{ "id": 6, "code_window": [ "import './header.css';\n", "\n", "export interface HeaderProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Header: React.FC<HeaderProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <header>\n", " <div className=\"wrapper\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Header.tsx", "type": "replace", "edit_start_line_idx": 7 }
require('./dist/register');
addons/jest/register.js
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017415365437045693, 0.00017415365437045693, 0.00017415365437045693, 0.00017415365437045693, 0 ]
{ "id": 6, "code_window": [ "import './header.css';\n", "\n", "export interface HeaderProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Header: React.FC<HeaderProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <header>\n", " <div className=\"wrapper\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Header.tsx", "type": "replace", "edit_start_line_idx": 7 }
/* * By the time this file was added the repository for angular2-template-loader received no updates in 3 years * This is just a copy of https://github.com/TheLarkInn/angular2-template-loader/blob/master/index.js in order * to fix a bug that prevents Storybook from updating raw-loader > ^1.0.0 * * As suggested in https://github.com/storybookjs/storybook/issues/7877#issuecomment-536556755 this code was * modified to be compatible with newer versions of raw-loader as well as backwards compatible with raw-loader ^1.0.0 */ // using: regex, capture groups, and capture group variables. const templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*([,}]))/gm; const stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g; const stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g; const replaceStringsWithRequires = (string: string) => { return string.replace(stringRegex, (match, quote, url) => { let newUrl = url; if (url.charAt(0) !== '.') { newUrl = `./${url}`; } const requireString = `(require('${newUrl}').default || require('${newUrl}'))`; // without the length check an empty style file will throw // "Expected 'styles' to be an array of strings" return `${requireString}.length ? ${requireString} : ''`; }); }; export default function (source: string) { const styleProperty = 'styles'; const templateProperty = 'template'; return source .replace(templateUrlRegex, (_, templateUrlString: string) => { // replace: templateUrl: './path/to/template.html' // with: template: require('./path/to/template.html') // or: templateUrl: require('./path/to/template.html') // if `keepUrl` query parameter is set to true. return `${templateProperty}:${replaceStringsWithRequires(templateUrlString)}`; }) .replace(stylesRegex, (_, styleUrlsString: string) => { // replace: stylesUrl: ['./foo.css', "./baz.css", "./index.component.css"] // with: styles: [require('./foo.css'), require("./baz.css"), require("./index.component.css")] // or: styleUrls: [require('./foo.css'), require("./baz.css"), require("./index.component.css")] // if `keepUrl` query parameter is set to true. return `${styleProperty}:${replaceStringsWithRequires(styleUrlsString)}`; }); }
app/angular/src/server/ngx-template-loader/index.ts
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.0001752455864334479, 0.00017159657727461308, 0.00016928381228353828, 0.00017122113786172122, 0.000001998906100197928 ]
{ "id": 7, "code_window": [ "import './page.css';\n", "\n", "export interface PageProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Page: React.FC<PageProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <article>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Page.tsx", "type": "replace", "edit_start_line_idx": 7 }
import React from 'react'; import { Header } from './Header'; import './page.css'; export interface PageProps { user?: {}; onLogin?: () => void; onLogout?: () => void; onCreateAccount?: () => void; } export const Page: React.FC<PageProps> = ({ user, onLogin, onLogout, onCreateAccount }) => ( <article> <Header user={user} onLogin={onLogin} onLogout={onLogout} onCreateAccount={onCreateAccount} /> <section> <h2>Pages in Storybook</h2> <p> We recommend building UIs with a{' '} <a href="https://componentdriven.org" target="_blank" rel="noopener noreferrer"> <strong>component-driven</strong> </a>{' '} process starting with atomic components and ending with pages. </p> <p> Render pages with mock data. This makes it easy to build and review page states without needing to navigate to them in your app. Here are some handy patterns for managing page data in Storybook: </p> <ul> <li> Use a higher-level connected component. Storybook helps you compose such data from the "args" of child component stories </li> <li> Assemble data in the page component from your services. You can mock these services out using Storybook. </li> </ul> <p> Get a guided tutorial on component-driven development at{' '} <a href="https://www.learnstorybook.com" target="_blank" rel="noopener noreferrer"> Learn Storybook </a> . Read more in the{' '} <a href="https://storybook.js.org/docs" target="_blank" rel="noopener noreferrer"> docs </a> . </p> <div className="tip-wrapper"> <span className="tip">Tip</span> Adjust the width of the canvas with the{' '} <svg width="10" height="10" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg"> <g fill="none" fillRule="evenodd"> <path d="M1.5 5.2h4.8c.3 0 .5.2.5.4v5.1c-.1.2-.3.3-.4.3H1.4a.5.5 0 01-.5-.4V5.7c0-.3.2-.5.5-.5zm0-2.1h6.9c.3 0 .5.2.5.4v7a.5.5 0 01-1 0V4H1.5a.5.5 0 010-1zm0-2.1h9c.3 0 .5.2.5.4v9.1a.5.5 0 01-1 0V2H1.5a.5.5 0 010-1zm4.3 5.2H2V10h3.8V6.2z" id="a" fill="#999" /> </g> </svg> Viewports addon in the toolbar </div> </section> </article> );
lib/cli/src/frameworks/react/ts/Page.tsx
1
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.9975868463516235, 0.28497403860092163, 0.00016349430370610207, 0.0001724626636132598, 0.45031681656837463 ]
{ "id": 7, "code_window": [ "import './page.css';\n", "\n", "export interface PageProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Page: React.FC<PageProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <article>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Page.tsx", "type": "replace", "edit_start_line_idx": 7 }
import { Button } from '@storybook/react/demo'; import { Story, Meta } from '@storybook/addon-docs/blocks'; <Meta title="Button" /> # Story definition <Story name="one"> <Button>One</Button> </Story> export const two = 2; <Story name="hello story"> <Button>Hello button</Button> </Story>
addons/docs/src/mdx/__testfixtures__/non-story-exports.mdx
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017823577218223363, 0.00017436419147998095, 0.00017049261077772826, 0.00017436419147998095, 0.000003871580702252686 ]
{ "id": 7, "code_window": [ "import './page.css';\n", "\n", "export interface PageProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Page: React.FC<PageProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <article>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Page.tsx", "type": "replace", "edit_start_line_idx": 7 }
import fs from 'fs'; import path from 'path'; import semver from '@storybook/semver'; import { logger } from '@storybook/node-logger'; const appDirectory = fs.realpathSync(process.cwd()); let reactScriptsPath: string; export function getReactScriptsPath({ noCache }: { noCache?: boolean } = {}) { if (reactScriptsPath && !noCache) return reactScriptsPath; let reactScriptsScriptPath = fs.realpathSync( path.join(appDirectory, '/node_modules/.bin/react-scripts') ); try { // Note: Since there is no symlink for .bin/react-scripts on Windows // we'll parse react-scripts file to find actual package path. // This is important if you use fork of CRA. const pathIsNotResolved = /node_modules[\\/]\.bin[\\/]react-scripts/i.test( reactScriptsScriptPath ); if (pathIsNotResolved) { const content = fs.readFileSync(reactScriptsScriptPath, 'utf8'); const packagePathMatch = content.match( /"\$basedir[\\/]([^\s]+?[\\/]bin[\\/]react-scripts\.js")/i ); if (packagePathMatch && packagePathMatch.length > 1) { reactScriptsScriptPath = path.join( appDirectory, '/node_modules/.bin/', packagePathMatch[1] ); } } } catch (e) { logger.warn(`Error occurred during react-scripts package path resolving: ${e}`); } reactScriptsPath = path.join(reactScriptsScriptPath, '../..'); const scriptsPkgJson = path.join(reactScriptsPath, 'package.json'); if (!fs.existsSync(scriptsPkgJson)) { reactScriptsPath = 'react-scripts'; } return reactScriptsPath; } export function isReactScriptsInstalled(requiredVersion = '2.0.0') { try { // eslint-disable-next-line import/no-dynamic-require,global-require const reactScriptsJson = require(path.join(getReactScriptsPath(), 'package.json')); return !semver.gtr(requiredVersion, reactScriptsJson.version); } catch (e) { return false; } }
app/react/src/server/cra-config.ts
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017874925106298178, 0.00017481959366705269, 0.00016871113621164113, 0.0001750889205140993, 0.0000030469661851384444 ]
{ "id": 7, "code_window": [ "import './page.css';\n", "\n", "export interface PageProps {\n", " user?: {};\n", " onLogin?: () => void;\n", " onLogout?: () => void;\n", " onCreateAccount?: () => void;\n", "}\n", "\n", "export const Page: React.FC<PageProps> = ({ user, onLogin, onLogout, onCreateAccount }) => (\n", " <article>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onLogin: () => void;\n", " onLogout: () => void;\n", " onCreateAccount: () => void;\n" ], "file_path": "lib/cli/src/frameworks/react/ts/Page.tsx", "type": "replace", "edit_start_line_idx": 7 }
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br /> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/).
examples/cra-ts-kitchen-sink/README.md
0
https://github.com/storybookjs/storybook/commit/71c20befcfe266d8ea8f50e96d2d2ecdadf2d04e
[ 0.00017414138710591942, 0.00016536194016225636, 0.00015969800006132573, 0.00016464902728330344, 0.0000048018700908869505 ]
{ "id": 0, "code_window": [ "\n", "import { AppEvents, SelectableValue } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { AsyncSelect } from '@grafana/ui';\n", "import { contextSrv } from 'app/core/services/context_srv';\n", "import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions';\n", "import { DashboardSearchHit } from 'app/features/search/types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ActionMeta, AsyncSelect } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9913901090621948, 0.04203658178448677, 0.00016742829757276922, 0.00031228686566464603, 0.19795618951320648 ]
{ "id": 0, "code_window": [ "\n", "import { AppEvents, SelectableValue } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { AsyncSelect } from '@grafana/ui';\n", "import { contextSrv } from 'app/core/services/context_srv';\n", "import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions';\n", "import { DashboardSearchHit } from 'app/features/search/types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ActionMeta, AsyncSelect } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 5 }
import { css } from '@emotion/css'; import React, { useEffect } from 'react'; import { DataTransformerID, FrameGeometrySource, FrameGeometrySourceMode, GrafanaTheme2, PanelOptionsEditorBuilder, PluginState, StandardEditorContext, TransformerRegistryItem, TransformerUIProps, } from '@grafana/data'; import { useTheme2 } from '@grafana/ui'; import { addLocationFields } from 'app/features/geo/editor/locationEditor'; import { SpatialCalculation, SpatialOperation, SpatialAction, SpatialTransformOptions } from './models.gen'; import { getDefaultOptions, getTransformerOptionPane } from './optionsHelper'; import { isLineBuilderOption, spatialTransformer } from './spatialTransformer'; // Nothing defined in state const supplier = ( builder: PanelOptionsEditorBuilder<SpatialTransformOptions>, context: StandardEditorContext<SpatialTransformOptions> ) => { const options = context.options ?? {}; builder.addSelect({ path: `action`, name: 'Action', description: '', defaultValue: SpatialAction.Prepare, settings: { options: [ { value: SpatialAction.Prepare, label: 'Prepare spatial field', description: 'Set a geometry field based on the results of other fields', }, { value: SpatialAction.Calculate, label: 'Calculate value', description: 'Use the geometry to define a new field (heading/distance/area)', }, { value: SpatialAction.Modify, label: 'Transform', description: 'Apply spatial operations to the geometry' }, ], }, }); if (options.action === SpatialAction.Calculate) { builder.addSelect({ path: `calculate.calc`, name: 'Function', description: '', defaultValue: SpatialCalculation.Heading, settings: { options: [ { value: SpatialCalculation.Heading, label: 'Heading' }, { value: SpatialCalculation.Area, label: 'Area' }, { value: SpatialCalculation.Distance, label: 'Distance' }, ], }, }); } else if (options.action === SpatialAction.Modify) { builder.addSelect({ path: `modify.op`, name: 'Operation', description: '', defaultValue: SpatialOperation.AsLine, settings: { options: [ { value: SpatialOperation.AsLine, label: 'As line', description: 'Create a single line feature with a vertex at each row', }, { value: SpatialOperation.LineBuilder, label: 'Line builder', description: 'Create a line between two points', }, ], }, }); } if (isLineBuilderOption(options)) { builder.addNestedOptions({ category: ['Source'], path: 'source', build: (b, c) => { const loc = (options.source ?? {}) as FrameGeometrySource; if (!loc.mode) { loc.mode = FrameGeometrySourceMode.Auto; } addLocationFields('Point', '', b, loc); }, }); builder.addNestedOptions({ category: ['Target'], path: 'modify', build: (b, c) => { const loc = (options.modify?.target ?? {}) as FrameGeometrySource; if (!loc.mode) { loc.mode = FrameGeometrySourceMode.Auto; } addLocationFields('Point', 'target.', b, loc); }, }); } else { addLocationFields('Location', 'source.', builder, options.source); } }; export const SetGeometryTransformerEditor: React.FC<TransformerUIProps<SpatialTransformOptions>> = (props) => { // a new component is created with every change :( useEffect(() => { if (!props.options.source?.mode) { const opts = getDefaultOptions(supplier); props.onChange({ ...opts, ...props.options }); console.log('geometry useEffect', opts); } }); const styles = getStyles(useTheme2()); const pane = getTransformerOptionPane<SpatialTransformOptions>(props, supplier); return ( <div> <div>{pane.items.map((v) => v.render())}</div> <div> {pane.categories.map((c) => { return ( <div key={c.props.id} className={styles.wrap}> <h5>{c.props.title}</h5> <div className={styles.item}>{c.items.map((s) => s.render())}</div> </div> ); })} </div> </div> ); }; const getStyles = (theme: GrafanaTheme2) => { return { wrap: css` margin-bottom: 20px; `, item: css` border-left: 4px solid ${theme.colors.border.strong}; padding-left: 10px; `, }; }; export const spatialTransformRegistryItem: TransformerRegistryItem<SpatialTransformOptions> = { id: DataTransformerID.spatial, editor: SetGeometryTransformerEditor, transformation: spatialTransformer, name: spatialTransformer.name, description: spatialTransformer.description, state: PluginState.alpha, };
public/app/features/transformers/spatial/SpatialTransformerEditor.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001785783824743703, 0.00017336991732008755, 0.0001655783853493631, 0.00017513932834845036, 0.000004224441454425687 ]
{ "id": 0, "code_window": [ "\n", "import { AppEvents, SelectableValue } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { AsyncSelect } from '@grafana/ui';\n", "import { contextSrv } from 'app/core/services/context_srv';\n", "import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions';\n", "import { DashboardSearchHit } from 'app/features/search/types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ActionMeta, AsyncSelect } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 5 }
import * as d3 from 'd3'; import * as d3ScaleChromatic from 'd3-scale-chromatic'; export function getColorScale(colorScheme: any, lightTheme: boolean, maxValue: number, minValue = 0): (d: any) => any { //@ts-ignore const colorInterpolator = d3ScaleChromatic[colorScheme.value]; const colorScaleInverted = colorScheme.invert === 'always' || colorScheme.invert === (lightTheme ? 'light' : 'dark'); const start = colorScaleInverted ? maxValue : minValue; const end = colorScaleInverted ? minValue : maxValue; return d3.scaleSequential(colorInterpolator).domain([start, end]); } export function getOpacityScale( options: { cardColor?: null; colorScale?: any; exponent?: any }, maxValue: number, minValue = 0 ): any { let legendOpacityScale; if (options.colorScale === 'linear') { legendOpacityScale = d3.scaleLinear().domain([minValue, maxValue]).range([0, 1]); } else if (options.colorScale === 'sqrt') { legendOpacityScale = d3.scalePow().exponent(options.exponent).domain([minValue, maxValue]).range([0, 1]); } return legendOpacityScale; }
public/app/plugins/panel/heatmap/color_scale.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017806743562687188, 0.00017522879352327436, 0.00017225935880560428, 0.00017535958613734692, 0.000002372940571149229 ]
{ "id": 0, "code_window": [ "\n", "import { AppEvents, SelectableValue } from '@grafana/data';\n", "import { selectors } from '@grafana/e2e-selectors';\n", "import { AsyncSelect } from '@grafana/ui';\n", "import { contextSrv } from 'app/core/services/context_srv';\n", "import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions';\n", "import { DashboardSearchHit } from 'app/features/search/types';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { ActionMeta, AsyncSelect } from '@grafana/ui';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 5 }
// Copyright (c) 2019 Uber Technologies, Inc. // // 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 { TDdgOperation, TDdgPath } from './types'; export default class PathElem { memberIdx: number; memberOf: TDdgPath; operation: TDdgOperation; private _visibilityIdx?: number; constructor({ path, operation, memberIdx }: { path: TDdgPath; operation: TDdgOperation; memberIdx: number }) { this.memberIdx = memberIdx; this.memberOf = path; this.operation = operation; } get distance() { return this.memberIdx - this.memberOf.focalIdx; } get externalPath(): PathElem[] { const result: PathElem[] = []; let current: PathElem | null | undefined = this; while (current) { result.push(current); current = current.externalSideNeighbor; } if (this.distance < 0) { result.reverse(); } return result; } get externalSideNeighbor(): PathElem | null | undefined { if (!this.distance) { return null; } return this.memberOf.members[this.memberIdx + Math.sign(this.distance)]; } get focalPath(): PathElem[] { const result: PathElem[] = []; let current: PathElem | null = this; while (current) { result.push(current); current = current.focalSideNeighbor; } if (this.distance > 0) { result.reverse(); } return result; } get focalSideNeighbor(): PathElem | null { if (!this.distance) { return null; } return this.memberOf.members[this.memberIdx - Math.sign(this.distance)]; } get isExternal(): boolean { return Boolean(this.distance) && (this.memberIdx === 0 || this.memberIdx === this.memberOf.members.length - 1); } set visibilityIdx(visibilityIdx: number) { if (this._visibilityIdx == null) { this._visibilityIdx = visibilityIdx; } else { throw new Error('Visibility Index cannot be changed once set'); } } get visibilityIdx(): number { if (this._visibilityIdx == null) { throw new Error('Visibility Index was never set for this PathElem'); } return this._visibilityIdx; } private toJSONHelper = () => ({ memberIdx: this.memberIdx, operation: this.operation.name, service: this.operation.service.name, visibilityIdx: this._visibilityIdx, }); /* * Because the memberOf on a PathElem contains an array of all of its members which in turn all contain * memberOf back to the path, some assistance is necessary when creating error messages. toJSON is called by * JSON.stringify and expected to return a JSON object. To that end, this method simplifies the * representation of the PathElems in memberOf's path to remove the circular reference. */ toJSON() { return { ...this.toJSONHelper(), memberOf: { focalIdx: this.memberOf.focalIdx, members: this.memberOf.members.map((member) => member.toJSONHelper()), }, }; } // `toJSON` is called by `JSON.stringify` while `toString` is used by template strings and string concat toString() { return JSON.stringify(this.toJSON(), null, 2); } // `[Symbol.toStringTag]` is used when attempting to use an object as a key on an object, where a full // stringified JSON would reduce clarity get [Symbol.toStringTag]() { return `PathElem ${this._visibilityIdx}`; } }
packages/jaeger-ui-components/src/model/ddg/PathElem.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00031298978137783706, 0.0001844897196860984, 0.00016329926438629627, 0.00017526495503261685, 0.00003725618444150314 ]
{ "id": 1, "code_window": [ " permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>;\n", " filter?: FolderPickerFilter;\n", " allowEmpty?: boolean;\n", " showRoot?: boolean;\n", " accessControlMetadata?: boolean;\n", " /**\n", " * Skips loading all folders in order to find the folder matching\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " onClear?: () => void;\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 27 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9980340600013733, 0.16738110780715942, 0.00016466222587041557, 0.00016930530546233058, 0.3697829246520996 ]
{ "id": 1, "code_window": [ " permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>;\n", " filter?: FolderPickerFilter;\n", " allowEmpty?: boolean;\n", " showRoot?: boolean;\n", " accessControlMetadata?: boolean;\n", " /**\n", " * Skips loading all folders in order to find the folder matching\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " onClear?: () => void;\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 27 }
import * as H from 'history'; import { ContextSrvStub } from 'test/specs/helpers'; import { dateTime, isDateTime } from '@grafana/data'; import { HistoryWrapper, locationService, setLocationService } from '@grafana/runtime'; import { beforeEach } from '../../../../test/lib/common'; import { TimeSrv } from './TimeSrv'; jest.mock('app/core/core', () => ({ appEvents: { subscribe: () => {}, }, })); describe('timeSrv', () => { let timeSrv: TimeSrv; let _dashboard: any; let locationUpdates: H.Location[] = []; beforeEach(() => { _dashboard = { time: { from: 'now-6h', to: 'now' }, getTimezone: jest.fn(() => 'browser'), refresh: false, timeRangeUpdated: jest.fn(() => {}), }; timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); locationUpdates = []; const history = new HistoryWrapper(); history.getHistory().listen((x) => locationUpdates.push(x)); setLocationService(history); }); describe('timeRange', () => { it('should return unparsed when parse is false', () => { timeSrv.setTime({ from: 'now', to: 'now-1h' }); const time = timeSrv.timeRange(); expect(time.raw.from).toBe('now'); expect(time.raw.to).toBe('now-1h'); }); it('should return parsed when parse is true', () => { timeSrv.setTime({ from: 'now', to: 'now-1h' }); const time = timeSrv.timeRange(); expect(isDateTime(time.from)).toBe(true); expect(isDateTime(time.to)).toBe(true); }); }); describe('init time from url', () => { it('should handle relative times', () => { locationService.push('/d/id?from=now-2d&to=now'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.raw.from).toBe('now-2d'); expect(time.raw.to).toBe('now'); }); it('should handle formatted dates', () => { locationService.push('/d/id?from=20140410T052010&to=20140520T031022'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(new Date('2014-04-10T05:20:10Z').getTime()); expect(time.to.valueOf()).toEqual(new Date('2014-05-20T03:10:22Z').getTime()); }); it('should ignore refresh if time absolute', () => { locationService.push('/d/id?from=20140410T052010&to=20140520T031022'); timeSrv = new TimeSrv(new ContextSrvStub() as any); // dashboard saved with refresh on _dashboard.refresh = true; timeSrv.init(_dashboard); expect(timeSrv.refresh).toBe(false); }); it('should handle formatted dates without time', () => { locationService.push('/d/id?from=20140410&to=20140520'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(new Date('2014-04-10T00:00:00Z').getTime()); expect(time.to.valueOf()).toEqual(new Date('2014-05-20T00:00:00Z').getTime()); }); it('should handle epochs', () => { locationService.push('/d/id?from=1410337646373&to=1410337665699'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(1410337646373); expect(time.to.valueOf()).toEqual(1410337665699); }); it('should handle epochs that look like formatted date without time', () => { locationService.push('/d/id?from=20149999&to=20159999'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(20149999); expect(time.to.valueOf()).toEqual(20159999); }); it('should handle epochs that look like formatted date', () => { locationService.push('/d/id?from=201499991234567&to=201599991234567'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(201499991234567); expect(time.to.valueOf()).toEqual(201599991234567); }); it('should handle bad dates', () => { locationService.push('/d/id?from=20151126T00010%3C%2Fp%3E%3Cspan%20class&to=now'); timeSrv = new TimeSrv(new ContextSrvStub() as any); _dashboard.time.from = 'now-6h'; timeSrv.init(_dashboard); expect(timeSrv.time.from).toEqual('now-6h'); expect(timeSrv.time.to).toEqual('now'); }); it('should handle refresh_intervals=null when refresh is enabled', () => { locationService.push('/d/id?refresh=30s'); timeSrv = new TimeSrv(new ContextSrvStub() as any); _dashboard.timepicker = { refresh_intervals: null, }; expect(() => timeSrv.init(_dashboard)).not.toThrow(); }); describe('data point windowing', () => { it('handles time window specfied as interval string', () => { locationService.push('/d/id?time=1410337645000&time.window=10s'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(1410337640000); expect(time.to.valueOf()).toEqual(1410337650000); }); it('handles time window specified in ms', () => { locationService.push('/d/id?time=1410337645000&time.window=10000'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(1410337640000); expect(time.to.valueOf()).toEqual(1410337650000); }); it('corrects inverted from/to dates in ms', () => { locationService.push('/d/id?from=1621436828909&to=1621436818909'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.from.valueOf()).toEqual(1621436818909); expect(time.to.valueOf()).toEqual(1621436828909); }); it('corrects inverted from/to dates as relative times', () => { locationService.push('/d/id?from=now&to=now-1h'); timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); const time = timeSrv.timeRange(); expect(time.raw.from).toBe('now-1h'); expect(time.raw.to).toBe('now'); }); }); }); describe('setTime', () => { it('should return disable refresh if refresh is disabled for any range', () => { _dashboard.refresh = false; timeSrv.setTime({ from: '2011-01-01', to: '2015-01-01' }); expect(_dashboard.refresh).toBe(false); }); it('should restore refresh for absolute time range', () => { _dashboard.refresh = '30s'; timeSrv.setTime({ from: '2011-01-01', to: '2015-01-01' }); expect(_dashboard.refresh).toBe('30s'); }); it('should restore refresh after relative time range is set', () => { _dashboard.refresh = '10s'; timeSrv.setTime({ from: dateTime([2011, 1, 1]), to: dateTime([2015, 1, 1]), }); expect(_dashboard.refresh).toBe(false); timeSrv.setTime({ from: '2011-01-01', to: 'now' }); expect(_dashboard.refresh).toBe('10s'); }); it('should keep refresh after relative time range is changed and now delay exists', () => { _dashboard.refresh = '10s'; timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); expect(_dashboard.refresh).toBe('10s'); }); it('should update location only once for consecutive calls with the same range', () => { timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); expect(locationUpdates.length).toBe(1); }); it('should update location so that bool params are preserved', () => { locationService.partial({ kiosk: true }); timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); expect(locationUpdates[1].search).toEqual('?kiosk&from=now-1h&to=now-10s'); }); it('should not change the URL if the updateUrl param is false', () => { timeSrv.setTime({ from: '1644340584281', to: '1644340584281' }, false); expect(locationUpdates.length).toBe(0); }); }); describe('pauseAutoRefresh', () => { it('should set refresh to empty value', () => { _dashboard.refresh = '10s'; timeSrv.pauseAutoRefresh(); expect(_dashboard.refresh).toBe(''); }); it('should set previousAutoRefresh value', () => { _dashboard.refresh = '10s'; timeSrv.pauseAutoRefresh(); expect(timeSrv.previousAutoRefresh).toBe('10s'); }); }); describe('resumeAutoRefresh', () => { it('should set refresh to empty value', () => { timeSrv.previousAutoRefresh = '10s'; timeSrv.resumeAutoRefresh(); expect(_dashboard.refresh).toBe('10s'); }); }); describe('isRefreshOutsideThreshold', () => { const originalNow = Date.now; beforeEach(() => { Date.now = jest.fn(() => 60000); }); afterEach(() => { Date.now = originalNow; }); describe('when called and current time range is absolute', () => { it('then it should return false', () => { timeSrv.setTime({ from: dateTime(), to: dateTime() }); expect(timeSrv.isRefreshOutsideThreshold(0, 0.05)).toBe(false); }); }); describe('when called and current time range is relative', () => { describe('and last refresh is within threshold', () => { it('then it should return false', () => { timeSrv.setTime({ from: 'now-1m', to: 'now' }); expect(timeSrv.isRefreshOutsideThreshold(57001, 0.05)).toBe(false); }); }); describe('and last refresh is outside the threshold', () => { it('then it should return true', () => { timeSrv.setTime({ from: 'now-1m', to: 'now' }); expect(timeSrv.isRefreshOutsideThreshold(57000, 0.05)).toBe(true); }); }); }); }); });
public/app/features/dashboard/services/TimeSrv.test.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017871364252641797, 0.00017610624490771443, 0.00017362224753014743, 0.0001760360028129071, 0.0000014883695484968484 ]
{ "id": 1, "code_window": [ " permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>;\n", " filter?: FolderPickerFilter;\n", " allowEmpty?: boolean;\n", " showRoot?: boolean;\n", " accessControlMetadata?: boolean;\n", " /**\n", " * Skips loading all folders in order to find the folder matching\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " onClear?: () => void;\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 27 }
package alerting import ( "context" "sync" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" "github.com/grafana/grafana/pkg/models" ) type ruleReader interface { fetch(context.Context) []*Rule } type defaultRuleReader struct { sync.RWMutex sqlStore AlertStore log log.Logger } func newRuleReader(sqlStore AlertStore) *defaultRuleReader { ruleReader := &defaultRuleReader{ sqlStore: sqlStore, log: log.New("alerting.ruleReader"), } return ruleReader } func (arr *defaultRuleReader) fetch(ctx context.Context) []*Rule { cmd := &models.GetAllAlertsQuery{} if err := arr.sqlStore.GetAllAlertQueryHandler(ctx, cmd); err != nil { arr.log.Error("Could not load alerts", "error", err) return []*Rule{} } res := make([]*Rule, 0) for _, ruleDef := range cmd.Result { if model, err := NewRuleFromDBAlert(ctx, arr.sqlStore, ruleDef, false); err != nil { arr.log.Error("Could not build alert model for rule", "ruleId", ruleDef.Id, "error", err) } else { res = append(res, model) } } metrics.MAlertingActiveAlerts.Set(float64(len(res))) return res }
pkg/services/alerting/reader.go
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.000176313376869075, 0.0001737871061777696, 0.00017072164337150753, 0.0001739372091833502, 0.000002011407104873797 ]
{ "id": 1, "code_window": [ " permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>;\n", " filter?: FolderPickerFilter;\n", " allowEmpty?: boolean;\n", " showRoot?: boolean;\n", " accessControlMetadata?: boolean;\n", " /**\n", " * Skips loading all folders in order to find the folder matching\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " onClear?: () => void;\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 27 }
import { css, cx } from '@emotion/css'; import React, { forwardRef, HTMLAttributes } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '../../themes'; export interface Props extends HTMLAttributes<HTMLDivElement> { className?: string; } export const ToolbarButtonRow = forwardRef<HTMLDivElement, Props>(({ className, children, ...rest }, ref) => { const styles = useStyles2(getStyles); return ( <div ref={ref} className={cx(styles.wrapper, className)} {...rest}> {children} </div> ); }); ToolbarButtonRow.displayName = 'ToolbarButtonRow'; const getStyles = (theme: GrafanaTheme2) => ({ wrapper: css` display: flex; > .button-group, > .toolbar-button { margin-left: ${theme.spacing(1)}; &:first-child { margin-left: 0; } } `, });
packages/grafana-ui/src/components/Button/ToolbarButtonRow.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001776666904333979, 0.00017505970026832074, 0.00017098621174227446, 0.00017579295672476292, 0.0000025618421659601154 ]
{ "id": 2, "code_window": [ "\n", " return options;\n", " };\n", "\n", " onFolderChange = (newFolder: SelectableValue<number>) => {\n", " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onFolderChange = (newFolder: SelectableValue<number>, actionMeta: ActionMeta) => {\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 118 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9976859092712402, 0.16879107058048248, 0.00016559986397624016, 0.0015913762617856264, 0.3701475262641907 ]
{ "id": 2, "code_window": [ "\n", " return options;\n", " };\n", "\n", " onFolderChange = (newFolder: SelectableValue<number>) => {\n", " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onFolderChange = (newFolder: SelectableValue<number>, actionMeta: ActionMeta) => {\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 118 }
import { TransformerRegistryItem } from '@grafana/data'; import { filterByValueTransformRegistryItem } from './FilterByValueTransformer/FilterByValueTransformerEditor'; import { heatmapTransformRegistryItem } from './calculateHeatmap/HeatmapTransformerEditor'; import { configFromQueryTransformRegistryItem } from './configFromQuery/ConfigFromQueryTransformerEditor'; import { calculateFieldTransformRegistryItem } from './editors/CalculateFieldTransformerEditor'; import { concatenateTransformRegistryItem } from './editors/ConcatenateTransformerEditor'; import { convertFieldTypeTransformRegistryItem } from './editors/ConvertFieldTypeTransformerEditor'; import { filterFieldsByNameTransformRegistryItem } from './editors/FilterByNameTransformerEditor'; import { filterFramesByRefIdTransformRegistryItem } from './editors/FilterByRefIdTransformerEditor'; import { groupByTransformRegistryItem } from './editors/GroupByTransformerEditor'; import { groupingToMatrixTransformRegistryItem } from './editors/GroupingToMatrixTransformerEditor'; import { histogramTransformRegistryItem } from './editors/HistogramTransformerEditor'; import { labelsToFieldsTransformerRegistryItem } from './editors/LabelsToFieldsTransformerEditor'; import { mergeTransformerRegistryItem } from './editors/MergeTransformerEditor'; import { organizeFieldsTransformRegistryItem } from './editors/OrganizeFieldsTransformerEditor'; import { reduceTransformRegistryItem } from './editors/ReduceTransformerEditor'; import { renameByRegexTransformRegistryItem } from './editors/RenameByRegexTransformer'; import { seriesToFieldsTransformerRegistryItem } from './editors/SeriesToFieldsTransformerEditor'; import { seriesToRowsTransformerRegistryItem } from './editors/SeriesToRowsTransformerEditor'; import { sortByTransformRegistryItem } from './editors/SortByTransformerEditor'; import { extractFieldsTransformRegistryItem } from './extractFields/ExtractFieldsTransformerEditor'; import { fieldLookupTransformRegistryItem } from './lookupGazetteer/FieldLookupTransformerEditor'; import { prepareTimeseriesTransformerRegistryItem } from './prepareTimeSeries/PrepareTimeSeriesEditor'; import { rowsToFieldsTransformRegistryItem } from './rowsToFields/RowsToFieldsTransformerEditor'; import { spatialTransformRegistryItem } from './spatial/SpatialTransformerEditor'; export const getStandardTransformers = (): Array<TransformerRegistryItem<any>> => { return [ reduceTransformRegistryItem, filterFieldsByNameTransformRegistryItem, renameByRegexTransformRegistryItem, filterFramesByRefIdTransformRegistryItem, filterByValueTransformRegistryItem, organizeFieldsTransformRegistryItem, seriesToFieldsTransformerRegistryItem, seriesToRowsTransformerRegistryItem, concatenateTransformRegistryItem, calculateFieldTransformRegistryItem, labelsToFieldsTransformerRegistryItem, groupByTransformRegistryItem, sortByTransformRegistryItem, mergeTransformerRegistryItem, histogramTransformRegistryItem, rowsToFieldsTransformRegistryItem, configFromQueryTransformRegistryItem, prepareTimeseriesTransformerRegistryItem, convertFieldTypeTransformRegistryItem, spatialTransformRegistryItem, fieldLookupTransformRegistryItem, extractFieldsTransformRegistryItem, heatmapTransformRegistryItem, groupingToMatrixTransformRegistryItem, ]; };
public/app/features/transformers/standardTransformers.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017604058666620404, 0.00017378620395902544, 0.00017000347725115716, 0.00017462941468693316, 0.0000022310393887892133 ]
{ "id": 2, "code_window": [ "\n", " return options;\n", " };\n", "\n", " onFolderChange = (newFolder: SelectableValue<number>) => {\n", " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onFolderChange = (newFolder: SelectableValue<number>, actionMeta: ActionMeta) => {\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 118 }
export const storyTpl = ` import React from 'react'; import { <%= name %> } from './<%= name %>'; import { withCenteredStory } from '@grafana/ui/src/utils/storybook/withCenteredStory'; import mdx from './<%= name %>.mdx'; export default { title: '<%= group %>/<%= name %>', component: <%= name %>, decorators: [withCenteredStory], parameters: { docs: { page: mdx, }, }, }; export const Basic = () => { return <<%= name %> />; }; `;
packages/grafana-toolkit/src/cli/templates/story.tsx.template.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.000179798633325845, 0.00017789301637094468, 0.0001748549984768033, 0.0001790254027582705, 0.0000021712689886044245 ]
{ "id": 2, "code_window": [ "\n", " return options;\n", " };\n", "\n", " onFolderChange = (newFolder: SelectableValue<number>) => {\n", " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " onFolderChange = (newFolder: SelectableValue<number>, actionMeta: ActionMeta) => {\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 118 }
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `storageService` // interface, and provide our custom implementation, // which will default to `true` for the correct string-key. // unfortunately, while the typescript-interface exists, // it is not exported from monaco-editor, // so we cannot rely on typescript to make sure // we do it right. all we can do is to manually // lookup the interface, and make sure we code our code right. // our code is a "best effort" approach, // i am not 100% how the `scope` and `target` things work, // but so far it seems to work ok. // i would use an another approach, if there was one available. function makeStorageService() { // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to be true by default strings.set('expandSuggestionDocs', true.toString()); return { // we do not implement the on* handlers onDidChangeValue: (data: unknown): void => undefined, onDidChangeTarget: (data: unknown): void => undefined, onWillSaveState: (data: unknown): void => undefined, get: (key: string, scope: unknown, fallbackValue?: string): string | undefined => { return strings.get(key) ?? fallbackValue; }, getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true'; } else { return fallbackValue; } }, getNumber: (key: string, scope: unknown, fallbackValue?: number): number | undefined => { const val = strings.get(key); if (val !== undefined) { return parseInt(val, 10); } else { return fallbackValue; } }, store: ( key: string, value: string | boolean | number | undefined | null, scope: unknown, target: unknown ): void => { // the interface-docs say if the value is nullish, it should act as delete if (value === null || value === undefined) { strings.delete(key); } else { strings.set(key, value.toString()); } }, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, isNew: (scope: unknown): boolean => { // we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; } let overrideServices: monacoTypes.editor.IEditorOverrideServices | null = null; export function getOverrideServices(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
public/app/plugins/datasource/prometheus/components/monaco-query-field/getOverrideServices.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017388783453498036, 0.00016962731024250388, 0.000163374948897399, 0.00016988081915769726, 0.0000027659229999699164 ]
{ "id": 3, "code_window": [ " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n", " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (actionMeta.action === 'clear' && this.props.onClear) {\n", " this.props.onClear();\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 123 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9534217715263367, 0.043428853154182434, 0.00016491835413035005, 0.0016675593797117472, 0.18981660902500153 ]
{ "id": 3, "code_window": [ " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n", " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (actionMeta.action === 'clear' && this.props.onClear) {\n", " this.props.onClear();\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 123 }
import { css } from '@emotion/css'; import React, { PropsWithChildren } from 'react'; import { GrafanaTheme } from '@grafana/data'; import { useTheme, stylesFactory } from '../../../themes'; interface Props { label: string | undefined; } const stopPropagation = (event: React.MouseEvent) => event.stopPropagation(); export const TimeZoneGroup: React.FC<PropsWithChildren<Props>> = (props) => { const theme = useTheme(); const { children, label } = props; const styles = getStyles(theme); if (!label) { return <div onClick={stopPropagation}>{children}</div>; } return ( <div onClick={stopPropagation}> <div className={styles.header}> <span className={styles.label}>{label}</span> </div> {children} </div> ); }; const getStyles = stylesFactory((theme: GrafanaTheme) => { return { header: css` padding: 7px 10px; width: 100%; border-top: 1px solid ${theme.colors.border1}; text-transform: capitalize; `, label: css` font-size: ${theme.typography.size.sm}; color: ${theme.colors.textWeak}; font-weight: ${theme.typography.weight.semibold}; `, }; });
packages/grafana-ui/src/components/DateTimePickers/TimeZonePicker/TimeZoneGroup.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00042381364619359374, 0.00022233501658774912, 0.00016663005226291716, 0.0001724289613775909, 0.000100792916782666 ]
{ "id": 3, "code_window": [ " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n", " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (actionMeta.action === 'clear' && this.props.onClear) {\n", " this.props.onClear();\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 123 }
#!/usr/bin/env bash # abort if we get any error set -e _tag=$1 _branch="$(git rev-parse --abbrev-ref HEAD)" if [ "${_tag}" == "" ]; then echo "Missing version param. ex './scripts/tag_release.sh v5.1.1'" exit 1 fi if [ "${_branch}" == "main" ]; then echo "you cannot tag releases from the main branch" echo "please checkout the release branch" echo "ex 'git checkout v5.1.x'" exit 1 fi # always make sure to pull latest changes from origin echo "pulling latest changes from ${_branch}" git pull origin "${_branch}" # create signed tag for latest commit git tag -s "${_tag}" -m "release ${_tag}" # verify the signed tag git tag -v "${_tag}" echo "Make sure the tag is signed as expected" echo "press [y] to push the tags" read -n 1 confirm if [ "${confirm}" == "y" ]; then git push origin "${_tag}" else git tag -d "${_tag}" echo "Abort! " fi
scripts/tag_release.sh
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001798411540221423, 0.00017481669783592224, 0.00017137239046860486, 0.0001751146191963926, 0.0000029167724733270006 ]
{ "id": 3, "code_window": [ " if (!newFolder) {\n", " newFolder = { value: 0, label: this.props.rootName };\n", " }\n", "\n", " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (actionMeta.action === 'clear' && this.props.onClear) {\n", " this.props.onClear();\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 123 }
import React from 'react'; import { DataSourcePluginOptionsEditorProps, SelectableValue } from '@grafana/data'; import { DataSourceHttpSettings, InlineFormLabel, Select } from '@grafana/ui'; import { AlertManagerDataSourceJsonData, AlertManagerImplementation } from './types'; export type Props = DataSourcePluginOptionsEditorProps<AlertManagerDataSourceJsonData>; const IMPL_OPTIONS: SelectableValue[] = [ { value: AlertManagerImplementation.cortex, label: 'Cortex', description: `https://cortexmetrics.io/`, }, { value: AlertManagerImplementation.prometheus, label: 'Prometheus', description: 'https://prometheus.io/. Does not support editing configuration via API, so contact points and notification policies are read-only.', }, ]; export const ConfigEditor: React.FC<Props> = ({ options, onOptionsChange }) => { return ( <> <h3 className="page-heading">Alertmanager</h3> <div className="gf-form-group"> <div className="gf-form-inline"> <div className="gf-form"> <InlineFormLabel width={13}>Implementation</InlineFormLabel> <Select width={40} options={IMPL_OPTIONS} value={options.jsonData.implementation || AlertManagerImplementation.cortex} onChange={(value) => onOptionsChange({ ...options, jsonData: { ...options.jsonData, implementation: value.value as AlertManagerImplementation, }, }) } /> </div> </div> </div> <DataSourceHttpSettings defaultUrl={''} dataSourceConfig={options} showAccessOptions={true} onChange={onOptionsChange} /> </> ); };
public/app/plugins/datasource/alertmanager/ConfigEditor.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0002140315918950364, 0.00018079667643178254, 0.00017230848607141525, 0.00017482998373452574, 0.000014925805771781597 ]
{ "id": 4, "code_window": [ " };\n", "\n", " createNewFolder = async (folderName: string) => {\n", " // @ts-ignore\n", " const newFolder = await createFolder({ title: folderName });\n", " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 132 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9984917640686035, 0.4323495626449585, 0.0001654227962717414, 0.0008804455865174532, 0.47314706444740295 ]
{ "id": 4, "code_window": [ " };\n", "\n", " createNewFolder = async (folderName: string) => {\n", " // @ts-ignore\n", " const newFolder = await createFolder({ title: folderName });\n", " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 132 }
--- name: Accessibility issue about: Help make Grafana be better at keyboard navigation, screen-readable and accessible to all. labels: 'type: accessibility' --- <!-- Please only use this template for submitting accessibility issues. This is a new feature area for Grafana that we want to improve. We have long way to go to really improve accessibility and would like your help to know where to start. --> **Steps to reproduce**: **Actual Result**: **Expected Result** **Relevant WCAG Criteria:** [#.#.# WCAG Criterion](link to https://www.w3.org/WAI/WCAG21/quickref/?versions=2.0) **Environment**: - Grafana version: - Data source type & version: - User OS & Browser: - Others:
.github/ISSUE_TEMPLATE/2-accessibility.md
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017454050248488784, 0.0001717900886433199, 0.0001675003150012344, 0.00017332947754766792, 0.0000030733615403732983 ]
{ "id": 4, "code_window": [ " };\n", "\n", " createNewFolder = async (folderName: string) => {\n", " // @ts-ignore\n", " const newFolder = await createFolder({ title: folderName });\n", " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 132 }
import React, { FC, ReactElement } from 'react'; import tinycolor from 'tinycolor2'; import { DisplayValue, Field, formattedValueToString } from '@grafana/data'; import { getTextColorForBackground, getCellLinks } from '../../utils'; import { CellActions } from './CellActions'; import { TableStyles } from './styles'; import { TableCellDisplayMode, TableCellProps, TableFieldOptions } from './types'; export const DefaultCell: FC<TableCellProps> = (props) => { const { field, cell, tableStyles, row, cellProps } = props; const inspectEnabled = Boolean((field.config.custom as TableFieldOptions)?.inspect); const displayValue = field.display!(cell.value); let value: string | ReactElement; if (React.isValidElement(cell.value)) { value = cell.value; } else { value = formattedValueToString(displayValue); } const showFilters = field.config.filterable; const showActions = (showFilters && cell.value !== undefined) || inspectEnabled; const cellStyle = getCellStyle(tableStyles, field, displayValue, inspectEnabled); const { link, onClick } = getCellLinks(field, row); return ( <div {...cellProps} className={cellStyle}> {!link && <div className={tableStyles.cellText}>{value}</div>} {link && ( <a href={link.href} onClick={onClick} target={link.target} title={link.title} className={tableStyles.cellLink}> {value} </a> )} {showActions && <CellActions {...props} previewMode="text" />} </div> ); }; function getCellStyle( tableStyles: TableStyles, field: Field, displayValue: DisplayValue, disableOverflowOnHover = false ) { if (field.config.custom?.displayMode === TableCellDisplayMode.ColorText) { return tableStyles.buildCellContainerStyle(displayValue.color, undefined, !disableOverflowOnHover); } if (field.config.custom?.displayMode === TableCellDisplayMode.ColorBackgroundSolid) { const bgColor = tinycolor(displayValue.color); const textColor = getTextColorForBackground(displayValue.color!); return tableStyles.buildCellContainerStyle(textColor, bgColor.toRgbString(), !disableOverflowOnHover); } if (field.config.custom?.displayMode === TableCellDisplayMode.ColorBackground) { const themeFactor = tableStyles.theme.isDark ? 1 : -0.7; const bgColor2 = tinycolor(displayValue.color) .darken(10 * themeFactor) .spin(5) .toRgbString(); const textColor = getTextColorForBackground(displayValue.color!); return tableStyles.buildCellContainerStyle( textColor, `linear-gradient(120deg, ${bgColor2}, ${displayValue.color})`, !disableOverflowOnHover ); } return disableOverflowOnHover ? tableStyles.cellContainerNoOverflow : tableStyles.cellContainer; }
packages/grafana-ui/src/components/Table/DefaultCell.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0002223402407253161, 0.00018166680820286274, 0.00017146245227195323, 0.0001766654459061101, 0.000015515235645580105 ]
{ "id": 4, "code_window": [ " };\n", "\n", " createNewFolder = async (folderName: string) => {\n", " // @ts-ignore\n", " const newFolder = await createFolder({ title: folderName });\n", " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 132 }
import { css } from '@emotion/css'; import React, { FC, useCallback, useEffect, useRef, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { useLocalStorage } from 'react-use'; import { GrafanaTheme, PanelData, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { Button, CustomScrollbar, FilterInput, RadioButtonGroup, useStyles } from '@grafana/ui'; import { Field } from '@grafana/ui/src/components/Forms/Field'; import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants'; import { PanelLibraryOptionsGroup } from 'app/features/library-panels/components/PanelLibraryOptionsGroup/PanelLibraryOptionsGroup'; import { VisualizationSuggestions } from 'app/features/panel/components/VizTypePicker/VisualizationSuggestions'; import { VizTypeChangeDetails } from 'app/features/panel/components/VizTypePicker/types'; import { VizTypePicker } from '../../../panel/components/VizTypePicker/VizTypePicker'; import { changePanelPlugin } from '../../../panel/state/actions'; import { PanelModel } from '../../state/PanelModel'; import { getPanelPluginWithFallback } from '../../state/selectors'; import { toggleVizPicker } from './state/reducers'; import { VisualizationSelectPaneTab } from './types'; interface Props { panel: PanelModel; data?: PanelData; } export const VisualizationSelectPane: FC<Props> = ({ panel, data }) => { const plugin = useSelector(getPanelPluginWithFallback(panel.type)); const [searchQuery, setSearchQuery] = useState(''); const [listMode, setListMode] = useLocalStorage( LS_VISUALIZATION_SELECT_TAB_KEY, VisualizationSelectPaneTab.Visualizations ); const dispatch = useDispatch(); const styles = useStyles(getStyles); const searchRef = useRef<HTMLInputElement | null>(null); const onVizChange = useCallback( (pluginChange: VizTypeChangeDetails) => { dispatch(changePanelPlugin({ panel: panel, ...pluginChange })); // close viz picker unless a mod key is pressed while clicking if (!pluginChange.withModKey) { dispatch(toggleVizPicker(false)); } }, [dispatch, panel] ); // Give Search input focus when using radio button switch list mode useEffect(() => { if (searchRef.current) { searchRef.current.focus(); } }, [listMode]); const onCloseVizPicker = () => { dispatch(toggleVizPicker(false)); }; if (!plugin) { return null; } const radioOptions: Array<SelectableValue<VisualizationSelectPaneTab>> = [ { label: 'Visualizations', value: VisualizationSelectPaneTab.Visualizations }, { label: 'Suggestions', value: VisualizationSelectPaneTab.Suggestions }, { label: 'Library panels', value: VisualizationSelectPaneTab.LibraryPanels, description: 'Reusable panels you can share between multiple dashboards.', }, ]; return ( <div className={styles.openWrapper}> <div className={styles.formBox}> <div className={styles.searchRow}> <FilterInput value={searchQuery} onChange={setSearchQuery} ref={searchRef} autoFocus={true} placeholder="Search for..." /> <Button title="Close" variant="secondary" icon="angle-up" className={styles.closeButton} aria-label={selectors.components.PanelEditor.toggleVizPicker} onClick={onCloseVizPicker} /> </div> <Field className={styles.customFieldMargin}> <RadioButtonGroup options={radioOptions} value={listMode} onChange={setListMode} fullWidth /> </Field> </div> <div className={styles.scrollWrapper}> <CustomScrollbar autoHeightMin="100%"> <div className={styles.scrollContent}> {listMode === VisualizationSelectPaneTab.Visualizations && ( <VizTypePicker current={plugin.meta} onChange={onVizChange} searchQuery={searchQuery} data={data} onClose={() => {}} /> )} {listMode === VisualizationSelectPaneTab.Suggestions && ( <VisualizationSuggestions current={plugin.meta} onChange={onVizChange} searchQuery={searchQuery} panel={panel} data={data} onClose={() => {}} /> )} {listMode === VisualizationSelectPaneTab.LibraryPanels && ( <PanelLibraryOptionsGroup searchQuery={searchQuery} panel={panel} key="Panel Library" /> )} </div> </CustomScrollbar> </div> </div> ); }; VisualizationSelectPane.displayName = 'VisualizationSelectPane'; const getStyles = (theme: GrafanaTheme) => { return { icon: css` color: ${theme.palette.gray33}; `, wrapper: css` display: flex; flex-direction: column; flex: 1 1 0; height: 100%; `, vizButton: css` text-align: left; `, scrollWrapper: css` flex-grow: 1; min-height: 0; `, scrollContent: css` padding: ${theme.spacing.sm}; `, openWrapper: css` display: flex; flex-direction: column; flex: 1 1 100%; height: 100%; background: ${theme.colors.bg1}; border: 1px solid ${theme.colors.border1}; `, searchRow: css` display: flex; margin-bottom: ${theme.spacing.sm}; `, closeButton: css` margin-left: ${theme.spacing.sm}; `, customFieldMargin: css` margin-bottom: ${theme.spacing.sm}; `, formBox: css` padding: ${theme.spacing.sm}; padding-bottom: 0; `, }; };
public/app/features/dashboard/components/PanelEditor/VisualizationSelectPane.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00018013996304944158, 0.0001763386680977419, 0.0001729665818857029, 0.00017641109297983348, 0.0000017678563608569675 ]
{ "id": 5, "code_window": [ " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n", " folder = { value: newFolder.id, label: newFolder.title };\n", " await this.onFolderChange(folder);\n", " } else {\n", " appEvents.emit(AppEvents.alertError, ['Folder could not be created']);\n", " }\n", "\n", " return folder;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n", " () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! })\n", " );\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 138 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9973592162132263, 0.09481237083673477, 0.00016507112013641745, 0.00017948087770491838, 0.2639029622077942 ]
{ "id": 5, "code_window": [ " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n", " folder = { value: newFolder.id, label: newFolder.title };\n", " await this.onFolderChange(folder);\n", " } else {\n", " appEvents.emit(AppEvents.alertError, ['Folder could not be created']);\n", " }\n", "\n", " return folder;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n", " () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! })\n", " );\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 138 }
.add-data-source-header { margin-bottom: $space-xl; padding-top: $spacer; text-align: center; } .add-data-source-search { display: flex; justify-content: center; margin-bottom: $space-lg; } .add-data-source-category { margin-bottom: $space-md; } .add-data-source-category__header { font-size: $font-size-h5; margin-bottom: $space-sm; } .add-data-source-item { padding: $space-md; display: flex; align-items: center; cursor: pointer; background: $panel-editor-viz-item-bg; border: 1px solid transparent; border-radius: 3px; margin-bottom: $space-xxs; &:hover { box-shadow: $panel-editor-viz-item-shadow-hover; background: $panel-editor-viz-item-bg-hover; border: $panel-editor-viz-item-border-hover; color: $text-color-strong; .add-data-source-item-actions { opacity: 1; transition: 0.15s opacity ease-in-out; } } } .add-data-source-item-text-wrapper { display: flex; flex-direction: column; flex-grow: 1; } .add-data-source-item-desc { font-size: $font-size-sm; color: $text-color-weak; } .add-data-source-item-badge { margin-top: 6px; } .add-data-source-item-text { font-size: $font-size-h5; } .add-data-source-item-logo { margin-right: $space-lg; margin-left: $space-sm; width: 55px; max-height: 55px; } .add-data-source-item-actions { opacity: 0; padding-left: $space-md; display: flex; align-items: center; > button { margin-left: $space-md; cursor: pointer; } } .add-datasource-item-actions__btn-icon { margin-left: $space-sm; } .add-data-source-more { text-align: center; margin: $space-xl; }
public/sass/components/_add_data_source.scss
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017599677084945142, 0.00017448642756789923, 0.0001682207075646147, 0.0001752043899614364, 0.0000021730156731791794 ]
{ "id": 5, "code_window": [ " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n", " folder = { value: newFolder.id, label: newFolder.title };\n", " await this.onFolderChange(folder);\n", " } else {\n", " appEvents.emit(AppEvents.alertError, ['Folder could not be created']);\n", " }\n", "\n", " return folder;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n", " () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! })\n", " );\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 138 }
// Copyright (c) 2017 Uber Technologies, Inc. // // 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 Positions from './Positions'; describe('Positions', () => { const bufferLen = 1; const getHeight = (i) => i * 2 + 2; let ps; beforeEach(() => { ps = new Positions(bufferLen); ps.profileData(10); }); describe('constructor()', () => { it('intializes member variables correctly', () => { ps = new Positions(1); expect(ps.ys).toEqual([]); expect(ps.heights).toEqual([]); expect(ps.bufferLen).toBe(1); expect(ps.dataLen).toBe(-1); expect(ps.lastI).toBe(-1); }); }); describe('profileData(...)', () => { it('manages increases in data length correctly', () => { expect(ps.dataLen).toBe(10); expect(ps.ys.length).toBe(10); expect(ps.heights.length).toBe(10); expect(ps.lastI).toBe(-1); }); it('manages decreases in data length correctly', () => { ps.lastI = 9; ps.profileData(5); expect(ps.dataLen).toBe(5); expect(ps.ys.length).toBe(5); expect(ps.heights.length).toBe(5); expect(ps.lastI).toBe(4); }); it('does nothing when data length is unchanged', () => { expect(ps.dataLen).toBe(10); expect(ps.ys.length).toBe(10); expect(ps.heights.length).toBe(10); expect(ps.lastI).toBe(-1); ps.profileData(10); expect(ps.dataLen).toBe(10); expect(ps.ys.length).toBe(10); expect(ps.heights.length).toBe(10); expect(ps.lastI).toBe(-1); }); }); describe('calcHeights()', () => { it('updates lastI correctly', () => { ps.calcHeights(1, getHeight); expect(ps.lastI).toBe(bufferLen + 1); }); it('saves the heights and y-values up to `lastI <= max + bufferLen`', () => { const ys = [0, 2, 6, 12]; ys.length = 10; const heights = [2, 4, 6]; heights.length = 10; ps.calcHeights(1, getHeight); expect(ps.ys).toEqual(ys); expect(ps.heights).toEqual(heights); }); it('does nothing when `max + buffer <= lastI`', () => { ps.calcHeights(2, getHeight); const ys = ps.ys.slice(); const heights = ps.heights.slice(); ps.calcHeights(1, getHeight); expect(ps.ys).toEqual(ys); expect(ps.heights).toEqual(heights); }); describe('recalculates values up to `max + bufferLen` when `max + buffer <= lastI` and `forcedLastI = 0` is passed', () => { beforeEach(() => { // the initial state for the test ps.calcHeights(2, getHeight); }); it('test-case has a valid initial state', () => { const initialYs = [0, 2, 6, 12, 20]; initialYs.length = 10; const initialHeights = [2, 4, 6, 8]; initialHeights.length = 10; expect(ps.ys).toEqual(initialYs); expect(ps.heights).toEqual(initialHeights); expect(ps.lastI).toBe(3); }); it('recalcualtes the y-values correctly', () => { // recalc a sub-set of the calcualted values using a different getHeight ps.calcHeights(1, () => 2, 0); const ys = [0, 2, 4, 6, 20]; ys.length = 10; expect(ps.ys).toEqual(ys); }); it('recalcualtes the heights correctly', () => { // recalc a sub-set of the calcualted values using a different getHeight ps.calcHeights(1, () => 2, 0); const heights = [2, 2, 2, 8]; heights.length = 10; expect(ps.heights).toEqual(heights); }); it('saves lastI correctly', () => { // recalc a sub-set of the calcualted values ps.calcHeights(1, getHeight, 0); expect(ps.lastI).toBe(2); }); }); it('limits caclulations to the known data length', () => { ps.calcHeights(999, getHeight); expect(ps.lastI).toBe(ps.dataLen - 1); }); }); describe('calcYs()', () => { it('scans forward until `yValue` is met or exceeded', () => { ps.calcYs(11, getHeight); const ys = [0, 2, 6, 12, 20]; ys.length = 10; const heights = [2, 4, 6, 8]; heights.length = 10; expect(ps.ys).toEqual(ys); expect(ps.heights).toEqual(heights); }); it('exits early if the known y-values exceed `yValue`', () => { ps.calcYs(11, getHeight); const spy = jest.spyOn(ps, 'calcHeights'); ps.calcYs(10, getHeight); expect(spy).not.toHaveBeenCalled(); }); it('exits when exceeds the data length even if yValue is unmet', () => { ps.calcYs(999, getHeight); expect(ps.ys[ps.ys.length - 1]).toBeLessThan(999); }); }); describe('findFloorIndex()', () => { beforeEach(() => { ps.calcYs(11, getHeight); // Note: ps.ys = [0, 2, 6, 12, 20, undefined x 5]; }); it('scans y-values for index that equals or precedes `yValue`', () => { let i = ps.findFloorIndex(3, getHeight); expect(i).toBe(1); i = ps.findFloorIndex(21, getHeight); expect(i).toBe(4); ps.calcYs(999, getHeight); i = ps.findFloorIndex(11, getHeight); expect(i).toBe(2); i = ps.findFloorIndex(12, getHeight); expect(i).toBe(3); i = ps.findFloorIndex(20, getHeight); expect(i).toBe(4); }); it('is robust against non-positive y-values', () => { let i = ps.findFloorIndex(0, getHeight); expect(i).toBe(0); i = ps.findFloorIndex(-10, getHeight); expect(i).toBe(0); }); it('scans no further than dataLen even if `yValue` is unmet', () => { const i = ps.findFloorIndex(999, getHeight); expect(i).toBe(ps.lastI); }); }); describe('getEstimatedHeight()', () => { const simpleGetHeight = () => 2; beforeEach(() => { ps.calcYs(5, simpleGetHeight); // Note: ps.ys = [0, 2, 4, 6, 8, undefined x 5]; }); it('returns the estimated max height, surpassing known values', () => { const estHeight = ps.getEstimatedHeight(); expect(estHeight).toBeGreaterThan(ps.heights[ps.lastI]); }); it('returns the known max height, if all heights have been calculated', () => { ps.calcYs(999, simpleGetHeight); const totalHeight = ps.getEstimatedHeight(); expect(totalHeight).toBeGreaterThan(ps.heights[ps.heights.length - 1]); }); }); describe('confirmHeight()', () => { const simpleGetHeight = () => 2; beforeEach(() => { ps.calcYs(5, simpleGetHeight); // Note: ps.ys = [0, 2, 4, 6, 8, undefined x 5]; }); it('calculates heights up to and including `_i` if necessary', () => { const startNumHeights = ps.heights.filter(Boolean).length; const calcHeightsSpy = jest.spyOn(ps, 'calcHeights'); ps.confirmHeight(7, simpleGetHeight); const endNumHeights = ps.heights.filter(Boolean).length; expect(startNumHeights).toBeLessThan(endNumHeights); expect(calcHeightsSpy).toHaveBeenCalled(); }); it('invokes `heightGetter` at `_i` to compare result with known height', () => { const getHeightSpy = jest.fn(simpleGetHeight); ps.confirmHeight(ps.lastI - 1, getHeightSpy); expect(getHeightSpy).toHaveBeenCalled(); }); it('cascades difference in observed height vs known height to known y-values', () => { const getLargerHeight = () => simpleGetHeight() + 2; const knownYs = ps.ys.slice(); const expectedYValues = knownYs.map((value) => (value ? value + 2 : value)); ps.confirmHeight(0, getLargerHeight); expect(ps.ys).toEqual(expectedYValues); }); }); });
packages/jaeger-ui-components/src/TraceTimelineViewer/ListView/Positions.test.js
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017959336400963366, 0.00017711115651763976, 0.00017309792747255415, 0.00017741884221322834, 0.0000015115969063117518 ]
{ "id": 5, "code_window": [ " let folder = { value: -1, label: 'Not created' };\n", " if (newFolder.id > -1) {\n", " appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']);\n", " folder = { value: newFolder.id, label: newFolder.title };\n", " await this.onFolderChange(folder);\n", " } else {\n", " appEvents.emit(AppEvents.alertError, ['Folder could not be created']);\n", " }\n", "\n", " return folder;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.setState(\n", " {\n", " folder: newFolder,\n", " },\n", " () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! })\n", " );\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 138 }
package channels import ( "context" "errors" "strings" "time" "github.com/prometheus/alertmanager/notify" "github.com/prometheus/alertmanager/template" "github.com/prometheus/alertmanager/types" "github.com/prometheus/common/model" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/notifications" "github.com/grafana/grafana/pkg/setting" ) const ( // victoropsAlertStateCritical - Victorops uses "CRITICAL" string to indicate "Alerting" state victoropsAlertStateCritical = "CRITICAL" // victoropsAlertStateRecovery - VictorOps "RECOVERY" message type victoropsAlertStateRecovery = "RECOVERY" ) type VictorOpsConfig struct { *NotificationChannelConfig URL string MessageType string } func VictorOpsFactory(fc FactoryConfig) (NotificationChannel, error) { cfg, err := NewVictorOpsConfig(fc.Config) if err != nil { return nil, receiverInitError{ Reason: err.Error(), Cfg: *fc.Config, } } return NewVictoropsNotifier(cfg, fc.NotificationService, fc.Template), nil } func NewVictorOpsConfig(config *NotificationChannelConfig) (*VictorOpsConfig, error) { url := config.Settings.Get("url").MustString() if url == "" { return nil, errors.New("could not find victorops url property in settings") } return &VictorOpsConfig{ NotificationChannelConfig: config, URL: url, MessageType: config.Settings.Get("messageType").MustString(), }, nil } // NewVictoropsNotifier creates an instance of VictoropsNotifier that // handles posting notifications to Victorops REST API func NewVictoropsNotifier(config *VictorOpsConfig, ns notifications.WebhookSender, t *template.Template) *VictoropsNotifier { return &VictoropsNotifier{ Base: NewBase(&models.AlertNotification{ Uid: config.UID, Name: config.Name, Type: config.Type, DisableResolveMessage: config.DisableResolveMessage, Settings: config.Settings, }), URL: config.URL, MessageType: config.MessageType, log: log.New("alerting.notifier.victorops"), ns: ns, tmpl: t, } } // VictoropsNotifier defines URL property for Victorops REST API // and handles notification process by formatting POST body according to // Victorops specifications (http://victorops.force.com/knowledgebase/articles/Integration/Alert-Ingestion-API-Documentation/) type VictoropsNotifier struct { *Base URL string MessageType string log log.Logger ns notifications.WebhookSender tmpl *template.Template } // Notify sends notification to Victorops via POST to URL endpoint func (vn *VictoropsNotifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) { vn.log.Debug("Executing victorops notification", "notification", vn.Name) var tmplErr error tmpl, _ := TmplText(ctx, vn.tmpl, as, vn.log, &tmplErr) messageType := strings.ToUpper(tmpl(vn.MessageType)) if messageType == "" { messageType = victoropsAlertStateCritical } alerts := types.Alerts(as...) if alerts.Status() == model.AlertResolved { messageType = victoropsAlertStateRecovery } groupKey, err := notify.ExtractGroupKey(ctx) if err != nil { return false, err } bodyJSON := simplejson.New() bodyJSON.Set("message_type", messageType) bodyJSON.Set("entity_id", groupKey.Hash()) bodyJSON.Set("entity_display_name", tmpl(DefaultMessageTitleEmbed)) bodyJSON.Set("timestamp", time.Now().Unix()) bodyJSON.Set("state_message", tmpl(`{{ template "default.message" . }}`)) bodyJSON.Set("monitoring_tool", "Grafana v"+setting.BuildVersion) ruleURL := joinUrlPath(vn.tmpl.ExternalURL.String(), "/alerting/list", vn.log) bodyJSON.Set("alert_url", ruleURL) if tmplErr != nil { vn.log.Warn("failed to template VictorOps message", "err", tmplErr.Error()) tmplErr = nil } u := tmpl(vn.URL) if tmplErr != nil { vn.log.Info("failed to template VictorOps URL", "err", tmplErr.Error(), "fallback", vn.URL) u = vn.URL } b, err := bodyJSON.MarshalJSON() if err != nil { return false, err } cmd := &models.SendWebhookSync{ Url: u, Body: string(b), } if err := vn.ns.SendWebhookSync(ctx, cmd); err != nil { vn.log.Error("Failed to send Victorops notification", "error", err, "webhook", vn.Name) return false, err } return true, nil } func (vn *VictoropsNotifier) SendResolved() bool { return !vn.GetDisableResolveMessage() }
pkg/services/ngalert/notifier/channels/victorops.go
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017764567746780813, 0.00017168129852507263, 0.00016422412591055036, 0.00017289344395976514, 0.0000037108586639078567 ]
{ "id": 6, "code_window": [ " );\n", " };\n", "\n", " render() {\n", " const { folder } = this.state;\n", " const { enableCreateNew, inputId } = this.props;\n", "\n", " return (\n", " <div data-testid={selectors.components.FolderPicker.containerV2}>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { enableCreateNew, inputId, onClear } = this.props;\n", " const isClearable = typeof onClear === 'function';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 192 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9989614486694336, 0.3455936014652252, 0.00016664291615597904, 0.007198018487542868, 0.4532550275325775 ]
{ "id": 6, "code_window": [ " );\n", " };\n", "\n", " render() {\n", " const { folder } = this.state;\n", " const { enableCreateNew, inputId } = this.props;\n", "\n", " return (\n", " <div data-testid={selectors.components.FolderPicker.containerV2}>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { enableCreateNew, inputId, onClear } = this.props;\n", " const isClearable = typeof onClear === 'function';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 192 }
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import * as runtimeMock from '@grafana/runtime'; import { LoginPage } from './LoginPage'; const postMock = jest.fn(); jest.mock('@grafana/runtime', () => ({ __esModule: true, getBackendSrv: () => ({ post: postMock, }), config: { loginError: false, buildInfo: { version: 'v1.0', commit: '1', env: 'production', edition: 'Open Source', }, licenseInfo: { stateInfo: '', licenseUrl: '', }, appSubUrl: '', verifyEmailEnabled: false, }, })); describe('Login Page', () => { beforeEach(() => { jest.resetAllMocks(); }); it('renders correctly', () => { render(<LoginPage />); expect(screen.getByRole('heading', { name: 'Welcome to Grafana' })).toBeInTheDocument(); expect(screen.getByRole('textbox', { name: 'Username input field' })).toBeInTheDocument(); expect(screen.getByLabelText('Password input field')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Login button' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Forgot your password?' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Forgot your password?' })).toHaveAttribute( 'href', '/user/password/send-reset-email' ); expect(screen.getByRole('link', { name: 'Sign up' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Sign up' })).toHaveAttribute('href', '/signup'); }); it('should pass validation checks for username field', async () => { render(<LoginPage />); fireEvent.click(screen.getByRole('button', { name: 'Login button' })); expect(await screen.findByText('Email or username is required')).toBeInTheDocument(); await userEvent.type(screen.getByRole('textbox', { name: 'Username input field' }), 'admin'); await waitFor(() => expect(screen.queryByText('Email or username is required')).not.toBeInTheDocument()); }); it('should pass validation checks for password field', async () => { render(<LoginPage />); fireEvent.click(screen.getByRole('button', { name: 'Login button' })); expect(await screen.findByText('Password is required')).toBeInTheDocument(); await userEvent.type(screen.getByLabelText('Password input field'), 'admin'); await waitFor(() => expect(screen.queryByText('Password is required')).not.toBeInTheDocument()); }); it('should navigate to default url if credentials is valid', async () => { Object.defineProperty(window, 'location', { value: { assign: jest.fn(), }, }); postMock.mockResolvedValueOnce({ message: 'Logged in' }); render(<LoginPage />); await userEvent.type(screen.getByLabelText('Username input field'), 'admin'); await userEvent.type(screen.getByLabelText('Password input field'), 'test'); fireEvent.click(screen.getByLabelText('Login button')); await waitFor(() => expect(postMock).toHaveBeenCalledWith('/login', { password: 'test', user: 'admin' })); expect(window.location.assign).toHaveBeenCalledWith('/'); }); it('renders social logins correctly', () => { (runtimeMock as any).config.oauth = { okta: { name: 'Okta Test', icon: 'signin', }, }; render(<LoginPage />); expect(screen.getByRole('link', { name: 'Sign in with Okta Test' })).toBeInTheDocument(); }); });
public/app/core/components/Login/LoginPage.test.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.9959806203842163, 0.4520665109157562, 0.00017053470946848392, 0.0037505379877984524, 0.4943752884864807 ]
{ "id": 6, "code_window": [ " );\n", " };\n", "\n", " render() {\n", " const { folder } = this.state;\n", " const { enableCreateNew, inputId } = this.props;\n", "\n", " return (\n", " <div data-testid={selectors.components.FolderPicker.containerV2}>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { enableCreateNew, inputId, onClear } = this.props;\n", " const isClearable = typeof onClear === 'function';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 192 }
import { Meta, Story } from '@storybook/react'; import React from 'react'; import { RangeSlider } from '@grafana/ui'; import { RangeSliderProps } from './types'; export default { title: 'Forms/Slider/Range', component: RangeSlider, parameters: { controls: { exclude: ['tooltipAlwaysVisible'], }, }, argTypes: { isStep: { name: 'step' }, orientation: { control: { type: 'select', options: ['horizontal', 'vertical'] } }, }, } as Meta; interface StoryProps extends Partial<RangeSliderProps> { isStep: boolean; } export const Basic: Story<StoryProps> = (args) => { return ( <div style={{ width: '200px', height: '200px' }}> <RangeSlider step={args.isStep ? 10 : undefined} value={[10, 20]} min={args.min as number} max={args.max as number} {...args} /> </div> ); }; Basic.args = { min: 0, max: 100, isStep: false, orientation: 'horizontal', reverse: false, };
packages/grafana-ui/src/components/Slider/RangeSlider.story.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00020789676636923105, 0.00017979383119381964, 0.0001687919138930738, 0.00017386479885317385, 0.000014209112123353407 ]
{ "id": 6, "code_window": [ " );\n", " };\n", "\n", " render() {\n", " const { folder } = this.state;\n", " const { enableCreateNew, inputId } = this.props;\n", "\n", " return (\n", " <div data-testid={selectors.components.FolderPicker.containerV2}>\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const { enableCreateNew, inputId, onClear } = this.props;\n", " const isClearable = typeof onClear === 'function';\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "replace", "edit_start_line_idx": 192 }
import client from './client'; import * as setup from './setup'; describe('GET /api/search', () => { const state = {}; beforeAll(async () => { state = await setup.ensureState({ orgName: 'api-test-org', users: [{ user: setup.admin, role: 'Admin' }], admin: setup.admin, dashboards: [ { title: 'Dashboard in root no permissions', uid: 'AAA', }, ], }); }); describe('With admin user', () => { it('should return all dashboards', async () => { let rsp = await client.callAs(state.admin).get('/api/search'); expect(rsp.data).toHaveLength(1); }); }); });
devenv/e2e-api-tests/search.test.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0002880341198761016, 0.00020892715838272125, 0.00016578439681325108, 0.00017296297301072627, 0.00005601378143182956 ]
{ "id": 7, "code_window": [ " allowCustomValue={enableCreateNew}\n", " loadOptions={this.debouncedSearch}\n", " onChange={this.onFolderChange}\n", " onCreateOption={this.createNewFolder}\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isClearable={isClearable}\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 207 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.8321871757507324, 0.03578376770019531, 0.0001640974951442331, 0.00021101928723510355, 0.1660713106393814 ]
{ "id": 7, "code_window": [ " allowCustomValue={enableCreateNew}\n", " loadOptions={this.debouncedSearch}\n", " onChange={this.onFolderChange}\n", " onCreateOption={this.createNewFolder}\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isClearable={isClearable}\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 207 }
import { FieldColorModeId, FieldConfigProperty, FieldMatcherID, PanelModel } from '@grafana/data'; import { LegendDisplayMode } from '@grafana/schema'; import { PieChartPanelChangedHandler } from './migrations'; import { PieChartLabels } from './types'; describe('PieChart -> PieChartV2 migrations', () => { it('only migrates old piechart', () => { const panel = {} as PanelModel; const options = PieChartPanelChangedHandler(panel, 'some-panel-id', {}); expect(options).toEqual({}); }); it('correctly assigns color overrides', () => { const panel = { options: {} } as PanelModel; const oldPieChartOptions = { angular: { aliasColors: { x: '#fff' }, }, }; PieChartPanelChangedHandler(panel, 'grafana-piechart-panel', oldPieChartOptions); expect(panel.fieldConfig.overrides).toContainEqual({ matcher: { id: FieldMatcherID.byName, options: 'x', }, properties: [ { id: FieldConfigProperty.Color, value: { mode: FieldColorModeId.Fixed, fixedColor: '#fff', }, }, ], }); }); it('correctly sets sum calculation', () => { const panel = { options: {} } as PanelModel; const oldPieChartOptions = { angular: { valueName: 'total' }, }; const options = PieChartPanelChangedHandler(panel, 'grafana-piechart-panel', oldPieChartOptions); expect(options).toMatchObject({ reduceOptions: { calcs: ['sum'] } }); }); it('correctly sets labels when old PieChart has legend on graph', () => { const panel = { options: {} } as PanelModel; const oldPieChartOptions = { angular: { legendType: 'On graph', legend: { values: true }, }, }; const options = PieChartPanelChangedHandler(panel, 'grafana-piechart-panel', oldPieChartOptions); expect(options).toMatchObject({ displayLabels: [PieChartLabels.Name, PieChartLabels.Value] }); }); it('hides the legend when no legend values are selected', () => { const panel = { options: {} } as PanelModel; const oldPieChartOptions = { angular: { legendType: 'On graph', legend: {}, }, }; const options = PieChartPanelChangedHandler(panel, 'grafana-piechart-panel', oldPieChartOptions); expect(options).toMatchObject({ legend: { displayMode: LegendDisplayMode.Hidden } }); }); });
public/app/plugins/panel/piechart/migrations.test.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001752098323777318, 0.00017179507995024323, 0.0001679532288108021, 0.00017146518803201616, 0.0000025409374302398646 ]
{ "id": 7, "code_window": [ " allowCustomValue={enableCreateNew}\n", " loadOptions={this.debouncedSearch}\n", " onChange={this.onFolderChange}\n", " onCreateOption={this.createNewFolder}\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isClearable={isClearable}\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 207 }
import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { Provider } from 'react-redux'; import { LoadingState } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { queryBuilder } from '../../shared/testing/builders'; import { getPreloadedState } from '../../state/helpers'; import { QueryVariableModel, VariableWithMultiSupport, VariableWithOptions } from '../../types'; import { VariablePickerProps } from '../types'; import { optionPickerFactory } from './OptionsPicker'; import { initialOptionPickerState, OptionsPickerState } from './reducer'; interface Args { pickerState?: Partial<OptionsPickerState>; variable?: Partial<QueryVariableModel>; } const defaultVariable = queryBuilder() .withId('query0') .withRootStateKey('key') .withName('query0') .withMulti() .withCurrent(['A', 'C']) .withOptions('A', 'B', 'C') .build(); function setupTestContext({ pickerState = {}, variable = {} }: Args = {}) { const v = { ...defaultVariable, ...variable, }; const onVariableChange = jest.fn(); const props: VariablePickerProps<VariableWithMultiSupport | VariableWithOptions> = { variable: v, onVariableChange, }; const Picker = optionPickerFactory(); const optionsPicker: OptionsPickerState = { ...initialOptionPickerState, ...pickerState }; const dispatch = jest.fn(); const subscribe = jest.fn(); const templatingState = { variables: { [v.id]: { ...v }, }, optionsPicker, }; const getState = jest.fn().mockReturnValue(getPreloadedState('key', templatingState)); const store: any = { getState, dispatch, subscribe }; const { rerender } = render( <Provider store={store}> <Picker {...props} /> </Provider> ); return { onVariableChange, variable, rerender, dispatch }; } function getSubMenu(text: string) { return screen.getByTestId(selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownValueLinkTexts(text)); } function getOption(text: string) { return screen.getByTestId(selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownOptionTexts('A')); } describe('OptionPicker', () => { describe('when mounted and picker id is not set', () => { it('should render link with correct text', () => { setupTestContext(); expect(getSubMenu('A + C')).toBeInTheDocument(); }); it('link text should be clickable', async () => { const { dispatch } = setupTestContext(); dispatch.mockClear(); await userEvent.click(getSubMenu('A + C')); expect(dispatch).toHaveBeenCalledTimes(1); }); }); describe('when mounted and picker id differs from variable id', () => { it('should render link with correct text', () => { setupTestContext({ variable: defaultVariable, pickerState: { id: 'Other' }, }); expect(getSubMenu('A + C')).toBeInTheDocument(); }); it('link text should be clickable', async () => { const { dispatch } = setupTestContext({ variable: defaultVariable, pickerState: { id: 'Other' }, }); dispatch.mockClear(); await userEvent.click(getSubMenu('A + C')); expect(dispatch).toHaveBeenCalledTimes(1); }); }); describe('when mounted and variable is loading', () => { it('should render link with correct text and loading indicator should be visible', () => { setupTestContext({ variable: { ...defaultVariable, state: LoadingState.Loading }, }); expect(getSubMenu('A + C')).toBeInTheDocument(); expect(screen.getByLabelText(selectors.components.LoadingIndicator.icon)).toBeInTheDocument(); }); it('link text should not be clickable', async () => { const { dispatch } = setupTestContext({ variable: { ...defaultVariable, state: LoadingState.Loading }, }); dispatch.mockClear(); await userEvent.click(getSubMenu('A + C')); expect(dispatch).toHaveBeenCalledTimes(0); }); }); describe('when mounted and picker id equals the variable id', () => { it('should render input, drop down list with correct options', () => { setupTestContext({ variable: defaultVariable, pickerState: { id: defaultVariable.id, options: defaultVariable.options, multi: defaultVariable.multi }, }); expect(screen.getByRole('textbox')).toBeInTheDocument(); expect(screen.getByRole('textbox')).toHaveValue(''); expect( screen.getByLabelText(selectors.pages.Dashboard.SubMenu.submenuItemValueDropDownDropDown) ).toBeInTheDocument(); expect(getOption('A')).toBeInTheDocument(); expect(getOption('B')).toBeInTheDocument(); expect(getOption('C')).toBeInTheDocument(); }); }); });
public/app/features/variables/pickers/OptionsPicker/OptionPicker.test.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0036897347308695316, 0.0004094323667231947, 0.00016439099272247404, 0.00017430201114621013, 0.0008767246035858989 ]
{ "id": 7, "code_window": [ " allowCustomValue={enableCreateNew}\n", " loadOptions={this.debouncedSearch}\n", " onChange={this.onFolderChange}\n", " onCreateOption={this.createNewFolder}\n", " />\n", " </div>\n", " );\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isClearable={isClearable}\n" ], "file_path": "public/app/core/components/Select/FolderPicker.tsx", "type": "add", "edit_start_line_idx": 207 }
// Copyright (c) 2017 Uber Technologies, Inc. // // 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 { css } from '@emotion/css'; import * as React from 'react'; import { useStyles2 } from '@grafana/ui'; const getStyles = () => { return { BreakableText: css` label: BreakableText; display: inline-block; white-space: pre; `, }; }; const WORD_RX = /\W*\w+\W*/g; type Props = { text: string; className?: string; wordRegexp?: RegExp; }; // TODO typescript doesn't understand text or null as react nodes // https://github.com/Microsoft/TypeScript/issues/21699 export default function BreakableText( props: Props ): any /* React.ReactNode /* React.ReactElement | React.ReactElement[] \*\/ */ { const { className, text, wordRegexp = WORD_RX } = props; const styles = useStyles2(getStyles); if (!text) { return typeof text === 'string' ? text : null; } const spans = []; wordRegexp.exec(''); // if the given text has no words, set the first match to the entire text let match: RegExpExecArray | string[] | null = wordRegexp.exec(text) || [text]; while (match) { spans.push( <span key={`${text}-${spans.length}`} className={className || styles.BreakableText}> {match[0]} </span> ); match = wordRegexp.exec(text); } return spans; } BreakableText.defaultProps = { wordRegexp: WORD_RX, };
packages/jaeger-ui-components/src/common/BreakableText.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017653814575169235, 0.00017363167717121542, 0.0001700563298072666, 0.00017414202739018947, 0.0000021702039703086484 ]
{ "id": 8, "code_window": [ "import { PanelPlugin } from '@grafana/data';\n", "import { config, DataSourcePicker } from '@grafana/runtime';\n", "import { TagsInput } from '@grafana/ui';\n", "import { RuleFolderPicker } from 'app/features/alerting/unified/components/rule-editor/RuleFolderPicker';\n", "\n", "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { FolderPicker } from 'app/core/components/Select/FolderPicker';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 5 }
import React from 'react'; import { PanelPlugin } from '@grafana/data'; import { config, DataSourcePicker } from '@grafana/runtime'; import { TagsInput } from '@grafana/ui'; import { RuleFolderPicker } from 'app/features/alerting/unified/components/rule-editor/RuleFolderPicker'; import { ALL_FOLDER, GENERAL_FOLDER, ReadonlyFolderPicker, } from '../../../core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker'; import { AlertList } from './AlertList'; import { alertListPanelMigrationHandler } from './AlertListMigrationHandler'; import { GroupBy } from './GroupByWithLoading'; import { UnifiedAlertList } from './UnifiedAlertList'; import { AlertListSuggestionsSupplier } from './suggestions'; import { AlertListOptions, GroupMode, ShowOption, SortOrder, UnifiedAlertListOptions } from './types'; function showIfCurrentState(options: AlertListOptions) { return options.showOptions === ShowOption.Current; } const alertList = new PanelPlugin<AlertListOptions>(AlertList) .setPanelOptions((builder) => { builder .addSelect({ name: 'Show', path: 'showOptions', settings: { options: [ { label: 'Current state', value: ShowOption.Current }, { label: 'Recent state changes', value: ShowOption.RecentChanges }, ], }, defaultValue: ShowOption.Current, category: ['Options'], }) .addNumberInput({ name: 'Max items', path: 'maxItems', defaultValue: 10, category: ['Options'], }) .addSelect({ name: 'Sort order', path: 'sortOrder', settings: { options: [ { label: 'Alphabetical (asc)', value: SortOrder.AlphaAsc }, { label: 'Alphabetical (desc)', value: SortOrder.AlphaDesc }, { label: 'Importance', value: SortOrder.Importance }, { label: 'Time (asc)', value: SortOrder.TimeAsc }, { label: 'Time (desc)', value: SortOrder.TimeDesc }, ], }, defaultValue: SortOrder.AlphaAsc, category: ['Options'], }) .addBooleanSwitch({ path: 'dashboardAlerts', name: 'Alerts from this dashboard', defaultValue: false, category: ['Options'], }) .addTextInput({ path: 'alertName', name: 'Alert name', defaultValue: '', category: ['Filter'], showIf: showIfCurrentState, }) .addTextInput({ path: 'dashboardTitle', name: 'Dashboard title', defaultValue: '', category: ['Filter'], showIf: showIfCurrentState, }) .addCustomEditor({ path: 'folderId', name: 'Folder', id: 'folderId', defaultValue: null, editor: function RenderFolderPicker({ value, onChange }) { return ( <ReadonlyFolderPicker initialFolderId={value} onChange={(folder) => onChange(folder?.id)} extraFolders={[ALL_FOLDER, GENERAL_FOLDER]} /> ); }, category: ['Filter'], showIf: showIfCurrentState, }) .addCustomEditor({ id: 'tags', path: 'tags', name: 'Tags', description: '', defaultValue: [], editor(props) { return <TagsInput tags={props.value} onChange={props.onChange} />; }, category: ['Filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.ok', name: 'Ok', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.paused', name: 'Paused', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.no_data', name: 'No data', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.execution_error', name: 'Execution error', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.alerting', name: 'Alerting', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }) .addBooleanSwitch({ path: 'stateFilter.pending', name: 'Pending', defaultValue: false, category: ['State filter'], showIf: showIfCurrentState, }); }) .setMigrationHandler(alertListPanelMigrationHandler) .setSuggestionsSupplier(new AlertListSuggestionsSupplier()); const unifiedAlertList = new PanelPlugin<UnifiedAlertListOptions>(UnifiedAlertList).setPanelOptions((builder) => { builder .addRadio({ path: 'groupMode', name: 'Group mode', description: 'How alert instances should be grouped', defaultValue: GroupMode.Default, settings: { options: [ { value: GroupMode.Default, label: 'Default grouping' }, { value: GroupMode.Custom, label: 'Custom grouping' }, ], }, category: ['Options'], }) .addCustomEditor({ path: 'groupBy', name: 'Group by', description: 'Filter alerts using label querying', id: 'groupBy', defaultValue: [], showIf: (options) => options.groupMode === GroupMode.Custom, category: ['Options'], editor: (props) => { return ( <GroupBy id={props.id ?? 'groupBy'} defaultValue={props.value.map((value: string) => ({ label: value, value }))} onChange={props.onChange} /> ); }, }) .addNumberInput({ name: 'Max items', path: 'maxItems', description: 'Maximum alerts to display', defaultValue: 20, category: ['Options'], }) .addSelect({ name: 'Sort order', path: 'sortOrder', description: 'Sort order of alerts and alert instances', settings: { options: [ { label: 'Alphabetical (asc)', value: SortOrder.AlphaAsc }, { label: 'Alphabetical (desc)', value: SortOrder.AlphaDesc }, { label: 'Importance', value: SortOrder.Importance }, { label: 'Time (asc)', value: SortOrder.TimeAsc }, { label: 'Time (desc)', value: SortOrder.TimeDesc }, ], }, defaultValue: SortOrder.AlphaAsc, category: ['Options'], }) .addBooleanSwitch({ path: 'dashboardAlerts', name: 'Alerts from this dashboard', description: 'Show alerts from this dashboard', defaultValue: false, category: ['Options'], }) .addTextInput({ path: 'alertName', name: 'Alert name', description: 'Filter for alerts containing this text', defaultValue: '', category: ['Filter'], }) .addTextInput({ path: 'alertInstanceLabelFilter', name: 'Alert instance label', description: 'Filter alert instances using label querying, ex: {severity="critical", instance=~"cluster-us-.+"}', defaultValue: '', category: ['Filter'], }) .addCustomEditor({ path: 'folder', name: 'Folder', description: 'Filter for alerts in the selected folder', id: 'folder', defaultValue: null, editor: function RenderFolderPicker(props) { return ( <RuleFolderPicker {...props} enableReset={true} onChange={({ title, id }) => { return props.onChange({ title, id }); }} /> ); }, category: ['Filter'], }) .addCustomEditor({ path: 'datasource', name: 'Datasource', description: 'Filter alerts from selected datasource', id: 'datasource', defaultValue: null, editor: function RenderDatasourcePicker(props) { return ( <DataSourcePicker {...props} type={['prometheus', 'loki', 'grafana']} noDefault current={props.value} onChange={(ds) => props.onChange(ds.name)} onClear={() => props.onChange('')} /> ); }, category: ['Filter'], }) .addBooleanSwitch({ path: 'stateFilter.firing', name: 'Alerting / Firing', defaultValue: true, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.pending', name: 'Pending', defaultValue: true, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.inactive', name: 'Inactive', defaultValue: false, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.noData', name: 'No Data', defaultValue: false, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.normal', name: 'Normal', defaultValue: false, category: ['Alert state filter'], }) .addBooleanSwitch({ path: 'stateFilter.error', name: 'Error', defaultValue: true, category: ['Alert state filter'], }); }); export const plugin = config.unifiedAlertingEnabled ? unifiedAlertList : alertList;
public/app/plugins/panel/alertlist/module.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.991200864315033, 0.05140639469027519, 0.0001672049256740138, 0.00017774829757399857, 0.2023763358592987 ]
{ "id": 8, "code_window": [ "import { PanelPlugin } from '@grafana/data';\n", "import { config, DataSourcePicker } from '@grafana/runtime';\n", "import { TagsInput } from '@grafana/ui';\n", "import { RuleFolderPicker } from 'app/features/alerting/unified/components/rule-editor/RuleFolderPicker';\n", "\n", "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { FolderPicker } from 'app/core/components/Select/FolderPicker';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 5 }
// Copyright (c) 2017 Uber Technologies, Inc. // // 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. export const FALLBACK_DAG_MAX_NUM_SERVICES = 100 as 100; export const FALLBACK_TRACE_NAME = '<trace-without-root-span>' as '<trace-without-root-span>'; export const FETCH_DONE = 'FETCH_DONE' as 'FETCH_DONE'; export const FETCH_ERROR = 'FETCH_ERROR' as 'FETCH_ERROR'; export const FETCH_LOADING = 'FETCH_LOADING' as 'FETCH_LOADING'; export const fetchedState = { DONE: FETCH_DONE, ERROR: FETCH_ERROR, LOADING: FETCH_LOADING, };
packages/jaeger-ui-components/src/constants/index.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001775594864739105, 0.00016963218513410538, 0.00016536239127162844, 0.0001659746776567772, 0.000005611018877971219 ]
{ "id": 8, "code_window": [ "import { PanelPlugin } from '@grafana/data';\n", "import { config, DataSourcePicker } from '@grafana/runtime';\n", "import { TagsInput } from '@grafana/ui';\n", "import { RuleFolderPicker } from 'app/features/alerting/unified/components/rule-editor/RuleFolderPicker';\n", "\n", "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { FolderPicker } from 'app/core/components/Select/FolderPicker';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 5 }
/** * See also: * https://github.com/grafana/grafana-plugin-sdk-go/blob/main/data/frame_type.go * * @public */ export enum DataFrameType { TimeSeriesWide = 'timeseries-wide', TimeSeriesLong = 'timeseries-long', TimeSeriesMany = 'timeseries-many', /** Directory listing */ DirectoryListing = 'directory-listing', /** * First field is X, the rest are bucket values */ HeatmapBuckets = 'heatmap-buckets', /** * Explicit fields for: * xMin, yMin, count, ... * * All values in the grid exist and have regular spacing */ HeatmapScanlines = 'heatmap-scanlines', /** * WIP sparse heatmap support * * @private */ HeatmapSparse = 'heatmap-cells-sparse', }
packages/grafana-data/src/types/dataFrameTypes.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0002575094986241311, 0.00019414236885495484, 0.00017155305249616504, 0.0001737534475978464, 0.00003661716982605867 ]
{ "id": 8, "code_window": [ "import { PanelPlugin } from '@grafana/data';\n", "import { config, DataSourcePicker } from '@grafana/runtime';\n", "import { TagsInput } from '@grafana/ui';\n", "import { RuleFolderPicker } from 'app/features/alerting/unified/components/rule-editor/RuleFolderPicker';\n", "\n", "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { FolderPicker } from 'app/core/components/Select/FolderPicker';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 5 }
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015 Grafana Labs 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.
packages/grafana-schema/LICENSE_APACHE2
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001783098850864917, 0.00017632113303989172, 0.00017097593809012324, 0.00017647822096478194, 0.0000015908425439192797 ]
{ "id": 9, "code_window": [ "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n", "} from '../../../core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "\n", "import { AlertList } from './AlertList';\n", "import { alertListPanelMigrationHandler } from './AlertListMigrationHandler';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "} from 'app/core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "import { PermissionLevelString } from 'app/types';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 11 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0036824762355536222, 0.00032640466815792024, 0.0001665865129325539, 0.00017146443133242428, 0.0007005151128396392 ]
{ "id": 9, "code_window": [ "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n", "} from '../../../core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "\n", "import { AlertList } from './AlertList';\n", "import { alertListPanelMigrationHandler } from './AlertListMigrationHandler';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "} from 'app/core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "import { PermissionLevelString } from 'app/types';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 11 }
scripts/build/release_publisher/testdata/grafana-enterprise-5.4.0-123pre1.linux-amd64.tar.gz
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017370439309161156, 0.00017370439309161156, 0.00017370439309161156, 0.00017370439309161156, 0 ]
{ "id": 9, "code_window": [ "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n", "} from '../../../core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "\n", "import { AlertList } from './AlertList';\n", "import { alertListPanelMigrationHandler } from './AlertListMigrationHandler';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "} from 'app/core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "import { PermissionLevelString } from 'app/types';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 11 }
// Code generated by mockery v2.10.0. DO NOT EDIT. package eval import ( backend "github.com/grafana/grafana-plugin-sdk-go/backend" expr "github.com/grafana/grafana/pkg/expr" mock "github.com/stretchr/testify/mock" models "github.com/grafana/grafana/pkg/services/ngalert/models" time "time" ) // FakeEvaluator is an autogenerated mock type for the Evaluator type type FakeEvaluator struct { mock.Mock } type FakeEvaluator_Expecter struct { mock *mock.Mock } func (_m *FakeEvaluator) EXPECT() *FakeEvaluator_Expecter { return &FakeEvaluator_Expecter{mock: &_m.Mock} } // ConditionEval provides a mock function with given fields: condition, now, expressionService func (_m *FakeEvaluator) ConditionEval(condition *models.Condition, now time.Time, expressionService *expr.Service) (Results, error) { ret := _m.Called(condition, now, expressionService) var r0 Results if rf, ok := ret.Get(0).(func(*models.Condition, time.Time, *expr.Service) Results); ok { r0 = rf(condition, now, expressionService) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(Results) } } var r1 error if rf, ok := ret.Get(1).(func(*models.Condition, time.Time, *expr.Service) error); ok { r1 = rf(condition, now, expressionService) } else { r1 = ret.Error(1) } return r0, r1 } // FakeEvaluator_ConditionEval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ConditionEval' type FakeEvaluator_ConditionEval_Call struct { *mock.Call } // ConditionEval is a helper method to define mock.On call // - condition *models.Condition // - now time.Time // - expressionService *expr.Service func (_e *FakeEvaluator_Expecter) ConditionEval(condition interface{}, now interface{}, expressionService interface{}) *FakeEvaluator_ConditionEval_Call { return &FakeEvaluator_ConditionEval_Call{Call: _e.mock.On("ConditionEval", condition, now, expressionService)} } func (_c *FakeEvaluator_ConditionEval_Call) Run(run func(condition *models.Condition, now time.Time, expressionService *expr.Service)) *FakeEvaluator_ConditionEval_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(*models.Condition), args[1].(time.Time), args[2].(*expr.Service)) }) return _c } func (_c *FakeEvaluator_ConditionEval_Call) Return(_a0 Results, _a1 error) *FakeEvaluator_ConditionEval_Call { _c.Call.Return(_a0, _a1) return _c } // QueriesAndExpressionsEval provides a mock function with given fields: orgID, data, now, expressionService func (_m *FakeEvaluator) QueriesAndExpressionsEval(orgID int64, data []models.AlertQuery, now time.Time, expressionService *expr.Service) (*backend.QueryDataResponse, error) { ret := _m.Called(orgID, data, now, expressionService) var r0 *backend.QueryDataResponse if rf, ok := ret.Get(0).(func(int64, []models.AlertQuery, time.Time, *expr.Service) *backend.QueryDataResponse); ok { r0 = rf(orgID, data, now, expressionService) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*backend.QueryDataResponse) } } var r1 error if rf, ok := ret.Get(1).(func(int64, []models.AlertQuery, time.Time, *expr.Service) error); ok { r1 = rf(orgID, data, now, expressionService) } else { r1 = ret.Error(1) } return r0, r1 } // FakeEvaluator_QueriesAndExpressionsEval_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QueriesAndExpressionsEval' type FakeEvaluator_QueriesAndExpressionsEval_Call struct { *mock.Call } // QueriesAndExpressionsEval is a helper method to define mock.On call // - orgID int64 // - data []models.AlertQuery // - now time.Time // - expressionService *expr.Service func (_e *FakeEvaluator_Expecter) QueriesAndExpressionsEval(orgID interface{}, data interface{}, now interface{}, expressionService interface{}) *FakeEvaluator_QueriesAndExpressionsEval_Call { return &FakeEvaluator_QueriesAndExpressionsEval_Call{Call: _e.mock.On("QueriesAndExpressionsEval", orgID, data, now, expressionService)} } func (_c *FakeEvaluator_QueriesAndExpressionsEval_Call) Run(run func(orgID int64, data []models.AlertQuery, now time.Time, expressionService *expr.Service)) *FakeEvaluator_QueriesAndExpressionsEval_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(int64), args[1].([]models.AlertQuery), args[2].(time.Time), args[3].(*expr.Service)) }) return _c } func (_c *FakeEvaluator_QueriesAndExpressionsEval_Call) Return(_a0 *backend.QueryDataResponse, _a1 error) *FakeEvaluator_QueriesAndExpressionsEval_Call { _c.Call.Return(_a0, _a1) return _c }
pkg/services/ngalert/eval/evaluator_mock.go
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.000733891676645726, 0.0002166203485103324, 0.00016143415996339172, 0.00017101620323956013, 0.00014976550301071256 ]
{ "id": 9, "code_window": [ "import {\n", " ALL_FOLDER,\n", " GENERAL_FOLDER,\n", " ReadonlyFolderPicker,\n", "} from '../../../core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "\n", "import { AlertList } from './AlertList';\n", "import { alertListPanelMigrationHandler } from './AlertListMigrationHandler';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "} from 'app/core/components/Select/ReadonlyFolderPicker/ReadonlyFolderPicker';\n", "import { PermissionLevelString } from 'app/types';\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 11 }
package service import ( "context" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/dashboardimport" "github.com/grafana/grafana/pkg/services/dashboardimport/api" "github.com/grafana/grafana/pkg/services/dashboardimport/utils" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/librarypanels" "github.com/grafana/grafana/pkg/services/plugindashboards" "github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/services/schemaloader" ) func ProvideService(routeRegister routing.RouteRegister, quotaService *quota.QuotaService, schemaLoaderService *schemaloader.SchemaLoaderService, pluginDashboardService plugindashboards.Service, pluginStore plugins.Store, libraryPanelService librarypanels.Service, dashboardService dashboards.DashboardService, ac accesscontrol.AccessControl, ) *ImportDashboardService { s := &ImportDashboardService{ pluginDashboardService: pluginDashboardService, dashboardService: dashboardService, libraryPanelService: libraryPanelService, } dashboardImportAPI := api.New(s, quotaService, schemaLoaderService, pluginStore, ac) dashboardImportAPI.RegisterAPIEndpoints(routeRegister) return s } type ImportDashboardService struct { pluginDashboardService plugindashboards.Service dashboardService dashboards.DashboardService libraryPanelService librarypanels.Service } func (s *ImportDashboardService) ImportDashboard(ctx context.Context, req *dashboardimport.ImportDashboardRequest) (*dashboardimport.ImportDashboardResponse, error) { var draftDashboard *models.Dashboard if req.PluginId != "" { loadReq := &plugindashboards.LoadPluginDashboardRequest{ PluginID: req.PluginId, Reference: req.Path, } if resp, err := s.pluginDashboardService.LoadPluginDashboard(ctx, loadReq); err != nil { return nil, err } else { draftDashboard = resp.Dashboard } } else { draftDashboard = models.NewDashboardFromJson(req.Dashboard) } evaluator := utils.NewDashTemplateEvaluator(draftDashboard.Data, req.Inputs) generatedDash, err := evaluator.Eval() if err != nil { return nil, err } saveCmd := models.SaveDashboardCommand{ Dashboard: generatedDash, OrgId: req.User.OrgId, UserId: req.User.UserId, Overwrite: req.Overwrite, PluginId: req.PluginId, FolderId: req.FolderId, } dto := &dashboards.SaveDashboardDTO{ OrgId: saveCmd.OrgId, Dashboard: saveCmd.GetDashboardModel(), Overwrite: saveCmd.Overwrite, User: req.User, } savedDashboard, err := s.dashboardService.ImportDashboard(ctx, dto) if err != nil { return nil, err } err = s.libraryPanelService.ImportLibraryPanelsForDashboard(ctx, req.User, savedDashboard, req.FolderId) if err != nil { return nil, err } err = s.libraryPanelService.ConnectLibraryPanelsForDashboard(ctx, req.User, savedDashboard) if err != nil { return nil, err } return &dashboardimport.ImportDashboardResponse{ UID: savedDashboard.Uid, PluginId: req.PluginId, Title: savedDashboard.Title, Path: req.Path, Revision: savedDashboard.Data.Get("revision").MustInt64(1), FolderId: savedDashboard.FolderId, ImportedUri: "db/" + savedDashboard.Slug, ImportedUrl: savedDashboard.GetUrl(), ImportedRevision: savedDashboard.Data.Get("revision").MustInt64(1), Imported: true, DashboardId: savedDashboard.Id, Slug: savedDashboard.Slug, }, nil }
pkg/services/dashboardimport/service/service.go
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00018367315351497382, 0.00017205788753926754, 0.00016584589320700616, 0.00017176655819639564, 0.000005240232894720975 ]
{ "id": 10, "code_window": [ " id: 'folder',\n", " defaultValue: null,\n", " editor: function RenderFolderPicker(props) {\n", " return (\n", " <RuleFolderPicker\n", " {...props}\n", " enableReset={true}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <FolderPicker\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 240 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.006971321068704128, 0.000999518553726375, 0.0001660471607465297, 0.00017430968000553548, 0.001757499878294766 ]
{ "id": 10, "code_window": [ " id: 'folder',\n", " defaultValue: null,\n", " editor: function RenderFolderPicker(props) {\n", " return (\n", " <RuleFolderPicker\n", " {...props}\n", " enableReset={true}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <FolderPicker\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 240 }
import { css } from '@emotion/css'; import React, { useEffect, useState } from 'react'; import { useFormContext } from 'react-hook-form'; import { useDispatch } from 'react-redux'; import { useDebounce } from 'react-use'; import { dateTime, GrafanaTheme2 } from '@grafana/data'; import { Badge, useStyles2 } from '@grafana/ui'; import { Alert, AlertingRule } from 'app/types/unified-alerting'; import { useCombinedRuleNamespaces } from '../../hooks/useCombinedRuleNamespaces'; import { fetchAllPromAndRulerRulesAction } from '../../state/actions'; import { MatcherFieldValue, SilenceFormFields } from '../../types/silence-form'; import { findAlertInstancesWithMatchers } from '../../utils/matchers'; import { isAlertingRule } from '../../utils/rules'; import { AlertLabels } from '../AlertLabels'; import { DynamicTable, DynamicTableColumnProps, DynamicTableItemProps } from '../DynamicTable'; import { AlertStateTag } from '../rules/AlertStateTag'; type MatchedRulesTableItemProps = DynamicTableItemProps<{ matchedInstance: Alert; }>; type MatchedRulesTableColumnProps = DynamicTableColumnProps<{ matchedInstance: Alert }>; export const MatchedSilencedRules = () => { const [matchedAlertRules, setMatchedAlertRules] = useState<MatchedRulesTableItemProps[]>([]); const formApi = useFormContext<SilenceFormFields>(); const dispatch = useDispatch(); const { watch } = formApi; const matchers: MatcherFieldValue[] = watch('matchers'); const styles = useStyles2(getStyles); const columns = useColumns(); useEffect(() => { dispatch(fetchAllPromAndRulerRulesAction()); }, [dispatch]); const combinedNamespaces = useCombinedRuleNamespaces(); useDebounce( () => { const matchedInstances = combinedNamespaces.flatMap((namespace) => { return namespace.groups.flatMap((group) => { return group.rules .map((combinedRule) => combinedRule.promRule) .filter((rule): rule is AlertingRule => isAlertingRule(rule)) .flatMap((rule) => findAlertInstancesWithMatchers(rule.alerts ?? [], matchers)); }); }); setMatchedAlertRules(matchedInstances); }, 500, [combinedNamespaces, matchers] ); return ( <div> <h4 className={styles.title}> Affected alert instances {matchedAlertRules.length > 0 ? ( <Badge className={styles.badge} color="blue" text={matchedAlertRules.length} /> ) : null} </h4> <div className={styles.table}> {matchers.every((matcher) => !matcher.value && !matcher.name) ? ( <span>Add a valid matcher to see affected alerts</span> ) : ( <> <DynamicTable items={matchedAlertRules.slice(0, 5) ?? []} isExpandable={false} cols={columns} /> {matchedAlertRules.length > 5 && ( <div className={styles.moreMatches}>and {matchedAlertRules.length - 5} more</div> )} </> )} </div> </div> ); }; function useColumns(): MatchedRulesTableColumnProps[] { return [ { id: 'state', label: 'State', renderCell: function renderStateTag({ data: { matchedInstance } }) { return <AlertStateTag state={matchedInstance.state} />; }, size: '160px', }, { id: 'labels', label: 'Labels', renderCell: function renderName({ data: { matchedInstance } }) { return <AlertLabels labels={matchedInstance.labels} />; }, size: '250px', }, { id: 'created', label: 'Created', renderCell: function renderSummary({ data: { matchedInstance } }) { return ( <> {matchedInstance.activeAt.startsWith('0001') ? '-' : dateTime(matchedInstance.activeAt).format('YYYY-MM-DD HH:mm:ss')} </> ); }, size: '400px', }, ]; } const getStyles = (theme: GrafanaTheme2) => ({ table: css` max-width: ${theme.breakpoints.values.lg}px; `, moreMatches: css` margin-top: ${theme.spacing(1)}; `, title: css` display: flex; align-items: center; `, badge: css` margin-left: ${theme.spacing(1)}; `, });
public/app/features/alerting/unified/components/silences/MatchedSilencedRules.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00018536743300501257, 0.0001737240090733394, 0.00016754455282352865, 0.0001723834138829261, 0.0000045424017116602045 ]
{ "id": 10, "code_window": [ " id: 'folder',\n", " defaultValue: null,\n", " editor: function RenderFolderPicker(props) {\n", " return (\n", " <RuleFolderPicker\n", " {...props}\n", " enableReset={true}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <FolderPicker\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 240 }
import { MapLayerRegistryItem, MapLayerOptions, PanelData, GrafanaTheme2, PluginState } from '@grafana/data'; import Map from 'ol/Map'; import Feature from 'ol/Feature'; import * as style from 'ol/style'; import * as source from 'ol/source'; import * as layer from 'ol/layer'; import { getGeometryField, getLocationMatchers } from 'app/features/geo/utils/location'; export interface LastPointConfig { icon?: string; } const defaultOptions: LastPointConfig = { icon: 'https://openlayers.org/en/latest/examples/data/icon.png', }; export const lastPointTracker: MapLayerRegistryItem<LastPointConfig> = { id: 'last-point-tracker', name: 'Icon at last point', description: 'Show an icon at the last point', isBaseMap: false, showLocation: true, state: PluginState.alpha, /** * Function that configures transformation and returns a transformer * @param options */ create: async (map: Map, options: MapLayerOptions<LastPointConfig>, theme: GrafanaTheme2) => { const point = new Feature({}); const config = { ...defaultOptions, ...options.config }; point.setStyle( new style.Style({ image: new style.Icon({ src: config.icon, }), }) ); const vectorSource = new source.Vector({ features: [point], }); const vectorLayer = new layer.Vector({ source: vectorSource, }); const matchers = await getLocationMatchers(options.location); return { init: () => vectorLayer, update: (data: PanelData) => { const frame = data.series[0]; if (frame && frame.length) { const out = getGeometryField(frame, matchers); if (!out.field) { return; // ??? } point.setGeometry(out.field.values.get(frame.length - 1)); } }, }; }, // fill in the default values defaultOptions, };
public/app/plugins/panel/geomap/layers/data/lastPointTracker.ts
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00017921344260685146, 0.00017402603407390416, 0.00016722183499950916, 0.00017386146646458656, 0.0000037347751913330285 ]
{ "id": 10, "code_window": [ " id: 'folder',\n", " defaultValue: null,\n", " editor: function RenderFolderPicker(props) {\n", " return (\n", " <RuleFolderPicker\n", " {...props}\n", " enableReset={true}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " <FolderPicker\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 240 }
dn: cn=admins,ou=groups,dc=grafana,dc=org cn: admins objectClass: groupOfNames objectClass: top member: cn=ldap-admin,ou=users,dc=grafana,dc=org member: cn=ldap-torkel,ou=users,dc=grafana,dc=org dn: cn=editors,ou=groups,dc=grafana,dc=org cn: editors objectClass: groupOfNames member: cn=ldap-editor,ou=users,dc=grafana,dc=org dn: cn=backend,ou=groups,dc=grafana,dc=org cn: backend objectClass: groupOfNames member: cn=ldap-carl,ou=users,dc=grafana,dc=org member: cn=ldap-leo,ou=users,dc=grafana,dc=org member: cn=ldap-torkel,ou=users,dc=grafana,dc=org dn: cn=frontend,ou=groups,dc=grafana,dc=org cn: frontend objectClass: groupOfNames member: cn=ldap-torkel,ou=users,dc=grafana,dc=org member: cn=ldap-daniel,ou=users,dc=grafana,dc=org member: cn=ldap-leo,ou=users,dc=grafana,dc=org # -- POSIX -- # posix admin group (without support for memberOf attribute) dn: cn=posix-admins,ou=groups,dc=grafana,dc=org cn: admins objectClass: top objectClass: posixGroup gidNumber: 1 memberUid: ldap-posix-admin # posix group (without support for memberOf attribute) dn: cn=posix,ou=groups,dc=grafana,dc=org cn: viewers objectClass: top objectClass: posixGroup gidNumber: 2 memberUid: ldap-posix
devenv/docker/blocks/openldap/prepopulate/3_groups.ldif
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0001748830109136179, 0.00016724001034162939, 0.00015768656157888472, 0.00016885806689970195, 0.000005609929303318495 ]
{ "id": 11, "code_window": [ " enableReset={true}\n", " onChange={({ title, id }) => {\n", " return props.onChange({ title, id });\n", " }}\n", " />\n", " );\n", " },\n", " category: ['Filter'],\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " showRoot={false}\n", " allowEmpty={true}\n", " initialTitle={props.value?.title}\n", " initialFolderId={props.value?.id}\n", " permissionLevel={PermissionLevelString.View}\n", " onClear={() => props.onChange('')}\n", " {...props}\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 243 }
import { debounce } from 'lodash'; import React, { PureComponent } from 'react'; import { AppEvents, SelectableValue } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; import { AsyncSelect } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { createFolder, getFolderById, searchFolders } from 'app/features/manage-dashboards/state/actions'; import { DashboardSearchHit } from 'app/features/search/types'; import { AccessControlAction, PermissionLevelString } from '../../../types'; import appEvents from '../../app_events'; export type FolderPickerFilter = (hits: DashboardSearchHit[]) => DashboardSearchHit[]; export interface Props { onChange: ($folder: { title: string; id: number }) => void; enableCreateNew?: boolean; rootName?: string; enableReset?: boolean; dashboardId?: any; initialTitle?: string; initialFolderId?: number; permissionLevel?: Exclude<PermissionLevelString, PermissionLevelString.Admin>; filter?: FolderPickerFilter; allowEmpty?: boolean; showRoot?: boolean; accessControlMetadata?: boolean; /** * Skips loading all folders in order to find the folder matching * the folder where the dashboard is stored. * Instead initialFolderId and initialTitle will be used to display the correct folder. * initialFolderId needs to have an value > -1 or an error will be thrown. */ skipInitialLoad?: boolean; /** The id of the search input. Use this to set a matching label with htmlFor */ inputId?: string; } interface State { folder: SelectableValue<number> | null; } export class FolderPicker extends PureComponent<Props, State> { debouncedSearch: any; constructor(props: Props) { super(props); this.state = { folder: null, }; this.debouncedSearch = debounce(this.getOptions, 300, { leading: true, trailing: true, }); } static defaultProps: Partial<Props> = { rootName: 'General', enableReset: false, initialTitle: '', enableCreateNew: false, permissionLevel: PermissionLevelString.Edit, allowEmpty: false, showRoot: true, }; componentDidMount = async () => { if (this.props.skipInitialLoad) { const folder = await getInitialValues({ getFolder: getFolderById, folderId: this.props.initialFolderId, folderName: this.props.initialTitle, }); this.setState({ folder }); return; } await this.loadInitialValue(); }; getOptions = async (query: string) => { const { rootName, enableReset, initialTitle, permissionLevel, filter, accessControlMetadata, initialFolderId, showRoot, } = this.props; const searchHits = await searchFolders(query, permissionLevel, accessControlMetadata); const options: Array<SelectableValue<number>> = mapSearchHitsToOptions(searchHits, filter); const hasAccess = contextSrv.hasAccess(AccessControlAction.DashboardsWrite, contextSrv.isEditor) || contextSrv.hasAccess(AccessControlAction.DashboardsCreate, contextSrv.isEditor); if (hasAccess && rootName?.toLowerCase().startsWith(query.toLowerCase()) && showRoot) { options.unshift({ label: rootName, value: 0 }); } if ( enableReset && query === '' && initialTitle !== '' && !options.find((option) => option.label === initialTitle) ) { options.unshift({ label: initialTitle, value: initialFolderId }); } return options; }; onFolderChange = (newFolder: SelectableValue<number>) => { if (!newFolder) { newFolder = { value: 0, label: this.props.rootName }; } this.setState( { folder: newFolder, }, () => this.props.onChange({ id: newFolder.value!, title: newFolder.label! }) ); }; createNewFolder = async (folderName: string) => { // @ts-ignore const newFolder = await createFolder({ title: folderName }); let folder = { value: -1, label: 'Not created' }; if (newFolder.id > -1) { appEvents.emit(AppEvents.alertSuccess, ['Folder Created', 'OK']); folder = { value: newFolder.id, label: newFolder.title }; await this.onFolderChange(folder); } else { appEvents.emit(AppEvents.alertError, ['Folder could not be created']); } return folder; }; private loadInitialValue = async () => { const { initialTitle, rootName, initialFolderId, enableReset, dashboardId } = this.props; const resetFolder: SelectableValue<number> = { label: initialTitle, value: undefined }; const rootFolder: SelectableValue<number> = { label: rootName, value: 0 }; const options = await this.getOptions(''); let folder: SelectableValue<number> | null = null; if (initialFolderId !== undefined && initialFolderId !== null && initialFolderId > -1) { folder = options.find((option) => option.value === initialFolderId) || null; } else if (enableReset && initialTitle) { folder = resetFolder; } else if (initialFolderId) { folder = options.find((option) => option.id === initialFolderId) || null; } if (!folder && !this.props.allowEmpty) { if (contextSrv.isEditor) { folder = rootFolder; } else { // We shouldn't assign a random folder without the user actively choosing it on a persisted dashboard const isPersistedDashBoard = !!dashboardId; if (isPersistedDashBoard) { folder = resetFolder; } else { folder = options.length > 0 ? options[0] : resetFolder; } } } this.setState( { folder, }, () => { // if this is not the same as our initial value notify parent if (folder && folder.value !== initialFolderId) { this.props.onChange({ id: folder.value!, title: folder.label! }); } } ); }; render() { const { folder } = this.state; const { enableCreateNew, inputId } = this.props; return ( <div data-testid={selectors.components.FolderPicker.containerV2}> <AsyncSelect inputId={inputId} aria-label={selectors.components.FolderPicker.input} loadingMessage="Loading folders..." defaultOptions defaultValue={folder} value={folder} allowCustomValue={enableCreateNew} loadOptions={this.debouncedSearch} onChange={this.onFolderChange} onCreateOption={this.createNewFolder} /> </div> ); } } function mapSearchHitsToOptions(hits: DashboardSearchHit[], filter?: FolderPickerFilter) { const filteredHits = filter ? filter(hits) : hits; return filteredHits.map((hit) => ({ label: hit.title, value: hit.id })); } interface Args { getFolder: typeof getFolderById; folderId?: number; folderName?: string; } export async function getInitialValues({ folderName, folderId, getFolder }: Args): Promise<SelectableValue<number>> { if (folderId === null || folderId === undefined || folderId < 0) { throw new Error('folderId should to be greater or equal to zero.'); } if (folderName) { return { label: folderName, value: folderId }; } const folderDto = await getFolder(folderId); return { label: folderDto.title, value: folderId }; }
public/app/core/components/Select/FolderPicker.tsx
1
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.004069980699568987, 0.0008080455590970814, 0.00016432060510851443, 0.0002611220406834036, 0.0011217326391488314 ]
{ "id": 11, "code_window": [ " enableReset={true}\n", " onChange={({ title, id }) => {\n", " return props.onChange({ title, id });\n", " }}\n", " />\n", " );\n", " },\n", " category: ['Filter'],\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " showRoot={false}\n", " allowEmpty={true}\n", " initialTitle={props.value?.title}\n", " initialFolderId={props.value?.id}\n", " permissionLevel={PermissionLevelString.View}\n", " onClear={() => props.onChange('')}\n", " {...props}\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 243 }
dn: cn=admins,ou=groups,dc=grafana,dc=org cn: admins objectClass: groupOfNames objectClass: top member: cn=ldap-admin,ou=users,dc=grafana,dc=org member: cn=ldap-torkel,ou=users,dc=grafana,dc=org
devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/3_groups.ldif
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.00016544376558158547, 0.00016544376558158547, 0.00016544376558158547, 0.00016544376558158547, 0 ]
{ "id": 11, "code_window": [ " enableReset={true}\n", " onChange={({ title, id }) => {\n", " return props.onChange({ title, id });\n", " }}\n", " />\n", " );\n", " },\n", " category: ['Filter'],\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " showRoot={false}\n", " allowEmpty={true}\n", " initialTitle={props.value?.title}\n", " initialFolderId={props.value?.id}\n", " permissionLevel={PermissionLevelString.View}\n", " onClear={() => props.onChange('')}\n", " {...props}\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 243 }
import React, { ReactElement } from 'react'; import { DragDropContext, Droppable, DropResult } from 'react-beautiful-dnd'; import { selectors } from '@grafana/e2e-selectors'; import { reportInteraction } from '@grafana/runtime'; import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA'; import { UsagesToNetwork, VariableUsageTree } from '../inspect/utils'; import { KeyedVariableIdentifier } from '../state/types'; import { VariableModel } from '../types'; import { VariableEditorListRow } from './VariableEditorListRow'; export interface Props { variables: VariableModel[]; usages: VariableUsageTree[]; usagesNetwork: UsagesToNetwork[]; onAdd: () => void; onEdit: (identifier: KeyedVariableIdentifier) => void; onChangeOrder: (identifier: KeyedVariableIdentifier, fromIndex: number, toIndex: number) => void; onDuplicate: (identifier: KeyedVariableIdentifier) => void; onDelete: (identifier: KeyedVariableIdentifier) => void; } export function VariableEditorList({ variables, usages, usagesNetwork, onChangeOrder, onAdd, onEdit, onDelete, onDuplicate, }: Props): ReactElement { const onDragEnd = (result: DropResult) => { if (!result.destination || !result.source) { return; } reportInteraction('Variable drag and drop'); const identifier = JSON.parse(result.draggableId); onChangeOrder(identifier, result.source.index, result.destination.index); }; return ( <div> <div> {variables.length === 0 && <EmptyVariablesList onAdd={onAdd} />} {variables.length > 0 && ( <div> <table className="filter-table filter-table--hover" aria-label={selectors.pages.Dashboard.Settings.Variables.List.table} > <thead> <tr> <th>Variable</th> <th>Definition</th> <th colSpan={5} /> </tr> </thead> <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="variables-list" direction="vertical"> {(provided) => ( <tbody ref={provided.innerRef} {...provided.droppableProps}> {variables.map((variable, index) => ( <VariableEditorListRow index={index} key={`${variable.name}-${index}`} variable={variable} usageTree={usages} usagesNetwork={usagesNetwork} onDelete={onDelete} onDuplicate={onDuplicate} onEdit={onEdit} /> ))} {provided.placeholder} </tbody> )} </Droppable> </DragDropContext> </table> </div> )} </div> </div> ); } function EmptyVariablesList({ onAdd }: { onAdd: () => void }): ReactElement { return ( <div> <EmptyListCTA title="There are no variables yet" buttonIcon="calculator-alt" buttonTitle="Add variable" infoBox={{ __html: ` <p> Variables enable more interactive and dynamic dashboards. Instead of hard-coding things like server or sensor names in your metric queries you can use variables in their place. Variables are shown as list boxes at the top of the dashboard. These drop-down lists make it easy to change the data being displayed in your dashboard. Check out the <a class="external-link" href="https://grafana.com/docs/grafana/latest/variables/" target="_blank"> Templates and variables documentation </a> for more information. </p>`, }} infoBoxTitle="What do variables do?" onClick={(event) => { event.preventDefault(); onAdd(); }} /> </div> ); }
public/app/features/variables/editor/VariableEditorList.tsx
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.0012291271705180407, 0.00037000307929702103, 0.00016516698815394193, 0.00019912961579393595, 0.00035030036815442145 ]
{ "id": 11, "code_window": [ " enableReset={true}\n", " onChange={({ title, id }) => {\n", " return props.onChange({ title, id });\n", " }}\n", " />\n", " );\n", " },\n", " category: ['Filter'],\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " showRoot={false}\n", " allowEmpty={true}\n", " initialTitle={props.value?.title}\n", " initialFolderId={props.value?.id}\n", " permissionLevel={PermissionLevelString.View}\n", " onClear={() => props.onChange('')}\n", " {...props}\n" ], "file_path": "public/app/plugins/panel/alertlist/module.tsx", "type": "replace", "edit_start_line_idx": 243 }
package dtos import ( "fmt" "time" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" ) func formatShort(interval time.Duration) string { var result string hours := interval / time.Hour if hours > 0 { result += fmt.Sprintf("%dh", hours) } remaining := interval - (hours * time.Hour) mins := remaining / time.Minute if mins > 0 { result += fmt.Sprintf("%dm", mins) } remaining -= (mins * time.Minute) seconds := remaining / time.Second if seconds > 0 { result += fmt.Sprintf("%ds", seconds) } return result } func NewAlertNotification(notification *models.AlertNotification) *AlertNotification { dto := &AlertNotification{ Id: notification.Id, Uid: notification.Uid, Name: notification.Name, Type: notification.Type, IsDefault: notification.IsDefault, Created: notification.Created, Updated: notification.Updated, Frequency: formatShort(notification.Frequency), SendReminder: notification.SendReminder, DisableResolveMessage: notification.DisableResolveMessage, Settings: notification.Settings, SecureFields: map[string]bool{}, } if notification.SecureSettings != nil { for k := range notification.SecureSettings { dto.SecureFields[k] = true } } return dto } type AlertNotification struct { Id int64 `json:"id"` Uid string `json:"uid"` Name string `json:"name"` Type string `json:"type"` IsDefault bool `json:"isDefault"` SendReminder bool `json:"sendReminder"` DisableResolveMessage bool `json:"disableResolveMessage"` Frequency string `json:"frequency"` Created time.Time `json:"created"` Updated time.Time `json:"updated"` Settings *simplejson.Json `json:"settings"` SecureFields map[string]bool `json:"secureFields"` } func NewAlertNotificationLookup(notification *models.AlertNotification) *AlertNotificationLookup { return &AlertNotificationLookup{ Id: notification.Id, Uid: notification.Uid, Name: notification.Name, Type: notification.Type, IsDefault: notification.IsDefault, } } type AlertNotificationLookup struct { Id int64 `json:"id"` Uid string `json:"uid"` Name string `json:"name"` Type string `json:"type"` IsDefault bool `json:"isDefault"` } type AlertTestCommand struct { Dashboard *simplejson.Json `json:"dashboard" binding:"Required"` PanelId int64 `json:"panelId" binding:"Required"` } type AlertTestResult struct { Firing bool `json:"firing"` State models.AlertStateType `json:"state"` ConditionEvals string `json:"conditionEvals"` TimeMs string `json:"timeMs"` Error string `json:"error,omitempty"` EvalMatches []*EvalMatch `json:"matches,omitempty"` Logs []*AlertTestResultLog `json:"logs,omitempty"` } type AlertTestResultLog struct { Message string `json:"message"` Data interface{} `json:"data"` } type EvalMatch struct { Tags map[string]string `json:"tags,omitempty"` Metric string `json:"metric"` Value null.Float `json:"value"` } type NotificationTestCommand struct { ID int64 `json:"id,omitempty"` Name string `json:"name"` Type string `json:"type"` SendReminder bool `json:"sendReminder"` DisableResolveMessage bool `json:"disableResolveMessage"` Frequency string `json:"frequency"` Settings *simplejson.Json `json:"settings"` SecureSettings map[string]string `json:"secureSettings"` } type PauseAlertCommand struct { AlertId int64 `json:"alertId"` Paused bool `json:"paused"` } type PauseAllAlertsCommand struct { Paused bool `json:"paused"` }
pkg/api/dtos/alerting.go
0
https://github.com/grafana/grafana/commit/b1e1a97c63c46238d468a2de01d48a92bacae825
[ 0.001858820440247655, 0.0003030340594705194, 0.00016443597269244492, 0.00017119146650657058, 0.0004325163899920881 ]
{ "id": 0, "code_window": [ "ion-checkbox {\n", " cursor: pointer;\n", " @include user-select-none();\n", "}\n", "\n", "ion-checkbox[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-checkbox[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/checkbox/checkbox.scss", "type": "replace", "edit_start_line_idx": 10 }
// Radio // -------------------------------------------------- ion-radio { display: block; cursor: pointer; @include user-select-none(); } ion-radio[aria-disabled=true] > * { opacity: 0.5; color: $subdued-text-color; pointer-events: none; }
ionic/components/radio/radio.scss
1
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0362788587808609, 0.02277468331158161, 0.009270508773624897, 0.02277468331158161, 0.013504174537956715 ]
{ "id": 0, "code_window": [ "ion-checkbox {\n", " cursor: pointer;\n", " @include user-select-none();\n", "}\n", "\n", "ion-checkbox[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-checkbox[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/checkbox/checkbox.scss", "type": "replace", "edit_start_line_idx": 10 }
export class Geo { static reverseGeocode(lat, lng) { return new Promise((resolve, reject) => { let geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'latLng': new google.maps.LatLng(lat, lng) }, (results, status) => { if (status == google.maps.GeocoderStatus.OK) { console.log('Reverse', results); if(results.length > 1) { var r = results[1]; var a, types; var parts = []; var foundLocality = false; var foundState = false; for(var i = 0; i < r.address_components.length; i++) { a = r.address_components[i]; types = a.types; for(var j = 0; j < types.length; j++) { if(!foundLocality && types[j] == 'locality') { foundLocality = true; parts.push(a.long_name); } else if(!foundState && types[j] == 'administrative_area_level_1') { foundState = true; parts.push(a.short_name); } } } console.log('Reverse', parts); resolve(parts.join(', ')); } } else { console.log('reverse fail', results, status); reject(results); } }); }); } static getLocation() { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition((position) => { resolve(position); }, (error) => { reject(error); }) }); } }
demos/weather/geo.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0001754130789777264, 0.00017375359311699867, 0.0001722626475384459, 0.00017363802180625498, 0.0000012173558161521214 ]
{ "id": 0, "code_window": [ "ion-checkbox {\n", " cursor: pointer;\n", " @include user-select-none();\n", "}\n", "\n", "ion-checkbox[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-checkbox[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/checkbox/checkbox.scss", "type": "replace", "edit_start_line_idx": 10 }
<ion-view> <ion-menu id="menu" side="left" [content]="content" (opening)="onMenuOpening($event, amt)"> <ion-list inset [parallax]="menuOpenAmount"> <ion-item> Search </ion-item> <ion-item> Browse </ion-item> <ion-item> Activity </ion-item> <ion-item> Radio </ion-item> <ion-item> Your Music </ion-item> <ion-item> Settings </ion-item> </ion-list> </ion-menu> <ion-nav #content [root]="rootView"></ion-nav> <style> ion-view { background-color: black !important; } .toolbar-container { background-color: #202020 !important; } #menu { background: url('http://ionic-io-assets.s3.amazonaws.com/menu.jpg'); background-size: cover; } .mode-ios .list .item { background: transparent; min-height: 55px; } .mode-ios .list .item ion-item-content { background: transparent; color: rgba(255,255,255,0.8); padding: 10px; } .mode-ios .toolbar-ios ion-title { color: white; font-size: 14px; font-weight: normal; letter-spacing: 2px; } #menu ion-item .item-label { font-size: 22px; } ion-content { background: transparent !important; } .mode-ios #menu ion-item-content:after { background: none; } .mode-ios .item:first-of-type:before { background: none !important; } .mode-ios .item:last-of-type:after { background: none !important; } .mode-ios .toolbar-container-ios:after { background: none; } ion-nav { background: black; } .nav-item { background: white; } </style> </ion-view>
demos/music/main.html
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.00031192274764180183, 0.000206719123525545, 0.00016571786545682698, 0.00017941227997653186, 0.00005375265754992142 ]
{ "id": 0, "code_window": [ "ion-checkbox {\n", " cursor: pointer;\n", " @include user-select-none();\n", "}\n", "\n", "ion-checkbox[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-checkbox[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/checkbox/checkbox.scss", "type": "replace", "edit_start_line_idx": 10 }
// Copyright 2014 Google Inc. All rights reserved. // // 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. (function(scope) { // consume* functions return a 2 value array of [parsed-data, '' or not-yet consumed input] // Regex should be anchored with /^ function consumeToken(regex, string) { var result = regex.exec(string); if (result) { result = regex.ignoreCase ? result[0].toLowerCase() : result[0]; return [result, string.substr(result.length)]; } } function consumeTrimmed(consumer, string) { string = string.replace(/^\s*/, ''); var result = consumer(string); if (result) { return [result[0], result[1].replace(/^\s*/, '')]; } } function consumeRepeated(consumer, separator, string) { consumer = consumeTrimmed.bind(null, consumer); var list = []; while (true) { var result = consumer(string); if (!result) { return [list, string]; } list.push(result[0]); string = result[1]; result = consumeToken(separator, string); if (!result || result[1] == '') { return [list, string]; } string = result[1]; } } // Consumes a token or expression with balanced parentheses function consumeParenthesised(parser, string) { var nesting = 0; for (var n = 0; n < string.length; n++) { if (/\s|,/.test(string[n]) && nesting == 0) { break; } else if (string[n] == '(') { nesting++; } else if (string[n] == ')') { nesting--; if (nesting == 0) n++; if (nesting <= 0) break; } } var parsed = parser(string.substr(0, n)); return parsed == undefined ? undefined : [parsed, string.substr(n)]; } function lcm(a, b) { var c = a; var d = b; while (c && d) c > d ? c %= d : d %= c; c = (a * b) / (c + d); return c; } function ignore(value) { return function(input) { var result = value(input); if (result) result[0] = undefined; return result; } } function optional(value, defaultValue) { return function(input) { var result = value(input); if (result) return result; return [defaultValue, input]; } } function consumeList(list, input) { var output = []; for (var i = 0; i < list.length; i++) { var result = scope.consumeTrimmed(list[i], input); if (!result || result[0] == '') return; if (result[0] !== undefined) output.push(result[0]); input = result[1]; } if (input == '') { return output; } } function mergeWrappedNestedRepeated(wrap, nestedMerge, separator, left, right) { var matchingLeft = []; var matchingRight = []; var reconsititution = []; var length = lcm(left.length, right.length); for (var i = 0; i < length; i++) { var thing = nestedMerge(left[i % left.length], right[i % right.length]); if (!thing) { return; } matchingLeft.push(thing[0]); matchingRight.push(thing[1]); reconsititution.push(thing[2]); } return [matchingLeft, matchingRight, function(positions) { var result = positions.map(function(position, i) { return reconsititution[i](position); }).join(separator); return wrap ? wrap(result) : result; }]; } function mergeList(left, right, list) { var lefts = []; var rights = []; var functions = []; var j = 0; for (var i = 0; i < list.length; i++) { if (typeof list[i] == 'function') { var result = list[i](left[j], right[j++]); lefts.push(result[0]); rights.push(result[1]); functions.push(result[2]); } else { (function(pos) { lefts.push(false); rights.push(false); functions.push(function() { return list[pos]; }); })(i); } } return [lefts, rights, function(results) { var result = ''; for (var i = 0; i < results.length; i++) { result += functions[i](results[i]); } return result; }]; } scope.consumeToken = consumeToken; scope.consumeTrimmed = consumeTrimmed; scope.consumeRepeated = consumeRepeated; scope.consumeParenthesised = consumeParenthesised; scope.ignore = ignore; scope.optional = optional; scope.consumeList = consumeList; scope.mergeNestedRepeated = mergeWrappedNestedRepeated.bind(null, null); scope.mergeWrappedNestedRepeated = mergeWrappedNestedRepeated; scope.mergeList = mergeList; })(webAnimations1);
scripts/resources/web-animations-js/src/handler-utils.js
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0001785625354386866, 0.00017444528930354863, 0.00017113414651248604, 0.00017444515833631158, 0.00000199945088752429 ]
{ "id": 1, "code_window": [ " @include user-select-none();\n", "}\n", "\n", "ion-radio[aria-disabled=true] > * {\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", " pointer-events: none;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-radio[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/radio/radio.scss", "type": "replace", "edit_start_line_idx": 11 }
// Switch // -------------------------------------------------- ion-switch { display: block; @include user-select-none(); } ion-switch media-switch { margin: 0; cursor: pointer; } ion-switch[aria-disabled=true] > * { pointer-events: none; opacity: 0.5; color: $subdued-text-color; }
ionic/components/switch/switch.scss
1
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.007860803976655006, 0.0027698513586074114, 0.0001786683133104816, 0.0002700813056435436, 0.0036000406835228205 ]
{ "id": 1, "code_window": [ " @include user-select-none();\n", "}\n", "\n", "ion-radio[aria-disabled=true] > * {\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", " pointer-events: none;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-radio[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/radio/radio.scss", "type": "replace", "edit_start_line_idx": 11 }
import {App} from 'ionic/ionic'; @App({ templateUrl: 'main.html' }) class E2EApp {}
ionic/components/item/test/text/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0001692596124485135, 0.0001692596124485135, 0.0001692596124485135, 0.0001692596124485135, 0 ]
{ "id": 1, "code_window": [ " @include user-select-none();\n", "}\n", "\n", "ion-radio[aria-disabled=true] > * {\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", " pointer-events: none;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-radio[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/radio/radio.scss", "type": "replace", "edit_start_line_idx": 11 }
import {Directive, Optional} from 'angular2/angular2'; import {NavController} from './nav-controller'; import {NavRegistry} from './nav-registry'; /** * Directive for declaratively linking to a new page instead of using * [NavController.push()](../NavController/#push). Similar to ui-router's `ui-sref`. * * Basic usage: * ```html * <button [nav-push]="pushPage"></button> * ``` * To specify parameters you can use array syntax or the `nav-params` property: * ```html * <button [nav-push]="pushPage" [nav-params]="params"></button> * ``` * Where `pushPage` and `params` are specified in your component, and `pushPage` * contains a reference to a [@Page component](../../../config/Page/): * * ```ts * import {LoginPage} from 'login'; * @Page({ * template: `<button [nav-push]="pushPage" [nav-params]="params"></button>` * }) * class MyPage { * constructor(){ * this.pushPage = LoginPage; * this.params = { id: 42 }; * } * } * ``` * * ### Alternate syntax * You can also use syntax similar to Angular2's router, passing an array to * NavPush: * ```html * <button [nav-push]="[pushPage, params]"></button> * ``` */ @Directive({ selector: '[nav-push]', inputs: [ 'instruction: navPush', 'params: navParams' ], host: { '(click)': 'onClick()', 'role': 'link' } }) export class NavPush { /** * TODO * @param {NavController} nav TODO */ constructor(@Optional() nav: NavController, registry: NavRegistry) { this.nav = nav; this.registry = registry; if (!nav) { console.error('nav-push must be within a NavController'); } } onClick() { let destination, params; if (this.instruction instanceof Array) { if (this.instruction.length > 2) { throw 'Too many [nav-push] arguments, expects [View, { params }]' } destination = this.instruction[0]; params = this.instruction[1] || this.params; } else { destination = this.instruction; params = this.params; } if (typeof destination === "string") { destination = this.registry.get(destination); } this.nav && this.nav.push(destination, params); } } /** * TODO */ @Directive({ selector: '[nav-pop]', host: { '(click)': 'onClick()', 'role': 'link' } }) export class NavPop { /** * TODO * @param {NavController} nav TODO */ constructor(@Optional() nav: NavController) { this.nav = nav; if (!nav) { console.error('nav-pop must be within a NavController'); } } onClick() { this.nav && this.nav.pop(); } }
ionic/components/nav/nav-push.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0002037791273323819, 0.00017254961130674928, 0.00016627546574454755, 0.00016930297715589404, 0.000009888796739687677 ]
{ "id": 1, "code_window": [ " @include user-select-none();\n", "}\n", "\n", "ion-radio[aria-disabled=true] > * {\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", " pointer-events: none;\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-radio[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/radio/radio.scss", "type": "replace", "edit_start_line_idx": 11 }
import {FormBuilder, Control, ControlGroup, Validators} from 'angular2/angular2'; import {App, IonicView, Animation, Modal, NavController, NavParams} from 'ionic/ionic'; @IonicView({ templateUrl: 'detail.html' }) export class DetailPage { constructor(params: NavParams) { this.post = params.post; } } @IonicView({ templateUrl: 'feed.html' }) export class FeedPage { constructor(nav: NavController) { this.nav = nav; this.filterForm = new ControlGroup({ filterControl: new Control("") }); this.posts = [ { text: 'I tried to keep both arts alive, but the camera won. I found that while the camera does not express the soul, perhaps a photograph can!', image: 'http://ionic-io-assets.s3.amazonaws.com/images/p.jpg', day: 5 }, { text: 'It is good to realize that if love and peace can prevail on earth, and if we can teach our children to honor nature\'s gifts, the joys and beauties of the outdoors will be here forever.', image: 'http://ionic-io-assets.s3.amazonaws.com/images/p1.png', day: 6 }, { text: 'I see humanity now as one vast plant, needing for its highest fulfillment only love, the natural blessings of the great outdoors, and intelligent crossing and selection.', image: 'http://ionic-io-assets.s3.amazonaws.com/images/p2.png', day: 7 }, { text: 'You must not lose faith in humanity. Humanity is an ocean; if a few drops of the ocean are dirty, the ocean does not become dirty.', image: 'http://ionic-io-assets.s3.amazonaws.com/images/p3.png', day: 7 }, { text: 'Keep close to Nature\'s heart... and break clear away, once in awhile, and climb a mountain or spend a week in the woods. Wash your spirit clean.', image: 'http://ionic-io-assets.s3.amazonaws.com/images/p4.png', day: 8 } ]; } postClicked(event, post) { console.log('Post clicked'); this.nav.push(DetailPage, { post: post }); event.preventDefault(); } } @App({ templateUrl: 'main.html' }) class IonicApp { constructor(modal: Modal) { this.modal = modal; this.rootView = FeedPage; } openHeart() { console.log('openHeart'); this.modal.open(HeartModal, { enterAnimation: 'my-fade-in', leaveAnimation: 'my-fade-out' }); } openGear() { console.log('openGear'); this.modal.open(SettingsModal, { enterAnimation: 'my-fade-in', leaveAnimation: 'my-fade-out' }); } } @IonicView({ template: '<ion-view id="settings-modal"><ion-content padding><button (click)="close()">Close</button></ion-content></ion-view>' }) export class SettingsModal {} @IonicView({ template: '<ion-view id="heart-modal"><button icon (click)="close()"><i class="icon ion-close"></i></button><h2>20</h2><p>You\'re pretty awesome</p></ion-view>' }) export class HeartModal {} class FadeIn extends Animation { constructor(element) { super(element); this .easing('ease') .duration(250) .fadeIn(); } } Animation.register('my-fade-in', FadeIn); class FadeOut extends Animation { constructor(element) { super(element); this .easing('ease') .duration(250) .fadeOut(); } } Animation.register('my-fade-out', FadeOut);
demos/snapcat/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.00021550062228925526, 0.0001742244348861277, 0.0001656327222008258, 0.00017042270337697119, 0.00001229996996698901 ]
{ "id": 2, "code_window": [ " margin: 0;\n", " cursor: pointer;\n", "}\n", "\n", "ion-switch[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-switch[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/switch/switch.scss", "type": "replace", "edit_start_line_idx": 15 }
// Checkbox // -------------------------------------------------- ion-checkbox { cursor: pointer; @include user-select-none(); } ion-checkbox[aria-disabled=true] > * { pointer-events: none; opacity: 0.5; color: $subdued-text-color; }
ionic/components/checkbox/checkbox.scss
1
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.016559582203626633, 0.014239996671676636, 0.011920412071049213, 0.014239996671676636, 0.0023195850662887096 ]
{ "id": 2, "code_window": [ " margin: 0;\n", " cursor: pointer;\n", "}\n", "\n", "ion-switch[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-switch[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/switch/switch.scss", "type": "replace", "edit_start_line_idx": 15 }
import {Page} from 'ionic/ionic'; import {forwardRef} from 'angular2/angular2'; import {AndroidAttribute} from '../../helpers'; @Page({ templateUrl: 'buttons/sizes/sizes.html', directives: [forwardRef(() => AndroidAttribute)] }) export class SizesPage { constructor() { } }
demos/component-docs/buttons/sizes/pages.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.00017437183123547584, 0.00017341066268272698, 0.00017244950868189335, 0.00017341066268272698, 9.611612767912447e-7 ]
{ "id": 2, "code_window": [ " margin: 0;\n", " cursor: pointer;\n", "}\n", "\n", "ion-switch[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-switch[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/switch/switch.scss", "type": "replace", "edit_start_line_idx": 15 }
import {App, IonicView, NavController} from 'ionic/ionic'; @App({ templateUrl: 'main.html' }) class IonicApp { constructor() { this.root = TabsPage; } } @IonicView({ template: '' + '<ion-navbar *navbar>' + '<ion-title>Home</ion-title>' + '</ion-navbar>' + '<ion-content padding>' + 'home' + '</ion-content>' }) class HomeTabPage { constructor(nav: NavController) { this.nav = nav; } push() { } } @IonicView({ template: '' + '<ion-navbar *navbar>' + '<ion-title>Peek</ion-title>' + '</ion-navbar>' + '<ion-content padding>' + 'peek' + '</ion-content>' }) class PeekTabPage { constructor(nav: NavController) { this.nav = nav; } push() { } } @IonicView({ templateUrl: 'tabs.html' }) class TabsPage { constructor() { this.homeTab = HomeTabPage; this.peekTab = PeekTabPage; } }
demos/yerk/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0005193119868636131, 0.00024348539591301233, 0.0001677651598583907, 0.00017320584447588772, 0.00012730961316265166 ]
{ "id": 2, "code_window": [ " margin: 0;\n", " cursor: pointer;\n", "}\n", "\n", "ion-switch[aria-disabled=true] > * {\n", " pointer-events: none;\n", " opacity: 0.5;\n", " color: $subdued-text-color;\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "ion-switch[aria-disabled=true] .item-inner > * {\n" ], "file_path": "ionic/components/switch/switch.scss", "type": "replace", "edit_start_line_idx": 15 }
import {App, NavController} from 'ionic/ionic'; import {Page, Config, IonicApp} from 'ionic/ionic'; import {NavParams, NavController, ViewController} from 'ionic/ionic'; import {SearchPipe} from 'ionic/components/searchbar/searchbar'; @App({ templateUrl: 'main.html' }) class IonicApp { toolbarSearch: string; constructor() { } }
ionic/components/searchbar/test/toolbar/index.ts
0
https://github.com/ionic-team/ionic-framework/commit/0ab3e230e0e8d6e1a0bf30fdfdfff0de8340f31b
[ 0.0001691773213678971, 0.00016916007734835148, 0.00016914281877689064, 0.00016916007734835148, 1.7251297279585742e-8 ]
{ "id": 0, "code_window": [ " .description('ensure browsers necessary for this version of Playwright are installed')\n", " .option('--with-deps', 'install system dependencies for browsers')\n", " .action(async function(args: string[], command: program.Command) {\n", " try {\n", " if (!args.length) {\n", " if (command.opts().withDeps)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " const executables = registry.defaultExecutables();\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 115 }
#!/usr/bin/env node /** * 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. */ /* eslint-disable no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9977941513061523, 0.034995678812265396, 0.00016311345098074526, 0.00017322160420008004, 0.17913903295993805 ]
{ "id": 0, "code_window": [ " .description('ensure browsers necessary for this version of Playwright are installed')\n", " .option('--with-deps', 'install system dependencies for browsers')\n", " .action(async function(args: string[], command: program.Command) {\n", " try {\n", " if (!args.length) {\n", " if (command.opts().withDeps)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " const executables = registry.defaultExecutables();\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 115 }
/** * 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 extract from 'extract-zip'; import fs from 'fs'; import readline from 'readline'; import os from 'os'; import path from 'path'; import rimraf from 'rimraf'; import { createPlaywright } from '../../playwright'; import { PersistentSnapshotStorage, TraceModel } from './traceModel'; import { ServerRouteHandler, HttpServer } from '../../../utils/httpServer'; import { SnapshotServer } from '../../snapshot/snapshotServer'; import * as consoleApiSource from '../../../generated/consoleApiSource'; import { isUnderTest } from '../../../utils/utils'; import { internalCallMetadata } from '../../instrumentation'; import { ProgressController } from '../../progress'; import { BrowserContext } from '../../browserContext'; import { registry } from '../../../utils/registry'; import { installAppIcon } from '../../chromium/crApp'; export class TraceViewer { private _server: HttpServer; private _browserName: string; constructor(tracesDir: string, browserName: string) { this._browserName = browserName; const resourcesDir = path.join(tracesDir, 'resources'); // Served by TraceServer // - "/tracemodel" - json with trace model. // // Served by TraceViewer // - "/traceviewer/..." - our frontend. // - "/file?filePath" - local files, used by sources tab. // - "/sha1/<sha1>" - trace resource bodies, used by network previews. // // Served by SnapshotServer // - "/resources/" - network resources from the trace. // - "/snapshot/" - root for snapshot frame. // - "/snapshot/pageId/..." - actual snapshot html. // - "/snapshot/service-worker.js" - service worker that intercepts snapshot resources // and translates them into network requests. const actionTraces = fs.readdirSync(tracesDir).filter(name => name.endsWith('.trace')); const debugNames = actionTraces.map(name => { const tracePrefix = path.join(tracesDir, name.substring(0, name.indexOf('.trace'))); return path.basename(tracePrefix); }); this._server = new HttpServer(); const traceListHandler: ServerRouteHandler = (request, response) => { response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(debugNames)); return true; }; this._server.routePath('/contexts', traceListHandler); const snapshotStorage = new PersistentSnapshotStorage(resourcesDir); new SnapshotServer(this._server, snapshotStorage); const traceModelHandler: ServerRouteHandler = (request, response) => { const debugName = request.url!.substring('/context/'.length); snapshotStorage.clear(); response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); (async () => { const traceFile = path.join(tracesDir, debugName + '.trace'); const match = debugName.match(/^(.*)-\d+$/); const networkFile = path.join(tracesDir, (match ? match[1] : debugName) + '.network'); const model = new TraceModel(snapshotStorage); await appendTraceEvents(model, traceFile); if (fs.existsSync(networkFile)) await appendTraceEvents(model, networkFile); model.build(); response.end(JSON.stringify(model.contextEntry)); })().catch(e => console.error(e)); return true; }; this._server.routePrefix('/context/', traceModelHandler); const traceViewerHandler: ServerRouteHandler = (request, response) => { const relativePath = request.url!.substring('/traceviewer/'.length); const absolutePath = path.join(__dirname, '..', '..', '..', 'web', ...relativePath.split('/')); return this._server.serveFile(response, absolutePath); }; this._server.routePrefix('/traceviewer/', traceViewerHandler); const fileHandler: ServerRouteHandler = (request, response) => { try { const url = new URL('http://localhost' + request.url!); const search = url.search; if (search[0] !== '?') return false; return this._server.serveFile(response, search.substring(1)); } catch (e) { return false; } }; this._server.routePath('/file', fileHandler); const sha1Handler: ServerRouteHandler = (request, response) => { const sha1 = request.url!.substring('/sha1/'.length); if (sha1.includes('/')) return false; return this._server.serveFile(response, path.join(resourcesDir!, sha1)); }; this._server.routePrefix('/sha1/', sha1Handler); } async show(headless: boolean): Promise<BrowserContext> { const urlPrefix = await this._server.start(); const traceViewerPlaywright = createPlaywright('javascript', true); const traceViewerBrowser = isUnderTest() ? 'chromium' : this._browserName; const args = traceViewerBrowser === 'chromium' ? [ '--app=data:text/html,', '--window-size=1280,800' ] : []; if (isUnderTest()) args.push(`--remote-debugging-port=0`); // For Chromium, fall back to the stable channels of popular vendors for work out of the box. // Null means no installation and no channels found. let channel = null; if (traceViewerBrowser === 'chromium') { for (const name of ['chromium', 'chrome', 'msedge']) { try { registry.findExecutable(name)!.executablePathOrDie(traceViewerPlaywright.options.sdkLanguage); channel = name === 'chromium' ? undefined : name; break; } catch (e) { } } if (channel === null) { // TODO: language-specific error message, or fallback to default error. throw new Error(` ================================================================== Please run 'npx playwright install' to install Playwright browsers ================================================================== `); } } const context = await traceViewerPlaywright[traceViewerBrowser as 'chromium'].launchPersistentContext(internalCallMetadata(), '', { // TODO: store language in the trace. channel: channel as any, args, noDefaultViewport: true, headless, useWebSocket: isUnderTest() }); const controller = new ProgressController(internalCallMetadata(), context._browser); await controller.run(async progress => { await context._browser._defaultContext!._loadDefaultContextAsIs(progress); }); await context.extendInjectedScript(consoleApiSource.source); const [page] = context.pages(); if (traceViewerBrowser === 'chromium') await installAppIcon(page); if (isUnderTest()) page.on('close', () => context.close(internalCallMetadata()).catch(() => {})); else page.on('close', () => process.exit()); await page.mainFrame().goto(internalCallMetadata(), urlPrefix + '/traceviewer/traceViewer/index.html'); return context; } } async function appendTraceEvents(model: TraceModel, file: string) { const fileStream = fs.createReadStream(file, 'utf8'); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); for await (const line of rl as any) model.appendEvent(line); } export async function showTraceViewer(tracePath: string, browserName: string, headless = false): Promise<BrowserContext | undefined> { let stat; try { stat = fs.statSync(tracePath); } catch (e) { console.log(`No such file or directory: ${tracePath}`); // eslint-disable-line no-console return; } if (stat.isDirectory()) { const traceViewer = new TraceViewer(tracePath, browserName); return await traceViewer.show(headless); } const zipFile = tracePath; const dir = fs.mkdtempSync(path.join(os.tmpdir(), `playwright-trace`)); process.on('exit', () => rimraf.sync(dir)); try { await extract(zipFile, { dir }); } catch (e) { console.log(`Invalid trace file: ${zipFile}`); // eslint-disable-line no-console return; } const traceViewer = new TraceViewer(dir, browserName); return await traceViewer.show(headless); }
src/server/trace/viewer/traceViewer.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0002790629514493048, 0.00017694632697384804, 0.0001655667001614347, 0.0001723203167784959, 0.00002200162816734519 ]
{ "id": 0, "code_window": [ " .description('ensure browsers necessary for this version of Playwright are installed')\n", " .option('--with-deps', 'install system dependencies for browsers')\n", " .action(async function(args: string[], command: program.Command) {\n", " try {\n", " if (!args.length) {\n", " if (command.opts().withDeps)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " const executables = registry.defaultExecutables();\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 115 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications 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 { test as it, expect } from './pageTest'; it('should work', async ({page}) => { const aHandle = await page.evaluateHandle(() => ({foo: 'bar'})); const json = await aHandle.jsonValue(); expect(json).toEqual({foo: 'bar'}); }); it('should work with dates', async ({page}) => { const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z')); const date = await dateHandle.jsonValue(); expect(date.toJSON()).toBe('2017-09-26T00:00:00.000Z'); }); it('should throw for circular objects', async ({page}) => { const windowHandle = await page.evaluateHandle('window'); let error = null; await windowHandle.jsonValue().catch(e => error = e); expect(error.message).toContain('Argument is a circular structure'); });
tests/page/jshandle-json-value.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017632279195822775, 0.00017319207836408168, 0.00016875746950972825, 0.00017384403327014297, 0.000002854504373317468 ]
{ "id": 0, "code_window": [ " .description('ensure browsers necessary for this version of Playwright are installed')\n", " .option('--with-deps', 'install system dependencies for browsers')\n", " .action(async function(args: string[], command: program.Command) {\n", " try {\n", " if (!args.length) {\n", " if (command.opts().withDeps)\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " const executables = registry.defaultExecutables();\n" ], "file_path": "src/cli/cli.ts", "type": "add", "edit_start_line_idx": 115 }
<script> window.geolocationPromise = new Promise(resolve => { navigator.geolocation.getCurrentPosition(position => { resolve({latitude: position.coords.latitude, longitude: position.coords.longitude}); }); }); </script>
tests/assets/geolocation.html
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017423421377316117, 0.00017423421377316117, 0.00017423421377316117, 0.00017423421377316117, 0 ]
{ "id": 1, "code_window": [ " if (command.opts().withDeps)\n", " await registry.installDeps();\n", " await registry.install();\n", " } else {\n", " const executables = checkBrowsersToInstall(args);\n", " if (command.opts().withDeps)\n", " await registry.installDeps(executables);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(executables);\n", " await registry.install(executables);\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 116 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications 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 os from 'os'; import path from 'path'; import * as util from 'util'; import * as fs from 'fs'; import lockfile from 'proper-lockfile'; import { getUbuntuVersion } from './ubuntuVersion'; import { getFromENV, getAsBooleanFromENV, calculateSha1, removeFolders, existsAsync, hostPlatform, canAccessFile, spawnAsync, fetchData, wrapInASCIIBox } from './utils'; import { DependencyGroup, installDependenciesLinux, installDependenciesWindows, validateDependenciesLinux, validateDependenciesWindows } from './dependencies'; import { downloadBrowserWithProgressBar, logPolitely } from './browserFetcher'; const PACKAGE_PATH = path.join(__dirname, '..', '..'); const BIN_PATH = path.join(__dirname, '..', '..', 'bin'); const EXECUTABLE_PATHS = { 'chromium': { 'ubuntu18.04': ['chrome-linux', 'chrome'], 'ubuntu20.04': ['chrome-linux', 'chrome'], 'mac10.13': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.14': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.15': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11-arm64': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'win32': ['chrome-win', 'chrome.exe'], 'win64': ['chrome-win', 'chrome.exe'], }, 'firefox': { 'ubuntu18.04': ['firefox', 'firefox'], 'ubuntu20.04': ['firefox', 'firefox'], 'mac10.13': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.14': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.15': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11-arm64': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'win32': ['firefox', 'firefox.exe'], 'win64': ['firefox', 'firefox.exe'], }, 'webkit': { 'ubuntu18.04': ['pw_run.sh'], 'ubuntu20.04': ['pw_run.sh'], 'mac10.13': undefined, 'mac10.14': ['pw_run.sh'], 'mac10.15': ['pw_run.sh'], 'mac11': ['pw_run.sh'], 'mac11-arm64': ['pw_run.sh'], 'win32': ['Playwright.exe'], 'win64': ['Playwright.exe'], }, 'ffmpeg': { 'ubuntu18.04': ['ffmpeg-linux'], 'ubuntu20.04': ['ffmpeg-linux'], 'mac10.13': ['ffmpeg-mac'], 'mac10.14': ['ffmpeg-mac'], 'mac10.15': ['ffmpeg-mac'], 'mac11': ['ffmpeg-mac'], 'mac11-arm64': ['ffmpeg-mac'], 'win32': ['ffmpeg-win32.exe'], 'win64': ['ffmpeg-win64.exe'], }, }; const DOWNLOAD_URLS = { 'chromium': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-win64.zip', }, 'chromium-with-symbols': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-with-symbols-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-with-symbols-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-with-symbols-win64.zip', }, 'firefox': { 'ubuntu18.04': '%s/builds/firefox/%s/firefox-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox/%s/firefox-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.14': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.15': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox/%s/firefox-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox/%s/firefox-win32.zip', 'win64': '%s/builds/firefox/%s/firefox-win64.zip', }, 'firefox-beta': { 'ubuntu18.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.14': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.15': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox-beta/%s/firefox-beta-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox-beta/%s/firefox-beta-win32.zip', 'win64': '%s/builds/firefox-beta/%s/firefox-beta-win64.zip', }, 'webkit': { 'ubuntu18.04': '%s/builds/webkit/%s/webkit-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/webkit/%s/webkit-ubuntu-20.04.zip', 'mac10.13': undefined, 'mac10.14': '%s/builds/deprecated-webkit-mac-10.14/%s/deprecated-webkit-mac-10.14.zip', 'mac10.15': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11-arm64': '%s/builds/webkit/%s/webkit-mac-11.0-arm64.zip', 'win32': '%s/builds/webkit/%s/webkit-win64.zip', 'win64': '%s/builds/webkit/%s/webkit-win64.zip', }, 'ffmpeg': { 'ubuntu18.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'ubuntu20.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'mac10.13': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.14': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.15': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11-arm64': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'win32': '%s/builds/ffmpeg/%s/ffmpeg-win32.zip', 'win64': '%s/builds/ffmpeg/%s/ffmpeg-win64.zip', }, }; export const registryDirectory = (() => { let result: string; const envDefined = getFromENV('PLAYWRIGHT_BROWSERS_PATH'); if (envDefined === '0') { result = path.join(__dirname, '..', '..', '.local-browsers'); } else if (envDefined) { result = envDefined; } else { let cacheDirectory: string; if (process.platform === 'linux') cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'); else if (process.platform === 'darwin') cacheDirectory = path.join(os.homedir(), 'Library', 'Caches'); else if (process.platform === 'win32') cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'); else throw new Error('Unsupported platform: ' + process.platform); result = path.join(cacheDirectory, 'ms-playwright'); } if (!path.isAbsolute(result)) { // It is important to resolve to the absolute path: // - for unzipping to work correctly; // - so that registry directory matches between installation and execution. // INIT_CWD points to the root of `npm/yarn install` and is probably what // the user meant when typing the relative path. result = path.resolve(getFromENV('INIT_CWD') || process.cwd(), result); } return result; })(); function isBrowserDirectory(browserDirectory: string): boolean { const baseName = path.basename(browserDirectory); for (const browserName of allDownloadable) { if (baseName.startsWith(browserName + '-')) return true; } return false; } type BrowsersJSON = { comment: string browsers: { name: string, revision: string, installByDefault: boolean, revisionOverrides?: {[os: string]: string}, }[] }; type BrowsersJSONDescriptor = { name: string, revision: string, installByDefault: boolean, dir: string, }; function readDescriptors(browsersJSON: BrowsersJSON) { return (browsersJSON['browsers']).map(obj => { const name = obj.name; const revisionOverride = (obj.revisionOverrides || {})[hostPlatform]; const revision = revisionOverride || obj.revision; const browserDirectoryPrefix = revisionOverride ? `${name}_${hostPlatform}_special` : `${name}`; const descriptor: BrowsersJSONDescriptor = { name, revision, installByDefault: !!obj.installByDefault, // Method `isBrowserDirectory` determines directory to be browser iff // it starts with some browser name followed by '-'. Some browser names // are prefixes of others, e.g. 'webkit' is a prefix of `webkit-technology-preview`. // To avoid older registries erroneously removing 'webkit-technology-preview', we have to // ensure that browser folders to never include dashes inside. dir: path.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, '_') + '-' + revision), }; return descriptor; }); } export type BrowserName = 'chromium' | 'firefox' | 'webkit'; type InternalTool = 'ffmpeg' | 'firefox-beta' | 'chromium-with-symbols'; type ChromiumChannel = 'chrome' | 'chrome-beta' | 'chrome-dev' | 'chrome-canary' | 'msedge' | 'msedge-beta' | 'msedge-dev' | 'msedge-canary'; const allDownloadable = ['chromium', 'firefox', 'webkit', 'ffmpeg', 'firefox-beta', 'chromium-with-symbols']; export interface Executable { type: 'browser' | 'tool' | 'channel'; name: BrowserName | InternalTool | ChromiumChannel; browserName: BrowserName | undefined; installType: 'download-by-default' | 'download-on-demand' | 'install-script' | 'none'; directory: string | undefined; executablePathOrDie(sdkLanguage: string): string; executablePath(): string | undefined; validateHostRequirements(): Promise<void>; } interface ExecutableImpl extends Executable { _install?: () => Promise<void>; _dependencyGroup?: DependencyGroup; } export class Registry { private _executables: ExecutableImpl[]; constructor(browsersJSON: BrowsersJSON) { const descriptors = readDescriptors(browsersJSON); const findExecutablePath = (dir: string, name: keyof typeof EXECUTABLE_PATHS) => { const tokens = EXECUTABLE_PATHS[name][hostPlatform]; return tokens ? path.join(dir, ...tokens) : undefined; }; const executablePathOrDie = (name: string, e: string | undefined, installByDefault: boolean, sdkLanguage: string) => { if (!e) throw new Error(`${name} is not supported on ${hostPlatform}`); const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install${installByDefault ? '' : ' ' + name}`); if (!canAccessFile(e)) { const prettyMessage = [ `Looks like Playwright Test or Playwright was just installed or updated.`, `Please run the following command to download new browser${installByDefault ? 's' : ''}:`, ``, ` ${installCommand}`, ``, `<3 Playwright Team`, ].join('\n'); throw new Error(`Executable doesn't exist at ${e}\n${wrapInASCIIBox(prettyMessage, 1)}`); } return e; }; this._executables = []; const chromium = descriptors.find(d => d.name === 'chromium')!; const chromiumExecutable = findExecutablePath(chromium.dir, 'chromium'); this._executables.push({ type: 'browser', name: 'chromium', browserName: 'chromium', directory: chromium.dir, executablePath: () => chromiumExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium', chromiumExecutable, chromium.installByDefault, sdkLanguage), installType: chromium.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromium.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromium, chromiumExecutable, DOWNLOAD_URLS['chromium'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); const chromiumWithSymbols = descriptors.find(d => d.name === 'chromium-with-symbols')!; const chromiumWithSymbolsExecutable = findExecutablePath(chromiumWithSymbols.dir, 'chromium'); this._executables.push({ type: 'tool', name: 'chromium-with-symbols', browserName: 'chromium', directory: chromiumWithSymbols.dir, executablePath: () => chromiumWithSymbolsExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium-with-symbols', chromiumWithSymbolsExecutable, chromiumWithSymbols.installByDefault, sdkLanguage), installType: chromiumWithSymbols.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromiumWithSymbols.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromiumWithSymbols, chromiumWithSymbolsExecutable, DOWNLOAD_URLS['chromium-with-symbols'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); this._executables.push(this._createChromiumChannel('chrome', { 'linux': '/opt/google/chrome/chrome', 'darwin': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', 'win32': `\\Google\\Chrome\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome', { 'linux': 'reinstall_chrome_stable_linux.sh', 'darwin': 'reinstall_chrome_stable_mac.sh', 'win32': 'reinstall_chrome_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-beta', { 'linux': '/opt/google/chrome-beta/chrome', 'darwin': '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta', 'win32': `\\Google\\Chrome Beta\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome-beta', { 'linux': 'reinstall_chrome_beta_linux.sh', 'darwin': 'reinstall_chrome_beta_mac.sh', 'win32': 'reinstall_chrome_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-dev', { 'linux': '/opt/google/chrome-unstable/chrome', 'darwin': '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev', 'win32': `\\Google\\Chrome Dev\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('chrome-canary', { 'linux': '', 'darwin': '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary', 'win32': `\\Google\\Chrome SxS\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('msedge', { 'linux': '', 'darwin': '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', 'win32': `\\Microsoft\\Edge\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge', { 'linux': '', 'darwin': 'reinstall_msedge_stable_mac.sh', 'win32': 'reinstall_msedge_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-beta', { 'linux': '/opt/microsoft/msedge-beta/msedge', 'darwin': '/Applications/Microsoft Edge Beta.app/Contents/MacOS/Microsoft Edge Beta', 'win32': `\\Microsoft\\Edge Beta\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-beta', { 'darwin': 'reinstall_msedge_beta_mac.sh', 'linux': 'reinstall_msedge_beta_linux.sh', 'win32': 'reinstall_msedge_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-dev', { 'linux': '/opt/microsoft/msedge-dev/msedge', 'darwin': '/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev', 'win32': `\\Microsoft\\Edge Dev\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-dev', { 'darwin': 'reinstall_msedge_dev_mac.sh', 'linux': 'reinstall_msedge_dev_linux.sh', 'win32': 'reinstall_msedge_dev_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-canary', { 'linux': '', 'darwin': '/Applications/Microsoft Edge Canary.app/Contents/MacOS/Microsoft Edge Canary', 'win32': `\\Microsoft\\Edge SxS\\Application\\msedge.exe`, })); const firefox = descriptors.find(d => d.name === 'firefox')!; const firefoxExecutable = findExecutablePath(firefox.dir, 'firefox'); this._executables.push({ type: 'browser', name: 'firefox', browserName: 'firefox', directory: firefox.dir, executablePath: () => firefoxExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox', firefoxExecutable, firefox.installByDefault, sdkLanguage), installType: firefox.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefox.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefox, firefoxExecutable, DOWNLOAD_URLS['firefox'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const firefoxBeta = descriptors.find(d => d.name === 'firefox-beta')!; const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, 'firefox'); this._executables.push({ type: 'tool', name: 'firefox-beta', browserName: 'firefox', directory: firefoxBeta.dir, executablePath: () => firefoxBetaExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox-beta', firefoxBetaExecutable, firefoxBeta.installByDefault, sdkLanguage), installType: firefoxBeta.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefoxBeta.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefoxBeta, firefoxBetaExecutable, DOWNLOAD_URLS['firefox-beta'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const webkit = descriptors.find(d => d.name === 'webkit')!; const webkitExecutable = findExecutablePath(webkit.dir, 'webkit'); const webkitLinuxLddDirectories = [ path.join('minibrowser-gtk'), path.join('minibrowser-gtk', 'bin'), path.join('minibrowser-gtk', 'lib'), path.join('minibrowser-wpe'), path.join('minibrowser-wpe', 'bin'), path.join('minibrowser-wpe', 'lib'), ]; this._executables.push({ type: 'browser', name: 'webkit', browserName: 'webkit', directory: webkit.dir, executablePath: () => webkitExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('webkit', webkitExecutable, webkit.installByDefault, sdkLanguage), installType: webkit.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('webkit', webkit.dir, webkitLinuxLddDirectories, ['libGLESv2.so.2', 'libx264.so'], ['']), _install: () => this._downloadExecutable(webkit, webkitExecutable, DOWNLOAD_URLS['webkit'][hostPlatform], 'PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST'), _dependencyGroup: 'webkit', }); const ffmpeg = descriptors.find(d => d.name === 'ffmpeg')!; const ffmpegExecutable = findExecutablePath(ffmpeg.dir, 'ffmpeg'); this._executables.push({ type: 'tool', name: 'ffmpeg', browserName: undefined, directory: ffmpeg.dir, executablePath: () => ffmpegExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('ffmpeg', ffmpegExecutable, ffmpeg.installByDefault, sdkLanguage), installType: ffmpeg.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => Promise.resolve(), _install: () => this._downloadExecutable(ffmpeg, ffmpegExecutable, DOWNLOAD_URLS['ffmpeg'][hostPlatform], 'PLAYWRIGHT_FFMPEG_DOWNLOAD_HOST'), _dependencyGroup: 'tools', }); } private _createChromiumChannel(name: ChromiumChannel, lookAt: Record<'linux' | 'darwin' | 'win32', string>, install?: () => Promise<void>): ExecutableImpl { const executablePath = (shouldThrow: boolean) => { const suffix = lookAt[process.platform as 'linux' | 'darwin' | 'win32']; if (!suffix) { if (shouldThrow) throw new Error(`Chromium distribution '${name}' is not supported on ${process.platform}`); return undefined; } const prefixes = (process.platform === 'win32' ? [ process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'] ].filter(Boolean) : ['']) as string[]; for (const prefix of prefixes) { const executablePath = path.join(prefix, suffix); if (canAccessFile(executablePath)) return executablePath; } if (!shouldThrow) return undefined; const location = prefixes.length ? ` at ${path.join(prefixes[0], suffix)}` : ``; // TODO: language-specific error message const installation = install ? `\nRun "npx playwright install ${name}"` : ''; throw new Error(`Chromium distribution '${name}' is not found${location}${installation}`); }; return { type: 'channel', name, browserName: 'chromium', directory: undefined, executablePath: () => executablePath(false), executablePathOrDie: (sdkLanguage: string) => executablePath(true)!, installType: install ? 'install-script' : 'none', validateHostRequirements: () => Promise.resolve(), _install: install, }; } executables(): Executable[] { return this._executables; } findExecutable(name: BrowserName): Executable; findExecutable(name: string): Executable | undefined; findExecutable(name: string): Executable | undefined { return this._executables.find(b => b.name === name); } private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] { const set = new Set<ExecutableImpl>(); if (!executables) executables = this._executables.filter(executable => executable.installType === 'download-by-default'); for (const executable of executables as ExecutableImpl[]) { set.add(executable); if (executable.browserName === 'chromium') set.add(this.findExecutable('ffmpeg')!); } return Array.from(set); } private async _validateHostRequirements(browserName: BrowserName, browserDirectory: string, linuxLddDirectories: string[], dlOpenLibraries: string[], windowsExeAndDllDirectories: string[]) { if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS')) { process.stdout.write('Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n'); return; } const ubuntuVersion = await getUbuntuVersion(); if (browserName === 'firefox' && ubuntuVersion === '16.04') throw new Error(`Cannot launch Firefox on Ubuntu 16.04! Minimum required Ubuntu version for Firefox browser is 18.04`); if (os.platform() === 'linux') return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries); if (os.platform() === 'win32' && os.arch() === 'x64') return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d))); } async installDeps(executablesToInstallDeps?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstallDeps); const targets = new Set<DependencyGroup>(); for (const executable of executables) { if (executable._dependencyGroup) targets.add(executable._dependencyGroup); } targets.add('tools'); if (os.platform() === 'win32') return await installDependenciesWindows(targets); if (os.platform() === 'linux') return await installDependenciesLinux(targets); } async install(executablesToInstall?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstall); await fs.promises.mkdir(registryDirectory, { recursive: true }); const lockfilePath = path.join(registryDirectory, '__dirlock'); const releaseLock = await lockfile.lock(registryDirectory, { retries: { retries: 10, // Retry 20 times during 10 minutes with // exponential back-off. // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions factor: 1.27579, }, onCompromised: (err: Error) => { throw new Error(`${err.message} Path: ${lockfilePath}`); }, lockfilePath, }); const linksDir = path.join(registryDirectory, '.links'); try { // Create a link first, so that cache validation does not remove our own browsers. await fs.promises.mkdir(linksDir, { recursive: true }); await fs.promises.writeFile(path.join(linksDir, calculateSha1(PACKAGE_PATH)), PACKAGE_PATH); // Remove stale browsers. await this._validateInstallationCache(linksDir); // Install browsers for this package. for (const executable of executables) { if (executable._install) await executable._install(); else throw new Error(`ERROR: Playwright does not support installing ${executable.name}`); } } catch (e) { if (e.code === 'ELOCKED') { const rmCommand = process.platform === 'win32' ? 'rm -R' : 'rm -rf'; throw new Error('\n' + wrapInASCIIBox([ `An active lockfile is found at:`, ``, ` ${lockfilePath}`, ``, `Either:`, `- wait a few minutes if other Playwright is installing browsers in parallel`, `- remove lock manually with:`, ``, ` ${rmCommand} ${lockfilePath}`, ``, `<3 Playwright Team`, ].join('\n'), 1)); } else { throw e; } } finally { await releaseLock(); } } private async _downloadExecutable(descriptor: BrowsersJSONDescriptor, executablePath: string | undefined, downloadURLTemplate: string | undefined, downloadHostEnv: string) { if (!downloadURLTemplate || !executablePath) throw new Error(`ERROR: Playwright does not support ${descriptor.name} on ${hostPlatform}`); const downloadHost = (downloadHostEnv && getFromENV(downloadHostEnv)) || getFromENV('PLAYWRIGHT_DOWNLOAD_HOST') || 'https://playwright.azureedge.net'; const downloadURL = util.format(downloadURLTemplate, downloadHost, descriptor.revision); const title = `${descriptor.name} v${descriptor.revision}`; const downloadFileName = `playwright-download-${descriptor.name}-${hostPlatform}-${descriptor.revision}.zip`; await downloadBrowserWithProgressBar(title, descriptor.dir, executablePath, downloadURL, downloadFileName).catch(e => { throw new Error(`Failed to download ${title}, caused by\n${e.stack}`); }); await fs.promises.writeFile(markerFilePath(descriptor.dir), ''); } private async _installMSEdgeChannel(channel: 'msedge'|'msedge-beta'|'msedge-dev', scripts: Record<'linux' | 'darwin' | 'win32', string>) { const scriptArgs: string[] = []; if (process.platform !== 'linux') { const products = JSON.parse(await fetchData({ url: 'https://edgeupdates.microsoft.com/api/products' })); const productName = { 'msedge': 'Stable', 'msedge-beta': 'Beta', 'msedge-dev': 'Dev', }[channel]; const product = products.find((product: any) => product.Product === productName); const searchConfig = ({ darwin: {platform: 'MacOS', arch: 'universal', artifact: 'pkg'}, win32: {platform: 'Windows', arch: os.arch() === 'x64' ? 'x64' : 'x86', artifact: 'msi'}, } as any)[process.platform]; const release = searchConfig ? product.Releases.find((release: any) => release.Platform === searchConfig.platform && release.Architecture === searchConfig.arch) : null; const artifact = release ? release.Artifacts.find((artifact: any) => artifact.ArtifactName === searchConfig.artifact) : null; if (artifact) scriptArgs.push(artifact.Location /* url */); else throw new Error(`Cannot install ${channel} on ${process.platform}`); } await this._installChromiumChannel(channel, scripts, scriptArgs); } private async _installChromiumChannel(channel: string, scripts: Record<'linux' | 'darwin' | 'win32', string>, scriptArgs: string[] = []) { const scriptName = scripts[process.platform as 'linux' | 'darwin' | 'win32']; if (!scriptName) throw new Error(`Cannot install ${channel} on ${process.platform}`); const shell = scriptName.endsWith('.ps1') ? 'powershell.exe' : 'bash'; const { code } = await spawnAsync(shell, [path.join(BIN_PATH, scriptName), ...scriptArgs], { cwd: BIN_PATH, stdio: 'inherit' }); if (code !== 0) throw new Error(`Failed to install ${channel}`); } private async _validateInstallationCache(linksDir: string) { // 1. Collect used downloads and package descriptors. const usedBrowserPaths: Set<string> = new Set(); for (const fileName of await fs.promises.readdir(linksDir)) { const linkPath = path.join(linksDir, fileName); let linkTarget = ''; try { linkTarget = (await fs.promises.readFile(linkPath)).toString(); const browsersJSON = require(path.join(linkTarget, 'browsers.json')); const descriptors = readDescriptors(browsersJSON); for (const browserName of allDownloadable) { // We retain browsers if they are found in the descriptor. // Note, however, that there are older versions out in the wild that rely on // the "download" field in the browser descriptor and use its value // to retain and download browsers. // As of v1.10, we decided to abandon "download" field. const descriptor = descriptors.find(d => d.name === browserName); if (!descriptor) continue; const usedBrowserPath = descriptor.dir; const browserRevision = parseInt(descriptor.revision, 10); // Old browser installations don't have marker file. const shouldHaveMarkerFile = (browserName === 'chromium' && browserRevision >= 786218) || (browserName === 'firefox' && browserRevision >= 1128) || (browserName === 'webkit' && browserRevision >= 1307) || // All new applications have a marker file right away. (browserName !== 'firefox' && browserName !== 'chromium' && browserName !== 'webkit'); if (!shouldHaveMarkerFile || (await existsAsync(markerFilePath(usedBrowserPath)))) usedBrowserPaths.add(usedBrowserPath); } } catch (e) { await fs.promises.unlink(linkPath).catch(e => {}); } } // 2. Delete all unused browsers. if (!getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_GC')) { let downloadedBrowsers = (await fs.promises.readdir(registryDirectory)).map(file => path.join(registryDirectory, file)); downloadedBrowsers = downloadedBrowsers.filter(file => isBrowserDirectory(file)); const directories = new Set<string>(downloadedBrowsers); for (const browserDirectory of usedBrowserPaths) directories.delete(browserDirectory); for (const directory of directories) logPolitely('Removing unused browser at ' + directory); await removeFolders([...directories]); } } } function markerFilePath(browserDirectory: string): string { return path.join(browserDirectory, 'INSTALLATION_COMPLETE'); } function buildPlaywrightCLICommand(sdkLanguage: string, parameters: string): string { switch (sdkLanguage) { case 'python': return `playwright ${parameters}`; case 'java': return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="${parameters}"`; case 'csharp': return `playwright ${parameters}`; default: return `npx playwright ${parameters}`; } } export async function installDefaultBrowsersForNpmInstall() { // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1 if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) { logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set'); return false; } await registry.install(); } export const registry = new Registry(require('../../browsers.json'));
src/utils/registry.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9972783923149109, 0.028157128021121025, 0.00016367759963031858, 0.0001700976863503456, 0.16356992721557617 ]
{ "id": 1, "code_window": [ " if (command.opts().withDeps)\n", " await registry.installDeps();\n", " await registry.install();\n", " } else {\n", " const executables = checkBrowsersToInstall(args);\n", " if (command.opts().withDeps)\n", " await registry.installDeps(executables);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(executables);\n", " await registry.install(executables);\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 116 }
#!/bin/bash set -e if [[ -z "${ANDROID_HOME}" ]]; then export SDKDIR=$PWD/.android-sdk export ANDROID_HOME=${SDKDIR} export ANDROID_SDK_ROOT=${SDKDIR} fi ${ANDROID_HOME}/tools/bin/avdmanager delete avd --name android31 || true echo "y" | ${ANDROID_HOME}/tools/bin/sdkmanager --install "system-images;android-31;google_apis;x86_64" echo "no" | ${ANDROID_HOME}/tools/bin/avdmanager create avd --force --name android31 --device "Nexus 5X" --package "system-images;android-31;google_apis;x86_64" ${ANDROID_HOME}/emulator/emulator -list-avds
utils/avd_recreate.sh
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0001713516394374892, 0.00017064361600205302, 0.0001699355780147016, 0.00017064361600205302, 7.080307113938034e-7 ]
{ "id": 1, "code_window": [ " if (command.opts().withDeps)\n", " await registry.installDeps();\n", " await registry.install();\n", " } else {\n", " const executables = checkBrowsersToInstall(args);\n", " if (command.opts().withDeps)\n", " await registry.installDeps(executables);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(executables);\n", " await registry.install(executables);\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 116 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications 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 { contextTest as it, expect } from './config/browserTest'; it('should return no cookies in pristine browser context', async ({context, page, server}) => { expect(await context.cookies()).toEqual([]); }); it('should get a cookie', async ({context, page, server, browserName}) => { await page.goto(server.EMPTY_PAGE); const documentCookie = await page.evaluate(() => { document.cookie = 'username=John Doe'; return document.cookie; }); expect(documentCookie).toBe('username=John Doe'); expect(await context.cookies()).toEqual([{ name: 'username', value: 'John Doe', domain: 'localhost', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: browserName === 'chromium' ? 'Lax' : 'None', }]); }); it('should get a non-session cookie', async ({context, page, server, browserName}) => { await page.goto(server.EMPTY_PAGE); // @see https://en.wikipedia.org/wiki/Year_2038_problem const date = +(new Date('1/1/2038')); const documentCookie = await page.evaluate(timestamp => { const date = new Date(timestamp); document.cookie = `username=John Doe;expires=${date.toUTCString()}`; return document.cookie; }, date); expect(documentCookie).toBe('username=John Doe'); expect(await context.cookies()).toEqual([{ name: 'username', value: 'John Doe', domain: 'localhost', path: '/', expires: date / 1000, httpOnly: false, secure: false, sameSite: browserName === 'chromium' ? 'Lax' : 'None', }]); }); it('should properly report httpOnly cookie', async ({context, page, server}) => { server.setRoute('/empty.html', (req, res) => { res.setHeader('Set-Cookie', 'name=value;HttpOnly; Path=/'); res.end(); }); await page.goto(server.EMPTY_PAGE); const cookies = await context.cookies(); expect(cookies.length).toBe(1); expect(cookies[0].httpOnly).toBe(true); }); it('should properly report "Strict" sameSite cookie', async ({context, page, server, browserName, platform}) => { it.fail(browserName === 'webkit' && platform === 'win32'); server.setRoute('/empty.html', (req, res) => { res.setHeader('Set-Cookie', 'name=value;SameSite=Strict'); res.end(); }); await page.goto(server.EMPTY_PAGE); const cookies = await context.cookies(); expect(cookies.length).toBe(1); expect(cookies[0].sameSite).toBe('Strict'); }); it('should properly report "Lax" sameSite cookie', async ({context, page, server, browserName, platform}) => { it.fail(browserName === 'webkit' && platform === 'win32'); server.setRoute('/empty.html', (req, res) => { res.setHeader('Set-Cookie', 'name=value;SameSite=Lax'); res.end(); }); await page.goto(server.EMPTY_PAGE); const cookies = await context.cookies(); expect(cookies.length).toBe(1); expect(cookies[0].sameSite).toBe('Lax'); }); it('should get multiple cookies', async ({context, page, server, browserName}) => { await page.goto(server.EMPTY_PAGE); const documentCookie = await page.evaluate(() => { document.cookie = 'username=John Doe'; document.cookie = 'password=1234'; return document.cookie.split('; ').sort().join('; '); }); const cookies = new Set(await context.cookies()); expect(documentCookie).toBe('password=1234; username=John Doe'); expect(cookies).toEqual(new Set([ { name: 'password', value: '1234', domain: 'localhost', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: browserName === 'chromium' ? 'Lax' : 'None', }, { name: 'username', value: 'John Doe', domain: 'localhost', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: browserName === 'chromium' ? 'Lax' : 'None', }, ])); }); it('should get cookies from multiple urls', async ({context, browserName, isWindows}) => { await context.addCookies([{ url: 'https://foo.com', name: 'doggo', value: 'woofs', sameSite: 'None', }, { url: 'https://bar.com', name: 'catto', value: 'purrs', sameSite: 'Lax', }, { url: 'https://baz.com', name: 'birdo', value: 'tweets', sameSite: 'Lax', }]); const cookies = new Set(await context.cookies(['https://foo.com', 'https://baz.com'])); expect(cookies).toEqual(new Set([{ name: 'birdo', value: 'tweets', domain: 'baz.com', path: '/', expires: -1, httpOnly: false, secure: true, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }, { name: 'doggo', value: 'woofs', domain: 'foo.com', path: '/', expires: -1, httpOnly: false, secure: true, sameSite: 'None', }])); }); it('should work with subdomain cookie', async ({context, browserName, isWindows}) => { await context.addCookies([{ domain: '.foo.com', path: '/', name: 'doggo', value: 'woofs', sameSite: 'Lax', secure: true }]); expect(await context.cookies('https://foo.com')).toEqual([{ name: 'doggo', value: 'woofs', domain: '.foo.com', path: '/', expires: -1, httpOnly: false, secure: true, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }]); expect(await context.cookies('https://sub.foo.com')).toEqual([{ name: 'doggo', value: 'woofs', domain: '.foo.com', path: '/', expires: -1, httpOnly: false, secure: true, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }]); }); it('should not return cookies with empty value', async ({context, page, server}) => { server.setRoute('/empty.html', (req, res) => { res.setHeader('Set-Cookie', 'name=;Path=/'); res.end(); }); await page.goto(server.EMPTY_PAGE); const cookies = await context.cookies(); expect(cookies.length).toBe(0); }); it('should return secure cookies based on HTTP(S) protocol', async ({context, browserName, isWindows}) => { await context.addCookies([{ url: 'https://foo.com', name: 'doggo', value: 'woofs', sameSite: 'Lax', secure: true }, { url: 'http://foo.com', name: 'catto', value: 'purrs', sameSite: 'Lax', secure: false }]); const cookies = new Set(await context.cookies('https://foo.com')); expect(cookies).toEqual(new Set([{ name: 'catto', value: 'purrs', domain: 'foo.com', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }, { name: 'doggo', value: 'woofs', domain: 'foo.com', path: '/', expires: -1, httpOnly: false, secure: true, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }])); expect(await context.cookies('http://foo.com/')).toEqual([{ name: 'catto', value: 'purrs', domain: 'foo.com', path: '/', expires: -1, httpOnly: false, secure: false, sameSite: (browserName === 'webkit' && isWindows) ? 'None' : 'Lax', }]); });
tests/browsercontext-cookies.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017720850883051753, 0.00017462742107454687, 0.00016756435798015445, 0.0001749715011101216, 0.000002330774350411957 ]
{ "id": 1, "code_window": [ " if (command.opts().withDeps)\n", " await registry.installDeps();\n", " await registry.install();\n", " } else {\n", " const executables = checkBrowsersToInstall(args);\n", " if (command.opts().withDeps)\n", " await registry.installDeps(executables);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(executables);\n", " await registry.install(executables);\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 116 }
#!/bin/bash set -e set +x trap "cd $(pwd -P)" EXIT cd "$(dirname "$0")" REMOTE_BROWSER_UPSTREAM="browser_upstream" BUILD_BRANCH="playwright-build" # COLORS RED=$'\e[1;31m' GRN=$'\e[1;32m' YEL=$'\e[1;33m' END=$'\e[0m' if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: export.sh [firefox|webkit] [custom_checkout_path]" echo echo "Exports patch from the current branch of the checkout to browser folder." echo "The checkout has to be 'prepared', meaning that 'prepare_checkout.sh' should be" echo "run against it first." echo echo "You can optionally specify custom_checkout_path if you have browser checkout somewhere else" echo "and wish to export patches from it." echo exit 0 fi if [[ $# == 0 ]]; then echo "missing browser: 'firefox' or 'webkit'" echo "try './export.sh --help' for more information" exit 1 fi # FRIENDLY_CHECKOUT_PATH is used only for logging. FRIENDLY_CHECKOUT_PATH=""; BUILD_NUMBER_UPSTREAM_URL="" CHECKOUT_PATH="" EXPORT_PATH="" EXTRA_FOLDER_PW_PATH="" EXTRA_FOLDER_CHECKOUT_RELPATH="" if [[ ("$1" == "firefox") || ("$1" == "firefox/") || ("$1" == "ff") ]]; then FRIENDLY_CHECKOUT_PATH="//browser_patches/firefox/checkout"; CHECKOUT_PATH="$PWD/firefox/checkout" EXTRA_FOLDER_PW_PATH="$PWD/firefox/juggler" EXTRA_FOLDER_CHECKOUT_RELPATH="juggler" EXPORT_PATH="$PWD/firefox" BUILD_NUMBER_UPSTREAM_URL="https://raw.githubusercontent.com/microsoft/playwright/master/browser_patches/firefox/BUILD_NUMBER" source "./firefox/UPSTREAM_CONFIG.sh" if [[ ! -z "${FF_CHECKOUT_PATH}" ]]; then echo "WARNING: using checkout path from FF_CHECKOUT_PATH env: ${FF_CHECKOUT_PATH}" CHECKOUT_PATH="${FF_CHECKOUT_PATH}" FRIENDLY_CHECKOUT_PATH="<FF_CHECKOUT_PATH>" fi elif [[ ("$1" == "firefox-beta") || ("$1" == "ff-beta") ]]; then # NOTE: firefox-beta re-uses firefox checkout. FRIENDLY_CHECKOUT_PATH="//browser_patches/firefox/checkout"; CHECKOUT_PATH="$PWD/firefox/checkout" EXTRA_FOLDER_PW_PATH="$PWD/firefox-beta/juggler" EXTRA_FOLDER_CHECKOUT_RELPATH="juggler" EXPORT_PATH="$PWD/firefox-beta" BUILD_NUMBER_UPSTREAM_URL="https://raw.githubusercontent.com/microsoft/playwright/master/browser_patches/firefox-beta/BUILD_NUMBER" source "./firefox-beta/UPSTREAM_CONFIG.sh" if [[ ! -z "${FF_CHECKOUT_PATH}" ]]; then echo "WARNING: using checkout path from FF_CHECKOUT_PATH env: ${FF_CHECKOUT_PATH}" CHECKOUT_PATH="${FF_CHECKOUT_PATH}" FRIENDLY_CHECKOUT_PATH="<FF_CHECKOUT_PATH>" fi elif [[ ("$1" == "webkit") || ("$1" == "webkit/") || ("$1" == "wk") ]]; then FRIENDLY_CHECKOUT_PATH="//browser_patches/webkit/checkout"; CHECKOUT_PATH="$PWD/webkit/checkout" EXTRA_FOLDER_PW_PATH="$PWD/webkit/embedder/Playwright" EXTRA_FOLDER_CHECKOUT_RELPATH="Tools/Playwright" EXPORT_PATH="$PWD/webkit" BUILD_NUMBER_UPSTREAM_URL="https://raw.githubusercontent.com/microsoft/playwright/master/browser_patches/webkit/BUILD_NUMBER" source "./webkit/UPSTREAM_CONFIG.sh" if [[ ! -z "${WK_CHECKOUT_PATH}" ]]; then echo "WARNING: using checkout path from WK_CHECKOUT_PATH env: ${WK_CHECKOUT_PATH}" CHECKOUT_PATH="${WK_CHECKOUT_PATH}" FRIENDLY_CHECKOUT_PATH="<WK_CHECKOUT_PATH>" fi else echo ERROR: unknown browser to export - "$1" exit 1 fi # we will use this just for beauty. if [[ $# == 2 ]]; then echo "WARNING: using custom checkout path $2" CHECKOUT_PATH=$2 FRIENDLY_CHECKOUT_PATH="<custom_checkout ( $2 )>" fi # if there's no checkout folder - bail out. if ! [[ -d $CHECKOUT_PATH ]]; then echo "ERROR: $FRIENDLY_CHECKOUT_PATH is missing - nothing to export." exit 1; else echo "-- checking $FRIENDLY_CHECKOUT_PATH exists - OK" fi # if folder exists but not a git repository - bail out. if ! [[ -d $CHECKOUT_PATH/.git ]]; then echo "ERROR: $FRIENDLY_CHECKOUT_PATH is not a git repository! Nothing to export." exit 1 else echo "-- checking $FRIENDLY_CHECKOUT_PATH is a git repo - OK" fi # Switch to git repository. cd "$CHECKOUT_PATH" # Setting up |$REMOTE_BROWSER_UPSTREAM| remote and fetch the $BASE_BRANCH if git remote get-url $REMOTE_BROWSER_UPSTREAM >/dev/null; then if ! [[ $(git config --get remote.$REMOTE_BROWSER_UPSTREAM.url || echo "") == "$REMOTE_URL" ]]; then echo "ERROR: remote $REMOTE_BROWSER_UPSTREAM is not pointing to '$REMOTE_URL'! run 'prepare_checkout.sh' first" exit 1 fi else echo "ERROR: checkout does not have $REMOTE_BROWSER_UPSTREAM; run 'prepare_checkout.sh' first" exit 1 fi # Check if git repo is dirty. if [[ -n $(git status -s --untracked-files=no) ]]; then echo "ERROR: $FRIENDLY_CHECKOUT_PATH has dirty GIT state - aborting export." exit 1 else echo "-- checking $FRIENDLY_CHECKOUT_PATH is clean - OK" fi PATCH_NAME=$(ls -1 "$EXPORT_PATH"/patches) if [[ -z "$PATCH_NAME" ]]; then PATCH_NAME="bootstrap.diff" OLD_DIFF="" else OLD_DIFF=$(cat "$EXPORT_PATH"/patches/$PATCH_NAME) fi CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) NEW_BASE_REVISION=$(git merge-base $REMOTE_BROWSER_UPSTREAM/"$BASE_BRANCH" "$CURRENT_BRANCH") NEW_DIFF=$(git diff --diff-algorithm=myers --full-index "$NEW_BASE_REVISION" "$CURRENT_BRANCH" -- . ":!${EXTRA_FOLDER_CHECKOUT_RELPATH}") # Increment BUILD_NUMBER BUILD_NUMBER=$(curl ${BUILD_NUMBER_UPSTREAM_URL} | head -1) BUILD_NUMBER=$((BUILD_NUMBER+1)) echo "REMOTE_URL=\"$REMOTE_URL\" BASE_BRANCH=\"$BASE_BRANCH\" BASE_REVISION=\"$NEW_BASE_REVISION\"" > "$EXPORT_PATH"/UPSTREAM_CONFIG.sh echo "$NEW_DIFF" > "$EXPORT_PATH"/patches/$PATCH_NAME echo $BUILD_NUMBER > "$EXPORT_PATH"/BUILD_NUMBER echo "Changed: $(git config user.email) $(date)" >> "$EXPORT_PATH"/BUILD_NUMBER echo "-- exporting standalone folder" rm -rf "${EXTRA_FOLDER_PW_PATH}" mkdir -p $(dirname "${EXTRA_FOLDER_PW_PATH}") cp -r "${EXTRA_FOLDER_CHECKOUT_RELPATH}" "${EXTRA_FOLDER_PW_PATH}" NEW_BASE_REVISION_TEXT="$NEW_BASE_REVISION (not changed)" if [[ "$NEW_BASE_REVISION" != "$BASE_REVISION" ]]; then NEW_BASE_REVISION_TEXT="$YEL$NEW_BASE_REVISION (changed)$END" fi echo "==============================================================" echo " Repository: $FRIENDLY_CHECKOUT_PATH" echo " Changes between branches: $REMOTE_BROWSER_UPSTREAM/$BASE_BRANCH..$CURRENT_BRANCH" echo " BASE_REVISION: $NEW_BASE_REVISION_TEXT" echo " BUILD_NUMBER: $YEL$BUILD_NUMBER (changed)$END" echo "==============================================================" echo
browser_patches/export.sh
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00019277172395959496, 0.00017043175466824323, 0.00016446922381874174, 0.000169776554685086, 0.000005827577751915669 ]
{ "id": 2, "code_window": [ " .command('install-deps [browser...]')\n", " .description('install dependencies necessary to run browsers (will ask for sudo permissions)')\n", " .action(async function(args: string[]) {\n", " try {\n", " if (!args.length)\n", " await registry.installDeps();\n", " else\n", " await registry.installDeps(checkBrowsersToInstall(args));\n", " } catch (e) {\n", " console.log(`Failed to install browser dependencies\\n${e}`);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(registry.defaultExecutables());\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 145 }
#!/usr/bin/env node /** * 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. */ /* eslint-disable no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9984819293022156, 0.01828482188284397, 0.00016139137733262032, 0.00017316626326646656, 0.12886925041675568 ]
{ "id": 2, "code_window": [ " .command('install-deps [browser...]')\n", " .description('install dependencies necessary to run browsers (will ask for sudo permissions)')\n", " .action(async function(args: string[]) {\n", " try {\n", " if (!args.length)\n", " await registry.installDeps();\n", " else\n", " await registry.installDeps(checkBrowsersToInstall(args));\n", " } catch (e) {\n", " console.log(`Failed to install browser dependencies\\n${e}`);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(registry.defaultExecutables());\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 145 }
/** * 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. */ export * from '../../../types/test'; export * from '../../../types/types'; export { default } from '../../../types/test';
tests/playwright-test/entry/index.d.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017629776266403496, 0.00017556280363351107, 0.00017482783005107194, 0.00017556280363351107, 7.349663064815104e-7 ]
{ "id": 2, "code_window": [ " .command('install-deps [browser...]')\n", " .description('install dependencies necessary to run browsers (will ask for sudo permissions)')\n", " .action(async function(args: string[]) {\n", " try {\n", " if (!args.length)\n", " await registry.installDeps();\n", " else\n", " await registry.installDeps(checkBrowsersToInstall(args));\n", " } catch (e) {\n", " console.log(`Failed to install browser dependencies\\n${e}`);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(registry.defaultExecutables());\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 145 }
/** * 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 { chromium, firefox, webkit, selectors, devices, errors } from 'playwright'; import playwright from 'playwright'; import errorsFile from 'playwright/lib/utils/errors.js'; import testESM from './esm.mjs'; testESM({ chromium, firefox, webkit, selectors, devices, errors, playwright, errorsFile }, [chromium, firefox, webkit]);
packages/installation-tests/esm-playwright.mjs
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017716358706820756, 0.00017493688210379332, 0.00017281921464018524, 0.00017482783005107194, 0.0000017752579424268333 ]
{ "id": 2, "code_window": [ " .command('install-deps [browser...]')\n", " .description('install dependencies necessary to run browsers (will ask for sudo permissions)')\n", " .action(async function(args: string[]) {\n", " try {\n", " if (!args.length)\n", " await registry.installDeps();\n", " else\n", " await registry.installDeps(checkBrowsersToInstall(args));\n", " } catch (e) {\n", " console.log(`Failed to install browser dependencies\\n${e}`);\n", " process.exit(1);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await registry.installDeps(registry.defaultExecutables());\n" ], "file_path": "src/cli/cli.ts", "type": "replace", "edit_start_line_idx": 145 }
<?xml version="1.0" encoding="utf-8"?> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@drawable/ic_launcher_background" /> <foreground android:drawable="@drawable/ic_launcher_foreground" /> </adaptive-icon>
src/server/android/driver/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0001707548653939739, 0.0001707548653939739, 0.0001707548653939739, 0.0001707548653939739, 0 ]
{ "id": 3, "code_window": [ " findExecutable(name: string): Executable | undefined {\n", " return this._executables.find(b => b.name === name);\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] {\n", " const set = new Set<ExecutableImpl>();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " defaultExecutables(): Executable[] {\n", " return this._executables.filter(e => e.installType === 'download-by-default');\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[]): ExecutableImpl[] {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 489 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications 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 os from 'os'; import path from 'path'; import * as util from 'util'; import * as fs from 'fs'; import lockfile from 'proper-lockfile'; import { getUbuntuVersion } from './ubuntuVersion'; import { getFromENV, getAsBooleanFromENV, calculateSha1, removeFolders, existsAsync, hostPlatform, canAccessFile, spawnAsync, fetchData, wrapInASCIIBox } from './utils'; import { DependencyGroup, installDependenciesLinux, installDependenciesWindows, validateDependenciesLinux, validateDependenciesWindows } from './dependencies'; import { downloadBrowserWithProgressBar, logPolitely } from './browserFetcher'; const PACKAGE_PATH = path.join(__dirname, '..', '..'); const BIN_PATH = path.join(__dirname, '..', '..', 'bin'); const EXECUTABLE_PATHS = { 'chromium': { 'ubuntu18.04': ['chrome-linux', 'chrome'], 'ubuntu20.04': ['chrome-linux', 'chrome'], 'mac10.13': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.14': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.15': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11-arm64': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'win32': ['chrome-win', 'chrome.exe'], 'win64': ['chrome-win', 'chrome.exe'], }, 'firefox': { 'ubuntu18.04': ['firefox', 'firefox'], 'ubuntu20.04': ['firefox', 'firefox'], 'mac10.13': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.14': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.15': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11-arm64': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'win32': ['firefox', 'firefox.exe'], 'win64': ['firefox', 'firefox.exe'], }, 'webkit': { 'ubuntu18.04': ['pw_run.sh'], 'ubuntu20.04': ['pw_run.sh'], 'mac10.13': undefined, 'mac10.14': ['pw_run.sh'], 'mac10.15': ['pw_run.sh'], 'mac11': ['pw_run.sh'], 'mac11-arm64': ['pw_run.sh'], 'win32': ['Playwright.exe'], 'win64': ['Playwright.exe'], }, 'ffmpeg': { 'ubuntu18.04': ['ffmpeg-linux'], 'ubuntu20.04': ['ffmpeg-linux'], 'mac10.13': ['ffmpeg-mac'], 'mac10.14': ['ffmpeg-mac'], 'mac10.15': ['ffmpeg-mac'], 'mac11': ['ffmpeg-mac'], 'mac11-arm64': ['ffmpeg-mac'], 'win32': ['ffmpeg-win32.exe'], 'win64': ['ffmpeg-win64.exe'], }, }; const DOWNLOAD_URLS = { 'chromium': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-win64.zip', }, 'chromium-with-symbols': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-with-symbols-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-with-symbols-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-with-symbols-win64.zip', }, 'firefox': { 'ubuntu18.04': '%s/builds/firefox/%s/firefox-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox/%s/firefox-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.14': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.15': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox/%s/firefox-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox/%s/firefox-win32.zip', 'win64': '%s/builds/firefox/%s/firefox-win64.zip', }, 'firefox-beta': { 'ubuntu18.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.14': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.15': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox-beta/%s/firefox-beta-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox-beta/%s/firefox-beta-win32.zip', 'win64': '%s/builds/firefox-beta/%s/firefox-beta-win64.zip', }, 'webkit': { 'ubuntu18.04': '%s/builds/webkit/%s/webkit-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/webkit/%s/webkit-ubuntu-20.04.zip', 'mac10.13': undefined, 'mac10.14': '%s/builds/deprecated-webkit-mac-10.14/%s/deprecated-webkit-mac-10.14.zip', 'mac10.15': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11-arm64': '%s/builds/webkit/%s/webkit-mac-11.0-arm64.zip', 'win32': '%s/builds/webkit/%s/webkit-win64.zip', 'win64': '%s/builds/webkit/%s/webkit-win64.zip', }, 'ffmpeg': { 'ubuntu18.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'ubuntu20.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'mac10.13': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.14': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.15': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11-arm64': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'win32': '%s/builds/ffmpeg/%s/ffmpeg-win32.zip', 'win64': '%s/builds/ffmpeg/%s/ffmpeg-win64.zip', }, }; export const registryDirectory = (() => { let result: string; const envDefined = getFromENV('PLAYWRIGHT_BROWSERS_PATH'); if (envDefined === '0') { result = path.join(__dirname, '..', '..', '.local-browsers'); } else if (envDefined) { result = envDefined; } else { let cacheDirectory: string; if (process.platform === 'linux') cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'); else if (process.platform === 'darwin') cacheDirectory = path.join(os.homedir(), 'Library', 'Caches'); else if (process.platform === 'win32') cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'); else throw new Error('Unsupported platform: ' + process.platform); result = path.join(cacheDirectory, 'ms-playwright'); } if (!path.isAbsolute(result)) { // It is important to resolve to the absolute path: // - for unzipping to work correctly; // - so that registry directory matches between installation and execution. // INIT_CWD points to the root of `npm/yarn install` and is probably what // the user meant when typing the relative path. result = path.resolve(getFromENV('INIT_CWD') || process.cwd(), result); } return result; })(); function isBrowserDirectory(browserDirectory: string): boolean { const baseName = path.basename(browserDirectory); for (const browserName of allDownloadable) { if (baseName.startsWith(browserName + '-')) return true; } return false; } type BrowsersJSON = { comment: string browsers: { name: string, revision: string, installByDefault: boolean, revisionOverrides?: {[os: string]: string}, }[] }; type BrowsersJSONDescriptor = { name: string, revision: string, installByDefault: boolean, dir: string, }; function readDescriptors(browsersJSON: BrowsersJSON) { return (browsersJSON['browsers']).map(obj => { const name = obj.name; const revisionOverride = (obj.revisionOverrides || {})[hostPlatform]; const revision = revisionOverride || obj.revision; const browserDirectoryPrefix = revisionOverride ? `${name}_${hostPlatform}_special` : `${name}`; const descriptor: BrowsersJSONDescriptor = { name, revision, installByDefault: !!obj.installByDefault, // Method `isBrowserDirectory` determines directory to be browser iff // it starts with some browser name followed by '-'. Some browser names // are prefixes of others, e.g. 'webkit' is a prefix of `webkit-technology-preview`. // To avoid older registries erroneously removing 'webkit-technology-preview', we have to // ensure that browser folders to never include dashes inside. dir: path.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, '_') + '-' + revision), }; return descriptor; }); } export type BrowserName = 'chromium' | 'firefox' | 'webkit'; type InternalTool = 'ffmpeg' | 'firefox-beta' | 'chromium-with-symbols'; type ChromiumChannel = 'chrome' | 'chrome-beta' | 'chrome-dev' | 'chrome-canary' | 'msedge' | 'msedge-beta' | 'msedge-dev' | 'msedge-canary'; const allDownloadable = ['chromium', 'firefox', 'webkit', 'ffmpeg', 'firefox-beta', 'chromium-with-symbols']; export interface Executable { type: 'browser' | 'tool' | 'channel'; name: BrowserName | InternalTool | ChromiumChannel; browserName: BrowserName | undefined; installType: 'download-by-default' | 'download-on-demand' | 'install-script' | 'none'; directory: string | undefined; executablePathOrDie(sdkLanguage: string): string; executablePath(): string | undefined; validateHostRequirements(): Promise<void>; } interface ExecutableImpl extends Executable { _install?: () => Promise<void>; _dependencyGroup?: DependencyGroup; } export class Registry { private _executables: ExecutableImpl[]; constructor(browsersJSON: BrowsersJSON) { const descriptors = readDescriptors(browsersJSON); const findExecutablePath = (dir: string, name: keyof typeof EXECUTABLE_PATHS) => { const tokens = EXECUTABLE_PATHS[name][hostPlatform]; return tokens ? path.join(dir, ...tokens) : undefined; }; const executablePathOrDie = (name: string, e: string | undefined, installByDefault: boolean, sdkLanguage: string) => { if (!e) throw new Error(`${name} is not supported on ${hostPlatform}`); const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install${installByDefault ? '' : ' ' + name}`); if (!canAccessFile(e)) { const prettyMessage = [ `Looks like Playwright Test or Playwright was just installed or updated.`, `Please run the following command to download new browser${installByDefault ? 's' : ''}:`, ``, ` ${installCommand}`, ``, `<3 Playwright Team`, ].join('\n'); throw new Error(`Executable doesn't exist at ${e}\n${wrapInASCIIBox(prettyMessage, 1)}`); } return e; }; this._executables = []; const chromium = descriptors.find(d => d.name === 'chromium')!; const chromiumExecutable = findExecutablePath(chromium.dir, 'chromium'); this._executables.push({ type: 'browser', name: 'chromium', browserName: 'chromium', directory: chromium.dir, executablePath: () => chromiumExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium', chromiumExecutable, chromium.installByDefault, sdkLanguage), installType: chromium.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromium.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromium, chromiumExecutable, DOWNLOAD_URLS['chromium'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); const chromiumWithSymbols = descriptors.find(d => d.name === 'chromium-with-symbols')!; const chromiumWithSymbolsExecutable = findExecutablePath(chromiumWithSymbols.dir, 'chromium'); this._executables.push({ type: 'tool', name: 'chromium-with-symbols', browserName: 'chromium', directory: chromiumWithSymbols.dir, executablePath: () => chromiumWithSymbolsExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium-with-symbols', chromiumWithSymbolsExecutable, chromiumWithSymbols.installByDefault, sdkLanguage), installType: chromiumWithSymbols.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromiumWithSymbols.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromiumWithSymbols, chromiumWithSymbolsExecutable, DOWNLOAD_URLS['chromium-with-symbols'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); this._executables.push(this._createChromiumChannel('chrome', { 'linux': '/opt/google/chrome/chrome', 'darwin': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', 'win32': `\\Google\\Chrome\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome', { 'linux': 'reinstall_chrome_stable_linux.sh', 'darwin': 'reinstall_chrome_stable_mac.sh', 'win32': 'reinstall_chrome_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-beta', { 'linux': '/opt/google/chrome-beta/chrome', 'darwin': '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta', 'win32': `\\Google\\Chrome Beta\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome-beta', { 'linux': 'reinstall_chrome_beta_linux.sh', 'darwin': 'reinstall_chrome_beta_mac.sh', 'win32': 'reinstall_chrome_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-dev', { 'linux': '/opt/google/chrome-unstable/chrome', 'darwin': '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev', 'win32': `\\Google\\Chrome Dev\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('chrome-canary', { 'linux': '', 'darwin': '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary', 'win32': `\\Google\\Chrome SxS\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('msedge', { 'linux': '', 'darwin': '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', 'win32': `\\Microsoft\\Edge\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge', { 'linux': '', 'darwin': 'reinstall_msedge_stable_mac.sh', 'win32': 'reinstall_msedge_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-beta', { 'linux': '/opt/microsoft/msedge-beta/msedge', 'darwin': '/Applications/Microsoft Edge Beta.app/Contents/MacOS/Microsoft Edge Beta', 'win32': `\\Microsoft\\Edge Beta\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-beta', { 'darwin': 'reinstall_msedge_beta_mac.sh', 'linux': 'reinstall_msedge_beta_linux.sh', 'win32': 'reinstall_msedge_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-dev', { 'linux': '/opt/microsoft/msedge-dev/msedge', 'darwin': '/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev', 'win32': `\\Microsoft\\Edge Dev\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-dev', { 'darwin': 'reinstall_msedge_dev_mac.sh', 'linux': 'reinstall_msedge_dev_linux.sh', 'win32': 'reinstall_msedge_dev_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-canary', { 'linux': '', 'darwin': '/Applications/Microsoft Edge Canary.app/Contents/MacOS/Microsoft Edge Canary', 'win32': `\\Microsoft\\Edge SxS\\Application\\msedge.exe`, })); const firefox = descriptors.find(d => d.name === 'firefox')!; const firefoxExecutable = findExecutablePath(firefox.dir, 'firefox'); this._executables.push({ type: 'browser', name: 'firefox', browserName: 'firefox', directory: firefox.dir, executablePath: () => firefoxExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox', firefoxExecutable, firefox.installByDefault, sdkLanguage), installType: firefox.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefox.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefox, firefoxExecutable, DOWNLOAD_URLS['firefox'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const firefoxBeta = descriptors.find(d => d.name === 'firefox-beta')!; const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, 'firefox'); this._executables.push({ type: 'tool', name: 'firefox-beta', browserName: 'firefox', directory: firefoxBeta.dir, executablePath: () => firefoxBetaExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox-beta', firefoxBetaExecutable, firefoxBeta.installByDefault, sdkLanguage), installType: firefoxBeta.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefoxBeta.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefoxBeta, firefoxBetaExecutable, DOWNLOAD_URLS['firefox-beta'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const webkit = descriptors.find(d => d.name === 'webkit')!; const webkitExecutable = findExecutablePath(webkit.dir, 'webkit'); const webkitLinuxLddDirectories = [ path.join('minibrowser-gtk'), path.join('minibrowser-gtk', 'bin'), path.join('minibrowser-gtk', 'lib'), path.join('minibrowser-wpe'), path.join('minibrowser-wpe', 'bin'), path.join('minibrowser-wpe', 'lib'), ]; this._executables.push({ type: 'browser', name: 'webkit', browserName: 'webkit', directory: webkit.dir, executablePath: () => webkitExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('webkit', webkitExecutable, webkit.installByDefault, sdkLanguage), installType: webkit.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('webkit', webkit.dir, webkitLinuxLddDirectories, ['libGLESv2.so.2', 'libx264.so'], ['']), _install: () => this._downloadExecutable(webkit, webkitExecutable, DOWNLOAD_URLS['webkit'][hostPlatform], 'PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST'), _dependencyGroup: 'webkit', }); const ffmpeg = descriptors.find(d => d.name === 'ffmpeg')!; const ffmpegExecutable = findExecutablePath(ffmpeg.dir, 'ffmpeg'); this._executables.push({ type: 'tool', name: 'ffmpeg', browserName: undefined, directory: ffmpeg.dir, executablePath: () => ffmpegExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('ffmpeg', ffmpegExecutable, ffmpeg.installByDefault, sdkLanguage), installType: ffmpeg.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => Promise.resolve(), _install: () => this._downloadExecutable(ffmpeg, ffmpegExecutable, DOWNLOAD_URLS['ffmpeg'][hostPlatform], 'PLAYWRIGHT_FFMPEG_DOWNLOAD_HOST'), _dependencyGroup: 'tools', }); } private _createChromiumChannel(name: ChromiumChannel, lookAt: Record<'linux' | 'darwin' | 'win32', string>, install?: () => Promise<void>): ExecutableImpl { const executablePath = (shouldThrow: boolean) => { const suffix = lookAt[process.platform as 'linux' | 'darwin' | 'win32']; if (!suffix) { if (shouldThrow) throw new Error(`Chromium distribution '${name}' is not supported on ${process.platform}`); return undefined; } const prefixes = (process.platform === 'win32' ? [ process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'] ].filter(Boolean) : ['']) as string[]; for (const prefix of prefixes) { const executablePath = path.join(prefix, suffix); if (canAccessFile(executablePath)) return executablePath; } if (!shouldThrow) return undefined; const location = prefixes.length ? ` at ${path.join(prefixes[0], suffix)}` : ``; // TODO: language-specific error message const installation = install ? `\nRun "npx playwright install ${name}"` : ''; throw new Error(`Chromium distribution '${name}' is not found${location}${installation}`); }; return { type: 'channel', name, browserName: 'chromium', directory: undefined, executablePath: () => executablePath(false), executablePathOrDie: (sdkLanguage: string) => executablePath(true)!, installType: install ? 'install-script' : 'none', validateHostRequirements: () => Promise.resolve(), _install: install, }; } executables(): Executable[] { return this._executables; } findExecutable(name: BrowserName): Executable; findExecutable(name: string): Executable | undefined; findExecutable(name: string): Executable | undefined { return this._executables.find(b => b.name === name); } private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] { const set = new Set<ExecutableImpl>(); if (!executables) executables = this._executables.filter(executable => executable.installType === 'download-by-default'); for (const executable of executables as ExecutableImpl[]) { set.add(executable); if (executable.browserName === 'chromium') set.add(this.findExecutable('ffmpeg')!); } return Array.from(set); } private async _validateHostRequirements(browserName: BrowserName, browserDirectory: string, linuxLddDirectories: string[], dlOpenLibraries: string[], windowsExeAndDllDirectories: string[]) { if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS')) { process.stdout.write('Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n'); return; } const ubuntuVersion = await getUbuntuVersion(); if (browserName === 'firefox' && ubuntuVersion === '16.04') throw new Error(`Cannot launch Firefox on Ubuntu 16.04! Minimum required Ubuntu version for Firefox browser is 18.04`); if (os.platform() === 'linux') return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries); if (os.platform() === 'win32' && os.arch() === 'x64') return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d))); } async installDeps(executablesToInstallDeps?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstallDeps); const targets = new Set<DependencyGroup>(); for (const executable of executables) { if (executable._dependencyGroup) targets.add(executable._dependencyGroup); } targets.add('tools'); if (os.platform() === 'win32') return await installDependenciesWindows(targets); if (os.platform() === 'linux') return await installDependenciesLinux(targets); } async install(executablesToInstall?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstall); await fs.promises.mkdir(registryDirectory, { recursive: true }); const lockfilePath = path.join(registryDirectory, '__dirlock'); const releaseLock = await lockfile.lock(registryDirectory, { retries: { retries: 10, // Retry 20 times during 10 minutes with // exponential back-off. // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions factor: 1.27579, }, onCompromised: (err: Error) => { throw new Error(`${err.message} Path: ${lockfilePath}`); }, lockfilePath, }); const linksDir = path.join(registryDirectory, '.links'); try { // Create a link first, so that cache validation does not remove our own browsers. await fs.promises.mkdir(linksDir, { recursive: true }); await fs.promises.writeFile(path.join(linksDir, calculateSha1(PACKAGE_PATH)), PACKAGE_PATH); // Remove stale browsers. await this._validateInstallationCache(linksDir); // Install browsers for this package. for (const executable of executables) { if (executable._install) await executable._install(); else throw new Error(`ERROR: Playwright does not support installing ${executable.name}`); } } catch (e) { if (e.code === 'ELOCKED') { const rmCommand = process.platform === 'win32' ? 'rm -R' : 'rm -rf'; throw new Error('\n' + wrapInASCIIBox([ `An active lockfile is found at:`, ``, ` ${lockfilePath}`, ``, `Either:`, `- wait a few minutes if other Playwright is installing browsers in parallel`, `- remove lock manually with:`, ``, ` ${rmCommand} ${lockfilePath}`, ``, `<3 Playwright Team`, ].join('\n'), 1)); } else { throw e; } } finally { await releaseLock(); } } private async _downloadExecutable(descriptor: BrowsersJSONDescriptor, executablePath: string | undefined, downloadURLTemplate: string | undefined, downloadHostEnv: string) { if (!downloadURLTemplate || !executablePath) throw new Error(`ERROR: Playwright does not support ${descriptor.name} on ${hostPlatform}`); const downloadHost = (downloadHostEnv && getFromENV(downloadHostEnv)) || getFromENV('PLAYWRIGHT_DOWNLOAD_HOST') || 'https://playwright.azureedge.net'; const downloadURL = util.format(downloadURLTemplate, downloadHost, descriptor.revision); const title = `${descriptor.name} v${descriptor.revision}`; const downloadFileName = `playwright-download-${descriptor.name}-${hostPlatform}-${descriptor.revision}.zip`; await downloadBrowserWithProgressBar(title, descriptor.dir, executablePath, downloadURL, downloadFileName).catch(e => { throw new Error(`Failed to download ${title}, caused by\n${e.stack}`); }); await fs.promises.writeFile(markerFilePath(descriptor.dir), ''); } private async _installMSEdgeChannel(channel: 'msedge'|'msedge-beta'|'msedge-dev', scripts: Record<'linux' | 'darwin' | 'win32', string>) { const scriptArgs: string[] = []; if (process.platform !== 'linux') { const products = JSON.parse(await fetchData({ url: 'https://edgeupdates.microsoft.com/api/products' })); const productName = { 'msedge': 'Stable', 'msedge-beta': 'Beta', 'msedge-dev': 'Dev', }[channel]; const product = products.find((product: any) => product.Product === productName); const searchConfig = ({ darwin: {platform: 'MacOS', arch: 'universal', artifact: 'pkg'}, win32: {platform: 'Windows', arch: os.arch() === 'x64' ? 'x64' : 'x86', artifact: 'msi'}, } as any)[process.platform]; const release = searchConfig ? product.Releases.find((release: any) => release.Platform === searchConfig.platform && release.Architecture === searchConfig.arch) : null; const artifact = release ? release.Artifacts.find((artifact: any) => artifact.ArtifactName === searchConfig.artifact) : null; if (artifact) scriptArgs.push(artifact.Location /* url */); else throw new Error(`Cannot install ${channel} on ${process.platform}`); } await this._installChromiumChannel(channel, scripts, scriptArgs); } private async _installChromiumChannel(channel: string, scripts: Record<'linux' | 'darwin' | 'win32', string>, scriptArgs: string[] = []) { const scriptName = scripts[process.platform as 'linux' | 'darwin' | 'win32']; if (!scriptName) throw new Error(`Cannot install ${channel} on ${process.platform}`); const shell = scriptName.endsWith('.ps1') ? 'powershell.exe' : 'bash'; const { code } = await spawnAsync(shell, [path.join(BIN_PATH, scriptName), ...scriptArgs], { cwd: BIN_PATH, stdio: 'inherit' }); if (code !== 0) throw new Error(`Failed to install ${channel}`); } private async _validateInstallationCache(linksDir: string) { // 1. Collect used downloads and package descriptors. const usedBrowserPaths: Set<string> = new Set(); for (const fileName of await fs.promises.readdir(linksDir)) { const linkPath = path.join(linksDir, fileName); let linkTarget = ''; try { linkTarget = (await fs.promises.readFile(linkPath)).toString(); const browsersJSON = require(path.join(linkTarget, 'browsers.json')); const descriptors = readDescriptors(browsersJSON); for (const browserName of allDownloadable) { // We retain browsers if they are found in the descriptor. // Note, however, that there are older versions out in the wild that rely on // the "download" field in the browser descriptor and use its value // to retain and download browsers. // As of v1.10, we decided to abandon "download" field. const descriptor = descriptors.find(d => d.name === browserName); if (!descriptor) continue; const usedBrowserPath = descriptor.dir; const browserRevision = parseInt(descriptor.revision, 10); // Old browser installations don't have marker file. const shouldHaveMarkerFile = (browserName === 'chromium' && browserRevision >= 786218) || (browserName === 'firefox' && browserRevision >= 1128) || (browserName === 'webkit' && browserRevision >= 1307) || // All new applications have a marker file right away. (browserName !== 'firefox' && browserName !== 'chromium' && browserName !== 'webkit'); if (!shouldHaveMarkerFile || (await existsAsync(markerFilePath(usedBrowserPath)))) usedBrowserPaths.add(usedBrowserPath); } } catch (e) { await fs.promises.unlink(linkPath).catch(e => {}); } } // 2. Delete all unused browsers. if (!getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_GC')) { let downloadedBrowsers = (await fs.promises.readdir(registryDirectory)).map(file => path.join(registryDirectory, file)); downloadedBrowsers = downloadedBrowsers.filter(file => isBrowserDirectory(file)); const directories = new Set<string>(downloadedBrowsers); for (const browserDirectory of usedBrowserPaths) directories.delete(browserDirectory); for (const directory of directories) logPolitely('Removing unused browser at ' + directory); await removeFolders([...directories]); } } } function markerFilePath(browserDirectory: string): string { return path.join(browserDirectory, 'INSTALLATION_COMPLETE'); } function buildPlaywrightCLICommand(sdkLanguage: string, parameters: string): string { switch (sdkLanguage) { case 'python': return `playwright ${parameters}`; case 'java': return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="${parameters}"`; case 'csharp': return `playwright ${parameters}`; default: return `npx playwright ${parameters}`; } } export async function installDefaultBrowsersForNpmInstall() { // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1 if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) { logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set'); return false; } await registry.install(); } export const registry = new Registry(require('../../browsers.json'));
src/utils/registry.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9992877840995789, 0.12432842701673508, 0.00016397393483202904, 0.0001764442858984694, 0.3265168368816376 ]
{ "id": 3, "code_window": [ " findExecutable(name: string): Executable | undefined {\n", " return this._executables.find(b => b.name === name);\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] {\n", " const set = new Set<ExecutableImpl>();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " defaultExecutables(): Executable[] {\n", " return this._executables.filter(e => e.installType === 'download-by-default');\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[]): ExecutableImpl[] {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 489 }
/** * 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 { test, expect } from './inspectorTest'; test.describe('cli codegen', () => { test.skip(({ mode }) => mode !== 'default'); test.fixme(({ browserName, headless }) => browserName === 'firefox' && !headless, 'Focus is off'); test('should click', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<button onclick="console.log('click')">Submit</button>`); const selector = await recorder.hoverOverElement('button'); expect(selector).toBe('text=Submit'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'click'), page.dispatchEvent('button', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=Submit await page.click('text=Submit');`); expect(sources.get('Python').text).toContain(` # Click text=Submit page.click("text=Submit")`); expect(sources.get('Python Async').text).toContain(` # Click text=Submit await page.click("text=Submit")`); expect(sources.get('Java').text).toContain(` // Click text=Submit page.click("text=Submit");`); expect(sources.get('C#').text).toContain(` // Click text=Submit await page.ClickAsync("text=Submit");`); expect(message.text()).toBe('click'); }); test('should click after same-document navigation', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); server.setRoute('/foo.html', (req, res) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(''); }); await recorder.setContentAndWait(`<button onclick="console.log('click')">Submit</button>`, server.PREFIX + '/foo.html'); await Promise.all([ page.waitForNavigation(), page.evaluate(() => history.pushState({}, '', '/url.html')), ]); // This is the only way to give recorder a chance to install // the second unnecessary copy of the recorder script. await page.waitForTimeout(1000); const selector = await recorder.hoverOverElement('button'); expect(selector).toBe('text=Submit'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'click'), page.dispatchEvent('button', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=Submit await page.click('text=Submit');`); expect(message.text()).toBe('click'); }); test('should work with TrustedTypes', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <head> <meta http-equiv="Content-Security-Policy" content="trusted-types unsafe escape; require-trusted-types-for 'script'"> </head> <body> <button onclick="console.log('click')">Submit</button> </body>`); const selector = await recorder.hoverOverElement('button'); expect(selector).toBe('text=Submit'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'click'), page.dispatchEvent('button', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=Submit await page.click('text=Submit');`); expect(sources.get('Python').text).toContain(` # Click text=Submit page.click("text=Submit")`); expect(sources.get('Python Async').text).toContain(` # Click text=Submit await page.click("text=Submit")`); expect(sources.get('Java').text).toContain(` // Click text=Submit page.click("text=Submit");`); expect(sources.get('C#').text).toContain(` // Click text=Submit await page.ClickAsync("text=Submit");`); expect(message.text()).toBe('click'); }); test('should not target selector preview by text regexp', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<span>dummy</span>`); // Force highlight. await recorder.hoverOverElement('span'); // Append text after highlight. await page.evaluate(() => { const div = document.createElement('div'); div.setAttribute('onclick', "console.log('click')"); div.textContent = ' Some long text here '; document.documentElement.appendChild(div); }); const selector = await recorder.hoverOverElement('div'); expect(selector).toBe('text=Some long text here'); // Sanity check that selector does not match our highlight. const divContents = await page.$eval(selector, div => div.outerHTML); expect(divContents).toBe(`<div onclick="console.log('click')"> Some long text here </div>`); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'click'), page.dispatchEvent('div', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=Some long text here await page.click('text=Some long text here');`); expect(message.text()).toBe('click'); }); test('should fill', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="input" name="name" oninput="console.log(input.value)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="name"]'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'fill'), page.fill('input', 'John') ]); expect(sources.get('JavaScript').text).toContain(` // Fill input[name="name"] await page.fill('input[name="name"]', 'John');`); expect(sources.get('Java').text).toContain(` // Fill input[name="name"] page.fill("input[name=\\\"name\\\"]", "John");`); expect(sources.get('Python').text).toContain(` # Fill input[name="name"] page.fill(\"input[name=\\\"name\\\"]\", \"John\")`); expect(sources.get('Python Async').text).toContain(` # Fill input[name="name"] await page.fill(\"input[name=\\\"name\\\"]\", \"John\")`); expect(sources.get('C#').text).toContain(` // Fill input[name="name"] await page.FillAsync(\"input[name=\\\"name\\\"]\", \"John\");`); expect(message.text()).toBe('John'); }); test('should fill textarea', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<textarea id="textarea" name="name" oninput="console.log(textarea.value)"></textarea>`); const selector = await recorder.focusElement('textarea'); expect(selector).toBe('textarea[name="name"]'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'fill'), page.fill('textarea', 'John') ]); expect(sources.get('JavaScript').text).toContain(` // Fill textarea[name="name"] await page.fill('textarea[name="name"]', 'John');`); expect(message.text()).toBe('John'); }); test('should press', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input name="name" onkeypress="console.log('press')"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="name"]'); const messages: any[] = []; page.on('console', message => messages.push(message)); const [, sources] = await Promise.all([ recorder.waitForActionPerformed(), recorder.waitForOutput('JavaScript', 'press'), page.press('input', 'Shift+Enter') ]); expect(sources.get('JavaScript').text).toContain(` // Press Enter with modifiers await page.press('input[name="name"]', 'Shift+Enter');`); expect(sources.get('Java').text).toContain(` // Press Enter with modifiers page.press("input[name=\\\"name\\\"]", "Shift+Enter");`); expect(sources.get('Python').text).toContain(` # Press Enter with modifiers page.press(\"input[name=\\\"name\\\"]\", \"Shift+Enter\")`); expect(sources.get('Python Async').text).toContain(` # Press Enter with modifiers await page.press(\"input[name=\\\"name\\\"]\", \"Shift+Enter\")`); expect(sources.get('C#').text).toContain(` // Press Enter with modifiers await page.PressAsync(\"input[name=\\\"name\\\"]\", \"Shift+Enter\");`); expect(messages[0].text()).toBe('press'); }); test('should update selected element after pressing Tab', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(` <input name="one"></input> <input name="two"></input> `); await page.click('input[name="one"]'); await recorder.waitForOutput('JavaScript', 'click'); await page.keyboard.type('foobar123'); await recorder.waitForOutput('JavaScript', 'foobar123'); await page.keyboard.press('Tab'); await recorder.waitForOutput('JavaScript', 'Tab'); await page.keyboard.type('barfoo321'); await recorder.waitForOutput('JavaScript', 'barfoo321'); const text = recorder.sources().get('JavaScript').text; expect(text).toContain(` // Fill input[name="one"] await page.fill('input[name="one"]', 'foobar123');`); expect(text).toContain(` // Press Tab await page.press('input[name="one"]', 'Tab');`); expect(text).toContain(` // Fill input[name="two"] await page.fill('input[name="two"]', 'barfoo321');`); }); test('should record ArrowDown', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input name="name" onkeydown="console.log('press:' + event.key)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="name"]'); const messages: any[] = []; page.on('console', message => { messages.push(message); }); const [, sources] = await Promise.all([ recorder.waitForActionPerformed(), recorder.waitForOutput('JavaScript', 'press'), page.press('input', 'ArrowDown') ]); expect(sources.get('JavaScript').text).toContain(` // Press ArrowDown await page.press('input[name="name"]', 'ArrowDown');`); expect(messages[0].text()).toBe('press:ArrowDown'); }); test('should emit single keyup on ArrowDown', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input name="name" onkeydown="console.log('down:' + event.key)" onkeyup="console.log('up:' + event.key)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="name"]'); const messages: any[] = []; page.on('console', message => { if (message.type() !== 'error') messages.push(message); }); const [, sources] = await Promise.all([ recorder.waitForActionPerformed(), recorder.waitForOutput('JavaScript', 'press'), page.press('input', 'ArrowDown') ]); expect(sources.get('JavaScript').text).toContain(` // Press ArrowDown await page.press('input[name="name"]', 'ArrowDown');`); expect(messages.length).toBe(2); expect(messages[0].text()).toBe('down:ArrowDown'); expect(messages[1].text()).toBe('up:ArrowDown'); }); test('should check', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="console.log(checkbox.checked)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="accept"]'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'check'), page.click('input') ]); expect(sources.get('JavaScript').text).toContain(` // Check input[name="accept"] await page.check('input[name="accept"]');`); expect(sources.get('Java').text).toContain(` // Check input[name="accept"] page.check("input[name=\\\"accept\\\"]");`); expect(sources.get('Python').text).toContain(` # Check input[name="accept"] page.check(\"input[name=\\\"accept\\\"]\")`); expect(sources.get('Python Async').text).toContain(` # Check input[name="accept"] await page.check(\"input[name=\\\"accept\\\"]\")`); expect(sources.get('C#').text).toContain(` // Check input[name="accept"] await page.CheckAsync(\"input[name=\\\"accept\\\"]\");`); expect(message.text()).toBe('true'); }); test('should check with keyboard', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" name="accept" onchange="console.log(checkbox.checked)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="accept"]'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'check'), page.keyboard.press('Space') ]); expect(sources.get('JavaScript').text).toContain(` // Check input[name="accept"] await page.check('input[name="accept"]');`); expect(message.text()).toBe('true'); }); test('should uncheck', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<input id="checkbox" type="checkbox" checked name="accept" onchange="console.log(checkbox.checked)"></input>`); const selector = await recorder.focusElement('input'); expect(selector).toBe('input[name="accept"]'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'uncheck'), page.click('input') ]); expect(sources.get('JavaScript').text).toContain(` // Uncheck input[name="accept"] await page.uncheck('input[name="accept"]');`); expect(sources.get('Java').text).toContain(` // Uncheck input[name="accept"] page.uncheck("input[name=\\\"accept\\\"]");`); expect(sources.get('Python').text).toContain(` # Uncheck input[name="accept"] page.uncheck(\"input[name=\\\"accept\\\"]\")`); expect(sources.get('Python Async').text).toContain(` # Uncheck input[name="accept"] await page.uncheck(\"input[name=\\\"accept\\\"]\")`); expect(sources.get('C#').text).toContain(` // Uncheck input[name="accept"] await page.UncheckAsync(\"input[name=\\\"accept\\\"]\");`); expect(message.text()).toBe('false'); }); test('should select', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait('<select id="age" onchange="console.log(age.selectedOptions[0].value)"><option value="1"><option value="2"></select>'); const selector = await recorder.hoverOverElement('select'); expect(selector).toBe('select'); const [message, sources] = await Promise.all([ page.waitForEvent('console', msg => msg.type() !== 'error'), recorder.waitForOutput('JavaScript', 'select'), page.selectOption('select', '2') ]); expect(sources.get('JavaScript').text).toContain(` // Select 2 await page.selectOption('select', '2');`); expect(sources.get('Java').text).toContain(` // Select 2 page.selectOption("select", "2");`); expect(sources.get('Python').text).toContain(` # Select 2 page.select_option(\"select\", \"2\")`); expect(sources.get('Python Async').text).toContain(` # Select 2 await page.select_option(\"select\", \"2\")`); expect(sources.get('C#').text).toContain(` // Select 2 await page.SelectOptionAsync(\"select\", new[] { \"2\" });`); expect(message.text()).toBe('2'); }); test('should await popup', async ({ page, openRecorder, browserName, headless }) => { test.fixme(browserName === 'webkit' && !headless, 'Middle click does not open a popup in our webkit embedder'); const recorder = await openRecorder(); await recorder.setContentAndWait('<a target=_blank rel=noopener href="about:blank">link</a>'); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); const [popup, sources] = await Promise.all([ page.context().waitForEvent('page'), recorder.waitForOutput('JavaScript', 'waitForEvent'), page.dispatchEvent('a', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=link const [page1] = await Promise.all([ page.waitForEvent('popup'), page.click('text=link') ]);`); expect(sources.get('Java').text).toContain(` // Click text=link Page page1 = page.waitForPopup(() -> { page.click("text=link"); });`); expect(sources.get('Python').text).toContain(` # Click text=link with page.expect_popup() as popup_info: page.click(\"text=link\") page1 = popup_info.value`); expect(sources.get('Python Async').text).toContain(` # Click text=link async with page.expect_popup() as popup_info: await page.click(\"text=link\") page1 = await popup_info.value`); expect(sources.get('C#').text).toContain(` var page1 = await page.RunAndWaitForPopupAsync(async () => { await page.ClickAsync(\"text=link\"); });`); expect(popup.url()).toBe('about:blank'); }); test('should assert navigation', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<a onclick="window.location.href='about:blank#foo'">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); const [, sources] = await Promise.all([ page.waitForNavigation(), recorder.waitForOutput('JavaScript', 'assert'), page.dispatchEvent('a', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=link await page.click('text=link'); // assert.equal(page.url(), 'about:blank#foo');`); expect(sources.get('Playwright Test').text).toContain(` // Click text=link await page.click('text=link'); await expect(page).toHaveURL('about:blank#foo');`); expect(sources.get('Java').text).toContain(` // Click text=link page.click("text=link"); // assert page.url().equals("about:blank#foo");`); expect(sources.get('Python').text).toContain(` # Click text=link page.click(\"text=link\") # assert page.url == \"about:blank#foo\"`); expect(sources.get('Python Async').text).toContain(` # Click text=link await page.click(\"text=link\") # assert page.url == \"about:blank#foo\"`); expect(sources.get('C#').text).toContain(` // Click text=link await page.ClickAsync(\"text=link\"); // Assert.AreEqual(\"about:blank#foo\", page.Url);`); expect(page.url()).toContain('about:blank#foo'); }); test('should await navigation', async ({ page, openRecorder }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<a onclick="setTimeout(() => window.location.href='about:blank#foo', 1000)">link</a>`); const selector = await recorder.hoverOverElement('a'); expect(selector).toBe('text=link'); const [, sources] = await Promise.all([ page.waitForNavigation(), recorder.waitForOutput('JavaScript', 'waitForNavigation'), page.dispatchEvent('a', 'click', { detail: 1 }) ]); expect(sources.get('JavaScript').text).toContain(` // Click text=link await Promise.all([ page.waitForNavigation(/*{ url: 'about:blank#foo' }*/), page.click('text=link') ]);`); expect(sources.get('Java').text).toContain(` // Click text=link // page.waitForNavigation(new Page.WaitForNavigationOptions().setUrl("about:blank#foo"), () -> page.waitForNavigation(() -> { page.click("text=link"); });`); expect(sources.get('Python').text).toContain(` # Click text=link # with page.expect_navigation(url=\"about:blank#foo\"): with page.expect_navigation(): page.click(\"text=link\")`); expect(sources.get('Python Async').text).toContain(` # Click text=link # async with page.expect_navigation(url=\"about:blank#foo\"): async with page.expect_navigation(): await page.click(\"text=link\")`); expect(sources.get('C#').text).toContain(` // Click text=link await page.RunAndWaitForNavigationAsync(async () => { await page.ClickAsync(\"text=link\"); }/*, new PageWaitForNavigationOptions { UrlString = \"about:blank#foo\" }*/);`); expect(page.url()).toContain('about:blank#foo'); }); test('should ignore AltGraph', async ({ openRecorder, browserName }) => { test.skip(browserName === 'firefox', 'The TextInputProcessor in Firefox does not work with AltGraph.'); const recorder = await openRecorder(); await recorder.setContentAndWait(`<input></input>`); await recorder.page.type('input', 'playwright'); await recorder.page.keyboard.press('AltGraph'); await recorder.page.keyboard.insertText('@'); await recorder.page.keyboard.type('example.com'); await recorder.waitForOutput('JavaScript', 'example.com'); expect(recorder.sources().get('JavaScript').text).not.toContain(`await page.press('input', 'AltGraph');`); expect(recorder.sources().get('JavaScript').text).toContain(`await page.fill('input', '[email protected]');`); }); test('should middle click', async ({ page, openRecorder, server }) => { const recorder = await openRecorder(); await recorder.setContentAndWait(`<a href${JSON.stringify(server.EMPTY_PAGE)}>Click me</a>`); const [sources] = await Promise.all([ recorder.waitForOutput('JavaScript', 'click'), page.click('a', { button: 'middle' }), ]); expect(sources.get('JavaScript').text).toContain(` await page.click('text=Click me', { button: 'middle' });`); expect(sources.get('Python').text).toContain(` page.click("text=Click me", button="middle")`); expect(sources.get('Python Async').text).toContain(` await page.click("text=Click me", button="middle")`); expect(sources.get('Java').text).toContain(` page.click("text=Click me", new Page.ClickOptions() .setButton(MouseButton.MIDDLE));`); expect(sources.get('C#').text).toContain(` await page.ClickAsync("text=Click me", new PageClickOptions { Button = MouseButton.Middle, });`); }); });
tests/inspector/cli-codegen-1.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00018118279695045203, 0.00017783523071557283, 0.00017259031301364303, 0.00017818414198700339, 0.0000022479484869109 ]
{ "id": 3, "code_window": [ " findExecutable(name: string): Executable | undefined {\n", " return this._executables.find(b => b.name === name);\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] {\n", " const set = new Set<ExecutableImpl>();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " defaultExecutables(): Executable[] {\n", " return this._executables.filter(e => e.installType === 'download-by-default');\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[]): ExecutableImpl[] {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 489 }
{ "version": "2.0", "extensions": { "queues": { "batchSize": 1, "newBatchThreshold": 0 } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1.*, 2.0.0)" } }
utils/flakiness-dashboard/processing/host.json
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0001756335113896057, 0.00017551945347804576, 0.00017540539556648582, 0.00017551945347804576, 1.1405791155993938e-7 ]
{ "id": 3, "code_window": [ " findExecutable(name: string): Executable | undefined {\n", " return this._executables.find(b => b.name === name);\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] {\n", " const set = new Set<ExecutableImpl>();\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " defaultExecutables(): Executable[] {\n", " return this._executables.filter(e => e.installType === 'download-by-default');\n", " }\n", "\n", " private _addRequirementsAndDedupe(executables: Executable[]): ExecutableImpl[] {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 489 }
<html> <script> function changeBackground() { const color = location.hash.substr(1); document.body.style.backgroundColor = color; } </script> <style> body { margin: 0; } .container { display: grid; background-color: rgb(0, 0, 0); grid-template-columns: auto auto; width: 100%; height: 100%; } .cell { border: none; font-size: 30px; text-align: center; } .cell.grey { background-color: rgb(100, 100, 100); } .cell.red { background-color: rgb(255, 0, 0); } </style> <body> <div class="container"> <div class="cell red"></div> <div class="cell grey"></div> <div class="cell grey"></div> <div class="cell red"></div> </div> </body> </html>
tests/assets/checkerboard.html
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017744506476446986, 0.00017611733346711844, 0.00017397207557223737, 0.00017643229512032121, 0.0000011547203939699102 ]
{ "id": 4, "code_window": [ " const set = new Set<ExecutableImpl>();\n", " if (!executables)\n", " executables = this._executables.filter(executable => executable.installType === 'download-by-default');\n", " for (const executable of executables as ExecutableImpl[]) {\n", " set.add(executable);\n", " if (executable.browserName === 'chromium')\n", " set.add(this.findExecutable('ffmpeg')!);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 491 }
#!/usr/bin/env node /** * 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. */ /* eslint-disable no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9909586906433105, 0.03171725943684578, 0.0001652463834034279, 0.0001734944962663576, 0.16534937918186188 ]
{ "id": 4, "code_window": [ " const set = new Set<ExecutableImpl>();\n", " if (!executables)\n", " executables = this._executables.filter(executable => executable.installType === 'download-by-default');\n", " for (const executable of executables as ExecutableImpl[]) {\n", " set.add(executable);\n", " if (executable.browserName === 'chromium')\n", " set.add(this.findExecutable('ffmpeg')!);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 491 }
/** * Copyright 2018 Google Inc. All rights reserved. * Modifications 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 { test as it, expect } from './pageTest'; import { globToRegex } from '../../lib/client/clientHelper'; import vm from 'vm'; it('should work with navigation', async ({page, server}) => { const requests = new Map(); await page.route('**/*', route => { requests.set(route.request().url().split('/').pop(), route.request()); route.continue(); }); server.setRedirect('/rrredirect', '/frames/one-frame.html'); await page.goto(server.PREFIX + '/rrredirect'); expect(requests.get('rrredirect').isNavigationRequest()).toBe(true); expect(requests.get('frame.html').isNavigationRequest()).toBe(true); expect(requests.get('script.js').isNavigationRequest()).toBe(false); expect(requests.get('style.css').isNavigationRequest()).toBe(false); }); it('should intercept after a service worker', async ({page, server, isAndroid}) => { it.skip(isAndroid); await page.goto(server.PREFIX + '/serviceworkers/fetchdummy/sw.html'); await page.evaluate(() => window['activationPromise']); // Sanity check. const swResponse = await page.evaluate(() => window['fetchDummy']('foo')); expect(swResponse).toBe('responseFromServiceWorker:foo'); await page.route('**/foo', route => { const slash = route.request().url().lastIndexOf('/'); const name = route.request().url().substring(slash + 1); route.fulfill({ status: 200, contentType: 'text/css', body: 'responseFromInterception:' + name }); }); // Page route is applied after service worker fetch event. const swResponse2 = await page.evaluate(() => window['fetchDummy']('foo')); expect(swResponse2).toBe('responseFromServiceWorker:foo'); // Page route is not applied to service worker initiated fetch. const nonInterceptedResponse = await page.evaluate(() => window['fetchDummy']('passthrough')); expect(nonInterceptedResponse).toBe('FAILURE: Not Found'); }); it('should work with glob', async () => { expect(globToRegex('**/*.js').test('https://localhost:8080/foo.js')).toBeTruthy(); expect(globToRegex('**/*.css').test('https://localhost:8080/foo.js')).toBeFalsy(); expect(globToRegex('*.js').test('https://localhost:8080/foo.js')).toBeFalsy(); expect(globToRegex('https://**/*.js').test('https://localhost:8080/foo.js')).toBeTruthy(); expect(globToRegex('http://localhost:8080/simple/path.js').test('http://localhost:8080/simple/path.js')).toBeTruthy(); expect(globToRegex('http://localhost:8080/?imple/path.js').test('http://localhost:8080/Simple/path.js')).toBeTruthy(); expect(globToRegex('**/{a,b}.js').test('https://localhost:8080/a.js')).toBeTruthy(); expect(globToRegex('**/{a,b}.js').test('https://localhost:8080/b.js')).toBeTruthy(); expect(globToRegex('**/{a,b}.js').test('https://localhost:8080/c.js')).toBeFalsy(); expect(globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.jpg')).toBeTruthy(); expect(globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.jpeg')).toBeTruthy(); expect(globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.png')).toBeTruthy(); expect(globToRegex('**/*.{png,jpg,jpeg}').test('https://localhost:8080/c.css')).toBeFalsy(); expect(globToRegex('foo*').test('foo.js')).toBeTruthy(); expect(globToRegex('foo*').test('foo/bar.js')).toBeFalsy(); expect(globToRegex('http://localhost:3000/signin-oidc*').test('http://localhost:3000/signin-oidc/foo')).toBeFalsy(); expect(globToRegex('http://localhost:3000/signin-oidc*').test('http://localhost:3000/signin-oidcnice')).toBeTruthy(); }); it('should intercept network activity from worker', async function({page, server, isAndroid}) { it.skip(isAndroid); await page.goto(server.EMPTY_PAGE); server.setRoute('/data_for_worker', (req, res) => res.end('failed to intercept')); const url = server.PREFIX + '/data_for_worker'; await page.route(url, route => { route.fulfill({ status: 200, body: 'intercepted', }).catch(e => null); }); const [msg] = await Promise.all([ page.waitForEvent('console'), page.evaluate(url => new Worker(URL.createObjectURL(new Blob([` fetch("${url}").then(response => response.text()).then(console.log); `], {type: 'application/javascript'}))), url), ]); expect(msg.text()).toBe('intercepted'); }); it('should intercept network activity from worker 2', async function({page, server, isElectron, isAndroid}) { it.skip(isAndroid); it.fixme(isElectron); const url = server.PREFIX + '/worker/worker.js'; await page.route(url, route => { route.fulfill({ status: 200, body: 'console.log("intercepted");', contentType: 'application/javascript', }).catch(e => null); }); const [msg] = await Promise.all([ page.waitForEvent('console'), page.goto(server.PREFIX + '/worker/worker.html'), ]); expect(msg.text()).toBe('intercepted'); }); it('should work with regular expression passed from a different context', async ({page, server, isElectron}) => { it.skip(isElectron); const ctx = vm.createContext(); const regexp = vm.runInContext('new RegExp("empty\\.html")', ctx); let intercepted = false; await page.route(regexp, (route, request) => { expect(route.request()).toBe(request); expect(request.url()).toContain('empty.html'); expect(request.headers()['user-agent']).toBeTruthy(); expect(request.method()).toBe('GET'); expect(request.postData()).toBe(null); expect(request.isNavigationRequest()).toBe(true); expect(request.resourceType()).toBe('document'); expect(request.frame() === page.mainFrame()).toBe(true); expect(request.frame().url()).toBe('about:blank'); route.continue(); intercepted = true; }); const response = await page.goto(server.EMPTY_PAGE); expect(response.ok()).toBe(true); expect(intercepted).toBe(true); }); it('should not break remote worker importScripts', async ({ page, server, browserName, browserMajorVersion }) => { it.fixme(browserName && browserMajorVersion < 91); await page.route('**', async route => { await route.continue(); }); await page.goto(server.PREFIX + '/worker/worker-http-import.html'); await page.waitForSelector("#status:has-text('finished')"); });
tests/page/interception.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017821777146309614, 0.00017445566481910646, 0.00016795113333500922, 0.00017521785048302263, 0.000002657015556906117 ]
{ "id": 4, "code_window": [ " const set = new Set<ExecutableImpl>();\n", " if (!executables)\n", " executables = this._executables.filter(executable => executable.installType === 'download-by-default');\n", " for (const executable of executables as ExecutableImpl[]) {\n", " set.add(executable);\n", " if (executable.browserName === 'chromium')\n", " set.add(this.findExecutable('ffmpeg')!);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 491 }
/* 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 { ActionTraceEvent } from '../../../server/trace/common/traceEvents'; import { ContextEntry } from '../../../server/trace/viewer/traceModel'; import { ActionList } from './actionList'; import { TabbedPane } from './tabbedPane'; import { Timeline } from './timeline'; import './workbench.css'; import * as React from 'react'; import { ContextSelector } from './contextSelector'; import { NetworkTab } from './networkTab'; import { SourceTab } from './sourceTab'; import { SnapshotTab } from './snapshotTab'; import { CallTab } from './callTab'; import { SplitView } from '../../components/splitView'; import { useAsyncMemo } from './helpers'; import { ConsoleTab } from './consoleTab'; import * as modelUtil from './modelUtil'; export const Workbench: React.FunctionComponent<{ debugNames: string[], }> = ({ debugNames }) => { const [debugName, setDebugName] = React.useState(debugNames[0]); const [selectedAction, setSelectedAction] = React.useState<ActionTraceEvent | undefined>(); const [highlightedAction, setHighlightedAction] = React.useState<ActionTraceEvent | undefined>(); const [selectedTab, setSelectedTab] = React.useState<string>('logs'); const context = useAsyncMemo(async () => { if (!debugName) return emptyContext; const context = (await fetch(`/context/${debugName}`).then(response => response.json())) as ContextEntry; modelUtil.indexModel(context); return context; }, [debugName], emptyContext); const actions = React.useMemo(() => { const actions: ActionTraceEvent[] = []; for (const page of context.pages) actions.push(...page.actions); return actions; }, [context]); const defaultSnapshotSize = context.options.viewport || { width: 1280, height: 720 }; const boundaries = { minimum: context.startTime, maximum: context.endTime }; // Leave some nice free space on the right hand side. boundaries.maximum += (boundaries.maximum - boundaries.minimum) / 20; const { errors, warnings } = selectedAction ? modelUtil.stats(selectedAction) : { errors: 0, warnings: 0 }; const consoleCount = errors + warnings; const networkCount = selectedAction ? modelUtil.resourcesForAction(selectedAction).length : 0; return <div className='vbox workbench'> <div className='hbox header'> <div className='logo'>🎭</div> <div className='product'>Playwright</div> <div className='spacer'></div> <ContextSelector debugNames={debugNames} debugName={debugName} onChange={debugName => { setDebugName(debugName); setSelectedAction(undefined); }} /> </div> <div style={{ background: 'white', paddingLeft: '20px', flex: 'none', borderBottom: '1px solid #ddd' }}> <Timeline context={context} boundaries={boundaries} selectedAction={selectedAction} highlightedAction={highlightedAction} onSelected={action => setSelectedAction(action)} onHighlighted={action => setHighlightedAction(action)} /> </div> <SplitView sidebarSize={300} orientation='horizontal' sidebarIsFirst={true}> <SplitView sidebarSize={300} orientation='horizontal'> <SnapshotTab action={selectedAction} defaultSnapshotSize={defaultSnapshotSize} /> <TabbedPane tabs={[ { id: 'logs', title: 'Call', count: 0, render: () => <CallTab action={selectedAction} /> }, { id: 'console', title: 'Console', count: consoleCount, render: () => <ConsoleTab action={selectedAction} /> }, { id: 'network', title: 'Network', count: networkCount, render: () => <NetworkTab action={selectedAction} /> }, { id: 'source', title: 'Source', count: 0, render: () => <SourceTab action={selectedAction} /> }, ]} selectedTab={selectedTab} setSelectedTab={setSelectedTab}/> </SplitView> <ActionList actions={actions} selectedAction={selectedAction} highlightedAction={highlightedAction} onSelected={action => { setSelectedAction(action); }} onHighlighted={action => setHighlightedAction(action)} setSelectedTab={setSelectedTab} /> </SplitView> </div>; }; const now = performance.now(); const emptyContext: ContextEntry = { startTime: now, endTime: now, browserName: '', options: { deviceScaleFactor: 1, isMobile: false, viewport: { width: 1280, height: 800 }, _debugName: '<empty>', }, pages: [], resources: [], };
src/web/traceViewer/ui/workbench.tsx
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017849258438218385, 0.00017502435366623104, 0.00016479275655001402, 0.00017605099128559232, 0.0000033671658457024023 ]
{ "id": 4, "code_window": [ " const set = new Set<ExecutableImpl>();\n", " if (!executables)\n", " executables = this._executables.filter(executable => executable.installType === 'download-by-default');\n", " for (const executable of executables as ExecutableImpl[]) {\n", " set.add(executable);\n", " if (executable.browserName === 'chromium')\n", " set.add(this.findExecutable('ffmpeg')!);\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 491 }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * * 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 { test as it, expect } from './pageTest'; it.fixme(({ isAndroid }) => isAndroid, 'Post data does not work'); it('should return correct postData buffer for utf-8 body', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const value = 'baẞ'; const [request] = await Promise.all([ page.waitForRequest('**'), page.evaluate(({url, value}) => { const request = new Request(url, { method: 'POST', body: JSON.stringify(value), }); request.headers.set('content-type', 'application/json;charset=UTF-8'); return fetch(request); }, {url: server.PREFIX + '/title.html', value}) ]); expect(request.postDataBuffer().equals(Buffer.from(JSON.stringify(value), 'utf-8'))).toBe(true); expect(request.postDataJSON()).toBe(value); }); it('should return post data w/o content-type', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest('**'), page.evaluate(({url}) => { const request = new Request(url, { method: 'POST', body: JSON.stringify({ value: 42 }), }); request.headers.set('content-type', ''); return fetch(request); }, {url: server.PREFIX + '/title.html'}) ]); expect(request.postDataJSON()).toEqual({ value: 42 }); }); it('should throw on invalid JSON in post data', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest('**'), page.evaluate(({url}) => { const request = new Request(url, { method: 'POST', body: '<not a json>', }); return fetch(request); }, {url: server.PREFIX + '/title.html'}) ]); let error; try { request.postDataJSON(); } catch (e) { error = e; } expect(error.message).toContain('POST data is not a valid JSON object: <not a json>'); }); it('should return post data for PUT requests', async ({page, server}) => { await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest('**'), page.evaluate(({url}) => { const request = new Request(url, { method: 'PUT', body: JSON.stringify({ value: 42 }), }); return fetch(request); }, {url: server.PREFIX + '/title.html'}) ]); expect(request.postDataJSON()).toEqual({ value: 42 }); }); it('should get post data for file/blob', async ({page, server, browserName}) => { it.fail(browserName === 'webkit' || browserName === 'chromium'); await page.goto(server.EMPTY_PAGE); const [request] = await Promise.all([ page.waitForRequest('**/*'), page.evaluate(() => { const file = new File(['file-contents'], 'filename.txt'); fetch('/data', { method: 'POST', headers: { 'content-type': 'application/octet-stream' }, body: file }); }) ]); expect(request.postData()).toBe('file-contents'); });
tests/page/network-post-data.spec.ts
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00020107183081563562, 0.00017450819723308086, 0.00016447815869469196, 0.00017240231682080775, 0.000008922605047700927 ]
{ "id": 5, "code_window": [ " return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries);\n", " if (os.platform() === 'win32' && os.arch() === 'x64')\n", " return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d)));\n", " }\n", "\n", " async installDeps(executablesToInstallDeps?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstallDeps);\n", " const targets = new Set<DependencyGroup>();\n", " for (const executable of executables) {\n", " if (executable._dependencyGroup)\n", " targets.add(executable._dependencyGroup);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async installDeps(executablesToInstallDeps: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 516 }
/** * Copyright 2017 Google Inc. All rights reserved. * Modifications 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 os from 'os'; import path from 'path'; import * as util from 'util'; import * as fs from 'fs'; import lockfile from 'proper-lockfile'; import { getUbuntuVersion } from './ubuntuVersion'; import { getFromENV, getAsBooleanFromENV, calculateSha1, removeFolders, existsAsync, hostPlatform, canAccessFile, spawnAsync, fetchData, wrapInASCIIBox } from './utils'; import { DependencyGroup, installDependenciesLinux, installDependenciesWindows, validateDependenciesLinux, validateDependenciesWindows } from './dependencies'; import { downloadBrowserWithProgressBar, logPolitely } from './browserFetcher'; const PACKAGE_PATH = path.join(__dirname, '..', '..'); const BIN_PATH = path.join(__dirname, '..', '..', 'bin'); const EXECUTABLE_PATHS = { 'chromium': { 'ubuntu18.04': ['chrome-linux', 'chrome'], 'ubuntu20.04': ['chrome-linux', 'chrome'], 'mac10.13': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.14': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac10.15': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'mac11-arm64': ['chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'], 'win32': ['chrome-win', 'chrome.exe'], 'win64': ['chrome-win', 'chrome.exe'], }, 'firefox': { 'ubuntu18.04': ['firefox', 'firefox'], 'ubuntu20.04': ['firefox', 'firefox'], 'mac10.13': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.14': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac10.15': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'mac11-arm64': ['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox'], 'win32': ['firefox', 'firefox.exe'], 'win64': ['firefox', 'firefox.exe'], }, 'webkit': { 'ubuntu18.04': ['pw_run.sh'], 'ubuntu20.04': ['pw_run.sh'], 'mac10.13': undefined, 'mac10.14': ['pw_run.sh'], 'mac10.15': ['pw_run.sh'], 'mac11': ['pw_run.sh'], 'mac11-arm64': ['pw_run.sh'], 'win32': ['Playwright.exe'], 'win64': ['Playwright.exe'], }, 'ffmpeg': { 'ubuntu18.04': ['ffmpeg-linux'], 'ubuntu20.04': ['ffmpeg-linux'], 'mac10.13': ['ffmpeg-mac'], 'mac10.14': ['ffmpeg-mac'], 'mac10.15': ['ffmpeg-mac'], 'mac11': ['ffmpeg-mac'], 'mac11-arm64': ['ffmpeg-mac'], 'win32': ['ffmpeg-win32.exe'], 'win64': ['ffmpeg-win64.exe'], }, }; const DOWNLOAD_URLS = { 'chromium': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-win64.zip', }, 'chromium-with-symbols': { 'ubuntu18.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'ubuntu20.04': '%s/builds/chromium/%s/chromium-with-symbols-linux.zip', 'mac10.13': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.14': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac10.15': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11': '%s/builds/chromium/%s/chromium-with-symbols-mac.zip', 'mac11-arm64': '%s/builds/chromium/%s/chromium-with-symbols-mac-arm64.zip', 'win32': '%s/builds/chromium/%s/chromium-with-symbols-win32.zip', 'win64': '%s/builds/chromium/%s/chromium-with-symbols-win64.zip', }, 'firefox': { 'ubuntu18.04': '%s/builds/firefox/%s/firefox-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox/%s/firefox-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.14': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac10.15': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11': '%s/builds/firefox/%s/firefox-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox/%s/firefox-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox/%s/firefox-win32.zip', 'win64': '%s/builds/firefox/%s/firefox-win64.zip', }, 'firefox-beta': { 'ubuntu18.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/firefox-beta/%s/firefox-beta-ubuntu-20.04.zip', 'mac10.13': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.14': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac10.15': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11': '%s/builds/firefox-beta/%s/firefox-beta-mac-10.14.zip', 'mac11-arm64': '%s/builds/firefox-beta/%s/firefox-beta-mac-11.0-arm64.zip', 'win32': '%s/builds/firefox-beta/%s/firefox-beta-win32.zip', 'win64': '%s/builds/firefox-beta/%s/firefox-beta-win64.zip', }, 'webkit': { 'ubuntu18.04': '%s/builds/webkit/%s/webkit-ubuntu-18.04.zip', 'ubuntu20.04': '%s/builds/webkit/%s/webkit-ubuntu-20.04.zip', 'mac10.13': undefined, 'mac10.14': '%s/builds/deprecated-webkit-mac-10.14/%s/deprecated-webkit-mac-10.14.zip', 'mac10.15': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11': '%s/builds/webkit/%s/webkit-mac-10.15.zip', 'mac11-arm64': '%s/builds/webkit/%s/webkit-mac-11.0-arm64.zip', 'win32': '%s/builds/webkit/%s/webkit-win64.zip', 'win64': '%s/builds/webkit/%s/webkit-win64.zip', }, 'ffmpeg': { 'ubuntu18.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'ubuntu20.04': '%s/builds/ffmpeg/%s/ffmpeg-linux.zip', 'mac10.13': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.14': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac10.15': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'mac11-arm64': '%s/builds/ffmpeg/%s/ffmpeg-mac.zip', 'win32': '%s/builds/ffmpeg/%s/ffmpeg-win32.zip', 'win64': '%s/builds/ffmpeg/%s/ffmpeg-win64.zip', }, }; export const registryDirectory = (() => { let result: string; const envDefined = getFromENV('PLAYWRIGHT_BROWSERS_PATH'); if (envDefined === '0') { result = path.join(__dirname, '..', '..', '.local-browsers'); } else if (envDefined) { result = envDefined; } else { let cacheDirectory: string; if (process.platform === 'linux') cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'); else if (process.platform === 'darwin') cacheDirectory = path.join(os.homedir(), 'Library', 'Caches'); else if (process.platform === 'win32') cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'); else throw new Error('Unsupported platform: ' + process.platform); result = path.join(cacheDirectory, 'ms-playwright'); } if (!path.isAbsolute(result)) { // It is important to resolve to the absolute path: // - for unzipping to work correctly; // - so that registry directory matches between installation and execution. // INIT_CWD points to the root of `npm/yarn install` and is probably what // the user meant when typing the relative path. result = path.resolve(getFromENV('INIT_CWD') || process.cwd(), result); } return result; })(); function isBrowserDirectory(browserDirectory: string): boolean { const baseName = path.basename(browserDirectory); for (const browserName of allDownloadable) { if (baseName.startsWith(browserName + '-')) return true; } return false; } type BrowsersJSON = { comment: string browsers: { name: string, revision: string, installByDefault: boolean, revisionOverrides?: {[os: string]: string}, }[] }; type BrowsersJSONDescriptor = { name: string, revision: string, installByDefault: boolean, dir: string, }; function readDescriptors(browsersJSON: BrowsersJSON) { return (browsersJSON['browsers']).map(obj => { const name = obj.name; const revisionOverride = (obj.revisionOverrides || {})[hostPlatform]; const revision = revisionOverride || obj.revision; const browserDirectoryPrefix = revisionOverride ? `${name}_${hostPlatform}_special` : `${name}`; const descriptor: BrowsersJSONDescriptor = { name, revision, installByDefault: !!obj.installByDefault, // Method `isBrowserDirectory` determines directory to be browser iff // it starts with some browser name followed by '-'. Some browser names // are prefixes of others, e.g. 'webkit' is a prefix of `webkit-technology-preview`. // To avoid older registries erroneously removing 'webkit-technology-preview', we have to // ensure that browser folders to never include dashes inside. dir: path.join(registryDirectory, browserDirectoryPrefix.replace(/-/g, '_') + '-' + revision), }; return descriptor; }); } export type BrowserName = 'chromium' | 'firefox' | 'webkit'; type InternalTool = 'ffmpeg' | 'firefox-beta' | 'chromium-with-symbols'; type ChromiumChannel = 'chrome' | 'chrome-beta' | 'chrome-dev' | 'chrome-canary' | 'msedge' | 'msedge-beta' | 'msedge-dev' | 'msedge-canary'; const allDownloadable = ['chromium', 'firefox', 'webkit', 'ffmpeg', 'firefox-beta', 'chromium-with-symbols']; export interface Executable { type: 'browser' | 'tool' | 'channel'; name: BrowserName | InternalTool | ChromiumChannel; browserName: BrowserName | undefined; installType: 'download-by-default' | 'download-on-demand' | 'install-script' | 'none'; directory: string | undefined; executablePathOrDie(sdkLanguage: string): string; executablePath(): string | undefined; validateHostRequirements(): Promise<void>; } interface ExecutableImpl extends Executable { _install?: () => Promise<void>; _dependencyGroup?: DependencyGroup; } export class Registry { private _executables: ExecutableImpl[]; constructor(browsersJSON: BrowsersJSON) { const descriptors = readDescriptors(browsersJSON); const findExecutablePath = (dir: string, name: keyof typeof EXECUTABLE_PATHS) => { const tokens = EXECUTABLE_PATHS[name][hostPlatform]; return tokens ? path.join(dir, ...tokens) : undefined; }; const executablePathOrDie = (name: string, e: string | undefined, installByDefault: boolean, sdkLanguage: string) => { if (!e) throw new Error(`${name} is not supported on ${hostPlatform}`); const installCommand = buildPlaywrightCLICommand(sdkLanguage, `install${installByDefault ? '' : ' ' + name}`); if (!canAccessFile(e)) { const prettyMessage = [ `Looks like Playwright Test or Playwright was just installed or updated.`, `Please run the following command to download new browser${installByDefault ? 's' : ''}:`, ``, ` ${installCommand}`, ``, `<3 Playwright Team`, ].join('\n'); throw new Error(`Executable doesn't exist at ${e}\n${wrapInASCIIBox(prettyMessage, 1)}`); } return e; }; this._executables = []; const chromium = descriptors.find(d => d.name === 'chromium')!; const chromiumExecutable = findExecutablePath(chromium.dir, 'chromium'); this._executables.push({ type: 'browser', name: 'chromium', browserName: 'chromium', directory: chromium.dir, executablePath: () => chromiumExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium', chromiumExecutable, chromium.installByDefault, sdkLanguage), installType: chromium.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromium.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromium, chromiumExecutable, DOWNLOAD_URLS['chromium'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); const chromiumWithSymbols = descriptors.find(d => d.name === 'chromium-with-symbols')!; const chromiumWithSymbolsExecutable = findExecutablePath(chromiumWithSymbols.dir, 'chromium'); this._executables.push({ type: 'tool', name: 'chromium-with-symbols', browserName: 'chromium', directory: chromiumWithSymbols.dir, executablePath: () => chromiumWithSymbolsExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('chromium-with-symbols', chromiumWithSymbolsExecutable, chromiumWithSymbols.installByDefault, sdkLanguage), installType: chromiumWithSymbols.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('chromium', chromiumWithSymbols.dir, ['chrome-linux'], [], ['chrome-win']), _install: () => this._downloadExecutable(chromiumWithSymbols, chromiumWithSymbolsExecutable, DOWNLOAD_URLS['chromium-with-symbols'][hostPlatform], 'PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST'), _dependencyGroup: 'chromium', }); this._executables.push(this._createChromiumChannel('chrome', { 'linux': '/opt/google/chrome/chrome', 'darwin': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', 'win32': `\\Google\\Chrome\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome', { 'linux': 'reinstall_chrome_stable_linux.sh', 'darwin': 'reinstall_chrome_stable_mac.sh', 'win32': 'reinstall_chrome_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-beta', { 'linux': '/opt/google/chrome-beta/chrome', 'darwin': '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta', 'win32': `\\Google\\Chrome Beta\\Application\\chrome.exe`, }, () => this._installChromiumChannel('chrome-beta', { 'linux': 'reinstall_chrome_beta_linux.sh', 'darwin': 'reinstall_chrome_beta_mac.sh', 'win32': 'reinstall_chrome_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('chrome-dev', { 'linux': '/opt/google/chrome-unstable/chrome', 'darwin': '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev', 'win32': `\\Google\\Chrome Dev\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('chrome-canary', { 'linux': '', 'darwin': '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary', 'win32': `\\Google\\Chrome SxS\\Application\\chrome.exe`, })); this._executables.push(this._createChromiumChannel('msedge', { 'linux': '', 'darwin': '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', 'win32': `\\Microsoft\\Edge\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge', { 'linux': '', 'darwin': 'reinstall_msedge_stable_mac.sh', 'win32': 'reinstall_msedge_stable_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-beta', { 'linux': '/opt/microsoft/msedge-beta/msedge', 'darwin': '/Applications/Microsoft Edge Beta.app/Contents/MacOS/Microsoft Edge Beta', 'win32': `\\Microsoft\\Edge Beta\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-beta', { 'darwin': 'reinstall_msedge_beta_mac.sh', 'linux': 'reinstall_msedge_beta_linux.sh', 'win32': 'reinstall_msedge_beta_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-dev', { 'linux': '/opt/microsoft/msedge-dev/msedge', 'darwin': '/Applications/Microsoft Edge Dev.app/Contents/MacOS/Microsoft Edge Dev', 'win32': `\\Microsoft\\Edge Dev\\Application\\msedge.exe`, }, () => this._installMSEdgeChannel('msedge-dev', { 'darwin': 'reinstall_msedge_dev_mac.sh', 'linux': 'reinstall_msedge_dev_linux.sh', 'win32': 'reinstall_msedge_dev_win.ps1', }))); this._executables.push(this._createChromiumChannel('msedge-canary', { 'linux': '', 'darwin': '/Applications/Microsoft Edge Canary.app/Contents/MacOS/Microsoft Edge Canary', 'win32': `\\Microsoft\\Edge SxS\\Application\\msedge.exe`, })); const firefox = descriptors.find(d => d.name === 'firefox')!; const firefoxExecutable = findExecutablePath(firefox.dir, 'firefox'); this._executables.push({ type: 'browser', name: 'firefox', browserName: 'firefox', directory: firefox.dir, executablePath: () => firefoxExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox', firefoxExecutable, firefox.installByDefault, sdkLanguage), installType: firefox.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefox.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefox, firefoxExecutable, DOWNLOAD_URLS['firefox'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const firefoxBeta = descriptors.find(d => d.name === 'firefox-beta')!; const firefoxBetaExecutable = findExecutablePath(firefoxBeta.dir, 'firefox'); this._executables.push({ type: 'tool', name: 'firefox-beta', browserName: 'firefox', directory: firefoxBeta.dir, executablePath: () => firefoxBetaExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('firefox-beta', firefoxBetaExecutable, firefoxBeta.installByDefault, sdkLanguage), installType: firefoxBeta.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('firefox', firefoxBeta.dir, ['firefox'], [], ['firefox']), _install: () => this._downloadExecutable(firefoxBeta, firefoxBetaExecutable, DOWNLOAD_URLS['firefox-beta'][hostPlatform], 'PLAYWRIGHT_FIREFOX_DOWNLOAD_HOST'), _dependencyGroup: 'firefox', }); const webkit = descriptors.find(d => d.name === 'webkit')!; const webkitExecutable = findExecutablePath(webkit.dir, 'webkit'); const webkitLinuxLddDirectories = [ path.join('minibrowser-gtk'), path.join('minibrowser-gtk', 'bin'), path.join('minibrowser-gtk', 'lib'), path.join('minibrowser-wpe'), path.join('minibrowser-wpe', 'bin'), path.join('minibrowser-wpe', 'lib'), ]; this._executables.push({ type: 'browser', name: 'webkit', browserName: 'webkit', directory: webkit.dir, executablePath: () => webkitExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('webkit', webkitExecutable, webkit.installByDefault, sdkLanguage), installType: webkit.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => this._validateHostRequirements('webkit', webkit.dir, webkitLinuxLddDirectories, ['libGLESv2.so.2', 'libx264.so'], ['']), _install: () => this._downloadExecutable(webkit, webkitExecutable, DOWNLOAD_URLS['webkit'][hostPlatform], 'PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST'), _dependencyGroup: 'webkit', }); const ffmpeg = descriptors.find(d => d.name === 'ffmpeg')!; const ffmpegExecutable = findExecutablePath(ffmpeg.dir, 'ffmpeg'); this._executables.push({ type: 'tool', name: 'ffmpeg', browserName: undefined, directory: ffmpeg.dir, executablePath: () => ffmpegExecutable, executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('ffmpeg', ffmpegExecutable, ffmpeg.installByDefault, sdkLanguage), installType: ffmpeg.installByDefault ? 'download-by-default' : 'download-on-demand', validateHostRequirements: () => Promise.resolve(), _install: () => this._downloadExecutable(ffmpeg, ffmpegExecutable, DOWNLOAD_URLS['ffmpeg'][hostPlatform], 'PLAYWRIGHT_FFMPEG_DOWNLOAD_HOST'), _dependencyGroup: 'tools', }); } private _createChromiumChannel(name: ChromiumChannel, lookAt: Record<'linux' | 'darwin' | 'win32', string>, install?: () => Promise<void>): ExecutableImpl { const executablePath = (shouldThrow: boolean) => { const suffix = lookAt[process.platform as 'linux' | 'darwin' | 'win32']; if (!suffix) { if (shouldThrow) throw new Error(`Chromium distribution '${name}' is not supported on ${process.platform}`); return undefined; } const prefixes = (process.platform === 'win32' ? [ process.env.LOCALAPPDATA, process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)'] ].filter(Boolean) : ['']) as string[]; for (const prefix of prefixes) { const executablePath = path.join(prefix, suffix); if (canAccessFile(executablePath)) return executablePath; } if (!shouldThrow) return undefined; const location = prefixes.length ? ` at ${path.join(prefixes[0], suffix)}` : ``; // TODO: language-specific error message const installation = install ? `\nRun "npx playwright install ${name}"` : ''; throw new Error(`Chromium distribution '${name}' is not found${location}${installation}`); }; return { type: 'channel', name, browserName: 'chromium', directory: undefined, executablePath: () => executablePath(false), executablePathOrDie: (sdkLanguage: string) => executablePath(true)!, installType: install ? 'install-script' : 'none', validateHostRequirements: () => Promise.resolve(), _install: install, }; } executables(): Executable[] { return this._executables; } findExecutable(name: BrowserName): Executable; findExecutable(name: string): Executable | undefined; findExecutable(name: string): Executable | undefined { return this._executables.find(b => b.name === name); } private _addRequirementsAndDedupe(executables: Executable[] | undefined): ExecutableImpl[] { const set = new Set<ExecutableImpl>(); if (!executables) executables = this._executables.filter(executable => executable.installType === 'download-by-default'); for (const executable of executables as ExecutableImpl[]) { set.add(executable); if (executable.browserName === 'chromium') set.add(this.findExecutable('ffmpeg')!); } return Array.from(set); } private async _validateHostRequirements(browserName: BrowserName, browserDirectory: string, linuxLddDirectories: string[], dlOpenLibraries: string[], windowsExeAndDllDirectories: string[]) { if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS')) { process.stdout.write('Skipping host requirements validation logic because `PLAYWRIGHT_SKIP_VALIDATE_HOST_REQUIREMENTS` env variable is set.\n'); return; } const ubuntuVersion = await getUbuntuVersion(); if (browserName === 'firefox' && ubuntuVersion === '16.04') throw new Error(`Cannot launch Firefox on Ubuntu 16.04! Minimum required Ubuntu version for Firefox browser is 18.04`); if (os.platform() === 'linux') return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries); if (os.platform() === 'win32' && os.arch() === 'x64') return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d))); } async installDeps(executablesToInstallDeps?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstallDeps); const targets = new Set<DependencyGroup>(); for (const executable of executables) { if (executable._dependencyGroup) targets.add(executable._dependencyGroup); } targets.add('tools'); if (os.platform() === 'win32') return await installDependenciesWindows(targets); if (os.platform() === 'linux') return await installDependenciesLinux(targets); } async install(executablesToInstall?: Executable[]) { const executables = this._addRequirementsAndDedupe(executablesToInstall); await fs.promises.mkdir(registryDirectory, { recursive: true }); const lockfilePath = path.join(registryDirectory, '__dirlock'); const releaseLock = await lockfile.lock(registryDirectory, { retries: { retries: 10, // Retry 20 times during 10 minutes with // exponential back-off. // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions factor: 1.27579, }, onCompromised: (err: Error) => { throw new Error(`${err.message} Path: ${lockfilePath}`); }, lockfilePath, }); const linksDir = path.join(registryDirectory, '.links'); try { // Create a link first, so that cache validation does not remove our own browsers. await fs.promises.mkdir(linksDir, { recursive: true }); await fs.promises.writeFile(path.join(linksDir, calculateSha1(PACKAGE_PATH)), PACKAGE_PATH); // Remove stale browsers. await this._validateInstallationCache(linksDir); // Install browsers for this package. for (const executable of executables) { if (executable._install) await executable._install(); else throw new Error(`ERROR: Playwright does not support installing ${executable.name}`); } } catch (e) { if (e.code === 'ELOCKED') { const rmCommand = process.platform === 'win32' ? 'rm -R' : 'rm -rf'; throw new Error('\n' + wrapInASCIIBox([ `An active lockfile is found at:`, ``, ` ${lockfilePath}`, ``, `Either:`, `- wait a few minutes if other Playwright is installing browsers in parallel`, `- remove lock manually with:`, ``, ` ${rmCommand} ${lockfilePath}`, ``, `<3 Playwright Team`, ].join('\n'), 1)); } else { throw e; } } finally { await releaseLock(); } } private async _downloadExecutable(descriptor: BrowsersJSONDescriptor, executablePath: string | undefined, downloadURLTemplate: string | undefined, downloadHostEnv: string) { if (!downloadURLTemplate || !executablePath) throw new Error(`ERROR: Playwright does not support ${descriptor.name} on ${hostPlatform}`); const downloadHost = (downloadHostEnv && getFromENV(downloadHostEnv)) || getFromENV('PLAYWRIGHT_DOWNLOAD_HOST') || 'https://playwright.azureedge.net'; const downloadURL = util.format(downloadURLTemplate, downloadHost, descriptor.revision); const title = `${descriptor.name} v${descriptor.revision}`; const downloadFileName = `playwright-download-${descriptor.name}-${hostPlatform}-${descriptor.revision}.zip`; await downloadBrowserWithProgressBar(title, descriptor.dir, executablePath, downloadURL, downloadFileName).catch(e => { throw new Error(`Failed to download ${title}, caused by\n${e.stack}`); }); await fs.promises.writeFile(markerFilePath(descriptor.dir), ''); } private async _installMSEdgeChannel(channel: 'msedge'|'msedge-beta'|'msedge-dev', scripts: Record<'linux' | 'darwin' | 'win32', string>) { const scriptArgs: string[] = []; if (process.platform !== 'linux') { const products = JSON.parse(await fetchData({ url: 'https://edgeupdates.microsoft.com/api/products' })); const productName = { 'msedge': 'Stable', 'msedge-beta': 'Beta', 'msedge-dev': 'Dev', }[channel]; const product = products.find((product: any) => product.Product === productName); const searchConfig = ({ darwin: {platform: 'MacOS', arch: 'universal', artifact: 'pkg'}, win32: {platform: 'Windows', arch: os.arch() === 'x64' ? 'x64' : 'x86', artifact: 'msi'}, } as any)[process.platform]; const release = searchConfig ? product.Releases.find((release: any) => release.Platform === searchConfig.platform && release.Architecture === searchConfig.arch) : null; const artifact = release ? release.Artifacts.find((artifact: any) => artifact.ArtifactName === searchConfig.artifact) : null; if (artifact) scriptArgs.push(artifact.Location /* url */); else throw new Error(`Cannot install ${channel} on ${process.platform}`); } await this._installChromiumChannel(channel, scripts, scriptArgs); } private async _installChromiumChannel(channel: string, scripts: Record<'linux' | 'darwin' | 'win32', string>, scriptArgs: string[] = []) { const scriptName = scripts[process.platform as 'linux' | 'darwin' | 'win32']; if (!scriptName) throw new Error(`Cannot install ${channel} on ${process.platform}`); const shell = scriptName.endsWith('.ps1') ? 'powershell.exe' : 'bash'; const { code } = await spawnAsync(shell, [path.join(BIN_PATH, scriptName), ...scriptArgs], { cwd: BIN_PATH, stdio: 'inherit' }); if (code !== 0) throw new Error(`Failed to install ${channel}`); } private async _validateInstallationCache(linksDir: string) { // 1. Collect used downloads and package descriptors. const usedBrowserPaths: Set<string> = new Set(); for (const fileName of await fs.promises.readdir(linksDir)) { const linkPath = path.join(linksDir, fileName); let linkTarget = ''; try { linkTarget = (await fs.promises.readFile(linkPath)).toString(); const browsersJSON = require(path.join(linkTarget, 'browsers.json')); const descriptors = readDescriptors(browsersJSON); for (const browserName of allDownloadable) { // We retain browsers if they are found in the descriptor. // Note, however, that there are older versions out in the wild that rely on // the "download" field in the browser descriptor and use its value // to retain and download browsers. // As of v1.10, we decided to abandon "download" field. const descriptor = descriptors.find(d => d.name === browserName); if (!descriptor) continue; const usedBrowserPath = descriptor.dir; const browserRevision = parseInt(descriptor.revision, 10); // Old browser installations don't have marker file. const shouldHaveMarkerFile = (browserName === 'chromium' && browserRevision >= 786218) || (browserName === 'firefox' && browserRevision >= 1128) || (browserName === 'webkit' && browserRevision >= 1307) || // All new applications have a marker file right away. (browserName !== 'firefox' && browserName !== 'chromium' && browserName !== 'webkit'); if (!shouldHaveMarkerFile || (await existsAsync(markerFilePath(usedBrowserPath)))) usedBrowserPaths.add(usedBrowserPath); } } catch (e) { await fs.promises.unlink(linkPath).catch(e => {}); } } // 2. Delete all unused browsers. if (!getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_GC')) { let downloadedBrowsers = (await fs.promises.readdir(registryDirectory)).map(file => path.join(registryDirectory, file)); downloadedBrowsers = downloadedBrowsers.filter(file => isBrowserDirectory(file)); const directories = new Set<string>(downloadedBrowsers); for (const browserDirectory of usedBrowserPaths) directories.delete(browserDirectory); for (const directory of directories) logPolitely('Removing unused browser at ' + directory); await removeFolders([...directories]); } } } function markerFilePath(browserDirectory: string): string { return path.join(browserDirectory, 'INSTALLATION_COMPLETE'); } function buildPlaywrightCLICommand(sdkLanguage: string, parameters: string): string { switch (sdkLanguage) { case 'python': return `playwright ${parameters}`; case 'java': return `mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="${parameters}"`; case 'csharp': return `playwright ${parameters}`; default: return `npx playwright ${parameters}`; } } export async function installDefaultBrowsersForNpmInstall() { // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1 if (getAsBooleanFromENV('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) { logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set'); return false; } await registry.install(); } export const registry = new Registry(require('../../browsers.json'));
src/utils/registry.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9983500242233276, 0.06092756241559982, 0.000157735135871917, 0.00017665424093138427, 0.22306451201438904 ]
{ "id": 5, "code_window": [ " return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries);\n", " if (os.platform() === 'win32' && os.arch() === 'x64')\n", " return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d)));\n", " }\n", "\n", " async installDeps(executablesToInstallDeps?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstallDeps);\n", " const targets = new Set<DependencyGroup>();\n", " for (const executable of executables) {\n", " if (executable._dependencyGroup)\n", " targets.add(executable._dependencyGroup);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async installDeps(executablesToInstallDeps: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 516 }
// Copyright (C) 2010, 2013 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Base.xcconfig" ARCHS = $(ARCHS_STANDARD_32_64_BIT); ONLY_ACTIVE_ARCH = YES; TARGET_MAC_OS_X_VERSION_MAJOR = $(MAC_OS_X_VERSION_MAJOR); MACOSX_DEPLOYMENT_TARGET = $(MACOSX_DEPLOYMENT_TARGET_$(TARGET_MAC_OS_X_VERSION_MAJOR)) MACOSX_DEPLOYMENT_TARGET_101300 = 10.13; MACOSX_DEPLOYMENT_TARGET_101400 = 10.14; MACOSX_DEPLOYMENT_TARGET_101500 = 10.15; MACOSX_DEPLOYMENT_TARGET_101600 = 10.16; GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES; SDKROOT = $(SDKROOT_$(USE_INTERNAL_SDK)); SDKROOT_ = macosx; SDKROOT_YES = macosx.internal; WK_CCACHE_DIR = $(SRCROOT)/../ccache; #include "../../ccache/ccache.xcconfig"
browser_patches/webkit/embedder/Playwright/Configurations/DebugRelease.xcconfig
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0009232453303411603, 0.0003297638613730669, 0.00016085105016827583, 0.00017613981617614627, 0.00029727601213380694 ]
{ "id": 5, "code_window": [ " return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries);\n", " if (os.platform() === 'win32' && os.arch() === 'x64')\n", " return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d)));\n", " }\n", "\n", " async installDeps(executablesToInstallDeps?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstallDeps);\n", " const targets = new Set<DependencyGroup>();\n", " for (const executable of executables) {\n", " if (executable._dependencyGroup)\n", " targets.add(executable._dependencyGroup);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async installDeps(executablesToInstallDeps: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 516 }
/** * 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. */ const {SimpleBlob} = require('./utils.js'); async function processDashboardRaw(context, report) { const timestamp = Date.now(); const dashboardBlob = await SimpleBlob.create('dashboards', `raw/${report.metadata.commitSHA}.json`); const dashboardData = (await dashboardBlob.download()) || []; dashboardData.push(report); await dashboardBlob.uploadGzipped(dashboardData); context.log(` ===== started dashboard raw ===== SHA: ${report.metadata.commitSHA} URL: ${report.metadata.runURL} timestamp: ${report.metadata.commitTimestamp} ===== complete in ${Date.now() - timestamp}ms ===== `); return { reports: dashboardData, commitSHA: report.metadata.commitSHA, }; } module.exports = {processDashboardRaw};
utils/flakiness-dashboard/processing/dashboard_raw.js
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0001779618760338053, 0.00017612837837077677, 0.00017424550605937839, 0.00017627104534767568, 0.000001278928834835824 ]
{ "id": 5, "code_window": [ " return await validateDependenciesLinux(linuxLddDirectories.map(d => path.join(browserDirectory, d)), dlOpenLibraries);\n", " if (os.platform() === 'win32' && os.arch() === 'x64')\n", " return await validateDependenciesWindows(windowsExeAndDllDirectories.map(d => path.join(browserDirectory, d)));\n", " }\n", "\n", " async installDeps(executablesToInstallDeps?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstallDeps);\n", " const targets = new Set<DependencyGroup>();\n", " for (const executable of executables) {\n", " if (executable._dependencyGroup)\n", " targets.add(executable._dependencyGroup);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async installDeps(executablesToInstallDeps: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 516 }
<style> /* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain) */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } </style>
tests/assets/resetcss.html
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.0006419671117328107, 0.0002523559087421745, 0.00017310486873611808, 0.00017394524184055626, 0.00017424748511984944 ]
{ "id": 6, "code_window": [ " return await installDependenciesWindows(targets);\n", " if (os.platform() === 'linux')\n", " return await installDependenciesLinux(targets);\n", " }\n", "\n", " async install(executablesToInstall?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstall);\n", " await fs.promises.mkdir(registryDirectory, { recursive: true });\n", " const lockfilePath = path.join(registryDirectory, '__dirlock');\n", " const releaseLock = await lockfile.lock(registryDirectory, {\n", " retries: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async install(executablesToInstall: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 530 }
#!/usr/bin/env node /** * 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. */ /* eslint-disable no-console */ import fs from 'fs'; import os from 'os'; import path from 'path'; import program from 'commander'; import { runDriver, runServer, printApiJson, launchBrowserServer } from './driver'; import { showTraceViewer } from '../server/trace/viewer/traceViewer'; import * as playwright from '../..'; import { BrowserContext } from '../client/browserContext'; import { Browser } from '../client/browser'; import { Page } from '../client/page'; import { BrowserType } from '../client/browserType'; import { BrowserContextOptions, LaunchOptions } from '../client/types'; import { spawn } from 'child_process'; import { registry, Executable } from '../utils/registry'; import { launchGridAgent } from '../grid/gridAgent'; import { launchGridServer } from '../grid/gridServer'; const packageJSON = require('../../package.json'); program .version('Version ' + packageJSON.version) .name(process.env.PW_CLI_NAME || 'npx playwright'); commandWithOpenOptions('open [url]', 'open page in browser specified via -b, --browser', []) .action(function(url, command) { open(command, url, language()).catch(logErrorAndExit); }) .on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ open'); console.log(' $ open -b webkit https://example.com'); }); commandWithOpenOptions('codegen [url]', 'open page and generate code for user actions', [ ['-o, --output <file name>', 'saves the generated script to a file'], ['--target <language>', `language to generate, one of javascript, test, python, python-async, csharp`, language()], ]).action(function(url, command) { codegen(command, url, command.target, command.output).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ codegen'); console.log(' $ codegen --target=python'); console.log(' $ codegen -b webkit https://example.com'); }); program .command('debug <app> [args...]', { hidden: true }) .description('run command in debug mode: disable timeout, open inspector') .allowUnknownOption(true) .action(function(app, args) { spawn(app, args, { env: { ...process.env, PWDEBUG: '1' }, stdio: 'inherit' }); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ debug node test.js'); console.log(' $ debug npm run test'); }); function suggestedBrowsersToInstall() { return registry.executables().filter(e => e.installType !== 'none' && e.type !== 'tool').map(e => e.name).join(', '); } function checkBrowsersToInstall(args: string[]): Executable[] { const faultyArguments: string[] = []; const executables: Executable[] = []; for (const arg of args) { const executable = registry.findExecutable(arg); if (!executable || executable.installType === 'none') faultyArguments.push(arg); else executables.push(executable); } if (faultyArguments.length) { console.log(`Invalid installation targets: ${faultyArguments.map(name => `'${name}'`).join(', ')}. Expecting one of: ${suggestedBrowsersToInstall()}`); process.exit(1); } return executables; } program .command('install [browser...]') .description('ensure browsers necessary for this version of Playwright are installed') .option('--with-deps', 'install system dependencies for browsers') .action(async function(args: string[], command: program.Command) { try { if (!args.length) { if (command.opts().withDeps) await registry.installDeps(); await registry.install(); } else { const executables = checkBrowsersToInstall(args); if (command.opts().withDeps) await registry.installDeps(executables); await registry.install(executables); } } catch (e) { console.log(`Failed to install browsers\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install`); console.log(` Install default browsers.`); console.log(``); console.log(` - $ install chrome firefox`); console.log(` Install custom browsers, supports ${suggestedBrowsersToInstall()}.`); }); program .command('install-deps [browser...]') .description('install dependencies necessary to run browsers (will ask for sudo permissions)') .action(async function(args: string[]) { try { if (!args.length) await registry.installDeps(); else await registry.installDeps(checkBrowsersToInstall(args)); } catch (e) { console.log(`Failed to install browser dependencies\n${e}`); process.exit(1); } }).on('--help', function() { console.log(``); console.log(`Examples:`); console.log(` - $ install-deps`); console.log(` Install dependencies for default browsers.`); console.log(``); console.log(` - $ install-deps chrome firefox`); console.log(` Install dependencies for specific browsers, supports ${suggestedBrowsersToInstall()}.`); }); const browsers = [ { alias: 'cr', name: 'Chromium', type: 'chromium' }, { alias: 'ff', name: 'Firefox', type: 'firefox' }, { alias: 'wk', name: 'WebKit', type: 'webkit' }, ]; for (const {alias, name, type} of browsers) { commandWithOpenOptions(`${alias} [url]`, `open page in ${name}`, []) .action(function(url, command) { open({ ...command, browser: type }, url, command.target).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(` $ ${alias} https://example.com`); }); } commandWithOpenOptions('screenshot <url> <filename>', 'capture a page screenshot', [ ['--wait-for-selector <selector>', 'wait for selector before taking a screenshot'], ['--wait-for-timeout <timeout>', 'wait for timeout in milliseconds before taking a screenshot'], ['--full-page', 'whether to take a full page screenshot (entire scrollable area)'], ]).action(function(url, filename, command) { screenshot(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ screenshot -b webkit https://example.com example.png'); }); commandWithOpenOptions('pdf <url> <filename>', 'save page as pdf', [ ['--wait-for-selector <selector>', 'wait for given selector before saving as pdf'], ['--wait-for-timeout <timeout>', 'wait for given timeout in milliseconds before saving as pdf'], ]).action(function(url, filename, command) { pdf(command, command, url, filename).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ pdf https://example.com example.pdf'); }); program .command('experimental-grid-server', { hidden: true }) .option('--port <port>', 'grid port; defaults to 3333') .option('--agent-factory <factory>', 'path to grid agent factory or npm package') .option('--auth-token <authToken>', 'optional authentication token') .action(function(options) { launchGridServer(options.agentFactory, options.port || 3333, options.authToken); }); program .command('experimental-grid-agent', { hidden: true }) .requiredOption('--agent-id <agentId>', 'agent ID') .requiredOption('--grid-url <gridURL>', 'grid URL') .action(function(options) { launchGridAgent(options.agentId, options.gridUrl); }); program .command('show-trace [trace]') .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .description('Show trace viewer') .action(function(trace, command) { if (command.browser === 'cr') command.browser = 'chromium'; if (command.browser === 'ff') command.browser = 'firefox'; if (command.browser === 'wk') command.browser = 'webkit'; showTraceViewer(trace, command.browser).catch(logErrorAndExit); }).on('--help', function() { console.log(''); console.log('Examples:'); console.log(''); console.log(' $ show-trace trace/directory'); }); if (!process.env.PW_CLI_TARGET_LANG) { let playwrightTestPackagePath = null; try { const isLocal = packageJSON.name === '@playwright/test' || process.env.PWTEST_CLI_ALLOW_TEST_COMMAND; if (isLocal) { playwrightTestPackagePath = '../test/cli'; } else { playwrightTestPackagePath = require.resolve('@playwright/test/lib/test/cli', { paths: [__dirname, process.cwd()] }); } } catch {} if (playwrightTestPackagePath) { require(playwrightTestPackagePath).addTestCommand(program); } else { const command = program.command('test').allowUnknownOption(true); command.description('Run tests with Playwright Test. Available in @playwright/test package.'); command.action(async (args, opts) => { console.error('Please install @playwright/test package to use Playwright Test.'); console.error(' npm install -D @playwright/test'); process.exit(1); }); } } if (process.argv[2] === 'run-driver') runDriver(); else if (process.argv[2] === 'run-server') runServer(process.argv[3] ? +process.argv[3] : undefined).catch(logErrorAndExit); else if (process.argv[2] === 'print-api-json') printApiJson(); else if (process.argv[2] === 'launch-server') launchBrowserServer(process.argv[3], process.argv[4]).catch(logErrorAndExit); else program.parse(process.argv); type Options = { browser: string; channel?: string; colorScheme?: string; device?: string; geolocation?: string; ignoreHttpsErrors?: boolean; lang?: string; loadStorage?: string; proxyServer?: string; saveStorage?: string; saveTrace?: string; timeout: string; timezone?: string; viewportSize?: string; userAgent?: string; }; type CaptureOptions = { waitForSelector?: string; waitForTimeout?: string; fullPage: boolean; }; async function launchContext(options: Options, headless: boolean, executablePath?: string): Promise<{ browser: Browser, browserName: string, launchOptions: LaunchOptions, contextOptions: BrowserContextOptions, context: BrowserContext }> { validateOptions(options); const browserType = lookupBrowserType(options); const launchOptions: LaunchOptions = { headless, executablePath }; if (options.channel) launchOptions.channel = options.channel as any; const contextOptions: BrowserContextOptions = // Copy the device descriptor since we have to compare and modify the options. options.device ? { ...playwright.devices[options.device] } : {}; // In headful mode, use host device scale factor for things to look nice. // In headless, keep things the way it works in Playwright by default. // Assume high-dpi on MacOS. TODO: this is not perfect. if (!headless) contextOptions.deviceScaleFactor = os.platform() === 'darwin' ? 2 : 1; // Work around the WebKit GTK scrolling issue. if (browserType.name() === 'webkit' && process.platform === 'linux') { delete contextOptions.hasTouch; delete contextOptions.isMobile; } if (contextOptions.isMobile && browserType.name() === 'firefox') contextOptions.isMobile = undefined; contextOptions.acceptDownloads = true; // Proxy if (options.proxyServer) { launchOptions.proxy = { server: options.proxyServer }; } const browser = await browserType.launch(launchOptions); // Viewport size if (options.viewportSize) { try { const [ width, height ] = options.viewportSize.split(',').map(n => parseInt(n, 10)); contextOptions.viewport = { width, height }; } catch (e) { console.log('Invalid window size format: use "width, height", for example --window-size=800,600'); process.exit(0); } } // Geolocation if (options.geolocation) { try { const [latitude, longitude] = options.geolocation.split(',').map(n => parseFloat(n.trim())); contextOptions.geolocation = { latitude, longitude }; } catch (e) { console.log('Invalid geolocation format: user lat, long, for example --geolocation="37.819722,-122.478611"'); process.exit(0); } contextOptions.permissions = ['geolocation']; } // User agent if (options.userAgent) contextOptions.userAgent = options.userAgent; // Lang if (options.lang) contextOptions.locale = options.lang; // Color scheme if (options.colorScheme) contextOptions.colorScheme = options.colorScheme as 'dark' | 'light'; // Timezone if (options.timezone) contextOptions.timezoneId = options.timezone; // Storage if (options.loadStorage) contextOptions.storageState = options.loadStorage; if (options.ignoreHttpsErrors) contextOptions.ignoreHTTPSErrors = true; // Close app when the last window closes. const context = await browser.newContext(contextOptions); let closingBrowser = false; async function closeBrowser() { // We can come here multiple times. For example, saving storage creates // a temporary page and we call closeBrowser again when that page closes. if (closingBrowser) return; closingBrowser = true; if (options.saveTrace) await context.tracing.stop({ path: options.saveTrace }); if (options.saveStorage) await context.storageState({ path: options.saveStorage }).catch(e => null); await browser.close(); } context.on('page', page => { page.on('dialog', () => {}); // Prevent dialogs from being automatically dismissed. page.on('close', () => { const hasPage = browser.contexts().some(context => context.pages().length > 0); if (hasPage) return; // Avoid the error when the last page is closed because the browser has been closed. closeBrowser().catch(e => null); }); }); if (options.timeout) { context.setDefaultTimeout(parseInt(options.timeout, 10)); context.setDefaultNavigationTimeout(parseInt(options.timeout, 10)); } if (options.saveTrace) await context.tracing.start({ screenshots: true, snapshots: true }); // Omit options that we add automatically for presentation purpose. delete launchOptions.headless; delete launchOptions.executablePath; delete contextOptions.deviceScaleFactor; delete contextOptions.acceptDownloads; return { browser, browserName: browserType.name(), context, contextOptions, launchOptions }; } async function openPage(context: BrowserContext, url: string | undefined): Promise<Page> { const page = await context.newPage(); if (url) { if (fs.existsSync(url)) url = 'file://' + path.resolve(url); else if (!url.startsWith('http') && !url.startsWith('file://') && !url.startsWith('about:') && !url.startsWith('data:')) url = 'http://' + url; await page.goto(url); } return page; } async function open(options: Options, url: string | undefined, language: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function codegen(options: Options, url: string | undefined, language: string, outputFile?: string) { const { context, launchOptions, contextOptions } = await launchContext(options, !!process.env.PWTEST_CLI_HEADLESS, process.env.PWTEST_CLI_EXECUTABLE_PATH); await context._enableRecorder({ language, launchOptions, contextOptions, device: options.device, saveStorage: options.saveStorage, startRecording: true, outputFile: outputFile ? path.resolve(outputFile) : undefined }); await openPage(context, url); if (process.env.PWTEST_CLI_EXIT) await Promise.all(context.pages().map(p => p.close())); } async function waitForPage(page: Page, captureOptions: CaptureOptions) { if (captureOptions.waitForSelector) { console.log(`Waiting for selector ${captureOptions.waitForSelector}...`); await page.waitForSelector(captureOptions.waitForSelector); } if (captureOptions.waitForTimeout) { console.log(`Waiting for timeout ${captureOptions.waitForTimeout}...`); await page.waitForTimeout(parseInt(captureOptions.waitForTimeout, 10)); } } async function screenshot(options: Options, captureOptions: CaptureOptions, url: string, path: string) { const { browser, context } = await launchContext(options, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Capturing screenshot into ' + path); await page.screenshot({ path, fullPage: !!captureOptions.fullPage }); await browser.close(); } async function pdf(options: Options, captureOptions: CaptureOptions, url: string, path: string) { if (options.browser !== 'chromium') { console.error('PDF creation is only working with Chromium'); process.exit(1); } const { browser, context } = await launchContext({ ...options, browser: 'chromium' }, true); console.log('Navigating to ' + url); const page = await openPage(context, url); await waitForPage(page, captureOptions); console.log('Saving as pdf into ' + path); await page.pdf!({ path }); await browser.close(); } function lookupBrowserType(options: Options): BrowserType { let name = options.browser; if (options.device) { const device = playwright.devices[options.device]; name = device.defaultBrowserType; } let browserType: any; switch (name) { case 'chromium': browserType = playwright.chromium; break; case 'webkit': browserType = playwright.webkit; break; case 'firefox': browserType = playwright.firefox; break; case 'cr': browserType = playwright.chromium; break; case 'wk': browserType = playwright.webkit; break; case 'ff': browserType = playwright.firefox; break; } if (browserType) return browserType; program.help(); } function validateOptions(options: Options) { if (options.device && !(options.device in playwright.devices)) { console.log(`Device descriptor not found: '${options.device}', available devices are:`); for (const name in playwright.devices) console.log(` "${name}"`); process.exit(0); } if (options.colorScheme && !['light', 'dark'].includes(options.colorScheme)) { console.log('Invalid color scheme, should be one of "light", "dark"'); process.exit(0); } } function logErrorAndExit(e: Error) { console.error(e); process.exit(1); } function language(): string { return process.env.PW_CLI_TARGET_LANG || 'test'; } function commandWithOpenOptions(command: string, description: string, options: any[][]): program.Command { let result = program.command(command).description(description); for (const option of options) result = result.option(option[0], ...option.slice(1)); return result .option('-b, --browser <browserType>', 'browser to use, one of cr, chromium, ff, firefox, wk, webkit', 'chromium') .option('--channel <channel>', 'Chromium distribution channel, "chrome", "chrome-beta", "msedge-dev", etc') .option('--color-scheme <scheme>', 'emulate preferred color scheme, "light" or "dark"') .option('--device <deviceName>', 'emulate device, for example "iPhone 11"') .option('--geolocation <coordinates>', 'specify geolocation coordinates, for example "37.819722,-122.478611"') .option('--ignore-https-errors', 'ignore https errors') .option('--load-storage <filename>', 'load context storage state from the file, previously saved with --save-storage') .option('--lang <language>', 'specify language / locale, for example "en-GB"') .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"') .option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage') .option('--save-trace <filename>', 'record a trace for the session and save it to a file') .option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"') .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds', '10000') .option('--user-agent <ua string>', 'specify user agent string') .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"'); }
src/cli/cli.ts
1
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.9981624484062195, 0.06725142151117325, 0.00016330642392858863, 0.0001734472025418654, 0.24839314818382263 ]
{ "id": 6, "code_window": [ " return await installDependenciesWindows(targets);\n", " if (os.platform() === 'linux')\n", " return await installDependenciesLinux(targets);\n", " }\n", "\n", " async install(executablesToInstall?: Executable[]) {\n", " const executables = this._addRequirementsAndDedupe(executablesToInstall);\n", " await fs.promises.mkdir(registryDirectory, { recursive: true });\n", " const lockfilePath = path.join(registryDirectory, '__dirlock');\n", " const releaseLock = await lockfile.lock(registryDirectory, {\n", " retries: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " async install(executablesToInstall: Executable[]) {\n" ], "file_path": "src/utils/registry.ts", "type": "replace", "edit_start_line_idx": 530 }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const {t, checkScheme} = ChromeUtils.import('chrome://juggler/content/protocol/PrimitiveTypes.js'); // Protocol-specific types. const browserTypes = {}; browserTypes.TargetInfo = { type: t.Enum(['page']), targetId: t.String, browserContextId: t.Optional(t.String), // PageId of parent tab, if any. openerId: t.Optional(t.String), }; browserTypes.CookieOptions = { name: t.String, value: t.String, url: t.Optional(t.String), domain: t.Optional(t.String), path: t.Optional(t.String), secure: t.Optional(t.Boolean), httpOnly: t.Optional(t.Boolean), sameSite: t.Optional(t.Enum(['Strict', 'Lax', 'None'])), expires: t.Optional(t.Number), }; browserTypes.Cookie = { name: t.String, domain: t.String, path: t.String, value: t.String, expires: t.Number, size: t.Number, httpOnly: t.Boolean, secure: t.Boolean, session: t.Boolean, sameSite: t.Enum(['Strict', 'Lax', 'None']), }; browserTypes.Geolocation = { latitude: t.Number, longitude: t.Number, accuracy: t.Optional(t.Number), }; browserTypes.DownloadOptions = { behavior: t.Optional(t.Enum(['saveToDisk', 'cancel'])), downloadsDir: t.Optional(t.String), }; const pageTypes = {}; pageTypes.DOMPoint = { x: t.Number, y: t.Number, }; pageTypes.Rect = { x: t.Number, y: t.Number, width: t.Number, height: t.Number, }; pageTypes.Size = { width: t.Number, height: t.Number, }; pageTypes.Viewport = { viewportSize: pageTypes.Size, deviceScaleFactor: t.Optional(t.Number), }; pageTypes.DOMQuad = { p1: pageTypes.DOMPoint, p2: pageTypes.DOMPoint, p3: pageTypes.DOMPoint, p4: pageTypes.DOMPoint, }; pageTypes.TouchPoint = { x: t.Number, y: t.Number, radiusX: t.Optional(t.Number), radiusY: t.Optional(t.Number), rotationAngle: t.Optional(t.Number), force: t.Optional(t.Number), }; pageTypes.Clip = { x: t.Number, y: t.Number, width: t.Number, height: t.Number, }; const runtimeTypes = {}; runtimeTypes.RemoteObject = { type: t.Optional(t.Enum(['object', 'function', 'undefined', 'string', 'number', 'boolean', 'symbol', 'bigint'])), subtype: t.Optional(t.Enum(['array', 'null', 'node', 'regexp', 'date', 'map', 'set', 'weakmap', 'weakset', 'error', 'proxy', 'promise', 'typedarray'])), objectId: t.Optional(t.String), unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])), value: t.Any }; runtimeTypes.ObjectProperty = { name: t.String, value: runtimeTypes.RemoteObject, }; runtimeTypes.ScriptLocation = { columnNumber: t.Number, lineNumber: t.Number, url: t.String, }; runtimeTypes.ExceptionDetails = { text: t.Optional(t.String), stack: t.Optional(t.String), value: t.Optional(t.Any), }; runtimeTypes.CallFunctionArgument = { objectId: t.Optional(t.String), unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])), value: t.Any, }; runtimeTypes.AuxData = { frameId: t.Optional(t.String), name: t.Optional(t.String), }; const axTypes = {}; axTypes.AXTree = { role: t.String, name: t.String, children: t.Optional(t.Array(t.Recursive(axTypes, 'AXTree'))), selected: t.Optional(t.Boolean), focused: t.Optional(t.Boolean), pressed: t.Optional(t.Boolean), focusable: t.Optional(t.Boolean), haspopup: t.Optional(t.Boolean), required: t.Optional(t.Boolean), invalid: t.Optional(t.Boolean), modal: t.Optional(t.Boolean), editable: t.Optional(t.Boolean), busy: t.Optional(t.Boolean), multiline: t.Optional(t.Boolean), readonly: t.Optional(t.Boolean), checked: t.Optional(t.Enum(['mixed', true])), expanded: t.Optional(t.Boolean), disabled: t.Optional(t.Boolean), multiselectable: t.Optional(t.Boolean), value: t.Optional(t.String), description: t.Optional(t.String), roledescription: t.Optional(t.String), valuetext: t.Optional(t.String), orientation: t.Optional(t.String), autocomplete: t.Optional(t.String), keyshortcuts: t.Optional(t.String), level: t.Optional(t.Number), tag: t.Optional(t.String), foundObject: t.Optional(t.Boolean), } const networkTypes = {}; networkTypes.HTTPHeader = { name: t.String, value: t.String, }; networkTypes.HTTPCredentials = { username: t.String, password: t.String, }; networkTypes.SecurityDetails = { protocol: t.String, subjectName: t.String, issuer: t.String, validFrom: t.Number, validTo: t.Number, }; networkTypes.ResourceTiming = { startTime: t.Number, domainLookupStart: t.Number, domainLookupEnd: t.Number, connectStart: t.Number, secureConnectionStart: t.Number, connectEnd: t.Number, requestStart: t.Number, responseStart: t.Number, }; networkTypes.InterceptedResponse = { status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), }; const Browser = { targets: ['browser'], types: browserTypes, events: { 'attachedToTarget': { sessionId: t.String, targetInfo: browserTypes.TargetInfo, }, 'detachedFromTarget': { sessionId: t.String, targetId: t.String, }, 'downloadCreated': { uuid: t.String, browserContextId: t.Optional(t.String), pageTargetId: t.String, url: t.String, suggestedFileName: t.String, }, 'downloadFinished': { uuid: t.String, canceled: t.Optional(t.Boolean), error: t.Optional(t.String), }, 'videoRecordingFinished': { screencastId: t.String, }, }, methods: { 'enable': { params: { attachToDefaultContext: t.Boolean, }, }, 'createBrowserContext': { params: { removeOnDetach: t.Optional(t.Boolean), }, returns: { browserContextId: t.String, }, }, 'removeBrowserContext': { params: { browserContextId: t.String, }, }, 'newPage': { params: { browserContextId: t.Optional(t.String), }, returns: { targetId: t.String, } }, 'close': {}, 'getInfo': { returns: { userAgent: t.String, version: t.String, }, }, 'setExtraHTTPHeaders': { params: { browserContextId: t.Optional(t.String), headers: t.Array(networkTypes.HTTPHeader), }, }, 'setBrowserProxy': { params: { type: t.Enum(['http', 'https', 'socks', 'socks4']), bypass: t.Array(t.String), host: t.String, port: t.Number, username: t.Optional(t.String), password: t.Optional(t.String), }, }, 'setContextProxy': { params: { browserContextId: t.Optional(t.String), type: t.Enum(['http', 'https', 'socks', 'socks4']), bypass: t.Array(t.String), host: t.String, port: t.Number, username: t.Optional(t.String), password: t.Optional(t.String), }, }, 'setHTTPCredentials': { params: { browserContextId: t.Optional(t.String), credentials: t.Nullable(networkTypes.HTTPCredentials), }, }, 'setRequestInterception': { params: { browserContextId: t.Optional(t.String), enabled: t.Boolean, }, }, 'setGeolocationOverride': { params: { browserContextId: t.Optional(t.String), geolocation: t.Nullable(browserTypes.Geolocation), } }, 'setUserAgentOverride': { params: { browserContextId: t.Optional(t.String), userAgent: t.Nullable(t.String), } }, 'setPlatformOverride': { params: { browserContextId: t.Optional(t.String), platform: t.Nullable(t.String), } }, 'setBypassCSP': { params: { browserContextId: t.Optional(t.String), bypassCSP: t.Nullable(t.Boolean), } }, 'setIgnoreHTTPSErrors': { params: { browserContextId: t.Optional(t.String), ignoreHTTPSErrors: t.Nullable(t.Boolean), } }, 'setJavaScriptDisabled': { params: { browserContextId: t.Optional(t.String), javaScriptDisabled: t.Boolean, } }, 'setLocaleOverride': { params: { browserContextId: t.Optional(t.String), locale: t.Nullable(t.String), } }, 'setTimezoneOverride': { params: { browserContextId: t.Optional(t.String), timezoneId: t.Nullable(t.String), } }, 'setDownloadOptions': { params: { browserContextId: t.Optional(t.String), downloadOptions: t.Nullable(browserTypes.DownloadOptions), } }, 'setTouchOverride': { params: { browserContextId: t.Optional(t.String), hasTouch: t.Nullable(t.Boolean), } }, 'setDefaultViewport': { params: { browserContextId: t.Optional(t.String), viewport: t.Nullable(pageTypes.Viewport), } }, 'setScrollbarsHidden': { params: { browserContextId: t.Optional(t.String), hidden: t.Boolean, } }, 'addScriptToEvaluateOnNewDocument': { params: { browserContextId: t.Optional(t.String), script: t.String, } }, 'addBinding': { params: { browserContextId: t.Optional(t.String), worldName: t.Optional(t.String), name: t.String, script: t.String, }, }, 'grantPermissions': { params: { origin: t.String, browserContextId: t.Optional(t.String), permissions: t.Array(t.String), }, }, 'resetPermissions': { params: { browserContextId: t.Optional(t.String), } }, 'setCookies': { params: { browserContextId: t.Optional(t.String), cookies: t.Array(browserTypes.CookieOptions), } }, 'clearCookies': { params: { browserContextId: t.Optional(t.String), } }, 'getCookies': { params: { browserContextId: t.Optional(t.String) }, returns: { cookies: t.Array(browserTypes.Cookie), }, }, 'setOnlineOverride': { params: { browserContextId: t.Optional(t.String), override: t.Nullable(t.Enum(['online', 'offline'])), } }, 'setColorScheme': { params: { browserContextId: t.Optional(t.String), colorScheme: t.Nullable(t.Enum(['dark', 'light', 'no-preference'])), }, }, 'setReducedMotion': { params: { browserContextId: t.Optional(t.String), reducedMotion: t.Nullable(t.Enum(['reduce', 'no-preference'])), }, }, 'setForcedColors': { params: { browserContextId: t.Optional(t.String), forcedColors: t.Nullable(t.Enum(['active', 'none'])), }, }, 'setVideoRecordingOptions': { params: { browserContextId: t.Optional(t.String), options: t.Optional({ dir: t.String, width: t.Number, height: t.Number, }), }, }, 'cancelDownload': { params: { uuid: t.Optional(t.String), } } }, }; const Network = { targets: ['page'], types: networkTypes, events: { 'requestWillBeSent': { // frameId may be absent for redirected requests. frameId: t.Optional(t.String), requestId: t.String, // RequestID of redirected request. redirectedFrom: t.Optional(t.String), postData: t.Optional(t.String), headers: t.Array(networkTypes.HTTPHeader), isIntercepted: t.Boolean, url: t.String, method: t.String, navigationId: t.Optional(t.String), cause: t.String, internalCause: t.String, }, 'responseReceived': { securityDetails: t.Nullable(networkTypes.SecurityDetails), requestId: t.String, fromCache: t.Boolean, remoteIPAddress: t.Optional(t.String), remotePort: t.Optional(t.Number), status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), timing: networkTypes.ResourceTiming, }, 'requestFinished': { requestId: t.String, responseEndTime: t.Number, transferSize: t.Number, encodedBodySize: t.Number, protocolVersion: t.String, }, 'requestFailed': { requestId: t.String, errorCode: t.String, }, }, methods: { 'setRequestInterception': { params: { enabled: t.Boolean, }, }, 'setExtraHTTPHeaders': { params: { headers: t.Array(networkTypes.HTTPHeader), }, }, 'abortInterceptedRequest': { params: { requestId: t.String, errorCode: t.String, }, }, 'resumeInterceptedRequest': { params: { requestId: t.String, url: t.Optional(t.String), method: t.Optional(t.String), headers: t.Optional(t.Array(networkTypes.HTTPHeader)), postData: t.Optional(t.String), interceptResponse: t.Optional(t.Boolean), }, returns: { response: t.Optional(networkTypes.InterceptedResponse), error: t.Optional(t.String), }, }, 'fulfillInterceptedRequest': { params: { requestId: t.String, status: t.Number, statusText: t.String, headers: t.Array(networkTypes.HTTPHeader), base64body: t.Optional(t.String), // base64-encoded }, }, 'getResponseBody': { params: { requestId: t.String, }, returns: { base64body: t.String, evicted: t.Optional(t.Boolean), }, }, }, }; const Runtime = { targets: ['page'], types: runtimeTypes, events: { 'executionContextCreated': { executionContextId: t.String, auxData: runtimeTypes.AuxData, }, 'executionContextDestroyed': { executionContextId: t.String, }, 'console': { executionContextId: t.String, args: t.Array(runtimeTypes.RemoteObject), type: t.String, location: runtimeTypes.ScriptLocation, }, }, methods: { 'evaluate': { params: { // Pass frameId here. executionContextId: t.String, expression: t.String, returnByValue: t.Optional(t.Boolean), }, returns: { result: t.Optional(runtimeTypes.RemoteObject), exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails), } }, 'callFunction': { params: { // Pass frameId here. executionContextId: t.String, functionDeclaration: t.String, returnByValue: t.Optional(t.Boolean), args: t.Array(runtimeTypes.CallFunctionArgument), }, returns: { result: t.Optional(runtimeTypes.RemoteObject), exceptionDetails: t.Optional(runtimeTypes.ExceptionDetails), } }, 'disposeObject': { params: { executionContextId: t.String, objectId: t.String, }, }, 'getObjectProperties': { params: { executionContextId: t.String, objectId: t.String, }, returns: { properties: t.Array(runtimeTypes.ObjectProperty), } }, }, }; const Page = { targets: ['page'], types: pageTypes, events: { 'ready': { }, 'crashed': { }, 'eventFired': { frameId: t.String, name: t.Enum(['load', 'DOMContentLoaded']), }, 'uncaughtError': { frameId: t.String, message: t.String, stack: t.String, }, 'frameAttached': { frameId: t.String, parentFrameId: t.Optional(t.String), }, 'frameDetached': { frameId: t.String, }, 'navigationStarted': { frameId: t.String, navigationId: t.String, url: t.String, }, 'navigationCommitted': { frameId: t.String, // |navigationId| can only be null in response to enable. navigationId: t.Optional(t.String), url: t.String, // frame.id or frame.name name: t.String, }, 'navigationAborted': { frameId: t.String, navigationId: t.String, errorText: t.String, }, 'sameDocumentNavigation': { frameId: t.String, url: t.String, }, 'dialogOpened': { dialogId: t.String, type: t.Enum(['prompt', 'alert', 'confirm', 'beforeunload']), message: t.String, defaultValue: t.Optional(t.String), }, 'dialogClosed': { dialogId: t.String, }, 'bindingCalled': { executionContextId: t.String, name: t.String, payload: t.Any, }, 'linkClicked': { phase: t.Enum(['before', 'after']), }, 'willOpenNewWindowAsynchronously': {}, 'fileChooserOpened': { executionContextId: t.String, element: runtimeTypes.RemoteObject }, 'workerCreated': { workerId: t.String, frameId: t.String, url: t.String, }, 'workerDestroyed': { workerId: t.String, }, 'dispatchMessageFromWorker': { workerId: t.String, message: t.String, }, 'videoRecordingStarted': { screencastId: t.String, file: t.String, }, 'webSocketCreated': { frameId: t.String, wsid: t.String, requestURL: t.String, }, 'webSocketOpened': { frameId: t.String, requestId: t.String, wsid: t.String, effectiveURL: t.String, }, 'webSocketClosed': { frameId: t.String, wsid: t.String, error: t.String, }, 'webSocketFrameSent': { frameId: t.String, wsid: t.String, opcode: t.Number, data: t.String, }, 'webSocketFrameReceived': { frameId: t.String, wsid: t.String, opcode: t.Number, data: t.String, }, 'screencastFrame': { data: t.String, deviceWidth: t.Number, deviceHeight: t.Number, }, }, methods: { 'close': { params: { runBeforeUnload: t.Optional(t.Boolean), }, }, 'setFileInputFiles': { params: { frameId: t.String, objectId: t.String, files: t.Array(t.String), }, }, 'addBinding': { params: { worldName: t.Optional(t.String), name: t.String, script: t.String, }, }, 'setViewportSize': { params: { viewportSize: t.Nullable(pageTypes.Size), }, }, 'bringToFront': { params: { }, }, 'setEmulatedMedia': { params: { type: t.Optional(t.Enum(['screen', 'print', ''])), colorScheme: t.Optional(t.Enum(['dark', 'light', 'no-preference'])), reducedMotion: t.Optional(t.Enum(['reduce', 'no-preference'])), forcedColors: t.Optional(t.Enum(['active', 'none'])), }, }, 'setCacheDisabled': { params: { cacheDisabled: t.Boolean, }, }, 'describeNode': { params: { frameId: t.String, objectId: t.String, }, returns: { contentFrameId: t.Optional(t.String), ownerFrameId: t.Optional(t.String), }, }, 'scrollIntoViewIfNeeded': { params: { frameId: t.String, objectId: t.String, rect: t.Optional(pageTypes.Rect), }, }, 'addScriptToEvaluateOnNewDocument': { params: { script: t.String, worldName: t.Optional(t.String), } }, 'navigate': { params: { frameId: t.String, url: t.String, referer: t.Optional(t.String), }, returns: { navigationId: t.Nullable(t.String), navigationURL: t.Nullable(t.String), } }, 'goBack': { params: { frameId: t.String, }, returns: { success: t.Boolean, }, }, 'goForward': { params: { frameId: t.String, }, returns: { success: t.Boolean, }, }, 'reload': { params: { frameId: t.String, }, }, 'adoptNode': { params: { frameId: t.String, objectId: t.String, executionContextId: t.String, }, returns: { remoteObject: t.Nullable(runtimeTypes.RemoteObject), }, }, 'screenshot': { params: { mimeType: t.Enum(['image/png', 'image/jpeg']), clip: t.Optional(pageTypes.Clip), omitDeviceScaleFactor: t.Optional(t.Boolean), }, returns: { data: t.String, } }, 'getContentQuads': { params: { frameId: t.String, objectId: t.String, }, returns: { quads: t.Array(pageTypes.DOMQuad), }, }, 'dispatchKeyEvent': { params: { type: t.String, key: t.String, keyCode: t.Number, location: t.Number, code: t.String, repeat: t.Boolean, text: t.Optional(t.String), } }, 'dispatchTouchEvent': { params: { type: t.Enum(['touchStart', 'touchEnd', 'touchMove', 'touchCancel']), touchPoints: t.Array(pageTypes.TouchPoint), modifiers: t.Number, }, returns: { defaultPrevented: t.Boolean, } }, 'dispatchTapEvent': { params: { x: t.Number, y: t.Number, modifiers: t.Number, } }, 'dispatchMouseEvent': { params: { type: t.String, button: t.Number, x: t.Number, y: t.Number, modifiers: t.Number, clickCount: t.Optional(t.Number), buttons: t.Number, } }, 'dispatchWheelEvent': { params: { x: t.Number, y: t.Number, deltaX: t.Number, deltaY: t.Number, deltaZ: t.Number, modifiers: t.Number, } }, 'insertText': { params: { text: t.String, } }, 'crash': { params: {} }, 'handleDialog': { params: { dialogId: t.String, accept: t.Boolean, promptText: t.Optional(t.String), }, }, 'setInterceptFileChooserDialog': { params: { enabled: t.Boolean, }, }, 'sendMessageToWorker': { params: { frameId: t.String, workerId: t.String, message: t.String, }, }, 'startScreencast': { params: { width: t.Number, height: t.Number, quality: t.Number, }, returns: { screencastId: t.String, }, }, 'screencastFrameAck': { params: { screencastId: t.String, }, }, 'stopScreencast': { }, }, }; const Accessibility = { targets: ['page'], types: axTypes, events: {}, methods: { 'getFullAXTree': { params: { objectId: t.Optional(t.String), }, returns: { tree: axTypes.AXTree }, } } } this.protocol = { domains: {Browser, Page, Runtime, Network, Accessibility}, }; this.checkScheme = checkScheme; this.EXPORTED_SYMBOLS = ['protocol', 'checkScheme'];
browser_patches/firefox-beta/juggler/protocol/Protocol.js
0
https://github.com/microsoft/playwright/commit/c673ef5330677c516a618a8a806a4ae23d325b9d
[ 0.00017697415023576468, 0.00017350283451378345, 0.00016284429875668138, 0.00017388536070939153, 0.0000022525798613060033 ]