text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
package com.aitongyi.web.dao.conf;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
/**
* Created by admin on 16/8/8.
*/
@Configuration
@EnableTransactionManagement
public class DatabaseConfig {
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${db.url}")
private String dbUrl;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
@Value("${db.maxtotal}")
private Integer maxTotal;
@Value("${db.minidle}")
private Integer minIdle;
@Value("${db.maxidle}")
private Integer maxIdle;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
logger.info("mysql url:"+dbUrl);
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUrl(dbUrl);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxTotal(maxTotal);
dataSource.setMinIdle(minIdle);
dataSource.setMaxIdle(maxIdle);
return dataSource;
}
@Bean
public DataSourceTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
}
| chwshuang/web/dao/src/main/java/com/aitongyi/web/dao/conf/DatabaseConfig.java/0 | {
"file_path": "chwshuang/web/dao/src/main/java/com/aitongyi/web/dao/conf/DatabaseConfig.java",
"repo_id": "chwshuang",
"token_count": 747
} | 159 |
package web
import (
"bufio"
"fmt"
"net"
"net/http"
)
// ResponseWriter includes net/http's ResponseWriter and adds a StatusCode() method to obtain the written status code.
// A ResponseWriter is sent to handlers on each request.
type ResponseWriter interface {
http.ResponseWriter
http.Flusher
http.Hijacker
http.CloseNotifier
// StatusCode returns the written status code, or 0 if none has been written yet.
StatusCode() int
// Written returns whether the header has been written yet.
Written() bool
// Size returns the size in bytes of the body written so far.
Size() int
}
type appResponseWriter struct {
http.ResponseWriter
statusCode int
size int
}
// Don't need this yet because we get it for free:
func (w *appResponseWriter) Write(data []byte) (n int, err error) {
if w.statusCode == 0 {
w.statusCode = http.StatusOK
}
size, err := w.ResponseWriter.Write(data)
w.size += size
return size, err
}
func (w *appResponseWriter) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
func (w *appResponseWriter) StatusCode() int {
return w.statusCode
}
func (w *appResponseWriter) Written() bool {
return w.statusCode != 0
}
func (w *appResponseWriter) Size() int {
return w.size
}
func (w *appResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("the ResponseWriter doesn't support the Hijacker interface")
}
return hijacker.Hijack()
}
func (w *appResponseWriter) CloseNotify() <-chan bool {
return w.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
func (w *appResponseWriter) Flush() {
flusher, ok := w.ResponseWriter.(http.Flusher)
if ok {
flusher.Flush()
}
}
| gocraft/web/response_writer.go/0 | {
"file_path": "gocraft/web/response_writer.go",
"repo_id": "gocraft",
"token_count": 590
} | 160 |
---
title: JavaScript
eleventyNavigation:
key: JavaScript
---
JavaScript is a scripting language for the web. It was invented in 1993 by Brendan Eich at Mozilla (the makers of the Firefox browser). The language standard is maintained by [ECMA International](http://www.ecma-international.org/), a technology standards organization, so you'll sometimes see the terms "JavaScript" (a trademark of Oracle Corporation) or <abbr>JS</abbr> and "ECMAScript" or <abbr>ES</abbr> used interchangeably. You can use JavaScript to dynamically manipulate the HTML document.
The purpose of this document isn't to be a comprehensive introduction to JavaScript, rather, to introduce some programming patterns using modern JavaScript features that we've found to be useful when writing standards-based web applications. Check out [MDN's JavaScript documentation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript) for a refresher before continuing.
## Composing Classes with JavaScript Mixins
> A mixin is an abstract subclass; i.e. a subclass definition that may be applied to different superclasses to create a related family of modified classes.
>
> - Gilad Bracha and William Cook, [Mixin-based Inheritance](http://www.bracha.org/oopsla90.pdf)
Some [object-oriented](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS) programming languages allow for "multiple inheritance", or the notion that a class can simultaneously inherit from two or more other classes. A "Baker" class might inherit simultaneously from the "Cook" and "CarbLover" classes. JavaScript does not allow multiple inheritances in `class` syntax. All JavaScript classes that extend other classes may only have one ancestor.
This presents a problem when you want to share some behaviour among classes which already inherit from a base class.
Let's take for example Logging. Imagine you have 3 Pages
```
+-----------+
+---->+ PageRed |
| +-----------+
|
+------------+ +------+ | +-----------+
| AppElement +-->+ Page +------>+ PageGreen |
+------------+ +------+ | +-----------+
|
| +-----------+
+---->+ PageBlue |
+-----------+
```
```js
// Assume AppElement is a base class for all elements of the app
class Page extends AppElement {
/*...*/
}
class PageRed extends Page {
static color = 'red';
}
class PageGreen extends Page {
static color = 'green';
}
class PageBlue extends Page {
static color = 'blue';
}
```
### Single Inheritance
Say we wanted to log the page color whenever someone enters the red page. Using JavaScript's single inheritance, we could define a `LoggedPageRed` class that inherits from `PageRed`.
```
+-----------+ +---------------+
+---->+ PageRed +---->+ LoggedPageRed |
| +-----------+ +---------------+
|
+------------+ +------+ | +-----------+
| AppElement +-->+ Page +------>+ PageGreen |
+------------+ +------+ | +-----------+
|
| +-----------+
+---->+ PageBlue |
+-----------+
```
```js
class LoggedPageRed extends PageRed {
connectedCallback() {
super.connectedCallback?.();
console.log(this.constructor.color);
}
}
```
This works fine for the red page, but what if we needed implement logging for _both_ the red and green pages, but _not_ the blue page. There's nothing about the logging code which is specific to the red instance of `Page`. How could be generalize the logging behaviour so as to apply it to any kind of class?
- We can't put the logic in `Page` as blue inherits from `Page`, and it shouldn't log
- We can't reuse the logic from `LoggedPageRed` in some new `LoggedPageGreen` class, as we can not extend from multiple sources.
- We could implement a new intermediary base class `PageThatLogs`, but down the line we might want to separate "logging" behaviour" from "pageness".
We need a way to define "A thing that logs" which is separate from "A thing that is a Page"
```
+---------------------+
+---->+ PageRed that logs |
| +---------------------+
|
+------------+ +------+ | +---------------------+
| AppElement +-->+ Page +------>+ PageGreen that logs |
+-----+------+ +------+ | +---------------------+
| |
| | +-----------+
| +---->+ PageBlue |
| +-----------+
|
| +---------------------+
+------------------------>+ Element that logs |
+---------------------+
```
### Class Mixins
JS class mixins let us share behaviours using class syntax. At it's heart, class mixins are function composition. JS classes are functions, and class mixins are higher order functions on classes.
You define a class mixin like you would any other function.
```js
const LoggingMixin = superclass =>
class extends superclass {
connectedCallback() {
super.connectedCallback?.();
console.log(this.constructor.color);
}
};
```
And you apply it like you would any other function
```js
class PageRed extends LoggingMixin(Page) {}
class PageGreen extends LoggingMixin(Page) {}
class PageBlue extends Page {}
```
You can use multiple mixins as well - function composition!
```js
class PageRed extends LoggingMixin(PageRouterMixin(StateStoreMixin(Page))) {
/*...*/
}
```
With that approach we can extract logic into a separate code piece we can use where needed.
### Read More
For a more in-depth technical explanation please read [Real Mixins with JavaScript Classes](https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/).
You can see the full blog post [Using JavaScript Mixins The Good Parts](https://dev.to/open-wc/using-javascript-mixins-the-good-parts-4l60).
| modernweb-dev/web/docs-drafts/faqs/javascript.md/0 | {
"file_path": "modernweb-dev/web/docs-drafts/faqs/javascript.md",
"repo_id": "modernweb-dev",
"token_count": 2262
} | 161 |
# Slack
You can also find us on the Lit & Friends Slack in the [#open-wc](https://lit-and-friends.slack.com/archives/CE6D9DN05) channel.
You can join the Lit & Friends Slack by visiting [https://lit.dev/slack-invite](https://lit.dev/slack-invite).
| modernweb-dev/web/docs/discover/slack.md/0 | {
"file_path": "modernweb-dev/web/docs/discover/slack.md",
"repo_id": "modernweb-dev",
"token_count": 86
} | 162 |
# Dev Server >> Plugins ||3
| modernweb-dev/web/docs/docs/dev-server/plugins/index.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/dev-server/plugins/index.md",
"repo_id": "modernweb-dev",
"token_count": 9
} | 163 |
# Test Runner >> Browser Launchers >> Browserstack ||60
Browser launchers for web test runner to run tests remotely on [Browserstack](https://www.browserstack.com/).
For modern browsers, we recommend using other browser launchers, as they are a lot faster. Browserstack is a good option for testing on older browser versions.
## Usage
Install the package:
```
npm i --save-dev @web/test-runner-browserstack
```
Add the browser launcher to your `web-test-runner.confg.mjs`:
```js
import { browserstackLauncher } from '@web/test-runner-browserstack';
// options shared between all browsers
const sharedCapabilities = {
// your username and key for browserstack, you can get this from your browserstack account
// it's recommended to store these as environment variables
'browserstack.user': process.env.BROWSER_STACK_USERNAME,
'browserstack.key': process.env.BROWSER_STACK_ACCESS_KEY,
project: 'my project',
name: 'my test',
// if you are running tests in a CI, the build id might be available as an
// environment variable. this is useful for identifying test runs
// this is for example the name for github actions
build: `build ${process.env.GITHUB_RUN_NUMBER || 'unknown'}`,
};
export default {
// how many browsers to run concurrently in browserstack. increasing this significantly
// reduces testing time, but your subscription might limit concurrent connections
concurrentBrowsers: 2,
// amount of test files to execute concurrently in a browser. the default value is based
// on amount of available CPUs locally which is irrelevant when testing remotely
concurrency: 6,
browsers: [
// create a browser launcher per browser you want to test
// you can get the browser capabilities from the browserstack website
browserstackLauncher({
capabilities: {
...sharedCapabilities,
browserName: 'Chrome',
os: 'Windows',
os_version: '10',
},
}),
browserstackLauncher({
capabilities: {
...sharedCapabilities,
browserName: 'Safari',
browser_version: '11.1',
os: 'OS X',
os_version: 'High Sierra',
},
}),
browserstackLauncher({
capabilities: {
...sharedCapabilities,
browserName: 'IE',
browser_version: '11.0',
os: 'Windows',
os_version: '7',
},
}),
],
};
```
## Configuration
The Browserstack launcher takes two properties, `capabilities` and `localOptions`.
`capabilities` are the selenium capabilities used to configure the browser to launch in Browserstack. You can generate most of these on the Saucelabs. It must contain a `browserstack.user` and `browserstack.key` property to authenticate with Browserstack, as well as `name`, `build` and `project` to identify the test run.
`localOptions` are options to configure the [browserstack-local](https://www.npmjs.com/package/browserstack-local) proxy. For most use cases, you don't need to configure this property.
| modernweb-dev/web/docs/docs/test-runner/browser-launchers/browserstack.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/test-runner/browser-launchers/browserstack.md",
"repo_id": "modernweb-dev",
"token_count": 914
} | 164 |
# Test Runner >> Reporters ||8
| modernweb-dev/web/docs/docs/test-runner/reporters/index.md/0 | {
"file_path": "modernweb-dev/web/docs/docs/test-runner/reporters/index.md",
"repo_id": "modernweb-dev",
"token_count": 9
} | 165 |
# Dev Server >> Browser support ||80
Web Dev Server is based on development using features available in modern browsers. With the help of plugins, we can use the dev server on older browsers as well.
At a high level, we make a split between browsers that support modules and those that don't. We consider a browser as supporting es modules when it supports module scripts, dynamic imports, and `import.meta`.
Browsers that support es module are:
- Chrome 64 (and equivalent chromium based browsers)
- Firefox 67
- Safari 11.1 and higher.
## JS syntax
When testing on older browsers, you might use javascript features that are not yet available. We can use the [esbuild plugin](../../docs/dev-server/plugins/esbuild.md) to transform javascript using the the `target` option. Esbuild supports javascript down to es2016, making it unsuitable for legacy browsers like IE11 which need es5 support.
We recommended setting the target to `auto`. This will skip work on the latest versions of chrome and firefox while transforming modern JS syntax on older browsers and safari (safari is excluded because the release cycle is slower).
The easiest way to set this is by using the command line flag.
Make sure you install the plugin first:
```
npm i --save-dev @web/dev-server @web/dev-server-esbuild
```
Then, set the command line flag:
```
npx web-dev-server --open /demo/ --esbuild-target auto
```
If you're using new syntax that is not yet available on the latest chrome or firefox you can force the transformations as well using the `auto-always` flag:
```
npx web-dev-server --open /demo/ --esbuild-target auto-always
```
The target flag can also be set when using the plugin programmatically:
```js
import { esbuildPlugin } from '@web/dev-server-esbuild';
export default {
plugins: [esbuildPlugin({ target: 'auto', ts: true })],
};
```
Read more about the esbuild plugin [here](../../docs/dev-server/plugins/esbuild.md).
## Legacy browsers
If you need to test on browsers that don't support es modules and modern javascript, such as Internet Explorer 11, you can use the `@web/dev-server-legacy` plugin.
Install the plugin:
```
npm i --save-dev @web/dev-server @web/dev-server-esbuild
```
Add a `web-dev-server.config.mjs`:
```js
import { legacyPlugin } from '@web/dev-server-legacy';
export default {
plugins: [
// make sure this plugin is always last
legacyPlugin(),
],
};
```
This plugin will polyfill es modules, transform your code to es5, and add polyfills for common browser features.
Read more about the legacy plugin [here](../../docs/dev-server/plugins/legacy.md).
## Learn more
All the code is available on [github](https://github.com/modernweb-dev/example-projects/tree/master/guides/dev-server).
See the [documentation of @web/dev-server](../../docs/dev-server/overview.md).
| modernweb-dev/web/docs/guides/dev-server/browser-support.md/0 | {
"file_path": "modernweb-dev/web/docs/guides/dev-server/browser-support.md",
"repo_id": "modernweb-dev",
"token_count": 792
} | 166 |
export default 'moduleFeaturesA';
| modernweb-dev/web/integration/test-runner/tests/basic/browser-tests/module-features-a.js/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/basic/browser-tests/module-features-a.js",
"repo_id": "modernweb-dev",
"token_count": 8
} | 167 |
setTimeout(() => {
window.location.replace('/new-page/');
}, 100);
it('x', async function test() {
this.timeout(20000);
await new Promise(r => setTimeout(r, 10000));
});
| modernweb-dev/web/integration/test-runner/tests/location-change/browser-tests/fail-location-replace.test.js/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/location-change/browser-tests/fail-location-replace.test.js",
"repo_id": "modernweb-dev",
"token_count": 62
} | 168 |
import { BrowserLauncher, TestRunnerCoreConfig } from '@web/test-runner-core';
import { runTests } from '@web/test-runner-core/test-helpers';
import { legacyPlugin } from '@web/dev-server-legacy';
import { resolve } from 'path';
export function runParallelTest(
createConfig: () => Partial<TestRunnerCoreConfig> & { browsers: BrowserLauncher[] },
) {
describe('parallel', async function () {
it('can run tests in parallel', async () => {
const configA = createConfig();
const configB = createConfig();
await Promise.all([
runTests({
...configA,
files: [...(configA.files ?? []), resolve(__dirname, 'browser-tests', '*.test.js')],
plugins: [...(configA.plugins ?? []), legacyPlugin()],
}),
runTests({
...configB,
files: [...(configB.files ?? []), resolve(__dirname, 'browser-tests', '*.test.js')],
plugins: [...(configB.plugins ?? []), legacyPlugin()],
}),
]);
});
});
}
| modernweb-dev/web/integration/test-runner/tests/parallel/runParallelTest.ts/0 | {
"file_path": "modernweb-dev/web/integration/test-runner/tests/parallel/runParallelTest.ts",
"repo_id": "modernweb-dev",
"token_count": 394
} | 169 |
module.exports = { foo: 'bar' };
| modernweb-dev/web/packages/config-loader/test/fixtures/package-cjs/commonjs-in-.mjs/my-project.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/config-loader/test/fixtures/package-cjs/commonjs-in-.mjs/my-project.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 13
} | 170 |
# Web Dev Server Core
Core library powering the web server of [@web/test-runner](https://github.com/modernweb-dev/web/tree/master/packages/test-runner) and [@web/dev-server](https://github.com/modernweb-dev/web/tree/master/packages/dev-server)
See [our website](https://modern-web.dev/docs/dev-server/overview/) for full documentation.
| modernweb-dev/web/packages/dev-server-core/README.md/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/README.md",
"repo_id": "modernweb-dev",
"token_count": 106
} | 171 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const {
FSWatcher,
Koa,
Server,
WebSocket,
DevServer,
WebSocketsManager,
getRequestBrowserPath,
getRequestFilePath,
getResponseBody,
getHtmlPath,
isInlineScriptRequest,
PluginSyntaxError,
PluginError,
} = cjsEntrypoint;
export {
FSWatcher,
Koa,
Server,
WebSocket,
DevServer,
WebSocketsManager,
getRequestBrowserPath,
getRequestFilePath,
getResponseBody,
getHtmlPath,
isInlineScriptRequest,
PluginSyntaxError,
PluginError,
};
| modernweb-dev/web/packages/dev-server-core/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 213
} | 172 |
import { Middleware } from 'koa';
import path from 'path';
import { toBrowserPath } from '../utils.js';
import { Logger } from '../logger/Logger.js';
/**
* Serves index.html when a non-file request within the scope of the app index is made.
* This allows SPA routing.
*/
export function historyApiFallbackMiddleware(
appIndex: string,
rootDir: string,
logger: Logger,
): Middleware {
const resolvedAppIndex = path.resolve(appIndex);
const relativeAppIndex = path.relative(rootDir, resolvedAppIndex);
const appIndexBrowserPath = `/${toBrowserPath(relativeAppIndex)}`;
const appIndexBrowserPathPrefix = path.dirname(appIndexBrowserPath);
return (ctx, next) => {
if (ctx.method !== 'GET' || path.extname(ctx.path)) {
// not a GET, or a direct file request
return next();
}
if (!ctx.headers || typeof ctx.headers.accept !== 'string') {
return next();
}
if (ctx.headers.accept.includes('application/json')) {
return next();
}
if (!(ctx.headers.accept.includes('text/html') || ctx.headers.accept.includes('*/*'))) {
return next();
}
if (!ctx.url.startsWith(appIndexBrowserPathPrefix)) {
return next();
}
// rewrite url and let static serve take it further
logger.debug(`Rewriting ${ctx.url} to app index ${appIndexBrowserPath}`);
ctx.url = appIndexBrowserPath;
return next();
};
}
| modernweb-dev/web/packages/dev-server-core/src/middleware/historyApiFallbackMiddleware.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/middleware/historyApiFallbackMiddleware.ts",
"repo_id": "modernweb-dev",
"token_count": 485
} | 173 |
import portfinder from 'portfinder';
import { expect } from 'chai';
import { green, red, yellow } from 'nanocolors';
import { DevServer } from './server/DevServer.js';
import { DevServerCoreConfig } from './server/DevServerCoreConfig.js';
import { Logger } from './logger/Logger.js';
import { Plugin } from './plugins/Plugin.js';
const defaultConfig: Omit<DevServerCoreConfig, 'port' | 'rootDir'> = {
hostname: 'localhost',
injectWebSocket: true,
middleware: [],
plugins: [],
};
const mockLogger: Logger = {
...console,
debug() {
// no debug
},
logSyntaxError(error) {
console.error(error);
},
};
export function virtualFilesPlugin(servedFiles: Record<string, string>): Plugin {
return {
name: 'test-helpers-virtual-files',
serve(context) {
if (context.path in servedFiles) {
return servedFiles[context.path];
}
},
};
}
export async function createTestServer(
config: Partial<DevServerCoreConfig>,
_mockLogger = mockLogger,
) {
if (!config.rootDir) {
throw new Error('A rootDir must be configured.');
}
const port = await portfinder.getPortPromise({
port: 9000 + Math.floor(Math.random() * 1000),
});
const server = new DevServer(
{ ...defaultConfig, ...config, rootDir: config.rootDir, port },
_mockLogger,
);
await server.start();
const url = new URL('http://localhost');
url.protocol = config.http2 ? 'https' : 'http';
url.port = port.toString();
return { server, port, host: url.toString().slice(0, -1) };
}
export const timeout = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
export async function fetchText(url: string, init?: RequestInit) {
const response = await fetch(url, init);
expect(response.status).to.equal(200);
return response.text();
}
export function expectIncludes(text: string, expected: string) {
if (!text.includes(expected)) {
throw new Error(red(`Expected "${yellow(expected)}" in string: \n\n${green(text)}`));
}
}
export function expectNotIncludes(text: string, expected: string) {
if (text.includes(expected)) {
throw new Error(`Did not expect "${expected}" in string: \n\n${text}`);
}
}
| modernweb-dev/web/packages/dev-server-core/src/test-helpers.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/src/test-helpers.ts",
"repo_id": "modernweb-dev",
"token_count": 735
} | 174 |
export default 'foo';
| modernweb-dev/web/packages/dev-server-core/test/fixtures/outside-root-dir/node_modules/foo/index.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-core/test/fixtures/outside-root-dir/node_modules/foo/index.js",
"repo_id": "modernweb-dev",
"token_count": 6
} | 175 |
import { browsers } from '@mdn/browser-compat-data';
type Release = { status: string };
export type Browser = { name: string; version: string };
export const TARGET_LATEST_MODERN = createModernTarget();
// earliest browser versions to support module scripts, dynamic imports and import.meta
export const TARGET_LOWEST_ESM_SUPPORT = ['chrome64', 'edge79', 'firefox67', 'safari11.1'];
function createModernTarget() {
try {
const latestChrome = getLatestStableMajor(browsers.chrome.releases);
if (!latestChrome) throw new Error('Could not find latest Chrome major version');
const latestEdge = getLatestStableMajor(browsers.edge.releases);
if (!latestEdge) throw new Error('Could not find latest Edge major version');
const latestSafari = getLatestStableMajor(browsers.safari.releases);
if (!latestSafari) throw new Error('Could not find latest Safari major version');
const latestFirefox = getLatestStableMajor(browsers.firefox.releases);
if (!latestFirefox) throw new Error('Could not find latest Firefox major version');
return [
`chrome${latestChrome - 1}`,
`edge${latestEdge - 1}`,
`safari${latestSafari}`,
`firefox${latestFirefox}`,
];
} catch (error) {
throw new Error(
`Error while initializing default browser targets for @web/dev-server-esbuild: ${
(error as Error).message
}`,
);
}
}
function getMajorVersion(version: string | number) {
return Number(version.toString().split('.')[0]);
}
export function getLatestStableMajor(releases: Record<string, Release>): number | undefined {
const release = Object.entries(releases).find(([, release]) => release.status === 'current')?.[0];
if (release) {
return getMajorVersion(release);
}
return undefined;
}
function isWithinRange(releases: Record<string, Release>, version: string | number, range: number) {
const currentMajorVersion = getMajorVersion(version);
const latestMajorVersion = getLatestStableMajor(releases);
if (latestMajorVersion == null) {
return false;
}
return currentMajorVersion >= latestMajorVersion - range;
}
export function isLatestSafari({ name, version }: Browser) {
const nameLowerCase = name.toLowerCase();
// don't use include to avoid matching safari iOS
if (nameLowerCase === 'safari') {
return isWithinRange(browsers.safari.releases, version, 0);
}
return false;
}
export function isLatestModernBrowser({ name, version }: Browser) {
const nameLowerCase = name.toLowerCase();
if (['chrome', 'chromium'].some(name => nameLowerCase.includes(name))) {
return isWithinRange(browsers.chrome.releases, version, 1);
}
if (nameLowerCase.includes('edge')) {
return isWithinRange(browsers.edge.releases, version, 1);
}
if (nameLowerCase.includes('firefox')) {
return isWithinRange(browsers.firefox.releases, version, 0);
}
return false;
}
| modernweb-dev/web/packages/dev-server-esbuild/src/browser-targets.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-esbuild/src/browser-targets.ts",
"repo_id": "modernweb-dev",
"token_count": 922
} | 176 |
<html>
<head></head>
<body>
<my-component></my-component>
<script type="module" src="./component.js"></script>
</body>
</html>
| modernweb-dev/web/packages/dev-server-hmr/demo/vanilla/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-hmr/demo/vanilla/index.html",
"repo_id": "modernweb-dev",
"token_count": 58
} | 177 |
import { expect } from 'chai';
import { createTestServer } from '@web/dev-server-core/test-helpers';
import { fetchText, expectIncludes } from '@web/dev-server-core/test-helpers';
import { legacyPlugin } from '../src/legacyPlugin.js';
import { modernUserAgents, legacyUserAgents } from './userAgents.js';
const htmlBody = `
<html>
<body>
<script type="module" src="./foo.js"></script>
<script src="./bar.js"></script>
</body>
</html>`;
const inlineScriptHtmlBody = `
<html>
<body>
<script type="module">
class InlineClass {
}
</script>
<script>console.log("x");</script>
</body>
</html>`;
describe('legacyPlugin - transform html', function () {
this.timeout(10000);
it(`does not do any work on a modern browser`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/index.html') {
return htmlBody;
}
},
},
legacyPlugin(),
],
});
const text = await fetchText(`${host}/index.html`, {
headers: { 'user-agent': modernUserAgents['Chrome 78'] },
});
expect(text.trim()).to.equal(htmlBody.trim());
server.stop();
});
it(`injects polyfills into the HTML page on legacy browsers`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/index.html') {
return htmlBody;
}
},
},
legacyPlugin(),
],
});
const text = await fetchText(`${host}/index.html`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
expectIncludes(text, 'function polyfillsLoader() {');
expectIncludes(text, "loadScript('./polyfills/regenerator-runtime.");
expectIncludes(text, "loadScript('./polyfills/fetch.");
expectIncludes(text, "loadScript('./polyfills/systemjs.");
server.stop();
});
it(`injects systemjs param to inline modules`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/index.html') {
return htmlBody;
}
},
},
legacyPlugin(),
],
});
const text = await fetchText(`${host}/index.html`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
expectIncludes(text, "loadScript('./bar.js'");
expectIncludes(text, "System.import('./foo.js?systemjs=true');");
server.stop();
});
it(`handles inline scripts`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/index.html') {
return inlineScriptHtmlBody;
}
},
},
legacyPlugin(),
],
});
const text = await fetchText(`${host}/index.html`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
expectIncludes(text, "loadScript('./inline-script-0.js?source=%2Findex.html'");
expectIncludes(
text,
"System.import('./inline-script-1.js?source=%2Findex.html&systemjs=true');",
);
server.stop();
});
it(`can request inline scripts`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.path === '/index.html') {
return inlineScriptHtmlBody;
}
},
},
legacyPlugin(),
],
});
await fetchText(`${host}/index.html`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
const text = await fetchText(`${host}/inline-script-1.js?source=%2Findex.html`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
expectIncludes(text, 'var InlineClass =');
expectIncludes(text, '_classCallCheck(this, InlineClass);');
server.stop();
});
it(`includes url parameters in inline script key`, async () => {
const { server, host } = await createTestServer({
rootDir: __dirname,
plugins: [
{
name: 'test',
serve(context) {
if (context.url === '/?foo=1') {
return {
body: '<html><body><script type="module">console.log("1");</script></body></html>',
type: 'html',
};
}
if (context.url === '/?foo=2') {
return {
body: '<html><body><script type="module">console.log("2");</script></body></html>',
type: 'html',
};
}
},
},
legacyPlugin(),
],
});
await fetchText(`${host}?foo=1`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
await fetchText(`${host}/?foo=2`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
const text1 = await fetchText(`${host}/inline-script-0.js?source=%2F%3Ffoo%3D1`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
const text2 = await fetchText(`${host}/inline-script-0.js?source=%2F%3Ffoo%3D2`, {
headers: { 'user-agent': legacyUserAgents['IE 11'] },
});
expectIncludes(text1, 'console.log("1");');
expectIncludes(text2, 'console.log("2");');
server.stop();
});
});
| modernweb-dev/web/packages/dev-server-legacy/test/transform-html.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-legacy/test/transform-html.test.ts",
"repo_id": "modernweb-dev",
"token_count": 2542
} | 178 |
import {
rollup,
InputOptions,
NormalizedInputOptions,
PluginContext,
TransformPluginContext,
} from 'rollup';
export interface RollupPluginContexts {
normalizedInputOptions: NormalizedInputOptions;
pluginContext: PluginContext;
minimalPluginContext: any;
transformPluginContext: TransformPluginContext;
}
/**
* Runs rollup with an empty module in order to capture the plugin context and
* normalized options.
* @param inputOptions
*/
export async function createRollupPluginContexts(
inputOptions: InputOptions,
): Promise<RollupPluginContexts> {
let normalizedInputOptions: NormalizedInputOptions | undefined = undefined;
let pluginContext: PluginContext | undefined = undefined;
let transformPluginContext: TransformPluginContext | undefined = undefined;
await rollup({
...inputOptions,
input: 'noop',
plugins: [
{
name: 'noop',
buildStart(options) {
normalizedInputOptions = options;
},
resolveId(id) {
pluginContext = this; // eslint-disable-line @typescript-eslint/no-this-alias
return id;
},
load() {
return '';
},
transform() {
transformPluginContext = this; // eslint-disable-line @typescript-eslint/no-this-alias
return null;
},
},
],
});
if (!normalizedInputOptions || !pluginContext || !transformPluginContext) {
throw new TypeError();
}
return {
normalizedInputOptions,
pluginContext,
transformPluginContext,
minimalPluginContext: { meta: (pluginContext as PluginContext).meta },
};
}
| modernweb-dev/web/packages/dev-server-rollup/src/createRollupPluginContexts.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/src/createRollupPluginContexts.ts",
"repo_id": "modernweb-dev",
"token_count": 560
} | 179 |
export default 'c';
| modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-basic/src/foo/c.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/bundle-basic/src/foo/c.js",
"repo_id": "modernweb-dev",
"token_count": 6
} | 180 |
import '../../../../../../node_modules/chai/chai.js';
import styles from './my-styles.css';
const { expect } = window.chai;
describe('postcss', () => {
it('can import css modules', () => {
expect(styles).to.exist;
});
it('exports scoped classes', () => {
expect(styles.foo).to.be.a('string');
expect(styles.bar).to.be.a('string');
});
it('the styles are injected in the document head', () => {
const styleTag = document.head.querySelector('style');
expect(styleTag).to.exist;
expect(styleTag.textContent).to.include('color: blue;');
expect(styleTag.textContent).to.include('color: red;');
expect(styleTag.textContent).to.include(styles.foo);
expect(styleTag.textContent).to.include(styles.bar);
});
});
| modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/postcss/postcss-browser-test.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/fixtures/postcss/postcss-browser-test.js",
"repo_id": "modernweb-dev",
"token_count": 270
} | 181 |
/// <reference types="../../../types/rollup-plugin-postcss" />
import rollupPostcss from 'rollup-plugin-postcss';
import { chromeLauncher } from '@web/test-runner-chrome';
import { runTests } from '@web/test-runner-core/test-helpers';
import { resolve } from 'path';
import { createTestServer, fetchText, expectIncludes } from '../test-helpers.js';
import { fromRollup } from '../../../src/index.js';
const postcss = fromRollup(rollupPostcss);
describe('@rollup/plugin-postcss', () => {
it('can run postcss on imported css files', async () => {
const { server, host } = await createTestServer({
rootDir: resolve(__dirname, '..', '..', '..', '..', '..'),
mimeTypes: {
'**/*.css': 'js',
},
plugins: [
{
name: 'serve-css',
serve(context) {
if (context.path === '/my-styles.css') {
return `
html {
font-size: 20px;
}
.foo {
color: blue;
}
#bar {
color: red;
}`;
}
},
},
postcss(),
],
});
try {
const text = await fetchText(`${host}/my-styles.css`);
expectIncludes(
text,
'"\\nhtml {\\n font-size: 20px;\\n}\\n\\n.foo {\\n color: blue;\\n}\\n\\n#bar {\\n color: red;\\n}";',
);
expectIncludes(text, 'export default');
expectIncludes(
text,
"import styleInject from './node_modules/style-inject/dist/style-inject.es.js';",
);
expectIncludes(text, 'styleInject(css_248z);');
} finally {
server.stop();
}
});
it('passes the in-browser tests', async function () {
this.timeout(40000);
await runTests({
files: [resolve(__dirname, '..', 'fixtures', 'postcss', 'postcss-browser-test.js')],
browsers: [chromeLauncher()],
mimeTypes: {
'**/*.css': 'js',
},
plugins: [fromRollup(rollupPostcss)({ modules: true })],
});
});
});
| modernweb-dev/web/packages/dev-server-rollup/test/node/plugins/postcss.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-rollup/test/node/plugins/postcss.test.ts",
"repo_id": "modernweb-dev",
"token_count": 852
} | 182 |
import { storybookPlugin } from '../../index.mjs';
export default {
rootDir: '../..',
open: true,
nodeResolve: true,
plugins: [
storybookPlugin({
type: 'preact',
configDir: 'demo/preact/.storybook',
}),
],
};
| modernweb-dev/web/packages/dev-server-storybook/demo/preact/web-dev-server.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/demo/preact/web-dev-server.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 99
} | 183 |
import { rollup, RollupOptions } from 'rollup';
export async function buildAndWrite(options: RollupOptions) {
const bundle = await rollup(options);
if (Array.isArray(options.output)) {
await bundle.write(options.output[0]);
await bundle.write(options.output[1]);
} else if (options.output) {
await bundle.write(options.output);
}
}
| modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/buildAndWrite.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/src/build/rollup/buildAndWrite.ts",
"repo_id": "modernweb-dev",
"token_count": 115
} | 184 |
import path from 'path';
import pathIsInside from 'path-is-inside';
export function createError(msg: string) {
return new Error(`[@web/dev-server-storybook] ${msg}`);
}
export function createBrowserImport(rootDir: string, filePath: string) {
if (!pathIsInside(filePath, rootDir)) {
throw createError(
`The file ${filePath} is not accessible by the browser because it is outside the root directory ${rootDir}. ` +
'Change the rootDir option to include this directory.',
);
}
const relativeFilePath = path.relative(rootDir, filePath);
const browserPath = relativeFilePath.split(path.sep).join('/');
return `./${browserPath}`;
}
| modernweb-dev/web/packages/dev-server-storybook/src/shared/utils.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server-storybook/src/shared/utils.ts",
"repo_id": "modernweb-dev",
"token_count": 210
} | 185 |
window.__moduleLoaded = true; | modernweb-dev/web/packages/dev-server/demo/http2/module.js/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/http2/module.js",
"repo_id": "modernweb-dev",
"token_count": 9
} | 186 |
<html>
<head> </head>
<body>
<img width="100" src="/demo/logo.png" />
<h1>Static demo</h1>
<p>A demo without any custom flags.</p>
<div id="test"></div>
<script type="module" src="/demo/static/module.js"></script>
<script type="module">
import './module.js';
window.__tests = {
moduleLoaded: window.__moduleLoaded || false,
};
document.getElementById('test').innerHTML = `<pre>${JSON.stringify(
window.__tests,
null,
2,
)}</pre>`;
</script>
<script>
(async () => {
await fetch('/demo/static/module.js');
})();
</script>
</body>
</html>
| modernweb-dev/web/packages/dev-server/demo/static/index.html/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/demo/static/index.html",
"repo_id": "modernweb-dev",
"token_count": 311
} | 187 |
#!/usr/bin/env node
import { startDevServer } from './startDevServer.js';
startDevServer();
| modernweb-dev/web/packages/dev-server/src/bin.ts/0 | {
"file_path": "modernweb-dev/web/packages/dev-server/src/bin.ts",
"repo_id": "modernweb-dev",
"token_count": 31
} | 188 |
// @ts-nocheck
import { createAddon } from '@web/storybook-prebuilt/create-addon.js';
import { React } from '@web/storybook-prebuilt/manager.js';
import { addons } from '@web/storybook-prebuilt/addons.js';
import { registerAddon } from './addon/register-addon.js';
// Storybook 6
registerAddon(addons, React, createAddon);
| modernweb-dev/web/packages/mocks/storybook/addon.js/0 | {
"file_path": "modernweb-dev/web/packages/mocks/storybook/addon.js",
"repo_id": "modernweb-dev",
"token_count": 111
} | 189 |
/** @typedef {import('parse5').TreeAdapter} TreeAdapter */
/** @typedef {import('parse5').Element} Element */
/** @typedef {import('parse5').Attribute} Attribute */
/** @typedef {import('parse5').Node} Node */
/** @typedef {import('parse5').ParentNode} ParentNode */
/** @typedef {import('parse5').ChildNode} ChildNode */
/** @typedef {import('parse5').CommentNode} CommentNode */
/** @typedef {import('parse5').TextNode} TextNode */
const parse5 = require('parse5');
const adapter = require('parse5/lib/tree-adapters/default');
const DEFAULT_NAMESPACE = 'http://www.w3.org/1999/xhtml';
const REGEXP_IS_HTML_DOCUMENT = /^\s*<(!doctype|html|head|body)\b/i;
/**
* Creates an element node.
*
* @param {string} tagName Tag name of the element.
* @param {Record<string, string>} attrs Attribute name-value pair array. Foreign attributes may contain `namespace` and `prefix` fields as well.
* @param {string} namespaceURI Namespace of the element.
* @returns {Element}
*/
function createElement(tagName, attrs = {}, namespaceURI = DEFAULT_NAMESPACE) {
const attrsArray = Object.entries(attrs).map(([name, value]) => ({ name, value }));
return adapter.createElement(tagName, namespaceURI, attrsArray);
}
/**
* Creates a script element.
* @param {Record<string,string>} [attrs]
* @param {string} [code]
* @returns {Element}
*/
function createScript(attrs = {}, code = undefined) {
const element = createElement('script', attrs);
if (code) {
setTextContent(element, code);
}
return element;
}
/**
* @param {string} html
*/
function isHtmlFragment(html) {
let htmlWithoutComments = html.replace(/<!--.*?-->/gs, '');
return !REGEXP_IS_HTML_DOCUMENT.test(htmlWithoutComments);
}
/**
* @param {Element} element
*/
function getAttributes(element) {
const attrsArray = adapter.getAttrList(element);
/** @type {Record<string,string>} */
const attrsObj = {};
for (const e of attrsArray) {
attrsObj[e.name] = e.value;
}
return attrsObj;
}
/**
* @param {Element} element
* @param {string} name
*/
function getAttribute(element, name) {
const attrList = adapter.getAttrList(element);
if (!attrList) {
return null;
}
const attr = attrList.find(a => a.name == name);
if (attr) {
return attr.value;
}
}
/**
* @param {Element} element
* @param {string} name
*/
function hasAttribute(element, name) {
return getAttribute(element, name) != null;
}
/**
* @param {Element} element
* @param {string} name
* @param {string} value
*/
function setAttribute(element, name, value) {
const attrs = adapter.getAttrList(element);
const existing = attrs.find(a => a.name === name);
if (existing) {
existing.value = value;
} else {
attrs.push({ name, value });
}
}
/**
* @param {Element} element
* @param {Record<string,string|undefined>} attributes
*/
function setAttributes(element, attributes) {
for (const [name, value] of Object.entries(attributes)) {
if (value !== undefined) {
setAttribute(element, name, value);
}
}
}
/**
* @param {Element} element
* @param {string} name
*/
function removeAttribute(element, name) {
const attrs = adapter.getAttrList(element);
element.attrs = attrs.filter(attr => attr.name !== name);
}
/**
* @param {Node} node
* @returns {string}
*/
function getTextContent(node) {
if (adapter.isCommentNode(node)) {
return node.data || '';
}
if (adapter.isTextNode(node)) {
return node.value || '';
}
const subtree = findNodes(node, n => adapter.isTextNode(n));
return subtree.map(getTextContent).join('');
}
/**
* @param {Node} node
* @param {string} value
*/
function setTextContent(node, value) {
if (adapter.isCommentNode(node)) {
node.data = value;
} else if (adapter.isTextNode(node)) {
node.value = value;
} else {
const textNode = {
nodeName: '#text',
value: value,
parentNode: node,
attrs: [],
__location: undefined,
};
/** @type {ParentNode} */ (node).childNodes = [/** @type {TextNode} */ (textNode)];
}
}
/**
* Removes element from the AST.
* @param {ChildNode} node
*/
function remove(node) {
const parent = node.parentNode;
if (parent && parent.childNodes) {
const idx = parent.childNodes.indexOf(node);
parent.childNodes.splice(idx, 1);
}
/** @type {any} */ (node).parentNode = undefined;
}
/**
* Looks for a child node which passes the given test
* @param {Node[] | Node} nodes
* @param {(node: Node) => boolean} test
* @returns {Node | null}
*/
function findNode(nodes, test) {
const n = Array.isArray(nodes) ? nodes.slice() : [nodes];
while (n.length > 0) {
const node = n.shift();
if (!node) {
continue;
}
if (test(node)) {
return node;
}
const children = adapter.getChildNodes(/** @type {ParentNode} */ (node));
if (Array.isArray(children)) {
n.unshift(...children);
}
}
return null;
}
/**
* Looks for all child nodes which passes the given test
* @param {Node | Node[]} nodes
* @param {(node: Node) => boolean} test
* @returns {Node[]}
*/
function findNodes(nodes, test) {
const n = Array.isArray(nodes) ? nodes.slice() : [nodes];
/** @type {Node[]} */
const found = [];
while (n.length) {
const node = n.shift();
if (!node) {
continue;
}
if (test(node)) {
found.push(node);
}
/** @type {Node[]} */
let children = [];
if (adapter.isElementNode(node) && adapter.getTagName(node) === 'template') {
const content = adapter.getTemplateContent(node);
if (content) {
children = adapter.getChildNodes(content);
}
} else {
children = adapter.getChildNodes(/** @type {ParentNode} */ (node));
}
if (Array.isArray(children)) {
n.unshift(...children);
}
}
return found;
}
/**
* Looks for a child element which passes the given test
* @param {Node[] | Node} nodes
* @param {(node: Element) => boolean} test
* @returns {Element | null}
*/
function findElement(nodes, test) {
return /** @type {Element | null} */ (findNode(nodes, n => adapter.isElementNode(n) && test(n)));
}
/**
* Looks for all child elements which passes the given test
* @param {Node | Node[]} nodes
* @param {(node: Element) => boolean} test
* @returns {Element[]}
*/
function findElements(nodes, test) {
return /** @type {Element[]} */ (findNodes(nodes, n => adapter.isElementNode(n) && test(n)));
}
/**
* @param {ParentNode} parent
* @param {ChildNode} node
*/
function prepend(parent, node) {
parent.childNodes.unshift(node);
node.parentNode = parent;
}
/**
* Prepends HTML snippet to the given html document. The document must have either
* a <body> or <head> element.
* @param {string} document
* @param {string} appendedHtml
* @returns {string | null}
*/
function prependToDocument(document, appendedHtml) {
const documentAst = parse5.parse(document, { sourceCodeLocationInfo: true });
let appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.startTag) {
// the original code did not contain a head
appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.startTag) {
// the original code did not contain a head or body, so we go with the generated AST
const head = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!head) throw new Error('parse5 did not generated a head element');
const fragment = parse5.parseFragment(appendedHtml);
for (const node of adapter.getChildNodes(fragment).reverse()) {
prepend(head, node);
}
return parse5.serialize(documentAst);
}
}
// the original source contained a head or body element, use string manipulation
// to preserve original code formatting
const { endOffset } = appendNode.sourceCodeLocation.startTag;
const start = document.substring(0, endOffset);
const end = document.substring(endOffset);
return `${start}${appendedHtml}${end}`;
}
/**
* Append HTML snippet to the given html document. The document must have either
* a <body> or <head> element.
* @param {string} document
* @param {string} appendedHtml
*/
function appendToDocument(document, appendedHtml) {
const documentAst = parse5.parse(document, { sourceCodeLocationInfo: true });
let appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.endTag) {
// there is no body node in the source, use the head instead
appendNode = findElement(documentAst, node => adapter.getTagName(node) === 'head');
if (!appendNode || !appendNode.sourceCodeLocation || !appendNode.sourceCodeLocation.endTag) {
// the original code did not contain a head or body, so we go with the generated AST
const body = findElement(documentAst, node => adapter.getTagName(node) === 'body');
if (!body) throw new Error('parse5 did not generated a body element');
const fragment = parse5.parseFragment(appendedHtml);
for (const node of adapter.getChildNodes(fragment)) {
adapter.appendChild(body, node);
}
return parse5.serialize(documentAst);
}
}
// the original source contained a head or body element, use string manipulation
// to preserve original code formatting
const { startOffset } = appendNode.sourceCodeLocation.endTag;
const start = document.substring(0, startOffset);
const end = document.substring(startOffset);
return `${start}${appendedHtml}${end}`;
}
module.exports.createDocument = adapter.createDocument;
module.exports.createDocumentFragment = adapter.createDocumentFragment;
module.exports.createElement = createElement;
module.exports.createScript = createScript;
module.exports.createCommentNode = adapter.createCommentNode;
module.exports.appendChild = adapter.appendChild;
module.exports.insertBefore = adapter.insertBefore;
module.exports.setTemplateContent = adapter.setTemplateContent;
module.exports.getTemplateContent = adapter.getTemplateContent;
module.exports.setDocumentType = adapter.setDocumentType;
module.exports.setDocumentMode = adapter.setDocumentMode;
module.exports.getDocumentMode = adapter.getDocumentMode;
module.exports.detachNode = adapter.detachNode;
module.exports.insertText = adapter.insertText;
module.exports.insertTextBefore = adapter.insertTextBefore;
module.exports.adoptAttributes = adapter.adoptAttributes;
module.exports.getFirstChild = adapter.getFirstChild;
module.exports.getChildNodes = adapter.getChildNodes;
module.exports.getParentNode = adapter.getParentNode;
module.exports.getAttrList = adapter.getAttrList;
module.exports.getTagName = adapter.getTagName;
module.exports.getNamespaceURI = adapter.getNamespaceURI;
module.exports.getTextNodeContent = adapter.getTextNodeContent;
module.exports.getCommentNodeContent = adapter.getCommentNodeContent;
module.exports.getDocumentTypeNodeName = adapter.getDocumentTypeNodeName;
module.exports.getDocumentTypeNodePublicId = adapter.getDocumentTypeNodePublicId;
module.exports.getDocumentTypeNodeSystemId = adapter.getDocumentTypeNodeSystemId;
module.exports.isTextNode = adapter.isTextNode;
module.exports.isCommentNode = adapter.isCommentNode;
module.exports.isDocumentTypeNode = adapter.isDocumentTypeNode;
module.exports.isElementNode = adapter.isElementNode;
module.exports.setNodeSourceCodeLocation = adapter.setNodeSourceCodeLocation;
module.exports.getNodeSourceCodeLocation = adapter.getNodeSourceCodeLocation;
module.exports.isHtmlFragment = isHtmlFragment;
module.exports.hasAttribute = hasAttribute;
module.exports.getAttribute = getAttribute;
module.exports.getAttributes = getAttributes;
module.exports.setAttribute = setAttribute;
module.exports.setAttributes = setAttributes;
module.exports.removeAttribute = removeAttribute;
module.exports.setTextContent = setTextContent;
module.exports.getTextContent = getTextContent;
module.exports.remove = remove;
module.exports.findNode = findNode;
module.exports.findNodes = findNodes;
module.exports.findElement = findElement;
module.exports.findElements = findElements;
module.exports.prepend = prepend;
module.exports.prependToDocument = prependToDocument;
module.exports.appendToDocument = appendToDocument;
| modernweb-dev/web/packages/parse5-utils/src/index.js/0 | {
"file_path": "modernweb-dev/web/packages/parse5-utils/src/index.js",
"repo_id": "modernweb-dev",
"token_count": 4098
} | 190 |
console.log('polyfill a');
| modernweb-dev/web/packages/polyfills-loader/test/custom-polyfills/polyfill-a.js/0 | {
"file_path": "modernweb-dev/web/packages/polyfills-loader/test/custom-polyfills/polyfill-a.js",
"repo_id": "modernweb-dev",
"token_count": 9
} | 191 |
import cjsEntrypoint from './src/copy.js';
const { copy } = cjsEntrypoint;
export { copy };
| modernweb-dev/web/packages/rollup-plugin-copy/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-copy/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 33
} | 192 |
console.log('lazy-2.js');
| modernweb-dev/web/packages/rollup-plugin-html/demo/spa/src/lazy-2.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/demo/spa/src/lazy-2.js",
"repo_id": "modernweb-dev",
"token_count": 12
} | 193 |
import { getEntrypointBundles } from './getEntrypointBundles.js';
import { getOutputHTML } from './getOutputHTML.js';
import { createError } from '../utils.js';
import {
GeneratedBundle,
RollupPluginHTMLOptions,
TransformHtmlFunction,
} from '../RollupPluginHTMLOptions.js';
import { EmittedFile } from 'rollup';
import { InputData } from '../input/InputData.js';
import { EmittedAssets } from './emitAssets.js';
export interface CreateHTMLAssetParams {
outputDir: string;
input: InputData;
emittedAssets: EmittedAssets;
generatedBundles: GeneratedBundle[];
externalTransformHtmlFns: TransformHtmlFunction[];
pluginOptions: RollupPluginHTMLOptions;
defaultInjectDisabled: boolean;
serviceWorkerPath: string;
injectServiceWorker: boolean;
absolutePathPrefix?: string;
strictCSPInlineScripts: boolean;
}
export async function createHTMLAsset(params: CreateHTMLAssetParams): Promise<EmittedFile> {
const {
outputDir,
input,
emittedAssets,
generatedBundles,
externalTransformHtmlFns,
pluginOptions,
defaultInjectDisabled,
serviceWorkerPath,
injectServiceWorker,
absolutePathPrefix,
strictCSPInlineScripts,
} = params;
if (generatedBundles.length === 0) {
throw createError('Cannot output HTML when no bundles have been generated');
}
const entrypointBundles = getEntrypointBundles({
pluginOptions,
generatedBundles,
inputModuleIds: input.moduleImports,
outputDir,
htmlFileName: input.name,
});
const outputHtml = await getOutputHTML({
pluginOptions,
entrypointBundles,
input,
outputDir,
emittedAssets,
externalTransformHtmlFns,
defaultInjectDisabled,
serviceWorkerPath,
injectServiceWorker,
absolutePathPrefix,
strictCSPInlineScripts,
});
return { fileName: input.name, name: input.name, source: outputHtml, type: 'asset' };
}
export interface CreateHTMLAssetsParams {
outputDir: string;
inputs: InputData[];
emittedAssets: EmittedAssets;
generatedBundles: GeneratedBundle[];
externalTransformHtmlFns: TransformHtmlFunction[];
pluginOptions: RollupPluginHTMLOptions;
defaultInjectDisabled: boolean;
serviceWorkerPath: string;
injectServiceWorker: boolean;
absolutePathPrefix?: string;
strictCSPInlineScripts: boolean;
}
export async function createHTMLOutput(params: CreateHTMLAssetsParams): Promise<EmittedFile[]> {
return Promise.all(params.inputs.map(input => createHTMLAsset({ ...params, input })));
}
| modernweb-dev/web/packages/rollup-plugin-html/src/output/createHTMLOutput.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/src/output/createHTMLOutput.ts",
"repo_id": "modernweb-dev",
"token_count": 823
} | 194 |
<html>
<body>
<p>inject a service worker into /sub-page/index.html</p>
</body>
</html>
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/inject-service-worker/sub-pure-html/index.html/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/inject-service-worker/sub-pure-html/index.html",
"repo_id": "modernweb-dev",
"token_count": 42
} | 195 |
@font-face {
font-family: 'Font';
src: url('fonts/font-normal.woff2') format('woff2');
font-weight: normal;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Font';
src: url('fonts/font-bold.woff2') format('woff2');
font-weight: bold;
font-style: normal;
font-display: swap;
}
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-node-modules/node_modules/foo/node_modules-styles-with-fonts.css/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/resolves-assets-in-styles-node-modules/node_modules/foo/node_modules-styles-with-fonts.css",
"repo_id": "modernweb-dev",
"token_count": 129
} | 196 |
import './shared-module.js';
console.log('module-a.js');
| modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/modules/module-a.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/fixtures/rollup-plugin-html/modules/module-a.js",
"repo_id": "modernweb-dev",
"token_count": 22
} | 197 |
import { rollup, OutputChunk, OutputAsset, OutputOptions, Plugin } from 'rollup';
import { expect } from 'chai';
import path from 'path';
import { rollupPluginHTML } from '../src/index.js';
type Output = (OutputChunk | OutputAsset)[];
function getChunk(output: Output, name: string) {
return output.find(o => o.fileName === name && o.type === 'chunk') as OutputChunk;
}
function getAsset(output: Output, name: string) {
return output.find(o => o.name === name && o.type === 'asset') as OutputAsset & {
source: string;
};
}
const outputConfig: OutputOptions = {
format: 'es',
dir: 'dist',
};
function stripNewlines(str: string) {
return str.replace(/(\r\n|\n|\r)/gm, '');
}
const rootDir = path.join(__dirname, 'fixtures', 'rollup-plugin-html');
describe('rollup-plugin-html', () => {
it('can build with an input path as input', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/index.html'),
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('can build with html file as rollup input', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/index.html'),
plugins: [rollupPluginHTML({ rootDir })],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('will retain attributes on script tags', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/retain-attributes.html'),
plugins: [rollupPluginHTML({ rootDir })],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'retain-attributes.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1>' +
'<script type="module" src="./entrypoint-a.js" keep-this-attribute=""></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('can build with pure html file as rollup input', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/pure-index.html'),
plugins: [rollupPluginHTML({ rootDir })],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'pure-index.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1></body></html>',
);
});
it('can build with multiple pure html inputs', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: [
require.resolve('./fixtures/rollup-plugin-html/pure-index.html'),
require.resolve('./fixtures/rollup-plugin-html/pure-index2.html'),
],
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'pure-index.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1></body></html>',
);
expect(stripNewlines(getAsset(output, 'pure-index2.html').source)).to.equal(
'<html><head></head><body><h1>hey there</h1></body></html>',
);
});
it('can build with html string as input', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
name: 'index.html',
html: '<h1>Hello world</h1><script type="module" src="./entrypoint-a.js"></script>',
},
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script></body></html>',
);
});
it('resolves paths relative to virtual html filename', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
name: 'pages/index.html',
html: '<h1>Hello world</h1><script type="module" src="../entrypoint-a.js"></script>',
},
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(stripNewlines(getAsset(output, 'pages/index.html').source)).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script type="module" src="../entrypoint-a.js"></script></body></html>',
);
});
it('can build with inline modules', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: {
name: 'index.html',
html: '<h1>Hello world</h1><script type="module">import "./entrypoint-a.js";</script>',
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
const hash = '5ec680a4efbb48ae254268ab1defe610';
const { code: appCode } = getChunk(output, `inline-module-${hash}.js`);
expect(appCode).to.include("console.log('entrypoint-a.js');");
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
`<script type="module" src="./inline-module-${hash}.js"></script>` +
'</body></html>',
);
});
it('resolves inline module imports relative to the HTML file', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/foo/foo.html'),
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
const { code: appCode } = getChunk(output, 'inline-module-1b13383486c70d87f4e2585ff87b147c.js');
expect(appCode).to.include("console.log('foo');");
});
it('can build transforming final output', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/entrypoint-a.js'),
plugins: [
rollupPluginHTML({
rootDir,
input: {
html: '<h1>Hello world</h1><script type="module" src="./entrypoint-a.js"></script>',
},
transformHtml(html) {
return html.replace('Hello world', 'Goodbye world');
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(getAsset(output, 'index.html').source).to.equal(
'<html><head></head><body><h1>Goodbye world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script></body></html>',
);
});
it('can build with a public path', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/entrypoint-a.js'),
plugins: [
rollupPluginHTML({
rootDir,
input: {
html: '<h1>Hello world</h1><script type="module" src="./entrypoint-a.js"></script>',
},
publicPath: '/static/',
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(getAsset(output, 'index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script type="module" src="/static/entrypoint-a.js"></script></body></html>',
);
});
it('can build with a public path with a file in a directory', async () => {
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/entrypoint-a.js'),
plugins: [
rollupPluginHTML({
rootDir,
input: {
name: 'pages/index.html',
html: '<h1>Hello world</h1><script type="module" src="../entrypoint-a.js"></script>',
},
publicPath: '/static/',
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(getAsset(output, 'pages/index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script type="module" src="/static/entrypoint-a.js"></script></body></html>',
);
});
it('can build with multiple build outputs', async () => {
const plugin = rollupPluginHTML({
rootDir,
input: {
html: '<h1>Hello world</h1><script type="module" src="./entrypoint-a.js"></script>',
},
publicPath: '/static/',
});
const config = {
input: require.resolve('./fixtures/rollup-plugin-html/entrypoint-a.js'),
plugins: [plugin],
};
const build = await rollup(config);
const bundleA = build.generate({
format: 'system',
dir: 'dist',
plugins: [plugin.api.addOutput('legacy')],
});
const bundleB = build.generate({
format: 'es',
dir: 'dist',
plugins: [plugin.api.addOutput('modern')],
});
const { output: outputA } = await bundleA;
const { output: outputB } = await bundleB;
expect(outputA.length).to.equal(1);
expect(outputB.length).to.equal(2);
const { code: entrypointA1 } = getChunk(outputA, 'entrypoint-a.js');
const { code: entrypointA2 } = getChunk(outputB, 'entrypoint-a.js');
expect(entrypointA1).to.include("console.log('entrypoint-a.js');");
expect(entrypointA1).to.include("console.log('module-a.js');");
expect(entrypointA2).to.include("console.log('entrypoint-a.js');");
expect(entrypointA2).to.include("console.log('module-a.js');");
expect(getAsset(outputA, 'index.html')).to.not.exist;
expect(getAsset(outputB, 'index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script>System.import("/static/entrypoint-a.js");</script>' +
'<script type="module" src="/static/entrypoint-a.js"></script></body></html>',
);
});
it('can build with index.html as input and an extra html file as output', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: {
html: '<h1>Hello world</h1><script type="module" src="./entrypoint-a.js"></script>',
},
}),
rollupPluginHTML({
rootDir,
input: {
name: 'foo.html',
html: '<html><body><h1>foo.html</h1></body></html>',
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
expect(getChunk(output, 'entrypoint-a.js')).to.exist;
expect(getAsset(output, 'index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script></body></html>',
);
expect(getAsset(output, 'foo.html').source).to.equal(
'<html><head></head><body><h1>foo.html</h1></body></html>',
);
});
it('can build with multiple html inputs', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: [
{
name: 'page-a.html',
html: `<h1>Page A</h1><script type="module" src="./entrypoint-a.js"></script>`,
},
{
name: 'page-b.html',
html: `<h1>Page B</h1><script type="module" src="./entrypoint-b.js"></script>`,
},
{
name: 'page-c.html',
html: `<h1>Page C</h1><script type="module" src="./entrypoint-c.js"></script>`,
},
],
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(7);
expect(getChunk(output, 'entrypoint-a.js')).to.exist;
expect(getChunk(output, 'entrypoint-b.js')).to.exist;
expect(getChunk(output, 'entrypoint-c.js')).to.exist;
expect(getAsset(output, 'page-a.html').source).to.equal(
'<html><head></head><body><h1>Page A</h1><script type="module" src="./entrypoint-a.js"></script></body></html>',
);
expect(getAsset(output, 'page-b.html').source).to.equal(
'<html><head></head><body><h1>Page B</h1><script type="module" src="./entrypoint-b.js"></script></body></html>',
);
expect(getAsset(output, 'page-c.html').source).to.equal(
'<html><head></head><body><h1>Page C</h1><script type="module" src="./entrypoint-c.js"></script></body></html>',
);
});
it('can use a glob to build multiple pages', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: 'pages/**/*.html',
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
const pageA = getAsset(output, 'page-a.html').source;
const pageB = getAsset(output, 'page-b.html').source;
const pageC = getAsset(output, 'page-c.html').source;
expect(output.length).to.equal(7);
expect(getChunk(output, 'page-a.js')).to.exist;
expect(getChunk(output, 'page-b.js')).to.exist;
expect(getChunk(output, 'page-c.js')).to.exist;
expect(pageA).to.include('<p>page-a.html</p>');
expect(pageA).to.include('<script type="module" src="./page-a.js"></script>');
expect(pageA).to.include('<script type="module" src="./shared.js"></script>');
expect(pageB).to.include('<p>page-b.html</p>');
expect(pageB).to.include('<script type="module" src="./page-b.js"></script>');
expect(pageB).to.include('<script type="module" src="./shared.js"></script>');
expect(pageC).to.include('<p>page-c.html</p>');
expect(pageC).to.include('<script type="module" src="./page-c.js"></script>');
expect(pageC).to.include('<script type="module" src="./shared.js"></script>');
});
it('can exclude globs', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: 'exclude/**/*.html',
exclude: '**/partial.html',
rootDir,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
});
it('creates unique inline script names', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: [
{
name: 'foo/index.html',
html: '<h1>Page A</h1><script type="module">console.log("A")</script>',
},
{
name: 'bar/index.html',
html: '<h1>Page B</h1><script type="module">console.log("B")</script>',
},
{
name: 'x.html',
html: '<h1>Page C</h1><script type="module">console.log("C")</script>',
},
],
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(6);
expect(getChunk(output, 'inline-module-b8667c926d8a16ee8b4499492c1726ed.js')).to.exist;
expect(getChunk(output, 'inline-module-c91911481b66e7483731d4de5df616a6.js')).to.exist;
expect(getChunk(output, 'inline-module-fbf0242ebea027b7392472c19328791d.js')).to.exist;
expect(getAsset(output, 'foo/index.html').source).to.equal(
'<html><head></head><body><h1>Page A</h1><script type="module" src="../inline-module-b8667c926d8a16ee8b4499492c1726ed.js"></script></body></html>',
);
expect(getAsset(output, 'bar/index.html').source).to.equal(
'<html><head></head><body><h1>Page B</h1><script type="module" src="../inline-module-c91911481b66e7483731d4de5df616a6.js"></script></body></html>',
);
expect(getAsset(output, 'x.html').source).to.equal(
'<html><head></head><body><h1>Page C</h1><script type="module" src="./inline-module-fbf0242ebea027b7392472c19328791d.js"></script></body></html>',
);
});
it('deduplicates common modules', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: [
{
name: 'a.html',
html: '<h1>Page A</h1><script type="module">console.log("A")</script>',
},
{
name: 'b.html',
html: '<h1>Page B</h1><script type="module">console.log("A")</script>',
},
{
name: 'c.html',
html: '<h1>Page C</h1><script type="module">console.log("A")</script>',
},
],
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
expect(getChunk(output, 'inline-module-b8667c926d8a16ee8b4499492c1726ed.js')).to.exist;
expect(getAsset(output, 'a.html').source).to.equal(
'<html><head></head><body><h1>Page A</h1><script type="module" src="./inline-module-b8667c926d8a16ee8b4499492c1726ed.js"></script></body></html>',
);
expect(getAsset(output, 'b.html').source).to.equal(
'<html><head></head><body><h1>Page B</h1><script type="module" src="./inline-module-b8667c926d8a16ee8b4499492c1726ed.js"></script></body></html>',
);
expect(getAsset(output, 'c.html').source).to.equal(
'<html><head></head><body><h1>Page C</h1><script type="module" src="./inline-module-b8667c926d8a16ee8b4499492c1726ed.js"></script></body></html>',
);
});
it('outputs the hashed entrypoint name', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: {
html:
'<h1>Hello world</h1>' + `<script type="module" src="./entrypoint-a.js"></script>`,
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate({
...outputConfig,
entryFileNames: '[name]-[hash].js',
});
expect(output.length).to.equal(2);
const entrypoint = output.find(f =>
// @ts-ignore
f.facadeModuleId.endsWith('entrypoint-a.js'),
) as OutputChunk;
// ensure it's actually hashed
expect(entrypoint.fileName).to.not.equal('entrypoint-a.js');
// get hashed name dynamically
expect(getAsset(output, 'index.html').source).to.equal(
`<html><head></head><body><h1>Hello world</h1><script type="module" src="./${entrypoint.fileName}"></script></body></html>`,
);
});
it('outputs import path relative to the final output html', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: {
name: 'pages/index.html',
html: '<h1>Hello world</h1><script type="module" src="../entrypoint-a.js"></script>',
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(getAsset(output, 'pages/index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1><script type="module" src="../entrypoint-a.js"></script></body></html>',
);
});
it('can change HTML root directory', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir: path.join(__dirname, 'fixtures'),
input: {
name: 'rollup-plugin-html/pages/index.html',
html: '<h1>Hello world</h1><script type="module" src="../entrypoint-a.js"></script>',
},
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(getAsset(output, 'rollup-plugin-html/pages/index.html').source).to.equal(
'<html><head></head><body><h1>Hello world</h1><script type="module" src="../../entrypoint-a.js"></script></body></html>',
);
});
it('can get the input with getInputs()', async () => {
// default filename
const pluginA = rollupPluginHTML({ input: { html: 'Hello world' } });
// filename inferred from input filename
const pluginB = rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/my-page.html'),
});
// filename explicitly set
const pluginC = rollupPluginHTML({
input: {
name: 'pages/my-other-page.html',
path: require.resolve('./fixtures/rollup-plugin-html/index.html'),
},
});
await rollup({
input: require.resolve('./fixtures/rollup-plugin-html/entrypoint-a.js'),
plugins: [pluginA],
});
await rollup({ plugins: [pluginB] });
await rollup({ plugins: [pluginC] });
expect(pluginA.api.getInputs()[0].name).to.equal('index.html');
expect(pluginB.api.getInputs()[0].name).to.equal('my-page.html');
expect(pluginC.api.getInputs()[0].name).to.equal('pages/my-other-page.html');
});
it('supports other plugins injecting a transform function', async () => {
const config = {
plugins: [
rollupPluginHTML({
rootDir,
input: require.resolve('./fixtures/rollup-plugin-html/index.html'),
}),
{
name: 'other-plugin',
buildStart(options) {
if (!options.plugins) throw new Error('no plugins');
const plugin = options.plugins.find(pl => {
if (pl.name === '@web/rollup-plugin-html') {
return pl!.api.getInputs()[0].name === 'index.html';
}
return false;
});
plugin!.api.addHtmlTransformer((html: string) =>
html.replace('</body>', '<!-- injected --></body>'),
);
},
} as Plugin,
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><h1>hello world</h1>' +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'<!-- injected --></body></html>',
);
});
it('includes referenced assets in the bundle', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<head>
<link rel="apple-touch-icon" sizes="180x180" href="./image-a.png" />
<link rel="icon" type="image/png" sizes="32x32" href="./image-b.png" />
<link rel="manifest" href="./webmanifest.json" />
<link rel="mask-icon" href="./image-a.svg" color="#3f93ce" />
<link rel="stylesheet" href="./styles.css" />
<link rel="stylesheet" href="./foo/x.css" />
<link rel="stylesheet" href="./foo/bar/y.css" />
</head>
<body>
<img src="./image-c.png" />
<div>
<img src="./image-b.svg" />
</div>
</body>
</html>`,
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(11);
const expectedAssets = [
'image-c.png',
'webmanifest.json',
'image-a.svg',
'styles.css',
'x.css',
'y.css',
'image-b.svg',
];
for (const name of expectedAssets) {
const asset = getAsset(output, name);
expect(asset).to.exist;
expect(asset.source).to.exist;
}
const outputHtml = getAsset(output, 'index.html').source;
expect(outputHtml).to.include(
'<link rel="apple-touch-icon" sizes="180x180" href="assets/image-a.png">',
);
expect(outputHtml).to.include(
'<link rel="icon" type="image/png" sizes="32x32" href="assets/image-b.png">',
);
expect(outputHtml).to.include('<link rel="manifest" href="assets/webmanifest.json">');
expect(outputHtml).to.include(
'<link rel="mask-icon" href="assets/image-a.svg" color="#3f93ce">',
);
expect(outputHtml).to.include('<link rel="stylesheet" href="assets/styles-hdiMuZ9V.css">');
expect(outputHtml).to.include('<link rel="stylesheet" href="assets/x-wxoPDuod.css">');
expect(outputHtml).to.include('<link rel="stylesheet" href="assets/y-yU65zx9z.css">');
expect(outputHtml).to.include('<img src="assets/image-c-Mr5Lb2jQ.png">');
expect(outputHtml).to.include('<img src="assets/image-b-yrDWczn5.svg">');
});
it('deduplicates static assets with similar names', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<head>
<link rel="icon" type="image/png" sizes="32x32" href="./foo.svg" />
<link rel="mask-icon" href="./x/foo.svg" color="#3f93ce" />
</head>
</html>`,
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head>' +
'<link rel="icon" type="image/png" sizes="32x32" href="assets/foo.svg">' +
'<link rel="mask-icon" href="assets/foo1.svg" color="#3f93ce">' +
'</head><body></body></html>',
);
});
it('static and hashed asset nodes can reference the same files', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<head>
<link rel="icon" type="image/png" sizes="32x32" href="./foo.svg">
<img src="./foo.svg">
</head>
</html>`,
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head><link rel="icon" type="image/png" sizes="32x32" href="assets/foo.svg"></head>' +
'<body><img src="assets/foo-WjgrfMGT.svg"></body></html>',
);
});
it('deduplicates common assets', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<body>
<link rel="stylesheet" href="./image-a.png">
<img src="./image-a.png">
<img src="./image-a.png">
</body>
</html>`,
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body>' +
'<link rel="stylesheet" href="assets/image-a-Mr5Lb2jQ.png">' +
'<img src="assets/image-a-Mr5Lb2jQ.png">' +
'<img src="assets/image-a-Mr5Lb2jQ.png">' +
'</body></html>',
);
});
it('deduplicates common assets across HTML files', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: [
{
name: 'page-a.html',
html: `<html>
<body>
<img src="./image-a.png">
</body>
</html>`,
},
{
name: 'page-b.html',
html: `<html>
<body>
<link rel="stylesheet" href="./image-a.png">
</body>
</html>`,
},
{
name: 'page-c.html',
html: `<html>
<body>
<link rel="stylesheet" href="./image-a.png">
<img src="./image-a.png">
</body>
</html>`,
},
],
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'page-a.html').source)).to.equal(
'<html><head></head><body>' +
' <img src="assets/image-a-Mr5Lb2jQ.png">' +
' </body></html>',
);
expect(stripNewlines(getAsset(output, 'page-b.html').source)).to.equal(
'<html><head></head><body>' +
' <link rel="stylesheet" href="assets/image-a-Mr5Lb2jQ.png">' +
' </body></html>',
);
expect(stripNewlines(getAsset(output, 'page-c.html').source)).to.equal(
'<html><head></head><body>' +
' <link rel="stylesheet" href="assets/image-a-Mr5Lb2jQ.png">' +
' <img src="assets/image-a-Mr5Lb2jQ.png">' +
' </body></html>',
);
});
it('can turn off extracting assets', async () => {
const config = {
plugins: [
rollupPluginHTML({
extractAssets: false,
input: {
html: `<html>
<body>
<img src="./image-c.png" />
<link rel="stylesheet" href="./styles.css" />
<img src="./image-b.svg" />
</body>
</html>`,
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(2);
expect(stripNewlines(getAsset(output, 'index.html').source)).to.equal(
'<html><head></head><body><img src="./image-c.png"><link rel="stylesheet" href="./styles.css"><img src="./image-b.svg"></body></html>',
);
});
it('can inject a CSP meta tag for inline scripts', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/csp-page-a.html'),
rootDir,
strictCSPInlineScripts: true,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'csp-page-a.html').source)).to.equal(
'<html><head>' +
"<meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'sha256-k0fj3IHUtZNziFbz6LL40uxkFlr28beNcMKKtp5+EwE=' 'sha256-UJadfRwzUCb1ajAJFfAPl8NTvtyiHtltKG/12veER70=';\">" +
'</head><body><h1>hello world</h1>' +
"<script>console.log('foo');</script>" +
"<script>console.log('bar');</script>" +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('can add to an existing CSP meta tag for inline scripts', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/csp-page-b.html'),
rootDir,
strictCSPInlineScripts: true,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'csp-page-b.html').source)).to.equal(
'<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' 'sha256-k0fj3IHUtZNziFbz6LL40uxkFlr28beNcMKKtp5+EwE=' 'sha256-UJadfRwzUCb1ajAJFfAPl8NTvtyiHtltKG/12veER70=';\">" +
'</head><body><h1>hello world</h1>' +
"<script>console.log('foo');</script>" +
"<script>console.log('bar');</script>" +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('can add to an existing CSP meta tag for inline scripts even if script-src is already there', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: require.resolve('./fixtures/rollup-plugin-html/csp-page-c.html'),
rootDir,
strictCSPInlineScripts: true,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(4);
const { code: entryA } = getChunk(output, 'entrypoint-a.js');
const { code: entryB } = getChunk(output, 'entrypoint-b.js');
expect(entryA).to.include("console.log('entrypoint-a.js');");
expect(entryB).to.include("console.log('entrypoint-b.js');");
expect(stripNewlines(getAsset(output, 'csp-page-c.html').source)).to.equal(
'<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' 'sha256-k0fj3IHUtZNziFbz6LL40uxkFlr28beNcMKKtp5+EwE=' 'sha256-UJadfRwzUCb1ajAJFfAPl8NTvtyiHtltKG/12veER70=';\">" +
'</head><body><h1>hello world</h1>' +
"<script>console.log('foo');</script>" +
"<script>console.log('bar');</script>" +
'<script type="module" src="./entrypoint-a.js"></script>' +
'<script type="module" src="./entrypoint-b.js"></script>' +
'</body></html>',
);
});
it('can inject a service worker registration script if injectServiceWorker and serviceWorkerPath are provided', async () => {
const serviceWorkerPath = path.join(
// @ts-ignore
path.resolve(outputConfig.dir),
'service-worker.js',
);
const config = {
plugins: [
rollupPluginHTML({
input: '**/*.html',
rootDir: path.join(__dirname, 'fixtures', 'inject-service-worker'),
flattenOutput: false,
injectServiceWorker: true,
serviceWorkerPath,
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
function extractServiceWorkerPath(src: string) {
const registerOpen = src.indexOf(".register('");
const registerClose = src.indexOf("')", registerOpen + 11);
return src.substring(registerOpen + 11, registerClose);
}
expect(extractServiceWorkerPath(getAsset(output, 'index.html').source)).to.equal(
'service-worker.js',
);
expect(
extractServiceWorkerPath(getAsset(output, path.join('sub-with-js', 'index.html')).source),
).to.equal(`../service-worker.js`);
expect(
extractServiceWorkerPath(getAsset(output, path.join('sub-pure-html', 'index.html')).source),
).to.equal(`../service-worker.js`);
});
it('does support a absolutePathPrefix to allow for sub folder deployments', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<body>
<img src="/my-prefix/x/foo.svg" />
<link rel="stylesheet" href="../styles.css" />
<img src="../image-b.svg" />
</body>
</html>`,
name: 'x/index.html',
},
rootDir: path.join(__dirname, 'fixtures', 'assets'),
absolutePathPrefix: '/my-prefix/',
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(stripNewlines(getAsset(output, 'x/index.html').source)).to.equal(
[
'<html><head></head><body>',
'<img src="../assets/foo-ACZ5M5Wv.svg">',
'<link rel="stylesheet" href="../assets/styles-hdiMuZ9V.css">',
'<img src="../assets/image-b-yrDWczn5.svg">',
'</body></html>',
].join(''),
);
});
it('handles fonts linked from css files', async () => {
const config = {
plugins: [
rollupPluginHTML({
bundleAssetsFromCss: true,
input: {
html: `
<html>
<head>
<link rel="stylesheet" href="./styles-with-fonts.css" />
</head>
<body>
</body>
</html>
`,
},
rootDir: path.join(__dirname, 'fixtures', 'resolves-assets-in-styles'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
const fontNormal = output.find(o => o.name?.endsWith('font-normal.woff2'));
const fontBold = output.find(o => o.name?.endsWith('font-normal.woff2'));
const style = output.find(o => o.name?.endsWith('styles-with-fonts.css'));
// It has emitted the font
expect(fontBold).to.exist;
expect(fontNormal).to.exist;
// e.g. "font-normal-f0mNRiTD.woff2"
const regex = /assets\/font-normal-\w+\.woff2/;
// It outputs the font to the assets folder
expect(regex.test(fontNormal!.fileName)).to.equal(true);
// The source of the style includes the font
const source = (style as OutputAsset)?.source.toString();
expect(source.includes(fontNormal!.fileName));
});
it('handles fonts linked from css files in node_modules', async () => {
const config = {
plugins: [
rollupPluginHTML({
bundleAssetsFromCss: true,
input: {
html: `
<html>
<head>
<link rel="stylesheet" href="./node_modules/foo/node_modules-styles-with-fonts.css" />
</head>
<body>
</body>
</html>
`,
},
rootDir: path.join(__dirname, 'fixtures', 'resolves-assets-in-styles-node-modules'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
const font = output.find(o => o.name?.endsWith('font-normal.woff2'));
const style = output.find(o => o.name?.endsWith('node_modules-styles-with-fonts.css'));
// It has emitted the font
expect(font).to.exist;
// e.g. "font-normal-f0mNRiTD.woff2"
const regex = /assets\/font-normal-\w+\.woff2/;
// It outputs the font to the assets folder
expect(regex.test(font!.fileName)).to.equal(true);
// The source of the style includes the font
const source = (style as OutputAsset)?.source.toString();
expect(source.includes(font!.fileName));
});
it('handles duplicate fonts correctly', async () => {
const config = {
plugins: [
rollupPluginHTML({
bundleAssetsFromCss: true,
input: {
html: `
<html>
<head>
<link rel="stylesheet" href="./styles-a.css" />
<link rel="stylesheet" href="./styles-b.css" />
</head>
<body>
</body>
</html>
`,
},
rootDir: path.join(__dirname, 'fixtures', 'resolves-assets-in-styles-duplicates'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
const fonts = output.filter(o => o.name?.endsWith('font-normal.woff2'));
expect(fonts.length).to.equal(1);
});
it('handles images referenced from css', async () => {
const config = {
plugins: [
rollupPluginHTML({
bundleAssetsFromCss: true,
input: {
html: `
<html>
<head>
<link rel="stylesheet" href="./styles.css" />
</head>
<body>
</body>
</html>
`,
},
rootDir: path.join(__dirname, 'fixtures', 'resolves-assets-in-styles-images'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.find(o => o.name?.endsWith('star.avif'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.gif'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.jpeg'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.jpg'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.png'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.svg'))).to.exist;
expect(output.find(o => o.name?.endsWith('star.webp'))).to.exist;
const rewrittenCss = (output.find(o => o.name === 'styles.css') as OutputAsset).source
.toString()
.trim();
expect(rewrittenCss).to.equal(
`#a {
background-image: url("assets/star-mrrzn5BV.svg");
}
#b {
background-image: url("assets/star-mrrzn5BV.svg#foo");
}
#c {
background-image: url("assets/star-eErsO14u.png");
}
#d {
background-image: url("assets/star-yqfHyXQC.jpg");
}
#e {
background-image: url("assets/star-G_i5Rpoh.jpeg");
}
#f {
background-image: url("assets/star-l7b58t3m.webp");
}
#g {
background-image: url("assets/star-P4TYRBwL.gif");
}
#h {
background-image: url("assets/star-H06WHrYy.avif");
}`.trim(),
);
});
it('allows to exclude external assets usign a glob pattern', async () => {
const config = {
plugins: [
rollupPluginHTML({
input: {
html: `<html>
<head>
<link rel="apple-touch-icon" sizes="180x180" href="./image-a.png" />
<link rel="icon" type="image/png" sizes="32x32" href="image-d.png" />
<link rel="manifest" href="./webmanifest.json" />
<link rel="mask-icon" href="./image-a.svg" color="#3f93ce" />
<link rel="mask-icon" href="image-d.svg" color="#3f93ce" />
<link rel="stylesheet" href="./styles-with-referenced-assets.css" />
<link rel="stylesheet" href="./foo/x.css" />
<link rel="stylesheet" href="foo/bar/y.css" />
</head>
<body>
<img src="./image-d.png" />
<div>
<img src="./image-d.svg" />
</div>
</body>
</html>`,
},
bundleAssetsFromCss: true,
externalAssets: ['**/foo/**/*', '*.svg'],
rootDir: path.join(__dirname, 'fixtures', 'assets'),
}),
],
};
const bundle = await rollup(config);
const { output } = await bundle.generate(outputConfig);
expect(output.length).to.equal(8);
const expectedAssets = [
'assets/image-a.png',
'assets/image-d.png',
'styles-with-referenced-assets.css',
'image-a.png',
'image-d.png',
'webmanifest.json',
];
for (const name of expectedAssets) {
const asset = getAsset(output, name);
expect(asset).to.exist;
expect(asset.source).to.exist;
}
const outputHtml = getAsset(output, 'index.html').source;
expect(outputHtml).to.include(
'<link rel="apple-touch-icon" sizes="180x180" href="assets/image-a.png">',
);
expect(outputHtml).to.include(
'<link rel="icon" type="image/png" sizes="32x32" href="assets/image-d.png">',
);
expect(outputHtml).to.include('<link rel="manifest" href="assets/webmanifest.json">');
expect(outputHtml).to.include('<link rel="mask-icon" href="./image-a.svg" color="#3f93ce">');
expect(outputHtml).to.include('<link rel="mask-icon" href="image-d.svg" color="#3f93ce">');
expect(outputHtml).to.include(
'<link rel="stylesheet" href="assets/styles-with-referenced-assets-NuwIw8gN.css">',
);
expect(outputHtml).to.include('<link rel="stylesheet" href="./foo/x.css">');
expect(outputHtml).to.include('<link rel="stylesheet" href="foo/bar/y.css">');
expect(outputHtml).to.include('<img src="assets/assets/image-d-y8_AQMDl.png">');
expect(outputHtml).to.include('<img src="./image-d.svg">');
const rewrittenCss = getAsset(output, 'styles-with-referenced-assets.css')
.source.toString()
.trim();
expect(rewrittenCss).to.equal(
`#a1 {
background-image: url("assets/image-a-Mr5Lb2jQ.png");
}
#a2 {
background-image: url("image-a.svg");
}
#d1 {
background-image: url("assets/image-d-y8_AQMDl.png");
}
#d2 {
background-image: url("./image-d.svg");
}`.trim(),
);
});
});
| modernweb-dev/web/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-html/test/rollup-plugin-html.test.ts",
"repo_id": "modernweb-dev",
"token_count": 20507
} | 198 |
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 directories = [
new URL('./', import.meta.url),
new URL('./one', import.meta.url),
new URL('./one/', import.meta.url),
new URL('./one/two', import.meta.url),
new URL('./one/two/', import.meta.url),
];
console.log({
justUrlObject,
href,
pathname,
searchParams,
directories,
});
| modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/directories-and-simple-entrypoint.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-import-meta-assets/test/fixtures/directories-and-simple-entrypoint.js",
"repo_id": "modernweb-dev",
"token_count": 215
} | 199 |
# Rollup Plugin Polyfills Loader
Rollup plugin for injecting a [Polyfills Loader](https://modern-web.dev/docs/building/polyfills-loader/) into a HTML file generated by `@web/rollup-plugin-html`
See [our website](https://modern-web.dev/docs/building/rollup-plugin-polyfills-loader/) for full documentation.
| modernweb-dev/web/packages/rollup-plugin-polyfills-loader/README.md/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-polyfills-loader/README.md",
"repo_id": "modernweb-dev",
"token_count": 94
} | 200 |
/** Handles ESM imports */
import { a } from './some-module.js';
console.log(a);
/** Handles process.env */
if (process.env.NODE_ENV === 'production') {
console.log('foo');
}
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
| modernweb-dev/web/packages/rollup-plugin-workbox/demo/injectManifestSwSrc.js/0 | {
"file_path": "modernweb-dev/web/packages/rollup-plugin-workbox/demo/injectManifestSwSrc.js",
"repo_id": "modernweb-dev",
"token_count": 88
} | 201 |
// based on https://github.com/storybookjs/storybook/blob/v7.0.9/code/lib/builder-vite/src/codegen-modern-iframe-script.ts
import { loadPreviewOrConfigFile } from '@storybook/core-common';
import type { Options, PreviewAnnotation } from '@storybook/types';
import { virtualSetupAddonsFilename, virtualStoriesFilename } from './virtual-file-names.js';
export async function generateAppScript(options: Options) {
const { presets, configDir } = options;
const previewOrConfigFile = loadPreviewOrConfigFile({ configDir });
const previewAnnotations = await presets.apply<PreviewAnnotation[]>(
'previewAnnotations',
[],
options,
);
const previewAnnotationURLs = [...previewAnnotations, previewOrConfigFile]
.filter((path): path is PreviewAnnotation => !!path)
.map((path: PreviewAnnotation) => (typeof path === 'object' ? path.bare : path));
// This is pulled out to a variable because it is reused in both the initial page load
// and the HMR handler. We don't use the hot.accept callback params because only the changed
// modules are provided, the rest are null. We can just re-import everything again in that case.
const getPreviewAnnotationsFunction = `
const getProjectAnnotations = async () => {
const configs = await Promise.all([
${previewAnnotationURLs.map(previewAnnotation => ` import('${previewAnnotation}')`).join(',\n')}
]);
return composeConfigs(configs);
}
`.trim();
return `
import { composeConfigs, PreviewWeb, ClientApi } from '@storybook/preview-api';
import '${virtualSetupAddonsFilename}';
import { importFn } from '${virtualStoriesFilename}';
${getPreviewAnnotationsFunction}
window.__STORYBOOK_PREVIEW__ = window.__STORYBOOK_PREVIEW__ || new PreviewWeb();
window.__STORYBOOK_STORY_STORE__ = window.__STORYBOOK_STORY_STORE__ || window.__STORYBOOK_PREVIEW__.storyStore;
window.__STORYBOOK_CLIENT_API__ = window.__STORYBOOK_CLIENT_API__ || new ClientApi({ storyStore: window.__STORYBOOK_PREVIEW__.storyStore });
window.__STORYBOOK_PREVIEW__.initialize({ importFn, getProjectAnnotations });
`.trim();
}
| modernweb-dev/web/packages/storybook-builder/src/generate-app-script.ts/0 | {
"file_path": "modernweb-dev/web/packages/storybook-builder/src/generate-app-script.ts",
"repo_id": "modernweb-dev",
"token_count": 645
} | 202 |
# Storybook framework for `@web/storybook-builder` + Web Components
See [our website](https://modern-web.dev/docs/storybook-builder/frameworks/#webstorybook-framework-web-components) for full documentation.
| modernweb-dev/web/packages/storybook-framework-web-components/README.md/0 | {
"file_path": "modernweb-dev/web/packages/storybook-framework-web-components/README.md",
"repo_id": "modernweb-dev",
"token_count": 58
} | 203 |
export class Manager {
/**
* @param {import('@playwright/test').Page} page
*/
constructor(page) {
this.page = page;
}
/**
* @param {string} title
*/
toolbarItemByTitle(title) {
return this.page.locator(`[title="${title}"]`);
}
/**
* @param {string} text
*/
panelButtonByText(text) {
return this.page
.locator('[role="tablist"] button')
.filter({ hasText: new RegExp(`^${text}$`) });
}
}
| modernweb-dev/web/packages/storybook-framework-web-components/tests/manager.js/0 | {
"file_path": "modernweb-dev/web/packages/storybook-framework-web-components/tests/manager.js",
"repo_id": "modernweb-dev",
"token_count": 185
} | 204 |
/**
* Manages browserstack-local instance, making sure there is only one per
* instance set up for all browser launchers.
*/
import browserstack from 'browserstack-local';
import { BrowserLauncher } from '@web/test-runner-core';
import { promisify } from 'util';
import { nanoid } from 'nanoid';
const launchers = new Set<BrowserLauncher>();
let connection: browserstack.Local | undefined = undefined;
export const localId = `web-test-runner-${nanoid()}`;
async function setupLocalConnection(password: string, options: Partial<browserstack.Options> = {}) {
process.on('SIGINT', closeLocalConnection);
process.on('SIGTERM', closeLocalConnection);
process.on('beforeExit', closeLocalConnection);
process.on('exit', closeLocalConnection);
connection = new browserstack.Local();
console.log('[Browserstack] Setting up Browserstack Local proxy...');
await promisify(connection.start).bind(connection)({
key: password,
force: true,
localIdentifier: localId,
...options,
});
}
function closeLocalConnection() {
if (connection && (connection as any).pid != null) {
process.kill((connection as any).pid);
connection = undefined;
}
}
export async function registerBrowserstackLocal(
launcher: BrowserLauncher,
password: string,
options: Partial<browserstack.Options> = {},
) {
launchers.add(launcher);
if (!connection) {
await setupLocalConnection(password, options);
}
}
export function unregisterBrowserstackLocal(launcher: BrowserLauncher) {
launchers.delete(launcher);
if (connection && launchers.size === 0) {
closeLocalConnection();
}
}
| modernweb-dev/web/packages/test-runner-browserstack/src/browserstackManager.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-browserstack/src/browserstackManager.ts",
"repo_id": "modernweb-dev",
"token_count": 472
} | 205 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const {
setViewportPlugin,
emulateMediaPlugin,
selectOptionPlugin,
setUserAgentPlugin,
sendKeysPlugin,
sendMousePlugin,
a11ySnapshotPlugin,
filePlugin,
snapshotPlugin,
} = cjsEntrypoint;
export {
setViewportPlugin,
emulateMediaPlugin,
selectOptionPlugin,
setUserAgentPlugin,
sendKeysPlugin,
sendMousePlugin,
a11ySnapshotPlugin,
filePlugin,
snapshotPlugin,
};
| modernweb-dev/web/packages/test-runner-commands/plugins.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/plugins.mjs",
"repo_id": "modernweb-dev",
"token_count": 169
} | 206 |
import { emulateMedia } from '../../browser/commands.mjs';
import { expect } from '../chai.js';
it('can emulate forced colors', async () => {
await emulateMedia({ forcedColors: 'active' });
expect(matchMedia('(forced-colors: active)').matches).to.be.true;
await emulateMedia({ forcedColors: 'none' });
expect(matchMedia('(forced-colors: none)').matches).to.be.true;
});
| modernweb-dev/web/packages/test-runner-commands/test/emulate-media/forced-colors-test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/emulate-media/forced-colors-test.js",
"repo_id": "modernweb-dev",
"token_count": 124
} | 207 |
import path from 'path';
import { runTests } from '@web/test-runner-core/test-helpers';
import { chromeLauncher } from '@web/test-runner-chrome';
import { setUserAgentPlugin } from '../../src/setUserAgentPlugin.js';
describe('setUserAgentPlugin', function test() {
this.timeout(20000);
it('can set the user agent on puppeteer', async () => {
await runTests({
files: [path.join(__dirname, 'browser-test.js')],
browsers: [chromeLauncher()],
plugins: [setUserAgentPlugin()],
});
});
});
| modernweb-dev/web/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-commands/test/set-user-agent/setUserAgentPlugin.test.ts",
"repo_id": "modernweb-dev",
"token_count": 184
} | 208 |
{
"name": "@web/test-runner-core",
"version": "0.13.1",
"publishConfig": {
"access": "public"
},
"description": "Web test runner core",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/modernweb-dev/web.git",
"directory": "packages/test-runner-core"
},
"author": "modern-web",
"homepage": "https://github.com/modernweb-dev/web/tree/master/packages/test-runner-core",
"main": "./dist/index.js",
"module": "./index.mjs",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"require": "./dist/index.js"
},
"./test-helpers": {
"types": "./dist/test-helpers.d.ts",
"import": "./test-helpers.mjs",
"require": "./dist/test-helpers.js"
},
"./browser/session.js": "./browser/session.js"
},
"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",
"core"
],
"dependencies": {
"@babel/code-frame": "^7.12.11",
"@types/babel__code-frame": "^7.0.2",
"@types/co-body": "^6.1.0",
"@types/convert-source-map": "^2.0.0",
"@types/debounce": "^1.2.0",
"@types/istanbul-lib-coverage": "^2.0.3",
"@types/istanbul-reports": "^3.0.0",
"@web/browser-logs": "^0.4.0",
"@web/dev-server-core": "^0.7.0",
"chokidar": "^3.4.3",
"cli-cursor": "^3.1.0",
"co-body": "^6.1.0",
"convert-source-map": "^2.0.0",
"debounce": "^1.2.0",
"dependency-graph": "^0.11.0",
"globby": "^11.0.1",
"ip": "^2.0.1",
"istanbul-lib-coverage": "^3.0.0",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.0.2",
"log-update": "^4.0.0",
"nanocolors": "^0.2.1",
"nanoid": "^3.1.25",
"open": "^8.0.2",
"picomatch": "^2.2.2",
"source-map": "^0.7.3"
},
"devDependencies": {
"portfinder": "^1.0.32"
}
}
| modernweb-dev/web/packages/test-runner-core/package.json/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/package.json",
"repo_id": "modernweb-dev",
"token_count": 1105
} | 209 |
import { TestRunnerCoreConfig } from '../config/TestRunnerCoreConfig.js';
import { createTestSessions } from './createSessionGroups.js';
import { TestSession } from '../test-session/TestSession.js';
import { getTestCoverage, TestCoverage } from '../coverage/getTestCoverage.js';
import { TestScheduler } from './TestScheduler.js';
import { TestSessionManager } from '../test-session/TestSessionManager.js';
import { SESSION_STATUS } from '../test-session/TestSessionStatus.js';
import { EventEmitter } from '../utils/EventEmitter.js';
import { createSessionUrl } from './createSessionUrl.js';
import { createDebugSessions } from './createDebugSessions.js';
import { TestRunnerServer } from '../server/TestRunnerServer.js';
import { BrowserLauncher } from '../browser-launcher/BrowserLauncher.js';
import { TestRunnerGroupConfig } from '../config/TestRunnerGroupConfig.js';
interface EventMap {
'test-run-started': { testRun: number };
'test-run-finished': { testRun: number; testCoverage?: TestCoverage };
finished: boolean;
stopped: boolean;
}
export class TestRunner extends EventEmitter<EventMap> {
public config: TestRunnerCoreConfig;
public sessions: TestSessionManager;
public testFiles: string[];
public browsers: BrowserLauncher[];
public browserNames: string[];
public startTime = -1;
public testRun = -1;
public started = false;
public stopped = false;
public running = false;
public passed = false;
public focusedTestFile: string | undefined;
private scheduler: TestScheduler;
private server: TestRunnerServer;
private pendingSessions = new Set<TestSession>();
constructor(config: TestRunnerCoreConfig, groupConfigs: TestRunnerGroupConfig[] = []) {
super();
if (!config.manual && (!config.browsers || config.browsers.length === 0)) {
throw new Error('No browsers are configured to run tests');
}
if (config.manual && config.watch) {
throw new Error('Cannot combine the manual and watch options.');
}
if (config.open && !config.manual) {
throw new Error('The open option requires the manual option to be set.');
}
const { sessionGroups, testFiles, testSessions, browsers } = createTestSessions(
config,
groupConfigs,
);
this.config = config;
this.testFiles = testFiles;
this.browsers = browsers;
this.browserNames = Array.from(new Set(this.browsers.map(b => b.name)));
this.browserNames.sort(
(a, b) =>
this.browsers.findIndex(br => br.name === a) - this.browsers.findIndex(br => br.name === b),
);
this.sessions = new TestSessionManager(sessionGroups, testSessions);
this.scheduler = new TestScheduler(config, this.sessions, browsers);
this.server = new TestRunnerServer(
this.config,
this,
this.sessions,
this.testFiles,
sessions => {
this.runTests(sessions);
},
);
this.sessions.on('session-status-updated', session => {
if (session.status === SESSION_STATUS.FINISHED) {
this.onSessionFinished();
}
});
}
async start() {
try {
if (this.started) {
throw new Error('Cannot start twice.');
}
this.started = true;
this.startTime = Date.now();
await this.server.start();
if (!this.config.manual) {
for (const browser of this.browsers) {
if (browser.initialize) {
await browser.initialize(this.config, this.testFiles);
}
}
// the browser names can be updated after initialize
this.browserNames = Array.from(new Set(this.browsers.map(b => b.name)));
this.runTests(this.sessions.all());
}
} catch (error) {
this.stop(error);
}
}
async runTests(sessions: Iterable<TestSession>) {
if (this.stopped) {
return;
}
if (this.running) {
for (const session of sessions) {
this.pendingSessions.add(session);
}
return;
}
const sessionsToRun = this.focusedTestFile
? Array.from(sessions).filter(f => f.testFile === this.focusedTestFile)
: [...sessions, ...this.pendingSessions];
this.pendingSessions.clear();
if (sessionsToRun.length === 0) {
return;
}
try {
this.testRun += 1;
this.running = true;
this.scheduler.schedule(this.testRun, sessionsToRun);
this.emit('test-run-started', { testRun: this.testRun });
} catch (error) {
this.running = false;
this.stop(error);
}
}
async stop(error?: any) {
if (error instanceof Error) {
console.error('Error while running tests:');
console.error(error);
console.error('');
}
if (this.stopped) {
return;
}
this.stopped = true;
await this.scheduler.stop();
const stopActions = [];
const stopServerAction = this.server.stop().catch(error => {
console.error(error);
});
stopActions.push(stopServerAction);
if (this.config.watch) {
// we only need to stop the browsers in watch mode, in non-watch
// mode the scheduler has already stopped them
const stopActions = [];
for (const browser of this.browsers) {
if (browser.stop) {
stopActions.push(
browser.stop().catch(error => {
console.error(error);
}),
);
}
}
}
await Promise.all(stopActions);
this.emit('stopped', this.passed);
}
startDebugBrowser(testFile: string) {
const sessions = this.sessions.forTestFile(testFile);
const debugSessions = createDebugSessions(Array.from(sessions));
this.sessions.addDebug(...debugSessions);
for (const session of debugSessions) {
session.browser
.startDebugSession(session.id, createSessionUrl(this.config, session))
.catch(error => {
console.error(error);
});
}
}
private async onSessionFinished() {
try {
const finishedAll = Array.from(this.sessions.all()).every(
s => s.status === SESSION_STATUS.FINISHED,
);
if (finishedAll) {
let passedCoverage = true;
let testCoverage: TestCoverage | undefined = undefined;
if (this.config.coverage) {
testCoverage = getTestCoverage(this.sessions.all(), this.config.coverageConfig);
passedCoverage = testCoverage.passed;
}
setTimeout(() => {
// emit finished event after a timeout to ensure all event listeners have processed
// the session status updated event
this.emit('test-run-finished', { testRun: this.testRun, testCoverage });
this.running = false;
if (this.pendingSessions) {
this.runTests(this.pendingSessions);
}
});
if (!this.config.watch) {
setTimeout(async () => {
this.passed = passedCoverage && Array.from(this.sessions.failed()).length === 0;
this.emit('finished', this.passed);
});
}
}
} catch (error) {
this.stop(error);
}
}
}
| modernweb-dev/web/packages/test-runner-core/src/runner/TestRunner.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/runner/TestRunner.ts",
"repo_id": "modernweb-dev",
"token_count": 2759
} | 210 |
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { Plugin } from '@web/dev-server-core';
import { TestFramework } from '../../test-framework/TestFramework';
const TEST_FRAMEWORK_IMPORT_ROOT = '/__web-test-runner__/test-framework/';
async function readFile(codePath: string) {
if (!fs.existsSync(codePath)) {
throw new Error(
`The test framework at ${codePath} could not be loaded. ` +
'Are your dependencies installed correctly? Is there a server plugin or middleware that interferes?',
);
}
return await promisify(fs.readFile)(codePath, 'utf-8');
}
/**
* Serves test framework without requiring the files to be available within the root dir of the project.
*/
export function serveTestFrameworkPlugin(testFramework: TestFramework) {
const testFrameworkFilePath = path.resolve(testFramework.path);
const testFrameworkBrowserPath = testFrameworkFilePath.split(path.sep).join('/');
const testFrameworkImport = encodeURI(
path.posix.join(TEST_FRAMEWORK_IMPORT_ROOT, testFrameworkBrowserPath),
);
const testFrameworkPlugin: Plugin = {
name: 'wtr-serve-test-framework',
async serve(context) {
if (context.path.startsWith(TEST_FRAMEWORK_IMPORT_ROOT)) {
const importPath = decodeURI(context.path.replace(TEST_FRAMEWORK_IMPORT_ROOT, ''));
let filePath = importPath.split('/').join(path.sep);
// for posix the leading / will be stripped by path.join above
if (path.sep === '/') {
filePath = `/${filePath}`;
}
const body = await readFile(filePath);
return { body, type: 'js', headers: { 'cache-control': 'public, max-age=31536000' } };
}
},
};
return { testFrameworkImport, testFrameworkPlugin };
}
| modernweb-dev/web/packages/test-runner-core/src/server/plugins/serveTestFrameworkPlugin.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/server/plugins/serveTestFrameworkPlugin.ts",
"repo_id": "modernweb-dev",
"token_count": 633
} | 211 |
import { PARAM_MANUAL_SESSION, PARAM_SESSION_ID } from './constants.js';
/**
* Returns where a given path points to a test file. This should be
* a browser path, such as an import path or network request.
* @param path
*/
export function isTestFilePath(path: string) {
// create a URL with a dummy domain
const url = new URL(path, 'http://localhost:123');
return url.searchParams.has(PARAM_SESSION_ID) || url.searchParams.has(PARAM_MANUAL_SESSION);
}
| modernweb-dev/web/packages/test-runner-core/src/utils/isTestFilePath.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-core/src/utils/isTestFilePath.ts",
"repo_id": "modernweb-dev",
"token_count": 148
} | 212 |
# Code Coverage v8
Profile code coverage using v8. Internal package, used by `@web/test-runner-chrome` and `@web/test-runner-playwright`.
See [our website](https://modern-web.dev/docs/test-runner/overview/) for full documentation.
| modernweb-dev/web/packages/test-runner-coverage-v8/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-coverage-v8/README.md",
"repo_id": "modernweb-dev",
"token_count": 70
} | 213 |
import '../../../../../node_modules/chai/chai.js';
describe('real numbers forming a monoid', function() {
it('under addition', function() {
chai.expect(1 + 1).to.equal(2);
});
});
describe('off-by-one boolean logic errors', function() {
it('null hypothesis', function() {
chai.expect(true).to.be.true;
});
it('asserts error', function() {
chai.expect(false).to.be.true;
});
it.skip('tbd: confirm true positive', function() {
chai.expect(false).to.be.false;
});
});
describe('logging during a test', function() {
it('reports logs to JUnit', function() {
const actual = '🤷♂️';
console.log('actual is ', actual);
chai.expect(typeof actual).to.equal('string');
});
});
| modernweb-dev/web/packages/test-runner-junit-reporter/test/fixtures/multiple/simple-test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-junit-reporter/test/fixtures/multiple/simple-test.js",
"repo_id": "modernweb-dev",
"token_count": 271
} | 214 |
export const styles = `
@charset "utf-8";
body {
margin:0;
}
#mocha {
font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 60px 50px;
}
#mocha ul,
#mocha li {
margin: 0;
padding: 0;
}
#mocha ul {
list-style: none;
}
#mocha h1,
#mocha h2 {
margin: 0;
}
#mocha h1 {
margin-top: 15px;
font-size: 1em;
font-weight: 200;
}
#mocha h1 a {
text-decoration: none;
color: inherit;
}
#mocha h1 a:hover {
text-decoration: underline;
}
#mocha .suite .suite h1 {
margin-top: 0;
font-size: .8em;
}
#mocha .hidden {
display: none;
}
#mocha h2 {
font-size: 12px;
font-weight: normal;
cursor: pointer;
}
#mocha .suite {
margin-left: 15px;
}
#mocha .test {
margin-left: 15px;
overflow: hidden;
}
#mocha .test.pending:hover h2::after {
content: '(pending)';
font-family: arial, sans-serif;
}
#mocha .test.pass.medium .duration {
background: #c09853;
}
#mocha .test.pass.slow .duration {
background: #b94a48;
}
#mocha .test.pass::before {
content: '✓';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #00d6b2;
}
#mocha .test.pass .duration {
font-size: 9px;
margin-left: 5px;
padding: 2px 5px;
color: #fff;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
box-shadow: inset 0 1px 1px rgba(0,0,0,.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
}
#mocha .test.pass.fast .duration {
display: none;
}
#mocha .test.pending {
color: #0b97c4;
}
#mocha .test.pending::before {
content: '◦';
color: #0b97c4;
}
#mocha .test.fail {
color: #c00;
}
#mocha .test.fail pre {
color: black;
}
#mocha .test.fail::before {
content: '✖';
font-size: 12px;
display: block;
float: left;
margin-right: 5px;
color: #c00;
}
#mocha .test pre.error {
color: #c00;
max-height: 300px;
overflow: auto;
}
#mocha .test .html-error {
overflow: auto;
color: black;
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: -webkit-calc(100% - 42px);
max-width: -moz-calc(100% - 42px);
max-width: calc(100% - 42px); /*(2)*/
max-height: 300px;
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-box-shadow: 0 1px 3px #eee;
box-shadow: 0 1px 3px #eee;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
#mocha .test .html-error pre.error {
border: none;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-box-shadow: 0;
-moz-box-shadow: 0;
box-shadow: 0;
padding: 0;
margin: 0;
margin-top: 18px;
max-height: none;
}
/**
* (1): approximate for browsers not supporting calc
* (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border)
* ^^ seriously
*/
#mocha .test pre {
display: block;
float: left;
clear: left;
font: 12px/1.5 monaco, monospace;
margin: 5px;
padding: 15px;
border: 1px solid #eee;
max-width: 85%; /*(1)*/
max-width: -webkit-calc(100% - 42px);
max-width: -moz-calc(100% - 42px);
max-width: calc(100% - 42px); /*(2)*/
word-wrap: break-word;
border-bottom-color: #ddd;
-webkit-box-shadow: 0 1px 3px #eee;
-moz-box-shadow: 0 1px 3px #eee;
box-shadow: 0 1px 3px #eee;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
#mocha .test h2 {
position: relative;
}
#mocha .test a.replay {
position: absolute;
top: 3px;
right: 0;
text-decoration: none;
vertical-align: middle;
display: block;
width: 15px;
height: 15px;
line-height: 15px;
text-align: center;
background: #eee;
font-size: 15px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
-webkit-transition:opacity 200ms;
-moz-transition:opacity 200ms;
-o-transition:opacity 200ms;
transition: opacity 200ms;
opacity: 0.3;
color: #888;
}
#mocha .test:hover a.replay {
opacity: 1;
}
#mocha-report.pass .test.fail {
display: none;
}
#mocha-report.fail .test.pass {
display: none;
}
#mocha-report.pending .test.pass,
#mocha-report.pending .test.fail {
display: none;
}
#mocha-report.pending .test.pass.pending {
display: block;
}
#mocha-error {
color: #c00;
font-size: 1.5em;
font-weight: 100;
letter-spacing: 1px;
}
#mocha-stats {
position: fixed;
top: 15px;
right: 10px;
font-size: 12px;
margin: 0;
color: #888;
z-index: 1;
}
#mocha-stats .progress {
float: right;
padding-top: 0;
/**
* Set safe initial values, so mochas .progress does not inherit these
* properties from Bootstrap .progress (which causes .progress height to
* equal line height set in Bootstrap).
*/
height: auto;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
background-color: initial;
}
#mocha-stats em {
color: black;
}
#mocha-stats a {
text-decoration: none;
color: inherit;
}
#mocha-stats a:hover {
border-bottom: 1px solid #eee;
}
#mocha-stats li {
display: inline-block;
margin: 0 5px;
list-style: none;
padding-top: 11px;
}
#mocha-stats canvas {
width: 40px;
height: 40px;
}
#mocha code .comment { color: #ddd; }
#mocha code .init { color: #2f6fad; }
#mocha code .string { color: #5890ad; }
#mocha code .keyword { color: #8a6343; }
#mocha code .number { color: #2f6fad; }
@media screen and (max-device-width: 480px) {
#mocha {
margin: 60px 0px;
}
#mocha #stats {
position: absolute;
}
}
`;
| modernweb-dev/web/packages/test-runner-mocha/src/styles.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-mocha/src/styles.ts",
"repo_id": "modernweb-dev",
"token_count": 2926
} | 215 |
// this file is autogenerated with the generate-mjs-dts-entrypoints script
import cjsEntrypoint from './dist/index.js';
const { playwright, PlaywrightLauncher, devices, playwrightLauncher } = cjsEntrypoint;
export { playwright, PlaywrightLauncher, devices, playwrightLauncher };
| modernweb-dev/web/packages/test-runner-playwright/index.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-playwright/index.mjs",
"repo_id": "modernweb-dev",
"token_count": 81
} | 216 |
# Web Test Runner Puppeteer
Run tests using [Puppeteer](https://www.npmjs.com/package/puppeteer), using a bundled version of Chromium or Firefox (experimental).
See [our website](https://modern-web.dev/docs/test-runner/browser-launchers/puppeteer/) for full documentation.
| modernweb-dev/web/packages/test-runner-puppeteer/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-puppeteer/README.md",
"repo_id": "modernweb-dev",
"token_count": 84
} | 217 |
# Web Test Runner Sauce Labs
Browser launchers for web test runner to run tests remotely on [Sauce Labs](http://saucelabs.com/).
See [our website](https://modern-web.dev/docs/test-runner/browser-launchers/saucelabs/) for full documentation.
| modernweb-dev/web/packages/test-runner-saucelabs/README.md/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-saucelabs/README.md",
"repo_id": "modernweb-dev",
"token_count": 71
} | 218 |
import { Capabilities } from 'selenium-webdriver';
/**
* Wraps a Promise with a timeout, rejecing the promise with the timeout.
*/
export function withTimeout<T>(promise: Promise<T>, message: string, timeout: number): Promise<T> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error(message));
}, timeout);
promise
.then(val => {
resolve(val);
})
.catch(err => {
reject(err);
})
.finally(() => {
clearTimeout(timeoutId);
});
});
}
const isDefined = (_: unknown) => !!_;
function getPlatform(c: Capabilities) {
return (
c.getPlatform() ||
c.get('platform') ||
[c.get('os'), c.get('os_version')].filter(isDefined).join(' ')
);
}
export function getBrowserName(c: Capabilities): string {
return c.getBrowserName() || c.get('browserName') || c.get('browser_name');
}
function getBrowserVersion(c: Capabilities): string {
return c.getBrowserVersion() || c.get('browserVersion') || c.get('browser_version');
}
export function getBrowserLabel(c: Capabilities): string {
return [getPlatform(c), getBrowserName(c), getBrowserVersion(c)].filter(_ => _).join(' ');
}
| modernweb-dev/web/packages/test-runner-selenium/src/utils.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-selenium/src/utils.ts",
"repo_id": "modernweb-dev",
"token_count": 439
} | 219 |
export class VisualRegressionError extends Error {}
| modernweb-dev/web/packages/test-runner-visual-regression/src/VisualRegressionError.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-visual-regression/src/VisualRegressionError.ts",
"repo_id": "modernweb-dev",
"token_count": 10
} | 220 |
import { TestRunnerCoreConfig } from '@web/test-runner-core';
import { Browser, Element } from 'webdriverio';
import { validateBrowserResult } from './coverage.js';
/**
* Manages tests to be executed in iframes on a page.
*/
export class IFrameManager {
private config: TestRunnerCoreConfig;
private driver: Browser;
private framePerSession = new Map<string, string>();
private inactiveFrames: string[] = [];
private frameCount = 0;
private initialized = false;
private initializePromise?: Promise<void>;
private locked?: Promise<unknown>;
private isIE: boolean;
constructor(config: TestRunnerCoreConfig, driver: Browser, isIE: boolean) {
this.config = config;
this.driver = driver;
this.isIE = isIE;
}
private async _initialize(url: string) {
const pageUrl = `${new URL(url).origin}/?mode=iframe`;
await this.driver.navigateTo(pageUrl);
}
isActive(id: string) {
return this.framePerSession.has(id);
}
async getBrowserUrl(sessionId: string): Promise<string | undefined> {
const frameId = this.getFrameId(sessionId);
const returnValue = (await this.driver.execute(`
try {
var iframe = document.getElementById("${frameId}");
return iframe.contentWindow.location.href;
} catch (_) {
return undefined;
}
`)) as string | undefined;
return returnValue;
}
private getFrameId(sessionId: string): string {
const frameId = this.framePerSession.get(sessionId);
if (!frameId) {
throw new Error(
`Something went wrong while running tests, there is no frame id for session ${sessionId}`,
);
}
return frameId;
}
private async scheduleCommand<T>(fn: () => Promise<T>) {
if (!this.isIE) {
return fn();
}
while (this.locked) {
await this.locked;
}
const fnPromise = fn();
this.locked = fnPromise;
const result = await fnPromise;
this.locked = undefined;
return result;
}
async queueStartSession(id: string, url: string) {
if (!this.initializePromise && !this.initialized) {
this.initializePromise = this._initialize(url);
}
if (this.initializePromise) {
await this.initializePromise;
this.initializePromise = undefined;
this.initialized = true;
}
this.scheduleCommand(() => this.startSession(id, url));
}
private async startSession(id: string, url: string) {
let frameId: string;
if (this.inactiveFrames.length > 0) {
frameId = this.inactiveFrames.pop()!;
await this.driver.execute(`
var iframe = document.getElementById("${frameId}");
iframe.src = "${url}";
`);
} else {
this.frameCount += 1;
frameId = `wtr-test-frame-${this.frameCount}`;
await this.driver.execute(`
var iframe = document.createElement("iframe");
iframe.id = "${frameId}";
iframe.src = "${url}";
document.body.appendChild(iframe);
`);
}
this.framePerSession.set(id, frameId);
}
async queueStopSession(id: string) {
return this.scheduleCommand(() => this.stopSession(id));
}
async stopSession(id: string) {
const frameId = this.getFrameId(id);
// Retrieve test results from iframe
const returnValue = await this.driver.executeAsync(`
var iframe = document.getElementById("${frameId}");
var testCoverage;
try {
testCoverage = iframe.contentWindow.__coverage__;
} catch (error) {
// iframe can throw a cross-origin error if the test navigated
}
// Don't move on until the iframe has settled after unloading the page
var done = arguments[arguments.length-1];
var loaded = function() {
iframe.removeEventListener('load', loaded);
iframe.removeEventListener('error', loaded);
done({ testCoverage: testCoverage });
};
iframe.addEventListener('load', loaded);
iframe.addEventListener('error', loaded);
// set src after retrieving values to avoid the iframe from navigating away
iframe.src = "about:blank";
`);
if (!validateBrowserResult(returnValue)) {
throw new Error();
}
const { testCoverage } = returnValue;
this.inactiveFrames.push(frameId);
return { testCoverage: this.config.coverage ? testCoverage : undefined };
}
async sendKeys(sessionId: string, keys: string[]) {
const frameId = this.getFrameId(sessionId);
const frame = await this.driver.$(`iframe#${frameId}`);
await this.driver.switchToFrame(frame);
return this.driver.keys(keys);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async performActions(_: string, _actions: object[]) {
throw new Error(
'Unsupported operation. In order to use device actions in Webdriver, set "concurrency" to 1.',
);
}
async takeScreenshot(sessionId: string, locator: string): Promise<Buffer> {
const frameId = this.getFrameId(sessionId);
const frame = await this.driver.$(`iframe#${frameId}`);
await this.driver.switchToFrame(frame);
const elementData = (await this.driver.execute(locator, [])) as Element;
const element = await this.driver.$(elementData);
let base64 = '';
try {
base64 = await this.driver.takeElementScreenshot(element.elementId);
} catch (err) {
console.log('Failed to take a screenshot:', err);
}
await this.driver.switchToParentFrame();
return Buffer.from(base64, 'base64');
}
}
| modernweb-dev/web/packages/test-runner-webdriver/src/IFrameManager.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-webdriver/src/IFrameManager.ts",
"repo_id": "modernweb-dev",
"token_count": 1995
} | 221 |
export default 'moduleFeaturesA';
| modernweb-dev/web/packages/test-runner-webdriver/test/fixtures/module-features-a.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner-webdriver/test/fixtures/module-features-a.js",
"repo_id": "modernweb-dev",
"token_count": 8
} | 222 |
import { expect } from '@esm-bundle/chai';
it('can run a test with focus b', async () => {
const input = document.createElement('input');
document.body.appendChild(input);
let firedEvent = false;
input.addEventListener('focus', () => {
firedEvent = true;
});
input.focus();
await new Promise(r => setTimeout(r, 100));
expect(firedEvent).to.be.true;
});
| modernweb-dev/web/packages/test-runner/demo/focus/test/focus-b.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/focus/test/focus-b.test.js",
"repo_id": "modernweb-dev",
"token_count": 124
} | 223 |
import { playwrightLauncher } from '@web/test-runner-playwright';
export default /** @type {import('@web/test-runner').TestRunnerConfig} */ ({
nodeResolve: true,
rootDir: '../../',
files: ['demo/test/pass-*.test.{js,html}'],
groups: [
{
name: 'chromium-a',
files: 'demo/test/pass-*.test.js',
browsers: [playwrightLauncher({ product: 'chromium' })],
},
{
name: 'chromium-b',
files: 'demo/test/pass-*.test.js',
browsers: [playwrightLauncher({ product: 'chromium' })],
},
{
name: 'firefox',
files: 'demo/test/pass-*.test.js',
browsers: [playwrightLauncher({ product: 'firefox' })],
},
{
name: 'webkit',
files: 'demo/test/pass-*.test.js',
browsers: [playwrightLauncher({ product: 'webkit' })],
},
],
});
| modernweb-dev/web/packages/test-runner/demo/groups.config.mjs/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/groups.config.mjs",
"repo_id": "modernweb-dev",
"token_count": 354
} | 224 |
/* @web/test-runner snapshot v1 */
export const snapshots = {}
snapshots["snapshot-a"] =
`some snapshot A`;
/* end snapshot snapshot-a */
snapshots["snapshot-b"] =
`some snapshot B`;
/* end snapshot snapshot-b */
snapshots["snapshot-c"] =
`some snapshot B`;
/* end snapshot snapshot-c */
| modernweb-dev/web/packages/test-runner/demo/test/__snapshots__/pass-snapshot.test.snap.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/__snapshots__/pass-snapshot.test.snap.js",
"repo_id": "modernweb-dev",
"token_count": 100
} | 225 |
import {
neverCalled,
neverCalledWithTrue,
calledOnce,
calledTwice,
calledThrice,
PublicClass,
} from './pass-coverage.js';
neverCalledWithTrue();
calledOnce();
calledTwice();
calledThrice();
const publicClass = new PublicClass();
publicClass.calledOnce();
publicClass.calledTwice();
publicClass.calledThrice();
| modernweb-dev/web/packages/test-runner/demo/test/pass-coverage-a.test.js/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/test/pass-coverage-a.test.js",
"repo_id": "modernweb-dev",
"token_count": 105
} | 226 |
import './shared-a.js';
import './shared-b.js';
| modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-15.test.d.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/demo/tsc/dist/test/pass-15.test.d.ts",
"repo_id": "modernweb-dev",
"token_count": 20
} | 227 |
import { TestRunnerGroupConfig } from '@web/test-runner-core';
import { readConfig, ConfigLoaderError } from '@web/config-loader';
import globby from 'globby';
import { TestRunnerStartError } from '../TestRunnerStartError.js';
function validateGroupConfig(configFilePath: string, config: Partial<TestRunnerGroupConfig>) {
if (config.browsers != null && !Array.isArray(config.browsers)) {
throw new TestRunnerStartError(
`Group config at ${configFilePath} has invalid browsers option. It should be an array.`,
);
}
if (config.files != null && !(typeof config.files === 'string' || Array.isArray(config.files))) {
throw new TestRunnerStartError(
`Group config at ${configFilePath} has an invalid files option. It should be a string or an array.`,
);
}
return { name: configFilePath, configFilePath, ...config } as TestRunnerGroupConfig;
}
export async function collectGroupConfigs(patterns: string[]) {
const groupConfigFiles = new Set<string>();
const groupConfigs: TestRunnerGroupConfig[] = [];
for (const pattern of patterns) {
const filePaths = globby.sync(pattern, { absolute: true });
for (const filePath of filePaths) {
groupConfigFiles.add(filePath);
}
}
for (const groupConfigFile of groupConfigFiles) {
try {
const maybeGroupConfig = (await readConfig(
'',
groupConfigFile,
)) as Partial<TestRunnerGroupConfig>;
const groupConfig = validateGroupConfig(groupConfigFile, maybeGroupConfig);
groupConfigs.push(groupConfig);
} catch (error) {
if (error instanceof ConfigLoaderError) {
throw new TestRunnerStartError(error.message);
}
throw error;
}
}
return groupConfigs;
}
| modernweb-dev/web/packages/test-runner/src/config/collectGroupConfigs.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/config/collectGroupConfigs.ts",
"repo_id": "modernweb-dev",
"token_count": 569
} | 228 |
import { TestSession, BufferedLogger } from '@web/test-runner-core';
import { bold, cyan } from 'nanocolors';
import { relative } from 'path';
import { reportTestsErrors } from './reportTestsErrors.js';
import { reportBrowserLogs } from './reportBrowserLogs.js';
import { reportRequest404s } from './reportRequest404s.js';
import { reportTestFileErrors } from './reportTestFileErrors.js';
export function reportTestFileResults(
logger: BufferedLogger,
testFile: string,
allBrowserNames: string[],
favoriteBrowser: string,
sessionsForTestFile: TestSession[],
) {
const failedSessions = sessionsForTestFile.filter(s => !s.passed);
reportBrowserLogs(logger, sessionsForTestFile);
reportRequest404s(logger, sessionsForTestFile);
reportTestFileErrors(logger, allBrowserNames, favoriteBrowser, sessionsForTestFile);
if (failedSessions.length > 0) {
reportTestsErrors(logger, allBrowserNames, favoriteBrowser, failedSessions);
}
if (logger.buffer.length > 0) {
logger.buffer.unshift({
method: 'log',
args: [`${bold(cyan(relative(process.cwd(), testFile)))}:\n`],
});
}
}
| modernweb-dev/web/packages/test-runner/src/reporter/reportTestFileResults.ts/0 | {
"file_path": "modernweb-dev/web/packages/test-runner/src/reporter/reportTestFileResults.ts",
"repo_id": "modernweb-dev",
"token_count": 368
} | 229 |
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { packages } from '../workspace-packages.mjs';
import merge from 'deepmerge';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const TSCONFIG_COMMENT = `// Don't edit this file directly. It is generated by generate-ts-configs script\n\n`;
const packagesRoot = path.join(__dirname, '..', 'packages');
const packageJSONMap = new Map();
const packageDirnameMap = new Map();
const internalDependencyMap = new Map();
// collect package json for all packages
packages.forEach(pkg => {
const packageJSONPath = path.join(packagesRoot, pkg.name, 'package.json');
if (!fs.existsSync(packageJSONPath)) {
console.error();
console.error(`Could not find package.json: ${packageJSONPath}`);
console.error();
process.exit(1);
}
const packageJSONData = JSON.parse(fs.readFileSync(packageJSONPath).toString());
const packageName = packageJSONData.name;
packageDirnameMap.set(packageName, pkg.name);
packageJSONMap.set(packageName, packageJSONData);
});
// collect initial cross package dependencies info
packageDirnameMap.forEach((_packageDirname, packageName) => {
const { dependencies, devDependencies } = packageJSONMap.get(packageName);
const internalDependencies = [
...(dependencies ? Object.keys(dependencies) : []),
...(devDependencies ? Object.keys(devDependencies) : []),
].filter(dep => packageDirnameMap.has(dep));
internalDependencyMap.set(packageName, internalDependencies);
});
function resolveInternalDependencies(dependencies) {
const childDeps = [];
for (const idep of dependencies) {
const deps = internalDependencyMap.get(idep);
const res = resolveInternalDependencies(deps);
for (const jdep of res) {
childDeps.push(jdep);
}
}
const resolved = childDeps.concat(dependencies);
// remove all duplicated after the first appearance
return resolved.filter((item, idx) => resolved.indexOf(item) === idx);
}
packageDirnameMap.forEach((packageDirname, packageName) => {
const pkg = packages.find(pkg => pkg.name === packageDirname);
const pkgDir = path.join(packagesRoot, packageDirname);
const tsconfigPath = path.join(pkgDir, 'tsconfig.json');
let tsConfigOverride = {};
const tsConfigOverridePath = path.join(pkgDir, 'tsconfig.override.json');
if (fs.existsSync(tsConfigOverridePath)) {
tsConfigOverride = JSON.parse(fs.readFileSync(tsConfigOverridePath));
}
const overwriteMerge = (destinationArray, sourceArray) => sourceArray;
const internalDependencies = resolveInternalDependencies(internalDependencyMap.get(packageName));
const tsconfigData = merge(
{
extends: `../../tsconfig.${pkg.environment === 'browser' ? 'browser' : 'node'}-base.json`,
compilerOptions: {
module: pkg.environment === 'browser' ? 'ESNext' : 'commonjs',
outDir: './dist',
rootDir: './src',
composite: true,
allowJs: true,
checkJs: pkg.type === 'js' ? true : undefined,
emitDeclarationOnly: pkg.type === 'js' ? true : undefined,
},
references: internalDependencies.map(dep => {
return { path: `../${packageDirnameMap.get(dep)}/tsconfig.json` };
}),
include: ['src', 'types'],
exclude: ['src/browser', 'tests', 'dist'],
},
tsConfigOverride,
{ arrayMerge: overwriteMerge },
);
if (pkg.ignoreTsConfig) {
return;
}
fs.writeFileSync(tsconfigPath, TSCONFIG_COMMENT + JSON.stringify(tsconfigData, null, ' '));
});
const projectLevelTsconfigPath = path.join(__dirname, '..', 'tsconfig.json');
const projectLevelTsconfigData = {
extends: './tsconfig.node-base.json',
files: [],
references: resolveInternalDependencies(Array.from(packageDirnameMap.keys())).map(
packageName => ({
path: `./packages/${packageDirnameMap.get(packageName)}/tsconfig.json`,
}),
),
};
fs.writeFileSync(
projectLevelTsconfigPath,
TSCONFIG_COMMENT + JSON.stringify(projectLevelTsconfigData, null, ' '),
);
| modernweb-dev/web/scripts/generate-ts-configs.mjs/0 | {
"file_path": "modernweb-dev/web/scripts/generate-ts-configs.mjs",
"repo_id": "modernweb-dev",
"token_count": 1381
} | 230 |
const path = require('path');
const commonRules = {
'no-mixed-operators': [
'error',
{
allowSamePrecedence: true,
},
],
'no-shadow': 1,
'jsx-a11y/anchor-is-valid': [
'warn',
{
components: ['Link'],
specialLink: ['to'],
},
],
'react/no-array-index-key': 1,
'react/require-default-props': 0,
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: ['.storybook/**', 'src/stories/**'],
},
],
'react/sort-comp': [2],
'react/jsx-indent': 'off',
'react/jsx-fragments': 'off',
'react/jsx-curly-newline': 'off',
'react/forbid-prop-types': 'off',
'react/static-property-placement': 'off',
'react/jsx-props-no-spreading': 'off',
'react/destructuring-assignment': 'off',
'react/prop-types': 'off',
'react/no-access-state-in-setstate': 'off',
'react/button-has-type': 'off',
'react/function-component-definition': 'off',
'react/default-props-match-prop-types': 'off',
'max-classes-per-file': 'off',
'import/no-cycle': 'off',
camelcase: 'off',
'default-param-last': 'off',
'no-restricted-exports': 'off',
'default-case-last': 'off',
'react/no-unused-class-component-methods': 'warn',
'react/no-unstable-nested-components': 'warn',
'react/no-unused-prop-types': 'warn',
radix: 'warn',
'no-use-before-define': 'warn',
'no-unused-vars': 'warn',
'no-unused-expressions': 'warn',
'no-param-reassign': 'warn',
'prefer-template': 'warn',
};
module.exports = {
parser: '@babel/eslint-parser',
env: {
browser: true,
jest: true,
},
settings: {
'import/resolver': {
node: {
paths: [path.resolve(__dirname, './src')],
},
},
},
extends: ['airbnb', 'prettier'],
rules: {
...commonRules,
'import/named': ['error'],
'react/state-in-constructor': 'off',
'react/destructuring-assignment': 'off',
'react/prop-types': 'off',
'react/no-access-state-in-setstate': 'off',
'react/button-has-type': 'off',
'max-classes-per-file': 'off',
'import/no-cycle': 'off',
'arrow-parens': 'off',
'operator-linebreak': 'off',
'react/jsx-wrap-multilines': 'off',
'react/jsx-one-expression-per-line': 'off',
'object-curly-newline': 'off',
'no-else-return': 'off',
'implicit-arrow-linebreak': 'off',
'prefer-object-spread': 'off',
'lines-between-class-members': 'off',
'react/jsx-tag-spacing': 'off',
'import/no-useless-path-segments': 'off',
'no-dupe-class-members': 'off',
},
overrides: [
{
files: ['./src/**/*.ts', './src/**/*.tsx'],
env: { browser: true, jest: true },
extends: [
'airbnb',
'plugin:import/typescript',
'plugin:@typescript-eslint/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: { jsx: true },
sourceType: 'module',
project: './tsconfig.json',
},
plugins: ['react', '@typescript-eslint'],
rules: {
...commonRules,
'@typescript-eslint/consistent-type-definitions': ['error', 'type'],
'@typescript-eslint/no-inferrable-types': [
'error',
{ ignoreProperties: true, ignoreParameters: false },
],
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'interface',
format: ['PascalCase'],
custom: {
regex: '^I[A-Z]',
match: true,
},
},
],
'@typescript-eslint/explicit-function-return-type': 'off',
'no-useless-constructor': 'off',
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/prefer-optional-chain': 'error',
'@typescript-eslint/prefer-nullish-coalescing': 'error',
'react/jsx-filename-extension': [1, { extensions: ['.ts', '.tsx'] }],
'import/prefer-default-export': 'off',
'react/state-in-constructor': 'off',
'import/extensions': 'off',
'import/no-unresolved': 'off',
semi: 'off',
'arrow-body-style': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'import/order': 'off',
'linebreak-style': 'off',
},
},
],
};
| odota/web/.eslintrc.js/0 | {
"file_path": "odota/web/.eslintrc.js",
"repo_id": "odota",
"token_count": 2031
} | 231 |
[build]
command = 'CI=false npm run build'
[build.environment]
NODE_VERSION = '16'
| odota/web/netlify.toml/0 | {
"file_path": "odota/web/netlify.toml",
"repo_id": "odota",
"token_count": 32
} | 232 |
<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="#fff" d="M0 0h640v479.997H0z"/>
<path fill="#00267f" d="M0 0h213.33v479.997H0z"/>
<path fill="#f31830" d="M426.663 0h213.33v479.997h-213.33z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/bl.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/bl.svg",
"repo_id": "odota",
"token_count": 153
} | 233 |
<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-79.458 32h640v480h-640z"/>
</clipPath>
</defs>
<g stroke-width="1pt" fill-rule="evenodd" clip-path="url(#a)" transform="translate(79.458 -32)">
<path fill="#ff0" d="M-119.46 32h720v480h-720z"/>
<path d="M-119.46 32v480l480-480h-480z" fill="#00ca00"/>
<path d="M120.54 512h480V32l-480 480z" fill="red"/>
</g>
</svg>
| odota/web/public/assets/images/flags/cg.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/cg.svg",
"repo_id": "odota",
"token_count": 236
} | 234 |
<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-40 0h682.67v512H-40z"/>
</clipPath>
</defs>
<g clip-path="url(#a)" fill-rule="evenodd" transform="translate(37.5) scale(.94)">
<path fill="#0c0" d="M-40 0h768v512H-40z"/>
<path fill="#69f" d="M-40 0h768v256H-40z"/>
<path d="M-40 0l382.73 255.67L-40 511.01V0z" fill="#fffefe"/>
<path d="M119.8 292.07l-30.82-22.18-30.67 22.4 11.407-36.41-30.613-22.48 37.874-.31 11.747-36.3 12 36.216 37.874.048-30.458 22.695 11.66 36.328z" fill="red"/>
</g>
</svg>
| odota/web/public/assets/images/flags/dj.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/dj.svg",
"repo_id": "odota",
"token_count": 322
} | 235 |
<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-81.333 0h682.67v512h-682.67z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(76.25) scale(.94)" stroke-width="1pt">
<path fill="#6797d6" d="M-252 0H772v512H-252z"/>
<path fill="#fff" d="M259.787 122.985l-32.44 22.214 12.433-35.9-32.475-22.177 40.122.038 12.366-35.92 12.366 35.92 40.12-.026L279.8 109.3l12.43 35.905m-32.443 244.847l-32.44-22.214 12.433 35.9-32.475 22.176 40.122-.038 12.366 35.92 12.366-35.92 40.12.027-32.48-22.166 12.43-35.905m-188.384-92.465l-24.53 30.73 1.395-37.967-37.54-11.713 38.38-11.695 1.324-37.966 22.328 30.735 38.36-11.755-24.58 30.694 22.383 30.7m274.28-11.763l24.53 30.73-1.395-37.967 37.54-11.713-38.38-11.695-1.324-37.966-22.328 30.735-38.36-11.755 24.58 30.694-22.383 30.7"/>
</g>
</svg>
| odota/web/public/assets/images/flags/fm.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/fm.svg",
"repo_id": "odota",
"token_count": 487
} | 236 |
<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-62.883 0h682.67v512h-682.67z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="translate(58.95) scale(.94)">
<path fill="#fff" d="M661.1 512h-766.65V0H661.1z"/>
<path fill="#df0000" d="M661.1 512h-766.65V256.45H661.1zM347.57 255.85c0-86.577-70.184-156.766-156.763-156.766-86.576 0-156.765 70.185-156.765 156.765"/>
<path d="M347.57 255.75c0 86.577-70.184 156.766-156.763 156.766-86.576 0-156.765-70.185-156.765-156.765" fill="#fff"/>
</g>
</svg>
| odota/web/public/assets/images/flags/gl.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/gl.svg",
"repo_id": "odota",
"token_count": 327
} | 237 |
<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="M640.006 479.994H0V0h640.006z"/>
<path fill="#388d00" d="M640.006 479.994H0V319.996h640.006z"/>
<path fill="#d43516" d="M640.006 160.127H0V.13h640.006z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/hu.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/hu.svg",
"repo_id": "odota",
"token_count": 154
} | 238 |
<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="#fff" d="M0 0h639.98v479.998H0z"/>
<path fill="#36a100" d="M426.654 0H639.98v479.998H426.654zM0 0h213.327v479.998H0z"/>
</g>
</svg>
| odota/web/public/assets/images/flags/ng.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/ng.svg",
"repo_id": "odota",
"token_count": 141
} | 239 |
<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 0h682.67v512H0z"/>
</clipPath>
</defs>
<g fill-rule="evenodd" clip-path="url(#a)" transform="scale(.9375)" stroke-width="1pt">
<path d="M0 341.32h1024V512H0z"/>
<path fill="#fff" d="M0 170.64h1024v170.68H0z"/>
<path fill="red" d="M0 0h1024.8v170.68H0z"/>
<path d="M0 0v512l341.32-256L0 0z" fill="#009a00"/>
</g>
</svg>
| odota/web/public/assets/images/flags/sd.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/sd.svg",
"repo_id": "odota",
"token_count": 249
} | 240 |
<svg xmlns="http://www.w3.org/2000/svg" height="480" width="640" viewBox="0 0 640 480">
<rect y="160" width="640" height="160" ry="0" rx="0" fill="#fff" fill-rule="evenodd"/>
<rect y="320" width="640" height="160" ry="0" rx="0" fill-rule="evenodd"/>
<path d="M0 0h640v160H0z" fill="red" fill-rule="evenodd"/>
<path d="M201.9 281l-28.822-20.867-28.68 21.072 10.667-34.242-28.628-21.145 35.418-.295 10.985-34.138 11.221 34.06 35.418.045-28.481 21.344L201.9 281zm307.64 0l-28.822-20.867-28.68 21.072 10.667-34.242-28.628-21.145 35.418-.295 10.985-34.138 11.221 34.06 35.418.045-28.481 21.344L509.54 281z" fill="#090" fill-rule="evenodd"/>
</svg>
| odota/web/public/assets/images/flags/sy.svg/0 | {
"file_path": "odota/web/public/assets/images/flags/sy.svg",
"repo_id": "odota",
"token_count": 308
} | 241 |
import heroes from 'dotaconstants/build/heroes.json';
import immutable from 'seamless-immutable';
import flatten from 'lodash/fp/flatten';
import {
isRadiant,
isSupport,
getLevelFromXp,
unpackPositionData,
} from '../utility';
import analyzeMatch from './analyzeMatch';
import store from '../store';
const abilityIds = (await import('dotaconstants/build/ability_ids.json')).default;
let expandedUnitNames = null;
function generateExpandedUnitNames(strings) {
const expanded = {};
Object.keys(strings)
.filter(str => str.indexOf('npc_dota_') === 0)
.forEach((key) => {
// Currently, no unit goes up higher than 4
for (let i = 1; i < 5; i += 1) {
expanded[key.replace('#', i)] = strings[key];
}
});
return expanded;
}
const getMaxKeyOfObject = field => Number(Object.keys(field || {}).sort((a, b) => Number(b) - Number(a))[0]) || 0;
function generateTeamfights({ players, teamfights = [] }) {
const computeTfData = (tf) => {
const newtf = {
...tf,
deaths_pos: [],
radiant_gold_advantage_delta: 0,
radiant_gold_delta: 0,
dire_gold_delta: 0,
radiant_xp_delta: 0,
radiant_participation: 0,
radiant_deaths: 0,
dire_participation: 0,
dire_deaths: 0,
};
newtf.players = players.map((player) => {
const tfplayer = tf.players[player.player_slot % (128 - 5)];
if (!tfplayer) {
return null;
}
// compute team gold/xp deltas
if (isRadiant(player.player_slot)) {
newtf.radiant_gold_advantage_delta += tfplayer.gold_delta;
newtf.radiant_gold_delta += tfplayer.gold_delta;
newtf.radiant_xp_delta += tfplayer.xp_delta;
newtf.radiant_participation += tfplayer.participate ? 1 : 0;
newtf.radiant_deaths += tfplayer.deaths ? 1 : 0;
} else {
newtf.radiant_gold_advantage_delta -= tfplayer.gold_delta;
newtf.dire_gold_delta -= tfplayer.gold_delta;
newtf.radiant_xp_delta -= tfplayer.xp_delta;
newtf.dire_participation += tfplayer.participate ? 1 : 0;
newtf.dire_deaths += tfplayer.deaths ? 1 : 0;
}
const playerDeathsPos = unpackPositionData(tfplayer.deaths_pos)
.map(deathPos => ({
...deathPos,
isRadiant: isRadiant(player.player_slot),
player,
}));
newtf.deaths_pos = newtf.deaths_pos.concat(playerDeathsPos);
return {
...player,
...tfplayer,
participate: tfplayer.deaths > 0 || tfplayer.damage > 0, // || tfplayer.healing > 0,
level_start: getLevelFromXp(tfplayer.xp_start),
level_end: getLevelFromXp(tfplayer.xp_end),
deaths_pos: playerDeathsPos,
};
}).filter(player => (player !== null));
// We have to do this after we process the stuff so that we will have the player in
// the data instead of just the 'teamfight player' which doesn't have enough data.
newtf.deaths_pos = newtf.deaths_pos
.map(death => ([{
...death,
killer: newtf.players
.find(killer => heroes[death.player.hero_id] && killer.killed[heroes[death.player.hero_id].name]),
}]))
.reduce(
(newDeathsPos, death) => {
const copy = [...newDeathsPos];
const samePosition = copy
.findIndex((deathPos) => {
const cursor = deathPos[0];
return cursor.x === death[0].x && cursor.y === death[0].y;
});
if (samePosition !== -1) {
copy[samePosition] = copy[samePosition].concat(death);
} else {
copy.push(death);
}
return copy;
},
[],
);
return newtf;
};
return (teamfights || []).map(computeTfData);
}
// create a detailed history of each wards
function generateVisionLog(match) {
const computeWardData = (player, i) => {
// let's coerce some value to be sure the structure is what we expect.
const safePlayer = {
...player,
obs_log: player.obs_log || [],
sen_log: player.sen_log || [],
obs_left_log: player.obs_left_log || [],
sen_left_log: player.sen_left_log || [],
};
// let's zip the *_log and the *_left log in a 2-tuples
const extractVisionLog = (type, enteredLog, leftLog) =>
enteredLog.map((e) => {
const wards = [e, leftLog.find(l => l.ehandle === e.ehandle)];
return {
player: i,
key: wards[0].ehandle,
type,
entered: wards[0],
left: wards[1],
};
});
const observers = extractVisionLog('observer', safePlayer.obs_log, safePlayer.obs_left_log);
const sentries = extractVisionLog('sentry', safePlayer.sen_log, safePlayer.sen_left_log);
return observers.concat(sentries);
};
const temp = flatten((match.players || []).map(computeWardData));
temp.sort((a, b) => a.entered.time - b.entered.time);
const result2 = temp.map((x, i) => ({ ...x, key: i }));
return result2;
}
function transformMatch(m) {
const { strings } = store.getState().app;
// lane winning
const lineResults = m.players.reduce((res, pl) => {
res[pl.isRadiant] = res[pl.isRadiant] || [];
res[pl.isRadiant][pl.lane] = res[pl.isRadiant][pl.lane] || 0;
res[pl.isRadiant][pl.lane] += (pl.gold_t || [])[10]
return res;
}, {});
const newPlayers = m.players.map((player) => {
const newPlayer = {
...player,
desc: [strings[`lane_role_${player.lane_role}`], isSupport(player) ? 'Support' : 'Core'].join('/'),
multi_kills_max: getMaxKeyOfObject(player.multi_kills),
kill_streaks_max: getMaxKeyOfObject(player.kill_streaks),
lh_ten: (player.lh_t || [])[10],
dn_ten: (player.dn_t || [])[10],
line_win: lineResults[player.isRadiant]?.[player.lane] > lineResults[!player.isRadiant]?.[player.lane],
analysis: analyzeMatch(m, player),
};
// filter interval data to only be >= 0
if (player.times) {
const intervals = ['lh_t', 'gold_t', 'xp_t', 'times'];
intervals.forEach((key) => {
newPlayer[key] = player[key].filter((el, i) => player.times[i] >= 0);
});
// compute a cs_t as a sum of lh_t & dn_t
const csT = (player.lh_t || []).map((v, i) => v + ((player.dn_t || [])[i] || 0));
newPlayer.cs_t = csT.filter((el, i) => player.times[i] >= 0);
}
// compute damage to towers/rax/roshan
if (player.damage) {
// npc_dota_goodguys_tower2_top
// npc_dota_goodguys_melee_rax_top
// npc_dota_roshan
// npc_dota_neutral_giant_wolf
// npc_dota_creep
newPlayer.objective_damage = {};
Object.keys(player.damage).forEach((key) => {
let identifier = null;
if (key.indexOf('tower') !== -1) {
identifier = key.split('_').slice(3).join('_');
}
if (key.indexOf('rax') !== -1) {
identifier = key.split('_').slice(4).join('_');
}
if (key.indexOf('roshan') !== -1) {
identifier = 'roshan';
}
if (key.indexOf('fort') !== -1) {
identifier = 'fort';
}
if (key.indexOf('healers') !== -1) {
identifier = 'shrine';
}
newPlayer.objective_damage[identifier] = newPlayer.objective_damage[identifier] ?
newPlayer.objective_damage[identifier] + player.damage[key] :
player.damage[key];
});
}
if (player.killed) {
newPlayer.specific = {};
// expand keys in specific by # (1-4)
// map to friendly name
// iterate through keys in killed
// if in expanded, put in pm.specific
if (!expandedUnitNames) {
expandedUnitNames = generateExpandedUnitNames(strings);
}
Object.keys(player.killed).forEach((key) => {
if (key in expandedUnitNames) {
const name = expandedUnitNames[key];
newPlayer.specific[name] = newPlayer.specific[name] ? newPlayer.specific[name] + newPlayer.killed[key] : newPlayer.killed[key];
}
});
}
if (player.purchase) {
newPlayer.purchase_tpscroll = player.purchase.tpscroll;
newPlayer.purchase_ward_observer = player.purchase.ward_observer;
newPlayer.purchase_ward_sentry = player.purchase.ward_sentry;
newPlayer.purchase_smoke_of_deceit = player.purchase.smoke_of_deceit;
newPlayer.purchase_dust = player.purchase.dust;
newPlayer.purchase_gem = player.purchase.gem;
}
newPlayer.buybacks = (player.buyback_log || []).length;
newPlayer.total_gold = (player.gold_per_min * m.duration) / 60;
if (m.game_mode === 18 && Object.prototype.hasOwnProperty.call(player, 'ability_upgrades_arr')) {
const arr = [];
if (player.ability_upgrades_arr) {
player.ability_upgrades_arr.forEach((ability) => {
if (!arr.includes(ability) && abilityIds[ability] && abilityIds[ability].indexOf('special_bonus') === -1) {
arr.push(ability);
}
});
}
newPlayer.abilities = arr;
}
newPlayer.hero_name = heroes[player.hero_id] && heroes[player.hero_id].name;
return newPlayer;
});
const newObjectives = (m.objectives || []).map((obj) => {
if (obj.slot > 0) {
return {
...obj,
player_slot: obj.slot > 4 ? obj.slot + 123 : obj.slot,
};
}
return {
...obj,
};
});
return {
...m,
teamfights: generateTeamfights(m),
players: newPlayers,
wards_log: generateVisionLog(immutable(m)),
objectives: newObjectives,
};
}
export default transformMatch;
| odota/web/src/actions/transformMatch.js/0 | {
"file_path": "odota/web/src/actions/transformMatch.js",
"repo_id": "odota",
"token_count": 4176
} | 242 |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import CircularProgress from 'material-ui/CircularProgress';
import RaisedButton from 'material-ui/RaisedButton';
import styled from 'styled-components';
import StripeCheckout from 'react-stripe-checkout';
import config from '../../config';
const path = '/keys';
const ApiContainer = styled.div`
width: 80%;
margin: 0 auto;
@media only screen and (max-width: 768px) {
width: 100%;
}
& li {
list-style-type: initial;
}
& h2 {
font-size: 1.17em;
}
`;
const KeyContainer = styled.pre`
background: grey;
display: inline;
padding: 10px;
`;
const TableContainer = styled.div`
table {
width: 80%;
margin: 0 auto;
background: rgba(255, 255, 255, 0.011);
}
& table td, table th {
white-space: inherit !important;
}
th {
color: rgb(255, 128, 171);
}
@media only screen and (max-width: 768px) {
width: 100%;
}
`;
const DetailsContainer = styled.div`
text-align: left;
width: 80%;
margin: 0 auto;
@media only screen and (max-width: 768px) {
width: 100%;
}
`;
class KeyManagement extends React.Component {
static propTypes = {
loading: PropTypes.bool,
user: PropTypes.shape({}),
strings: PropTypes.shape({}),
};
constructor(props) {
super(props);
this.state = {
error: false,
loading: true,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUpdate = this.handleUpdate.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
componentDidMount() {
fetch(`${config.VITE_API_HOST}${path}`, {
credentials: 'include',
method: 'GET',
})
.then((res) => {
if (res.ok) {
return res.json();
} else if (res.status === 403) {
return {};
}
throw Error();
})
.then((json) => {
this.setState({ ...json, loading: false });
})
.catch(() => this.setState({ error: true }));
}
handleSubmit(token) {
this.setState({ loading: true });
fetch(`${config.VITE_API_HOST}${path}`, {
credentials: 'include',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
}),
})
.then((res) => {
if (res.ok) {
window.location.reload(false);
} else {
throw Error();
}
})
.catch(() => this.setState({ error: true }));
}
handleDelete() {
this.setState({ loading: true });
fetch(`${config.VITE_API_HOST}${path}`, {
credentials: 'include',
method: 'DELETE',
})
.then((res) => {
if (res.ok) {
window.location.reload(false);
} else {
throw Error();
}
})
.catch(() => this.setState({ error: true }));
}
handleUpdate(token) {
this.setState({ loading: true });
fetch(`${config.VITE_API_HOST}${path}`, {
credentials: 'include',
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
}),
})
.then((res) => {
if (res.ok) {
window.location.reload(false);
} else {
throw Error();
}
})
.catch(() => this.setState({ error: true }));
}
render() {
const { loading, user, strings } = this.props;
const showLoginButton = !user;
const showGetKeyButton = user && !(this.state.customer && this.state.customer.api_key);
const premUnit = 100;
const freeCallLimit = 2000;
const freeRateLimit = 60;
const premRateLimit = 1200;
const premPrice = 0.01;
return (
<div>
<Helmet>
<title>{strings.title_api}</title>
<meta name="description" content={strings.api_meta_description} />
</Helmet>
<ApiContainer style={{ textAlign: 'center' }}>
{
this.state.error
? (
<div>
{strings.api_error}
</div>
)
: <div />
}
<h1>{strings.api_title}</h1>
<h2>{strings.api_subtitle}</h2>
{
loading || this.state.loading || !Object.keys(strings).length
? <CircularProgress mode="indeterminate" />
: (
<div>
{ showLoginButton
? (
<RaisedButton primary href={`${config.VITE_API_HOST}/login`} label={strings.api_login} style={{ margin: '5px 5px' }} />
)
: <div />
}
{ showGetKeyButton
? (
<StripeCheckout
name="OpenDota"
description={strings.api_title}
billingAddress
stripeKey={config.VITE_STRIPE_PUBLIC_KEY}
token={this.handleSubmit}
zipCode
locale="auto"
>
<RaisedButton primary label={strings.api_get_key} style={{ margin: '5px 5px' }} />
</StripeCheckout>
)
: <span />
}
<RaisedButton href="//docs.opendota.com" target="_blank" rel="noopener noreferrer" label={strings.api_docs} style={{ margin: '5px 5px' }} />
{ this.state.customer
? (
<div>
{ this.state.customer.api_key
? (
<div>
<h4>{strings.api_header_key}</h4>
<KeyContainer>{this.state.customer.api_key}</KeyContainer>
<p>{strings.api_key_usage.replace('$param', 'api_key=XXXX')}</p>
<div style={{ overflow: 'hidden' }}>
<a href={`https://api.opendota.com/api/matches/271145478?api_key=${this.state.customer.api_key}`}>
<KeyContainer>{`https://api.opendota.com/api/matches/271145478?api_key=${this.state.customer.api_key}`}</KeyContainer>
</a>
</div>
<p>
{`${strings.api_billing_cycle
.replace('$date', (new Date(this.state.customer.current_period_end * 1000)).toLocaleDateString())} ${
strings.api_billed_to
.replace('$brand', this.state.customer.credit_brand)
.replace('$last4', this.state.customer.credit_last4)}`
}
</p>
<p>{strings.api_support.replace('$email', 'api@opendota.com')}</p>
<RaisedButton label={strings.api_delete} style={{ margin: '5px 5px' }} onClick={this.handleDelete} />
<StripeCheckout
name="OpenDota"
description={strings.api_title}
billingAddress
stripeKey={config.VITE_STRIPE_PUBLIC_KEY}
token={this.handleUpdate}
zipCode
locale="auto"
>
<RaisedButton label={strings.api_update_billing} style={{ margin: '5px 5px' }} />
</StripeCheckout>
</div>
)
: <div />
}
{
this.state.usage
? (
<div>
<h4>{strings.api_header_usage}</h4>
<TableContainer>
<table>
<thead
displaySelectAll={false}
adjustForCheckbox={false}
>
<tr>
<th>{strings.api_month}</th>
<th>{strings.api_usage_calls}</th>
<th>{strings.api_usage_fees}</th>
</tr>
</thead>
<tbody
displayRowCheckbox={false}
>
{ this.state.usage.map((e) => (
<tr key={e.month}>
<td>{e.month}</td>
<td>{e.usage_count}</td>
<td>{`$${Number(premPrice * Math.ceil(e.usage_count / premUnit)).toFixed(2)}`}</td>
</tr>))}
</tbody>
</table>
</TableContainer>
</div>
)
: <div />
}
</div>
)
: <div />
}
<h2>{strings.api_header_table}</h2>
<TableContainer>
<table>
<thead
displaySelectAll={false}
adjustForCheckbox={false}
>
<tr>
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label */}
<th aria-hidden="true"/>
<th>{strings.api_details_free_tier}</th>
<th>{strings.api_details_premium_tier}</th>
</tr>
</thead>
<tbody
displayRowCheckbox={false}
>
<tr>
<th>{strings.api_details_price}</th>
<td>{strings.api_details_price_free}</td>
<td>{strings.api_details_price_prem.replace('price', premPrice).replace('$unit', premUnit)}</td>
</tr>
<tr>
<th>{strings.api_details_key_required}</th>
<td>{strings.api_details_key_required_free}</td>
<td>{strings.api_details_key_required_prem}</td>
</tr>
<tr>
<th>{strings.api_details_call_limit}</th>
<td>{strings.api_details_call_limit_free_day.replace('$limit', freeCallLimit)}</td>
<td>{strings.api_details_call_limit_prem}</td>
</tr>
<tr>
<th>{strings.api_details_rate_limit}</th>
<td>{strings.api_details_rate_limit_val.replace('$num', freeRateLimit)}</td>
<td>{strings.api_details_rate_limit_val.replace('$num', premRateLimit)}</td>
</tr>
<tr>
<th>{strings.api_details_support}</th>
<td>{strings.api_details_support_free}</td>
<td>{strings.api_details_support_prem}</td>
</tr>
<tr style={{ height: '24px' }} />
</tbody>
</table>
</TableContainer>
<h3>{strings.api_header_details}</h3>
<DetailsContainer>
<ul>
<li>{strings.api_charging.replace('$cost', `$${premPrice / premUnit}`)}</li>
<li>{strings.api_credit_required}</li>
<li>{strings.api_failure}</li>
</ul>
</DetailsContainer>
</div>
)
}
</ApiContainer>
</div>
);
}
}
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)(KeyManagement);
| odota/web/src/components/Api/Api.jsx/0 | {
"file_path": "odota/web/src/components/Api/Api.jsx",
"repo_id": "odota",
"token_count": 7728
} | 243 |
import { PureComponent } from 'react';
import PropTypes from 'prop-types';
export default class DeferredContainer extends PureComponent {
static propTypes = {
children: PropTypes.arrayOf(PropTypes.node),
}
state = { shouldRender: false };
componentDidMount() {
requestAnimationFrame(() => {
this.setState({ shouldRender: true });
});
}
render() {
return this.state.shouldRender ? this.props.children : null;
}
}
| odota/web/src/components/DeferredContainer/index.jsx/0 | {
"file_path": "odota/web/src/components/DeferredContainer/index.jsx",
"repo_id": "odota",
"token_count": 190
} | 244 |
function conjoin(strings, value) {
if (!value) {
return '';
}
const str0 = strings[0];
const str1 = strings[1];
if (Array.isArray(value)) {
const o = value.map(x => x.value);
const r = [];
if (!value.length) {
return '';
}
o.forEach((s) => {
r.push(`${str0}${s}${str1}`);
});
return `AND (${r.join(' OR ')})`;
}
return `AND ${str0}${value.value !== undefined ? value.value : value}${str1}`;
}
function validateArray(p) {
return Array.isArray(p) && p.length > 0;
}
const tiTeams = [7119388, 2586976, 6209166, 8254400, 7391077, 7732977, 8260983, 8291895, 8599101, 350190, 39,
7390454, 8131728, 8605863, 8721219, 6209804, 8597976, 2163, 1838315, 15];
const queryTemplate = (props) => {
const {
select,
group,
minPatch,
maxPatch,
hero,
player,
league,
playerPurchased,
minDuration,
maxDuration,
side,
result,
team,
organization,
laneRole,
region,
minDate,
maxDate,
order,
tier,
having,
limit,
isTiTeam,
megaWin,
minGoldAdvantage,
maxGoldAdvantage,
} = props;
// array inputs
// group
// hero
// player
// league
// team
// organization
let query;
let groupArray = [];
let selectArray = [];
if (!(Array.isArray(group))) {
groupArray.push(group);
} else {
groupArray = group;
}
if (!(Array.isArray(select))) {
selectArray.push(select);
} else {
selectArray = select;
}
selectArray = selectArray.filter(x => x !== undefined);
groupArray = groupArray.filter(x => x !== undefined);
groupArray.forEach((x) => {
if (x.json_each) {
selectArray.push(x);
}
});
groupArray = groupArray.filter(x => !x.json_each);
selectArray.forEach((x, index) => {
if (x && x.groupValue) {
const a = {
value: x.groupKey, groupKeySelect: x.groupKeySelect, alias: x.alias, key: `key${index.toString()}`,
};
if (x.groupKey === 'key') {
const p = x;
a.value = `key${index.toString()}.key`;
p.value = `key${index.toString()}.key`;
p.join = `${x.join} key${index.toString()}`;
p.groupValue = `key${index.toString()}.${x.groupValue}`;
}
groupArray.push(a);
}
});
if (validateArray(selectArray) && selectArray.some(p => p.template === 'picks_bans')) {
query = `SELECT
hero_id,
count(1) total,
sum(is_pick::int) picks,
sum((NOT is_pick)::int) bans,
sum((is_pick IS TRUE AND ord < 8)::int) first_pick,
sum((is_pick IS FALSE AND ord < 8)::int) first_ban,
sum((is_pick IS TRUE AND ord >= 8 AND ord < 16)::int) second_pick,
sum((is_pick IS FALSE AND ord >= 8 AND ord < 16)::int) second_ban,
sum((is_pick IS TRUE AND ord >= 16)::int) third_pick,
sum((is_pick IS FALSE AND ord >= 16)::int) third_ban,
sum((radiant = radiant_win)::int)::float/count(1) winrate,
sum((radiant = radiant_win AND is_pick IS TRUE)::int)::float/NULLIF(sum(is_pick::int), 0) pick_winrate,
sum((radiant = radiant_win AND is_pick IS FALSE)::int)::float/NULLIF(sum((NOT is_pick)::int), 0) ban_winrate
FROM picks_bans
JOIN matches using(match_id)
JOIN match_patch using(match_id)
JOIN leagues using(leagueid)
JOIN team_match using(match_id)
JOIN teams using(team_id)
WHERE TRUE
${validateArray(selectArray) && selectArray.find(x => x.where) !== undefined ? selectArray.find(x => x.where).where : ''}
${conjoin`team_id = ${organization}`}
${conjoin`match_patch.patch >= '${minPatch}'`}
${conjoin`match_patch.patch <= '${maxPatch}'`}
${conjoin`matches.leagueid = ${league}`}
${conjoin`matches.duration >= ${minDuration}`}
${conjoin`matches.duration <= ${maxDuration}`}
${conjoin`team_match.radiant = ${side}`}
${conjoin`(team_match.radiant = matches.radiant_win) = ${result}`}
${conjoin`matches.cluster IN (${region})`}
${minDate ? conjoin`matches.start_time >= extract(epoch from timestamp '${new Date(minDate.value).toISOString()}')` : ''}
${maxDate ? conjoin`matches.start_time <= extract(epoch from timestamp '${new Date(maxDate.value).toISOString()}')` : ''}
${conjoin`leagues.tier = '${tier}'`}
${isTiTeam ? `AND teams.team_id IN (${tiTeams.join(',')})` : ''}
${megaWin ? 'AND ((matches.barracks_status_radiant = 0 AND matches.radiant_win) OR (matches.barracks_status_dire = 0 AND NOT matches.radiant_win))' : ''}
${maxGoldAdvantage ? `AND @ matches.radiant_gold_adv[array_upper(matches.radiant_gold_adv, 1)] <= ${maxGoldAdvantage.value}` : ''}
${minGoldAdvantage ? `AND @ matches.radiant_gold_adv[array_upper(matches.radiant_gold_adv, 1)] >= ${minGoldAdvantage.value}` : ''}
GROUP BY hero_id
ORDER BY total ${(order && order.value) || 'DESC'}`;
} else {
const selectVal = {};
const groupVal = {};
if (validateArray(groupArray)) {
groupArray.forEach((x) => { groupVal[x.key] = `${x.value}${x.bucket ? ` / ${x.bucket} * ${x.bucket}` : ''}`; });
}
if (validateArray(selectArray)) {
selectArray.forEach((x) => { selectVal[x.key] = x.groupValue || (x && x.value) || 1; });
}
query = `SELECT
${validateArray(selectArray) ? selectArray.map(x => (x.distinct && !validateArray(groupArray) ? `DISTINCT ON (${x.value})` : '')).join('') : ''}\
${(validateArray(groupArray)) ?
groupArray.map(x =>
[`${x.groupKeySelect || groupVal[x.key]} ${x.alias || ''},`].filter(Boolean).join(',\n')).join('') : ''}
${(validateArray(groupArray)) ?
(validateArray(selectArray) && selectArray.map(x =>
[
(x && x.countValue) || '',
(x && x.avgPerMatch) ? `sum(${selectVal[x.key]})::numeric/count(distinct matches.match_id) "AVG ${x.text}"` : `${x && x.avg ? x.avg : `avg(${selectVal[x.key]})`} "AVG ${x.text}"`,
'count(distinct matches.match_id) count',
'sum(case when (player_matches.player_slot < 128) = radiant_win then 1 else 0 end)::float/count(1) winrate',
`((sum(case when (player_matches.player_slot < 128) = radiant_win then 1 else 0 end)::float/count(1))
+ 1.96 * 1.96 / (2 * count(1))
- 1.96 * sqrt((((sum(case when (player_matches.player_slot < 128) = radiant_win then 1 else 0 end)::float/count(1)) * (1 - (sum(case when (player_matches.player_slot < 128) = radiant_win then 1 else 0 end)::float/count(1))) + 1.96 * 1.96 / (4 * count(1))) / count(1))))
/ (1 + 1.96 * 1.96 / count(1)) winrate_wilson`,
`sum(${selectVal[x.key]}) sum`,
`min(${selectVal[x.key]}) min`,
`max(${selectVal[x.key]}) max`,
`stddev(${selectVal[x.key]}::numeric) stddev
`,
].filter(Boolean).join(',\n'))) || '' : ''}
${!validateArray(groupArray) ?
[validateArray(selectArray) ? selectArray.map(x => `${x.value} ${x.alias || ''}`) : '',
'matches.match_id',
'matches.start_time',
'((player_matches.player_slot < 128) = matches.radiant_win) win',
'player_matches.hero_id',
'player_matches.account_id',
'leagues.name leaguename',
].filter(Boolean).join(',\n') : ''}
FROM matches
JOIN match_patch using(match_id)
JOIN leagues using(leagueid)
JOIN player_matches using(match_id)
JOIN heroes on heroes.id = player_matches.hero_id
LEFT JOIN notable_players ON notable_players.account_id = player_matches.account_id
LEFT JOIN teams using(team_id)
${organization || (groupArray !== null && groupArray.length > 0 && groupArray[0] && groupArray.some(x => x.key === 'organization')) ?
'JOIN team_match ON matches.match_id = team_match.match_id AND (player_matches.player_slot < 128) = team_match.radiant JOIN teams teams2 ON team_match.team_id = teams2.team_id' : ''}
${validateArray(selectArray) ? selectArray.map(x => (x.joinFn ? x.joinFn(props) : '')).join('') : ''}
${validateArray(selectArray) ? selectArray.map(x => (x.join ? x.join : '')).join('') : ''}
WHERE TRUE
${validateArray(selectArray) ? selectArray.map(x => `AND ${x.value} IS NOT NULL `).join('') : ''}
${conjoin`match_patch.patch >= '${minPatch}'`}
${conjoin`match_patch.patch <= '${maxPatch}'`}
${conjoin`player_matches.hero_id = ${hero}`}
${conjoin`player_matches.account_id = ${player}`}
${conjoin`matches.leagueid = ${league}`}
${conjoin`(player_matches.purchase->>'${playerPurchased}')::int > 0`}
${conjoin`matches.duration >= ${minDuration}`}
${conjoin`matches.duration <= ${maxDuration}`}
${conjoin`(player_matches.player_slot < 128) = ${side}`}
${conjoin`((player_matches.player_slot < 128) = matches.radiant_win) = ${result}`}
${conjoin`notable_players.team_id = ${team}`}
${conjoin`team_match.team_id = ${organization} AND (player_matches.player_slot < 128) = team_match.radiant`}
${conjoin`player_matches.lane_role = ${laneRole}`}
${conjoin`matches.cluster IN (${region})`}
${minDate ? conjoin`matches.start_time >= extract(epoch from timestamp '${new Date(minDate.value).toISOString()}')` : ''}
${maxDate ? conjoin`matches.start_time <= extract(epoch from timestamp '${new Date(maxDate.value).toISOString()}')` : ''}
${conjoin`leagues.tier = '${tier}'`}
${isTiTeam ? `AND teams.team_id IN (${tiTeams.join(',')})` : ''}
${megaWin ? 'AND ((matches.barracks_status_radiant = 0 AND matches.radiant_win) OR (matches.barracks_status_dire = 0 AND NOT matches.radiant_win))' : ''}
${maxGoldAdvantage ? `AND @ matches.radiant_gold_adv[array_upper(matches.radiant_gold_adv, 1)] <= ${maxGoldAdvantage.value}` : ''}
${minGoldAdvantage ? `AND @ matches.radiant_gold_adv[array_upper(matches.radiant_gold_adv, 1)] >= ${minGoldAdvantage.value}` : ''}
${validateArray(groupArray) ? 'GROUP BY' : ''}${(validateArray(groupArray) && groupArray.map(x => ` ${groupVal[x.key]}`)) || ''}
${validateArray(groupArray) ? `HAVING count(distinct matches.match_id) >= ${(having && having.value) || '1'}` : ''}
ORDER BY ${
[`${(validateArray(groupArray) && validateArray(selectArray) && selectArray.map(x => `"AVG ${x.text}" ${order ? order.value : 'DESC'}`)) ||
(validateArray(selectArray) && selectArray.map(x => `${x.value} ${order ? order.value : 'DESC'}`).join(',')) || 'matches.match_id'}`,
validateArray(groupArray) ? 'count DESC' : '',
].filter(Boolean).join(',')} NULLS LAST
LIMIT ${limit ? limit.value : 200}`;
}
return query
// Remove extra newlines
.replace(/\n{2,}/g, '\n');
};
export default queryTemplate;
| odota/web/src/components/Explorer/queryTemplate.js/0 | {
"file_path": "odota/web/src/components/Explorer/queryTemplate.js",
"repo_id": "odota",
"token_count": 4087
} | 245 |
import Header from './Header';
export default Header;
| odota/web/src/components/Header/index.js/0 | {
"file_path": "odota/web/src/components/Header/index.js",
"repo_id": "odota",
"token_count": 14
} | 246 |
import React from 'react';
import { connect } from 'react-redux';
import { oneOfType, shape, arrayOf } from 'prop-types';
import Table from '../Table';
const BenchmarkTable = ({ data, strings }) => {
const columns = d => Object.keys(d[0] || {}).map(stat => ({
displayName: strings[`th_${stat}`],
tooltip: strings[`tooltip_${stat}`],
field: stat,
displayFn: (row, col, field) => (stat === 'percentile' ? `${field * 100}%` : typeof field === 'number' && Number(field.toFixed(2))),
}));
return (<Table data={data} columns={columns(data)} />);
};
BenchmarkTable.propTypes = {
data: oneOfType([
arrayOf(shape({})),
shape({}),
]),
strings: shape({}),
};
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(BenchmarkTable);
| odota/web/src/components/Hero/BenchmarkTable.jsx/0 | {
"file_path": "odota/web/src/components/Hero/BenchmarkTable.jsx",
"repo_id": "odota",
"token_count": 290
} | 247 |
import styled from 'styled-components';
import constants from '../constants';
export const HeadContainerDiv = styled.div`
width: 600px;
height: 380px;
margin: 0 auto;
text-align: center;
padding-top: 120px;
@media only screen and (max-width: 768px) {
width: auto;
}
`;
export const HeadlineDiv = styled.div`
text-transform: uppercase;
font-size: 90px;
font-weight: ${constants.fontWeightMedium};
line-height: 1.2;
text-shadow: #000 0 0 3px;
& h1 {
all: inherit;
}
@media only screen and (max-width: 425px) {
font-size: 60px;
}
@media only screen and (max-width: 375px) {
font-size: 42px;
}
`;
export const DescriptionDiv = styled.div`
font-size: 32px;
font-weight: ${constants.fontWeightLight};
margin-bottom: 20px;
text-shadow: #000 0 0 3px;
& h2 {
all: inherit;
}
@media only screen and (max-width: 768px) {
font-size: 25px;
}
`;
export const BottomTextDiv = styled.div`
font-size: ${constants.fontSizeMedium};
opacity: 0.6;
font-weight: ${constants.fontWeightLight};
text-align: right;
`;
export const ButtonsDiv = styled.div`
margin-bottom: 30px;
& .bottomButtons {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
& a {
background-color: ${constants.defaultPrimaryColor} !important;
border: 2px solid ${constants.textColorPrimary} !important;
padding: 3px 6px !important;
height: auto !important;
margin: 10px 5px !important;
@media only screen and (max-width: 375px) {
line-height: 20px !important;
}
&:hover {
background-color: ${constants.colorSuccess} !important;
}
& .label {
font-weight: ${constants.fontWeightLight};
font-size: ${constants.fontSizeCommon};
& b {
font-size: 18px;
font-weight: ${constants.fontWeightMedium};
}
}
}
& span {
text-transform: none !important;
}
& svg {
width: 20px;
height: 20px;
fill: ${constants.textColorPrimary};
vertical-align: sub !important;
}
`;
| odota/web/src/components/Home/Styled.tsx/0 | {
"file_path": "odota/web/src/components/Home/Styled.tsx",
"repo_id": "odota",
"token_count": 801
} | 248 |
import React from 'react';
export default props => (
<svg {...props} viewBox="0 0 300 300">
<path
d="M122.6,125.9c-8.5,0-15.3,7.5-15.3,16.7c0,9.1,6.9,16.6,15.3,16.6c8.6,0,15.3-7.5,15.3-16.6
C138.1,133.4,131.2,125.9,122.6,125.9z M177.4,125.9c-8.6,0-15.3,7.5-15.3,16.7c0,9.1,6.9,16.6,15.3,16.6c8.5,0,15.3-7.5,15.3-16.6
C192.7,133.4,185.9,125.9,177.4,125.9z"
/>
<path
d="M250.5,0h-201c-17,0-30.8,13.8-30.8,30.9v202.8c0,17.1,13.8,30.9,30.8,30.9h170.1l-7.9-27.8l19.2,17.8
l18.2,16.8l32.3,28.5V30.9C281.3,13.8,267.5,0,250.5,0z M192.6,195.9c0,0-5.4-6.5-9.9-12.2c19.7-5.6,27.2-17.8,27.2-17.8
c-6.2,4-12,6.9-17.3,8.8c-7.5,3.2-14.7,5.3-21.8,6.4c-14.4,2.7-27.6,2-38.9-0.2c-8.5-1.7-15.9-4-22-6.4c-3.5-1.3-7.2-3-11-5.1
c-0.5-0.3-0.9-0.5-1.4-0.8c-0.3-0.2-0.5-0.3-0.6-0.5c-2.7-1.5-4.2-2.5-4.2-2.5s7.2,12,26.3,17.7c-4.5,5.7-10,12.5-10,12.5
c-33.2-1.1-45.8-22.8-45.8-22.8c0-48.3,21.6-87.5,21.6-87.5C106.5,69.5,127,69.9,127,69.9l1.5,1.8c-27,7.8-39.5,19.6-39.5,19.6
s3.3-1.8,8.9-4.3c16-7,28.8-9,34.1-9.5c0.9-0.2,1.6-0.3,2.5-0.3c9.2-1.2,19.5-1.5,30.3-0.3c14.3,1.6,29.6,5.8,45.2,14.4
c0,0-11.8-11.3-37.3-19l2.1-2.4c0,0,20.6-0.5,42.2,15.8c0,0,21.6,39.2,21.6,87.5C238.5,173.1,225.8,194.9,192.6,195.9z"
/>
</svg>
);
| odota/web/src/components/Icons/Discord.jsx/0 | {
"file_path": "odota/web/src/components/Icons/Discord.jsx",
"repo_id": "odota",
"token_count": 1014
} | 249 |
import React from 'react';
export default props => (
<svg {...props} viewBox="0 0 300 300">
<path
d="M94.2,272c113.2,0,175.2-93.9,175.2-175.2c0-2.6,0-5.3-0.1-7.9c12-8.6,22.4-19.6,30.7-31.9c-11,4.9-22.9,8.2-35.4,9.7
c12.7-7.6,22.4-19.7,27.1-34.1c-11.9,7.1-25.1,12.1-39.1,14.9c-11.3-12-27.3-19.4-44.9-19.4c-34,0-61.6,27.6-61.6,61.6
c0,4.8,0.6,9.5,1.6,14c-51.1-2.5-96.5-27.1-126.9-64.3c-5.3,9.1-8.3,19.7-8.3,31c0,21.4,10.9,40.2,27.4,51.3
c-10.1-0.4-19.6-3.1-27.9-7.7c0,0.2,0,0.5,0,0.8c0,29.8,21.2,54.7,49.3,60.4c-5.2,1.4-10.6,2.2-16.2,2.2c-4,0-7.8-0.4-11.5-1.1
c7.8,24.5,30.6,42.3,57.5,42.7c-21.1,16.6-47.7,26.4-76.5,26.4c-4.9,0-9.8-0.2-14.6-0.8C27.1,261.8,59.5,272,94.2,272"
/>
</svg>
);
| odota/web/src/components/Icons/Twitter.jsx/0 | {
"file_path": "odota/web/src/components/Icons/Twitter.jsx",
"repo_id": "odota",
"token_count": 563
} | 250 |
import heroes from 'dotaconstants/build/heroes.json';
import playerColors from 'dotaconstants/build/player_colors.json';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import {
Brush,
CartesianGrid,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import { getHeroIconUrlFromHeroKey } from '../../../utility';
import Heading from '../../Heading';
import { StyledCustomizedTooltip, StyledHolder } from '../../Visualizations/Graph/Styled';
const formatGraphTime = minutes => `${minutes}:00`;
const CustomizedTooltip = ({ label, payload }) => (
<StyledCustomizedTooltip>
<div className="label">{label}</div>
{payload.map((data, i) => (
<div key={i} value={data.value} className={`data ${i < 5 && 'isRadiant'}`} style={{ borderLeft: `8px solid ${data.color}` }}>
{data.dataKey}: {data.value}
</div>)).sort((a, b) => b.props.value - a.props.value)
}
</StyledCustomizedTooltip>
);
CustomizedTooltip.propTypes = {
payload: PropTypes.arrayOf(PropTypes.shape({})),
label: PropTypes.string,
};
const CustomizedDot = (props) => {
const {
cx, cy, payload, killsLog,
} = props;
const kills = killsLog.filter((l) => {
const t = (l.time - (l.time % 60)) / 60;
return formatGraphTime(t) === payload.time;
});
if (kills.length > 0) {
return (
<svg x={cx - 16} y={(cy - (16 * kills.length))} width={32} height={32 * kills.length}>
{kills.map((k, i) => <image key={i} cx={16} y={32 * i} width={32} height={32} href={getHeroIconUrlFromHeroKey(k.key)} />)}
</svg>
);
}
return <svg />;
};
CustomizedDot.propTypes = {
cx: PropTypes.number,
cy: PropTypes.number,
payload: PropTypes.shape({}),
killsLog: PropTypes.arrayOf(PropTypes.shape({})),
};
class Graph extends React.Component {
static propTypes = {
match: PropTypes.shape({}),
strings: PropTypes.shape({}),
selectedPlayer: PropTypes.number,
}
constructor(props) {
super(props);
this.state = {
};
}
render() {
const {
strings,
selectedPlayer,
match,
} = this.props;
const matchData = [];
const { players } = match;
if (players[0] && players[0].cs_t) {
players[0].lh_t.forEach((value, index) => {
if (index <= Math.floor(match.duration / 60)) {
const obj = { time: formatGraphTime(index) };
players.forEach((player) => {
const hero = heroes[player.hero_id] || {};
obj[hero.localized_name] = player.cs_t[index];
});
matchData.push(obj);
}
});
return (
<StyledHolder>
<Heading title={strings.heading_graph_cs} />
<ResponsiveContainer width="100%" height={400}>
<LineChart
data={matchData}
margin={{
top: 5, right: 10, left: 10, bottom: 5,
}}
>
<XAxis dataKey="time" />
<YAxis mirror />
<CartesianGrid
stroke="#505050"
strokeWidth={1}
opacity={0.5}
/>
<Tooltip content={<CustomizedTooltip />} />
{match.players.map((player) => {
const hero = heroes[player.hero_id] || {};
const playerColor = playerColors[player.player_slot];
const isSelected = selectedPlayer === player.player_slot;
const opacity = (isSelected) ? 1 : 0.25;
const stroke = (isSelected) ? 4 : 2;
return (<Line
dot={isSelected ? <CustomizedDot killsLog={player.kills_log} /> : false}
dataKey={hero.localized_name}
key={hero.localized_name}
stroke={playerColor}
strokeWidth={stroke}
strokeOpacity={opacity}
name={hero.localized_name}
/>);
})}
<Legend />
<Brush endIndex={12} height={20} />
</LineChart>
</ResponsiveContainer>
</StyledHolder>
);
}
return null;
}
}
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(Graph);
| odota/web/src/components/Match/Laning/Graph.jsx/0 | {
"file_path": "odota/web/src/components/Match/Laning/Graph.jsx",
"repo_id": "odota",
"token_count": 2007
} | 251 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { arrayOf, object, shape, number, bool, func, string, array } from 'prop-types';
import ReactTooltip from 'react-tooltip';
import styled from 'styled-components';
import { formatSeconds, calculateDistance, calculateRelativeXY, bindWidth } from '../../../utility';
import { IconRadiant, IconDire, IconDot } from '../../Icons';
import TeamTable from '../TeamTable';
import mcs from '../matchColumns';
import PlayerThumb from '../PlayerThumb';
import Timeline from '../Overview/Timeline';
import DotaMap from '../../DotaMap';
import constants from '../../constants';
import config from '../../../config';
const Styled = styled.div`
.parentContainer {
display: flex;
flex-direction: column;
margin: 0 -5px;
}
.timelineContainer {
margin-bottom: 75px;
}
.mapAndInfoContainer {
margin: 0 5px 10px 5px;
}
.headerGold {
margin: 0 25px;
}
.header {
margin: 10px 0 66px 0;
display: flex;
flex-direction: column;
align-items: center;
}
.headerSubInfo {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin-top: 10px;
& svg {
margin: 0;
}
}
.teamfightContainer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.tableContainer {
flex-grow: 1;
overflow-x: hidden;
margin: -56px 5px 0 5px;
}
.map {
position: relative;
max-width: 400px;
max-height: 400px;
background-size: contain;
}
.mapIcon {
position: absolute;
margin: 0 !important;
}
.teamfightIcon {
position: absolute;
margin: 0 !important;
cursor: pointer;
}
.tombstone {
position: absolute;
margin: 0 !important;
fill: ${constants.colorGolden};
opacity: 0.75;
}
.radiantTombstone {
fill: ${constants.colorSuccess};
}
.direTombstone {
fill: ${constants.colorDanger};
}
.radiantTombstoneTooltip {
border-width: 2px !important;
border-color: ${constants.colorSuccess} !important;
}
.direTombstoneTooltip {
border-width: 2px !important;
border-color: ${constants.colorDanger} !important;
}
.tooltipContainer {
display: flex;
align-items: center;
flex-direction: row;
padding: 10px;
margin: -8px -12px;
& > * {
margin: 0 5px;
&:first-child {
margin-left: 0;
}
&:last-child {
margin-right: 0;
}
}
& > div {
margin: 0;
color: ${constants.colorMutedLight};
}
}
.teamfightTooltipContainer {
flex-direction: column;
}
.winner {
filter: drop-shadow(0 0 20px #000);
padding: 0;
}
.goldChange {
display: flex;
align-items: center;
& img {
margin-left: 5px;
filter: drop-shadow(0 0 5px ${constants.colorGolden});
}
}
.radiantSelected {
& .header {
color: ${constants.colorSuccess};
}
}
.direSelected {
& .header {
color: ${constants.colorDanger};
}
}
.radiant {
padding: 0;
& .goldChange {
color: ${constants.colorSuccess};
}
margin: 0;
fill: #f5f5f5;
& svg {
filter: drop-shadow(0 0 5px green) drop-shadow(0 0 20px #000);
}
}
.dire {
padding: 0;
& .goldChange {
color: ${constants.colorDanger};
}
& svg {
filter: drop-shadow(0 0 5px red) drop-shadow(0 0 20px #000);
}
margin: 0;
fill: #000000;
}
.teamfightIconSvg {
& svg {
transition: ${constants.linearTransition};
}
}
.hovered {
& svg {
fill: ${constants.colorBlue} !important;
}
}
.selected {
& svg {
fill: ${constants.colorGolden} !important;
}
}
`;
const iconSize = (mapWidth, factor = 12, minSize = 15) =>
(mapWidth / factor <= minSize ? minSize : mapWidth / factor);
const style = (width, position, iconSizeOverride, options = { noTopAdjustment: false }) => ({
width: iconSizeOverride || iconSize(width),
height: iconSizeOverride || iconSize(width),
top: options.noTopAdjustment ? ((width / 127) * position.y) : ((width / 127) * position.y) - (iconSizeOverride || iconSize(width) / 2),
left: ((width / 127) * position.x) - (iconSizeOverride || iconSize(width) / 2),
});
const isRadiant = radiantGoldDelta => radiantGoldDelta > 0;
const IconType = _isRadiant => (_isRadiant ? IconRadiant : IconDire);
export const TeamfightIcon = ({
position, tooltipKey, mapWidth, onClick, Icon, ...props
}) => (
<Icon
className="teamfightIcon"
style={style(mapWidth, position)}
data-tip
data-for={tooltipKey}
onClick={onClick}
{...props}
/>
);
export const GoldDelta = ({ radiantGoldDelta }) => (
<div className="goldChange">
{isRadiant(radiantGoldDelta) ? radiantGoldDelta : radiantGoldDelta * -1}
<img src={`${config.VITE_IMAGE_CDN}/apps/dota2/images/tooltips/gold.png`} alt="Gold" />
</div>
);
const getIconStyle = radiantGoldDelta => (isRadiant(radiantGoldDelta) ? 'radiant' : 'dire');
const getSelectedStyle = radiantGoldDelta =>
(isRadiant(radiantGoldDelta) ? 'radiantSelected' : 'direSelected');
const getTombStyle = position => position.reduce(
(str, _position) => {
const radStr = _position.isRadiant ? 'radiant' : 'dire';
if (str !== radStr) {
return 'both';
}
return str;
},
position[0].isRadiant ? 'radiant' : 'dire',
);
export const Tombstones = ({
deathPositions, mapWidth, tooltipKey, strings,
}) => (
<div>
{deathPositions.map((position, index) => (
<div key={index}>
<TeamfightIcon
Icon={IconDot}
position={position[0]}
mapWidth={mapWidth}
tooltipKey={`${index}_${tooltipKey}`}
className={`mapIcon ${getTombStyle(position)}Tombstone`}
style={style(mapWidth, position[0], iconSize(mapWidth, 20))}
/>
<ReactTooltip
id={`${index}_${tooltipKey}`}
effect="solid"
border
class={`${getTombStyle(position)}TombstoneTooltip`}
>
{position.map((pos, _index) => (
<div key={_index} className="tooltipContainer">
<PlayerThumb {...pos.player} />
<div>{strings.tooltip_tombstone_killer}</div>
<PlayerThumb {...pos.killer} />
</div>
))}
</ReactTooltip>
</div>
))}
</div>
);
export const Teamfight = ({
position,
tooltipKey,
start,
end,
radiantGoldDelta,
selected,
hovered,
mapWidth,
onClick,
deathPositions,
strings,
}) => (
<div>
<div className={getIconStyle(radiantGoldDelta)}>
<div className={`teamfightIconSvg ${hovered && 'hovered'} ${selected && 'selected'}`}>
<TeamfightIcon
position={position}
isRadiant={isRadiant(radiantGoldDelta)}
tooltipKey={tooltipKey}
mapWidth={mapWidth}
onClick={onClick}
Icon={IconType(isRadiant(radiantGoldDelta))}
/>
</div>
<ReactTooltip
id={tooltipKey}
effect="solid"
>
<div className="tooltipContainer teamfightTooltipContainer">
<div>{formatSeconds(start)} - {formatSeconds(end)}</div>
<div>
<GoldDelta radiantGoldDelta={radiantGoldDelta} />
</div>
</div>
</ReactTooltip>
</div>
{selected && <Tombstones deathPositions={deathPositions} mapWidth={mapWidth} tooltipKey={tooltipKey} strings={strings} />}
</div>
);
const avgPosition = ({ deaths_pos: deathPositions }) => {
const avgs = deathPositions.reduce((avg, position, index) => {
const posTotal = position.reduce((_avg, _position) => ({
x: _avg.x + _position.x,
y: _avg.y + _position.y,
length: _avg.length + 1,
}), {
x: 0,
y: 0,
length: 0,
});
const newAvg = {
x: avg.x + posTotal.x,
y: avg.y + posTotal.y,
length: avg.length + posTotal.length,
};
if (index === deathPositions.length - 1) {
newAvg.x /= newAvg.length;
newAvg.y /= newAvg.length;
}
return newAvg;
}, {
x: 0,
y: 0,
length: 0,
});
return {
x: avgs.x,
y: avgs.y,
};
};
class TeamfightMap extends Component {
static propTypes = {
teamfights: arrayOf(object),
match: shape({}),
strings: shape({}),
sponsorIcon: string,
sponsorURL: string,
}
constructor(props) {
super();
const { teamfights = [] } = props;
const teamfight = teamfights.length > 0 ? teamfights[0] : null;
this.state = {
teamfight,
};
}
onIconClick = teamfight => () => {
// We do this because we need to prevent the map click event from
// being executed. That click event is innaccurate if the actual icon is clicked.
// event.stopPropagation();
this.setState({
teamfight,
});
};
onMapClick = width => (event) => {
const { x: x1, y: y1 } = calculateRelativeXY(event);
const { teamfights } = this.props;
const newSelection = teamfights
.reduce((cursor, teamfight) => {
let newCursor = { ...cursor };
const { left: x2, top: y2 } = style(width, avgPosition(teamfight));
const distance = calculateDistance(x1, y1, x2 + (iconSize(width) / 2), y2 + (iconSize(width) / 2));
if (distance < cursor.distance) {
newCursor = {
teamfight,
distance,
};
}
return newCursor;
}, {
teamfight: this.state.teamfight,
distance: Infinity,
});
this.setState({
teamfight: newSelection.teamfight,
});
};
onTeamfightHover = teamfight => () => {
this.setState({
hoveredTeamfight: teamfight,
});
};
onTimelineHover = start => this.curriedTeamfightHandler(this.onTeamfightHover, start);
onTimelineIconClick = start => this.curriedTeamfightHandler(this.onIconClick, start);
curriedTeamfightHandler = (fn, start) => (event) => {
fn(this.props.teamfights.find(tf => tf.start === start))(event);
};
isSelected = (teamfight = { start: null }) => this.state.teamfight && this.state.teamfight.start === teamfight.start;
isHovered(teamfight = { start: null }) {
return this.state.hoveredTeamfight && this.state.hoveredTeamfight.start === teamfight.start;
}
render() {
const {
teamfights = [], match, strings, sponsorURL, sponsorIcon,
} = this.props;
const teamfight = this.state.teamfight || {};
const Icon = IconType(isRadiant(teamfight.radiant_gold_advantage_delta));
const { teamfightColumns } = mcs(strings);
return (
<Styled>
<div className="timelineContainer">
<Timeline
match={match}
onTeamfightClick={this.onTimelineIconClick}
onTeamfightHover={this.onTimelineHover}
selectedTeamfight={teamfight && teamfight.start}
/>
</div>
<div className={`parentContainer ${getSelectedStyle(teamfight.radiant_gold_advantage_delta)}`}>
<div className="teamfightContainer">
<div className="mapAndInfoContainer">
<DotaMap
width={400}
maxWidth={400}
startTime={match.start_time}
>
{teamfights.map((teamFight, index) => (
<Teamfight
selected={this.isSelected(teamFight)}
hovered={this.isHovered(teamFight)}
key={teamFight.start}
onClick={this.onIconClick(teamFight)}
position={avgPosition(teamFight)}
tooltipKey={`${index}_${teamFight.start}`}
start={teamFight.start}
end={teamFight.end}
radiantGoldDelta={teamFight.radiant_gold_advantage_delta}
deathPositions={teamFight.deaths_pos}
mapWidth={400}
strings={strings}
/>
))}
</DotaMap>
<header className="header">
<div className="muted">
{formatSeconds(teamfight.start)} - {formatSeconds(teamfight.end)}
</div>
<div className="headerSubInfo">
<div className={getIconStyle(teamfight.radiant_gold_advantage_delta)}>
<Icon style={{ height: iconSize(bindWidth(400, 400)), width: iconSize(bindWidth(400, 400)) }} />
</div>
<span className="headerGold"><GoldDelta radiantGoldDelta={teamfight.radiant_gold_advantage_delta} /></span>
</div>
</header>
</div>
<div className="tableContainer">
<TeamTable
players={teamfight.players}
columns={teamfightColumns}
heading={strings.heading_teamfights}
buttonLabel={config.VITE_ENABLE_GOSUAI ? strings.gosu_teamfights : null}
buttonTo={`${sponsorURL}Teamfights`}
buttonIcon={sponsorIcon}
radiantTeam={this.props.match.radiant_team}
direTeam={this.props.match.dire_team}
radiantWin={match.radiant_win}
hideWinnerTag
/>
</div>
</div>
</div>
</Styled>
);
}
}
const positionShape = {
x: number,
y: number,
};
TeamfightIcon.propTypes = {
position: shape(positionShape),
tooltipKey: string,
mapWidth: number,
onClick: func, // not required because tombstone doesn't need click fn
Icon: func,
style: shape({}),
};
GoldDelta.propTypes = {
radiantGoldDelta: number,
};
Tombstones.propTypes = {
tooltipKey: string,
mapWidth: number,
deathPositions: arrayOf(array),
strings: shape({}),
};
Teamfight.propTypes = {
position: shape(positionShape),
tooltipKey: string,
start: number,
end: number,
radiantGoldDelta: number,
selected: bool,
hovered: bool,
mapWidth: number,
onClick: func,
deathPositions: arrayOf(array),
strings: shape({}),
};
const mapStateToProps = state => ({
strings: state.app.strings,
});
export default connect(mapStateToProps)(TeamfightMap);
| odota/web/src/components/Match/TeamfightMap/index.jsx/0 | {
"file_path": "odota/web/src/components/Match/TeamfightMap/index.jsx",
"repo_id": "odota",
"token_count": 6003
} | 252 |
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
const StyledSvg = styled.svg`
width: 32px;
height: 32px;
transform: rotate(-90deg);
border-radius: 50%;
`;
const StyledCircle = styled.circle`
fill: var(--primaryTextColor);
stroke: var(--colorYelor);
stroke-width: 32;
stroke-dasharray: 38 100;
`;
const PiePercent = ({ percent, color, negativeColor }) => (
<StyledSvg viewBox="0 0 32 32" styles={{ color: negativeColor }}>
<StyledCircle
r="16"
cx="16"
cy="16"
shapeRendering="crispEdges"
style={{ strokeDasharray: `${percent} 100`, color }}
/>
</StyledSvg>
);
PiePercent.propTypes = {
percent: PropTypes.number,
color: PropTypes.string,
negativeColor: PropTypes.string,
};
export default PiePercent;
| odota/web/src/components/PiePercent/PiePercent.jsx/0 | {
"file_path": "odota/web/src/components/PiePercent/PiePercent.jsx",
"repo_id": "odota",
"token_count": 308
} | 253 |
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { getPlayerHistograms } from '../../../../actions';
import ButtonGarden from '../../../ButtonGarden';
import Container from '../../../Container';
import Heading from '../../../Heading';
import { HistogramGraph } from '../../../Visualizations';
import dataColumns from '../matchDataColumns';
import { formatGraphValueData } from '../../../../utility';
const getMedian = (columns, midpoint) => {
let sum = 0;
const medianCol = columns.find((col) => {
sum += col.games;
return (sum >= midpoint);
});
return medianCol && medianCol.x;
};
const getSubtitleStats = (columns, strings, histogramName) => {
const total = columns.reduce((sum, col) => (sum + col.games), 0);
let median = getMedian(columns, total / 2);
median = formatGraphValueData(median, histogramName);
return `(${strings.heading_total_matches}: ${total}${(median !== undefined) ? `, ${strings.heading_median}: ${median})` : ''}`;
};
const getSubtitleDescription = (histogramName, strings) => (strings[`histograms_${histogramName}_description`] || '');
const histogramNames = dataColumns.filter(col => col !== 'win_rate');
const Histogram = ({
routeParams, columns, playerId, error, loading, histogramName, history, strings,
}) => (
<div>
<Heading title={strings.histograms_name} subtitle={strings.histograms_description} />
<ButtonGarden
onClick={(buttonName) => {
history.push(`/players/${playerId}/histograms/${buttonName}${window.location.search}`);
}}
buttonNames={histogramNames}
selectedButton={routeParams.subInfo || histogramNames[0]}
/>
<Container error={error} loading={loading}>
<div>
<Heading
title={strings[`heading_${histogramName}`]}
subtitle={loading ? '' : [getSubtitleDescription(histogramName, strings), getSubtitleStats(columns, strings, histogramName)].filter(Boolean).join(' ')}
/>
<HistogramGraph columns={columns || []} histogramName={histogramName} />
</div>
</Container>
</div>
);
Histogram.propTypes = {
routeParams: PropTypes.shape({}),
columns: PropTypes.number,
playerId: PropTypes.string,
error: PropTypes.string,
loading: PropTypes.bool,
histogramName: PropTypes.string,
history: PropTypes.shape({}),
strings: PropTypes.shape({}),
};
const getData = (props) => {
props.getPlayerHistograms(props.playerId, props.location.search, props.routeParams.subInfo || histogramNames[0]);
};
class RequestLayer extends React.Component {
static propTypes = {
playerId: PropTypes.string,
location: PropTypes.shape({
key: PropTypes.string,
}),
strings: PropTypes.shape({}),
}
componentDidMount() {
getData(this.props);
}
componentDidUpdate(prevProps) {
if (this.props.playerId !== prevProps.playerId
|| this.props.location.key !== prevProps.location.key) {
getData(this.props);
}
}
render() {
return <Histogram {...this.props} />;
}
}
const mapStateToProps = (state, { histogramName = histogramNames[0] }) => ({
histogramName,
columns: state.app.playerHistograms.data,
loading: state.app.playerHistograms.loading,
error: state.app.playerHistograms.error,
strings: state.app.strings,
});
export default withRouter(connect(mapStateToProps, { getPlayerHistograms })(RequestLayer));
| odota/web/src/components/Player/Pages/Histograms/Histograms.jsx/0 | {
"file_path": "odota/web/src/components/Player/Pages/Histograms/Histograms.jsx",
"repo_id": "odota",
"token_count": 1202
} | 254 |
import { transformations, displayHeroId } from '../../../../utility';
export default strings => [{
displayName: strings.th_hero_id,
tooltip: strings.tooltip_hero_id,
field: 'hero_id',
sortFn: true,
displayFn: displayHeroId,
}, {
displayName: strings.th_result,
tooltip: strings.tooltip_result,
field: 'radiant_win',
displayFn: transformations.radiant_win_and_game_mode,
}, {
displayName: strings.th_duration,
tooltip: strings.tooltip_duration,
field: 'duration',
sortFn: true,
displayFn: transformations.duration,
}];
| odota/web/src/components/Player/Pages/Records/playerRecordsColumns.jsx/0 | {
"file_path": "odota/web/src/components/Player/Pages/Records/playerRecordsColumns.jsx",
"repo_id": "odota",
"token_count": 186
} | 255 |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { transformations, formatSeconds, getOrdinal, displayHeroId } from '../../utility';
import { getRecords } from '../../actions';
import Table from '../Table';
import Heading from '../Heading';
// import { IconRadiant, IconDire, IconTrophy } from '../Icons';
import Container from '../Container';
import TabBar from '../TabBar';
const matchesColumns = (field, strings) => [{
displayName: strings.th_rank,
field: 'rank',
displayFn: (row, col, _field) => getOrdinal(_field),
}, {
displayName: strings[`heading_${field}`],
tooltip: strings[`tooltip_${field}`],
field: 'score',
displayFn: (row, col, _field) => (!row.hero_id ? formatSeconds(_field) : Number(_field).toLocaleString()),
}, {
displayName: strings.th_match_id,
tooltip: strings.match_id,
field: 'match_id',
displayFn: transformations.match_id_with_time,
}, {
displayName: strings.th_hero_id,
tooltip: strings.tooltip_hero_id,
field: 'hero_id',
displayFn: (row, col, _field) => (!row.hero_id ? null : displayHeroId(row, col, _field)),
}];
const fields = ['duration', 'kills', 'deaths', 'assists', 'gold_per_min', 'xp_per_min', 'last_hits', 'denies', 'hero_damage', 'tower_damage', 'hero_healing'];
const tabs = strings => (fields.map(field => ({
name: strings[`heading_${field}`],
key: field,
tooltip: strings[`tooltip_${field}`],
content: propsPar => (
<Container>
<Table
data={propsPar.data.map((element, index) => ({ ...element, rank: index + 1 }))}
columns={matchesColumns(field, strings)}
loading={propsPar.loading}
/>
</Container>),
route: `/records/${field}`,
})));
const getData = (props) => {
const route = props.match.params.info || 'duration';
props.dispatchRecords(route);
};
class RequestLayer extends React.Component {
static propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
info: PropTypes.string,
}),
}),
strings: PropTypes.shape({}),
}
componentDidMount() {
getData(this.props);
}
componentDidUpdate(prevProps) {
if (this.props.match.params.info !== prevProps.match.params.info) {
getData(this.props);
}
}
render() {
const route = this.props.match.params.info || 'duration';
const { strings } = this.props;
const tab = tabs(strings).find(_tab => _tab.key === route);
return (
<div>
<Helmet title={strings.heading_records} />
<div>
<TabBar
info={route}
tabs={tabs(strings)}
/>
<Heading title={strings.heading_records} subtitle={strings.subheading_records} className="top-heading with-tabbar"/>
{tab && tab.content(this.props)}
</div>
</div>);
}
}
const mapStateToProps = state => ({
data: state.app.records.data,
loading: state.app.records.loading,
strings: state.app.strings,
});
const mapDispatchToProps = dispatch => ({
dispatchRecords: info => dispatch(getRecords(info)),
});
export default connect(mapStateToProps, mapDispatchToProps)(RequestLayer);
| odota/web/src/components/Records/index.jsx/0 | {
"file_path": "odota/web/src/components/Records/index.jsx",
"repo_id": "odota",
"token_count": 1201
} | 256 |
import React from 'react';
import ContentLoader from 'react-content-loader';
const DistributionsSkeleton = props => (
<ContentLoader
height={200}
width={500}
primaryColor="#666"
secondaryColor="#ecebeb"
animate
{...props}
>
<rect x="150" y="50" rx="5" ry="5" width="5" height="100" />
<rect x="160" y="45" rx="5" ry="5" width="5" height="105" />
<rect x="170" y="41" rx="5" ry="5" width="5" height="109" />
<rect x="180" y="37" rx="5" ry="5" width="5" height="113" />
<rect x="190" y="33" rx="5" ry="5" width="5" height="117" />
<rect x="200" y="29" rx="5" ry="5" width="5" height="121" />
<rect x="210" y="25" rx="5" ry="5" width="5" height="125" />
<rect x="220" y="21" rx="5" ry="5" width="5" height="129" />
<rect x="230" y="18" rx="5" ry="5" width="5" height="132" />
<rect x="240" y="15" rx="5" ry="5" width="5" height="135" />
<rect x="250" y="14" rx="5" ry="5" width="5" height="136" />
<rect x="260" y="14" rx="5" ry="5" width="5" height="136" />
<rect x="270" y="15" rx="5" ry="5" width="5" height="135" />
<rect x="280" y="18" rx="5" ry="5" width="5" height="132" />
<rect x="290" y="21" rx="5" ry="5" width="5" height="129" />
<rect x="300" y="25" rx="5" ry="5" width="5" height="125" />
<rect x="310" y="29" rx="5" ry="5" width="5" height="121" />
<rect x="320" y="33" rx="5" ry="5" width="5" height="117" />
<rect x="330" y="37" rx="5" ry="5" width="5" height="113" />
<rect x="340" y="41" rx="5" ry="5" width="5" height="109" />
<rect x="350" y="45" rx="5" ry="5" width="5" height="105" />
</ContentLoader>
);
export default DistributionsSkeleton;
| odota/web/src/components/Skeletons/DistributionsSkeleton.jsx/0 | {
"file_path": "odota/web/src/components/Skeletons/DistributionsSkeleton.jsx",
"repo_id": "odota",
"token_count": 799
} | 257 |
import React from 'react';
import PropTypes from 'prop-types';
import { List } from 'react-content-loader';
import TabBar from '../TabBar';
class RenderContent extends React.Component {
static propTypes = {
skeleton: PropTypes.bool,
content: PropTypes.shape({}),
};
state = {
render: false,
};
componentDidMount() {
requestAnimationFrame(() => {
requestAnimationFrame(() => this.setState({ render: true }));
});
}
render() {
const { skeleton, content } = this.props;
const { render } = this.state;
const PlaceHolder = () =>
(skeleton ? <List primaryColor="#666" width={250} height={120} /> : null);
return render && content ? (
content
) : (
<div style={{ width: '100%', height: 1200 }}>
<PlaceHolder />
</div>
);
}
}
const TabbedContent = ({
info, tabs, match, content, skeleton,
}) => (
<React.Fragment>
<TabBar info={info} tabs={tabs} match={match} />
<RenderContent content={content} skeleton={skeleton} key={info} />
</React.Fragment>
);
TabbedContent.propTypes = {
tabs: PropTypes.arrayOf(PropTypes.shape({})),
info: PropTypes.string,
match: PropTypes.shape({}),
content: PropTypes.shape({}),
skeleton: PropTypes.bool,
};
export default TabbedContent;
| odota/web/src/components/TabbedContent/TabbedContent.jsx/0 | {
"file_path": "odota/web/src/components/TabbedContent/TabbedContent.jsx",
"repo_id": "odota",
"token_count": 463
} | 258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.