text
stringlengths 1
2.83M
| id
stringlengths 16
152
| metadata
dict | __index_level_0__
int64 0
949
|
---|---|---|---|
import { expect } from '../../../../../node_modules/@esm-bundle/chai/esm/chai.js';
it('bad predicate', function() {
const fixture = { x: 'x' }
fixture.circle = fixture;
expect(fixture).to.equal(null);
})
| modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-circular-error.test.js/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/test-failure/browser-tests/fail-circular-error.test.js",
"repo_id": "modernweb-dev",
"token_count": 77
} | 200 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
export * from './dist/index.js';
| modernweb-dev/web/packages/browser-logs/index.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/browser-logs/index.d.ts",
"repo_id": "modernweb-dev",
"token_count": 34
} | 201 |
{
"name": "@web/config-loader",
"version": "0.3.1",
"publishConfig": {
"access": "public"
},
"description": "Load a esm or cjs config from the file system",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/modernweb-dev/web.git",
"directory": "packages/config-loader"
},
"author": "modern-web",
"homepage": "https://github.com/modernweb-dev/web/tree/master/packages/config-loader",
"main": "src/index.js",
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"build": "tsc",
"test:node": "mocha test/**/*.test.js --reporter dot",
"test:watch": "mocha test/**/*.test.js --watch --watch-files .,src,test --reporter dot"
},
"files": [
"*.d.ts",
"*.js",
"*.mjs",
"dist",
"src"
],
"keywords": [
"web",
"node",
"config",
"loader",
"esm",
"es module"
],
"dependencies": {},
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"require": "./src/index.js"
}
}
}
| modernweb-dev/web/packages/config-loader/package.json/0 | {
"file_path": "modernweb-dev/web/packages/config-loader/package.json",
"repo_id": "modernweb-dev",
"token_count": 491
} | 202 |
module.exports = { foo: 'bar' };
| modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/commonjs-in-.mjs/my-project.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/config-loader/test/fixtures/package-mjs/commonjs-in-.mjs/my-project.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 13
} | 203 |
<!DOCTYPE html>
<html>
<body>
<script type="module" src="./app.js"></script>
</body>
</html>
| modernweb-dev/web/packages/dev-server-core/demo/event-stream/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/demo/event-stream/index.html",
"repo_id": "modernweb-dev",
"token_count": 47
} | 204 |
/* eslint-disable */
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import { getAttribute, getAttributeIndex, getTextContent } from './util.js';
/**
* Match the text inside an element, textnode, or comment
*
* Note: nodeWalkAll with hasTextValue may return an textnode and its parent if
* the textnode is the only child in that parent.
*/
function hasTextValue(value: string): Predicate {
return function (node) {
return getTextContent(node) === value;
};
}
export type Predicate = (node: any) => boolean;
/**
* OR an array of predicates
*/
function OR(...predicates: Predicate[]): Predicate;
function OR(/* ...rules */): Predicate {
const rules = new Array<Predicate>(arguments.length);
for (let i = 0; i < arguments.length; i++) {
rules[i] = arguments[i];
}
return function (node) {
for (let i = 0; i < rules.length; i++) {
if (rules[i](node)) {
return true;
}
}
return false;
};
}
/**
* AND an array of predicates
*/
function AND(...predicates: Predicate[]): Predicate;
function AND(/* ...rules */): Predicate {
const rules = new Array<Predicate>(arguments.length);
for (let i = 0; i < arguments.length; i++) {
rules[i] = arguments[i];
}
return function (node) {
for (let i = 0; i < rules.length; i++) {
if (!rules[i](node)) {
return false;
}
}
return true;
};
}
/**
* negate an individual predicate, or a group with AND or OR
*/
function NOT(predicateFn: Predicate): Predicate {
return function (node) {
return !predicateFn(node);
};
}
/**
* Returns a predicate that matches any node with a parent matching
* `predicateFn`.
*/
function parentMatches(predicateFn: Predicate): Predicate {
return function (node) {
let parent = node.parentNode;
while (parent !== undefined) {
if (predicateFn(parent)) {
return true;
}
parent = parent.parentNode;
}
return false;
};
}
function hasAttr(attr: string): Predicate {
return function (node) {
return getAttributeIndex(node, attr) > -1;
};
}
function hasAttrValue(attr: string, value: string): Predicate {
return function (node) {
return getAttribute(node, attr) === value;
};
}
function hasClass(name: string): Predicate {
return hasSpaceSeparatedAttrValue('class', name);
}
function hasTagName(name: string): Predicate {
const n = name.toLowerCase();
return function (node) {
if (!node.tagName) {
return false;
}
return node.tagName.toLowerCase() === n;
};
}
/**
* Returns true if `regex.match(tagName)` finds a match.
*
* This will use the lowercased tagName for comparison.
*/
function hasMatchingTagName(regex: RegExp): Predicate {
return function (node) {
if (!node.tagName) {
return false;
}
return regex.test(node.tagName.toLowerCase());
};
}
export function hasSpaceSeparatedAttrValue(name: string, value: string): Predicate {
return function (element: any) {
const attributeValue = getAttribute(element, name);
if (typeof attributeValue !== 'string') {
return false;
}
return attributeValue.split(' ').indexOf(value) !== -1;
};
}
export function isDocument(node: any): boolean {
return node.nodeName === '#document';
}
export function isDocumentFragment(node: any): boolean {
return node.nodeName === '#document-fragment';
}
export function isElement(node: any): boolean {
return node.nodeName === node.tagName;
}
export function isTextNode(node: any): boolean {
return node.nodeName === '#text';
}
export function isCommentNode(node: any): boolean {
return node.nodeName === '#comment';
}
export const predicates = {
hasClass: hasClass,
hasAttr: hasAttr,
hasAttrValue: hasAttrValue,
hasMatchingTagName: hasMatchingTagName,
hasSpaceSeparatedAttrValue: hasSpaceSeparatedAttrValue,
hasTagName: hasTagName,
hasTextValue: hasTextValue,
AND: AND,
OR: OR,
NOT: NOT,
parentMatches: parentMatches,
};
| modernweb-dev/web/packages/dev-server-core/src/dom5/predicates.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/dom5/predicates.ts",
"repo_id": "modernweb-dev",
"token_count": 1519
} | 205 |
import { Middleware } from 'koa';
import { FSWatcher } from 'chokidar';
import fs from 'fs';
import { getRequestFilePath } from '../utils.js';
/**
* Sets up a middleware which tracks served files and sends a reload message to any
* active browsers when any of the files change.
*/
export function watchServedFilesMiddleware(fileWatcher: FSWatcher, rootDir: string): Middleware {
return async (ctx, next) => {
await next();
if (ctx.response.status !== 404) {
let filePath = getRequestFilePath(ctx.url, rootDir);
// if the request ends with a / it might be an index.html, check if it exists
// and watch it
if (filePath.endsWith('/')) {
filePath += 'index.html';
}
// watch file if it exists
fs.stat(filePath, (err, stats) => {
if (!err && !stats.isDirectory()) {
fileWatcher.add(filePath);
}
});
}
};
}
| modernweb-dev/web/packages/dev-server-core/src/middleware/watchServedFilesMiddleware.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/middleware/watchServedFilesMiddleware.ts",
"repo_id": "modernweb-dev",
"token_count": 337
} | 206 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/test-helpers.js';
const {
virtualFilesPlugin,
createTestServer,
timeout,
fetchText,
expectIncludes,
expectNotIncludes,
} = cjsEntrypoint;
export {
virtualFilesPlugin,
createTestServer,
timeout,
fetchText,
expectIncludes,
expectNotIncludes,
};
| modernweb-dev/web/packages/dev-server-core/test-helpers.mjs/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/test-helpers.mjs",
"repo_id": "modernweb-dev",
"token_count": 122
} | 207 |
import { expect } from 'chai';
import { createTestServer } from '../helpers.js';
describe('plugin-mime-type middleware', () => {
it('can set the mime type of a file with a string', async () => {
const { host, server } = await createTestServer({
plugins: [
{
name: 'test',
resolveMimeType(ctx) {
if (ctx.path === '/src/hello-world.txt') {
return 'js';
}
},
},
],
});
try {
const response = await fetch(`${host}/src/hello-world.txt`);
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.include('application/javascript');
} finally {
server.stop();
}
});
it('can set the mime type of a file with an object', async () => {
const { host, server } = await createTestServer({
plugins: [
{
name: 'test',
resolveMimeType(ctx) {
if (ctx.path === '/src/hello-world.txt') {
return { type: 'js' };
}
},
},
],
});
try {
const response = await fetch(`${host}/src/hello-world.txt`);
expect(response.status).to.equal(200);
expect(response.headers.get('content-type')).to.include('application/javascript');
} finally {
server.stop();
}
});
});
| modernweb-dev/web/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/test/middleware/pluginMimeTypeMiddleware.test.ts",
"repo_id": "modernweb-dev",
"token_count": 611
} | 208 |
import { expect } from 'chai';
import { browsers } from '@mdn/browser-compat-data';
import { isLatestModernBrowser, getLatestStableMajor } from '../src/browser-targets.js';
describe('isLatestModernBrowser', () => {
it('returns true for latest Chrome', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest) })).to.be.true;
});
it('returns true for latest Chrome -1', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 1) })).to.be.true;
});
it('returns true for future version of Chrome', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest + 1) })).to.be.true;
});
it('returns true for unknown version of Chrome', async () => {
expect(isLatestModernBrowser({ name: 'Chrome', version: '9999999' })).to.be.true;
});
it('returns false for latest Chrome -2', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) })).to.be.false;
});
it('returns false for latest Chrome -3', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 3) })).to.be.false;
});
it('returns true for latest Chrome Headless', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome Headless', version: String(latest) })).to.be.true;
});
it('returns true for latest chromium', async () => {
const latest = getLatestStableMajor(browsers.chrome.releases)!;
expect(isLatestModernBrowser({ name: 'Chromium', version: String(latest) })).to.be.true;
});
it('returns true for latest Firefox', async () => {
const latest = getLatestStableMajor(browsers.firefox.releases)!;
expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest) })).to.be.true;
});
it('returns false for latest Firefox -1', async () => {
const latest = getLatestStableMajor(browsers.firefox.releases)!;
expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 1) })).to.be.false;
});
it('returns false for latest Firefox -2', async () => {
const latest = getLatestStableMajor(browsers.firefox.releases)!;
expect(isLatestModernBrowser({ name: 'Firefox', version: String(latest - 2) })).to.be.false;
});
it('returns true for latest Edge', async () => {
const latest = getLatestStableMajor(browsers.edge.releases)!;
expect(isLatestModernBrowser({ name: 'Edge', version: String(latest) })).to.be.true;
});
it('returns true for latest Edge -1', async () => {
const latest = getLatestStableMajor(browsers.edge.releases)!;
expect(isLatestModernBrowser({ name: 'Edge', version: String(latest - 1) })).to.be.true;
});
it('returns false for latest Edge -2', async () => {
const latest = getLatestStableMajor(browsers.edge.releases)!;
expect(isLatestModernBrowser({ name: 'Chrome', version: String(latest - 2) })).to.be.false;
});
});
| modernweb-dev/web/packages/dev-server-esbuild/test/browser-targets.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-esbuild/test/browser-targets.test.ts",
"repo_id": "modernweb-dev",
"token_count": 1096
} | 209 |
import { webSocket, sendMessage } from '__WEBSOCKET_IMPORT__';
const modules = new Map();
const disposeTrigger = Symbol('trigger.dispose');
const acceptTrigger = Symbol('trigger.accept');
const disposeHandlers = Symbol('handlers.dispose');
const acceptHandlers = Symbol('handlers.accept');
const moduleState = Symbol('moduleState');
const HmrState = {
None: 0,
Declined: 1,
Accepted: 2,
};
export class HotModule {
constructor(id) {
this.id = id;
this.data = {};
this[disposeHandlers] = new Set();
this[acceptHandlers] = new Set();
this[moduleState] = HmrState.None;
}
acceptDeps(deps, callback) {
if (this[moduleState] === HmrState.Accepted) {
return;
}
sendMessage({ type: 'hmr:accept', id: this.id });
this[moduleState] = HmrState.Accepted;
this[acceptHandlers].add({
deps,
callback,
});
}
accept(callbackOrOptions, options) {
let callback;
if (typeof callbackOrOptions === 'function') {
callback = callbackOrOptions;
} else {
options = callbackOrOptions;
callback = () => {};
}
if (this[moduleState] === HmrState.Accepted) {
return;
}
sendMessage({ type: 'hmr:accept', id: this.id, options });
this[moduleState] = HmrState.Accepted;
this[acceptHandlers].add(callback);
}
dispose(handler) {
this[disposeHandlers].add(handler);
}
decline() {
this[moduleState] = HmrState.Declined;
}
invalidate() {
window.location.reload();
}
[disposeTrigger]() {
const handlers = this[disposeHandlers];
this.data = {};
this[disposeHandlers] = new Set();
for (const handler of handlers) {
handler();
}
}
async [acceptTrigger]() {
if (this[moduleState] === HmrState.Declined) {
return;
}
const time = Date.now();
const handlers = [...this[acceptHandlers]];
const results = await Promise.all(
handlers.map(handler => {
if (typeof handler === 'function') {
return Promise.all([Promise.resolve(handler), import(`${this.id}?m=${time}`)]);
}
return Promise.all([
Promise.resolve(handler.callback),
Promise.all(handler.deps.map(path => import(`${path}?m=${time}`))),
]);
}),
);
for (const [callback, modules] of results) {
if (callback) {
callback(modules);
}
}
}
}
export function create(url) {
const urlObj = new URL(url);
const path = urlObj.pathname;
const existing = modules.get(path);
if (existing) {
existing[disposeTrigger]();
return existing;
}
const instance = new HotModule(path);
modules.set(path, instance);
return instance;
}
webSocket.addEventListener('message', e => {
try {
const message = JSON.parse(e.data);
if (message.type === 'hmr:reload') {
window.location.reload();
} else if (message.type === 'hmr:update') {
const module = modules.get(message.url);
if (module) {
module[acceptTrigger]();
}
}
} catch (error) {
console.error('[hmr] Error while handling websocket message.');
console.error(error);
}
});
| modernweb-dev/web/packages/dev-server-hmr/scripts/hmrClientScript.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-hmr/scripts/hmrClientScript.js",
"repo_id": "modernweb-dev",
"token_count": 1226
} | 210 |
export function postData(endpoint, data) {
return fetch(`/api/${endpoint}`, { method: 'POST', body: JSON.stringify(data) });
}
export const __importMeta = import.meta;
| modernweb-dev/web/packages/dev-server-import-maps/test-browser/src/postData.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-import-maps/test-browser/src/postData.js",
"repo_id": "modernweb-dev",
"token_count": 56
} | 211 |
import moduleA from 'module-a';
console.log(moduleA);
| modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/basic/app.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/basic/app.js",
"repo_id": "modernweb-dev",
"token_count": 19
} | 212 |
export default 'c';
| modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-multi/src/foo/c.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-multi/src/foo/c.js",
"repo_id": "modernweb-dev",
"token_count": 6
} | 213 |
{
"name": "resolve-outside-dir-foo"
} | modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/resolve-outside-dir-foo/package.json/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/resolve-outside-dir-foo/package.json",
"repo_id": "modernweb-dev",
"token_count": 20
} | 214 |
declare module 'rollup-plugin-postcss' {
import { Plugin } from 'rollup';
export default function rollupPluginPostCss(options?: any): Plugin;
}
| modernweb-dev/web/packages/dev-server-rollup/types/rollup-plugin-postcss/index.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/types/rollup-plugin-postcss/index.d.ts",
"repo_id": "modernweb-dev",
"token_count": 45
} | 215 |
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
};
| modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/preview.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/demo/wc/.storybook/preview.js",
"repo_id": "modernweb-dev",
"token_count": 29
} | 216 |
// @ts-ignore
import { DevServerCoreConfig, getRequestFilePath, Plugin } from '@web/dev-server-core';
import { mdjsToCsf } from 'storybook-addon-markdown-docs';
import { StorybookPluginConfig } from '../shared/config/StorybookPluginConfig.js';
import { createManagerHtml } from '../shared/html/createManagerHtml.js';
import { createPreviewHtml } from '../shared/html/createPreviewHtml.js';
import { readStorybookConfig } from '../shared/config/readStorybookConfig.js';
import { validatePluginConfig } from '../shared/config/validatePluginConfig.js';
import { findStories } from '../shared/stories/findStories.js';
import { transformMdxToCsf } from '../shared/mdx/transformMdxToCsf.js';
import { injectExportsOrder } from '../shared/stories/injectExportsOrder.js';
const regexpReplaceWebsocket = /<!-- injected by web-dev-server -->(.|\s)*<\/script>/m;
interface Context {
URL: URL;
path: string;
body: unknown;
url: string;
}
export function storybookPlugin(pluginConfig: StorybookPluginConfig): Plugin {
validatePluginConfig(pluginConfig);
let serverConfig: DevServerCoreConfig;
let storyImports: string[] = [];
let storyFilePaths: string[] = [];
return {
name: 'storybook',
serverStart(args: { config: DevServerCoreConfig }) {
serverConfig = args.config;
},
resolveMimeType(context: Context) {
if (context.URL.searchParams.get('story') !== 'true') {
return;
}
if (context.path.endsWith('.mdx') || context.path.endsWith('.md')) {
return 'js';
}
},
async transform(context: Context) {
if (typeof context.body !== 'string') {
return;
}
if (context.path === '/') {
// replace the injected websocket script to avoid reloading the manager in watch mode
context.body = context.body.replace(regexpReplaceWebsocket, '');
return;
}
if (context.URL.searchParams.get('story') !== 'true') {
return;
}
const filePath = getRequestFilePath(context.url, serverConfig.rootDir);
if (context.path.endsWith('.mdx')) {
context.body = await transformMdxToCsf(context.body, filePath);
}
if (context.path.endsWith('.md')) {
context.body = await mdjsToCsf(context.body as string, filePath, pluginConfig.type);
}
if (storyFilePaths.includes(filePath)) {
// inject story order, note that MDX and MD and fall through to this as well
context.body = await injectExportsOrder(context.body as string, filePath);
}
},
async serve(context: Context) {
const storybookConfig = await readStorybookConfig(pluginConfig);
if (context.path === '/') {
return { type: 'html', body: createManagerHtml(storybookConfig, serverConfig.rootDir) };
}
if (context.path === '/iframe.html') {
({ storyImports, storyFilePaths } = await findStories(
serverConfig.rootDir,
storybookConfig.mainJsPath,
storybookConfig.mainJs.stories,
));
storyImports = storyImports.map(i => `${i}?story=true`);
return {
type: 'html',
body: createPreviewHtml(
pluginConfig,
storybookConfig,
serverConfig.rootDir,
storyImports,
),
};
}
},
};
}
| modernweb-dev/web/packages/dev-server-storybook/src/serve/storybookPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/src/serve/storybookPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 1288
} | 217 |
import { fileURLToPath } from 'url';
import { resolve } from 'path';
export default {
rootDir: resolve(fileURLToPath(import.meta.url), '..', '..', '..'),
appIndex: 'demo/base-path/index.html',
basePath: '/my-base-path',
};
| modernweb-dev/web/packages/dev-server/demo/base-path/config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/base-path/config.mjs",
"repo_id": "modernweb-dev",
"token_count": 84
} | 218 |
export default 'moduleFeaturesB';
| modernweb-dev/web/packages/dev-server/demo/syntax/module-features-b.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/syntax/module-features-b.js",
"repo_id": "modernweb-dev",
"token_count": 8
} | 219 |
export { RollupNodeResolveOptions } from '@web/dev-server-rollup';
export { startDevServer } from './startDevServer.js';
export { mergeConfigs } from './config/mergeConfigs.js';
export { DevServerStartError } from './DevServerStartError.js';
export { esbuildPlugin } from './plugins/esbuildPlugin.js';
export { nodeResolvePlugin } from './plugins/nodeResolvePlugin.js';
import type { DevServerConfig as FullDevServerConfig } from './config/DevServerConfig.js';
export type DevServerConfig = Partial<FullDevServerConfig>;
| modernweb-dev/web/packages/dev-server/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 153
} | 220 |
// @ts-nocheck
import { LitElement, html } from 'lit';
class MyElement extends LitElement {
static properties = {
transactions: { type: Array },
state: { type: String },
}
async connectedCallback() {
super.connectedCallback();
this.state = 'PENDING';
try {
this.transactions = await fetch('/api/transactions').then(r => r.json()).then(({ transactions }) => transactions);
this.state = 'SUCCESS'
} catch {
this.state = 'ERROR';
}
}
render() {
switch (this.state) {
case 'PENDING':
return html`<p>Loading...</p>`;
case 'ERROR':
return html`<p>Something went wrong</p>`;
case 'SUCCESS':
return html`
<ul>
${this.transactions.map(t => html`<li>${t}</li>`)}
</ul>
`;
}
}
}
customElements.define('my-element', MyElement);
| modernweb-dev/web/packages/mocks/demo/wc/src/MyFeature.js/0 | {
"file_path": "modernweb-dev/web/packages/mocks/demo/wc/src/MyFeature.js",
"repo_id": "modernweb-dev",
"token_count": 376
} | 221 |
import { http } from '../http.js';
import { expect } from '@esm-bundle/chai';
import { registerMockRoutes } from '../browser.js';
it('mocks a request', async () => {
registerMockRoutes(http.get('/api/foo', () => Response.json({ foo: 'foo' })));
const { foo } = await fetch('/api/foo').then(r => r.json());
expect(foo).to.equal('foo');
});
it('overrides a previous handler', async () => {
registerMockRoutes(http.get('/api/foo', () => Response.json({ foo: 'bar' })));
const { foo } = await fetch('/api/foo').then(r => r.json());
expect(foo).to.equal('bar');
});
| modernweb-dev/web/packages/mocks/test-browser/mocks.test.js/0 | {
"file_path": "modernweb-dev/web/packages/mocks/test-browser/mocks.test.js",
"repo_id": "modernweb-dev",
"token_count": 211
} | 222 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const {
createPolyfillsData,
createPolyfillsLoader,
injectPolyfillsLoader,
hasFileOfType,
fileTypes,
getScriptFileType,
} = cjsEntrypoint;
export {
createPolyfillsData,
createPolyfillsLoader,
injectPolyfillsLoader,
hasFileOfType,
fileTypes,
getScriptFileType,
};
| modernweb-dev/web/packages/polyfills-loader/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 141
} | 223 |
<html><head></head><body><div>before</div>
<script type="module" src="./app.js"></script>
<div>after</div>
<script>(function () {
function loadScript(src, type, attributes) {
return new Promise(function (resolve) {
var script = document.createElement('script');
script.fetchPriority = 'high';
function onLoaded() {
if (script.parentElement) {
script.parentElement.removeChild(script);
}
resolve();
}
script.src = src;
script.onload = onLoaded;
if (attributes) {
attributes.forEach(function (att) {
script.setAttribute(att.name, att.value);
});
}
script.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + src + ' check the network tab for HTTP status.');
onLoaded();
};
if (type) script.type = type;
document.head.appendChild(script);
});
}
var polyfills = [];
if (!('fetch' in window)) {
polyfills.push(loadScript('./polyfills/fetch.js'));
}
if (!('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype)) {
polyfills.push(loadScript('./polyfills/intersection-observer.js'));
}
if (!('attachShadow' in Element.prototype) || !('getRootNode' in Element.prototype) || window.ShadyDOM && window.ShadyDOM.force) {
polyfills.push(loadScript('./polyfills/webcomponents.js'));
}
if (!('noModule' in HTMLScriptElement.prototype) && 'getRootNode' in Element.prototype) {
polyfills.push(loadScript('./polyfills/custom-elements-es5-adapter.js'));
}
function loadFiles() {
loadScript('./app.js', 'module', []);
}
if (polyfills.length) {
Promise.all(polyfills).then(loadFiles);
} else {
loadFiles();
}
})();</script></body></html> | modernweb-dev/web/packages/polyfills-loader/test/snapshots/injectPolyfillsLoader/module-and-polyfills.html/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/test/snapshots/injectPolyfillsLoader/module-and-polyfills.html",
"repo_id": "modernweb-dev",
"token_count": 733
} | 224 |
<h1>Page B</h1>
<ul>
<li>
<a href="/">Index</a>
</li>
<li>
<a href="/pages/page-a.html">A</a>
</li>
<li>
<a href="/pages/page-B.html">B</a>
</li>
<li>
<a href="/pages/page-C.html">C</a>
</li>
</ul>
<script type="module" src="./page-b.js"></script>
<script type="module">
console.log('inline');
</script>
| modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-b.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/mpa/pages/page-b.html",
"repo_id": "modernweb-dev",
"token_count": 171
} | 225 |
import { OutputChunk, OutputOptions, OutputBundle } from 'rollup';
import { Attribute } from 'parse5';
export interface InputHTMLOptions {
/** The html source code. If set, overwrites path. */
html?: string;
/** Name of the HTML files when using the html option. */
name?: string;
/** Path to the HTML file, or glob to multiple HTML files. */
path?: string;
}
export interface RollupPluginHTMLOptions {
/** HTML file(s) to use as input. If not set, uses rollup input option. */
input?: string | InputHTMLOptions | (string | InputHTMLOptions)[];
/** HTML file glob pattern or patterns to ignore */
exclude?: string | string[];
/** Whether to minify the output HTML. */
minify?: boolean;
/** Whether to preserve or flatten the directory structure of the HTML file. */
flattenOutput?: boolean;
/** Directory to resolve absolute paths relative to, and to use as base for non-flatted filename output. */
rootDir?: string;
/** Path to load modules and assets from at runtime. */
publicPath?: string;
/** Transform asset source before output. */
transformAsset?: TransformAssetFunction | TransformAssetFunction[];
/** Transform HTML file before output. */
transformHtml?: TransformHtmlFunction | TransformHtmlFunction[];
/** Whether to extract and bundle assets referenced in HTML. Defaults to true. */
extractAssets?: boolean;
/** Whether to ignore assets referenced in HTML and CSS with glob patterns. */
externalAssets?: string | string[];
/** Define a full absolute url to your site (e.g. https://domain.com) */
absoluteBaseUrl?: string;
/** Whether to set full absolute urls for ['meta[property=og:image]', 'link[rel=canonical]', 'meta[property=og:url]'] or not. Requires a absoluteBaseUrl to be set. Default to true. */
absoluteSocialMediaUrls?: boolean;
/** Should a service worker registration script be injected. Defaults to false. */
injectServiceWorker?: boolean;
/** File system path to the generated service worker file */
serviceWorkerPath?: string;
/** Prefix to strip from absolute paths when resolving assets and scripts, for example when using a base path that does not exist on disk. */
absolutePathPrefix?: string;
/** When set to true, will insert meta tags for CSP and add script-src values for inline scripts by sha256-hashing the contents */
strictCSPInlineScripts?: boolean;
/** Bundle assets reference from CSS via `url` */
bundleAssetsFromCss?: boolean;
}
export interface GeneratedBundle {
name: string;
options: OutputOptions;
bundle: OutputBundle;
}
export interface ScriptModuleTag {
importPath: string;
attributes?: Attribute[];
code?: string;
}
export interface EntrypointBundle extends GeneratedBundle {
entrypoints: {
// path to import the entrypoint, can be used in an import statement
// or script tag directly
importPath: string;
// associated rollup chunk, useful if you need to get more information
// about the chunk. See the rollup docs for type definitions
chunk: OutputChunk;
attributes?: Attribute[];
}[];
}
export interface TransformHtmlArgs {
// the rollup bundle to be injected on the page. if there are multiple
// rollup output options, this will reference the first bundle
//
// if one of the input options was set, only the bundled module script contained
// in the HTML input are available to be injected in both the bundle and bundles
// options
bundle: EntrypointBundle;
// the rollup bundles to be injected on the page. if there is only one
// build output options, this will be an array with one option
bundles: Record<string, EntrypointBundle>;
htmlFileName: string;
}
export type TransformHtmlFunction = (
html: string,
args: TransformHtmlArgs,
) => string | Promise<string>;
export type TransformAssetFunction = (
content: Buffer,
filePath: string,
) => string | Buffer | Promise<string | Buffer>;
| modernweb-dev/web/packages/rollup-plugin-html/src/RollupPluginHTMLOptions.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/RollupPluginHTMLOptions.ts",
"repo_id": "modernweb-dev",
"token_count": 1047
} | 226 |
import { Document, Attribute } from 'parse5';
import { createScript, findElement, getTagName, appendChild } from '@web/parse5-utils';
import { EntrypointBundle } from '../RollupPluginHTMLOptions.js';
import { createError } from '../utils.js';
export function createLoadScript(src: string, format: string, attributes?: Attribute[]) {
const attributesObject: Record<string, string> = {};
if (attributes) {
for (const attribute of attributes) {
attributesObject[attribute.name] = attribute.value;
}
}
if (['es', 'esm', 'module'].includes(format)) {
return createScript({ type: 'module', src, ...attributesObject });
}
if (['system', 'systemjs'].includes(format)) {
return createScript({}, `System.import(${JSON.stringify(src)});`);
}
return createScript({ src, defer: '' });
}
export function injectBundles(
document: Document,
entrypointBundles: Record<string, EntrypointBundle>,
) {
const body = findElement(document, e => getTagName(e) === 'body');
if (!body) {
throw new Error('Missing body in HTML document.');
}
for (const { options, entrypoints } of Object.values(entrypointBundles)) {
if (!options.format) throw createError('Missing output format.');
for (const entrypoint of entrypoints) {
appendChild(
body,
createLoadScript(entrypoint.importPath, options.format, entrypoint.attributes),
);
}
}
}
| modernweb-dev/web/packages/rollup-plugin-html/src/output/injectBundles.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/output/injectBundles.ts",
"repo_id": "modernweb-dev",
"token_count": 459
} | 227 |
image-d.svg
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/image-d.svg/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/assets/image-d.svg",
"repo_id": "modernweb-dev",
"token_count": 7
} | 228 |
<html>
<body>
<p>page-a.html</p>
<script type="module" src="./page-a.js"></script>
<script type="module" src="./shared.js"></script>
</body>
</html>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/pages/page-a.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/basic/pages/page-a.html",
"repo_id": "modernweb-dev",
"token_count": 75
} | 229 |
a | modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-images/images/star.avif/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-images/images/star.avif",
"repo_id": "modernweb-dev",
"token_count": 1
} | 230 |
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; prefetch-src 'self'; upgrade-insecure-requests; style-src 'self' 'unsafe-inline'; script-src 'self';"
/>
</head>
<body>
<h1>hello world</h1>
<script type="module" src="./entrypoint-a.js"></script>
<script type="module" src="./entrypoint-b.js"></script>
<script>
console.log('foo');
</script>
<script>
console.log('bar');
</script>
</body>
</html>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/csp-page-c.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/csp-page-c.html",
"repo_id": "modernweb-dev",
"token_count": 167
} | 231 |
export default 'page a';
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pages/page-a.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/pages/page-a.js",
"repo_id": "modernweb-dev",
"token_count": 7
} | 232 |
import { getTextContent } from '@web/parse5-utils';
import { expect } from 'chai';
import { parse, serialize } from 'parse5';
import { injectBundles, createLoadScript } from '../../../src/output/injectBundles.js';
describe('createLoadScript()', () => {
it('creates a script for es modules', () => {
// parse5 types are broken
const scriptAst = createLoadScript('./app.js', 'es') as any;
expect(scriptAst.tagName).to.equal('script');
expect(scriptAst.attrs).to.eql([
{ name: 'type', value: 'module' },
{ name: 'src', value: './app.js' },
]);
});
it('creates a script for systemjs', () => {
// parse5 types are broken
const scriptAst = createLoadScript('./app.js', 'system') as any;
expect(scriptAst.tagName).to.equal('script');
expect(getTextContent(scriptAst)).to.equal('System.import("./app.js");');
});
it('creates a script for other modules types', () => {
const scriptAst = createLoadScript('./app.js', 'iife') as any;
expect(scriptAst.tagName).to.equal('script');
expect(scriptAst.attrs).to.eql([
{ name: 'src', value: './app.js' },
{ name: 'defer', value: '' },
]);
});
});
describe('injectBundles()', () => {
it('can inject a single bundle', () => {
const document = parse(
[
//
'<html>',
'<head></head>',
'<body>',
'<h1>Hello world</h1>',
'</body>',
'</html>',
].join(''),
);
injectBundles(document, [
{
options: { format: 'es' },
entrypoints: [
{
importPath: 'app.js',
// @ts-ignore
chunk: {},
},
],
},
]);
const expected = [
//
'<html>',
'<head></head>',
'<body>',
'<h1>Hello world</h1>',
'<script type="module" src="app.js"></script>',
'</body>',
'</html>',
].join('');
expect(serialize(document)).to.eql(expected);
});
it('can inject multiple bundles', () => {
const document = parse(
[
//
'<html>',
'<head></head>',
'<body>',
'<h1>Hello world</h1>',
'</body>',
'</html>',
].join(''),
);
injectBundles(document, [
// @ts-ignore
{
options: { format: 'es' },
entrypoints: [
{
importPath: './app.js',
// @ts-ignore
chunk: null,
},
],
},
// @ts-ignore
{
options: { format: 'iife' },
entrypoints: [
{
importPath: '/scripts/script.js',
// @ts-ignore
chunk: null,
},
],
},
]);
const expected = [
//
'<html>',
'<head></head>',
'<body>',
'<h1>Hello world</h1>',
'<script type="module" src="./app.js"></script>',
'<script src="/scripts/script.js" defer=""></script>',
'</body>',
'</html>',
].join('');
expect(serialize(document)).to.eql(expected);
});
});
| modernweb-dev/web/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/src/output/injectBundles.test.ts",
"repo_id": "modernweb-dev",
"token_count": 1488
} | 233 |
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="100" width="100"
style="stroke:#000000; fill: #ffff00"/>
</svg>
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/four.svg/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/four.svg",
"repo_id": "modernweb-dev",
"token_count": 97
} | 234 |
const justUrlObject = new URL('./one.svg', import.meta.url);
const href = new URL('./two.svg', import.meta.url).href;
const pathname = new URL('./three.svg', import.meta.url).pathname;
const searchParams = new URL('./four.svg', import.meta.url).searchParams;
const someJpg = new URL('./image.jpg', import.meta.url);
console.log({
justUrlObject,
href,
pathname,
searchParams,
someJpg,
});
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/transform-entrypoint.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/transform-entrypoint.js",
"repo_id": "modernweb-dev",
"token_count": 150
} | 235 |
const nameThree = 'three-name';
const imageThree = new URL(new URL('assets/three-CDdgprDC.svg', import.meta.url).href, import.meta.url).href;
export { imageThree, nameThree };
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/three-bundle.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/snapshots/three-bundle.js",
"repo_id": "modernweb-dev",
"token_count": 60
} | 236 |
import { RollupPluginHtml } from '@web/rollup-plugin-html';
import { Plugin } from 'rollup';
import { GeneratedFile, injectPolyfillsLoader, File, fileTypes } from '@web/polyfills-loader';
import path from 'path';
import { RollupPluginPolyfillsLoaderConfig } from './types';
import { createError, shouldInjectLoader } from './utils.js';
import { createPolyfillsLoaderConfig, formatToFileType } from './createPolyfillsLoaderConfig.js';
export function polyfillsLoader(pluginOptions: RollupPluginPolyfillsLoaderConfig = {}): Plugin {
let generatedFiles: GeneratedFile[] | undefined;
return {
name: '@web/rollup-plugin-polyfills-loader',
buildStart(options) {
generatedFiles = undefined;
if (!options.plugins) {
throw createError('Could not find any installed plugins');
}
const htmlPlugins = options.plugins.filter(
p => p.name === '@web/rollup-plugin-html',
) as RollupPluginHtml[];
const [htmlPlugin] = htmlPlugins;
if (!htmlPlugin) {
throw createError(
'Could not find any instance of @web/rollup-plugin-html in rollup build.',
);
}
htmlPlugin.api.disableDefaultInject();
htmlPlugin.api.addHtmlTransformer(async (html, { bundle, bundles, htmlFileName }) => {
const config = createPolyfillsLoaderConfig(pluginOptions, bundle, bundles);
const relativePathToPolyfills = path.relative(
path.dirname(htmlFileName),
path.dirname(pluginOptions.polyfillsDir || './polyfills'),
);
let htmlString = html;
if (shouldInjectLoader(config)) {
const result = await injectPolyfillsLoader(html, { ...config, relativePathToPolyfills });
htmlString = result.htmlString;
generatedFiles = result.polyfillFiles;
} else {
// we don't need to inject a polyfills loader, so we just inject the scripts directly
const scripts = config
.modern!.files.map((f: File) => {
let attributes = '';
if (f.attributes && f.attributes.length > 0) {
attributes = ' ';
attributes += f.attributes
.map(attribute => `${attribute.name}="${attribute.value}"`)
.join(' ');
}
return `<script type="module" src="${f.path}"${attributes}></script>\n`;
})
.join('');
htmlString = htmlString.replace('</body>', `\n${scripts}\n</body>`);
}
// preload all entrypoints as well as their direct dependencies
const { entrypoints } =
pluginOptions.legacyOutput && pluginOptions.modernOutput
? bundles[pluginOptions.modernOutput.name]
: bundle;
let preloaded = [];
function normalize(path: string) {
if (path.startsWith('../')) {
return path;
} else if (path.startsWith('./')) {
return path;
} else if (path.startsWith('/')) {
return '.' + path;
} else {
return './' + path;
}
}
for (const entrypoint of entrypoints) {
const importPath = normalize(path.posix.relative('', entrypoint.importPath));
preloaded.push(importPath);
// js files (incl. chunks) will always be in the root directory
const pathToRoot = path.posix.dirname(importPath);
for (const chunkPath of entrypoint.chunk.imports) {
const relativeChunkPath = normalize(path.posix.join(pathToRoot, chunkPath));
preloaded.push(relativeChunkPath);
}
}
preloaded = [...new Set(preloaded)];
const type =
pluginOptions.modernOutput?.type ?? formatToFileType(bundle?.options.format ?? 'esm');
const crossorigin = type === fileTypes.MODULE ? ' crossorigin="anonymous"' : '';
const shim = type === fileTypes.MODULESHIM;
const rel = `${shim ? 'module' : ''}preload${shim ? '-shim' : ''}`;
const as = shim ? '' : ' as="script"';
return htmlString.replace(
'</head>',
`\n${preloaded
.map(i => `<link rel="${rel}" href="${i}"${as}${crossorigin} />\n`)
.join('')}</head>`,
);
});
},
generateBundle(_, bundle) {
if (generatedFiles) {
for (const file of generatedFiles) {
// if the polyfills loader is used multiple times, this polyfill might already be output
// so we guard against that. polyfills are already hashed, so there is no need to worry
// about clashing
if (!(file.path in bundle)) {
this.emitFile({
type: 'asset',
name: file.path,
fileName: file.path,
source: file.content,
});
}
}
}
},
};
}
| modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/rollupPluginPolyfillsLoader.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/src/rollupPluginPolyfillsLoader.ts",
"repo_id": "modernweb-dev",
"token_count": 2121
} | 237 |
<html><head>
<link rel="preload" href="../entrypoint-b.js" as="script" crossorigin="anonymous" />
<link rel="preload" href="../entrypoint-a.js" as="script" crossorigin="anonymous" />
</head><body><script>(function () {
function loadScript(src, type, attributes) {
return new Promise(function (resolve) {
var script = document.createElement('script');
script.fetchPriority = 'high';
function onLoaded() {
if (script.parentElement) {
script.parentElement.removeChild(script);
}
resolve();
}
script.src = src;
script.onload = onLoaded;
if (attributes) {
attributes.forEach(function (att) {
script.setAttribute(att.name, att.value);
});
}
script.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + src + ' check the network tab for HTTP status.');
onLoaded();
};
if (type) script.type = type;
document.head.appendChild(script);
});
}
var polyfills = [];
if (!('fetch' in window)) {
polyfills.push(loadScript('./../polyfills/fetch.js'));
}
function loadFiles() {
[function () {
return loadScript('../entrypoint-b.js', 'module', []);
}, function () {
return loadScript('../entrypoint-a.js', 'module', []);
}].reduce(function (a, c) {
return a.then(c);
}, Promise.resolve());
}
if (polyfills.length) {
Promise.all(polyfills).then(loadFiles);
} else {
loadFiles();
}
})();</script></body></html> | modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/non-flattened.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/test/snapshots/non-flattened.html",
"repo_id": "modernweb-dev",
"token_count": 627
} | 238 |
{
"name": "rollup-plugin-workbox",
"version": "8.1.0",
"description": "Rollup plugin that builds a service worker with workbox as part of your rollup build",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/modernweb-dev/web.git",
"directory": "packages/rollup-plugin-workbox"
},
"author": "modern-web",
"homepage": "https://github.com/modernweb-dev/web/tree/master/packages/rollup-plugin-workbox",
"bugs": {
"url": "https://github.com/modernweb-dev/web/issues"
},
"main": "dist/index.js",
"module": "index.mjs",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"require": "./dist/index.js"
}
},
"scripts": {
"build": "tsc",
"demo": "rollup -c demo/rollup.config.mjs"
},
"keywords": [
"rollup",
"service-worker",
"workbox"
],
"dependencies": {
"esbuild": "^0.19.5",
"pretty-bytes": "^5.5.0",
"workbox-build": "^7.0.0"
},
"contributors": [
"Pascal Schilp <pascalschilp@gmail.com>",
"Benny Powers <web@bennypowers.com>"
]
}
| modernweb-dev/web/packages/rollup-plugin-workbox/package.json/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-workbox/package.json",
"repo_id": "modernweb-dev",
"token_count": 488
} | 239 |
// based on https://github.com/modernweb-dev/web/blob/%40web/dev-server-storybook%400.7.1/packages/dev-server-storybook/src/shared/stories/injectExportsOrder.ts
import { parse } from 'es-module-lexer';
export async function injectExportsOrder(source: string, filePath: string) {
const [, exports] = await parse(source, filePath);
if (exports.some(e => e.n === '__namedExportsOrder')) {
// user has defined named exports already
return null;
}
const orderedExports = exports.filter(e => e.n !== 'default');
const exportsArray = `['${orderedExports.map(({ n }) => n).join("', '")}']`;
return `${source};\nexport const __namedExportsOrder = ${exportsArray};`;
}
| modernweb-dev/web/packages/storybook-builder/src/inject-exports-order.ts/0 | {
"file_path": "modernweb-dev/web/packages/storybook-builder/src/inject-exports-order.ts",
"repo_id": "modernweb-dev",
"token_count": 232
} | 240 |
import baseConfig from './playwright.base.config.ts';
// @ts-ignore
baseConfig.webServer.command = 'npm run test:start:build';
export default baseConfig;
| modernweb-dev/web/packages/storybook-framework-web-components/playwright.build.config.ts/0 | {
"file_path": "modernweb-dev/web/packages/storybook-framework-web-components/playwright.build.config.ts",
"repo_id": "modernweb-dev",
"token_count": 49
} | 241 |
{
"name": "@web/storybook-utils",
"version": "1.0.1",
"publishConfig": {
"access": "public"
},
"description": "Utils for Storybook",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/modernweb-dev/web.git",
"directory": "packages/storybook-utils"
},
"author": "modern-web",
"homepage": "https://github.com/modernweb-dev/web/tree/master/packages/storybook-utils",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./index.mjs"
}
},
"engines": {
"node": ">=16.0.0"
},
"scripts": {
"build": "tsc"
},
"files": [
"*.d.ts",
"*.mjs",
"CHANGELOG.md",
"dist",
"src",
"README.md"
],
"keywords": [
"web",
"storybook",
"utils"
],
"peerDependencies": {
"react": "^18.0.0"
},
"dependencies": {
"@storybook/core-events": "^7.0.0"
},
"devDependencies": {
"react": "^18.0.0"
}
}
| modernweb-dev/web/packages/storybook-utils/package.json/0 | {
"file_path": "modernweb-dev/web/packages/storybook-utils/package.json",
"repo_id": "modernweb-dev",
"token_count": 462
} | 242 |
/* eslint-disable */
it('test a', async function () {
this.timeout(5000);
await new Promise(resolve => setTimeout(resolve, 100));
});
it('test b', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
});
it('test c', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
});
| modernweb-dev/web/packages/test-runner-browserstack/test-remote/fixtures/d.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-browserstack/test-remote/fixtures/d.js",
"repo_id": "modernweb-dev",
"token_count": 105
} | 243 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { ChromeLauncher, puppeteerCore, chromeLauncher } = cjsEntrypoint;
export { ChromeLauncher, puppeteerCore, chromeLauncher };
| modernweb-dev/web/packages/test-runner-chrome/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-chrome/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 77
} | 244 |
# Web Test Runner CLI
This package is deprecated, merged into `@web/test-runner-core` and `@web/test-runner`.
| modernweb-dev/web/packages/test-runner-cli/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-cli/README.md",
"repo_id": "modernweb-dev",
"token_count": 34
} | 245 |
import { TestRunnerPlugin } from '@web/test-runner-core';
import type { ChromeLauncher, puppeteerCore } from '@web/test-runner-chrome';
import type { PlaywrightLauncher } from '@web/test-runner-playwright';
import type { WebdriverLauncher } from '@web/test-runner-webdriver';
type TypePayload = { type: string };
type PressPayload = { press: string };
type DownPayload = { down: string };
type UpPayload = { up: string };
export type SendKeysPayload = TypePayload | PressPayload | DownPayload | UpPayload;
function isObject(payload: unknown): payload is Record<string, unknown> {
return payload != null && typeof payload === 'object';
}
function isSendKeysPayload(payload: unknown): boolean {
const validOptions = ['type', 'press', 'down', 'up'];
if (!isObject(payload)) throw new Error('You must provide a `SendKeysPayload` object');
const numberOfValidOptions = Object.keys(payload).filter(key =>
validOptions.includes(key),
).length;
const unknownOptions = Object.keys(payload).filter(key => !validOptions.includes(key));
if (numberOfValidOptions > 1)
throw new Error(
`You must provide ONLY one of the following properties to pass to the browser runner: ${validOptions.join(
', ',
)}.`,
);
if (numberOfValidOptions === 0)
throw new Error(
`You must provide one of the following properties to pass to the browser runner: ${validOptions.join(
', ',
)}.`,
);
if (unknownOptions.length > 0) {
throw new Error('Unknown options `' + unknownOptions.join(', ') + '` present.');
}
return true;
}
function isTypePayload(payload: SendKeysPayload): payload is TypePayload {
return 'type' in payload;
}
function isPressPayload(payload: SendKeysPayload): payload is PressPayload {
return 'press' in payload;
}
function isDownPayload(payload: SendKeysPayload): payload is DownPayload {
return 'down' in payload;
}
function isUpPayload(payload: SendKeysPayload): payload is UpPayload {
return 'up' in payload;
}
export function sendKeysPlugin(): TestRunnerPlugin<SendKeysPayload> {
return {
name: 'send-keys-command',
async executeCommand({ command, payload, session }): Promise<any> {
if (command === 'send-keys') {
if (!isSendKeysPayload(payload) || !payload) {
throw new Error('You must provide a `SendKeysPayload` object');
}
// handle specific behavior for playwright
if (session.browser.type === 'playwright') {
const page = (session.browser as PlaywrightLauncher).getPage(session.id);
if (isTypePayload(payload)) {
await page.keyboard.type(payload.type);
return true;
} else if (isPressPayload(payload)) {
await page.keyboard.press(payload.press);
return true;
} else if (isDownPayload(payload)) {
await page.keyboard.down(payload.down);
return true;
} else if (isUpPayload(payload)) {
await page.keyboard.up(payload.up);
return true;
}
}
// handle specific behavior for puppeteer
if (session.browser.type === 'puppeteer') {
const page = (session.browser as ChromeLauncher).getPage(session.id);
if (isTypePayload(payload)) {
await page.keyboard.type(payload.type);
return true;
} else if (isPressPayload(payload)) {
await page.keyboard.press(payload.press as puppeteerCore.KeyInput);
return true;
} else if (isDownPayload(payload)) {
await page.keyboard.down(payload.down as puppeteerCore.KeyInput);
return true;
} else if (isUpPayload(payload)) {
await page.keyboard.up(payload.up as puppeteerCore.KeyInput);
return true;
}
}
// handle specific behavior for webdriver
if (session.browser.type === 'webdriver') {
const browser = session.browser as WebdriverLauncher;
if (isTypePayload(payload)) {
await browser.sendKeys(session.id, payload.type.split(''));
return true;
} else if (isPressPayload(payload)) {
await browser.sendKeys(session.id, [payload.press]);
return true;
} else {
throw new Error('Only "press" and "type" are supported by webdriver.');
}
}
// you might not be able to support all browser launchers
throw new Error(`Sending keys is not supported for browser type ${session.browser.type}.`);
}
},
};
}
| modernweb-dev/web/packages/test-runner-commands/src/sendKeysPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/src/sendKeysPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 1785
} | 246 |
import path from 'path';
import { runTests } from '@web/test-runner-core/test-helpers';
import { chromeLauncher } from '@web/test-runner-chrome';
import { filePlugin } from '../../src/filePlugin.js';
describe('filePlugin', function test() {
this.timeout(20000);
it('passes file plugin tests', async () => {
await runTests({
files: [path.join(__dirname, 'browser-test.js')],
browsers: [chromeLauncher()],
plugins: [filePlugin()],
logger: {
...console,
error() {
// ignore errors as they're expected in tests
},
debug() {
//
},
logSyntaxError(error) {
console.error(error);
},
},
});
});
});
| modernweb-dev/web/packages/test-runner-commands/test/file/filePlugin.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/file/filePlugin.test.ts",
"repo_id": "modernweb-dev",
"token_count": 310
} | 247 |
/* @web/test-runner snapshot v1 */
export const snapshots = {};
snapshots['persistent-a'] = `this is nested snapshot A`;
/* end snapshot persistent-a */
snapshots['persistent-b'] = `this is nested snapshot B`;
/* end snapshot persistent-b */
| modernweb-dev/web/packages/test-runner-commands/test/snapshot/src/__snapshots__/nested-test.snap.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/snapshot/src/__snapshots__/nested-test.snap.js",
"repo_id": "modernweb-dev",
"token_count": 74
} | 248 |
import { gray } from 'nanocolors';
export function getWatchCommands(
coverage: boolean,
testFiles: string[],
focusedTest?: boolean,
): string[] {
if (focusedTest) {
return [
`${gray('Press')} F ${gray('to focus another test file.')}`,
`${gray('Press')} D ${gray('to debug in the browser.')}`,
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
`${gray('Press')} Q ${gray('to exit watch mode.')}`,
`${gray('Press')} Enter ${gray('to re-run this test file.')}`,
`${gray('Press')} ESC ${gray('to exit focus mode')}`,
].filter(_ => !!_);
}
return [
testFiles.length > 1 ? `${gray('Press')} F ${gray('to focus on a test file.')}` : '',
`${gray('Press')} D ${gray('to debug in the browser.')}`,
`${gray('Press')} M ${gray('to debug manually in a custom browser.')}`,
coverage ? `${gray('Press')} C ${gray('to view coverage details.')}` : '',
`${gray('Press')} Q ${gray('to quit watch mode.')}`,
`${gray('Press')} Enter ${gray('to re-run all tests.')}`,
].filter(_ => !!_);
}
| modernweb-dev/web/packages/test-runner-core/src/cli/getWatchCommands.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/cli/getWatchCommands.ts",
"repo_id": "modernweb-dev",
"token_count": 398
} | 249 |
import path from 'path';
import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig.js';
import { PARAM_SESSION_ID } from '../utils/constants.js';
import { BasicTestSession } from '../test-session/BasicTestSession.js';
const toBrowserPathRegExp = new RegExp(path.sep === '\\' ? '\\\\' : path.sep, 'g');
export function toBrowserPath(filePath: string) {
return filePath.replace(toBrowserPathRegExp, '/');
}
export function createSessionUrl(config: TestRunnerCoreConfig, session: BasicTestSession) {
let browserPath: string;
if (session.testFile.endsWith('.html')) {
const resolvedPath = path.resolve(session.testFile);
const relativePath = path.relative(config.rootDir, resolvedPath);
browserPath = `/${toBrowserPath(relativePath)}`;
} else {
browserPath = '/';
}
const params = `?${PARAM_SESSION_ID}=${session.id}`;
return `${config.protocol}//${config.hostname}:${config.port}${browserPath}${params}`;
}
| modernweb-dev/web/packages/test-runner-core/src/runner/createSessionUrl.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/runner/createSessionUrl.ts",
"repo_id": "modernweb-dev",
"token_count": 312
} | 250 |
import { BrowserLauncher } from '../browser-launcher/BrowserLauncher';
import { TestSessionGroup } from './TestSessionGroup.js';
export interface BasicTestSession {
id: string;
group: TestSessionGroup;
debug: boolean;
browser: BrowserLauncher;
testFile: string;
}
| modernweb-dev/web/packages/test-runner-core/src/test-session/BasicTestSession.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/test-session/BasicTestSession.ts",
"repo_id": "modernweb-dev",
"token_count": 80
} | 251 |
// Don't edit this file directly. It is generated by generate-ts-configs script
{
"extends": "../../tsconfig.node-base.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"composite": true,
"allowJs": true
},
"references": [
{
"path": "../parse5-utils/tsconfig.json"
},
{
"path": "../browser-logs/tsconfig.json"
},
{
"path": "../dev-server-core/tsconfig.json"
},
{
"path": "../test-runner-core/tsconfig.json"
}
],
"include": [
"src",
"types"
],
"exclude": [
"src/browser",
"tests",
"dist"
]
} | modernweb-dev/web/packages/test-runner-coverage-v8/tsconfig.json/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-coverage-v8/tsconfig.json",
"repo_id": "modernweb-dev",
"token_count": 300
} | 252 |
import { expect } from 'chai';
import { promises as fs } from 'fs';
import path from 'path';
import globby from 'globby';
import { chromeLauncher } from '@web/test-runner-chrome';
import { TestRunnerCoreConfig } from '@web/test-runner-core';
import { runTests } from '@web/test-runner-core/test-helpers';
import { junitReporter } from '../src/junitReporter.js';
const NON_ZERO_TIME_VALUE_REGEX = /time="((\d\.\d+)|(\d))"/g;
const USER_AGENT_STRING_REGEX = /"Mozilla\/5\.0 (.*)"/g;
const rootDir = path.join(__dirname, '..', '..', '..');
const normalizeOutput = (cwd: string, output: string) =>
output
.replace(NON_ZERO_TIME_VALUE_REGEX, 'time="<<computed>>"')
.replace(USER_AGENT_STRING_REGEX, '"<<useragent>>"')
.replace(/(Context|n).<anonymous>/g, '<<anonymous>>')
// don't judge - normalizing paths for windblows
.replace(/\/>/g, '🙈>')
.replace(/<\//g, '<🙈')
.replace(/\//g, path.sep)
.replace(/🙈>/g, '/>')
.replace(/<🙈/g, '</')
.trimEnd();
const readNormalized = (filePath: string): Promise<string> =>
fs.readFile(filePath, 'utf-8').then(out => normalizeOutput(rootDir, out));
function createConfig({
files,
reporters,
}: Partial<TestRunnerCoreConfig>): Partial<TestRunnerCoreConfig> {
return {
files,
reporters,
rootDir,
coverageConfig: {
report: false,
reportDir: process.cwd(),
},
browserLogs: true,
watch: false,
browsers: [chromeLauncher()],
};
}
async function run(cwd: string): Promise<{ actual: string; expected: string }> {
const files = await globby('*-test.js', { absolute: true, cwd });
const outputPath = path.join(cwd, './test-results.xml');
const reporters = [junitReporter({ outputPath })];
await runTests(createConfig({ files, reporters }), [], {
allowFailure: true,
reportErrors: false,
});
const actual = await readNormalized(outputPath);
const expected = await readNormalized(path.join(cwd, './expected.xml'));
return { actual, expected };
}
async function cleanupFixtures() {
for (const file of await globby('fixtures/**/test-results.xml', {
absolute: true,
cwd: __dirname,
}))
await fs.unlink(file);
}
describe('junitReporter', function () {
after(cleanupFixtures);
describe('for a simple case', function () {
const fixtureDir = path.join(__dirname, 'fixtures/simple');
it('produces expected results', async function () {
const { actual, expected } = await run(fixtureDir);
expect(actual).to.equal(expected);
});
});
describe('for a nested suite', function () {
const fixtureDir = path.join(__dirname, 'fixtures/nested');
it('produces expected results', async function () {
const { actual, expected } = await run(fixtureDir);
expect(actual).to.equal(expected);
});
});
describe('for multiple test files', function () {
const fixtureDir = path.join(__dirname, 'fixtures/multiple');
it('produces expected results', async function () {
const { actual, expected } = await run(fixtureDir);
expect(actual).to.equal(expected);
});
});
});
| modernweb-dev/web/packages/test-runner-junit-reporter/test/junitReporter.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-junit-reporter/test/junitReporter.test.ts",
"repo_id": "modernweb-dev",
"token_count": 1138
} | 253 |
// Don't edit this file directly. It is generated by generate-ts-configs script
{
"extends": "../../tsconfig.browser-base.json",
"compilerOptions": {
"module": "ESNext",
"outDir": "./dist",
"rootDir": "./src",
"composite": true,
"allowJs": true
},
"references": [
{
"path": "../parse5-utils/tsconfig.json"
},
{
"path": "../browser-logs/tsconfig.json"
},
{
"path": "../dev-server-core/tsconfig.json"
},
{
"path": "../test-runner-core/tsconfig.json"
}
],
"include": [
"src",
"types"
],
"exclude": [
"src/browser",
"tests",
"dist"
]
} | modernweb-dev/web/packages/test-runner-mocha/tsconfig.json/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-mocha/tsconfig.json",
"repo_id": "modernweb-dev",
"token_count": 300
} | 254 |
import { importMockable } from '../../../browser/index.js';
await importMockable('/inexistent-module.js');
| modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/inexistent/browser-test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-module-mocking/test/fixtures/inexistent/browser-test.js",
"repo_id": "modernweb-dev",
"token_count": 37
} | 255 |
/* eslint-disable */
it('test a', () => {});
it('test b', () => {});
it('test c', () => {});
| modernweb-dev/web/packages/test-runner-playwright/test/fixtures/b.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-playwright/test/fixtures/b.js",
"repo_id": "modernweb-dev",
"token_count": 40
} | 256 |
import { BrowserLauncher } from '@web/test-runner-core';
import { SauceLabsOptions, SauceConnectOptions } from 'saucelabs';
import WebDriver from 'webdriver';
import { RemoteOptions } from 'webdriverio';
import { Options } from '@wdio/types';
import { nanoid } from 'nanoid';
import { SauceLabsLauncher } from './SauceLabsLauncher.js';
import { SauceLabsLauncherManager } from './SauceLabsLauncherManager.js';
export function createSauceLabsLauncher(
saucelabsOptions: SauceLabsOptions,
saucelabsCapabilities?: WebDriver.DesiredCapabilities,
sauceConnectOptions?: SauceConnectOptions,
) {
if (saucelabsOptions == null) {
throw new Error('Options are required to set user and key.');
}
if (typeof saucelabsOptions.user !== 'string') {
throw new Error('Missing user in options');
}
if (typeof saucelabsOptions.key !== 'string') {
throw new Error('Missing key in options');
}
const finalSauceLabsOptions = { ...saucelabsOptions };
if (typeof finalSauceLabsOptions.region !== 'string') {
finalSauceLabsOptions.region = 'us';
}
const finalConnectOptions: SauceConnectOptions = { ...sauceConnectOptions };
if (typeof finalConnectOptions.tunnelIdentifier !== 'string') {
finalConnectOptions.tunnelIdentifier = `web-test-runner-${nanoid()}`;
}
const manager = new SauceLabsLauncherManager(finalSauceLabsOptions, finalConnectOptions);
return function sauceLabsLauncher(capabilities: WebDriver.DesiredCapabilities): BrowserLauncher {
if (capabilities == null) {
throw new Error('Capabilities are required.');
}
let finalCapabilities = { ...capabilities };
const finalSauceCapabilities = {
tunnelIdentifier: finalConnectOptions.tunnelIdentifier,
...saucelabsCapabilities,
};
// W3C capabilities: only browserVersion is mandatory, platformName is optional.
// Note that setting 'sauce:options' forces Sauce Labs to use W3C capabilities.
if (capabilities.browserVersion) {
// version is not a valid W3C key.
delete finalCapabilities.version;
// platform is not a valid W3C key and will throw, use platformName instead.
if (capabilities.platform) {
finalCapabilities.platformName =
finalCapabilities.platformName || finalCapabilities.platform;
delete finalCapabilities.platform;
}
finalCapabilities['sauce:options'] = {
...finalSauceCapabilities,
...(finalCapabilities['sauce:options'] || {}),
};
} else {
// JWP capabilities for remote environments not yet supporting W3C.
// This enables running tests on iPhone Simulators in Sauce Labs.
finalCapabilities = { ...finalCapabilities, ...finalSauceCapabilities };
}
// Type cast to not fail on snake case syntax e.g. browser_version.
const caps = finalCapabilities as Record<string, string>;
const browserName = caps.browserName ?? caps.browser ?? caps.device ?? 'unknown';
const browserVersion = caps.browserVersion ?? caps.version ?? caps.browser_version ?? '';
const platform = caps.platformName ?? caps.platform ?? '';
const browserIdentifier = `${browserName}${browserVersion}${platform}`;
const options: RemoteOptions = {
user: finalSauceLabsOptions.user,
key: finalSauceLabsOptions.key,
region: finalSauceLabsOptions.region as Options.SauceRegions,
logLevel: 'error',
capabilities: {
...finalCapabilities,
},
};
return new SauceLabsLauncher(manager, browserIdentifier, options);
};
}
| modernweb-dev/web/packages/test-runner-saucelabs/src/createSauceLabsLauncher.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/src/createSauceLabsLauncher.ts",
"repo_id": "modernweb-dev",
"token_count": 1167
} | 257 |
import { runIntegrationTests } from '../../../integration/test-runner/index.js';
import { createSauceLabsLauncher } from '../src/index.js';
if (!process.env.SAUCE_USERNAME) {
throw new Error('Missing env var SAUCE_USERNAME');
}
if (!process.env.SAUCE_ACCESS_KEY) {
throw new Error('Missing env var SAUCE_ACCESS_KEY');
}
const sauceLabsCapabilities = {
build: `modern-web ${process.env.GITHUB_REF ?? 'local'} build ${
process.env.GITHUB_RUN_NUMBER ?? ''
}`,
name: 'integration test',
};
const sauceLabsLauncher = createSauceLabsLauncher(
{
user: process.env.SAUCE_USERNAME,
key: process.env.SAUCE_ACCESS_KEY,
region: 'eu',
},
sauceLabsCapabilities,
);
describe('test-runner-saucelabs', function () {
this.timeout(400000);
function createConfig() {
return {
browserStartTimeout: 1000 * 60 * 2,
testsStartTimeout: 1000 * 60 * 2,
testsFinishTimeout: 1000 * 60 * 2,
browsers: [
sauceLabsLauncher({
browserName: 'chrome',
browserVersion: 'latest',
platformName: 'Windows 10',
}),
// sauceLabsLauncher({
// browserName: 'safari',
// browserVersion: 'latest',
// platformName: 'macOS 10.15',
// }),
sauceLabsLauncher({
browserName: 'internet explorer',
browserVersion: '11.0',
platformName: 'Windows 7',
}),
],
};
}
runIntegrationTests(createConfig, {
basic: false,
many: true,
focus: false,
groups: false,
parallel: false,
testFailure: false,
locationChanged: false,
});
});
| modernweb-dev/web/packages/test-runner-saucelabs/test-remote/saucelabsLauncher.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/test-remote/saucelabsLauncher.test.ts",
"repo_id": "modernweb-dev",
"token_count": 682
} | 258 |
/* eslint-disable */
it('test a', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
});
it('test b', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
});
it('test c', async () => {
await new Promise(resolve => setTimeout(resolve, 100));
});
| modernweb-dev/web/packages/test-runner-selenium/test/fixtures/f.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-selenium/test/fixtures/f.js",
"repo_id": "modernweb-dev",
"token_count": 97
} | 259 |
{
"name": "@web/test-runner-visual-regression",
"version": "0.9.0",
"publishConfig": {
"access": "public"
},
"description": "Web test runner visual regression",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/modernweb-dev/web.git",
"directory": "packages/test-runner-visual-regression"
},
"author": "modern-web",
"homepage": "https://github.com/modernweb-dev/web/tree/master/packages/test-runner-visual-regression",
"main": "browser/commands.mjs",
"exports": {
".": {
"import": "./browser/commands.mjs",
"types": "./index.d.ts"
},
"./plugin": {
"import": "./plugin.mjs",
"require": "./dist/index.js",
"types": "./plugin.d.ts"
}
},
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"build": "tsc",
"test:node": "mocha test/**/*.test.ts --require ts-node/register --reporter dot",
"test:watch": "mocha test/**/*.test.ts --require ts-node/register --watch --watch-files src,test"
},
"files": [
"*.d.ts",
"*.js",
"*.mjs",
"browser",
"dist",
"src"
],
"keywords": [
"web",
"test",
"runner",
"testrunner",
"visual-regression"
],
"dependencies": {
"@types/mkdirp": "^1.0.1",
"@types/pixelmatch": "^5.2.2",
"@types/pngjs": "^6.0.0",
"@web/test-runner-commands": "^0.9.0",
"@web/test-runner-core": "^0.13.0",
"mkdirp": "^1.0.4",
"pixelmatch": "^5.2.1",
"pngjs": "^7.0.0"
},
"devDependencies": {
"@web/test-runner-chrome": "^0.16.0",
"@web/test-runner-playwright": "^0.11.0",
"@web/test-runner-webdriver": "^0.8.0",
"mocha": "^10.2.0"
}
}
| modernweb-dev/web/packages/test-runner-visual-regression/package.json/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/package.json",
"repo_id": "modernweb-dev",
"token_count": 791
} | 260 |
import { TestRunnerPlugin } from '@web/test-runner-core';
import type { ChromeLauncher } from '@web/test-runner-chrome';
import type { PlaywrightLauncher } from '@web/test-runner-playwright';
import type { WebdriverLauncher } from '@web/test-runner-webdriver';
import { defaultOptions, VisualRegressionPluginOptions } from './config.js';
import {
visualDiffCommand,
VisualDiffCommandContext,
VisualDiffCommandResult,
} from './visualDiffCommand.js';
import { VisualRegressionError } from './VisualRegressionError.js';
interface Payload {
id: string;
name: string;
}
function validatePayload(payload: any): payload is Payload {
if (payload == null || typeof payload !== 'object') {
throw new Error('Command visual-diff requires a payload with an id and name');
}
if (typeof payload.id !== 'string') {
throw new Error('Command visual-diff is missing an id in payload');
}
if (typeof payload.name !== 'string') {
throw new Error('Command visual-diff is missing a name in payload');
}
return true;
}
export function visualRegressionPlugin(
options: Partial<VisualRegressionPluginOptions> = {},
): TestRunnerPlugin {
const mergedOptions = {
...defaultOptions,
...options,
diffOptions: {
...defaultOptions.diffOptions,
...options.diffOptions,
},
};
return {
name: 'visual-regression',
async executeCommand({ command, session, payload }): Promise<VisualDiffCommandResult | void> {
if (command === 'visual-diff') {
try {
if (!validatePayload(payload)) {
return;
}
const context: VisualDiffCommandContext = {
testFile: session.testFile,
browser: session.browser.name,
};
if (session.browser.type === 'puppeteer') {
const browser = session.browser as ChromeLauncher;
const page = browser.getPage(session.id);
const handle = await page.evaluateHandle(function findElement(elementId) {
return (
(window as any).__WTR_VISUAL_REGRESSION__ &&
(window as any).__WTR_VISUAL_REGRESSION__[elementId]
);
}, payload.id);
// @ts-ignore
const element = handle.asElement();
if (!element) {
throw new VisualRegressionError(
'Something went wrong diffing element, the browser could not find it.',
);
}
const screenshot = (await element.screenshot({ encoding: 'binary' })) as Buffer;
return visualDiffCommand(mergedOptions, screenshot, payload.name, context);
}
if (session.browser.type === 'playwright') {
const browser = session.browser as PlaywrightLauncher;
const page = browser.getPage(session.id);
const handle = await page.evaluateHandle(function findElement(elementId) {
return (
(window as any).__WTR_VISUAL_REGRESSION__ &&
(window as any).__WTR_VISUAL_REGRESSION__[elementId]
);
}, payload.id);
const element = handle.asElement();
if (!element) {
throw new VisualRegressionError(
'Something went wrong diffing element, the browser could not find it.',
);
}
const screenshot = await element.screenshot();
return visualDiffCommand(mergedOptions, screenshot, payload.name, context);
}
if (session.browser.type === 'webdriver') {
const browser = session.browser as WebdriverLauncher;
const locator = `
return (function () {
try {
var wtr = window.__WTR_VISUAL_REGRESSION__;
return wtr && wtr[${payload.id}];
} catch (_) {
return undefined;
}
})();
`;
const screenshot = await browser.takeScreenshot(session.id, locator);
return visualDiffCommand(mergedOptions, screenshot, payload.name, context);
}
throw new Error(
`Browser type ${session.browser.type} is not supported for visual diffing.`,
);
} catch (error: unknown) {
if (error instanceof VisualRegressionError) {
return {
errorMessage: `Something went wrong while executing creating visual diff: ${error.message}`,
diffPercentage: -1,
passed: false,
};
}
console.error(error);
return {
errorMessage: 'Something went wrong while creating visual diff.',
diffPercentage: -1,
passed: false,
};
}
}
},
};
}
| modernweb-dev/web/packages/test-runner-visual-regression/src/visualRegressionPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/src/visualRegressionPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 2064
} | 261 |
# @web/test-runner
## 0.18.1
### Patch Changes
- Updated dependencies [4cc90648]
- @web/test-runner-chrome@0.16.0
## 0.18.0
### Minor Changes
- c185cbaa: Set minimum node version to 18
### Patch Changes
- Updated dependencies [c185cbaa]
- @web/test-runner-commands@0.9.0
- @web/test-runner-chrome@0.15.0
- @web/test-runner-mocha@0.9.0
- @web/test-runner-core@0.13.0
- @web/config-loader@0.3.0
- @web/browser-logs@0.4.0
- @web/dev-server@0.4.0
## 0.17.3
### Patch Changes
- Updated dependencies [43be7391]
- Updated dependencies [60dda46f]
- @web/test-runner-core@0.12.0
- @web/test-runner-mocha@0.8.2
- @web/test-runner-chrome@0.14.4
- @web/test-runner-commands@0.8.3
## 0.17.2
### Patch Changes
- d07fc49c: Add the selectOption plugin's exports and types correctly
- Updated dependencies [d07fc49c]
- Updated dependencies [d9996d2d]
- @web/test-runner-commands@0.8.1
- @web/dev-server@0.3.3
## 0.17.1
### Patch Changes
- 72d31ec6: update mjs entrypoint with formatError
- Updated dependencies [5470b5b9]
- @web/dev-server@0.3.1
## 0.17.0
### Minor Changes
- 0c87f59e: feat/various fixes
- Update puppeteer to `20.0.0`, fixes #2282
- Use puppeteer's new `page.mouse.reset()` in sendMousePlugin, fixes #2262
- Use `development` export condition by default
### Patch Changes
- Updated dependencies [0c87f59e]
- @web/browser-logs@0.3.3
- @web/dev-server@0.3.0
- @web/test-runner-chrome@0.14.0
- @web/test-runner-commands@0.8.0
## 0.16.1
### Patch Changes
- 0cd3a2f8: chore(deps): bump puppeteer from 19.8.2 to 19.9.0
- c26d3730: Update TypeScript
- Updated dependencies [0cd3a2f8]
- Updated dependencies [c26d3730]
- @web/browser-logs@0.3.1
- @web/dev-server@0.2.1
- @web/test-runner-mocha@0.8.1
- @web/test-runner-core@0.11.1
- @web/config-loader@0.2.1
## 0.16.0
### Minor Changes
- febd9d9d: Set node 16 as the minimum version.
- 72c63bc5: Require Rollup@v3.x and update all Rollup related dependencies to latest.
### Patch Changes
- Updated dependencies [febd9d9d]
- Updated dependencies [b7d8ee66]
- Updated dependencies [72c63bc5]
- @web/browser-logs@0.3.0
- @web/config-loader@0.2.0
- @web/dev-server@0.2.0
- @web/test-runner-chrome@0.13.0
- @web/test-runner-commands@0.7.0
- @web/test-runner-core@0.11.0
- @web/test-runner-mocha@0.8.0
## 0.15.3
### Patch Changes
- c103f166: Update `isbinaryfile`
- 18a16bb0: Update `html-minifier-terser`
- d8579f15: Update `command-line-usage`
- 445b20e6: Update `convert-source-map`
- 6188c8ff: chore(deps): update dependency concurrently to v8
- 8128ca53: Update @rollup/plugin-replace
- Updated dependencies [77e413d9]
- Updated dependencies [cdeafe4a]
- Updated dependencies [c103f166]
- Updated dependencies [18a16bb0]
- Updated dependencies [1113fa09]
- Updated dependencies [d8579f15]
- Updated dependencies [817d674b]
- Updated dependencies [445b20e6]
- Updated dependencies [9b83280e]
- Updated dependencies [bd12ff9b]
- Updated dependencies [8128ca53]
- @web/test-runner-chrome@0.12.1
- @web/test-runner-core@0.10.29
- @web/dev-server@0.1.38
- @web/browser-logs@0.2.6
- @web/test-runner-commands@0.6.6
## 0.15.2
### Patch Changes
- b8198d19: Report browsers logs when using summary reporter
- bf82ccf1: Indent nested suites in summaryReporter output
- 57fd96c4: Export formatError from `@web/test-runner`
- Updated dependencies [0f5631d0]
- Updated dependencies [0e198dcc]
- @web/dev-server@0.1.37
- @web/test-runner-chrome@0.12.0
## 0.15.1
### Patch Changes
- b2c85736: Report browsers logs when using summary reporter
## 0.15.0
### Minor Changes
- acca5d51: Update dependency v8-to-istanbul to v9
### Patch Changes
- Updated dependencies [acca5d51]
- @web/test-runner-chrome@0.11.0
## 0.14.1
### Patch Changes
- 04e2fa7d: Update portfinder dependency to 1.0.32
- Updated dependencies [04e2fa7d]
- @web/dev-server@0.1.35
## 0.14.0
### Minor Changes
- 13b75cf3: Add browser name to summaryReporter output
### Patch Changes
- Updated dependencies [00da4255]
- @web/dev-server@0.1.33
## 0.13.31
### Patch Changes
- 570cdf70: - improve caching of snapshots in-memory
- don't block browser command on writing snapshot to disk
- don't write snapshot to disk for each change, batch write per file
- Updated dependencies [78d610d1]
- Updated dependencies [570cdf70]
- @web/dev-server@0.1.32
- @web/test-runner-commands@0.6.3
- @web/test-runner-core@0.10.27
## 0.13.30
### Patch Changes
- fff82902: Add types field to package.json exports map
## 0.13.29
### Patch Changes
- 8e3bb3cf: Add "forcedColors" support to "emulateMedia" command
- Updated dependencies [8e3bb3cf]
- Updated dependencies [efe42a8f]
- @web/test-runner-commands@0.6.2
## 0.13.28
### Patch Changes
- 2b6854cd: Ignore external urls from coverage
## 0.13.27
### Patch Changes
- 3192c9ff: Update puppeteer-core dependency to 13.1.3
- Updated dependencies [3192c9ff]
- @web/test-runner-chrome@0.10.7
## 0.13.26
### Patch Changes
- 7c2fa463: Update puppeteer-core and puppeteer to v13
- Updated dependencies [7c2fa463]
- @web/test-runner-chrome@0.10.6
## 0.13.25
### Patch Changes
- 24cc9212: Add `sendMousePlugin` to the default test runner config so that it will load automatically.
## 0.13.24
### Patch Changes
- 65eed8d7: Adds a summary reporter which lists all the tests run when the test runner finishes.
```js
import { summaryReporter } from '@web/test-runner';
export default {
reporters: [summaryReporter()],
};
```
If you'd like to flatten the suite names, so that each test is reported with it's full chain of suite titles, set the `flatten` option to true.
```js
summaryReporter({ flatten: true });
```
- 8edded31: Adds a dot reporter a la mocha.
```js
import { dotReporter } from '@web/test-runner';
export default {
reporters: [dotReporter()],
};
```
## 0.13.23
### Patch Changes
- Updated dependencies [36a06160]
- Updated dependencies [064b9dde]
- @web/test-runner-commands@0.6.0
## 0.13.22
### Patch Changes
- 3f79c247: Update dependency chrome-launcher to ^0.15.0
- Updated dependencies [3f79c247]
- @web/test-runner-chrome@0.10.5
## 0.13.21
### Patch Changes
- aab9a42f: Update dependency puppeteer-core to v11
- Updated dependencies [aab9a42f]
- @web/test-runner-chrome@0.10.4
## 0.13.20
### Patch Changes
- 64bd29ac: Corrected the typings for test-runner user config `testFramework` option
- Updated dependencies [64bd29ac]
- @web/test-runner-core@0.10.22
## 0.13.19
### Patch Changes
- e6c7459e: Use full path to browser session file
- Updated dependencies [e6c7459e]
- @web/test-runner-mocha@0.7.5
## 0.13.18
### Patch Changes
- d4f92e25: Replace uuid dependency with nanoid
- a09282b4: Replace chalk with nanocolors
- Updated dependencies [d4f92e25]
- Updated dependencies [a09282b4]
- @web/test-runner-core@0.10.21
- @web/dev-server@0.1.24
## 0.13.17
### Patch Changes
- de756b28: Update dependency puppeteer-core to v10
- Updated dependencies [de756b28]
- @web/test-runner-chrome@0.10.3
## 0.13.16
### Patch Changes
- 33ada3d8: Align @web/test-runner-core version
- Updated dependencies [33ada3d8]
- @web/test-runner-chrome@0.10.2
- @web/test-runner-commands@0.5.10
- @web/test-runner-mocha@0.7.4
## 0.13.15
### Patch Changes
- 73681b6d: Allow user config to be partial
- Updated dependencies [73681b6d]
- @web/test-runner-core@0.10.19
## 0.13.14
### Patch Changes
- cb693c71: Use block comments in snapshots to make them work in all browsers
- Updated dependencies [cb693c71]
- @web/test-runner-commands@0.5.6
## 0.13.13
### Patch Changes
- b362288a: make snapshots work on all browsers
- Updated dependencies [b362288a]
- @web/test-runner-commands@0.5.5
## 0.13.12
### Patch Changes
- 7cc5d13f: Fix coverage branch fusion
- Updated dependencies [51de0db1]
- @web/test-runner-core@0.10.18
## 0.13.11
### Patch Changes
- 270a633a: dynamic import web socket module
- Updated dependencies [270a633a]
- @web/test-runner-commands@0.5.4
## 0.13.10
### Patch Changes
- 3af6ff86: improve snapshot formatting
- Updated dependencies [3af6ff86]
- @web/test-runner-commands@0.5.3
## 0.13.9
### Patch Changes
- 773160f9: expose mocha runner
- Updated dependencies [773160f9]
- @web/test-runner-mocha@0.7.3
## 0.13.8
### Patch Changes
- 94cddfab: fix: allow stripXMLInvalidChars when replace it not available
## 0.13.7
### Patch Changes
- 91e0e617: add compareSnapshot function
- Updated dependencies [91e0e617]
- @web/test-runner-commands@0.5.2
## 0.13.6
### Patch Changes
- 339d05f7: add snapshots plugin
- Updated dependencies [339d05f7]
- @web/test-runner-commands@0.5.1
## 0.13.5
### Patch Changes
- Updated dependencies [c3ead4fa]
- @web/test-runner-commands@0.5.0
## 0.13.4
### Patch Changes
- 6f80be68: fix(test-runner): fix error when function metadata varies between tests, as seen in [https://github.com/modernweb-dev/web/issues/689](https://github.com/modernweb-dev/web/issues/689) and [https://github.com/istanbuljs/v8-to-istanbul/issues/121](https://github.com/istanbuljs/v8-to-istanbul/issues/121).
- Updated dependencies [6f80be68]
- @web/test-runner-core@0.10.17
## 0.13.3
### Patch Changes
- e7efd5b7: use script origin to connect websocket
- 16c6d567: Automatically loads `sendKeysPlugin` in the default test runner config
- Updated dependencies [e7efd5b7]
- @web/dev-server@0.1.17
- @web/test-runner-core@0.10.16
## 0.13.2
### Patch Changes
- 21f53211: add commands for reading/writing files
- Updated dependencies [6bf34874]
- Updated dependencies [21f53211]
- @web/dev-server@0.1.16
- @web/test-runner-commands@0.4.5
## 0.13.1
### Patch Changes
- 6c5893cc: use unescaped import specifier
- Updated dependencies [6c5893cc]
- @web/dev-server@0.1.15
- @web/test-runner-core@0.10.15
## 0.13.0
### Minor Changes
- 2c06f31e: Update puppeteer and puppeteer-core to 8.0.0
### Patch Changes
- Updated dependencies [a6a018da]
- Updated dependencies [2c06f31e]
- @web/test-runner-chrome@0.10.0
- @web/test-runner-commands@0.4.4
- @web/browser-logs@0.2.2
- @web/dev-server@0.1.14
## 0.12.20
### Patch Changes
- 1d9411a3: Export `sendKeysPlugin` from `@web/test-runner-commands/plugins`.
Loosen the typing of the command payload.
- d2389bac: Add a11ySnapshotPlugin to acquire the current accessibility tree from the browser:
```js
import { a11ySnapshot, findAccessibilityNode } from '@web/test-runner-commands';
// ...
const nodeName = 'Label Text';
const snapshot = await a11ySnapshot();
const foundNode = findAccessibilityNode(snapshot, node => node.name === nodeName);
expect(foundNode).to.not.be.null;
```
- Updated dependencies [1d9411a3]
- Updated dependencies [d2389bac]
- @web/test-runner-commands@0.4.3
## 0.12.19
### Patch Changes
- ce90c7c3: Add the `sendKeys` command
Sends a string of keys for the browser to press (all at once, as with single keys
or shortcuts; e.g. `{press: 'Tab'}` or `{press: 'Shift+a'}` or
`{press: 'Option+ArrowUp}`) or type (in sequence, e.g. `{type: 'Your name'}`) natively.
For specific documentation of the strings to leverage here, see the Playwright documentation,
here:
- `press`: https://playwright.dev/docs/api/class-keyboard#keyboardpresskey-options
- `type`: https://playwright.dev/docs/api/class-keyboard#keyboardtypetext-options
Or, the Puppeter documentation, here:
- `press`: https://pptr.dev/#?product=Puppeteer&show=api-keyboardpresskey-options
- `type`: https://pptr.dev/#?product=Puppeteer&show=api-keyboardtypetext-options
@param payload An object including a `press` or `type` property an the associated string
for the browser runner to apply via that input method.
@example
```ts
await sendKeys({
press: 'Tab',
});
```
@example
```ts
await sendKeys({
type: 'Your address',
});
```
- Updated dependencies [0a05464b]
- Updated dependencies [ce90c7c3]
- @web/dev-server@0.1.11
- @web/test-runner-commands@0.4.2
- @web/test-runner-core@0.10.14
## 0.12.18
### Patch Changes
- 4c5fa2fe: coverageConfig now uses object spread to merge with defaults
## 0.12.17
### Patch Changes
- aea269c9: Capture visual regressions across changing screenshot sizes.
## 0.12.16
### Patch Changes
- b146365a: Add `buildCache` option to the visual regression config to support always saving the "current" screenshot.
Make the `update` option in the visual regression config _strict_, and only save "current" shots as "baseline" when it is set to `true`.
- Updated dependencies [b146365a]
- @web/test-runner-core@0.10.13
## 0.12.15
### Patch Changes
- 83750cd2: fallback to fetch on IE11
- Updated dependencies [83750cd2]
- Updated dependencies [096fe25f]
- @web/test-runner-core@0.10.11
- @web/dev-server@0.1.7
## 0.12.14
### Patch Changes
- 2c223cf0: filter server stream errors
- Updated dependencies [2c223cf0]
- @web/dev-server@0.1.6
- @web/test-runner-core@0.10.10
## 0.12.13
### Patch Changes
- 3885b33e: configure timeout for fetching source maps for code coverage
- Updated dependencies [3885b33e]
- @web/test-runner-core@0.10.9
## 0.12.12
### Patch Changes
- 4a609a18: skip non-http coverage files
- Updated dependencies [4a609a18]
- @web/test-runner-chrome@0.9.4
## 0.12.11
### Patch Changes
- e3314b02: update dependency on core
- Updated dependencies [e3314b02]
- @web/test-runner-commands@0.4.1
- @web/test-runner-mocha@0.7.2
## 0.12.10
### Patch Changes
- 9ecb49f4: release test coverage package
- Updated dependencies [9ecb49f4]
- @web/test-runner-chrome@0.9.3
## 0.12.9
### Patch Changes
- 83e0757e: handle cases when userAgent is not defined
- Updated dependencies [83e0757e]
- @web/test-runner-chrome@0.9.2
- @web/test-runner-core@0.10.8
## 0.12.8
### Patch Changes
- 8861ded8: feat(dev-server-core): share websocket instances with iframe parent
- Updated dependencies [8861ded8]
- @web/test-runner-core@0.10.6
## 0.12.7
### Patch Changes
- c37b4343: Don't use red text color when there are 0 failures
## 0.12.6
### Patch Changes
- ad815710: fetch source map from server when generating code coverage reports. this fixes errors when using build tools that generate source maps on the fly, which don't exist on the file system
- c4738a40: support non-inline source maps for stack traces
- Updated dependencies [ad815710]
- Updated dependencies [c4738a40]
- @web/test-runner-chrome@0.9.1
- @web/test-runner-core@0.10.5
## 0.12.5
### Patch Changes
- 43bc451c: add configuration option reporters in coverageConfig to use various istanbul reporters
- fd831b54: fix manual testing HTML tests
- Updated dependencies [43bc451c]
- Updated dependencies [fd831b54]
- @web/test-runner-core@0.10.4
## 0.12.4
### Patch Changes
- 82ce63d1: add backwards compatibility for "middlewares" config property
- Updated dependencies [82ce63d1]
- @web/dev-server@0.1.5
## 0.12.3
### Patch Changes
- 8e3b1128: fix regression introduced in filterBrowserLogs function that flipped the return value. returning true now properly includes the logs
- d5a5f2bf: Add undeclared dependencies
- Updated dependencies [8e3b1128]
- Updated dependencies [d5a5f2bf]
- @web/test-runner-core@0.10.3
## 0.12.2
### Patch Changes
- 66638204: deduplicate parallel source map requests
- Updated dependencies [66638204]
- Updated dependencies [5d36f239]
- @web/test-runner-core@0.10.2
- @web/dev-server@0.1.4
## 0.12.1
### Patch Changes
- 9f1a8a56: normalize test framework path in stack trace
- Updated dependencies [9f1a8a56]
- @web/test-runner-core@0.10.1
## 0.12.0
### Minor Changes
- 1dd7cd0e: improve serialization of stack traces cross-browser
this adds two breaking changes, which should not affect most users:
- removed `userAgent` field from `TestSession`
- test reporter `reportTestFileResults` is no longer async
- a7d74fdc: drop support for node v10 and v11
### Patch Changes
- Updated dependencies [1dd7cd0e]
- Updated dependencies [a7d74fdc]
- Updated dependencies [1dd7cd0e]
- Updated dependencies [1dd7cd0e]
- @web/test-runner-core@0.10.0
- @web/test-runner-chrome@0.9.0
- @web/test-runner-commands@0.4.0
- @web/test-runner-mocha@0.7.0
- @web/browser-logs@0.2.0
## 0.11.7
### Patch Changes
- cbbeae3f: allow configuring puppeteer and playwright browser context
- Updated dependencies [cbbeae3f]
- @web/test-runner-chrome@0.8.2
## 0.11.6
### Patch Changes
- 69b2d13d: use about:blank to kill stale browser pages, this makes tests that rely on browser focus work with puppeteer
- 005ab9ae: use fast chrome-launcher installation finder
- Updated dependencies [69b2d13d]
- Updated dependencies [375116ad]
- Updated dependencies [005ab9ae]
- @web/test-runner-chrome@0.8.1
- @web/dev-server@0.1.3
## 0.11.5
### Patch Changes
- f2a84204: reduce delay when clearing terminal between test runs
- Updated dependencies [f2a84204]
- @web/test-runner-core@0.9.3
## 0.11.4
### Patch Changes
- b92fa63e: filter out non-objects from config
- Updated dependencies [b92fa63e]
- @web/dev-server@0.1.2
## 0.11.3
### Patch Changes
- af9811e2: regenerate MJS entrypoint
- Updated dependencies [af9811e2]
- @web/test-runner-core@0.9.2
## 0.11.2
### Patch Changes
- eceb6295: match dotfiles when resolving mimetypes
- Updated dependencies [eceb6295]
- @web/dev-server@0.1.1
- @web/test-runner-core@0.9.1
## 0.11.1
### Patch Changes
- 3e861601: include url params when resolving stack traces
## 0.11.0
### Minor Changes
- 6e313c18: merged @web/test-runner-cli package into @web/test-runner
- 0f613e0e: handle modules resolved outside root dir
- 36f6ab39: update to node-resolve v11
### Patch Changes
- 65de3390: reuse common dev server plugins
- Updated dependencies [6e313c18]
- Updated dependencies [6e313c18]
- Updated dependencies [0f613e0e]
- Updated dependencies [36f6ab39]
- Updated dependencies [6055a600]
- @web/config-loader@0.1.3
- @web/test-runner-core@0.9.0
- @web/test-runner-chrome@0.8.0
- @web/test-runner-commands@0.3.0
- @web/test-runner-mocha@0.6.0
- @web/dev-server@0.1.0
## 0.10.2
### Patch Changes
- a5dead1: reuse common dev server plugins
## 0.10.1
### Patch Changes
- 836abc0: handle errors thrown when (de)serializing browser logs
- f6107a4: handle logging shadow root
- Updated dependencies [836abc0]
- Updated dependencies [5ac055f]
- @web/test-runner-core@0.8.12
- @web/dev-server-rollup@0.2.13
## 0.10.0
### Minor Changes
- 0620eb9: fix(test-runner): run node-resolve after user plugins
## 0.9.13
### Patch Changes
- db298f0: make saucelabs a dev dependency
## 0.9.12
### Patch Changes
- 13993fa: avoid under 1 concurrency
- Updated dependencies [13993fa]
- @web/test-runner-cli@0.6.13
## 0.9.11
### Patch Changes
- 0614acf: update v8-to-istanbul
- Updated dependencies [2278a95]
- @web/test-runner-chrome@0.7.3
- @web/test-runner-cli@0.6.12
- @web/test-runner-core@0.8.11
## 0.9.10
### Patch Changes
- 8da3fe0: add debug option
- Updated dependencies [8da3fe0]
- @web/test-runner-cli@0.6.11
## 0.9.9
### Patch Changes
- 0f0d474: track manual test session imports
- Updated dependencies [0f0d474]
- @web/test-runner-cli@0.6.10
- @web/test-runner-core@0.8.9
## 0.9.8
### Patch Changes
- 4bbaa21: use consistent paths on windows
- Updated dependencies [4bbaa21]
- @web/test-runner-core@0.8.8
## 0.9.7
### Patch Changes
- 382affc: don't require files to exist on disk for coverage
- Updated dependencies [a70da8d]
- @web/test-runner-cli@0.6.9
## 0.9.6
### Patch Changes
- e21a4cf: add coverage failure per type when below threshold
- Updated dependencies [e21a4cf]
- @web/test-runner-cli@0.6.8
## 0.9.5
### Patch Changes
- 145a8e6: correctly encode/decode test framework url
- Updated dependencies [145a8e6]
- @web/test-runner-core@0.8.7
- @web/test-runner-cli@0.6.7
## 0.9.4
### Patch Changes
- 49fba90: run user plugins after builtin plugins
## 0.9.3
### Patch Changes
- 304558e: fix(test-runner): deduplicated browsers when reporting
- Updated dependencies [304558e]
- @web/test-runner-cli@0.6.6
- @web/test-runner-core@0.8.6
## 0.9.2
### Patch Changes
- 4edf123: added option to configure test runner HTML per group
- cd8928b: separate reporting per browser launcher
- Updated dependencies [4edf123]
- Updated dependencies [cd8928b]
- @web/test-runner-core@0.8.5
- @web/test-runner-cli@0.6.5
## 0.9.1
### Patch Changes
- aadf0fe: Speed up test loading by inling test config and preloading test files.
- Updated dependencies [416c0d2]
- Updated dependencies [aadf0fe]
- @web/test-runner-chrome@0.7.2
- @web/test-runner-cli@0.6.4
- @web/test-runner-commands@0.2.1
- @web/test-runner-saucelabs@0.1.1
- @web/test-runner-core@0.8.4
- @web/test-runner-mocha@0.5.1
## 0.9.0
### Minor Changes
- b397a4c: Disabled the in-browser reporter during regular test runs, improving performance.
Defaulted to the spec reporter instead of the HTML reporter in the browser when debugging. This avoids manipulating the testing environment by default.
You can opt back into the old behavior by setting the mocha config:
```js
export default {
testFramework: {
config: { reporter: 'html' },
},
};
```
### Patch Changes
- Updated dependencies [b397a4c]
- @web/test-runner-mocha@0.5.0
## 0.8.5
### Patch Changes
- c256a08: allow configuring concurrency per browser launcher
- Updated dependencies [c256a08]
- @web/test-runner-cli@0.6.3
- @web/test-runner-chrome@0.7.1
- @web/test-runner-core@0.8.3
## 0.8.4
### Patch Changes
- 859008b: added experimental mode to test workflows where tests on firefox require the browser window to be focused
- Updated dependencies [859008b]
- @web/test-runner-core@0.8.2
## 0.8.3
### Patch Changes
- 0b5cc82: always print stack traces in errors
- Updated dependencies [0b5cc82]
- @web/test-runner-cli@0.6.2
## 0.8.2
### Patch Changes
- 175b124: fixed reporting multiple test files for a browser
- 7ec6e94: don't require files option when using groups
- 438176c: Allow specifying default test group
- Updated dependencies [175b124]
- Updated dependencies [7ec6e94]
- Updated dependencies [438176c]
- @web/test-runner-core@0.8.1
- @web/test-runner-cli@0.6.1
## 0.8.1
### Patch Changes
- Updated dependencies [80d5814]
- @web/test-runner-mocha@0.4.0
## 0.8.0
### Minor Changes
- 2291ca1: replaced HTTP with websocket for server-browser communication
this improves test speed, especially when a test file makes a lot of concurrent requests
it lets us us catch more errors during test execution, and makes us catch them faster
### Patch Changes
- Updated dependencies [2291ca1]
- @web/test-runner-chrome@0.7.0
- @web/test-runner-cli@0.6.0
- @web/test-runner-commands@0.2.0
- @web/test-runner-core@0.8.0
- @web/test-runner-saucelabs@0.1.0
## 0.7.42
### Patch Changes
- f2d0bb2: avoid using document.baseURI in IE11
- Updated dependencies [f2d0bb2]
- @web/test-runner-mocha@0.3.7
## 0.7.41
### Patch Changes
- ae056f5: throw when combining browsers config and flags
## 0.7.40
### Patch Changes
- 72ffcde: improve error message when no browsers are configured
- fcc2e28: added manual testing and open browser options
- Updated dependencies [72ffcde]
- Updated dependencies [fcc2e28]
- @web/test-runner-core@0.7.23
- @web/test-runner-cli@0.5.18
## 0.7.39
### Patch Changes
- bd27fff: improve browser and proxy close logic
- Updated dependencies [bd27fff]
- @web/test-runner-core@0.7.22
- @web/test-runner-saucelabs@0.0.9
## 0.7.38
### Patch Changes
- c8abc29: fix generating manual debug page
- Updated dependencies [c8abc29]
- @web/test-runner-core@0.7.21
## 0.7.37
### Patch Changes
- 38d8f03: turn on selenium iframe mode by default
- Updated dependencies [38d8f03]
- Updated dependencies [38d8f03]
- @web/test-runner-cli@0.5.17
- @web/test-runner-saucelabs@0.0.8
## 0.7.36
### Patch Changes
- d15ffee: serve iframe page with HTML content-type
- Updated dependencies [d15ffee]
- @web/test-runner-core@0.7.20
## 0.7.35
### Patch Changes
- f5d6086: improve iframe mode speed
- Updated dependencies [f5d6086]
- @web/test-runner-saucelabs@0.0.7
## 0.7.34
### Patch Changes
- c723271: add port CLI flag
- Updated dependencies [c723271]
- @web/test-runner-cli@0.5.16
## 0.7.33
### Patch Changes
- 88cc7ac: Reworked concurrent scheduling logic
When running tests in multiple browsers, the browsers are no longer all started in parallel. Instead a new `concurrentBrowsers` property controls how many browsers are run concurrently. This helps improve speed and stability.
- Updated dependencies [88cc7ac]
- @web/test-runner-chrome@0.6.8
- @web/test-runner-cli@0.5.15
- @web/test-runner-core@0.7.19
- @web/test-runner-saucelabs@0.0.6
## 0.7.32
### Patch Changes
- 34efaad: added support for config groups
- Updated dependencies [34efaad]
- @web/test-runner-cli@0.5.14
- @web/test-runner-core@0.7.18
## 0.7.31
### Patch Changes
- 4ac0b3a: added experimental iframes mode to test improve speed when testing with selenium
- Updated dependencies [4ac0b3a]
- @web/test-runner-core@0.7.17
## 0.7.30
### Patch Changes
- 534e92c: added the ability to transform test file imports
- Updated dependencies [534e92c]
- @web/test-runner-core@0.7.16
- @web/test-runner-cli@0.5.13
## 0.7.29
### Patch Changes
- 13001e2: bump versions
## 0.7.28
### Patch Changes
- cde5d29: add browser logging for all browser launchers
- cde5d29: add filterBrowserLogs option
- Updated dependencies [cde5d29]
- Updated dependencies [cde5d29]
- @web/test-runner-chrome@0.6.7
- @web/test-runner-core@0.7.15
## 0.7.27
### Patch Changes
- 6949d03: fix serving generated rollup chunks
- Updated dependencies [6949d03]
- @web/dev-server-rollup@0.2.9
## 0.7.26
### Patch Changes
- 3d6004b: added rollup bundle plugin
- Updated dependencies [3d6004b]
- @web/dev-server-rollup@0.2.8
## 0.7.25
### Patch Changes
- 3c72bdd: fixed serving test files outside cwd
- Updated dependencies [3c72bdd]
- @web/test-runner-core@0.7.14
## 0.7.24
### Patch Changes
- 28007f1: allow unknown cli args
- 28007f1: allow custom command line args
- 89612d3: removed debug variable
- Updated dependencies [28007f1]
- Updated dependencies [28007f1]
- Updated dependencies [89612d3]
- @web/test-runner-cli@0.5.11
## 0.7.23
### Patch Changes
- 123c0c0: don't serve compressed files
- Updated dependencies [123c0c0]
- @web/test-runner-cli@0.5.10
- @web/test-runner-core@0.7.12
## 0.7.22
### Patch Changes
- 5ba52dd: properly close server on exit
- Updated dependencies [985a784]
- Updated dependencies [5ba52dd]
- @web/test-runner-cli@0.5.9
- @web/test-runner-core@0.7.11
## 0.7.21
### Patch Changes
- be3c9ed: track and log page reloads
- 2802df6: handle cases where reloading the page creates an infinite loop
- Updated dependencies [be3c9ed]
- Updated dependencies [2802df6]
- @web/test-runner-chrome@0.6.6
- @web/test-runner-core@0.7.10
## 0.7.20
### Patch Changes
- 431ec8f: added support for manually debugging in a browser
- Updated dependencies [431ec8f]
- Updated dependencies [abf811f]
- @web/test-runner-cli@0.5.8
- @web/test-runner-core@0.7.9
- @web/test-runner-commands@0.1.5
## 0.7.19
### Patch Changes
- 4de5259: also report syntax errors when not using the node-resolve flag
## 0.7.18
### Patch Changes
- 41d895f: capture native browser errors
- Updated dependencies [41d895f]
- @web/test-runner-chrome@0.6.5
## 0.7.17
### Patch Changes
- 43cd03b: increased browser start timeout
- Updated dependencies [43cd03b]
- @web/test-runner-cli@0.5.7
- @web/test-runner-core@0.7.8
## 0.7.16
### Patch Changes
- b1306c9: fixed race condition caching headers
- Updated dependencies [b1306c9]
- @web/test-runner-core@0.7.7
## 0.7.15
### Patch Changes
- ee8c8d1: improved handling of timeouts starting or stopping a page
- 6694af7: added esbuild-target flag
- Updated dependencies [ee8c8d1]
- Updated dependencies [e3e6b22]
- Updated dependencies [e83ac30]
- @web/test-runner-core@0.7.6
- @web/dev-server-rollup@0.2.5
## 0.7.14
### Patch Changes
- cd1213e: improved logging of resolving outside root dir
- Updated dependencies [cd1213e]
- @web/dev-server-rollup@0.2.4
- @web/test-runner-core@0.7.5
## 0.7.13
### Patch Changes
- 05f826e: add missing get-stream package
## 0.7.12
### Patch Changes
- 0cc6a82: expose a startTestRunner function
- Updated dependencies [0cc6a82]
- @web/test-runner-cli@0.5.6
## 0.7.11
### Patch Changes
- 2ff6570: avoid using instanceOf check when checking for BufferedLogger
- Updated dependencies [2ff6570]
- @web/test-runner-cli@0.5.5
## 0.7.10
### Patch Changes
- ce2a2e6: align dependencies
- Updated dependencies [ce2a2e6]
- @web/dev-server-rollup@0.2.3
- @web/test-runner-chrome@0.6.4
- @web/test-runner-cli@0.5.4
- @web/test-runner-commands@0.1.3
## 0.7.9
### Patch Changes
- 944aa88: fixed handling of circular references generated by serializing certain types, like functions and regexp
- Updated dependencies [bc1741d]
- @web/test-runner-core@0.7.4
## 0.7.8
### Patch Changes
- 22c85b5: fix handle race condition when starting browser
- da80c1d: fixed collecting test coverage on chrome/puppeteer
- Updated dependencies [22c85b5]
- Updated dependencies [da80c1d]
- @web/test-runner-chrome@0.6.3
## 0.7.7
### Patch Changes
- 60de9b5: improve handling of undefined and null in browser logs
- Updated dependencies [60de9b5]
- Updated dependencies [4d29bb4]
- @web/test-runner-cli@0.5.3
- @web/test-runner-chrome@0.6.2
## 0.7.6
### Patch Changes
- 74bbffe: implemented import maps plugin
- Updated dependencies [74bbffe]
- @web/test-runner-core@0.7.3
## 0.7.5
### Patch Changes
- dfef174: adds a custom reporter for HTML tests, avoiding errors when debugging
- Updated dependencies [dfef174]
- @web/test-runner-mocha@0.3.3
## 0.7.4
### Patch Changes
- a137493: improve HTML tests setup
- Updated dependencies [a137493]
- @web/test-runner-mocha@0.3.2
## 0.7.3
### Patch Changes
- 7e6e633: Added a --help command
- Updated dependencies [7e6e633]
- Updated dependencies [519e6e2]
- @web/test-runner-cli@0.5.2
- @web/test-runner-commands@0.1.2
## 0.7.2
### Patch Changes
- b020eee: update dependencies
## 0.7.1
### Patch Changes
- aa65fd1: run build before publishing
- Updated dependencies [aa65fd1]
- @web/dev-server-rollup@0.2.1
- @web/test-runner-chrome@0.6.1
- @web/test-runner-cli@0.5.1
- @web/test-runner-commands@0.1.1
- @web/test-runner-core@0.7.1
- @web/test-runner-mocha@0.3.1
## 0.7.0
### Minor Changes
- cdddf68: Removed support for `@web/test-runner-helpers`. This is a breaking change, the functionality is now available in `@web/test-runner-commands`.
- fdcf2e5: Merged test runner server into core, and made it no longer possible configure a different server.
The test runner relies on the server for many things, merging it into core makes the code more maintainable. The server is composable, you can proxy requests to other servers and we can look into adding more composition APIs later.
- 9be1f95: Added native node es module entrypoints. This is a breaking change. Before, native node es module imports would import a CJS module as a default import and require destructuring afterwards:
```js
import playwrightModule from '@web/test-runner-playwright';
const { playwrightLauncher } = playwrightModule;
```
Now, the exports are only available directly as a named export:
```js
import { playwrightLauncher } from '@web/test-runner-playwright';
```
- 3307aa8: update to mocha v8
### Patch Changes
- 62ff8b2: make tests work on windows
- Updated dependencies [cdddf68]
- Updated dependencies [fdcf2e5]
- Updated dependencies [62ff8b2]
- Updated dependencies [9be1f95]
- Updated dependencies [3307aa8]
- @web/test-runner-chrome@0.6.0
- @web/test-runner-core@0.7.0
- @web/test-runner-cli@0.5.0
- @web/test-runner-commands@0.1.0
- @web/dev-server-rollup@0.2.0
- @web/test-runner-mocha@0.3.0
## 0.6.65
### Patch Changes
- f924a9b: improve support for puppeteer firefox
- Updated dependencies [f924a9b]
- @web/test-runner-chrome@0.5.21
## 0.6.64
### Patch Changes
- 8fb820b: add an easy way to change served mime types
- Updated dependencies [8fb820b]
- @web/dev-server-rollup@0.1.9
- @web/test-runner-server@0.5.16
## 0.6.63
### Patch Changes
- d77093b: allow code coverage instrumentation through JS
- Updated dependencies [d77093b]
- @web/test-runner-chrome@0.5.20
- @web/test-runner-cli@0.4.30
- @web/test-runner-core@0.6.23
## 0.6.62
### Patch Changes
- f0fe1f0: update to playwright 1.3.x
## 0.6.61
### Patch Changes
- 74cc129: implement commands API
- Updated dependencies [02a3926]
- Updated dependencies [74cc129]
- @web/test-runner-chrome@0.5.19
- @web/test-runner-cli@0.4.29
- @web/test-runner-core@0.6.22
- @web/test-runner-server@0.5.15
- @web/test-runner-commands@0.0.1
- @web/test-runner-mocha@0.2.15
## 0.6.60
### Patch Changes
- cbdf3c7: chore: merge browser lib into test-runner-core
- Updated dependencies [cbdf3c7]
- @web/test-runner-chrome@0.5.18
- @web/test-runner-core@0.6.21
- @web/test-runner-mocha@0.2.14
## 0.6.59
### Patch Changes
- 4112c2b: feat(config-loader): add jsdoc type checking
- Updated dependencies [4112c2b]
- @web/test-runner-cli@0.4.28
## 0.6.58
### Patch Changes
- c7c7cc9: fix(dev-server-rollup): add missing parse5 dependency
- Updated dependencies [c7c7cc9]
- @web/dev-server-rollup@0.1.8
## 0.6.57
### Patch Changes
- 1d975e3: improve repository build setup
- Updated dependencies [1d975e3]
- @web/test-runner-mocha@0.2.13
- @web/test-runner-server@0.5.14
## 0.6.56
### Patch Changes
- c6fb524: expose test suite hierarchy, passed tests and duration
- Updated dependencies [c6fb524]
- @web/test-runner-cli@0.4.27
- @web/test-runner-core@0.6.20
- @web/test-runner-mocha@0.2.12
## 0.6.55
### Patch Changes
- 5b36825: prevent debug sessions from interferring with regular test sessions
- Updated dependencies [432f090]
- Updated dependencies [5b36825]
- @web/test-runner-chrome@0.5.17
- @web/test-runner-cli@0.4.26
- @web/test-runner-core@0.6.19
- @web/test-runner-server@0.5.13
## 0.6.54
### Patch Changes
- ae09789: improve CLI performance
- Updated dependencies [ae09789]
- @web/test-runner-cli@0.4.25
## 0.6.53
### Patch Changes
- 736d101: improve scheduling logic and error handling
- Updated dependencies [736d101]
- @web/test-runner-chrome@0.5.16
- @web/test-runner-cli@0.4.24
- @web/test-runner-core@0.6.18
## 0.6.52
### Patch Changes
- 4e3de03: fix a potential race condition when starting a new test
- Updated dependencies [4e3de03]
- @web/test-runner-chrome@0.5.15
## 0.6.51
### Patch Changes
- 7c25ba4: guard against the logs script being unavailable
- Updated dependencies [7c25ba4]
- @web/test-runner-chrome@0.5.14
## 0.6.50
### Patch Changes
- ad11e36: resolve coverage include/exclude patterns
- @web/test-runner-chrome@0.5.13
## 0.6.49
### Patch Changes
- 9484e97: replace rollupAdapter with fromRollup
- Updated dependencies [556827f]
- Updated dependencies [9484e97]
- Updated dependencies [7741a51]
- @web/dev-server-rollup@0.1.6
## 0.6.48
### Patch Changes
- 3757865: add more args to test reporter callbacks
- Updated dependencies [3757865]
- @web/test-runner-cli@0.4.23
- @web/test-runner-core@0.6.17
## 0.6.47
### Patch Changes
- 868d795: account for numbers in urls in stack traces
- c64fbe6: improve testing with HTML
- Updated dependencies [868d795]
- Updated dependencies [c64fbe6]
- @web/test-runner-cli@0.4.22
- @web/test-runner-mocha@0.2.11
## 0.6.46
### Patch Changes
- 5fada4a: improve logging and error reporting
- Updated dependencies [5fada4a]
- @web/test-runner-chrome@0.5.12
- @web/test-runner-cli@0.4.21
- @web/test-runner-core@0.6.16
- @web/test-runner-mocha@0.2.9
- @web/test-runner-server@0.5.12
## 0.6.45
### Patch Changes
- 7a22269: allow customize browser page creation
- Updated dependencies [7a22269]
- @web/test-runner-chrome@0.5.11
## 0.6.44
### Patch Changes
- 868f786: don't override user defined browser launchers
## 0.6.43
### Patch Changes
- 9712125: fix not watching files with syntax errors
## 0.6.42
### Patch Changes
- 6bc4381: handle windows paths in @web/dev-server-rolup
- 588a971: fix loading esm config on windows
- Updated dependencies [6bc4381]
- @web/dev-server-rollup@0.1.5
- @web/test-runner-cli@0.4.20
## 0.6.41
### Patch Changes
- 8d3f7df: fix handling of inline source maps
- 92bba60: feat(test-runner-cli): show source location for diff errors
- Updated dependencies [8d3f7df]
- Updated dependencies [92bba60]
- @web/test-runner-cli@0.4.19
## 0.6.40
### Patch Changes
- c2b5d6c: dedupe syntax errors
- 8596276: move logger to test runner cli
- Updated dependencies [f9dfcd3]
- Updated dependencies [c2b5d6c]
- Updated dependencies [8596276]
- @web/dev-server-rollup@0.1.3
- @web/test-runner-cli@0.4.18
- @web/test-runner-core@0.6.15
- @web/test-runner-server@0.5.11
## 0.6.39
### Patch Changes
- 4ced29a: fix race condition which cleared terminal on debug
- 023cc3f: don't require selecting files when there is only one test file
- a409489: remove multiple browsers total progress
- 7db1da1: open debug in a larger browser window
- Updated dependencies [4ced29a]
- Updated dependencies [023cc3f]
- Updated dependencies [a409489]
- Updated dependencies [7db1da1]
- @web/test-runner-cli@0.4.17
- @web/test-runner-core@0.6.14
- @web/test-runner-chrome@0.5.10
## 0.6.38
### Patch Changes
- e97d492: allow adding custom reporters
- Updated dependencies [e97d492]
- @web/test-runner-cli@0.4.16
- @web/test-runner-core@0.6.13
## 0.6.37
### Patch Changes
- 3478d90: reduce .ts file extension priority
## 0.6.36
### Patch Changes
- 27a91cc: allow configuring test framework options
- Updated dependencies [27a91cc]
- @web/test-runner-cli@0.4.15
- @web/test-runner-core@0.6.12
- @web/test-runner-mocha@0.2.8
- @web/test-runner-server@0.5.10
## 0.6.35
### Patch Changes
- f991708: encode source map url requests
- Updated dependencies [f991708]
- @web/test-runner-core@0.6.11
## 0.6.34
### Patch Changes
- d8b5f9e: don't report test coverage if it is not enabled
- Updated dependencies [d8b5f9e]
- @web/test-runner-cli@0.4.14
## 0.6.33
### Patch Changes
- 45741c7: improve test coverage logging
- Updated dependencies [45741c7]
- @web/test-runner-cli@0.4.13
## 0.6.32
### Patch Changes
- 1ebbf4a: fix deep cloning causing slow coverage measurements
- Updated dependencies [1ebbf4a]
- @web/test-runner-core@0.6.10
## 0.6.31
### Patch Changes
- db5baff: cleanup and sort dependencies
- Updated dependencies [db5baff]
- @web/test-runner-cli@0.4.12
- @web/test-runner-core@0.6.9
- @web/test-runner-mocha@0.2.7
- @web/test-runner-server@0.5.9
- @web/test-runner-chrome@0.5.9
## 0.6.30
### Patch Changes
- cfa4738: remove puppeteer dependency
- Updated dependencies [cfa4738]
- @web/test-runner-chrome@0.5.8
## 0.6.29
### Patch Changes
- 687089f: support source maps in error stack traces
- Updated dependencies [687089f]
- @web/test-runner-cli@0.4.11
- @web/test-runner-core@0.6.8
## 0.6.28
### Patch Changes
- c72ea22: allow configuring browser launch options
- Updated dependencies [c72ea22]
- @web/test-runner-chrome@0.5.7
- @web/test-runner-core@0.6.7
## 0.6.27
### Patch Changes
- 7c3b466: revert setting browser:true by default
## 0.6.26
### Patch Changes
- b34ec0c: Added web_modules and browser: true to the node resolve plugin
## 0.6.25
### Patch Changes
- 6bcf981: correctly map pages to browsers
## 0.6.24
### Patch Changes
- 4a6b9c2: make coverage work in watch mode
- Updated dependencies [4a6b9c2]
- @web/test-runner-chrome@0.5.6
- @web/test-runner-core@0.6.6
## 0.6.23
### Patch Changes
- c104663: run legacy plugin after resolving imports
## 0.6.22
### Patch Changes
- 2672e8a: expose isInlineScriptRequest function
## 0.6.21
### Patch Changes
- Updated dependencies [2a25595]
- @web/dev-server-legacy@0.0.1
## 0.6.20
### Patch Changes
- 1d6d498: allow changing viewport in tests
- Updated dependencies [1d6d498]
- @web/test-runner-chrome@0.5.5
- @web/test-runner-core@0.6.5
- @web/test-runner-helpers@0.0.1
- @web/test-runner-server@0.5.8
## 0.6.19
### Patch Changes
- e3bcdb6: fix(test-runner-cli): improve stack message detection
- Updated dependencies [e3bcdb6]
- @web/test-runner-cli@0.4.10
## 0.6.18
### Patch Changes
- afc3cc7: update dependencies
- Updated dependencies [afc3cc7]
- @web/dev-server-rollup@0.1.2
- @web/test-runner-chrome@0.5.4
## 0.6.17
### Patch Changes
- 2150a26: update dependencies
## 0.6.15
### Patch Changes
- 8b94b03: update to esbuild 0.6.x
## 0.6.14
### Patch Changes
- 5ab18d8: feat(test-runner-core): batch v8 test coverage
- Updated dependencies [5ab18d8]
- @web/test-runner-chrome@0.5.2
- @web/test-runner-core@0.6.4
- @web/test-runner-server@0.5.7
## 0.6.13
### Patch Changes
- ed59f5f: log relative test file paths
- Updated dependencies [ed59f5f]
- @web/test-runner-cli@0.4.8
## 0.6.12
### Patch Changes
- a6aad93: strip test session id from test file
- Updated dependencies [a6aad93]
- @web/test-runner-cli@0.4.7
## 0.6.11
### Patch Changes
- a9603b5: fix merging v8 code coverage
- Updated dependencies [a9603b5]
- @web/test-runner-core@0.6.3
## 0.6.10
### Patch Changes
- 7e773c0: remove incorrect dependency
## 0.6.9
### Patch Changes
- 3dab600: profile test coverage through v8/chromium
- Updated dependencies [3dab600]
- @web/test-runner-chrome@0.5.1
- @web/test-runner-cli@0.4.6
- @web/test-runner-core@0.6.2
- @web/test-runner-playwright@0.4.1
- @web/test-runner-server@0.5.6
## 0.6.8
### Patch Changes
- afee22a: run test coverage after user plugins
- Updated dependencies [afee22a]
- @web/test-runner-server@0.5.5
## 0.6.7
### Patch Changes
- ca0168d: move dependencies to the correct project
- Updated dependencies [ca0168d]
- @web/test-runner-server@0.5.4
## 0.6.6
### Patch Changes
- d1e9bec: emit test run finished after session update
- a9aec33: don't overwrite use coverage config
- Updated dependencies [d1e9bec]
- Updated dependencies [a9aec33]
- @web/test-runner-core@0.6.1
- @web/test-runner-cli@0.4.4
## 0.6.5
### Patch Changes
- eaf714d: print pending files in blue
- Updated dependencies [eaf714d]
- @web/test-runner-cli@0.4.3
## 0.6.4
### Patch Changes
- 93dbfe5: remove minified test framework from stack trace
- Updated dependencies [93dbfe5]
- @web/test-runner-cli@0.4.2
## 0.6.3
### Patch Changes
- 00c3fa2: add syntax export default from
- Updated dependencies [00c3fa2]
- @web/test-runner-server@0.5.3
## 0.6.2
### Patch Changes
- 307dd02: improve failure message
- Updated dependencies [307dd02]
- @web/test-runner-cli@0.4.1
## 0.6.1
### Patch Changes
- bfbc965: add missing dependency
- Updated dependencies [3523426]
- @web/test-runner-server@0.5.1
## 0.6.0
### Minor Changes
- c4cb321: Use web dev server in test runner. This contains multiple breaking changes:
- Browsers that don't support es modules are not supported for now. We will add this back later.
- Most es-dev-server config options are no longer available. The only options that are kept are `plugins`, `middleware`, `nodeResolve` and `preserveSymlinks`.
- Test runner config changes:
- Dev server options are now available on the root level of the configuration file.
- `nodeResolve` is no longer enabled by default. You can enable it with the `--node-resolve` flag or `nodeResolve` option.
- `middlewares` option is now called `middleware`.
- `testFrameworkImport` is now called `testFramework`.
- `address` is now split into `protocol` and `hostname`.
### Patch Changes
- Updated dependencies [c4cb321]
- @web/test-runner-chrome@0.5.0
- @web/test-runner-cli@0.4.0
- @web/test-runner-core@0.6.0
- @web/test-runner-server@0.5.0
## 0.5.22
### Patch Changes
- 7acda96: browser cache files in non-watch mode
- Updated dependencies [7acda96]
- @web/test-runner-server@0.4.6
## 0.5.21
### Patch Changes
- 7fbda3c: update mocha import
## 0.5.20
### Patch Changes
- f7c3e08: Create a separate config loader package
- Updated dependencies [f7c3e08]
- @web/test-runner-cli@0.3.10
## 0.5.19
### Patch Changes
- 2804b98: cache test runner libs
- Updated dependencies [2804b98]
- @web/test-runner-server@0.4.5
## 0.5.18
### Patch Changes
- 2f4ea46: resolve stack trace paths relative to the root dir
- Updated dependencies [2f4ea46]
- @web/test-runner-cli@0.3.9
## 0.5.17
### Patch Changes
- 50d1036: reset request 404s on rerun
- Updated dependencies [50d1036]
- @web/test-runner-core@0.5.7
## 0.5.16
### Patch Changes
- 14b7fae: handle errors in mocha hooks
- Updated dependencies [14b7fae]
- @web/test-runner-chrome@0.4.4
- @web/test-runner-cli@0.3.8
- @web/test-runner-core@0.5.6
- @web/test-runner-mocha@0.2.5
## 0.5.15
### Patch Changes
- 52803c0: add esbuild plugin
- Updated dependencies [52803c0]
- @web/test-runner-server@0.4.4
## 0.5.14
### Patch Changes
- 4f54bd3: only remove server adress in stack trace
- Updated dependencies [4f54bd3]
- @web/test-runner-cli@0.3.6
## 0.5.13
### Patch Changes
- 589ac94: use custom toString when logging objects
## 0.5.12
### Patch Changes
- f2bf9ae: first setup of browserstack
- Updated dependencies [f2bf9ae]
- @web/test-runner-server@0.4.3
## 0.5.11
### Patch Changes
- 54e2737: serialize logged complex objects
## 0.5.10
### Patch Changes
- f356e4c: re-render progress bar on rerun
- Updated dependencies [f356e4c]
- @web/test-runner-cli@0.3.5
## 0.5.9
### Patch Changes
- 56ed519: open browser windows sequentially in selenium
- Updated dependencies [56ed519]
- @web/test-runner-chrome@0.4.3
- @web/test-runner-core@0.5.5
## 0.5.8
### Patch Changes
- 1ed03f5: add mocha debug CSS from JS (for now)
- Updated dependencies [1ed03f5]
- @web/test-runner-mocha@0.2.4
## 0.5.7
### Patch Changes
- fe3a850: don't override config defaults
## 0.5.6
### Patch Changes
- 9d64995: handle mocking fetch
- Updated dependencies [9d64995]
- @web/test-runner-mocha@0.2.3
## 0.5.5
### Patch Changes
- ebfdfd2: add selenium browser launcher
- Updated dependencies [ebfdfd2]
- @web/test-runner-core@0.5.4
## 0.5.4
### Patch Changes
- ea8d173: don't overide default root dir
- Updated dependencies [ea8d173]
- @web/test-runner-mocha@0.2.2
## 0.5.3
### Patch Changes
- 3d3a375: update dependencies
## 0.5.2
### Patch Changes
- 45a2f21: add ability to run HTML tests
- Updated dependencies [45a2f21]
- @web/test-runner-chrome@0.4.1
- @web/test-runner-core@0.5.1
- @web/test-runner-mocha@0.2.1
- @web/test-runner-server@0.4.2
## 0.5.1
### Patch Changes
- 01fac81: always use a random port
- Updated dependencies [01fac81]
- @web/test-runner-cli@0.3.2
## 0.5.0
### Minor Changes
- 1d277e9: rename framework to browser-lib
### Patch Changes
- Updated dependencies [1d277e9]
- @web/test-runner-chrome@0.4.0
- @web/test-runner-core@0.5.0
- @web/test-runner-mocha@0.2.0
- @web/test-runner-cli@0.3.1
- @web/test-runner-server@0.4.1
## 0.4.0
### Minor Changes
- ccb63df: @web/test-runner-dev-server to @web/test-runner-server
### Patch Changes
- Updated dependencies [ccb63df]
- @web/test-runner-chrome@0.3.0
- @web/test-runner-cli@0.3.0
- @web/test-runner-core@0.4.0
- @web/test-runner-server@0.4.0
## 0.3.1
### Patch Changes
- 8a568d7: ignore favicon 404s
- Updated dependencies [8a568d7]
- @web/test-runner-dev-server@0.3.1
## 0.3.0
### Minor Changes
- 0c83d7e: create separate coverage and coverageConfig options
### Patch Changes
- Updated dependencies [0c83d7e]
- @web/test-runner-cli@0.2.0
- @web/test-runner-core@0.3.0
- @web/test-runner-dev-server@0.3.0
## 0.2.12
### Patch Changes
- b1ff44a: don't log coverage in focus mode
- Updated dependencies [b1ff44a]
- @web/test-runner-cli@0.1.12
## 0.2.11
### Patch Changes
- 7a7967f: handle non-object errors
## 0.2.10
### Patch Changes
- ed7b8db: add assets to published files
- Updated dependencies [ed7b8db]
- @web/test-runner-mocha@0.1.2
## 0.2.9
### Patch Changes
- 61afea4: improve speed when test coverage is enabled
- Updated dependencies [61afea4]
- @web/test-runner-dev-server@0.2.8
## 0.2.8
### Patch Changes
- 3d35527: fix config loading on node 10 and 12
- Updated dependencies [3d35527]
- @web/test-runner-cli@0.1.11
## 0.2.7
### Patch Changes
- ccce5e1: add babel plugin
- Updated dependencies [ccce5e1]
- @web/test-runner-dev-server@0.2.7
## 0.2.6
### Patch Changes
- 115442b: add readme, package tags and description
- Updated dependencies [115442b]
- @web/test-runner-chrome@0.2.2
- @web/test-runner-cli@0.1.8
- @web/test-runner-core@0.2.5
- @web/test-runner-dev-server@0.2.6
- @web/test-runner-mocha@0.1.1
## 0.2.5
### Patch Changes
- 0e10aa4: Update dependencies
## 0.2.4
### Patch Changes
- f63ab90: allow configuring dev server from config
- Updated dependencies [f63ab90]
- @web/test-runner-cli@0.1.6
## 0.2.3
### Patch Changes
- a0b2c81: add puppeteer and playwright flags
## 0.2.2
### Patch Changes
- 998dda8: add root dir and symlink flags
- Updated dependencies [df85d7e]
- @web/test-runner-dev-server@0.2.2
## 0.2.1
### Patch Changes
- Updated dependencies [79f9e6b]
- @web/test-runner-chrome@0.2.0
## 0.2.0
### Minor Changes
- 6df4c3a: use @web/test-runner-chrome by default
### Patch Changes
- Updated dependencies [97e85e6]
- Updated dependencies [37eb13a]
- @web/test-runner-chrome@0.1.0
- @web/test-runner-core@0.2.0
- @web/test-runner-cli@0.1.2
- @web/test-runner-dev-server@0.2.1
## 0.1.0
### Minor Changes
- 42b4182: first setup
### Patch Changes
- Updated dependencies [42b4182]
- @web/test-runner-cli@0.1.1
| modernweb-dev/web/packages/test-runner/CHANGELOG.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/CHANGELOG.md",
"repo_id": "modernweb-dev",
"token_count": 19227
} | 262 |
import { expect } from '@esm-bundle/chai';
it('can run a test with focus h', async () => {
const input = document.createElement('input');
document.body.appendChild(input);
let firedEvent = false;
input.addEventListener('focus', () => {
firedEvent = true;
});
input.focus();
await Promise.resolve();
expect(firedEvent).to.be.true;
});
| modernweb-dev/web/packages/test-runner/demo/focus/test/focus-h.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/focus/test/focus-h.test.js",
"repo_id": "modernweb-dev",
"token_count": 117
} | 263 |
{
"version": 3,
"file": "index.js",
"sources": [
"../src/a.js",
"../src/b.js"
],
"sourcesContent": [
"export function a() {\n throw new Error('error thrown in a.js')\n}",
"export function b() {\n throw new Error('error thrown in b.js')\n}"
],
"names": [],
"mappings": "AAAO,SAAS,CAAC,GAAG;AACpB,EAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC;AACzC;;ACFO,SAAS,CAAC,GAAG;AACpB,EAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC;AACzC;;;;"
}
| modernweb-dev/web/packages/test-runner/demo/source-maps/bundled/dist/index.js.map/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/source-maps/bundled/dist/index.js.map",
"repo_id": "modernweb-dev",
"token_count": 230
} | 264 |
import { MyClass, doBar } from '../src/MyClass';
describe('fail source maps separate', () => {
it('fails one', () => {
doBar('a', 5);
});
it('fails two', async () => {
const myClass = new MyClass();
await myClass.doFoo('a', 5);
});
});
| modernweb-dev/web/packages/test-runner/demo/source-maps/separate/test/fail-source-maps-separate.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/source-maps/separate/test/fail-source-maps-separate.test.ts",
"repo_id": "modernweb-dev",
"token_count": 100
} | 265 |
import { expect } from './chai.js';
before(() => {
throw new Error('error thrown in before hook');
});
it('true is true', () => {
expect(true).to.equal(true);
});
it('true is really true', () => {
expect(true).to.equal(true);
});
| modernweb-dev/web/packages/test-runner/demo/test/fail-before.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-before.test.js",
"repo_id": "modernweb-dev",
"token_count": 85
} | 266 |
import './fail-syntax-error-dependency.js';
describe('test 404 import', () => {
it('is never registered because ./x.js does not exist', () => {});
});
| modernweb-dev/web/packages/test-runner/demo/test/fail-syntax-error.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/fail-syntax-error.test.js",
"repo_id": "modernweb-dev",
"token_count": 50
} | 267 |
import { expect } from '../../chai.js';
import '../../shared-a.js';
import '../../shared-b.js';
it('test 1', () => {
expect(true).to.be.true;
});
it('test 2', () => {
expect('foo').to.be.a('string');
});
it('test 3', () => {
expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
});
it('test 4', () => {
expect(4).to.equal(4);
});
it('test 5', () => {
expect(() => {}).to.be.a('function');
});
describe('scoped tests', () => {
it('test 6', () => {
expect(true).to.be.true;
});
it('test 7', () => {
expect('foo').to.be.a('string');
});
it('test 8', () => {
expect({ foo: 'bar' }).to.eql({ foo: 'bar' });
});
it('test 9', () => {
expect(4).to.equal(4);
});
it('test 10', () => {
expect(() => {}).to.be.a('function');
});
});
| modernweb-dev/web/packages/test-runner/demo/test/many/a/pass-17.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/many/a/pass-17.test.js",
"repo_id": "modernweb-dev",
"token_count": 337
} | 268 |
import { expect } from './chai.js';
it('test 1', () => {
if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
console.log('message logged only on safari');
}
expect(true).to.be.true;
});
| modernweb-dev/web/packages/test-runner/demo/test/pass-log-safari.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-log-safari.test.js",
"repo_id": "modernweb-dev",
"token_count": 81
} | 269 |
export class MyClass {
async doFoo(foo, bar) {
await Promise.resolve();
foo.nonExisting();
return new Promise(resolve => {
resolve();
});
}
}
export function doBar(bar, foo) {
throw new Error('undefined is a function');
}
//# sourceMappingURL=MyClass.js.map | modernweb-dev/web/packages/test-runner/demo/tsc/dist/src/MyClass.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/src/MyClass.js",
"repo_id": "modernweb-dev",
"token_count": 134
} | 270 |
import './shared-a.js';
| modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-17.test.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-17.test.d.ts",
"repo_id": "modernweb-dev",
"token_count": 10
} | 271 |
import type { TestRunnerConfig as FullTestRunnerConfig } from './config/TestRunnerConfig.js';
export * from '@web/test-runner-core';
export { chromeLauncher } from '@web/test-runner-chrome';
export { startTestRunner } from './startTestRunner.js';
export { defaultReporter } from './reporter/defaultReporter.js';
export { summaryReporter } from './reporter/summaryReporter.js';
export { dotReporter } from './reporter/dotReporter.js';
export { formatError } from './reporter/reportTestsErrors.js';
export type TestRunnerConfig = Partial<FullTestRunnerConfig>;
| modernweb-dev/web/packages/test-runner/src/index.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/index.ts",
"repo_id": "modernweb-dev",
"token_count": 166
} | 272 |
import path from 'path';
export function toBrowserPath(filePath: string) {
return filePath.split(path.sep).join('/');
}
| modernweb-dev/web/packages/test-runner/src/reporter/utils/toBrowserPath.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/reporter/utils/toBrowserPath.ts",
"repo_id": "modernweb-dev",
"token_count": 40
} | 273 |
// Don't edit this file directly. It is generated by generate-ts-configs script
{
"extends": "./tsconfig.node-base.json",
"files": [],
"references": [
{
"path": "./packages/parse5-utils/tsconfig.json"
},
{
"path": "./packages/polyfills-loader/tsconfig.json"
},
{
"path": "./packages/rollup-plugin-html/tsconfig.json"
},
{
"path": "./packages/browser-logs/tsconfig.json"
},
{
"path": "./packages/dev-server-core/tsconfig.json"
},
{
"path": "./packages/test-runner-core/tsconfig.json"
},
{
"path": "./packages/test-runner-coverage-v8/tsconfig.json"
},
{
"path": "./packages/test-runner-mocha/tsconfig.json"
},
{
"path": "./packages/test-runner-chrome/tsconfig.json"
},
{
"path": "./packages/config-loader/tsconfig.json"
},
{
"path": "./packages/dev-server-rollup/tsconfig.json"
},
{
"path": "./packages/dev-server/tsconfig.json"
},
{
"path": "./packages/test-runner-playwright/tsconfig.json"
},
{
"path": "./packages/test-runner-webdriver/tsconfig.json"
},
{
"path": "./packages/dev-server-esbuild/tsconfig.json"
},
{
"path": "./packages/dev-server-legacy/tsconfig.json"
},
{
"path": "./packages/test-runner-commands/tsconfig.json"
},
{
"path": "./packages/test-runner-saucelabs/tsconfig.json"
},
{
"path": "./packages/test-runner/tsconfig.json"
},
{
"path": "./packages/storybook-builder/tsconfig.json"
},
{
"path": "./packages/rollup-plugin-polyfills-loader/tsconfig.json"
},
{
"path": "./packages/rollup-plugin-copy/tsconfig.json"
},
{
"path": "./packages/rollup-plugin-workbox/tsconfig.json"
},
{
"path": "./packages/rollup-plugin-import-meta-assets/tsconfig.json"
},
{
"path": "./packages/dev-server-hmr/tsconfig.json"
},
{
"path": "./packages/dev-server-polyfill/tsconfig.json"
},
{
"path": "./packages/dev-server-import-maps/tsconfig.json"
},
{
"path": "./packages/storybook-framework-web-components/tsconfig.json"
},
{
"path": "./packages/storybook-utils/tsconfig.json"
},
{
"path": "./packages/test-runner-puppeteer/tsconfig.json"
},
{
"path": "./packages/test-runner-selenium/tsconfig.json"
},
{
"path": "./packages/test-runner-browserstack/tsconfig.json"
},
{
"path": "./packages/test-runner-module-mocking/tsconfig.json"
},
{
"path": "./packages/test-runner-junit-reporter/tsconfig.json"
},
{
"path": "./packages/test-runner-visual-regression/tsconfig.json"
},
{
"path": "./packages/dev-server-storybook/tsconfig.json"
}
]
} | modernweb-dev/web/tsconfig.json/0 | {
"file_path": "modernweb-dev/web/tsconfig.json",
"repo_id": "modernweb-dev",
"token_count": 1325
} | 274 |
FROM node:16
ENV NPM_CONFIG_LOGLEVEL warn
WORKDIR /usr/src
CMD ["npm", "run", "start:install"]
| odota/web/Dockerfile/0 | {
"file_path": "odota/web/Dockerfile",
"repo_id": "odota",
"token_count": 44
} | 275 |
<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<g>
<title>background</title>
<rect fill="none" id="canvas_background" height="26" width="26" y="-1" x="-1"/>
<g display="none" id="canvasGrid">
<rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%" id="svg_1"/>
</g>
</g>
<g>
<title>Layer 1</title>
<line stroke-linecap="null" stroke-linejoin="null" id="svg_13" y2="4.020203" x2="3.616162" y1="9.070707" x1="1.6633" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" stroke="null" fill="none"/>
<path stroke="null" id="svg_22" d="m1.633841,19.588383l14.807068,0l0,-5.892256l-2.269696,0l4.539393,-2.946127l4.539395,2.946127l-2.269698,0l0,8.838385l-19.346462,0l0,-2.946129z" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" fill="#e0cf6e"/>
<path transform="rotate(180 11.558079719543457,7.642255783081055) " stroke="null" id="svg_23" d="m0.75,10.588383l14.807068,0l0,-5.892256l-2.269696,0l4.539393,-2.946127l4.539395,2.946127l-2.269698,0l0,8.838385l-19.346462,0l0,-2.946129z" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" fill="#e0cf6e"/>
</g>
</svg> | odota/web/public/assets/images/dota2/lane_1.svg/0 | {
"file_path": "odota/web/public/assets/images/dota2/lane_1.svg",
"repo_id": "odota",
"token_count": 554
} | 276 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<path fill="#3f9c35" d="M.1 0h640v480H.1z"/>
<path fill="#ed2939" d="M.1 0h640v320H.1z"/>
<path fill="#00b9e4" d="M.1 0h640v160H.1z"/>
<circle cx="304" cy="240" r="72" fill="#fff"/>
<circle cx="320" cy="240" r="60" fill="#ed2939"/>
<path d="M384 200l7.654 21.522 20.63-9.806-9.806 20.63L424 240l-21.522 7.654 9.806 20.63-20.63-9.806L384 280l-7.654-21.522-20.63 9.806 9.806-20.63L344 240l21.522-7.654-9.806-20.63 20.63 9.806L384 200z" fill="#fff"/>
</svg>
| odota/web/public/assets/images/flags/az.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/az.svg",
"repo_id": "odota",
"token_count": 278
} | 277 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<defs>
<clipPath id="a">
<path fill-opacity=".67" d="M-12 0h640v480H-12z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(12)">
<path fill="#fff" d="M968.53 480H-10.45V1.77h978.98z"/>
<path fill="#ffe900" d="M968.53 344.48H-10.45V143.3h978.98z"/>
<path fill="#08ced6" d="M968.53 480H-10.45V320.59h978.98zm0-318.69H-10.45V1.9h978.98z"/>
<path d="M-10.913 0c2.173 0 391.71 236.82 391.71 236.82l-392.8 242.38L-10.916 0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/bs.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/bs.svg",
"repo_id": "odota",
"token_count": 308
} | 278 |
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="480" width="640" viewBox="0 0 640 480">
<defs>
<path id="a" fill="#ffde00" d="M-.588.81L0-1 .588.81-.952-.31H.952z"/>
</defs>
<path d="M0 0h640v480H0z" fill="#de2910"/>
<use xlink:href="#a" transform="matrix(71.9991 0 0 72 119.999 120)" width="30" height="20"/>
<use xlink:href="#a" transform="matrix(-12.33562 -20.5871 20.58684 -12.33577 240.291 47.996)" width="30" height="20"/>
<use xlink:href="#a" transform="matrix(-3.38573 -23.75998 23.75968 -3.38578 287.95 95.796)" width="30" height="20"/>
<use xlink:href="#a" transform="matrix(6.5991 -23.0749 23.0746 6.59919 287.959 168.012)" width="30" height="20"/>
<use xlink:href="#a" transform="matrix(14.9991 -18.73557 18.73533 14.99929 239.933 216.054)" width="30" height="20"/>
</svg>
| odota/web/public/assets/images/flags/cn.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/cn.svg",
"repo_id": "odota",
"token_count": 372
} | 279 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt">
<rect rx="0" ry="0" height="477.9" width="640"/>
<rect rx="0" ry="0" height="159.3" width="640" y="320.7" fill="#fff"/>
<path fill="#1291ff" d="M0 0h640v159.3H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ee.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ee.svg",
"repo_id": "odota",
"token_count": 154
} | 280 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<defs>
<clipPath id="a">
<path fill-opacity=".67" d="M-95.808-.44h682.67v512h-682.67z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(89.82 .412) scale(.9375)">
<path fill="#fff" d="M610.61 511.56h-730.17v-512h730.17z"/>
<path d="M251.871 256.021c0 62.137-50.372 112.508-112.507 112.508-62.137 0-112.507-50.372-112.507-112.508 0-62.137 50.371-112.507 112.507-112.507 62.137 0 112.507 50.372 112.507 112.507z" fill="#fff"/>
<path d="M393.011 262.55c0 81.079-65.034 146.803-145.261 146.803S102.488 343.63 102.488 262.55s65.034-146.804 145.262-146.804S393.01 181.471 393.01 262.55z" fill="#c70000"/>
<path d="M-49.417 126.44l83.66-96.77 19.821 17.135-83.66 96.771zM-22.018 150.127l83.66-96.77 19.82 17.135-83.66 96.77z"/>
<path d="M-49.417 126.44l83.66-96.77 19.821 17.135-83.66 96.771z"/>
<path d="M-49.417 126.44l83.66-96.77 19.821 17.135-83.66 96.771zM5.967 174.32l83.66-96.77 19.82 17.136-83.66 96.77z"/>
<path d="M-49.417 126.44l83.66-96.77 19.821 17.135-83.66 96.771z"/>
<path d="M-49.417 126.44l83.66-96.77 19.821 17.135-83.66 96.771zM459.413 29.638l83.002 97.335-19.937 17-83.002-97.334zM403.707 77.141l83.002 97.335-19.936 17-83.002-97.334z"/>
<path d="M417.55 133.19l78.602-67.814 14.641 16.953-83.996 75.519-9.247-24.659z" fill="#fff"/>
<path d="M514.228 372.013l-80.416 95.829-19.716-16.4 80.417-95.828zM431.853 53.14l83.002 97.334-19.936 17.001-83.002-97.334zM541.475 394.676l-80.417 95.829-19.715-16.399 80.417-95.829zM486.39 348.857l-80.417 95.83-19.715-16.4 80.416-95.829z"/>
<path d="M104.6 236.68c4.592 36.974 11.297 78.175 68.199 82.455 21.328 1.278 62.817-5.074 77.061-63.19 18.688-55.829 74.975-71.88 113.28-41.613 21.718 14.166 27.727 36.666 29.283 53.557-1.739 54.243-32.874 101.2-72.823 122.14-45.93 27.3-109.56 27.87-165.3-13.49-25.12-23.57-60.219-67.02-49.7-139.86z" fill="#3d5897"/>
<path d="M435.91 370.59l78.734 67.661-14.591 16.997-87.156-71.851 23.013-12.807z" fill="#fff"/>
<path d="M-1.887 357.197l83.002 97.335-19.937 17-83.002-97.334z"/>
<path d="M-16.188 437.25l78.602-67.814 14.641 16.953-83.996 75.519-9.247-24.659z" fill="#fff"/>
<path d="M25.672 333.696l83.003 97.334-19.937 17-83.002-97.334zM-30.033 381.199l83.002 97.334-19.936 17L-49.97 398.2z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/kr.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/kr.svg",
"repo_id": "odota",
"token_count": 1275
} | 281 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd" stroke-width="1pt">
<path fill="#f31830" d="M0 0h640v240H0z"/>
<path fill="#fff" d="M0 240h640v240H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/mc.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/mc.svg",
"repo_id": "odota",
"token_count": 113
} | 282 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd">
<path fill="#009a00" d="M0 360h640v120H0z"/>
<path fill="#00f" d="M0 120h640v120H0z"/>
<path fill="red" d="M0 0h640v120H0z"/>
<path fill="#ff0" d="M0 240h640v120H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/mu.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/mu.svg",
"repo_id": "odota",
"token_count": 154
} | 283 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<defs>
<clipPath id="a">
<path fill-opacity=".67" d="M0 0h496.06v372.05H0z"/>
</clipPath>
</defs>
<g transform="scale(1.2902)" clip-path="url(#a)">
<path fill-rule="evenodd" fill="#fff" d="M.013 0h499.55v248.1H.013z"/>
<path d="M.013 0l-.02 18.621 119.21 61.253 44.86 1.3L.012 0z" fill="#c00"/>
<path d="M51.054 0l144.53 75.491V.001H51.064z" fill="#006"/>
<path fill="#c00" d="M214.86 0v96.372H.02v55.07h214.84v96.372h66.106v-96.372h214.84v-55.07h-214.84V0H214.86z"/>
<path d="M300.24 0v71.132L441.63.552 300.24 0z" fill="#006"/>
<path d="M304.71 78.887l39.76-.32L498.95.551l-40.99.668-153.25 77.668z" fill="#c00"/>
<path d="M.013 167.5v52.775l99.16-52.22-99.16-.56z" fill="#006"/>
<path d="M381.85 169.68l-41.336-.321 155.82 77.58-1.025-17.749-113.46-59.51zM38.73 248.25l146.11-76.71-38.38.26L.01 248.14" fill="#c00"/>
<path d="M497.9 21.795l-118 58.515 116.43.436v87.194h-99.159l98.242 53.23 1.442 27.08-52.474-.627-143.62-70.505v71.132h-104.67v-71.132l-134.72 70.94-60.844.192v247.81h991.59V.43L498.947 0M.537 27.971L.014 79.438l104.39 1.308L.544 27.971z" fill="#006"/>
<g fill-rule="evenodd" stroke-width="1pt" fill="#ffd900">
<path d="M496.06 0h496.06v496.06H496.06z"/>
<path d="M0 248.03h523.49v248.03H0z"/>
</g>
<g fill-rule="evenodd">
<path d="M290.9 125.29c0 23.619-19.148 42.767-42.768 42.767-23.619 0-42.767-19.147-42.767-42.767s19.147-42.767 42.767-42.767c23.62 0 42.767 19.147 42.767 42.767z" fill="#000067"/>
<path fill="#fff40d" d="M240.189 114.32l8.225-24.592 8.224 24.591 26.686-.018-21.603 15.175 8.266 24.58-21.577-15.211-21.577 15.207 8.27-24.576-21.6-15.182zM388.737 118.346l4.076-11.512 4.076 11.512 13.226-.008-10.707 7.104 4.097 11.508-10.694-7.122-10.693 7.12 4.098-11.506-10.704-7.107zM244.057 203.886l4.076-11.512 4.076 11.512 13.226-.008-10.707 7.104 4.097 11.508-10.694-7.122-10.693 7.12 4.098-11.506-10.704-7.107zM244.057 36.836l4.076-11.512 4.076 11.512 13.226-.008-10.707 7.104 4.097 11.508-10.694-7.122-10.693 7.12 4.098-11.506-10.704-7.107zM98.93 118.346l4.076-11.512 4.076 11.512 13.225-.008-10.706 7.104 4.096 11.508-10.693-7.122-10.694 7.12 4.099-11.506-10.705-7.107z"/>
</g>
</g>
</svg>
| odota/web/public/assets/images/flags/nu.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/nu.svg",
"repo_id": "odota",
"token_count": 1247
} | 284 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<g fill-rule="evenodd">
<path fill="#fff" d="M0 0h640v480H0z"/>
<path fill="#001b9a" d="M0 162.544h640v160.003H0z"/>
<path fill="#e70000" d="M0 .042h640v82.5H0zM0 400.003h640v80H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/th.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/th.svg",
"repo_id": "odota",
"token_count": 152
} | 285 |
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600" viewBox="0 0 9 6">
<rect fill="#d00" width="9" height="6"/>
<rect fill="#fff" width="9" height="4"/>
<rect fill="#003893" width="9" height="2"/>
</svg> | odota/web/public/assets/images/flags/yu.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/yu.svg",
"repo_id": "odota",
"token_count": 105
} | 286 |
import { Button } from '@material-ui/core';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import config from '../../config';
import Error from '../Error';
import { IconSteam } from '../Icons';
import LoggedIn from './LoggedIn';
const ButtonLabel = styled.span`
margin-left: 4px;
`;
const AccountWidget = ({
loading, error, user, style, strings,
}) => {
if (loading) return null;
return (
<div style={style}>
{error && <Error />}
{!error && !loading && user
? <LoggedIn style={style} playerId={user.account_id} />
:
<Button href={`${config.VITE_API_HOST}/login`}>
<IconSteam />
<ButtonLabel
style={{
lineHeight: '1px',
}}
>{strings.app_login}
</ButtonLabel>
</Button>
}
</div>
);
};
AccountWidget.propTypes = {
loading: PropTypes.bool,
error: PropTypes.string,
user: PropTypes.shape({}),
style: PropTypes.string,
strings: PropTypes.shape({}),
};
const mapStateToProps = (state) => {
const { error, loading, data } = state.app.metadata;
return {
loading,
error,
user: data.user,
strings: state.app.strings,
};
};
export default connect(mapStateToProps, null)(AccountWidget);
| odota/web/src/components/AccountWidget/AccountWidget.jsx/0 | {
"file_path": "odota/web/src/components/AccountWidget/AccountWidget.jsx",
"repo_id": "odota",
"token_count": 545
} | 287 |
import constants from '../constants';
const muiTheme = {
fontFamily: constants.fontFamily,
card: { fontWeight: constants.fontWeightNormal },
badge: { fontWeight: constants.fontWeightNormal },
subheader: { fontWeight: constants.fontWeightNormal },
raisedButton: { fontWeight: constants.fontWeightNormal },
flatButton: { fontWeight: constants.fontWeightNormal },
inkBar: {
backgroundColor: constants.colorBlue,
},
palette: {
textColor: constants.textColorPrimary,
primary1Color: constants.colorBlue,
canvasColor: constants.primarySurfaceColor,
borderColor: constants.dividerColor,
},
tabs: {
backgroundColor: 'transparent',
textColor: constants.colorMuted,
selectedTextColor: constants.textColorPrimary,
},
button: { height: 38 },
};
export default muiTheme;
| odota/web/src/components/App/muiTheme.js/0 | {
"file_path": "odota/web/src/components/App/muiTheme.js",
"repo_id": "odota",
"token_count": 246
} | 288 |
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Toggle from 'material-ui/Toggle';
import styled from 'styled-components';
const StyledDiv = styled.div`
padding: 0 15px;
box-sizing: border-box;
display: ${props => (props.showEditor ? 'none' : 'flex')};
flex-direction: row;
flex-wrap: wrap;
`;
const ExplorerControlSection = ({
showToggle, showEditor, toggleEditor, children, strings,
}) => (
<div>
<div style={{ width: '180px', margin: '10px' }}>
<div>{/* drawOmnibox(this, expandedFields) */}</div>
{showToggle && <Toggle
label={strings.explorer_toggle_sql}
defaultToggled={showEditor}
onToggle={toggleEditor}
/>}
</div>
<StyledDiv showEditor={showEditor}>
{children}
</StyledDiv>
<div style={{ display: showEditor ? 'block' : 'none' }}>
<div
id="editor"
style={{
height: 100,
width: '100%',
}}
/>
</div>
</div>);
ExplorerControlSection.propTypes = {
showToggle: PropTypes.bool,
showEditor: PropTypes.bool,
toggleEditor: PropTypes.func,
children: PropTypes.arrayOf(PropTypes.node),
strings: PropTypes.shape({}),
};
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(ExplorerControlSection);
| odota/web/src/components/Explorer/ExplorerControlSection.jsx/0 | {
"file_path": "odota/web/src/components/Explorer/ExplorerControlSection.jsx",
"repo_id": "odota",
"token_count": 544
} | 289 |
import Footer from './Footer';
export default Footer;
| odota/web/src/components/Footer/index.js/0 | {
"file_path": "odota/web/src/components/Footer/index.js",
"repo_id": "odota",
"token_count": 17
} | 290 |
import React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import propTypes from 'prop-types';
import Ability from './Ability';
import Talents from './Talents';
import AghanimUpgrades from './AghanimUpgrades';
const abilities = (await import('dotaconstants/build/abilities.json')).default;
const heroAbilities = (await import('dotaconstants/build/hero_abilities.json')).default;
const Wrapper = styled.div`
align-items: center;
display: flex;
justify-content: center;
margin-left: -4px;
margin-right: -4px;
margin-top: 16px;
`;
const AbilityItem = styled.div`
flex: 1 1 100%;
margin-bottom: 4px;
margin-top: 4px;
max-width: 64px;
padding-left: 4px;
padding-right: 4px;
`;
const renderAbilities = abilities => abilities.map(ability => (
<AbilityItem key={ability.key}>
<Ability {...ability.data} abilityID={ability.key} />
</AbilityItem>
));
const Abilities = ({ hero }) => {
const filterAbilities = (toFilterAbs) =>
toFilterAbs.filter((ability) => ability !== 'generic_hidden' && abilities[ability].behavior !== 'Hidden');
const mapAbilities = toFilterAbs => toFilterAbs.map((ability, id) => ({ data: abilities[ability], key: id }));
const mapTalents = talents => talents.map(talent => ({ ...abilities[talent.name], ...talent }));
const mapTalentsToLevel = (talents) => {
const talentMap = [];
talents.forEach((talent, i) => {
if (!talentMap[Math.floor(i / 2)]) {
talentMap[Math.floor(i / 2)] = [];
}
talentMap[Math.floor(i / 2)].push({
name: talent.dname,
});
});
return talentMap;
};
const mapAbilitiesAndTalents = (toMapHeroAbsTals) => {
const talsMap = {
skills: [],
talents: [],
};
const heroNpcName = toMapHeroAbsTals.name;
const heroAbs = heroAbilities[heroNpcName];
// Filter out generic_hidden skills from skill list
heroAbs.abilities = filterAbilities(heroAbs.abilities);
talsMap.skills = mapAbilities(heroAbs.abilities);
// Map Talents and assign them to correct level in Object
const heroTalents = mapTalents(heroAbs.talents);
talsMap.talents = mapTalentsToLevel(heroTalents);
return talsMap;
};
const heroAbs = mapAbilitiesAndTalents(hero);
return (
<Wrapper>
<AbilityItem>
<Talents talents={heroAbs.talents} />
</AbilityItem>
{renderAbilities(heroAbs.skills)}
<AbilityItem>
<AghanimUpgrades heroName={hero.name} skills={heroAbs.skills} />
</AbilityItem>
</Wrapper>
);
};
Abilities.propTypes = {
hero: propTypes.shape({}).isRequired,
};
const mapStateToProps = state => ({
});
export default connect(mapStateToProps)(Abilities);
| odota/web/src/components/Hero/Abilities.jsx/0 | {
"file_path": "odota/web/src/components/Hero/Abilities.jsx",
"repo_id": "odota",
"token_count": 989
} | 291 |
import React, { Component } from 'react';
import { shape, string, bool, oneOfType, func, arrayOf } from 'prop-types';
import { connect } from 'react-redux';
import { getRanking } from '../../actions';
import RankingTable from './RankingTable';
import RankingSkeleton from '../Skeletons/RankingSkeleton';
const renderRanking = (hero, rankings) => (
<div>
<RankingTable rankings={rankings} />
</div>
);
class Ranking extends Component {
static propTypes = {
match: shape({
params: shape({
heroId: string,
}),
}),
isLoading: bool,
isError: bool,
rankings: oneOfType([
arrayOf(shape({})),
shape({}),
]),
hero: string,
getRanking: func,
}
componentDidMount() {
if (
this.props.match.params &&
this.props.match.params.heroId
) {
this.props.getRanking(this.props.match.params.heroId);
}
}
render() {
const {
isLoading, isError, rankings, hero,
} = this.props;
return (
<div>
{isLoading || isError || rankings === null ? (
<RankingSkeleton />
) : (
renderRanking(hero, rankings || [])
)}
</div>
);
}
}
const mapStateToProps = state => ({
rankings: state.app.heroRanking.data.rankings,
isLoading: state.app.heroRanking.loading,
isError: state.app.heroRanking.error,
});
const mapDispatchToProps = dispatch => ({
getRanking: heroId => dispatch(getRanking(heroId)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Ranking);
| odota/web/src/components/Hero/Ranking.jsx/0 | {
"file_path": "odota/web/src/components/Hero/Ranking.jsx",
"repo_id": "odota",
"token_count": 615
} | 292 |
import React from 'react';
export default props => (
// Generated with vectorizer.ai
<svg viewBox='0.00 0.00 46.00 46.00' {...props}>
<g strokeWidth='2.00' fill='none' strokeLinecap='butt'>
<path
stroke='#898f1b'
vectorEffect='non-scaling-stroke'
d='
M 43.94 24.25
L 40.55 21.73'
/>
<path
stroke='#898f1b'
vectorEffect='non-scaling-stroke'
d='
M 23.35 22.02
L 23.27 22.55'
/>
<path
stroke='#13dd8e'
vectorEffect='non-scaling-stroke'
d='
M 13.16 8.28
Q 13.58 5.86 12.88 4.62'
/>
<path
stroke='#768b79'
vectorEffect='non-scaling-stroke'
d='
M 15.31 38.70
L 11.52 40.56'
/>
</g>
<path
fill='#26e030'
d='
M 43.94 24.25
L 40.55 21.73
Q 39.61 13.59 33.10 8.64
Q 32.62 8.28 32.09 8.55
Q 25.76 11.81 23.63 19.12
Q 23.40 19.91 23.13 20.65
Q 22.72 21.80 22.70 20.58
Q 22.59 12.49 28.57 6.81
A 0.40 0.40 0.0 0 0 28.53 6.20
L 28.26 6.01
Q 28.00 5.82 27.75 6.03
Q 24.89 8.36 23.75 11.76
Q 23.53 12.41 23.30 11.76
Q 23.12 11.22 23.34 10.68
Q 24.41 8.17 26.02 5.92
Q 26.16 5.73 25.97 5.58
L 25.77 5.42
Q 25.64 5.33 25.53 5.44
Q 22.59 8.45 22.19 12.53
Q 21.89 15.54 21.82 18.14
Q 21.82 18.27 21.78 18.14
Q 19.99 11.88 22.62 6.09
Q 22.91 5.44 22.21 5.48
L 20.50 5.57
Q 19.77 5.61 19.55 6.32
Q 17.16 14.11 21.51 21.23
Q 21.84 21.77 23.35 22.02
L 23.27 22.55
C 22.55 22.53 22.00 22.56 21.37 22.16
Q 13.89 17.46 13.16 8.28
Q 13.58 5.86 12.88 4.62
A 20.98 20.95 35.9 0 1 26.91 2.39
A 21.03 21.01 77.7 0 1 40.12 10.87
A 21.00 20.99 29.1 0 1 43.94 24.25
Z'
/>
<path
fill='#00d9ec'
d='
M 12.88 4.62
Q 13.58 5.86 13.16 8.28
C 8.81 12.28 6.26 15.31 5.58 21.08
A 1.00 0.99 20.1 0 0 6.03 22.04
C 10.63 25.06 16.79 25.38 21.52 23.32
Q 22.45 22.91 21.74 23.64
Q 21.16 24.24 20.47 24.61
Q 13.53 28.32 6.07 25.74
Q 5.57 25.57 5.72 26.07
L 5.92 26.76
A 0.71 0.69 89.0 0 0 6.41 27.25
Q 9.26 27.98 12.31 28.06
Q 12.43 28.06 12.39 28.17
L 12.29 28.46
Q 12.26 28.53 12.18 28.55
Q 9.47 28.99 6.97 28.50
A 0.35 0.34 8.5 0 0 6.56 28.80
L 6.52 29.08
A 0.35 0.35 0.0 0 0 6.83 29.47
Q 13.85 30.30 19.54 26.24
Q 19.65 26.16 19.74 26.27
L 19.74 26.28
Q 19.81 26.37 19.73 26.44
Q 14.89 30.92 8.19 31.43
Q 7.53 31.49 7.91 32.03
L 9.03 33.65
Q 9.46 34.26 10.19 34.09
Q 19.08 32.02 22.63 24.22
Q 23.49 22.34 23.43 24.41
Q 23.19 33.11 15.31 38.70
L 11.52 40.56
A 20.98 20.97 -61.3 0 1 3.88 14.38
A 20.98 20.96 -2.3 0 1 12.88 4.62
Z'
/>
<path
fill='#ec3d06'
d='
M 40.55 21.73
L 43.94 24.25
A 20.98 20.98 0.0 0 1 27.95 43.39
A 20.99 20.98 -35.2 0 1 11.52 40.56
L 15.31 38.70
Q 22.67 42.22 30.19 38.95
Q 30.86 38.66 30.85 37.93
Q 30.67 30.06 25.33 24.79
Q 23.03 22.53 25.79 24.20
Q 32.26 28.13 34.01 35.98
A 0.39 0.39 0.0 0 0 34.63 36.20
L 34.84 36.04
A 0.82 0.81 64.0 0 0 35.13 35.18
Q 34.06 31.16 31.60 28.10
Q 30.93 27.27 31.86 27.80
C 33.52 28.75 35.21 32.44 36.18 34.06
Q 36.75 34.99 36.65 33.91
Q 36.55 32.82 35.96 31.79
Q 32.97 26.55 27.98 24.39
Q 27.80 24.32 27.88 24.14
L 27.88 24.13
Q 27.95 23.97 28.11 24.03
Q 34.46 26.25 37.78 31.36
Q 38.21 32.02 38.53 31.29
L 39.27 29.55
Q 39.52 28.97 39.11 28.49
Q 33.10 21.57 23.27 22.55
L 23.35 22.02
C 24.84 21.83 26.10 20.87 27.32 20.51
Q 34.09 18.50 40.55 21.73
Z'
/>
</svg>
);
| odota/web/src/components/Icons/AttrUniversal.jsx/0 | {
"file_path": "odota/web/src/components/Icons/AttrUniversal.jsx",
"repo_id": "odota",
"token_count": 1948
} | 293 |
import React from 'react';
export default props => (
<svg {...props} viewBox="0 0 300 300">
<polygon
points="224.2,195.5 239.4,210.6 300,150 239.4,89.4 224.2,104.5 259,139.3 107.1,139.3 107.1,160.7
259,160.7"
/>
<path
d="M240.7,240.9c-24.3,24.3-56.6,37.7-90.9,37.7c-34.3,0-66.6-13.4-90.9-37.7c-24.3-24.3-37.5-56.6-37.5-90.9
c0-34.3,13.2-66.6,37.5-90.9c24.3-24.3,56.6-37.7,90.9-37.7c34.3,0,66.6,13.4,90.9,37.7c1.7,1.7,3.3,3.4,4.9,5.2h27.3
C245.8,25.4,200.8,0,149.8,0C67,0,0,67.2,0,150c0,82.8,67,150,149.8,150c51,0,96-25.4,123.1-64.3h-27.3
C244.1,237.5,242.4,239.2,240.7,240.9z"
/>
</svg>
);
| odota/web/src/components/Icons/Logout.jsx/0 | {
"file_path": "odota/web/src/components/Icons/Logout.jsx",
"repo_id": "odota",
"token_count": 435
} | 294 |
import React from 'react';
import PropTypes from 'prop-types';
import { isRadiant, getTeamName } from '../../utility';
import { IconRadiant, IconDire } from '../Icons';
import Heading from '../Heading';
import Table from '../Table';
const filterMatchPlayers = (players, team = '') =>
players
.filter(player => (team === 'radiant' && isRadiant(player.player_slot)) || (team === 'dire' && !isRadiant(player.player_slot)) || team === '')
.sort((a, b) => a.player_slot - b.player_slot);
const AbilityBuildTable = ({
players = [], columns, heading = '', radiantTeam = {}, direTeam = {}, summable = false,
}) => (
<div>
<Heading title={`${getTeamName(radiantTeam, true)} - ${heading}`} icon={<IconRadiant />} />
<Table data={filterMatchPlayers(players, 'radiant')} columns={columns} summable={summable} />
<Heading title={`${getTeamName(direTeam, false)} - ${heading}`} icon={<IconDire />} />
<Table data={filterMatchPlayers(players, 'dire')} columns={columns} summable={summable} />
</div>
);
AbilityBuildTable.propTypes = {
players: PropTypes.arrayOf({}),
columns: PropTypes.arrayOf({}),
heading: PropTypes.string,
radiantTeam: PropTypes.arrayOf({}),
direTeam: PropTypes.arrayOf({}),
summable: PropTypes.bool,
};
export default AbilityBuildTable;
| odota/web/src/components/Match/AbilityDraftTable.jsx/0 | {
"file_path": "odota/web/src/components/Match/AbilityDraftTable.jsx",
"repo_id": "odota",
"token_count": 440
} | 295 |
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Tooltip } from '@material-ui/core';
import heroes from 'dotaconstants/build/heroes.json';
import itemColors from 'dotaconstants/build/item_colors.json';
import emotes from 'dota2-emoticons/resources/json/charname.json';
import { IconRadiant, IconDire } from '../Icons';
import HeroImage from "../Visualizations/HeroImage";
import {
formatSeconds,
jsonFn,
formatTemplate,
formatTemplateToString,
} from '../../utility';
import { StyledEmote, StyledStoryNetWorthBar, StyledStoryNetWorthText, StyledStoryGoldAmount, StyledStorySpan, StyledStoryWrapper } from './StyledMatch';
import constants from '../constants';
import store from '../../store';
import config from '../../config';
const items = (await import('dotaconstants/build/items.json')).default;
const heroesArr = jsonFn(heroes);
// can be used in conjunction with is_radiant
const TEAM = {
radiant: true,
dire: false,
};
const GoldSpan = (amount) => {
const { strings } = store.getState().app;
return (
<StyledStorySpan key={`gold_${amount}`}>
<StyledStoryGoldAmount>
{amount.toLocaleString()}
</StyledStoryGoldAmount>
<img
width="25px"
height="17px"
alt={` ${strings.story_gold}`}
src='/assets/images/dota2/gold.png'
style={{ marginLeft: '3px' }}
/>
</StyledStorySpan>
);
};
const TeamSpan = (isRadiant) => {
const { strings } = store.getState().app;
return (
<StyledStorySpan isRadiant={isRadiant} key={`team_${isRadiant ? 'radiant' : 'dire'}`}>
{isRadiant ? <IconRadiant /> : <IconDire />}
{isRadiant ? strings.general_radiant : strings.general_dire}
</StyledStorySpan>
);
};
// Modified version of PlayerThumb
const PlayerSpan = (player) => {
const { strings } = store.getState().app;
if (!player || !heroes[player.hero_id]) {
return strings.story_invalid_hero;
}
const heroName = heroes[player.hero_id] ? heroes[player.hero_id].localized_name : strings.story_invalid_hero;
return (
<span>
<Tooltip title={player.account_id ? player.personaname : strings.general_anonymous}>
<StyledStorySpan
key={`player_${player.player_slot}`}
style={{ color: (player.isRadiant ? constants.colorGreen : constants.colorRed) }}
>
<HeroImage id={player.hero_id} isIcon />
{heroName}
</StyledStorySpan>
</Tooltip>
</span>);
};
// Modified version of PlayerThumb
const ItemSpan = item => (
<StyledStorySpan
key={`item_${item}`}
style={{ color: itemColors[(items[item] || {}).qual] }}
>
<img
width="26px"
src={items[item]
? `${config.VITE_IMAGE_CDN}${items[item].img}`
: '/assets/images/blank-1x1.gif'
}
alt={(items[item] || {}).dname}
/>
{(items[item] || {}).dname}
</StyledStorySpan>
);
const capitalizeFirst = (list) => {
if (typeof list[0] === 'string' || list[0] instanceof String) {
if (list[0].length > 0) { // MORE STUFF HERE
return [list[0][0].toUpperCase() + list[0].slice(1)].concat(list.slice(1));
}
} else if (list[0] instanceof Array) {
if (list[0].length > 0) {
return [capitalizeFirst(list[0])].concat(list.slice(1));
}
}
return list.slice(0);
};
// Adds a fullstop to the end of a sentence, and capitalizes the first letter if it can
const toSentence = (content) => {
const { strings } = store.getState().app;
const result = capitalizeFirst(content);
result.push(`${strings.story_fullstop} `);
return result;
};
const articleFor = (followingWord) => {
const { strings } = store.getState().app;
// Whether we use a or an depends on the sound of the following word, but that's much hardder to detect programmatically,
// so we're looking solely at vowel usage for now.
if (['A', 'E', 'I', 'O', 'U'].includes(followingWord.charAt(0))) {
return strings.article_before_vowel_sound;
}
return strings.article_before_consonant_sound;
};
const formatApproximateTime = (timeSeconds) => {
const { strings } = store.getState().app;
const timeMinutes = parseInt(timeSeconds / 60, 10);
// If the time is at least two hours, describe it in hours
if (timeMinutes > 120) {
const timeHours = parseInt(timeSeconds / (60 * 60), 10);
return `${strings.advb_over} ${formatTemplateToString(strings.time_hh, timeHours)}`;
} else if (timeMinutes > 60 && timeMinutes <= 120) {
// If the time is an hour to a quarter after, describe it as "over an hour"
return `${strings.advb_over} ${strings.time_h}`;
} else if (timeMinutes >= 50 && timeMinutes < 60) {
// If the time is between 50 and 60 minutes, describe it as "almost an hour"
return `${strings.advb_almost} ${strings.time_h}`;
}
// Otherwise, describe the time in minutes
return `${strings.advb_about} ${formatTemplateToString(strings.time_mm, timeMinutes)}`;
};
const renderSentence = (template, dict) => toSentence(formatTemplate(template, dict));
// Enumerates a list of items using the correct language syntax
const formatList = (list, noneValue = []) => {
const { strings } = store.getState().app;
switch (list.length) {
case 0:
return noneValue;
case 1:
return list;
case 2:
return formatTemplate(strings.story_list_2, { 1: list[0], 2: list[1] });
case 3:
return formatTemplate(strings.story_list_3, { 1: list[0], 2: list[1], 3: list[2] });
default:
return formatTemplate(strings.story_list_n, { i: list.shift(), rest: formatList(list) });
}
};
const isQuestion = message => /\w(?:\W*(\?)\W*)$/.test(message);
// evaluate the sentiment behind the message - rage, question, statement etc
const evaluateSentiment = (event, lastMessage) => {
const { strings } = store.getState().app;
const { message, player, time } = event;
const sentiment = isQuestion(message) ? ['question'] : ['statement'];
if (lastMessage && lastMessage.time + 130 > time) {
if (player && lastMessage.player_slot === player.player_slot) {
sentiment.push('continued');
} else if (isQuestion(lastMessage.key)) {
sentiment.push('response');
}
}
if (message.split(' ').length > 10) {
sentiment.push('long');
} else if (['XD', ':D', 'LOL'].includes(message.replace('?', '').toUpperCase())) {
sentiment.push('laughed');
} else if (message.toUpperCase() === message && /\w/.test(message)) {
sentiment.push('shouted');
} else if (/(\?|!|@|~|#|\$){2,}/.test(message)) {
sentiment.push('excited');
} else {
sentiment.push('normal');
}
return strings[sentiment.join('_')];
};
const emoteKeys = Object.keys(emotes);
// Abstract class
class StoryEvent {
constructor(time) {
this.time = time;
}
formatSentence() {
return toSentence(this.format());
}
render() {
return <div key={`event_at_${this.time}`}>{this.formatSentence()}</div>;
}
}
class IntroEvent extends StoryEvent {
constructor(match) {
super(-90);
this.game_mode = match.game_mode;
this.region = match.region;
this.date = new Date(match.start_time * 1000);
this.match_duration_seconds = match.duration;
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_intro, {
game_mode_article: articleFor(strings[`game_mode_${this.game_mode}`]),
game_mode: strings[`game_mode_${this.game_mode}`],
date: this.date.toLocaleDateString(
(window.localStorage && window.localStorage.getItem('localization')) || 'en-US',
{
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
},
),
region: strings[`region_${this.region}`],
duration_in_words: formatApproximateTime(this.match_duration_seconds),
});
}
}
class FirstbloodEvent extends StoryEvent {
constructor(match, obj) {
super(obj.time);
this.killer = match.players.find(player => player.player_slot === obj.player_slot);
if (obj.key !== null && obj.key !== undefined) {
this.victim = match.players[obj.key];
} else {
const killerLog = this.killer.kills_log;
const victimHero = (Array.isArray(killerLog) && killerLog[0] ? killerLog[0].key : null);
const foundHero = heroesArr('find')(hero => hero.name === victimHero);
this.victim = match.players.find(player => foundHero && player.hero_id === foundHero.id);
}
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_firstblood, {
time: formatSeconds(this.time),
killer: PlayerSpan(this.killer),
victim: PlayerSpan(this.victim),
});
}
}
class ChatMessageEvent extends StoryEvent {
constructor(match, obj, lastMessage) {
super(obj.time + 70);
this.type = obj.type;
this.player = match.players.find(player => player.player_slot === obj.player_slot);
this.lastMessage = lastMessage;
this.message = obj.key.trim();
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_chatmessage, {
player: PlayerSpan(this.player),
message: this.message.split('')
.map((char) => {
const emote = emotes[emoteKeys[emoteKeys.indexOf(char)]];
if (emote) {
return <StyledEmote emote={emote} />;
}
return char;
}),
said_verb: evaluateSentiment(this, this.lastMessage),
});
}
}
class AegisEvent extends StoryEvent {
constructor(match, obj, index) {
super(obj.time);
this.action = obj.type;
this.index = index;
this.player = match.players.find(player => player.player_slot === obj.player_slot);
}
get localizedAction() {
const { strings } = store.getState().app;
return ((this.action === 'CHAT_MESSAGE_AEGIS' && strings.timeline_aegis_picked_up) ||
(this.action === 'CHAT_MESSAGE_AEGIS_STOLEN' && strings.timeline_aegis_snatched) ||
(this.action === 'CHAT_MESSAGE_DENIED_AEGIS' && strings.timeline_aegis_denied));
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_aegis, {
action: this.localizedAction,
player: PlayerSpan(this.player),
});
}
}
class RoshanEvent extends StoryEvent {
constructor(match, obj, index, aegisEvents) {
super(obj.time);
this.team = obj.team === 2;
this.aegis = aegisEvents.find(aegis => aegis.index === index);
}
format() {
const { strings } = store.getState().app;
const formatted = formatTemplate(strings.story_roshan, { team: TeamSpan(this.team) });
return this.aegis ? formatList([formatted, this.aegis.format()]) : formatted;
}
}
class CourierKillEvent extends StoryEvent {
constructor(match, obj) {
super(obj.time);
this.team = obj.team === 2;
// Adjust for incorrect data from post 7.23 core bug
// Here the team value is killer id
if (obj.killer === undefined) {
this.team = obj.team > 4
obj.killer = (this.team ? 123 : 0) + obj.team
}
this.killer = match.players.find(player => player.player_slot === obj.killer) || -1;
this.amount = obj.value || 0;
}
format() {
const { strings } = store.getState().app;
const team = TeamSpan(this.team)
const killer = this.killer === -1 ? TeamSpan(!this.team) : PlayerSpan(this.killer);
// Legacy team couriers
if (this.killer === null) {
return formatTemplate(strings.story_courier_kill, {
team,
});
}
if (this.amount === 0) {
return formatTemplate(strings.story_courier_kill_killer, {
team,
killer,
});
}
return formatTemplate(strings.story_courier_kill_gold, {
team,
killer,
gold: GoldSpan(this.amount),
});
}
}
class PredictionEvent extends StoryEvent {
constructor(match, team) {
super(team);
if (team === -89) {
this.team = true; // radiant
this.players = match.players.filter(player => player.isRadiant && player.pred_vict);
} else {
this.team = false; // dire
this.players = match.players.filter(player => !player.isRadiant && player.pred_vict);
}
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_predicted_victory, {
players: formatList(this.players.map(PlayerSpan), strings.story_predicted_victory_empty),
team: TeamSpan(this.team),
});
}
}
const localizedLane = strings => ({
1: strings.lane_pos_1,
2: strings.lane_pos_2,
3: strings.lane_pos_3,
});
const getLaneScore = players => (Math.max(...players.map(player => player.gold_t[10] || 0)) || 0);
const laneScoreDraw = 500;
class LaneStory {
constructor(match, lane) {
this.radiant_players = match.players.filter(player => player.lane === parseInt(lane, 10) && player.isRadiant && (!player.is_roaming));
this.dire_players = match.players.filter(player => player.lane === parseInt(lane, 10) && !player.isRadiant && (!player.is_roaming));
this.lane = lane;
this.winning_team = getLaneScore(this.radiant_players) > getLaneScore(this.dire_players);
this.is_draw = Math.abs(getLaneScore(this.radiant_players) - getLaneScore(this.dire_players)) <= laneScoreDraw;
}
format() {
const { strings } = store.getState().app;
// If there is nobody in this lane
if (this.radiant_players.length === 0 && this.dire_players.length === 0) {
return renderSentence(strings.story_lane_empty, {
lane: localizedLane(strings)[this.lane],
});
}
// If only one team is in this lane
if (this.radiant_players.length === 0 || this.dire_players.length === 0) {
return renderSentence(strings.story_lane_free, {
players: formatList(this.radiant_players.concat(this.dire_players).map(PlayerSpan)),
lane: localizedLane(strings)[this.lane],
});
}
// If both teams are in this lane
// If it's close enough to be a draw
if (this.is_draw) {
return renderSentence(strings.story_lane_draw, {
radiant_players: formatList(this.radiant_players.map(PlayerSpan), strings.story_lane_empty),
dire_players: formatList(this.dire_players.map(PlayerSpan), strings.story_lane_empty),
lane: localizedLane(strings)[this.lane],
});
}
// If one team won
return renderSentence(this.winning_team ? strings.story_lane_radiant_win : strings.story_lane_radiant_lose, {
radiant_players: formatList(this.radiant_players.map(PlayerSpan), strings.story_lane_empty),
dire_players: formatList(this.dire_players.map(PlayerSpan), strings.story_lane_empty),
lane: localizedLane(strings)[this.lane],
});
}
}
class JungleStory {
constructor(match) {
this.players = match.players.filter(player => (player.lane === 4 || player.lane === 5) && !player.is_roaming);
this.lane = 4;
}
static exists(match) {
return match.players.filter(player => (player.lane === 4 || player.lane === 5) && !player.is_roaming).length > 0;
}
format() {
const { strings } = store.getState().app;
return renderSentence(strings.story_lane_jungle, {
players: formatList(this.players.map(PlayerSpan)),
});
}
}
class RoamStory {
constructor(match) {
this.players = match.players.filter(player => player.is_roaming);
this.lane = 6;
}
static exists(match) {
return match.players.filter(player => player.is_roaming).length > 0;
}
format() {
const { strings } = store.getState().app;
return renderSentence(strings.story_lane_roam, {
players: formatList(this.players.map(PlayerSpan)),
});
}
}
class LanesEvent extends StoryEvent {
constructor(match) {
super(10 * 60);
this.lanes = Object.keys(localizedLane({})).map(lane => new LaneStory(match, lane));
if (JungleStory.exists(match)) {
this.lanes.push(new JungleStory(match));
}
if (RoamStory.exists(match)) {
this.lanes.push(new RoamStory(match));
}
}
formatSentence() {
return this.format();
}
format() {
const { strings } = store.getState().app;
return [strings.story_lane_intro, <ul key="lanestory">{this.lanes.map(lane => <li key={lane.lane}>{lane.format()}</li>)}</ul>];
}
}
// returnes a formatted template when given a TowerEvent or BarracksEvent
const formatBuilding = (event) => {
const { strings } = store.getState().app;
let template = strings.story_building_destroy;
if (event.player) {
template = event.player.isRadiant === event.team ? strings.story_building_deny_player : strings.story_building_destroy_player;
}
return formatTemplate(template, {
building: event.localizedBuilding,
player: event.player ? PlayerSpan(event.player) : null,
});
};
class TowerEvent extends StoryEvent {
constructor(match, obj) {
super(obj.time);
if (obj.type === 'building_kill') {
const groups = /npc_dota_(good|bad)guys_tower(1|2|3|4)_?(bot|mid|top|)/.exec(obj.key);
this.team = groups[1] === 'good';
this.tier = parseInt(groups[2], 10);
this.lane = {
bot: 1,
mid: 2,
top: 3,
'': 2,
}[groups[3]];
this.player = match.players.find(player => player.player_slot === obj.player_slot);
} else if (obj.type === 'CHAT_MESSAGE_TOWER_KILL' || obj.type === 'CHAT_MESSAGE_TOWER_DENY') {
this.player = match.players.find(player => player.player_slot === obj.player_slot);
this.team = obj.type === 'CHAT_MESSAGE_TOWER_DENY' ? this.player.isRadiant : obj.team !== 2;
}
}
get localizedBuilding() {
const { strings } = store.getState().app;
const template = this.tier === undefined ? strings.story_tower_simple : strings.story_tower;
return formatTemplate(template, {
team: TeamSpan(this.team),
tier: this.tier,
lane: localizedLane(strings)[this.lane],
});
}
format() {
return formatBuilding(this);
}
}
class BarracksEvent extends StoryEvent {
constructor(match, obj) {
super(obj.time);
if (obj.type === 'building_kill') {
const groups = /npc_dota_(good|bad)guys_(range|melee)_rax_(bot|mid|top)/.exec(obj.key);
this.team = groups[1] === 'good';
this.is_melee = groups[2] === 'melee';
this.lane = {
bot: 1,
mid: 2,
top: 3,
}[groups[3]];
this.player = match.players.find(player => player.player_slot === obj.player_slot);
} else if (obj.type === 'CHAT_MESSAGE_BARRACKS_KILL') {
this.team = obj.key >= 64;
this.key = obj.key < 64 ? obj.key : obj.key / 64;
const power = Math.log2(this.key);
this.is_melee = (power % 2) === 0;
this.lane = Math.floor(power / 2) + 1;
}
}
get localizedBuilding() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_barracks, {
team: TeamSpan(this.team),
lane: localizedLane(strings)[this.lane],
rax_type: this.is_melee ? strings.building_melee_rax : strings.building_range_rax,
});
}
format() {
return formatBuilding(this);
}
}
class BuildingListEvent extends StoryEvent {
constructor(buildingEvents) {
super(buildingEvents[0].time);
this.buildings = buildingEvents;
}
format() {
const { strings } = store.getState().app;
const buildingList = [];
[TEAM.radiant, TEAM.dire].forEach((team) => {
const towers = this.buildings.filter(building => building.team === team && building instanceof TowerEvent);
if (towers.length === 1) {
buildingList.push(towers[0].localizedBuilding);
} else if (towers.length > 1) {
buildingList.push(formatTemplate(strings.story_towers_n, {
team: TeamSpan(team),
n: towers.length,
}));
}
Object.keys(localizedLane(strings)).forEach((lane) => {
const barracks = this.buildings.filter(building => (
building.team === team && building instanceof BarracksEvent && building.lane === parseInt(lane, 10)));
if (barracks.length === 1) {
buildingList.push(barracks[0].localizedBuilding);
} else if (barracks.length === 2) {
buildingList.push(formatTemplate(strings.story_barracks_both, {
team: TeamSpan(team),
lane: localizedLane(strings)[lane],
}));
}
});
});
return formatTemplate(strings.story_building_list_destroy, { buildings: formatList(buildingList) });
}
}
const formatObjectiveEvents = (events) => {
let formatted = events.filter(event => !(event instanceof TowerEvent || event instanceof BarracksEvent));
const buildings = events.filter(event => event instanceof TowerEvent || event instanceof BarracksEvent);
if (buildings.length <= 1) {
formatted = formatted.concat(buildings);
} else {
formatted.push(new BuildingListEvent(buildings));
}
return formatList(formatted.map(event => event.format()));
};
class TeamfightEvent extends StoryEvent {
constructor(match, fight) {
super(fight.start);
this.time_end = fight.end;
this.winning_team = fight.radiant_gold_advantage_delta >= 0; // is_radiant value basically
this.gold_delta = Math.abs(fight.radiant_gold_advantage_delta);
const deaths = fight.players
.map((player, i) => ({ player: match.players[i], count: player.deaths }))
.filter(death => death.count > 0);
this.win_dead = deaths.filter(death => death.player.isRadiant === this.winning_team);
this.lose_dead = deaths.filter(death => death.player.isRadiant !== this.winning_team);
this.during_events = [];
this.after_events = [];
}
formatSentence() {
return this.format();
}
format() {
const { strings } = store.getState().app;
let template = strings.story_teamfight;
if (this.win_dead.length === 0) {
template = strings.story_teamfight_none_dead;
} else if (this.lose_dead.length === 0) {
template = strings.story_teamfight_none_dead_loss;
}
let formatted = [renderSentence(template, {
winning_team: TeamSpan(this.winning_team),
net_change: GoldSpan(this.gold_delta),
win_dead: formatList(this.win_dead.map(death => (
death.count === 1 ? PlayerSpan(death.player) : [PlayerSpan(death.player), `(x${death.count})`]))),
lose_dead: formatList(this.lose_dead.map(death => (
death.count === 1 ? PlayerSpan(death.player) : [PlayerSpan(death.player), `(x${death.count})`]))),
})];
if (this.during_events.length > 0) {
formatted = formatted.concat(renderSentence(
strings.story_during_teamfight,
{ events: formatObjectiveEvents(this.during_events) },
));
}
if (this.after_events.length > 0) {
formatted = formatted.concat(renderSentence(
strings.story_after_teamfight,
{ events: formatObjectiveEvents(this.after_events) },
));
}
return formatted;
}
}
class ExpensiveItemEvent extends StoryEvent {
constructor(match, price) {
super(match.duration);
this.price_limit = price;
match.players.forEach((player) => {
Object.entries(player.first_purchase_time).forEach(([item, time]) => {
if (item in items && items[item].cost >= price && time < this.time) {
this.time = time;
this.item = item;
this.player = player;
}
});
});
}
static exists(match, price) {
let found = false;
match.players.forEach((player) => {
Object.keys(player.first_purchase_time).forEach((item) => {
if (item in items && items[item].cost >= price) {
found = true;
}
});
});
return found;
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_expensive_item, {
time: formatSeconds(this.time),
player: PlayerSpan(this.player),
item: ItemSpan(this.item),
price_limit: GoldSpan(this.price_limit),
});
}
}
class ItemPurchaseEvent extends StoryEvent {
constructor(player, purchase) {
super(purchase.time);
this.player = player;
this.item = purchase.key;
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_item_purchase, {
time: formatSeconds(this.time),
player: PlayerSpan(this.player),
item: ItemSpan(this.item),
});
}
}
class TimeMarkerEvent extends StoryEvent {
constructor(match, minutes) {
super(minutes * 60);
this.radiant_gold = match.players
.filter(player => player.isRadiant)
.map(player => player.gold_t[minutes])
.reduce((a, b) => a + b, 0);
this.dire_gold = match.players
.filter(player => !player.isRadiant)
.map(player => player.gold_t[minutes])
.reduce((a, b) => a + b, 0);
this.radiant_percent = Math.round(100 * this.radiant_gold / (this.radiant_gold + this.dire_gold));
this.dire_percent = 100 - this.radiant_percent;
}
formatSentence() {
return this.format();
}
get minutes() {
return this.time / 60;
}
format() {
const { strings } = store.getState().app;
return [
<h3 key={`minute_${this.minutes}_subheading`} style={{ marginBottom: 0 }}>
{formatTemplate(strings.story_time_marker, { minutes: this.minutes })}
</h3>,
<StyledStoryNetWorthText key={`minute_${this.minutes}_networth_text`}>
<StyledStoryNetWorthText width={this.radiant_percent}>
{GoldSpan(this.radiant_gold)}
</StyledStoryNetWorthText>
<StyledStoryNetWorthText style={{ backgroundColor: 'rgba(0,0,0,0)' }} color={this.radiant_gold > this.dire_gold ? constants.colorGreen : constants.colorRed} left={this.radiant_percent}>
{formatTemplate(strings.story_networth_diff, {
percent: Math.abs(this.radiant_percent - this.dire_percent),
gold: GoldSpan(Math.abs(this.radiant_gold - this.dire_gold)),
})}
</StyledStoryNetWorthText>
<StyledStoryNetWorthText width={this.dire_percent}>
{GoldSpan(this.dire_gold)}
</StyledStoryNetWorthText>
</StyledStoryNetWorthText>,
<StyledStoryNetWorthBar key={`minute_${this.minutes}_networth`}>
<StyledStoryNetWorthText color={constants.colorGreen} width={this.radiant_percent} />
<StyledStoryNetWorthText color={constants.colorRed} width={this.dire_percent} />
</StyledStoryNetWorthBar>,
];
}
}
class GameoverEvent extends StoryEvent {
constructor(match) {
super(match.duration);
this.winning_team = match.radiant_win;
this.radiant_score = match.radiant_score || match.players
.filter(player => player.isRadiant)
.map(player => player.kills)
.reduce((a, b) => a + b, 0);
this.dire_score = match.dire_score || match.players
.filter(player => !player.isRadiant)
.map(player => player.kills)
.reduce((a, b) => a + b, 0);
}
format() {
const { strings } = store.getState().app;
return formatTemplate(strings.story_gameover, {
duration: formatSeconds(this.time),
winning_team: TeamSpan(this.winning_team),
radiant_score: <font key="radiant_score" color={constants.colorGreen}>{this.radiant_score}</font>,
dire_score: <font key="dire_score" color={constants.colorRed}>{this.dire_score}</font>,
});
}
}
// Modified version of timeline data
const generateStory = (match) => {
let events = [];
// Intro
events.push(new IntroEvent(match));
// Prediction
let predExists = false;
match.players.forEach((player) => {
if (player.pred_vict === true) {
predExists = true;
}
});
if (predExists === true) {
events.push(new PredictionEvent(match, -89));
events.push(new PredictionEvent(match, -88));
}
// Firstblood
const fbIndex = match.objectives.findIndex(obj => obj.type === 'CHAT_MESSAGE_FIRSTBLOOD');
if (fbIndex > -1) {
events.push(new FirstbloodEvent(match, match.objectives[fbIndex]));
}
// Chat messages
const chatMessageEvents = match.chat
.filter(obj => obj.type === 'chat')
.map((obj, i, array) => new ChatMessageEvent(match, obj, i > 0 && array[i - 1]));
events = events.concat(chatMessageEvents);
// Aegis pickups
const aegisEvents = match.objectives
.filter(obj => obj.type === 'CHAT_MESSAGE_AEGIS' ||
obj.type === 'CHAT_MESSAGE_AEGIS_STOLEN' ||
obj.type === 'CHAT_MESSAGE_DENIED_AEGIS')
.map((obj, index) => new AegisEvent(match, obj, index));
// Roshan kills, team 2 = radiant, 3 = dire
events = events.concat(match.objectives
.filter(obj => obj.type === 'CHAT_MESSAGE_ROSHAN_KILL')
.map((obj, index) => new RoshanEvent(match, obj, index, aegisEvents)));
// Courier kills
events = events.concat(match.objectives
.filter(obj => obj.type === 'CHAT_MESSAGE_COURIER_LOST')
.map(obj => new CourierKillEvent(match, obj)));
// Teamfights
events = events.concat(match.teamfights && match.teamfights.length > 0 ? match.teamfights.map(fight => new TeamfightEvent(match, fight)) : []);
// Lanes (1=Bottom, 2=Middle, 3=Top) (jungle/roaming not considered a lane here)
if (match.duration > 10 * 60) {
events.push(new LanesEvent(match));
}
// New Buildings Events
match.objectives.filter(obj => obj.type === 'building_kill').forEach((obj) => {
if (obj.key.includes('tower')) {
events.push(new TowerEvent(match, obj));
} else if (obj.key.includes('rax')) {
events.push(new BarracksEvent(match, obj));
}
});
// Old Buildings Events
// Towers
events = events.concat(match.objectives
.filter(obj => obj.type === 'CHAT_MESSAGE_TOWER_KILL' || obj.type === 'CHAT_MESSAGE_TOWER_DENY')
.map(obj => new TowerEvent(match, obj)));
// Barracks
events = events.concat(match.objectives
.filter(obj => obj.type === 'CHAT_MESSAGE_BARRACKS_KILL')
.map(obj => new BarracksEvent(match, obj)));
// Expensive Item
if (ExpensiveItemEvent.exists(match, 4000)) {
events = events.concat(new ExpensiveItemEvent(match, 4000));
}
// Rapiers
match.players.forEach((player) => {
player.purchase_log.forEach((purchase) => {
if (purchase.key === 'rapier') {
events.push(new ItemPurchaseEvent(player, purchase));
}
});
});
// Time Markers
for (let min = 20; min < (match.duration / 60); min += 10) {
events.push(new TimeMarkerEvent(match, min));
}
// Gameover
events.push(new GameoverEvent(match));
// Sort by time
events.sort((a, b) => a.time - b.time);
// ////// Group events together now
// Group during events for teamfights
let lastFight = null;
for (let i = 0; i < events.length; i += 1) {
if (events[i] instanceof TeamfightEvent) {
lastFight = events[i];
} else if (lastFight !== null && (events[i] instanceof RoshanEvent || events[i] instanceof TowerEvent || events[i] instanceof BarracksEvent)) {
if (events[i].time < lastFight.time_end) { // During
lastFight.during_events.push(events[i]);
events.splice(i, 1);
i -= 1;
} else if (events[i].time < lastFight.time_end + (60 * 2)) { // After (within 2 minutes)
lastFight.after_events.push(events[i]);
events.splice(i, 1);
i -= 1;
}
}
}
// Remove any unneeded Time Markers
events = events.filter((event, i, list) => i === (list.length - 1) || !(event instanceof TimeMarkerEvent && list[i + 1] instanceof TimeMarkerEvent));
return events;
};
class MatchStory extends React.Component {
static propTypes = {
match: PropTypes.shape({}),
strings: PropTypes.shape({}),
}
renderEvents() {
const events = generateStory(this.props.match);
return (<StyledStoryWrapper key="matchstory">{events.map(event => event.render())}</StyledStoryWrapper>);
}
render() {
const { strings } = this.props;
try {
return this.renderEvents();
} catch (e) {
let exmsg = 'Story Tab Error:\n';
if (e.message) {
exmsg += e.message;
}
if (e.stack) {
exmsg += ` | stack: ${e.stack}`;
}
console.error(exmsg); // eslint-disable-line no-console
return (<div>{strings.story_error}</div>);
}
}
}
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(MatchStory);
| odota/web/src/components/Match/MatchStory.jsx/0 | {
"file_path": "odota/web/src/components/Match/MatchStory.jsx",
"repo_id": "odota",
"token_count": 12459
} | 296 |
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Slider from 'material-ui/Slider';
import rangeStep from 'lodash/fp/rangeStep';
import debounce from 'lodash/fp/debounce';
import styled from 'styled-components';
import { formatSeconds } from '../../../utility';
import VisionFilter from './VisionFilter';
import VisionItems from './VisionItems';
import VisionMap from './VisionMap';
import VisionLog from './VisionLog';
import constants from '../../constants';
import Heading from '../../Heading';
import config from '../../../config';
const Styled = styled.div`
.visionLog {
margin-top: 30px;
}
.visionSliderText {
text-align: center;
width: 200px;
margin: 5px auto;
text-transform: uppercase;
color: ${constants.colorMutedLight};
}
.sliderTicks {
position: relative;
height: 30px;
margin-top: 33px;
margin-bottom: -33px;
font-size: ${constants.fontSizeTiny};
border-color: ${constants.sliderTicksColor};
color: ${constants.sliderTicksColor};
& .sliderTick {
position: absolute;
display: inline-block;
height: 100%;
padding: 0 0.4em;
border-width: 0;
border-color: inherit;
border-style: solid;
border-left-width: 1px;
cursor: pointer;
transition: color 150ms ease, border-color 150ms ease;
&.active {
border-color: ${constants.sliderTicksColorActive};
color: ${constants.sliderTicksColorActive};
}
}
}
.visionFilter {
box-sizing: border-box;
display: flex;
flex-wrap: wrap;
margin: 50px -0.5rem 0;
& .tableWrapper {
box-sizing: border-box;
flex-basis: 50%;
max-width: 50%;
padding-right: 0.5rem;
padding-left: 0.5rem;
@media only screen and (max-width: 1024px) {
flex-basis: 100%;
max-width: 100%;
}
}
& table th > div {
text-align: left !important;
}
& table td > img {
margin-left: -2px;
}
}
`;
/* eslint-disable jsx-a11y/anchor-is-valid */
const SliderTicks = ({
ticks, onTickClick, value, min, max,
}) => (
<Styled>
<div className="sliderTicks">
{ticks.map((tick) => {
const percent = 100 * ((tick - min) / (max - min));
const classNames = ['sliderTick'];
if (tick <= value) {
classNames.push('active');
}
return (
<a
role="link"
tabIndex={0}
key={tick}
onClick={() => onTickClick(tick)}
onKeyPress={() => {}}
className={classNames.join(' ')}
style={{ left: `${percent}%` }}
>
{formatSeconds(tick)}
</a>
);
})}
</div>
</Styled>
);
SliderTicks.propTypes = {
value: PropTypes.shape({}),
ticks: PropTypes.arrayOf({}),
onTickClick: PropTypes.func,
min: PropTypes.number,
max: PropTypes.number,
};
const alive = (ward, time) => time === -90 || (time > ward.entered.time && (!ward.left || time < ward.left.time));
// const team = (ward, teams) => (teams.radiant && ward.player < 5) || (teams.dire && ward.player > 4);
// Currently always return true for team since we're just using it as a mass select-deselect
// const isTeam = () => true;
class Vision extends React.Component {
static propTypes = {
match: PropTypes.shape({
duration: PropTypes.number,
wards_log: PropTypes.arrayOf({}),
}),
strings: PropTypes.shape({}),
sponsorIcon: PropTypes.string,
sponsorURL: PropTypes.string,
};
constructor(props) {
super(props);
this.sliderMin = -90;
this.sliderMax = props.match.duration;
this.state = {
currentTick: -90,
teams: {
radiant: true,
dire: true,
},
players: {
observer: Array(...new Array(10)).map(() => true),
sentry: Array(...new Array(10)).map(() => true),
},
};
this.ticks = this.computeTick();
this.handleViewportChange = debounce(50, this.viewportChange);
}
onCheckAllWardsTeam(index, end) {
const { players } = this.state;
const [observer, sentry] = ['observer', 'sentry'];
const allWardsTeam = players[observer].slice(index, end).concat(players[sentry].slice(index, end));
return !(allWardsTeam.indexOf(true) === -1);
}
setPlayer(player, type, value) {
const { players } = this.state;
const newArray = players[type];
newArray[player] = value;
const index = player < 5 ? 0 : 5;
const end = index + 5;
const newTeam = this.onCheckAllWardsTeam(index, end);
this.setState({ ...this.state, teams: { ...this.state.teams, [index === 0 ? 'radiant' : 'dire']: newTeam }, players: { ...this.state.players, [type]: newArray } });
}
setTeam(team, value) {
const start = team === 'radiant' ? 0 : 5;
const end = start + 5;
const newPlayerObs = this.state.players.observer;
const newPlayerSentry = this.state.players.sentry;
for (let i = start; i < end; i += 1) {
newPlayerObs[i] = value;
newPlayerSentry[i] = value;
}
const newState = { ...this.state, teams: { ...this.state.teams, [team]: value }, players: { observer: newPlayerObs, sentry: newPlayerSentry } };
this.setState(newState);
}
setTypeWard(index, ward) {
const { players } = this.state;
const end = index + 5;
const checked = (players[ward].slice(index, end).indexOf(true) !== -1);
for (let i = index; i < end; i += 1) {
players[ward][i] = !checked;
}
const newTeam = this.onCheckAllWardsTeam(index, end);
const newState = { ...this.state, teams: { ...this.state.teams, [index === 0 ? 'radiant' : 'dire']: newTeam }, players };
this.setState(newState);
}
checkedTypeWard(index, ward) {
return (this.state.players[ward].slice(index, index + 5).indexOf(true) !== -1);
}
computeTick() {
const interval = 10 * 60; // every 10 minutes interval
return rangeStep(interval, 0, this.sliderMax);
}
viewportChange(value) {
this.setState({ ...this.state, currentTick: value });
}
visibleData() {
const self = this;
const filter = ward => alive(ward, self.state.currentTick) && self.state.players[ward.type][ward.player];
return this.props.match.wards_log.filter(filter);
}
render() {
const visibleWards = this.visibleData();
const {
match, strings, sponsorIcon, sponsorURL,
} = this.props;
return (
<div>
<div style={{ display: 'flex', flexWrap: 'wrap' }}>
<div style={{ margin: '10px', flexGrow: '1' }}>
<VisionMap match={match} wards={visibleWards} strings={strings} />
</div>
<div style={{ flexGrow: '2' }}>
<Heading
buttonLabel={config.VITE_ENABLE_GOSUAI ? strings.gosu_vision : null}
buttonTo={`${sponsorURL}Vision`}
buttonIcon={sponsorIcon}
/>
<div className="visionSliderText">
{this.state.currentTick === -90 ? strings.vision_all_time : formatSeconds(this.state.currentTick)}
</div>
<SliderTicks
value={this.state.currentTick}
min={this.sliderMin}
max={this.sliderMax}
onTickClick={tick => this.handleViewportChange(tick)}
ticks={this.ticks}
/>
<Slider
value={this.state.currentTick}
min={this.sliderMin}
max={this.sliderMax}
step={5}
disableFocusRipple
onChange={(e, value) => this.handleViewportChange(value)}
/>
<VisionFilter match={match} parent={this} strings={strings} />
</div>
</div>
<VisionItems match={match} strings={strings} />
<VisionLog match={match} wards={visibleWards} strings={strings} />
</div>
);
}
}
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(Vision);
| odota/web/src/components/Match/Vision/index.jsx/0 | {
"file_path": "odota/web/src/components/Match/Vision/index.jsx",
"repo_id": "odota",
"token_count": 3327
} | 297 |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Avatar from 'material-ui/Avatar';
import Badge from 'material-ui/Badge';
import styled from 'styled-components';
import { Facebook } from 'react-content-loader';
import { rankTierToString } from '../../../utility';
import Error from '../../Error';
import PlayerStats from './PlayerStats';
import PlayerBadges from './PlayerBadges';
import PlayerButtons from './PlayerButtons';
import constants from '../../constants';
const Styled = styled.div`
width: 100vw;
margin: 0px -50vw;
position: relative;
left: 50%;
right: 50%;
display: grid;
padding-top: 35px;
background-color: rgba(14,84,113,37%);
grid-template-columns: 1fr minmax(min-content, ${constants.appWidth}px) 1fr;
.container {
display: flex;
flex-direction: column;
justify-content: center;
padding-bottom: 10px;
grid-column: 2;
}
.playerName {
color: rgba(245, 245, 245, 0.870588);
font-size: 28px;
text-align: center;
}
.titleNameButtons {
display: flex;
flex-direction: row;
justify-content: flex-start;
flex-wrap: wrap;
@media only screen and (max-width: 768px) {
flex-direction: column;
align-items: center;
}
}
.imageContainer {
display: flex;
flex-direction: column;
justify-content: center;
}
.overviewAvatar {
box-shadow: 0 0 15px 2px rgba(0, 0, 0, 0.4);
@media only screen and (max-width: 768px) {
margin-left: 0 !important;
}
}
.icon {
fill: ${constants.colorMutedLight} !important;
}
.topContainer {
display: flex;
flex-direction: row;
@media only screen and (max-width: 768px) {
flex-direction: column;
align-items: center;
}
}
.topButtons {
margin-left: auto;
}
.playerInfo {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.registered {
width: 18px;
height: 18px;
position: relative;
&[data-hint-position="top"] {
&::before {
top: -7px;
margin-left: 3px;
}
&::after {
margin-bottom: 7px;
margin-left: -7px;
}
}
}
.rankTierContainer {
display: flex;
flex-direction: column;
justify-content: center;
}
.dotaPlusMedal {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
-webkit-filter: drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3))
drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3));
filter: drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3))
drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3));
@media only screen and (max-width: 768px) {
flex-wrap: nowrap;
}
&[data-hint-position="top"] {
&::after {
margin-bottom: 3px;
margin-left: 52px;
}
&::before {
top: -3px;
margin-left: 57px;
}
}
& img {
width: 65px;
height: 75px;
}
}
.rankMedal {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
margin: 0 25px;
-webkit-filter: drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3))
drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3));
filter: drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3))
drop-shadow(2px -2px 2px rgba(0, 0, 0, 0.3));
&[data-hint-position="top"] {
&::after {
margin-bottom: 3px;
margin-left: 52px;
}
&::before {
top: -3px;
margin-left: 57px;
}
}
& img {
width: 124px;
height: 124px;
}
&-icon {
}
&-board {
position: absolute;
align-self: center;
margin-top: 80px;
margin-left: 1px;
font-size: 22px;
color: #ECD9C8;
text-shadow: 2px 2px 2px black;
}
&-star {
position: absolute;
}
}
`;
const LARGE_IMAGE_SIZE = 124;
const getRegistrationBadge = (registered, strings) => registered && (
<div
className="registered"
data-hint={strings.tooltip_registered_user}
data-hint-position="top"
/>
);
const getDotaPlusBadge = (plus, strings) => plus && (
<div
className="dotaPlusMedal"
data-hint={strings.tooltip_dotaplus}
data-hint-position="top"
>
<img
src="/assets/images/dota2/dota_plus_icon.png"
alt="Dota Plus icon"
/>
</div>
);
const getRankTierMedal = (rankTier, leaderboardRank) => {
let medalElement = null;
const imgDescription = rankTierToString(rankTier);
if (rankTier) { // if the players ranktier is 0 they are uncalibrated
let iconPath;
if (leaderboardRank) { // if the player is on leaderboard ie. immortal
if (leaderboardRank <= 10) { // top 10 and top 100 positions have different icons
iconPath = '/assets/images/dota2/rank_icons/rank_icon_8c.png';
} else if (leaderboardRank <= 100) {
iconPath = '/assets/images/dota2/rank_icons/rank_icon_8b.png';
} else {
iconPath = '/assets/images/dota2/rank_icons/rank_icon_8.png';
}
medalElement = (
<div className="rankTierContainer">
<div className="rankMedal" data-hint={imgDescription} data-hint-position="top">
<img className="rankMedal-icon" src={iconPath} alt="Immortal medal icon" />
{leaderboardRank && <span className="rankMedal-board">{leaderboardRank}</span>}
</div>
</div>
);
} else { // everyone who isn't immortal has an icon and some number of stars
const intRankTier = parseInt(rankTier, 10);
let star = intRankTier % 10;
if (star < 1) { // I'm not sure if ranktier can give a number outside this range but better safe than sorry
star = 1;
} else if (star > 7) {
star = 7;
}
const starPath = `/assets/images/dota2/rank_icons/rank_star_${star}.png`;
iconPath = `/assets/images/dota2/rank_icons/rank_icon_${Math.floor(intRankTier / 10)}.png`;
medalElement = (
<div className="rankTierContainer">
<div className="rankMedal" data-hint={imgDescription} data-hint-position="top">
<img className="rankMedal-icon" src={iconPath} alt="Ranked medal icon" />
{(star !== 0) ? <img className="rankMedal-star" src={starPath} alt="Ranked medal stars " /> : ''}
{leaderboardRank && <span className="rankMedal-board">{leaderboardRank}</span>}
</div>
</div>
);
}
} else { // uncalibrated players
const iconPath = '/assets/images/dota2/rank_icons/rank_icon_0.png';
medalElement = (
<div className="rankTierContainer">
<div className="rankMedal" data-hint={imgDescription} data-hint-position="top">
<img className="rankMedal-icon" src={iconPath} alt="Uncalibrated medal" />
</div>
</div>
);
}
return medalElement;
};
const PlayerHeader = ({
playerName,
officialPlayerName,
playerId,
picture,
registered,
plus,
loading,
error,
small,
playerSoloCompetitiveRank,
loggedInUser,
rankTier,
leaderboardRank,
strings,
}) => {
if (error) {
return <Error />;
}
if (loading) {
return <Facebook primaryColor="#666" secondaryColor="#ecebeb" width={400} height={60} animate />;
}
let badgeStyle = {
fontSize: 20,
top: 5,
left: 40,
background: registered ? constants.colorGreen : 'transparent',
width: 18,
height: 18,
};
const avatarStyle = {
marginLeft: small ? 30 : 0,
marginRight: small ? 30 : 0,
};
if (!small) {
badgeStyle = {
...badgeStyle,
marginLeft: -1 * (LARGE_IMAGE_SIZE / 2) * 0.75,
};
}
return (
<Styled>
<div className="container">
<div className="topContainer">
<div className="imageContainer">
<Badge
badgeContent={getRegistrationBadge(registered, strings)}
badgeStyle={badgeStyle}
style={{
margin: 0,
padding: 0,
}}
>
<Avatar
src={picture}
style={avatarStyle}
size={LARGE_IMAGE_SIZE}
className="overviewAvatar"
/>
</Badge>
</div>
<div className="playerInfo">
<div className="titleNameButtons">
<span className="playerName">{officialPlayerName || playerName}</span>
<PlayerBadges playerId={playerId} />
</div>
<PlayerStats playerId={playerId} loggedInId={loggedInUser && String(loggedInUser.account_id)} compact={!small} />
<PlayerButtons playerId={playerId} playerSoloCompetitiveRank={playerSoloCompetitiveRank} compact={!small} />
</div>
<div style={{ display: 'flex' }}>
{getDotaPlusBadge(plus, strings)}
{getRankTierMedal(rankTier, leaderboardRank)}
</div>
</div>
</div>
</Styled>
);
};
PlayerHeader.propTypes = {
playerName: PropTypes.string,
officialPlayerName: PropTypes.string,
playerId: PropTypes.string,
picture: PropTypes.string,
registered: PropTypes.string,
plus: PropTypes.string,
loading: PropTypes.bool,
error: PropTypes.string,
small: PropTypes.bool,
playerSoloCompetitiveRank: PropTypes.number,
loggedInUser: PropTypes.shape({}),
rankTier: PropTypes.number,
leaderboardRank: PropTypes.number,
strings: PropTypes.shape({}),
};
const mapStateToProps = state => ({
loading: state.app.player.loading,
error: state.app.player.error,
playerName: (state.app.player.data.profile || {}).personaname,
officialPlayerName: (state.app.player.data.profile || {}).name,
playerSoloCompetitiveRank: state.app.player.data.solo_competitive_rank,
picture: (state.app.player.data.profile || {}).avatarfull,
registered: (state.app.player.data.profile || {}).last_login,
plus: (state.app.player.data.profile || {}).plus,
small: state.browser.greaterThan.small,
loggedInUser: state.app.metadata.data.user,
rankTier: state.app.player.data.rank_tier,
leaderboardRank: state.app.player.data.leaderboard_rank,
strings: state.app.strings,
});
export default connect(mapStateToProps)(PlayerHeader);
| odota/web/src/components/Player/Header/PlayerHeader.jsx/0 | {
"file_path": "odota/web/src/components/Player/Header/PlayerHeader.jsx",
"repo_id": "odota",
"token_count": 4126
} | 298 |
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import GaugeChart from './../../../Visualizations/GaugeChart';
import constants from '../../../constants';
const Styled = styled.div`
border: 1px solid rgb(0, 0, 0, 0.12);
background-color: rgba(255,255,255,0.03);
overflow: hidden;
position: relative;
.gauge-container {
justify-content: center;
display: flex;
flex-wrap: wrap;
}
@media only screen and (min-width: ${constants.appWidth}px) {
.gauge-chart:nth-child(even)::after {
content: "";
width: 2px;
height: 300px;
position: absolute;
background: rgb(39, 39, 58);
bottom: -50px;
right: -13px;
}
}
`;
const Summary = ({ data }) => (
<Styled>
<div className="gauge-container">
{data.map(el => <GaugeChart number={el.matches} percent={el.winPercent} caption={el.category} />)}
</div>
</Styled>
);
Summary.propTypes = {
data: PropTypes.arrayOf({}),
};
export default Summary;
| odota/web/src/components/Player/Pages/Overview/CountsSummary.jsx/0 | {
"file_path": "odota/web/src/components/Player/Pages/Overview/CountsSummary.jsx",
"repo_id": "odota",
"token_count": 448
} | 299 |