hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 3,
"code_window": [
" `Unable to update '${packageJsonPath}': Format properties ` +\n",
" `(${formatProperties.join(', ')}) map to more than one format-path.`);\n",
" }\n",
"\n",
" update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty});\n",
" }\n",
"\n",
" update.writeChanges(packageJsonPath, packageJson);\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" update.addChange(\n",
" [`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], newFormatPath, {before: formatProperty});\n"
],
"file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts",
"type": "replace",
"edit_start_line_idx": 95
}
|
# Sharing modules
Creating shared modules allows you to organize and streamline your code. You can put commonly
used directives, pipes, and components into one module and then import just that module wherever
you need it in other parts of your app.
Consider the following module from an imaginary app:
```typescript
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CustomerComponent } from './customer.component';
import { NewItemDirective } from './new-item.directive';
import { OrdersPipe } from './orders.pipe';
@NgModule({
imports: [ CommonModule ],
declarations: [ CustomerComponent, NewItemDirective, OrdersPipe ],
exports: [ CustomerComponent, NewItemDirective, OrdersPipe,
CommonModule, FormsModule ]
})
export class SharedModule { }
```
Note the following:
* It imports the `CommonModule` because the module's component needs common directives.
* It declares and exports the utility pipe, directive, and component classes.
* It re-exports the `CommonModule` and `FormsModule`.
By re-exporting `CommonModule` and `FormsModule`, any other module that imports this
`SharedModule`, gets access to directives like `NgIf` and `NgFor` from `CommonModule`
and can bind to component properties with `[(ngModel)]`, a directive in the `FormsModule`.
Even though the components declared by `SharedModule` might not bind
with `[(ngModel)]` and there may be no need for `SharedModule`
to import `FormsModule`, `SharedModule` can still export
`FormsModule` without listing it among its `imports`. This
way, you can give other modules access to `FormsModule` without
having to import it directly into the `@NgModule` decorator.
### Using components vs services from other modules
There is an important distinction between using another module's component and
using a service from another module. Import modules when you want to use
directives, pipes, and components. Importing a module with services means that you will have a new instance of that service, which typically is not what you need (typically one wants to reuse an existing service). Use module imports to control service instantiation.
The most common way to get a hold of shared services is through Angular
[dependency injection](guide/dependency-injection), rather than through the module system (importing a module will result in a new service instance, which is not a typical usage).
To read about sharing services, see [Providers](guide/providers).
<hr />
## More on NgModules
You may also be interested in the following:
* [Providers](guide/providers).
* [Types of Feature Modules](guide/module-types).
|
aio/content/guide/sharing-ngmodules.md
| 0 |
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
|
[
0.00017858178762253374,
0.00016589155711699277,
0.00015848064504098147,
0.00016251170018222183,
0.000006480184310930781
] |
{
"id": 3,
"code_window": [
" `Unable to update '${packageJsonPath}': Format properties ` +\n",
" `(${formatProperties.join(', ')}) map to more than one format-path.`);\n",
" }\n",
"\n",
" update.addChange([`${formatProperty}_ivy_ngcc`], newFormatPath, {before: formatProperty});\n",
" }\n",
"\n",
" update.writeChanges(packageJsonPath, packageJson);\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" update.addChange(\n",
" [`${formatProperty}${NGCC_PROPERTY_EXTENSION}`], newFormatPath, {before: formatProperty});\n"
],
"file_path": "packages/compiler-cli/ngcc/src/writing/new_entry_point_file_writer.ts",
"type": "replace",
"edit_start_line_idx": 95
}
|
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.
|
integration/cli-hello-world-ivy-minimal/browserslist
| 0 |
https://github.com/angular/angular/commit/16e15f50d2e7769c153f3e6cf07f57e2dc8054c5
|
[
0.00016955392493400723,
0.00016920003690756857,
0.00016884614888112992,
0.00016920003690756857,
3.5388802643865347e-7
] |
{
"id": 0,
"code_window": [
"/// <reference path=\"./polylabel.d.ts\" />\n",
"/// <reference path=\"../node/node.d.ts\" />\n",
"import polylabel = require('polylabel');\n",
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"import * as polylabel from 'polylabel';\n"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
/// <reference path="./polylabel.d.ts" />
/// <reference path="../node/node.d.ts" />
import polylabel = require('polylabel');
const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]
let p: number[]
p = polylabel(polygon)
p = polylabel(polygon, 1.0)
p = polylabel(polygon, 1.0, true)
p = polylabel(polygon, 1.0, false)
|
polylabel/polylabel-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.9981968998908997,
0.49918702244758606,
0.00017713250417727977,
0.49918702244758606,
0.4990098774433136
] |
{
"id": 0,
"code_window": [
"/// <reference path=\"./polylabel.d.ts\" />\n",
"/// <reference path=\"../node/node.d.ts\" />\n",
"import polylabel = require('polylabel');\n",
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"import * as polylabel from 'polylabel';\n"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> The repository for *high quality* TypeScript type definitions.
For more information see the [definitelytyped.org](http://definitelytyped.org) website.
## Usage
Include a line like this:
```typescript
/// <reference path="jquery.d.ts" />
```
## Contributions
DefinitelyTyped only works because of contributions by users like you!
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped.
## How to get the definitions
* Directly from the GitHub repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [Typings - TypeScript Definition Manager](https://github.com/typings/typings)
## List of definitions
* See [CONTRIBUTORS.md](CONTRIBUTORS.md)
## Requested definitions
Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
## License
This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[](https://github.com/igrigorik/ga-beacon)
|
README.md
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0001707765186438337,
0.00016754676471464336,
0.0001636045635677874,
0.00016841075557749718,
0.0000025220783754775766
] |
{
"id": 0,
"code_window": [
"/// <reference path=\"./polylabel.d.ts\" />\n",
"/// <reference path=\"../node/node.d.ts\" />\n",
"import polylabel = require('polylabel');\n",
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"import * as polylabel from 'polylabel';\n"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
// Type definitions for redux-devtools-dock-monitor 1.0.1
// Project: https://github.com/gaearon/redux-devtools-dock-monitor
// Definitions by: Petryshyn Sergii <https://github.com/mc-petry>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare module "redux-devtools-dock-monitor" {
import * as React from 'react'
interface IDockMonitorProps {
/**
* Any valid Redux DevTools monitor.
*/
children?: React.ReactNode
/**
* A key or a key combination that toggles the dock visibility.
* Must be recognizable by parse-key (for example, 'ctrl-h')
*/
toggleVisibilityKey: string
/**
* A key or a key combination that toggles the dock position.
* Must be recognizable by parse-key (for example, 'ctrl-w')
*/
changePositionKey: string
/**
* When true, the dock size is a fraction of the window size, fixed otherwise.
*
* @default true
*/
fluid?: boolean
/**
* Size of the dock. When fluid is true, a float (0.5 means half the window size).
* When fluid is false, a width in pixels
*
* @default 0.3 (3/10th of the window size)
*/
defaultSize?: number
/**
* Where the dock appears on the screen.
* Valid values: 'left', 'top', 'right', 'bottom'
*
* @default 'right'
*/
defaultPosition?: string
/**
* @default true
*/
defaultIsVisible?: boolean
}
export default class DockMonitor extends React.Component<IDockMonitorProps, any> {}
}
|
redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00017216165724676102,
0.00016942298680078238,
0.000165000295965001,
0.00017034992924891412,
0.00000257791657531925
] |
{
"id": 0,
"code_window": [
"/// <reference path=\"./polylabel.d.ts\" />\n",
"/// <reference path=\"../node/node.d.ts\" />\n",
"import polylabel = require('polylabel');\n",
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n"
],
"labels": [
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"import * as polylabel from 'polylabel';\n"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 1
}
|
// Type definitions for babel-template v6.7
// Project: https://github.com/babel/babel/tree/master/packages/babel-template
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../babylon/babylon.d.ts" />
/// <reference path="../babel-types/babel-types.d.ts" />
declare module "babel-template" {
import {BabylonOptions} from 'babylon';
import * as t from 'babel-types';
type Node = t.Node;
// NB: This export doesn't match the handbook example, where `template` is the default export.
// But it does match the runtime behaviour (at least at the time of this writing). For some reason,
// babel-template/lib/index.js has this line at the bottom: module.exports = exports["default"];
export = template;
function template(code: string, opts?: BabylonOptions): UseTemplate;
type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node;
}
|
babel-template/babel-template.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00017659908917266876,
0.0001706782350083813,
0.0001637945242691785,
0.00017164109158329666,
0.000005271593181532808
] |
{
"id": 1,
"code_window": [
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n",
"let p: number[]\n",
"p = polylabel(polygon)\n",
"p = polylabel(polygon, 1.0)\n",
"p = polylabel(polygon, 1.0, true)\n",
"p = polylabel(polygon, 1.0, false)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"polylabel(polygon)\n",
"polylabel(polygon, 1.0)\n",
"polylabel(polygon, 1.0, true)\n",
"polylabel(polygon, 1.0, false)"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
// Type definitions for polylabel 1.0.0
// Project: https://github.com/mapbox/polylabel
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* polylabel
*
* A fast algorithm for finding polygon pole of inaccessibility, the most distant internal point from
* the polygon outline (not to be confused with centroid), implemented as a JavaScript library.
* Useful for optimal placement of a text label on a polygon.
* It's an iterative grid algorithm, inspired by paper by Garcia-Castellanos & Lombardo, 2007.
* Unlike the one in the paper, this algorithm:
*
* - guarantees finding global optimum within the given precision
* - is many times faster (10-40x)
*/
declare module 'polylabel' {
/**
* Polylabel returns the pole of inaccessibility coordinate in [x, y] format.
*
* @name polylabel
* @function
* @param {Array<number>} polygon - Given polygon coordinates in GeoJSON-like format
* @param {number} precision - Precision (1.0 by default)
* @param {boolean} debug - Debugging for Console
* @return {Array<number>}
* @example
* var p = polylabel(polygon, 1.0);
*/
function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];
export = polylabel;
}
|
polylabel/polylabel.d.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.9963262677192688,
0.2559208273887634,
0.0005292052519507706,
0.013413949869573116,
0.42759639024734497
] |
{
"id": 1,
"code_window": [
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n",
"let p: number[]\n",
"p = polylabel(polygon)\n",
"p = polylabel(polygon, 1.0)\n",
"p = polylabel(polygon, 1.0, true)\n",
"p = polylabel(polygon, 1.0, false)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"polylabel(polygon)\n",
"polylabel(polygon, 1.0)\n",
"polylabel(polygon, 1.0, true)\n",
"polylabel(polygon, 1.0, false)"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
/// <reference path="supertest-as-promised.d.ts" />
/// <reference path="../express/express.d.ts" />
/// <reference path="../jasmine/jasmine.d.ts" />
import * as request from 'supertest-as-promised';
import * as express from 'express';
var app = express();
// chain your requests like you were promised:
request(app)
.get("/user")
.expect(200)
.then(function (res) {
return request(app)
.post("/kittens")
.send({ userId: res})
.expect(201);
})
.then(function (res) {
// ...
});
// Usage
request(app)
.get("/kittens")
.expect(200)
.then(function (res) {
// ...
});
describe("GET /kittens", function () {
it("should work", function () {
return request(app).get("/kittens").expect(200);
});
});
// Agents
var agent = request.agent(app);
agent
.get("/ugly-kitteh")
.expect(404)
.then(function () {
// ...
})
// Promisey goodness
request(app)
.get("/kittens")
.expect(201)
.then(function (res) { /* ... */ })
// I'm a real promise now!
.catch(function (err) { /* ... */ })
request(app)
.get("/kittens")
.expect(201)
.toPromise()
// I'm a real promise now!
.delay(10)
.then(function (res) { /* ... */ })
|
supertest-as-promised/supertest-as-promised-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00017363234655931592,
0.00017002761887852103,
0.0001636711967876181,
0.0001714541285764426,
0.0000032253478821075987
] |
{
"id": 1,
"code_window": [
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n",
"let p: number[]\n",
"p = polylabel(polygon)\n",
"p = polylabel(polygon, 1.0)\n",
"p = polylabel(polygon, 1.0, true)\n",
"p = polylabel(polygon, 1.0, false)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"polylabel(polygon)\n",
"polylabel(polygon, 1.0)\n",
"polylabel(polygon, 1.0, true)\n",
"polylabel(polygon, 1.0, false)"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
// Type definitions for db-migrate-pg
// Project: https://github.com/db-migrate/pg
// Definitions by: nickiannone <http://github.com/nickiannone>
// Definitions: https://github.com/nickiannone/DefinitelyTyped
/// <reference path="../db-migrate-base/db-migrate-base.d.ts"/>
/// <reference path="../pg/pg.d.ts" />
declare module "db-migrate-pg" {
import * as pg from "pg";
import * as DbMigrateBase from "db-migrate-base";
import * as Promise from "bluebird";
// Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options.
export interface CreateDatabaseOptions {}
export interface DropDatabaseOptions {
ifExists?: boolean;
}
export interface CreateSequenceOptions {
temp?: boolean;
}
export interface SwitchDatabaseOptions {
database?: string;
}
export interface DropSequenceOptions {
ifExists?: boolean;
cascade?: boolean;
restrict?: boolean;
}
export interface ColumnConstraint {
foreignKey: (callback: DbMigrateBase.CallbackFunction) => void;
constraints: string;
}
export interface ColumnConstraintOptions {
emitPrimaryKey?: boolean;
}
export class PgDriver extends DbMigrateBase.Base {
constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions);
createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void;
dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint;
createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise<any>;
dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise<any>;
createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise<any>;
switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise<any>;
dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise<any>;
}
}
|
db-migrate-pg/db-migrate-pg.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0009740851819515228,
0.0002920057740993798,
0.00016417668666690588,
0.00016906495147850364,
0.00027923763263970613
] |
{
"id": 1,
"code_window": [
"\n",
"const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]\n",
"let p: number[]\n",
"p = polylabel(polygon)\n",
"p = polylabel(polygon, 1.0)\n",
"p = polylabel(polygon, 1.0, true)\n",
"p = polylabel(polygon, 1.0, false)\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"polylabel(polygon)\n",
"polylabel(polygon, 1.0)\n",
"polylabel(polygon, 1.0, true)\n",
"polylabel(polygon, 1.0, false)"
],
"file_path": "polylabel/polylabel-tests.ts",
"type": "replace",
"edit_start_line_idx": 5
}
|
/// <reference path="falcor-json-graph.d.ts" />
import {Key, KeySet, Path, PathSet, ref, atom, error, pathValue, pathInvalidation} from 'falcor-json-graph';
const stringKey: Key = "productsById";
const numberKey: Key = 10;
const booleanKey: Key = true;
const keySet01: KeySet = stringKey;
const keySet02: KeySet = [stringKey];
const KeySet03: KeySet = {from: 1, to: 10};
const KeySet04: KeySet = ["name", {from: 0, length: 10}];
const path0: Path = ["productsById", "1234", "name"];
const path1: Path = [stringKey, numberKey, booleanKey];
const pathSet01: PathSet = ["productsById", ["1234", "5678"], ["name", "price"]];
const pathSet02: PathSet = ["products", [{from: 0, length: 10}, "length"], ["name", "price"]];
var ref01 = ref(['hoge']);
var ref02 = ref(['hoge'], {$expires: 1000});
console.log(ref02.$type, ref02.value, ref02.$expires);
var atom01 = atom('hoge');
var atom02 = atom('hoge', {$expires: 1000});
console.log(atom02.$type, atom02.value, atom02.$expires);
var err01 = error('some error!');
var err02 = error('some error!', {$expires: 1000});
console.log(err02.$type === 'error', ref02.value, ref02.$expires);
var pv01 = pathValue('hoge', 'FOO');
var pv02 = pathValue('hoge[0].bar', 'FOO');
var pv03 = pathValue('hoge[0...100].bar', 'FOO');
var pv04 = pathValue(['hoge', {from: 0, to: 100}, 'bar'], 'FOO');
console.log(pv04.path, pv04.value);
var ip01 = pathInvalidation('hoge');
console.log(ip01.path, ip01.invalidate);
|
falcor-json-graph/falcor-json-graph-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0002121196303050965,
0.00018063462630379945,
0.0001679480919847265,
0.00017123541329056025,
0.000018306769561604597
] |
{
"id": 2,
"code_window": [
" * - guarantees finding global optimum within the given precision\n",
" * - is many times faster (10-40x)\n",
" */\n",
"declare module 'polylabel' {\n",
" /**\n",
" * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.\n",
" * \n",
" * @name polylabel\n",
" * @function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare module \"polylabel\" {\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 17
}
|
/// <reference path="./polylabel.d.ts" />
/// <reference path="../node/node.d.ts" />
import polylabel = require('polylabel');
const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]
let p: number[]
p = polylabel(polygon)
p = polylabel(polygon, 1.0)
p = polylabel(polygon, 1.0, true)
p = polylabel(polygon, 1.0, false)
|
polylabel/polylabel-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0008731039706617594,
0.0005221178289502859,
0.00017113170179072767,
0.0005221178289502859,
0.00035098614171147346
] |
{
"id": 2,
"code_window": [
" * - guarantees finding global optimum within the given precision\n",
" * - is many times faster (10-40x)\n",
" */\n",
"declare module 'polylabel' {\n",
" /**\n",
" * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.\n",
" * \n",
" * @name polylabel\n",
" * @function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare module \"polylabel\" {\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 17
}
|
--target es5 --noImplicitAny
|
jbinary/jbinary.d.ts.tscparams
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00017522786220069975,
0.00017522786220069975,
0.00017522786220069975,
0.00017522786220069975,
0
] |
{
"id": 2,
"code_window": [
" * - guarantees finding global optimum within the given precision\n",
" * - is many times faster (10-40x)\n",
" */\n",
"declare module 'polylabel' {\n",
" /**\n",
" * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.\n",
" * \n",
" * @name polylabel\n",
" * @function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare module \"polylabel\" {\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 17
}
|
///<reference path="graphviz.d.ts"/>
import graphviz = require('graphviz');
// Create digraph G
var g: graphviz.Graph = graphviz.digraph("G");
// Add node (ID: Hello)
var n1: graphviz.Node = g.addNode( "Hello", {"color" : "blue"} );
n1.set( "style", "filled" );
// Add node (ID: World)
g.addNode( "World" );
// Add edge between the two nodes
var e: graphviz.Edge = g.addEdge( n1, "World" );
e.set( "color", "red" );
// Print the dot script
console.log( g.to_dot() );
// Set GraphViz path (if not in your path)
g.setGraphVizPath( "/usr/local/bin" );
// Generate a PNG output
g.output( "png", "test01.png" );
|
graphviz/graphviz-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0001786093635018915,
0.00017837736231740564,
0.00017826091789174825,
0.00017826177645474672,
1.6405684277742694e-7
] |
{
"id": 2,
"code_window": [
" * - guarantees finding global optimum within the given precision\n",
" * - is many times faster (10-40x)\n",
" */\n",
"declare module 'polylabel' {\n",
" /**\n",
" * Polylabel returns the pole of inaccessibility coordinate in [x, y] format.\n",
" * \n",
" * @name polylabel\n",
" * @function\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"declare module \"polylabel\" {\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 17
}
|
/// <reference path="smart-fox-server.d.ts" />
function test_Vec3D() {
var Vec3D: SFS2X.Entities.Data.Vec3D = new SFS2X.Entities.Data.Vec3D(0, 0, 0);
var Vec3Dalt: SFS2X.Entities.Data.Vec3D = new SFS2X.Entities.Data.Vec3D(0, 0);
var positionX: number = Vec3D.px;
var positionY: number = Vec3D.py;
var positionZ: number = Vec3D.pz;
var isFloat: boolean = Vec3D.isFloat();
return Vec3D;
};
function test_MatchExpression() {
var exp = new SFS2X.Entities.Match.MatchExpression('rank', SFS2X.Entities.Match.NumberMatch.GREATER_THAN, 5)
.and('country', SFS2X.Entities.Match.StringMatch.EQUALS, 'Italy');
var exp = new SFS2X.Entities.Match.MatchExpression(SFS2X.Entities.Match.RoomProperties.IS_GAME, SFS2X.Entities.Match.BoolMatch.EQUALS, true)
.and(SFS2X.Entities.Match.RoomProperties.HAS_FREE_PLAYER_SLOTS, SFS2X.Entities.Match.BoolMatch.EQUALS, true)
.and('isGameStarted', SFS2X.Entities.Match.BoolMatch.EQUALS, false);
var exp = new SFS2X.Entities.Match.MatchExpression('avatarData.shield.inUse', SFS2X.Entities.Match.BoolMatch.EQUALS, true);
var exp = new SFS2X.Entities.Match.MatchExpression('avatarData.weapons.3.name', SFS2X.Entities.Match.StringMatch.EQUALS, "Narsil");
}
function test_MMOItemVariable() {
var MMOItemVar1: SFS2X.Entities.Variables.MMOItemVariable = new SFS2X.Entities.Variables.MMOItemVariable('string', 'vlaue');
var MMOItemVar2: SFS2X.Entities.Variables.MMOItemVariable = new SFS2X.Entities.Variables.MMOItemVariable('string', 'vlaue', 2);
var MMOItemTypeName: string = MMOItemVar1.getTypeName(1);
var MMOItemisNull: boolean = MMOItemVar1.isNull();
var MMOItemString: string = MMOItemVar1.toString();
var name: string = MMOItemVar1.name;
var value: any = MMOItemVar1.value;
return MMOItemVar1;
}
function test_BuddyListAddBuddyRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.AddBuddyRequest('John'));
}
function test_BuddyListBlockBuddyRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.BlockBuddyRequest('John', true));
}
function test_BuddyListGoOnlineRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.GoOnlineRequest(true));
}
function test_BuddyListInitBuddyListRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.InitBuddyListRequest());
}
function test_BuddyListRemoveBuddyRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.RemoveBuddyRequest('John'));
}
function test_BuddyListSetBuddyVariablesRequest() {
var sfs = new SFS2X.SmartFox();
sfs.send(new SFS2X.Requests.BuddyList.SetBuddyVariablesRequest([]));
}
function test_GameCreateSFSGameRequest() {
var sfs = new SFS2X.SmartFox();
var settings = new SFS2X.Requests.Game.SFSGameSettings("DartsGame");
settings.maxUsers = 2;
settings.maxSpectators = 8;
settings.isPublic = true;
settings.minPlayersToStartGame = 2;
settings.notifyGameStarted = true;
sfs.send(new SFS2X.Requests.Game.CreateSFSGameRequest(settings));
}
function test_ErrorCodes() {
SFS2X.ErrorCodes.setErrorMessage(13, "Le Groupe demandé n'est pas disponible - Salle: {0}; Groupe: {1}");
}
function test_SmartFoxaddEventListener() {
var sfs = new SFS2X.SmartFox();
function onConnection(event: SFS2X.ICONNECTION) {
if(event.success)
{
// On Success
}
};
function onConnectionLost(event: SFS2X.ICONNECTION_LOST) {
// Print why connection was lost
console.log(event.reason);
};
function onLoginError(event: SFS2X.ILOGIN_ERROR) {
if (event.errorCode)
{
// handle error
}
};
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this);
}
|
smart-fox-server/smart-fox-server-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.0001745917834341526,
0.00017175239918287843,
0.0001692229852778837,
0.00017215621483046561,
0.000001864047931121604
] |
{
"id": 3,
"code_window": [
" * @example\n",
" * var p = polylabel(polygon, 1.0);\n",
" */\n",
" function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" export = polylabel;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" namespace polylabel {}\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 30
}
|
/// <reference path="./polylabel.d.ts" />
/// <reference path="../node/node.d.ts" />
import polylabel = require('polylabel');
const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]]
let p: number[]
p = polylabel(polygon)
p = polylabel(polygon, 1.0)
p = polylabel(polygon, 1.0, true)
p = polylabel(polygon, 1.0, false)
|
polylabel/polylabel-tests.ts
| 1 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.9043976068496704,
0.4522891640663147,
0.0001807373046176508,
0.4522891640663147,
0.4521084129810333
] |
{
"id": 3,
"code_window": [
" * @example\n",
" * var p = polylabel(polygon, 1.0);\n",
" */\n",
" function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" export = polylabel;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" namespace polylabel {}\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 30
}
|
// Type definitions for Vega
// Project: http://trifacta.github.io/vega/
// Definitions by: Tom Crockett <http://github.com/pelotom>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Vega {
export interface Parse {
spec(url: string, callback: (chart: (args: ViewArgs) => View) => void): void;
spec(spec: Spec, callback: (chart: (args: ViewArgs) => View) => void): void;
data(dataSet: Data[], callback: () => void): void;
// TODO all the other stuff
}
export interface ViewArgs {
// TODO docs
el: any;
data?: any;
hover?: boolean;
renderer?: string;
}
export interface View {
// TODO docs
width(): number;
width(w: number): View;
height(): number;
height(h: number): View;
padding(): Padding;
padding(p: Padding): View;
viewport(): number[];
viewport(v: number[]): View;
renderer(r: string): View;
data(): Runtime.DataSets;
data(d: any/*TODO*/): View;
initialize(selector: string): View;
initialize(node: Element): View;
render(r?: any[]): View;
update(options?: UpdateOptions): View;
model(): Vega.Model;
defs(): Defs;
defs(defs: Defs): View;
}
export interface Padding {
// TODO docs
top: number;
right: number;
bottom: number;
left: number;
}
export interface UpdateOptions {
// TODO docs
props?: string;
items?: any;
duration?: number;
ease?: string;
}
export interface Bounds {
x1: number;
y1: number;
x2: number;
y2: number;
clear(): Bounds;
set(x1: number, y1: number, x2: number, y2: number): Bounds;
add(x: number, y: number): Bounds;
expand(d: number): Bounds;
round(): Bounds;
translate(dx: number, dy: number): Bounds;
rotate(angle: number, x: number, y: number): Bounds;
union(b: Bounds): Bounds;
encloses(b: Bounds): boolean;
intersects(b: Bounds): boolean;
contains(x: number, y: number): boolean;
width(): number;
height(): number;
}
export interface Model {
defs(): Defs;
defs(defs: Defs): Model;
data(): Runtime.DataSets;
data(data: Runtime.DataSets): Model;
ingest(name: string, tx: any/*TODO*/, input: any/*TODO*/): void;
dependencies(name: string, tx: any/*TODO*/): void;
width(w: number): Model;
height(h: number): Model;
scene(): Node;
scene(node: Node): Model;
build(): Model;
encode(trans?: any/*TODO*/, request?: string, item?: any): Model;
reset(): Model;
}
export namespace Runtime {
export interface DataSets {
[name: string]: Datum[];
}
export interface Datum {
[key: string]: any
}
export interface Marks {
type: string;
width: number;
height: number;
scales: Scale[];
axes: Axis[];
legends: Legend[];
marks: Mark[];
}
export interface PropertySets {
enter?: Properties;
exit?: Properties;
update?: Properties;
hover?: Properties;
}
export interface Properties {
(item: Node, group: Node, trans: any/*TODO*/): void;
}
}
export interface Node {
def: Vega.Mark;
marktype: string;
interactive: boolean;
items: Node[];
bounds: Bounds;
// mark item members
hasPropertySet(name: string): boolean;
cousin(offset: number, index: number): Node;
sibling(offset: number): Node;
remove(): Node;
touch(): void;
// group members
scales?: {[name: string]: any};
axisItems?: Node[];
}
export interface Defs {
width: number;
height: number;
viewport?: number[];
padding: any;
marks: Runtime.Marks;
data: Data[];
}
export interface Spec {
/**
* A unique name for the visualization specification.
*/
name?: string;
/**
* The total width, in pixels, of the data rectangle. Default is 500 if
* undefined.
*/
width?: number;
/**
* The total height, in pixels, of the data rectangle. Default is 500 if
* undefined.
*/
height?: number;
/**
* The width and height of the on-screen viewport, in pixels. If necessary,
* clipping and scrolling will be applied.
*/
viewport?: number[];
/**
* [Number | Object | String]
* The internal padding, in pixels, from the edge of the visualization
* canvas to the data rectangle. If an object is provided, it must include
* {top, left, right, bottom} properties. Two string values are also
* acceptable: "auto" (the default) and "strict". Auto-padding computes the
* padding dynamically based on the contents of the visualization. All
* marks, including axes and legends, are used to compute the necessary
* padding. "Strict" auto-padding attempts to adjust the padding such that
* the overall width and height of the visualization is unchanged. This mode
* can cause the visualization's width and height parameters to be adjusted
* such that the total size, including padding, remains constant. Note that
* in some cases strict padding is not possible; for example, if the axis
* labels are much larger than the data rectangle.
*/
padding?: number | string | {
top: number; left: number; right: number; bottom: number
}; // string is "auto" or "strict"
/**
* Definitions of data to visualize.
*/
data: Data[];
/**
* Scale transform definitions.
*/
scales?: Scale[];
/**
* Axis definitions.
*/
axes?: Axis[];
/**
* Legend definitions.
*/
legends?: Legend[];
/**
* Graphical mark definitions.
*/
marks: (Mark | GroupMark)[];
}
export interface Data {
/**
* A unique name for the data set.
*/
name: string;
/**
* An object that specifies the format for the data file, if loaded from a
* URL.
*/
format?: Data.Format;
/**
* The actual data set to use. The values property allows data to be inlined
* directly within the specification itself.
*/
values?: any;
/**
* The name of another data set to use as the source for this data set. The
* source property is particularly useful in combination with a transform
* pipeline to derive new data.
*/
source?: string;
/**
* A URL from which to load the data set. Use the format property to ensure
* the loaded data is correctly parsed. If the format property is not specified,
* the data is assumed to be in a row-oriented JSON format.
*/
url?: string;
/**
* An array of transforms to perform on the data. Transform operators will be
* run on the default data, as provided by late-binding or as specified by the
* source, values, or url properties.
*/
transform?: Data.Transform[];
}
export namespace Data {
export interface FormatBase {
/**
* The currently supported format types are json (JavaScript Object
* Notation), csv (comma-separated values), tsv (tab-separated values),
* topojson, and treejson.
*/
type: string;
// TODO: fields for specific formats
}
/**
* The JSON property containing the desired data.
* This parameter can be used when the loaded JSON file may have surrounding structure or meta-data.
* For example "property": "values.features" is equivalent to retrieving json.values.features from the
* loaded JSON object.
*/
export interface JsonFormat extends FormatBase {
type: string; // "json"
property?: string;
}
export interface CsvOrTsvFormat extends FormatBase {
type: string; // "csv" | "tsv"
parse?: {
[propertyName: string]: string; // "number" | "boolean" | "date"
}
}
export interface TopoJsonFormat extends FormatBase {
type: string; // "topojson"
feature?: string;
mesh?: string;
}
export interface TreeJson extends FormatBase {
type: string; // "treejson"
children?: string;
parse?: {
[propertyName: string]: string; // "number" | "boolean" | "date"
}
}
export type Format = JsonFormat | CsvOrTsvFormat | TopoJsonFormat | TreeJson;
export interface Transform {
// TODO
}
}
export interface Scale {
// TODO docs
// -- Common scale properties
name?: string;
type?: string;
domain?: any;
domainMin?: any;
domainMax?: any;
range?: any;
rangeMin?: any;
rangeMax?: any;
reverse?: boolean;
round?: boolean;
// -- Ordinal scale properties
points?: boolean;
padding?: number;
sort?: boolean;
// -- Time/Quantitative scale properties
clamp?: boolean;
/** boolean for quantitative scales, string for time scales */
nice?: boolean | string;
// -- Quantitative scale properties
exponent?: number;
zero?: boolean;
}
export interface Axis {
// TODO docs
type: string;
scale: string;
orient?: string;
title?: string;
titleOffset?: number;
format?: string;
ticks?: number;
values?: any[];
subdivide?: number;
tickPadding?: number;
tickSize?: number;
tickSizeMajor?: number;
tickSizeMinor?: number;
tickSizeEnd?: number;
offset?: any;
layer?: string;
grid?: boolean;
properties?: Axis.Properties
}
export namespace Axis {
export interface Properties {
ticks?: PropertySet;
minorTicks?: PropertySet;
grid?: PropertySet;
labels?: PropertySet;
title?: PropertySet;
axis?: PropertySet;
}
}
export interface Legend {
// TODO
}
export interface Mark {
// TODO docs
// Stuff from Spec.Mark
type: string; // "rect" | "symbol" | "path" | "arc" | "area" | "line" | "rule" | "image" | "text" | "group"
name?: string;
description?: string;
from?: Mark.From;
key?: string;
delay?: ValueRef;
/**
* "linear-in" | "linear-out" | "linear-in-out" | "linear-out-in" | "quad-in" | "quad-out" | "quad-in-out" |
* "quad-out-in" | "cubic-in" | "cubic-out" | "cubic-in-out" | "cubic-out-in" | "sin-in" | "sin-out" | "sin-in-out" |
* "sin-out-in" | "exp-in" | "exp-out" | "exp-in-out" | "exp-out-in" | "circle-in" | "circle-out" | "circle-in-out" |
* "circle-out-in" | "bounce-in" | "bounce-out" | "bounce-in-out" | "bounce-out-in"
*/
ease?: string;
interactive?: boolean;
// Runtime PropertySets
properties?: PropertySets;
}
export module Mark {
export interface From {
// TODO docs
data?: string;
mark?: string;
transform?: Data.Transform[];
}
}
export interface GroupMark extends Mark {
type: string; // "group"
/**
* Scale transform definitions.
*/
scales?: Scale[];
/**
* Axis definitions.
*/
axes?: Axis[];
/**
* Legend definitions.
*/
legends?: Legend[];
/**
* Groups differ from other mark types in their ability to contain children marks.
* Marks defined within a group mark can inherit data from their parent group.
* For inheritance to work each data element for a group must contain data elements of its own.
* This arrangement of nested data is typically achieved by facetting the data, such that each group-level data element includes its own array of sub-elements
*/
marks?: (Mark | GroupMark)[];
}
export interface PropertySets {
// TODO docs
enter?: PropertySet;
exit?: PropertySet;
update?: PropertySet;
hover?: PropertySet;
}
export interface PropertySet {
// TODO docs
// -- Shared visual properties
x?: ValueRef;
x2?: ValueRef;
width?: ValueRef;
y?: ValueRef;
y2?: ValueRef;
height?: ValueRef;
opacity?: ValueRef;
fill?: ValueRef;
fillOpacity?: ValueRef;
stroke?: ValueRef;
strokeWidth?: ValueRef;
strokeOpacity?: ValueRef;
strokeDash?: ValueRef;
strokeDashOffset?: ValueRef;
// -- symbol
size?: ValueRef;
shape?: ValueRef;
// -- path
path?: ValueRef;
// -- arc
innerRadius?: ValueRef;
outerRadius?: ValueRef;
startAngle?: ValueRef;
endAngle?: ValueRef;
// -- area / line
interpolate?: ValueRef;
tension?: ValueRef;
// -- image / text
align?: ValueRef;
baseline?: ValueRef;
// -- image
url?: ValueRef;
// -- text
text?: ValueRef;
dx?: ValueRef;
dy?: ValueRef;
angle?: ValueRef;
font?: ValueRef;
fontSize?: ValueRef;
fontWeight?: ValueRef;
fontStyle?: ValueRef;
}
export interface ValueRef {
// TODO docs
value?: any;
field?: any;
group?: any;
scale?: any;
mult?: number;
offset?: number;
band?: boolean;
}
}
declare namespace vg {
export var parse: Vega.Parse;
export namespace scene {
export function item(mark: Vega.Node): Vega.Node;
}
export class Bounds implements Vega.Bounds {
x1: number;
y1: number;
x2: number;
y2: number;
clear(): Bounds;
set(x1: number, y1: number, x2: number, y2: number): Bounds;
add(x: number, y: number): Bounds;
expand(d: number): Bounds;
round(): Bounds;
translate(dx: number, dy: number): Bounds;
rotate(angle: number, x: number, y: number): Bounds;
union(b: Bounds): Bounds;
encloses(b: Bounds): boolean;
intersects(b: Bounds): boolean;
contains(x: number, y: number): boolean;
width(): number;
height(): number;
}
// TODO: classes for View, Model, etc.
}
|
vega/vega.d.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00278483796864748,
0.00031583887175656855,
0.0001638462272239849,
0.00023082738334778696,
0.00035953911719843745
] |
{
"id": 3,
"code_window": [
" * @example\n",
" * var p = polylabel(polygon, 1.0);\n",
" */\n",
" function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" export = polylabel;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" namespace polylabel {}\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 30
}
|
jasmine-ajax/jasmine-ajax-tests.ts.tscparams
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00018073747924063355,
0.00018073747924063355,
0.00018073747924063355,
0.00018073747924063355,
0
] |
|
{
"id": 3,
"code_window": [
" * @example\n",
" * var p = polylabel(polygon, 1.0);\n",
" */\n",
" function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" export = polylabel;\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[];\n",
" namespace polylabel {}\n"
],
"file_path": "polylabel/polylabel.d.ts",
"type": "replace",
"edit_start_line_idx": 30
}
|
/// <reference path="escodegen.d.ts" />
import * as escodegen from 'escodegen';
let emptyIndentOptions: escodegen.IndentOptions = {};
let indentOptions: escodegen.IndentOptions = {
style: ' ',
base: 0,
adjustMultilineComment: true
};
let emptyFormatOptions: escodegen.FormatOptions = {};
let formatOptions: escodegen.FormatOptions = {
indent: indentOptions,
newline: '\n',
space: ' ',
json: true,
renumber: true,
hexadecimal: true,
quotes: 'single',
escapeless: true,
compact: true,
parentheses: true,
semicolons: true,
safeConcatenation: true,
preserveBlankLines: true
}
let emptyMozillaOptions: escodegen.MozillaOptions = {};
let mozillaOptions: escodegen.MozillaOptions = {
starlessGenerator: true,
parenthesizedComprehensionBlock: true,
comprehensionExpressionStartsWithAssignment: true
}
let emptyGenerateOptions: escodegen.GenerateOptions = {};
let generateOptions: escodegen.GenerateOptions = {
format: formatOptions,
moz: mozillaOptions,
parse: () => {},
comment: true,
sourceMap: " ",
sourceMapWithCode: true,
sourceContent: " ",
sourceCode: " ",
sourceMapRoot: " ",
directive: true,
file: " ",
verbatim: " "
};
let precedence: escodegen.Precedence = escodegen.Precedence.Primary;
let myCode: string = escodegen.generate({}, generateOptions);
let ast: any = escodegen.attachComments({}, {}, {});
|
escodegen/escodegen-tests.ts
| 0 |
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/c0ce167c104f2224111c87fb81c8be5c530916ba
|
[
0.00018031935906037688,
0.00017484917771071196,
0.00016806632629595697,
0.00017525684961583465,
0.000003838965767499758
] |
{
"id": 0,
"code_window": [
" getArgs?: (call: Call, state: State) => Call['args'];\n",
"}\n",
"\n",
"export interface State {\n",
" renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';\n",
" isDebugging: boolean;\n",
" cursor: number;\n",
" calls: Call[];\n",
" shadowCalls: Call[];\n",
" callRefsByResult: Map<any, CallRef & { retain: boolean }>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" renderPhase: 'loading' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
/* eslint-disable no-underscore-dangle */
import { addons, Channel, StoryId } from '@storybook/addons';
import { once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, LogItem } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
LOCK: 'instrumenter/lock',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
export interface Options {
intercept?: boolean | ((method: string, path: Array<string | CallRef>) => boolean);
retain?: boolean;
mutate?: boolean;
path?: Array<string | CallRef>;
getArgs?: (call: Call, state: State) => Call['args'];
}
export interface State {
renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';
isDebugging: boolean;
cursor: number;
calls: Call[];
shadowCalls: Call[];
callRefsByResult: Map<any, CallRef & { retain: boolean }>;
chainedCallIds: Set<Call['id']>;
parentCall?: Call;
playUntil?: Call['id'];
resolvers: Record<Call['id'], Function>;
syncTimeout: ReturnType<typeof setTimeout>;
forwardedException?: Error;
}
export type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentCall: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
forwardedException: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({ storyId, isDebugging }: { storyId?: StoryId; isDebugging?: boolean }) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.channel.emit(EVENTS.SYNC, this.getLog(storyId));
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging, forwardedException } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'completed') {
this.setState(storyId, { isDebugging: false, forwardedException: undefined });
// Rethrow any unhandled forwarded exception so it doesn't go unnoticed.
if (forwardedException) throw forwardedException;
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, state: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const { isDebugging } = this.getState(storyId);
const log = this.getLog(storyId);
const next = isDebugging
? log.findIndex(({ state }) => state === CallStates.WAITING)
: log.length;
start({ storyId, playUntil: log[next - 2]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall) {
const nextCallId = this.getLog(storyId).find(({ state }) => state === CallStates.WAITING)
?.callId;
if (shadowCall.id !== nextCallId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, []);
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if (call.interceptable && !seen.has(call.id) && !seen.has(call.parentId)) {
acc.unshift({ callId: call.id, state: call.state });
seen.add(call.id);
if (call.parentId) {
seen.add(call.parentId);
}
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const index = this.getState(storyId).cursor;
this.setState(storyId, { cursor: index + 1 });
const id = `${storyId} [${index}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, path, method, storyId, args, interceptable, retain };
const result = (interceptable ? this.intercept : this.invoke).call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.channel.emit(EVENTS.LOCK, false);
this.setState(call.storyId, ({ resolvers }) => ({
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.channel.emit(EVENTS.LOCK, true);
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { parentCall, callRefsByResult, forwardedException, renderPhase } = this.getState(
call.storyId
);
const callWithParent = { ...call, parentId: parentCall?.id };
const info: Call = {
...callWithParent,
// Map args that originate from a tracked function call to a call reference to enable nesting.
// These values are often not fully serializable anyway (e.g. HTML elements).
args: call.args.map((arg) => {
if (callRefsByResult.has(arg)) {
return callRefsByResult.get(arg);
}
if (arg instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = arg;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
return arg;
}),
};
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: unknown) => {
if (e instanceof Error) {
const { name, message, stack } = e;
const exception = { name, message, stack, callId: call.id };
this.sync({ ...info, state: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (call.interceptable && e !== alreadyCompletedException) {
throw IGNORED_EXCEPTION;
}
// Non-interceptable calls need their exceptions forwarded to the next interceptable call.
// In case no interceptable call picks it up, it'll get rethrown in the "completed" phase.
this.setState(call.storyId, { forwardedException: e });
return e;
}
throw e;
};
try {
// An earlier, non-interceptable call might have forwarded an exception.
if (forwardedException) {
this.setState(call.storyId, { forwardedException: undefined });
throw forwardedException;
}
if (renderPhase === 'completed' && !call.retain) {
throw alreadyCompletedException;
}
const finalArgs = options.getArgs
? options.getArgs(callWithParent, this.getState(call.storyId))
: call.args;
const result = fn(
// Wrap any callback functions to provide a way to access their "parent" call.
...finalArgs.map((arg: any) => {
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
const prev = this.getState(call.storyId).parentCall;
this.setState(call.storyId, { parentCall: call });
const res = arg(...args);
this.setState(call.storyId, { parentCall: prev });
return res;
};
})
);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.sync({
...info,
state: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.sync({ ...info, state: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
sync(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => ({
calls: calls.concat(call),
syncTimeout: setTimeout(() => this.channel.emit(EVENTS.SYNC, this.getLog(call.storyId)), 0),
}));
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe.
if (global.window.parent === global.window) return obj;
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}
|
lib/instrumenter/src/instrumenter.ts
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.9990363121032715,
0.649284303188324,
0.00016325317847076803,
0.9907293915748596,
0.465118944644928
] |
{
"id": 0,
"code_window": [
" getArgs?: (call: Call, state: State) => Call['args'];\n",
"}\n",
"\n",
"export interface State {\n",
" renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';\n",
" isDebugging: boolean;\n",
" cursor: number;\n",
" calls: Call[];\n",
" shadowCalls: Call[];\n",
" callRefsByResult: Map<any, CallRef & { retain: boolean }>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" renderPhase: 'loading' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
export default {
title: 'Foo|Bar/baz.whatever',
};
|
lib/codemod/src/transforms/__testfixtures__/upgrade-hierarchy-separators/csf.input.js
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001664241135586053,
0.0001664241135586053,
0.0001664241135586053,
0.0001664241135586053,
0
] |
{
"id": 0,
"code_window": [
" getArgs?: (call: Call, state: State) => Call['args'];\n",
"}\n",
"\n",
"export interface State {\n",
" renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';\n",
" isDebugging: boolean;\n",
" cursor: number;\n",
" calls: Call[];\n",
" shadowCalls: Call[];\n",
" callRefsByResult: Map<any, CallRef & { retain: boolean }>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" renderPhase: 'loading' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
import React from 'react';
import PropTypes from 'prop-types';
// eslint-disable-next-line react/prefer-stateless-function
export default class Test extends React.Component {
static propTypes = {
/**
* Please work...
*/
test: PropTypes.string,
};
render() {
return <div>test</div>;
}
}
export const component = Test;
|
addons/docs/src/frameworks/react/__testfixtures__/8428-js-static-prop-types/input.js
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00021293647296261042,
0.00019219823298044503,
0.00017145999299827963,
0.00019219823298044503,
0.000020738239982165396
] |
{
"id": 0,
"code_window": [
" getArgs?: (call: Call, state: State) => Call['args'];\n",
"}\n",
"\n",
"export interface State {\n",
" renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';\n",
" isDebugging: boolean;\n",
" cursor: number;\n",
" calls: Call[];\n",
" shadowCalls: Call[];\n",
" callRefsByResult: Map<any, CallRef & { retain: boolean }>;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" renderPhase: 'loading' | 'rendering' | 'playing' | 'played' | 'completed' | 'aborted' | 'errored';\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 33
}
|
```ts
// ButtonGroup.stories.ts | ButtonGroup.stories.tsx
import React from 'react';
import { Story, Meta } from '@storybook/react';
import { ButtonGroup, ButtonGroupProps } from '../ButtonGroup';
//👇 Imports the Button stories
import * as ButtonStories from './Button.stories';
export default {
title: 'ButtonGroup',
component: ButtonGroup,
} as Meta;
const Template: Story<ButtonGroupProps> = (args) => <ButtonGroup {...args} />;
export const Pair = Template.bind({});
Pair.args = {
buttons: [{ ...ButtonStories.Primary.args }, { ...ButtonStories.Secondary.args }],
orientation: 'horizontal',
};
```
|
docs/snippets/react/button-group-story.ts.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00018988826195709407,
0.00017807225231081247,
0.00017208437202498317,
0.00017224409384652972,
0.000008355441423191223
] |
{
"id": 1,
"code_window": [
" if (newPhase === 'playing') {\n",
" resetState({ storyId, isDebugging });\n",
" }\n",
" if (newPhase === 'completed') {\n",
" this.setState(storyId, { isDebugging: false, forwardedException: undefined });\n",
" // Rethrow any unhandled forwarded exception so it doesn't go unnoticed.\n",
" if (forwardedException) throw forwardedException;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (newPhase === 'played') {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 141
}
|
import deprecate from 'util-deprecate';
import dedent from 'ts-dedent';
import global from 'global';
import { SynchronousPromise } from 'synchronous-promise';
import Events, { IGNORED_EXCEPTION } from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import { addons, Channel } from '@storybook/addons';
import {
AnyFramework,
StoryId,
ProjectAnnotations,
Args,
Globals,
ViewMode,
StoryContextForLoaders,
StoryContext,
} from '@storybook/csf';
import {
ModuleImportFn,
Selection,
Story,
RenderContext,
CSFFile,
StoryStore,
StorySpecifier,
StoryIndex,
} from '@storybook/store';
import { WebProjectAnnotations } from './types';
import { UrlStore } from './UrlStore';
import { WebView } from './WebView';
const { window: globalWindow, AbortController, FEATURES, fetch } = global;
function focusInInput(event: Event) {
const target = event.target as Element;
return /input|textarea/i.test(target.tagName) || target.getAttribute('contenteditable') !== null;
}
function createController(): AbortController {
if (AbortController) return new AbortController();
// Polyfill for IE11
return {
signal: { aborted: false },
abort() {
this.signal.aborted = true;
},
} as AbortController;
}
export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';
type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;
type MaybePromise<T> = Promise<T> | T;
type StoryCleanupFn = () => MaybePromise<void>;
const STORY_INDEX_PATH = './stories.json';
export class PreviewWeb<TFramework extends AnyFramework> {
channel: Channel;
serverChannel?: Channel;
urlStore: UrlStore;
storyStore: StoryStore<TFramework>;
view: WebView;
renderToDOM: WebProjectAnnotations<TFramework>['renderToDOM'];
previousSelection: Selection;
previousStory: Story<TFramework>;
previousCleanup: StoryCleanupFn;
abortSignal: AbortSignal;
constructor() {
this.channel = addons.getChannel();
if (FEATURES?.storyStoreV7) {
this.serverChannel = addons.getServerChannel();
}
this.view = new WebView();
this.urlStore = new UrlStore();
this.storyStore = new StoryStore();
// Add deprecated APIs for back-compat
// @ts-ignore
this.storyStore.getSelection = deprecate(
() => this.urlStore.selection,
dedent`
\`__STORYBOOK_STORY_STORE__.getSelection()\` is deprecated and will be removed in 7.0.
To get the current selection, use the \`useStoryContext()\` hook from \`@storybook/addons\`.
`
);
}
// NOTE: the reason that the preview and store's initialization code is written in a promise
// style and not `async-await`, and the use of `SynchronousPromise`s is in order to allow
// storyshots to immediately call `raw()` on the store without waiting for a later tick.
// (Even simple things like `Promise.resolve()` and `await` involve the callback happening
// in the next promise "tick").
// See the comment in `storyshots-core/src/api/index.ts` for more detail.
initialize({
getStoryIndex,
importFn,
getProjectAnnotations,
}: {
// In the case of the v6 store, we can only get the index from the facade *after*
// getProjectAnnotations has been run, thus this slightly awkward approach
getStoryIndex?: () => StoryIndex;
importFn: ModuleImportFn;
getProjectAnnotations: () => MaybePromise<WebProjectAnnotations<TFramework>>;
}): PromiseLike<void> {
return this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(
(projectAnnotations) => {
this.storyStore.setProjectAnnotations(projectAnnotations);
this.setupListeners();
let storyIndexPromise: PromiseLike<StoryIndex>;
if (FEATURES?.storyStoreV7) {
storyIndexPromise = this.getStoryIndexFromServer();
} else {
if (!getStoryIndex) {
throw new Error('No `getStoryIndex` passed defined in v6 mode');
}
storyIndexPromise = SynchronousPromise.resolve().then(getStoryIndex);
}
return storyIndexPromise
.then((storyIndex: StoryIndex) => {
return this.storyStore
.initialize({
storyIndex,
importFn,
cache: !FEATURES?.storyStoreV7,
})
.then(() => {
if (!FEATURES?.storyStoreV7) {
this.channel.emit(Events.SET_STORIES, this.storyStore.getSetStoriesPayload());
}
this.setGlobalsAndRenderSelection();
});
})
.catch((err) => {
logger.warn(err);
this.renderPreviewEntryError(err);
});
}
);
}
getProjectAnnotationsOrRenderError(
getProjectAnnotations: () => MaybePromise<WebProjectAnnotations<TFramework>>
): PromiseLike<ProjectAnnotations<TFramework>> {
return SynchronousPromise.resolve()
.then(() => getProjectAnnotations())
.then((projectAnnotations) => {
this.renderToDOM = projectAnnotations.renderToDOM;
if (!this.renderToDOM) {
throw new Error(dedent`
Expected 'framework' in your main.js to export 'renderToDOM', but none found.
You can fix this automatically by running:
npx sb@next automigrate
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
`);
}
return projectAnnotations;
})
.catch((err) => {
logger.warn(err);
// This is an error extracting the projectAnnotations (i.e. evaluating the previewEntries) and
// needs to be show to the user as a simple error
this.renderPreviewEntryError(err);
return {};
});
}
setupListeners() {
globalWindow.onkeydown = this.onKeydown.bind(this);
this.serverChannel?.on(Events.STORY_INDEX_INVALIDATED, this.onStoryIndexChanged.bind(this));
this.channel.on(Events.SET_CURRENT_STORY, this.onSetCurrentStory.bind(this));
this.channel.on(Events.UPDATE_QUERY_PARAMS, this.onUpdateQueryParams.bind(this));
this.channel.on(Events.UPDATE_GLOBALS, this.onUpdateGlobals.bind(this));
this.channel.on(Events.UPDATE_STORY_ARGS, this.onUpdateArgs.bind(this));
this.channel.on(Events.RESET_STORY_ARGS, this.onResetArgs.bind(this));
}
async setGlobalsAndRenderSelection() {
const { globals } = this.urlStore.selectionSpecifier || {};
if (globals) {
this.storyStore.globals.updateFromPersisted(globals);
}
this.channel.emit(Events.SET_GLOBALS, {
globals: this.storyStore.globals.get() || {},
globalTypes: this.storyStore.projectAnnotations.globalTypes || {},
});
return this.selectSpecifiedStory();
}
// Use the selection specifier to choose a story, then render it
async selectSpecifiedStory() {
if (!this.urlStore.selectionSpecifier) {
await this.renderMissingStory();
return;
}
const { storySpecifier, viewMode, args } = this.urlStore.selectionSpecifier;
const storyId = this.storyStore.storyIndex.storyIdFromSpecifier(storySpecifier);
if (!storyId) {
await this.renderMissingStory(storySpecifier);
return;
}
this.urlStore.setSelection({ storyId, viewMode });
this.channel.emit(Events.STORY_SPECIFIED, this.urlStore.selection);
this.channel.emit(Events.CURRENT_STORY_WAS_SET, this.urlStore.selection);
await this.renderSelection({ persistedArgs: args });
}
onKeydown(event: KeyboardEvent) {
if (!focusInInput(event)) {
// We have to pick off the keys of the event that we need on the other side
const { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode } = event;
this.channel.emit(Events.PREVIEW_KEYDOWN, {
event: { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode },
});
}
}
onSetCurrentStory(selection: Selection) {
this.urlStore.setSelection(selection);
this.channel.emit(Events.CURRENT_STORY_WAS_SET, this.urlStore.selection);
this.renderSelection();
}
onUpdateQueryParams(queryParams: any) {
this.urlStore.setQueryParams(queryParams);
}
onUpdateGlobals({ globals }: { globals: Globals }) {
this.storyStore.globals.update(globals);
this.channel.emit(Events.GLOBALS_UPDATED, {
globals: this.storyStore.globals.get(),
initialGlobals: this.storyStore.globals.initialGlobals,
});
}
onUpdateArgs({ storyId, updatedArgs }: { storyId: StoryId; updatedArgs: Args }) {
this.storyStore.args.update(storyId, updatedArgs);
this.channel.emit(Events.STORY_ARGS_UPDATED, {
storyId,
args: this.storyStore.args.get(storyId),
});
}
async onResetArgs({ storyId, argNames }: { storyId: string; argNames?: string[] }) {
// NOTE: we have to be careful here and avoid await-ing when updating the current story's args.
// That's because below in `renderStoryToElement` we have also bound to this event and will
// render the story in the same tick.
// However, we can do that safely as the current story is available in `this.previousStory`
const { initialArgs } =
storyId === this.previousStory.id
? this.previousStory
: await this.storyStore.loadStory({ storyId });
const argNamesToReset = argNames || Object.keys(this.storyStore.args.get(storyId));
const updatedArgs = argNamesToReset.reduce((acc, argName) => {
acc[argName] = initialArgs[argName];
return acc;
}, {} as Partial<Args>);
this.onUpdateArgs({ storyId, updatedArgs });
}
async onStoryIndexChanged() {
const storyIndex = await this.getStoryIndexFromServer();
return this.onStoriesChanged({ storyIndex });
}
// This happens when a glob gets HMR-ed
async onStoriesChanged({
importFn,
storyIndex,
}: {
importFn?: ModuleImportFn;
storyIndex?: StoryIndex;
}) {
await this.storyStore.onStoriesChanged({ importFn, storyIndex });
if (this.urlStore.selection) {
await this.renderSelection();
} else {
await this.selectSpecifiedStory();
}
if (!FEATURES?.storyStoreV7) {
this.channel.emit(Events.SET_STORIES, await this.storyStore.getSetStoriesPayload());
}
}
// This happens when a config file gets reloade
async onGetProjectAnnotationsChanged({
getProjectAnnotations,
}: {
getProjectAnnotations: () => MaybePromise<ProjectAnnotations<TFramework>>;
}) {
const projectAnnotations = await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);
if (!projectAnnotations) {
return;
}
this.storyStore.setProjectAnnotations(projectAnnotations);
this.renderSelection();
}
async getStoryIndexFromServer() {
const result = await fetch(STORY_INDEX_PATH);
if (result.status === 200) return result.json() as StoryIndex;
throw new Error(await result.text());
}
// We can either have:
// - a story selected in "story" viewMode,
// in which case we render it to the root element, OR
// - a story selected in "docs" viewMode,
// in which case we render the docsPage for that story
async renderSelection({ persistedArgs }: { persistedArgs?: Args } = {}) {
if (!this.urlStore.selection) {
throw new Error('Cannot render story as no selection was made');
}
const {
selection,
selection: { storyId },
} = this.urlStore;
let story;
try {
story = await this.storyStore.loadStory({ storyId });
} catch (err) {
this.previousStory = null;
logger.warn(err);
await this.renderMissingStory(storyId);
return;
}
const storyIdChanged = this.previousSelection?.storyId !== storyId;
const viewModeChanged = this.previousSelection?.viewMode !== selection.viewMode;
const implementationChanged =
!storyIdChanged && this.previousStory && story !== this.previousStory;
if (persistedArgs) {
this.storyStore.args.updateFromPersisted(story, persistedArgs);
}
// Don't re-render the story if nothing has changed to justify it
if (this.previousStory && !storyIdChanged && !implementationChanged && !viewModeChanged) {
this.channel.emit(Events.STORY_UNCHANGED, storyId);
return;
}
await this.cleanupPreviousRender({ unmountDocs: viewModeChanged });
// If we are rendering something new (as opposed to re-rendering the same or first story), emit
if (this.previousSelection && (storyIdChanged || viewModeChanged)) {
this.channel.emit(Events.STORY_CHANGED, storyId);
}
// Record the previous selection *before* awaiting the rendering, in cases things change before it is done.
this.previousSelection = selection;
this.previousStory = story;
const { parameters, initialArgs, argTypes, args } = this.storyStore.getStoryContext(story);
if (FEATURES?.storyStoreV7) {
this.channel.emit(Events.STORY_PREPARED, {
id: storyId,
parameters,
initialArgs,
argTypes,
args,
});
}
// If the implementation changed, the args also may have changed
if (implementationChanged) {
this.channel.emit(Events.STORY_ARGS_UPDATED, { storyId, args });
}
if (selection.viewMode === 'docs' || story.parameters.docsOnly) {
this.previousCleanup = await this.renderDocs({ story });
} else {
this.previousCleanup = this.renderStory({ story });
}
}
async renderDocs({ story }: { story: Story<TFramework> }) {
const { id, title, name } = story;
const element = this.view.prepareForDocs();
const csfFile: CSFFile<TFramework> = await this.storyStore.loadCSFFileByStoryId(id);
const docsContext = {
id,
title,
name,
// NOTE: these two functions are *sync* so cannot access stories from other CSF files
storyById: (storyId: StoryId) => this.storyStore.storyFromCSFFile({ storyId, csfFile }),
componentStories: () => this.storyStore.componentStoriesFromCSFFile({ csfFile }),
loadStory: (storyId: StoryId) => this.storyStore.loadStory({ storyId }),
renderStoryToElement: this.renderStoryToElement.bind(this),
getStoryContext: (renderedStory: Story<TFramework>) =>
({
...this.storyStore.getStoryContext(renderedStory),
viewMode: 'docs' as ViewMode,
} as StoryContextForLoaders<TFramework>),
};
const render = async () => {
const fullDocsContext = {
...docsContext,
// Put all the storyContext fields onto the docs context for back-compat
...(!FEATURES?.breakingChangesV7 && this.storyStore.getStoryContext(story)),
};
(await import('./renderDocs')).renderDocs(story, fullDocsContext, element, () =>
this.channel.emit(Events.DOCS_RENDERED, id)
);
};
// Initially render right away
render();
// Listen to events and re-render
// NOTE: we aren't checking to see the story args are targetted at the "right" story.
// This is because we may render >1 story on the page and there is no easy way to keep track
// of which ones were rendered by the docs page.
// However, in `modernInlineRender`, the individual stories track their own events as they
// each call `renderStoryToElement` below.
if (!global?.FEATURES?.modernInlineRender) {
this.channel.on(Events.UPDATE_GLOBALS, render);
this.channel.on(Events.UPDATE_STORY_ARGS, render);
this.channel.on(Events.RESET_STORY_ARGS, render);
}
return async () => {
if (!global?.FEATURES?.modernInlineRender) {
this.channel.off(Events.UPDATE_GLOBALS, render);
this.channel.off(Events.UPDATE_STORY_ARGS, render);
this.channel.off(Events.RESET_STORY_ARGS, render);
}
};
}
renderStory({ story }: { story: Story<TFramework> }) {
const element = this.view.prepareForStory(story);
const { id, componentId, title, name } = story;
const renderContext = {
componentId,
title,
kind: title,
id,
name,
story: name,
showMain: () => this.view.showMain(),
showError: (err: { title: string; description: string }) => this.renderError(id, err),
showException: (err: Error) => this.renderException(id, err),
};
return this.renderStoryToElement({ story, renderContext, element });
}
// Render a story into a given element and watch for the events that would trigger us
// to re-render it (plus deal sensibly with things like changing story mid-way through).
renderStoryToElement({
story,
renderContext: renderContextWithoutStoryContext,
element,
}: {
story: Story<TFramework>;
renderContext: Omit<
RenderContext<TFramework>,
'storyContext' | 'storyFn' | 'unboundStoryFn' | 'forceRemount'
>;
element: HTMLElement;
}): StoryCleanupFn {
const { id, applyLoaders, unboundStoryFn, playFunction } = story;
let phase: RenderPhase;
const isPending = () => ['rendering', 'playing'].includes(phase);
let controller: AbortController;
let notYetRendered = true;
const render = async ({ forceRemount = false } = {}) => {
let ctrl = controller; // we also need a stable reference within this closure
// Abort the signal used by the previous render, so it'll (hopefully) stop executing. The
// play function might continue execution regardless, which we deal with during cleanup.
// Note we can't reload the page here because there's a legitimate use case for forceRemount
// while in the 'playing' phase: the play function may never resolve during debugging, while
// "step back" will trigger a forceRemount. In this case it's up to the debugger to reload.
if (ctrl) ctrl.abort();
ctrl = createController();
controller = ctrl;
this.abortSignal = controller.signal;
const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {
phase = phaseName;
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });
await phaseFn();
if (ctrl.signal.aborted) {
phase = 'aborted';
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });
}
};
try {
let loadedContext: StoryContext<TFramework>;
await runPhase('loading', async () => {
loadedContext = await applyLoaders({
...this.storyStore.getStoryContext(story),
viewMode: element === this.view.storyRoot() ? 'story' : 'docs',
} as StoryContextForLoaders<TFramework>);
});
if (ctrl.signal.aborted) return;
const renderStoryContext: StoryContext<TFramework> = {
...loadedContext,
// By this stage, it is possible that new args/globals have been received for this story
// and we need to ensure we render it with the new values
...this.storyStore.getStoryContext(story),
abortSignal: ctrl.signal,
canvasElement: element,
};
const renderContext: RenderContext<TFramework> = {
...renderContextWithoutStoryContext,
forceRemount: forceRemount || notYetRendered,
storyContext: renderStoryContext,
storyFn: () => unboundStoryFn(renderStoryContext),
unboundStoryFn,
};
await runPhase('rendering', () => this.renderToDOM(renderContext, element));
notYetRendered = false;
if (ctrl.signal.aborted) return;
if (forceRemount && playFunction) {
await runPhase('playing', () => playFunction(renderContext.storyContext));
if (ctrl.signal.aborted) return;
}
await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));
} catch (err) {
renderContextWithoutStoryContext.showException(err);
}
};
// Start the first (initial) render. We don't await here because we need to return the "cleanup"
// function below right away, so if the user changes story during the first render we can cancel
// it without having to first wait for it to finish.
// Whenever the selection changes we want to force the component to be remounted.
render({ forceRemount: true });
const remountStoryIfMatches = ({ storyId }: { storyId: StoryId }) => {
if (storyId === story.id) render({ forceRemount: true });
};
const rerenderStoryIfMatches = ({ storyId }: { storyId: StoryId }) => {
if (storyId === story.id) render();
};
// Listen to events and re-render story
// Don't forget to unsubscribe on cleanup
this.channel.on(Events.UPDATE_GLOBALS, render);
this.channel.on(Events.FORCE_RE_RENDER, render);
this.channel.on(Events.FORCE_REMOUNT, remountStoryIfMatches);
this.channel.on(Events.UPDATE_STORY_ARGS, rerenderStoryIfMatches);
this.channel.on(Events.RESET_STORY_ARGS, rerenderStoryIfMatches);
// Cleanup / teardown function invoked on next render (via `cleanupPreviousRender`)
return async () => {
// If the story is torn down (either a new story is rendered or the docs page removes it)
// we need to consider the fact that the initial render may not be finished
// (possibly the loaders or the play function are still running). We use the controller
// as a method to abort them, ASAP, but this is not foolproof as we cannot control what
// happens inside the user's code.
controller.abort();
this.storyStore.cleanupStory(story);
this.channel.off(Events.UPDATE_GLOBALS, render);
this.channel.off(Events.FORCE_RE_RENDER, render);
this.channel.off(Events.FORCE_REMOUNT, remountStoryIfMatches);
this.channel.off(Events.UPDATE_STORY_ARGS, rerenderStoryIfMatches);
this.channel.off(Events.RESET_STORY_ARGS, rerenderStoryIfMatches);
// Check if we're done rendering/playing. If not, we may have to reload the page.
if (!isPending()) return;
// Wait several ticks that may be needed to handle the abort, then try again.
// Note that there's a max of 5 nested timeouts before they're no longer "instant".
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
// If we still haven't completed, reload the page (iframe) to ensure we have a clean slate
// for the next render. Since the reload can take a brief moment to happen, we want to stop
// further rendering by awaiting a never-resolving promise (which is destroyed on reload).
global.window.location.reload();
await new Promise(() => {});
};
}
async cleanupPreviousRender({ unmountDocs = true }: { unmountDocs?: boolean } = {}) {
const previousViewMode = this.previousStory?.parameters?.docsOnly
? 'docs'
: this.previousSelection?.viewMode;
if (unmountDocs && previousViewMode === 'docs') {
(await import('./renderDocs')).unmountDocs(this.view.docsRoot());
}
if (this.previousCleanup) {
await this.previousCleanup();
}
}
renderPreviewEntryError(err: Error) {
this.view.showErrorDisplay(err);
this.channel.emit(Events.CONFIG_ERROR, err);
}
async renderMissingStory(storySpecifier?: StorySpecifier) {
await this.cleanupPreviousRender();
this.view.showNoPreview();
this.channel.emit(Events.STORY_MISSING, storySpecifier);
}
// renderException is used if we fail to render the story and it is uncaught by the app layer
renderException(storyId: StoryId, error: Error) {
this.channel.emit(Events.STORY_THREW_EXCEPTION, error);
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: 'errored', storyId });
// Ignored exceptions exist for control flow purposes, and are typically handled elsewhere.
if (error !== IGNORED_EXCEPTION) {
this.view.showErrorDisplay(error);
logger.error(error);
}
}
// renderError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
renderError(storyId: StoryId, { title, description }: { title: string; description: string }) {
this.channel.emit(Events.STORY_ERRORED, { title, description });
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: 'errored', storyId });
this.view.showErrorDisplay({
message: title,
stack: description,
});
}
}
|
lib/preview-web/src/PreviewWeb.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0086056562140584,
0.0004255867679603398,
0.00016275457164738327,
0.00017209906945936382,
0.0011341809295117855
] |
{
"id": 1,
"code_window": [
" if (newPhase === 'playing') {\n",
" resetState({ storyId, isDebugging });\n",
" }\n",
" if (newPhase === 'completed') {\n",
" this.setState(storyId, { isDebugging: false, forwardedException: undefined });\n",
" // Rethrow any unhandled forwarded exception so it doesn't go unnoticed.\n",
" if (forwardedException) throw forwardedException;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (newPhase === 'played') {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 141
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>demo2</title>
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
|
examples/vue-kitchen-sink/index.html
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.000175084249349311,
0.00017428159480914474,
0.0001734789548208937,
0.00017428159480914474,
8.026472073652258e-7
] |
{
"id": 1,
"code_window": [
" if (newPhase === 'playing') {\n",
" resetState({ storyId, isDebugging });\n",
" }\n",
" if (newPhase === 'completed') {\n",
" this.setState(storyId, { isDebugging: false, forwardedException: undefined });\n",
" // Rethrow any unhandled forwarded exception so it doesn't go unnoticed.\n",
" if (forwardedException) throw forwardedException;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (newPhase === 'played') {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 141
}
|
---
title: 'Write an addon'
---
One of Storybook's main features is its robust addon ecosystem. Use addons to enhance and extend your development workflow. This page shows you how to create your own addon.
## What we're building
For this example, we're going to build a bare-bones addon which:
- Adds a new panel in Storybook.
- Retrieves a custom parameter from the stories.
- Displays the parameter data in the panel.
### Addon kit
This guide shows you how to setup an addon from scratch. Alternatively, you can jumpstart your addon development with the [`addon-kit`](https://github.com/storybookjs/addon-kit).
### Addon directory structure
We recommend a common addon file and directory structure for consistency.
| Files/Directories | Description |
| :---------------- | :--------------------------------- |
| dist | Transpiled directory for the addon |
| src | Source code for the addon |
| .babelrc.js | Babel configuration |
| preset.js | Addon entry point |
| package.json | Addon metadata information |
| README.md | General information for the addon |
### Get started
Open a new terminal and create a new directory called `my-addon`. Inside it, run `npm init` to initialize a new node project. For your project's name, choose `my-addon` and for entry point `dist/preset.js`.
Once you've gone through the prompts, your `package.json` should look like:
```json
{
"name": "my-addon",
"version": "1.0.0",
"description": "A barebones Storybook addon",
"main": "dist/preset.js",
"files": ["dist/**/*", "README.md", "*.js"],
"keywords": ["storybook", "addons"],
"author": "YourUsername",
"license": "MIT"
}
```
### Build system
We'll need to add the necessary dependencies and make some adjustments. Run the following commands:
```shell
# Installs React and Babel CLI
yarn add react react-dom @babel/cli
# Adds Storybook:
npx sb init
```
<div class="aside">
💡 Initializing Storybook adds the building blocks for our addon. If you're building a standalone Storybook addon, set the React and Storybook packages as peer dependencies. It prevents the addon from breaking Storybook when there are different versions available.
</div>
Next, create a `.babelrc.js` file in the root directory with the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/my-addon-babel-configuration.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
<div class="aside">
Babel configuration is required because our addon uses ES6 and JSX.
</div>
Change your `package.json` and add the following script to build the addon:
```json
{
"scripts": {
"build": "babel ./src --out-dir ./dist"
}
}
```
<div class="aside">
💡 Running <code>yarn build</code> at this stage will output the code into the <code>dist</code> directory, transpiled into a ES5 module ready to be installed into any Storybook.
</div>
Finally, create a new directory called `src` and inside a new file called `preset.js` with the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/my-addon-preset-implementation.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
Presets are the way addons hook into Storybook. Among other tasks they allow you to:
- Add to [Storybook's UI](#add-a-panel)
- Add to the [preview iframe](./writing-presets.md#preview-entries)
- Modify [babel](./writing-presets.md#babel) and [webpack settings](./writing-presets.md#webpack)
For this example, we'll modify Storybook's UI.
### Add a panel
Now let’s add a panel to Storybook. Inside the `src` directory, create a new file called `register.js` and add the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/my-addon-initial-panel-state.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
<div class="aside">
💡 Make sure to include the <code>key</code> when you register the addon. It will prevent any issues when the addon renders.
</div>
Going over the code snippet in more detail. When Storybook starts up:
1. It [registers](./addons-api.md#addonsregister) the addon
2. [Adds](./addons-api.md#addonsadd) a new `panel` titled `My Addon` to the UI
3. When selected, the `panel` renders the static `div` content
### Register the addon
Finally, let’s hook it all up. Change `.storybook/main.js` to the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/my-addon-storybook-registration.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
<div class="aside">
💡 When you register a Storybook addon, it will look for either <code>register.js</code> or <code>preset.js</code> as the entry points.
</div>
Run `yarn storybook` and you should see something similar to:

### Display story parameter
Next, let’s replace the `MyPanel` component from above to show the parameter.
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-addon-change-panel.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
The new version is made smarter by [`useParameter`](./addons-api.md#useparameter), which is a [React hook](https://reactjs.org/docs/hooks-intro.html) that updates the parameter value and re-renders the panel every time the story changes.
The [addon API](./addons-api.md) provides hooks like this, so all of that communication can happen behind the scenes. That means you can focus on your addon's functionality.
### Using the addon with a story
When Storybook was initialized, it provided a small set of example stories. Change your `Button.stories.js` to the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'react/button-story-with-addon-example.js.mdx',
'vue/button-story-with-addon-example.js.mdx',
'angular/button-story-with-addon-example.ts.mdx',
'svelte/button-story-with-addon-example.js.mdx',
'svelte/button-story-with-addon-example.native-format.mdx',
]}
/>
<!-- prettier-ignore-end -->
After applying the changes to the story, the Storybook UI will show the following:
<video autoPlay muted playsInline loop>
<source
src="addon-final-stage-optimized.mp4"
type="video/mp4"
/>
</video>
### Root level preset.js
Before publishing the addon, we'll need to make one last change. In the root directory of the addon, create a new file called `preset.js` and add the following:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/my-addon-root-level-preset.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
This auto-registers the addon without any additional configuration from the user. Storybook looks for either a `preset.js` or a `register.js` file located at the root level.
### Packaging and publishing
Now that you've seen how to create a bare-bones addon let's see how to share it with the community. Before we begin, make sure your addon meets the following requirements:
- `package.json` file with metadata about the addon
- Peer dependencies of `react` and `@storybook/addons`
- `preset.js` file at the root level written as an ES5 module
- `src` directory containing the ES6 addon code
- `dist` directory containing transpiled ES5 code on publish
- [GitHub](https://github.com/) account to host your code
- [NPM](https://www.npmjs.com/) account to publish the addon
Reference the [storybook-addon-outline](https://www.npmjs.com/package/storybook-addon-outline) to see a project that meets these requirements.
Learn how to [add to the addon catalog](./addon-catalog.md).
### More guides and tutorials
In the previous example, we introduced the structure of an addon but barely scratched the surface of what addons can do.
To dive deeper, we recommend Storybook's [creating an addon](https://storybook.js.org/tutorials/create-an-addon/) tutorial. It’s an excellent walkthrough covering the same ground as the above introduction but goes further and leads you through the entire process of creating a realistic addon.
### Addon kit
To help you jumpstart the addon development, the Storybook maintainers created an [`addon-kit`](https://github.com/storybookjs/addon-kit), use it to bootstrap your next addon.
|
docs/addons/writing-addons.md
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001741252635838464,
0.00016874080756679177,
0.00016371847596019506,
0.00016853764827828854,
0.0000029757743504887912
] |
{
"id": 1,
"code_window": [
" if (newPhase === 'playing') {\n",
" resetState({ storyId, isDebugging });\n",
" }\n",
" if (newPhase === 'completed') {\n",
" this.setState(storyId, { isDebugging: false, forwardedException: undefined });\n",
" // Rethrow any unhandled forwarded exception so it doesn't go unnoticed.\n",
" if (forwardedException) throw forwardedException;\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (newPhase === 'played') {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 141
}
|
import React from 'react';
import './button.css';
interface ButtonProps {
/**
* Is this the principal call to action on the page?
*/
primary?: boolean;
/**
* What background color to use
*/
backgroundColor?: string;
/**
* How large should the button be?
*/
size?: 'small' | 'medium' | 'large';
/**
* Button contents
*/
label: string;
/**
* Optional click handler
*/
onClick?: () => void;
}
/**
* Primary UI component for user interaction
*/
export const Button = ({
primary = false,
size = 'medium',
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
return (
<button
type="button"
className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
style={{ backgroundColor }}
{...props}
>
{label}
</button>
);
};
|
lib/cli/src/frameworks/react/ts/Button.tsx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017823220696300268,
0.00017433489847462624,
0.00017074770585168153,
0.0001750743977027014,
0.0000025594583803467685
] |
{
"id": 2,
"code_window": [
" throw forwardedException;\n",
" }\n",
"\n",
" if (renderPhase === 'completed' && !call.retain) {\n",
" throw alreadyCompletedException;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (renderPhase === 'played' && !call.retain) {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 432
}
|
/* eslint-disable no-underscore-dangle */
import { addons, Channel, StoryId } from '@storybook/addons';
import { once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, LogItem } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
LOCK: 'instrumenter/lock',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
export interface Options {
intercept?: boolean | ((method: string, path: Array<string | CallRef>) => boolean);
retain?: boolean;
mutate?: boolean;
path?: Array<string | CallRef>;
getArgs?: (call: Call, state: State) => Call['args'];
}
export interface State {
renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';
isDebugging: boolean;
cursor: number;
calls: Call[];
shadowCalls: Call[];
callRefsByResult: Map<any, CallRef & { retain: boolean }>;
chainedCallIds: Set<Call['id']>;
parentCall?: Call;
playUntil?: Call['id'];
resolvers: Record<Call['id'], Function>;
syncTimeout: ReturnType<typeof setTimeout>;
forwardedException?: Error;
}
export type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentCall: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
forwardedException: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({ storyId, isDebugging }: { storyId?: StoryId; isDebugging?: boolean }) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.channel.emit(EVENTS.SYNC, this.getLog(storyId));
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging, forwardedException } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'completed') {
this.setState(storyId, { isDebugging: false, forwardedException: undefined });
// Rethrow any unhandled forwarded exception so it doesn't go unnoticed.
if (forwardedException) throw forwardedException;
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, state: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const { isDebugging } = this.getState(storyId);
const log = this.getLog(storyId);
const next = isDebugging
? log.findIndex(({ state }) => state === CallStates.WAITING)
: log.length;
start({ storyId, playUntil: log[next - 2]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall) {
const nextCallId = this.getLog(storyId).find(({ state }) => state === CallStates.WAITING)
?.callId;
if (shadowCall.id !== nextCallId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, []);
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if (call.interceptable && !seen.has(call.id) && !seen.has(call.parentId)) {
acc.unshift({ callId: call.id, state: call.state });
seen.add(call.id);
if (call.parentId) {
seen.add(call.parentId);
}
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const index = this.getState(storyId).cursor;
this.setState(storyId, { cursor: index + 1 });
const id = `${storyId} [${index}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, path, method, storyId, args, interceptable, retain };
const result = (interceptable ? this.intercept : this.invoke).call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.channel.emit(EVENTS.LOCK, false);
this.setState(call.storyId, ({ resolvers }) => ({
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.channel.emit(EVENTS.LOCK, true);
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { parentCall, callRefsByResult, forwardedException, renderPhase } = this.getState(
call.storyId
);
const callWithParent = { ...call, parentId: parentCall?.id };
const info: Call = {
...callWithParent,
// Map args that originate from a tracked function call to a call reference to enable nesting.
// These values are often not fully serializable anyway (e.g. HTML elements).
args: call.args.map((arg) => {
if (callRefsByResult.has(arg)) {
return callRefsByResult.get(arg);
}
if (arg instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = arg;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
return arg;
}),
};
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: unknown) => {
if (e instanceof Error) {
const { name, message, stack } = e;
const exception = { name, message, stack, callId: call.id };
this.sync({ ...info, state: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (call.interceptable && e !== alreadyCompletedException) {
throw IGNORED_EXCEPTION;
}
// Non-interceptable calls need their exceptions forwarded to the next interceptable call.
// In case no interceptable call picks it up, it'll get rethrown in the "completed" phase.
this.setState(call.storyId, { forwardedException: e });
return e;
}
throw e;
};
try {
// An earlier, non-interceptable call might have forwarded an exception.
if (forwardedException) {
this.setState(call.storyId, { forwardedException: undefined });
throw forwardedException;
}
if (renderPhase === 'completed' && !call.retain) {
throw alreadyCompletedException;
}
const finalArgs = options.getArgs
? options.getArgs(callWithParent, this.getState(call.storyId))
: call.args;
const result = fn(
// Wrap any callback functions to provide a way to access their "parent" call.
...finalArgs.map((arg: any) => {
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
const prev = this.getState(call.storyId).parentCall;
this.setState(call.storyId, { parentCall: call });
const res = arg(...args);
this.setState(call.storyId, { parentCall: prev });
return res;
};
})
);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.sync({
...info,
state: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.sync({ ...info, state: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
sync(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => ({
calls: calls.concat(call),
syncTimeout: setTimeout(() => this.channel.emit(EVENTS.SYNC, this.getLog(call.storyId)), 0),
}));
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe.
if (global.window.parent === global.window) return obj;
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}
|
lib/instrumenter/src/instrumenter.ts
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.9988994598388672,
0.04628529027104378,
0.0001627946039661765,
0.00018017756519839168,
0.1961466670036316
] |
{
"id": 2,
"code_window": [
" throw forwardedException;\n",
" }\n",
"\n",
" if (renderPhase === 'completed' && !call.retain) {\n",
" throw alreadyCompletedException;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (renderPhase === 'played' && !call.retain) {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 432
}
|
import { makeRe } from 'picomatch';
export function globToRegexp(glob: string) {
const regex = makeRe(glob, {
fastpaths: false,
noglobstar: false,
bash: false,
});
if (!regex.source.startsWith('^')) {
throw new Error(`Invalid glob: >> ${glob} >> ${regex}`);
}
if (!glob.startsWith('./')) {
return regex;
}
// makeRe is sort of funny. If you pass it a directory starting with `./` it
// creates a matcher that expects files with no prefix (e.g. `src/file.js`)
// but if you pass it a directory that starts with `../` it expects files that
// start with `../`. Let's make it consistent.
// Globs starting `**` require special treatment due to the regex they
// produce, specifically a negative look-ahead
return new RegExp(
['^\\.', glob.startsWith('./**') ? '' : '[\\\\/]', regex.source.substring(1)].join('')
);
}
|
lib/core-common/src/utils/glob-to-regexp.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017419485084246844,
0.0001734403776936233,
0.00017271000251639634,
0.0001734162651700899,
6.06426397098403e-7
] |
{
"id": 2,
"code_window": [
" throw forwardedException;\n",
" }\n",
"\n",
" if (renderPhase === 'completed' && !call.retain) {\n",
" throw alreadyCompletedException;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (renderPhase === 'played' && !call.retain) {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 432
}
|
```js
// .storybook/preview.js
import React from "react";
export const decorators = [
(Story) => (
<div style={{ margin: '3em' }}>
{Story()}
</div>
),
];
```
|
docs/snippets/react/storybook-preview-global-decorator.story-function.js.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00018026265024673194,
0.00017785359523259103,
0.00017544454021845013,
0.00017785359523259103,
0.000002409055014140904
] |
{
"id": 2,
"code_window": [
" throw forwardedException;\n",
" }\n",
"\n",
" if (renderPhase === 'completed' && !call.retain) {\n",
" throw alreadyCompletedException;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (renderPhase === 'played' && !call.retain) {\n"
],
"file_path": "lib/instrumenter/src/instrumenter.ts",
"type": "replace",
"edit_start_line_idx": 432
}
|
import { Story, Canvas, Meta, ArgsTable } from '@storybook/addon-docs';
import { html } from 'lit';
import '../../../../demo-wc-card.js';
# Storybook Docs for Web Components
<Meta title="Misc. / Addons - Docs" />
## Story definition
A story can be a simple return of `html`
<Story name="simple" height="220px">
{html` <demo-wc-card>Hello World</demo-wc-card> `}
</Story>
## API
You can show the api table of a web component at any point in your documentation.
<ArgsTable of="demo-wc-card" />
## Function stories
Or a function
<Story name="function" height="220px">
{() => {
const rows = [
{ header: 'health', value: '200' },
{ header: 'mana', value: '100' },
];
return html`
<demo-wc-card back-side .rows=${rows}> A card with data on the back </demo-wc-card>
`;
}}
</Story>
## Wrapper
You can also wrap your live demos in a nice little wrapper.
<Canvas withToolbar>
<Story name="wrapper" height="220px">
{html` <demo-wc-card>Hello World</demo-wc-card> `}
</Story>
</Canvas>
## Story reference
You can also reference an existing story from within your MDX file.
<Canvas withToolbar>
<Story id="welcome--welcome" height="500px" inline={false} />
</Canvas>
## Stories not inline
By default stories are rendered inline.
For web components that is usually fine as they are style encapsulated via shadow dom.
However when you have a style tag in you template it might be best to show them in an iframe.
To always use iframes you can set
```js
addParameters({
docs: {
inlineStories: false,
},
});
```
or add it to individual stories.
```
<Story inline={false} />
```
<Canvas withToolbar>
<Story name="notInline" height="220px">
{html`
<style>
p { color: red; }
</style>
<p>Makes all p tags red... so best to not render inline</pd>
`}
</Story>
</Canvas>
|
examples/web-components-kitchen-sink/src/stories/misc/to-update/addon-docs.stories.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017559465777594596,
0.00017273175762966275,
0.00016700051492080092,
0.00017234987171832472,
0.000002386533651588252
] |
{
"id": 3,
"code_window": [
" } as AbortController;\n",
"}\n",
"\n",
"export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';\n",
"type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;\n",
"type MaybePromise<T> = Promise<T> | T;\n",
"type StoryCleanupFn = () => MaybePromise<void>;\n",
"\n",
"const STORY_INDEX_PATH = './stories.json';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export type RenderPhase =\n",
" | 'loading'\n",
" | 'rendering'\n",
" | 'playing'\n",
" | 'played'\n",
" | 'completed'\n",
" | 'aborted'\n",
" | 'errored';\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
import deprecate from 'util-deprecate';
import dedent from 'ts-dedent';
import global from 'global';
import { SynchronousPromise } from 'synchronous-promise';
import Events, { IGNORED_EXCEPTION } from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import { addons, Channel } from '@storybook/addons';
import {
AnyFramework,
StoryId,
ProjectAnnotations,
Args,
Globals,
ViewMode,
StoryContextForLoaders,
StoryContext,
} from '@storybook/csf';
import {
ModuleImportFn,
Selection,
Story,
RenderContext,
CSFFile,
StoryStore,
StorySpecifier,
StoryIndex,
} from '@storybook/store';
import { WebProjectAnnotations } from './types';
import { UrlStore } from './UrlStore';
import { WebView } from './WebView';
const { window: globalWindow, AbortController, FEATURES, fetch } = global;
function focusInInput(event: Event) {
const target = event.target as Element;
return /input|textarea/i.test(target.tagName) || target.getAttribute('contenteditable') !== null;
}
function createController(): AbortController {
if (AbortController) return new AbortController();
// Polyfill for IE11
return {
signal: { aborted: false },
abort() {
this.signal.aborted = true;
},
} as AbortController;
}
export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';
type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;
type MaybePromise<T> = Promise<T> | T;
type StoryCleanupFn = () => MaybePromise<void>;
const STORY_INDEX_PATH = './stories.json';
export class PreviewWeb<TFramework extends AnyFramework> {
channel: Channel;
serverChannel?: Channel;
urlStore: UrlStore;
storyStore: StoryStore<TFramework>;
view: WebView;
renderToDOM: WebProjectAnnotations<TFramework>['renderToDOM'];
previousSelection: Selection;
previousStory: Story<TFramework>;
previousCleanup: StoryCleanupFn;
abortSignal: AbortSignal;
constructor() {
this.channel = addons.getChannel();
if (FEATURES?.storyStoreV7) {
this.serverChannel = addons.getServerChannel();
}
this.view = new WebView();
this.urlStore = new UrlStore();
this.storyStore = new StoryStore();
// Add deprecated APIs for back-compat
// @ts-ignore
this.storyStore.getSelection = deprecate(
() => this.urlStore.selection,
dedent`
\`__STORYBOOK_STORY_STORE__.getSelection()\` is deprecated and will be removed in 7.0.
To get the current selection, use the \`useStoryContext()\` hook from \`@storybook/addons\`.
`
);
}
// NOTE: the reason that the preview and store's initialization code is written in a promise
// style and not `async-await`, and the use of `SynchronousPromise`s is in order to allow
// storyshots to immediately call `raw()` on the store without waiting for a later tick.
// (Even simple things like `Promise.resolve()` and `await` involve the callback happening
// in the next promise "tick").
// See the comment in `storyshots-core/src/api/index.ts` for more detail.
initialize({
getStoryIndex,
importFn,
getProjectAnnotations,
}: {
// In the case of the v6 store, we can only get the index from the facade *after*
// getProjectAnnotations has been run, thus this slightly awkward approach
getStoryIndex?: () => StoryIndex;
importFn: ModuleImportFn;
getProjectAnnotations: () => MaybePromise<WebProjectAnnotations<TFramework>>;
}): PromiseLike<void> {
return this.getProjectAnnotationsOrRenderError(getProjectAnnotations).then(
(projectAnnotations) => {
this.storyStore.setProjectAnnotations(projectAnnotations);
this.setupListeners();
let storyIndexPromise: PromiseLike<StoryIndex>;
if (FEATURES?.storyStoreV7) {
storyIndexPromise = this.getStoryIndexFromServer();
} else {
if (!getStoryIndex) {
throw new Error('No `getStoryIndex` passed defined in v6 mode');
}
storyIndexPromise = SynchronousPromise.resolve().then(getStoryIndex);
}
return storyIndexPromise
.then((storyIndex: StoryIndex) => {
return this.storyStore
.initialize({
storyIndex,
importFn,
cache: !FEATURES?.storyStoreV7,
})
.then(() => {
if (!FEATURES?.storyStoreV7) {
this.channel.emit(Events.SET_STORIES, this.storyStore.getSetStoriesPayload());
}
this.setGlobalsAndRenderSelection();
});
})
.catch((err) => {
logger.warn(err);
this.renderPreviewEntryError(err);
});
}
);
}
getProjectAnnotationsOrRenderError(
getProjectAnnotations: () => MaybePromise<WebProjectAnnotations<TFramework>>
): PromiseLike<ProjectAnnotations<TFramework>> {
return SynchronousPromise.resolve()
.then(() => getProjectAnnotations())
.then((projectAnnotations) => {
this.renderToDOM = projectAnnotations.renderToDOM;
if (!this.renderToDOM) {
throw new Error(dedent`
Expected 'framework' in your main.js to export 'renderToDOM', but none found.
You can fix this automatically by running:
npx sb@next automigrate
More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#mainjs-framework-field
`);
}
return projectAnnotations;
})
.catch((err) => {
logger.warn(err);
// This is an error extracting the projectAnnotations (i.e. evaluating the previewEntries) and
// needs to be show to the user as a simple error
this.renderPreviewEntryError(err);
return {};
});
}
setupListeners() {
globalWindow.onkeydown = this.onKeydown.bind(this);
this.serverChannel?.on(Events.STORY_INDEX_INVALIDATED, this.onStoryIndexChanged.bind(this));
this.channel.on(Events.SET_CURRENT_STORY, this.onSetCurrentStory.bind(this));
this.channel.on(Events.UPDATE_QUERY_PARAMS, this.onUpdateQueryParams.bind(this));
this.channel.on(Events.UPDATE_GLOBALS, this.onUpdateGlobals.bind(this));
this.channel.on(Events.UPDATE_STORY_ARGS, this.onUpdateArgs.bind(this));
this.channel.on(Events.RESET_STORY_ARGS, this.onResetArgs.bind(this));
}
async setGlobalsAndRenderSelection() {
const { globals } = this.urlStore.selectionSpecifier || {};
if (globals) {
this.storyStore.globals.updateFromPersisted(globals);
}
this.channel.emit(Events.SET_GLOBALS, {
globals: this.storyStore.globals.get() || {},
globalTypes: this.storyStore.projectAnnotations.globalTypes || {},
});
return this.selectSpecifiedStory();
}
// Use the selection specifier to choose a story, then render it
async selectSpecifiedStory() {
if (!this.urlStore.selectionSpecifier) {
await this.renderMissingStory();
return;
}
const { storySpecifier, viewMode, args } = this.urlStore.selectionSpecifier;
const storyId = this.storyStore.storyIndex.storyIdFromSpecifier(storySpecifier);
if (!storyId) {
await this.renderMissingStory(storySpecifier);
return;
}
this.urlStore.setSelection({ storyId, viewMode });
this.channel.emit(Events.STORY_SPECIFIED, this.urlStore.selection);
this.channel.emit(Events.CURRENT_STORY_WAS_SET, this.urlStore.selection);
await this.renderSelection({ persistedArgs: args });
}
onKeydown(event: KeyboardEvent) {
if (!focusInInput(event)) {
// We have to pick off the keys of the event that we need on the other side
const { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode } = event;
this.channel.emit(Events.PREVIEW_KEYDOWN, {
event: { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode },
});
}
}
onSetCurrentStory(selection: Selection) {
this.urlStore.setSelection(selection);
this.channel.emit(Events.CURRENT_STORY_WAS_SET, this.urlStore.selection);
this.renderSelection();
}
onUpdateQueryParams(queryParams: any) {
this.urlStore.setQueryParams(queryParams);
}
onUpdateGlobals({ globals }: { globals: Globals }) {
this.storyStore.globals.update(globals);
this.channel.emit(Events.GLOBALS_UPDATED, {
globals: this.storyStore.globals.get(),
initialGlobals: this.storyStore.globals.initialGlobals,
});
}
onUpdateArgs({ storyId, updatedArgs }: { storyId: StoryId; updatedArgs: Args }) {
this.storyStore.args.update(storyId, updatedArgs);
this.channel.emit(Events.STORY_ARGS_UPDATED, {
storyId,
args: this.storyStore.args.get(storyId),
});
}
async onResetArgs({ storyId, argNames }: { storyId: string; argNames?: string[] }) {
// NOTE: we have to be careful here and avoid await-ing when updating the current story's args.
// That's because below in `renderStoryToElement` we have also bound to this event and will
// render the story in the same tick.
// However, we can do that safely as the current story is available in `this.previousStory`
const { initialArgs } =
storyId === this.previousStory.id
? this.previousStory
: await this.storyStore.loadStory({ storyId });
const argNamesToReset = argNames || Object.keys(this.storyStore.args.get(storyId));
const updatedArgs = argNamesToReset.reduce((acc, argName) => {
acc[argName] = initialArgs[argName];
return acc;
}, {} as Partial<Args>);
this.onUpdateArgs({ storyId, updatedArgs });
}
async onStoryIndexChanged() {
const storyIndex = await this.getStoryIndexFromServer();
return this.onStoriesChanged({ storyIndex });
}
// This happens when a glob gets HMR-ed
async onStoriesChanged({
importFn,
storyIndex,
}: {
importFn?: ModuleImportFn;
storyIndex?: StoryIndex;
}) {
await this.storyStore.onStoriesChanged({ importFn, storyIndex });
if (this.urlStore.selection) {
await this.renderSelection();
} else {
await this.selectSpecifiedStory();
}
if (!FEATURES?.storyStoreV7) {
this.channel.emit(Events.SET_STORIES, await this.storyStore.getSetStoriesPayload());
}
}
// This happens when a config file gets reloade
async onGetProjectAnnotationsChanged({
getProjectAnnotations,
}: {
getProjectAnnotations: () => MaybePromise<ProjectAnnotations<TFramework>>;
}) {
const projectAnnotations = await this.getProjectAnnotationsOrRenderError(getProjectAnnotations);
if (!projectAnnotations) {
return;
}
this.storyStore.setProjectAnnotations(projectAnnotations);
this.renderSelection();
}
async getStoryIndexFromServer() {
const result = await fetch(STORY_INDEX_PATH);
if (result.status === 200) return result.json() as StoryIndex;
throw new Error(await result.text());
}
// We can either have:
// - a story selected in "story" viewMode,
// in which case we render it to the root element, OR
// - a story selected in "docs" viewMode,
// in which case we render the docsPage for that story
async renderSelection({ persistedArgs }: { persistedArgs?: Args } = {}) {
if (!this.urlStore.selection) {
throw new Error('Cannot render story as no selection was made');
}
const {
selection,
selection: { storyId },
} = this.urlStore;
let story;
try {
story = await this.storyStore.loadStory({ storyId });
} catch (err) {
this.previousStory = null;
logger.warn(err);
await this.renderMissingStory(storyId);
return;
}
const storyIdChanged = this.previousSelection?.storyId !== storyId;
const viewModeChanged = this.previousSelection?.viewMode !== selection.viewMode;
const implementationChanged =
!storyIdChanged && this.previousStory && story !== this.previousStory;
if (persistedArgs) {
this.storyStore.args.updateFromPersisted(story, persistedArgs);
}
// Don't re-render the story if nothing has changed to justify it
if (this.previousStory && !storyIdChanged && !implementationChanged && !viewModeChanged) {
this.channel.emit(Events.STORY_UNCHANGED, storyId);
return;
}
await this.cleanupPreviousRender({ unmountDocs: viewModeChanged });
// If we are rendering something new (as opposed to re-rendering the same or first story), emit
if (this.previousSelection && (storyIdChanged || viewModeChanged)) {
this.channel.emit(Events.STORY_CHANGED, storyId);
}
// Record the previous selection *before* awaiting the rendering, in cases things change before it is done.
this.previousSelection = selection;
this.previousStory = story;
const { parameters, initialArgs, argTypes, args } = this.storyStore.getStoryContext(story);
if (FEATURES?.storyStoreV7) {
this.channel.emit(Events.STORY_PREPARED, {
id: storyId,
parameters,
initialArgs,
argTypes,
args,
});
}
// If the implementation changed, the args also may have changed
if (implementationChanged) {
this.channel.emit(Events.STORY_ARGS_UPDATED, { storyId, args });
}
if (selection.viewMode === 'docs' || story.parameters.docsOnly) {
this.previousCleanup = await this.renderDocs({ story });
} else {
this.previousCleanup = this.renderStory({ story });
}
}
async renderDocs({ story }: { story: Story<TFramework> }) {
const { id, title, name } = story;
const element = this.view.prepareForDocs();
const csfFile: CSFFile<TFramework> = await this.storyStore.loadCSFFileByStoryId(id);
const docsContext = {
id,
title,
name,
// NOTE: these two functions are *sync* so cannot access stories from other CSF files
storyById: (storyId: StoryId) => this.storyStore.storyFromCSFFile({ storyId, csfFile }),
componentStories: () => this.storyStore.componentStoriesFromCSFFile({ csfFile }),
loadStory: (storyId: StoryId) => this.storyStore.loadStory({ storyId }),
renderStoryToElement: this.renderStoryToElement.bind(this),
getStoryContext: (renderedStory: Story<TFramework>) =>
({
...this.storyStore.getStoryContext(renderedStory),
viewMode: 'docs' as ViewMode,
} as StoryContextForLoaders<TFramework>),
};
const render = async () => {
const fullDocsContext = {
...docsContext,
// Put all the storyContext fields onto the docs context for back-compat
...(!FEATURES?.breakingChangesV7 && this.storyStore.getStoryContext(story)),
};
(await import('./renderDocs')).renderDocs(story, fullDocsContext, element, () =>
this.channel.emit(Events.DOCS_RENDERED, id)
);
};
// Initially render right away
render();
// Listen to events and re-render
// NOTE: we aren't checking to see the story args are targetted at the "right" story.
// This is because we may render >1 story on the page and there is no easy way to keep track
// of which ones were rendered by the docs page.
// However, in `modernInlineRender`, the individual stories track their own events as they
// each call `renderStoryToElement` below.
if (!global?.FEATURES?.modernInlineRender) {
this.channel.on(Events.UPDATE_GLOBALS, render);
this.channel.on(Events.UPDATE_STORY_ARGS, render);
this.channel.on(Events.RESET_STORY_ARGS, render);
}
return async () => {
if (!global?.FEATURES?.modernInlineRender) {
this.channel.off(Events.UPDATE_GLOBALS, render);
this.channel.off(Events.UPDATE_STORY_ARGS, render);
this.channel.off(Events.RESET_STORY_ARGS, render);
}
};
}
renderStory({ story }: { story: Story<TFramework> }) {
const element = this.view.prepareForStory(story);
const { id, componentId, title, name } = story;
const renderContext = {
componentId,
title,
kind: title,
id,
name,
story: name,
showMain: () => this.view.showMain(),
showError: (err: { title: string; description: string }) => this.renderError(id, err),
showException: (err: Error) => this.renderException(id, err),
};
return this.renderStoryToElement({ story, renderContext, element });
}
// Render a story into a given element and watch for the events that would trigger us
// to re-render it (plus deal sensibly with things like changing story mid-way through).
renderStoryToElement({
story,
renderContext: renderContextWithoutStoryContext,
element,
}: {
story: Story<TFramework>;
renderContext: Omit<
RenderContext<TFramework>,
'storyContext' | 'storyFn' | 'unboundStoryFn' | 'forceRemount'
>;
element: HTMLElement;
}): StoryCleanupFn {
const { id, applyLoaders, unboundStoryFn, playFunction } = story;
let phase: RenderPhase;
const isPending = () => ['rendering', 'playing'].includes(phase);
let controller: AbortController;
let notYetRendered = true;
const render = async ({ forceRemount = false } = {}) => {
let ctrl = controller; // we also need a stable reference within this closure
// Abort the signal used by the previous render, so it'll (hopefully) stop executing. The
// play function might continue execution regardless, which we deal with during cleanup.
// Note we can't reload the page here because there's a legitimate use case for forceRemount
// while in the 'playing' phase: the play function may never resolve during debugging, while
// "step back" will trigger a forceRemount. In this case it's up to the debugger to reload.
if (ctrl) ctrl.abort();
ctrl = createController();
controller = ctrl;
this.abortSignal = controller.signal;
const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {
phase = phaseName;
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });
await phaseFn();
if (ctrl.signal.aborted) {
phase = 'aborted';
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });
}
};
try {
let loadedContext: StoryContext<TFramework>;
await runPhase('loading', async () => {
loadedContext = await applyLoaders({
...this.storyStore.getStoryContext(story),
viewMode: element === this.view.storyRoot() ? 'story' : 'docs',
} as StoryContextForLoaders<TFramework>);
});
if (ctrl.signal.aborted) return;
const renderStoryContext: StoryContext<TFramework> = {
...loadedContext,
// By this stage, it is possible that new args/globals have been received for this story
// and we need to ensure we render it with the new values
...this.storyStore.getStoryContext(story),
abortSignal: ctrl.signal,
canvasElement: element,
};
const renderContext: RenderContext<TFramework> = {
...renderContextWithoutStoryContext,
forceRemount: forceRemount || notYetRendered,
storyContext: renderStoryContext,
storyFn: () => unboundStoryFn(renderStoryContext),
unboundStoryFn,
};
await runPhase('rendering', () => this.renderToDOM(renderContext, element));
notYetRendered = false;
if (ctrl.signal.aborted) return;
if (forceRemount && playFunction) {
await runPhase('playing', () => playFunction(renderContext.storyContext));
if (ctrl.signal.aborted) return;
}
await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));
} catch (err) {
renderContextWithoutStoryContext.showException(err);
}
};
// Start the first (initial) render. We don't await here because we need to return the "cleanup"
// function below right away, so if the user changes story during the first render we can cancel
// it without having to first wait for it to finish.
// Whenever the selection changes we want to force the component to be remounted.
render({ forceRemount: true });
const remountStoryIfMatches = ({ storyId }: { storyId: StoryId }) => {
if (storyId === story.id) render({ forceRemount: true });
};
const rerenderStoryIfMatches = ({ storyId }: { storyId: StoryId }) => {
if (storyId === story.id) render();
};
// Listen to events and re-render story
// Don't forget to unsubscribe on cleanup
this.channel.on(Events.UPDATE_GLOBALS, render);
this.channel.on(Events.FORCE_RE_RENDER, render);
this.channel.on(Events.FORCE_REMOUNT, remountStoryIfMatches);
this.channel.on(Events.UPDATE_STORY_ARGS, rerenderStoryIfMatches);
this.channel.on(Events.RESET_STORY_ARGS, rerenderStoryIfMatches);
// Cleanup / teardown function invoked on next render (via `cleanupPreviousRender`)
return async () => {
// If the story is torn down (either a new story is rendered or the docs page removes it)
// we need to consider the fact that the initial render may not be finished
// (possibly the loaders or the play function are still running). We use the controller
// as a method to abort them, ASAP, but this is not foolproof as we cannot control what
// happens inside the user's code.
controller.abort();
this.storyStore.cleanupStory(story);
this.channel.off(Events.UPDATE_GLOBALS, render);
this.channel.off(Events.FORCE_RE_RENDER, render);
this.channel.off(Events.FORCE_REMOUNT, remountStoryIfMatches);
this.channel.off(Events.UPDATE_STORY_ARGS, rerenderStoryIfMatches);
this.channel.off(Events.RESET_STORY_ARGS, rerenderStoryIfMatches);
// Check if we're done rendering/playing. If not, we may have to reload the page.
if (!isPending()) return;
// Wait several ticks that may be needed to handle the abort, then try again.
// Note that there's a max of 5 nested timeouts before they're no longer "instant".
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
await new Promise((resolve) => setTimeout(resolve, 0));
if (!isPending()) return;
// If we still haven't completed, reload the page (iframe) to ensure we have a clean slate
// for the next render. Since the reload can take a brief moment to happen, we want to stop
// further rendering by awaiting a never-resolving promise (which is destroyed on reload).
global.window.location.reload();
await new Promise(() => {});
};
}
async cleanupPreviousRender({ unmountDocs = true }: { unmountDocs?: boolean } = {}) {
const previousViewMode = this.previousStory?.parameters?.docsOnly
? 'docs'
: this.previousSelection?.viewMode;
if (unmountDocs && previousViewMode === 'docs') {
(await import('./renderDocs')).unmountDocs(this.view.docsRoot());
}
if (this.previousCleanup) {
await this.previousCleanup();
}
}
renderPreviewEntryError(err: Error) {
this.view.showErrorDisplay(err);
this.channel.emit(Events.CONFIG_ERROR, err);
}
async renderMissingStory(storySpecifier?: StorySpecifier) {
await this.cleanupPreviousRender();
this.view.showNoPreview();
this.channel.emit(Events.STORY_MISSING, storySpecifier);
}
// renderException is used if we fail to render the story and it is uncaught by the app layer
renderException(storyId: StoryId, error: Error) {
this.channel.emit(Events.STORY_THREW_EXCEPTION, error);
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: 'errored', storyId });
// Ignored exceptions exist for control flow purposes, and are typically handled elsewhere.
if (error !== IGNORED_EXCEPTION) {
this.view.showErrorDisplay(error);
logger.error(error);
}
}
// renderError is used by the various app layers to inform the user they have done something
// wrong -- for instance returned the wrong thing from a story
renderError(storyId: StoryId, { title, description }: { title: string; description: string }) {
this.channel.emit(Events.STORY_ERRORED, { title, description });
this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: 'errored', storyId });
this.view.showErrorDisplay({
message: title,
stack: description,
});
}
}
|
lib/preview-web/src/PreviewWeb.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.9991662502288818,
0.17833194136619568,
0.00016417824372183532,
0.0001766726200003177,
0.3711945712566376
] |
{
"id": 3,
"code_window": [
" } as AbortController;\n",
"}\n",
"\n",
"export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';\n",
"type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;\n",
"type MaybePromise<T> = Promise<T> | T;\n",
"type StoryCleanupFn = () => MaybePromise<void>;\n",
"\n",
"const STORY_INDEX_PATH = './stories.json';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export type RenderPhase =\n",
" | 'loading'\n",
" | 'rendering'\n",
" | 'playing'\n",
" | 'played'\n",
" | 'completed'\n",
" | 'aborted'\n",
" | 'errored';\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
import('@types/compression');
declare module 'lazy-universal-dotenv';
declare module 'pnp-webpack-plugin';
declare module '@storybook/semver';
declare namespace jest {
interface Matchers<R> {
toMatchPaths(paths: string[]): R;
}
}
declare module 'file-system-cache' {
export interface Options {
basePath?: string;
ns?: string | string[];
extension?: string;
}
export declare class FileSystemCache {
constructor(options: Options);
path(key: string): string;
fileExists(key: string): Promise<boolean>;
ensureBasePath(): Promise<void>;
get(key: string, defaultValue?: any): Promise<any | typeof defaultValue>;
getSync(key: string, defaultValue?: any): any | typeof defaultValue;
set(key: string, value: any): Promise<{ path: string }>;
setSync(key: string, value: any): this;
remove(key: string): Promise<void>;
clear(): Promise<void>;
save(): Promise<{ paths: string[] }>;
load(): Promise<{ files: Array<{ path: string; value: any }> }>;
}
function create(options: Options): FileSystemCache;
export = create;
}
|
lib/core-common/typings.d.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00028901672339998186,
0.00020614481763914227,
0.00016818367294035852,
0.00018368946621194482,
0.00004859366890741512
] |
{
"id": 3,
"code_window": [
" } as AbortController;\n",
"}\n",
"\n",
"export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';\n",
"type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;\n",
"type MaybePromise<T> = Promise<T> | T;\n",
"type StoryCleanupFn = () => MaybePromise<void>;\n",
"\n",
"const STORY_INDEX_PATH = './stories.json';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export type RenderPhase =\n",
" | 'loading'\n",
" | 'rendering'\n",
" | 'playing'\n",
" | 'played'\n",
" | 'completed'\n",
" | 'aborted'\n",
" | 'errored';\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
import React, { FC, ChangeEvent, useCallback, useState } from 'react';
import { styled } from '@storybook/theming';
import { Form } from '../form';
import { getControlId, getControlSetterButtonId } from './helpers';
import { ControlProps, TextValue, TextConfig } from './types';
export type TextProps = ControlProps<TextValue | undefined> & TextConfig;
const Wrapper = styled.label({
display: 'flex',
});
export const TextControl: FC<TextProps> = ({ name, value, onChange, onFocus, onBlur }) => {
const handleChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
onChange(event.target.value);
};
const [forceVisible, setForceVisible] = useState(false);
const onForceVisible = useCallback(() => {
onChange('');
setForceVisible(true);
}, [setForceVisible]);
if (value === undefined) {
return (
<Form.Button id={getControlSetterButtonId(name)} onClick={onForceVisible}>
Set string
</Form.Button>
);
}
const isValid = typeof value === 'string';
return (
<Wrapper>
<Form.Textarea
id={getControlId(name)}
onChange={handleChange}
size="flex"
placeholder="Edit string..."
autoFocus={forceVisible}
valid={isValid ? null : 'error'}
{...{ name, value: isValid ? value : '', onFocus, onBlur }}
/>
</Wrapper>
);
};
|
lib/components/src/controls/Text.tsx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001759756269166246,
0.00017393834423273802,
0.0001715196849545464,
0.0001739289436955005,
0.0000014947515865060268
] |
{
"id": 3,
"code_window": [
" } as AbortController;\n",
"}\n",
"\n",
"export type RenderPhase = 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted' | 'errored';\n",
"type PromiseLike<T> = Promise<T> | SynchronousPromise<T>;\n",
"type MaybePromise<T> = Promise<T> | T;\n",
"type StoryCleanupFn = () => MaybePromise<void>;\n",
"\n",
"const STORY_INDEX_PATH = './stories.json';\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export type RenderPhase =\n",
" | 'loading'\n",
" | 'rendering'\n",
" | 'playing'\n",
" | 'played'\n",
" | 'completed'\n",
" | 'aborted'\n",
" | 'errored';\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
import deprecate from 'util-deprecate';
import dedent from 'ts-dedent';
export function parseList(str: string): string[] {
return str
.split(',')
.map((item) => item.trim())
.filter((item) => item.length > 0);
}
export function getEnvConfig(program: Record<string, any>, configEnv: Record<string, any>): void {
Object.keys(configEnv).forEach((fieldName) => {
const envVarName = configEnv[fieldName];
const envVarValue = process.env[envVarName];
if (envVarValue) {
program[fieldName] = envVarValue; // eslint-disable-line
}
});
}
const warnDLLsDeprecated = deprecate(
() => {},
dedent`
DLL-related CLI flags are deprecated, see:
https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated-dll-flags
`
);
export function checkDeprecatedFlags(options: {
dll?: boolean;
uiDll?: boolean;
docsDll?: boolean;
}) {
if (!options.dll || options.uiDll || options.docsDll) {
warnDLLsDeprecated();
}
}
|
lib/core-server/src/cli/utils.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017982555436901748,
0.00017337175086140633,
0.00016661464178469032,
0.00017352341092191637,
0.000004684873147198232
] |
{
"id": 4,
"code_window": [
" ctrl = createController();\n",
" controller = ctrl;\n",
" this.abortSignal = controller.signal;\n",
"\n",
" const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {\n",
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" const runPhase = async (phaseName: RenderPhase, phaseFn?: () => MaybePromise<void>) => {\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 520
}
|
/* eslint-disable no-underscore-dangle */
import { addons, Channel, StoryId } from '@storybook/addons';
import { once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, LogItem } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
LOCK: 'instrumenter/lock',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
export interface Options {
intercept?: boolean | ((method: string, path: Array<string | CallRef>) => boolean);
retain?: boolean;
mutate?: boolean;
path?: Array<string | CallRef>;
getArgs?: (call: Call, state: State) => Call['args'];
}
export interface State {
renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';
isDebugging: boolean;
cursor: number;
calls: Call[];
shadowCalls: Call[];
callRefsByResult: Map<any, CallRef & { retain: boolean }>;
chainedCallIds: Set<Call['id']>;
parentCall?: Call;
playUntil?: Call['id'];
resolvers: Record<Call['id'], Function>;
syncTimeout: ReturnType<typeof setTimeout>;
forwardedException?: Error;
}
export type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentCall: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
forwardedException: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({ storyId, isDebugging }: { storyId?: StoryId; isDebugging?: boolean }) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.channel.emit(EVENTS.SYNC, this.getLog(storyId));
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging, forwardedException } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'completed') {
this.setState(storyId, { isDebugging: false, forwardedException: undefined });
// Rethrow any unhandled forwarded exception so it doesn't go unnoticed.
if (forwardedException) throw forwardedException;
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, state: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const { isDebugging } = this.getState(storyId);
const log = this.getLog(storyId);
const next = isDebugging
? log.findIndex(({ state }) => state === CallStates.WAITING)
: log.length;
start({ storyId, playUntil: log[next - 2]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall) {
const nextCallId = this.getLog(storyId).find(({ state }) => state === CallStates.WAITING)
?.callId;
if (shadowCall.id !== nextCallId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, []);
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if (call.interceptable && !seen.has(call.id) && !seen.has(call.parentId)) {
acc.unshift({ callId: call.id, state: call.state });
seen.add(call.id);
if (call.parentId) {
seen.add(call.parentId);
}
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const index = this.getState(storyId).cursor;
this.setState(storyId, { cursor: index + 1 });
const id = `${storyId} [${index}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, path, method, storyId, args, interceptable, retain };
const result = (interceptable ? this.intercept : this.invoke).call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.channel.emit(EVENTS.LOCK, false);
this.setState(call.storyId, ({ resolvers }) => ({
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.channel.emit(EVENTS.LOCK, true);
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { parentCall, callRefsByResult, forwardedException, renderPhase } = this.getState(
call.storyId
);
const callWithParent = { ...call, parentId: parentCall?.id };
const info: Call = {
...callWithParent,
// Map args that originate from a tracked function call to a call reference to enable nesting.
// These values are often not fully serializable anyway (e.g. HTML elements).
args: call.args.map((arg) => {
if (callRefsByResult.has(arg)) {
return callRefsByResult.get(arg);
}
if (arg instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = arg;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
return arg;
}),
};
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: unknown) => {
if (e instanceof Error) {
const { name, message, stack } = e;
const exception = { name, message, stack, callId: call.id };
this.sync({ ...info, state: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (call.interceptable && e !== alreadyCompletedException) {
throw IGNORED_EXCEPTION;
}
// Non-interceptable calls need their exceptions forwarded to the next interceptable call.
// In case no interceptable call picks it up, it'll get rethrown in the "completed" phase.
this.setState(call.storyId, { forwardedException: e });
return e;
}
throw e;
};
try {
// An earlier, non-interceptable call might have forwarded an exception.
if (forwardedException) {
this.setState(call.storyId, { forwardedException: undefined });
throw forwardedException;
}
if (renderPhase === 'completed' && !call.retain) {
throw alreadyCompletedException;
}
const finalArgs = options.getArgs
? options.getArgs(callWithParent, this.getState(call.storyId))
: call.args;
const result = fn(
// Wrap any callback functions to provide a way to access their "parent" call.
...finalArgs.map((arg: any) => {
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
const prev = this.getState(call.storyId).parentCall;
this.setState(call.storyId, { parentCall: call });
const res = arg(...args);
this.setState(call.storyId, { parentCall: prev });
return res;
};
})
);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.sync({
...info,
state: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.sync({ ...info, state: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
sync(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => ({
calls: calls.concat(call),
syncTimeout: setTimeout(() => this.channel.emit(EVENTS.SYNC, this.getLog(call.storyId)), 0),
}));
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe.
if (global.window.parent === global.window) return obj;
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}
|
lib/instrumenter/src/instrumenter.ts
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.9762313961982727,
0.018964828923344612,
0.00016014065477065742,
0.00017230141384061426,
0.13275602459907532
] |
{
"id": 4,
"code_window": [
" ctrl = createController();\n",
" controller = ctrl;\n",
" this.abortSignal = controller.signal;\n",
"\n",
" const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {\n",
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" const runPhase = async (phaseName: RenderPhase, phaseFn?: () => MaybePromise<void>) => {\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 520
}
|
import { action } from '@storybook/addon-actions';
import Button from '../components/Button.svelte';
export default {
title: 'Addon/Actions',
};
export const ActionOnComponentMethod = () => ({
Component: Button,
props: {
text: 'Custom text',
},
on: {
click: action('I am logging in the actions tab too'),
},
});
ActionOnComponentMethod.storyName = 'Action on component method';
|
examples/svelte-kitchen-sink/src/stories/addon-actions.stories.js
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001769182999851182,
0.00017459811351727694,
0.00017227792704943568,
0.00017459811351727694,
0.0000023201864678412676
] |
{
"id": 4,
"code_window": [
" ctrl = createController();\n",
" controller = ctrl;\n",
" this.abortSignal = controller.signal;\n",
"\n",
" const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {\n",
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" const runPhase = async (phaseName: RenderPhase, phaseFn?: () => MaybePromise<void>) => {\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 520
}
|
module.exports = {
logLevel: 'debug',
stories: ['../src/**/*.stories.@(ts|mdx)'],
addons: [
'@storybook/addon-docs',
'@storybook/addon-controls',
'@storybook/addon-a11y',
'@storybook/addon-actions',
'@storybook/addon-backgrounds',
'@storybook/addon-interactions',
'@storybook/addon-links',
'@storybook/addon-storysource',
'@storybook/addon-viewport',
'@storybook/addon-toolbars',
],
core: {
builder: 'webpack4',
},
};
|
examples/web-components-kitchen-sink/.storybook/main.js
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017489268793724477,
0.00017489201854914427,
0.000174891363712959,
0.00017489201854914427,
6.621521109195783e-10
] |
{
"id": 4,
"code_window": [
" ctrl = createController();\n",
" controller = ctrl;\n",
" this.abortSignal = controller.signal;\n",
"\n",
" const runPhase = async (phaseName: RenderPhase, phaseFn: () => MaybePromise<void>) => {\n",
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" const runPhase = async (phaseName: RenderPhase, phaseFn?: () => MaybePromise<void>) => {\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 520
}
|
{
"application-template-wrapper": false,
"jquery-integration": false,
"template-only-glimmer-components": true
}
|
examples/ember-cli/config/optional-features.json
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001723347813822329,
0.0001723347813822329,
0.0001723347813822329,
0.0001723347813822329,
0
] |
{
"id": 5,
"code_window": [
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" await phaseFn();\n",
" if (ctrl.signal.aborted) {\n",
" phase = 'aborted';\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (phaseFn) await phaseFn();\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 523
}
|
/* eslint-disable no-underscore-dangle */
import { addons, Channel, StoryId } from '@storybook/addons';
import { once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, LogItem } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
LOCK: 'instrumenter/lock',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
export interface Options {
intercept?: boolean | ((method: string, path: Array<string | CallRef>) => boolean);
retain?: boolean;
mutate?: boolean;
path?: Array<string | CallRef>;
getArgs?: (call: Call, state: State) => Call['args'];
}
export interface State {
renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';
isDebugging: boolean;
cursor: number;
calls: Call[];
shadowCalls: Call[];
callRefsByResult: Map<any, CallRef & { retain: boolean }>;
chainedCallIds: Set<Call['id']>;
parentCall?: Call;
playUntil?: Call['id'];
resolvers: Record<Call['id'], Function>;
syncTimeout: ReturnType<typeof setTimeout>;
forwardedException?: Error;
}
export type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentCall: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
forwardedException: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({ storyId, isDebugging }: { storyId?: StoryId; isDebugging?: boolean }) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.channel.emit(EVENTS.SYNC, this.getLog(storyId));
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging, forwardedException } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'completed') {
this.setState(storyId, { isDebugging: false, forwardedException: undefined });
// Rethrow any unhandled forwarded exception so it doesn't go unnoticed.
if (forwardedException) throw forwardedException;
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, state: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const { isDebugging } = this.getState(storyId);
const log = this.getLog(storyId);
const next = isDebugging
? log.findIndex(({ state }) => state === CallStates.WAITING)
: log.length;
start({ storyId, playUntil: log[next - 2]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall) {
const nextCallId = this.getLog(storyId).find(({ state }) => state === CallStates.WAITING)
?.callId;
if (shadowCall.id !== nextCallId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, []);
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if (call.interceptable && !seen.has(call.id) && !seen.has(call.parentId)) {
acc.unshift({ callId: call.id, state: call.state });
seen.add(call.id);
if (call.parentId) {
seen.add(call.parentId);
}
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const index = this.getState(storyId).cursor;
this.setState(storyId, { cursor: index + 1 });
const id = `${storyId} [${index}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, path, method, storyId, args, interceptable, retain };
const result = (interceptable ? this.intercept : this.invoke).call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.channel.emit(EVENTS.LOCK, false);
this.setState(call.storyId, ({ resolvers }) => ({
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.channel.emit(EVENTS.LOCK, true);
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { parentCall, callRefsByResult, forwardedException, renderPhase } = this.getState(
call.storyId
);
const callWithParent = { ...call, parentId: parentCall?.id };
const info: Call = {
...callWithParent,
// Map args that originate from a tracked function call to a call reference to enable nesting.
// These values are often not fully serializable anyway (e.g. HTML elements).
args: call.args.map((arg) => {
if (callRefsByResult.has(arg)) {
return callRefsByResult.get(arg);
}
if (arg instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = arg;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
return arg;
}),
};
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: unknown) => {
if (e instanceof Error) {
const { name, message, stack } = e;
const exception = { name, message, stack, callId: call.id };
this.sync({ ...info, state: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (call.interceptable && e !== alreadyCompletedException) {
throw IGNORED_EXCEPTION;
}
// Non-interceptable calls need their exceptions forwarded to the next interceptable call.
// In case no interceptable call picks it up, it'll get rethrown in the "completed" phase.
this.setState(call.storyId, { forwardedException: e });
return e;
}
throw e;
};
try {
// An earlier, non-interceptable call might have forwarded an exception.
if (forwardedException) {
this.setState(call.storyId, { forwardedException: undefined });
throw forwardedException;
}
if (renderPhase === 'completed' && !call.retain) {
throw alreadyCompletedException;
}
const finalArgs = options.getArgs
? options.getArgs(callWithParent, this.getState(call.storyId))
: call.args;
const result = fn(
// Wrap any callback functions to provide a way to access their "parent" call.
...finalArgs.map((arg: any) => {
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
const prev = this.getState(call.storyId).parentCall;
this.setState(call.storyId, { parentCall: call });
const res = arg(...args);
this.setState(call.storyId, { parentCall: prev });
return res;
};
})
);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.sync({
...info,
state: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.sync({ ...info, state: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
sync(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => ({
calls: calls.concat(call),
syncTimeout: setTimeout(() => this.channel.emit(EVENTS.SYNC, this.getLog(call.storyId)), 0),
}));
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe.
if (global.window.parent === global.window) return obj;
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}
|
lib/instrumenter/src/instrumenter.ts
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.009721982292830944,
0.00042706189560703933,
0.0001615214569028467,
0.00017495156498625875,
0.0013080061180517077
] |
{
"id": 5,
"code_window": [
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" await phaseFn();\n",
" if (ctrl.signal.aborted) {\n",
" phase = 'aborted';\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (phaseFn) await phaseFn();\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 523
}
|
import type { StoriesHash, State } from '@storybook/api';
import { ControllerStateAndHelpers } from 'downshift';
export type Refs = State['refs'];
export type RefType = Refs[keyof Refs];
export type Item = StoriesHash[keyof StoriesHash];
export type Dataset = Record<string, Item>;
export interface CombinedDataset {
hash: Refs;
entries: [string, RefType][];
}
export interface ItemRef {
itemId: string;
refId: string;
}
export interface StoryRef {
storyId: string;
refId: string;
}
export type Highlight = ItemRef | null;
export type Selection = StoryRef | null;
export interface Match {
value: string;
indices: [number, number][];
key: 'name' | 'path';
arrayIndex: number;
}
export function isCloseType(x: any): x is CloseType {
return !!(x && x.closeMenu);
}
export function isClearType(x: any): x is ClearType {
return !!(x && x.clearLastViewed);
}
export function isExpandType(x: any): x is ExpandType {
return !!(x && x.showAll);
}
export function isSearchResult(x: any): x is SearchResult {
return !!(x && x.item);
}
export interface CloseType {
closeMenu: () => void;
}
export interface ClearType {
clearLastViewed: () => void;
}
export interface ExpandType {
showAll: () => void;
totalCount: number;
moreCount: number;
}
export type SearchItem = Item & { refId: string; path: string[] };
export type SearchResult = Fuse.FuseResultWithMatches<SearchItem> &
Fuse.FuseResultWithScore<SearchItem>;
export type DownshiftItem = SearchResult | ExpandType | ClearType | CloseType;
export type SearchChildrenFn = (args: {
query: string;
results: DownshiftItem[];
isBrowsing: boolean;
closeMenu: (cb?: () => void) => void;
getMenuProps: ControllerStateAndHelpers<DownshiftItem>['getMenuProps'];
getItemProps: ControllerStateAndHelpers<DownshiftItem>['getItemProps'];
highlightedIndex: number | null;
}) => React.ReactNode;
|
lib/ui/src/components/sidebar/types.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00019968952983617783,
0.00017641749582253397,
0.00017068632587324828,
0.00017365504754707217,
0.000008912642442737706
] |
{
"id": 5,
"code_window": [
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" await phaseFn();\n",
" if (ctrl.signal.aborted) {\n",
" phase = 'aborted';\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (phaseFn) await phaseFn();\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 523
}
|
import { getFrameworks } from './frameworks';
const REACT = {
'@storybook/react': '5.2.5',
};
const VUE = {
'@storybook/vue': '5.2.5',
};
const NONE = {
'@storybook/addons': '5.2.5',
lodash: '^4.17.15',
};
describe('getFrameworks', () => {
it('single framework', () => {
const frameworks = getFrameworks({
dependencies: NONE,
devDependencies: REACT,
});
expect(frameworks).toEqual(['react']);
});
it('multi-framework', () => {
const frameworks = getFrameworks({
dependencies: VUE,
devDependencies: REACT,
});
expect(frameworks.sort()).toEqual(['react', 'vue']);
});
it('no deps', () => {
const frameworks = getFrameworks({});
expect(frameworks).toEqual([]);
});
it('no framework', () => {
const frameworks = getFrameworks({
dependencies: NONE,
});
expect(frameworks).toEqual([]);
});
});
|
lib/postinstall/src/frameworks.test.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.0001780883176252246,
0.00017324773943983018,
0.00016394500562455505,
0.0001763374311849475,
0.000005184378551348345
] |
{
"id": 5,
"code_window": [
" phase = phaseName;\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" await phaseFn();\n",
" if (ctrl.signal.aborted) {\n",
" phase = 'aborted';\n",
" this.channel.emit(Events.STORY_RENDER_PHASE_CHANGED, { newPhase: phase, storyId: id });\n",
" }\n",
" };\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (phaseFn) await phaseFn();\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "replace",
"edit_start_line_idx": 523
}
|
import React from 'react';
import PropTypes from 'prop-types';
export const Component = (props) => <>JSON.stringify(props)</>;
Component.propTypes = {
optionalObject: PropTypes.object,
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number,
}),
optionalObjectWithStrictShape: PropTypes.exact({
name: PropTypes.string,
quantity: PropTypes.number,
}),
};
|
addons/docs/src/lib/convert/__testfixtures__/proptypes/objects.js
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017663663311395794,
0.00017553649377077818,
0.00017443635442759842,
0.00017553649377077818,
0.0000011001393431797624
] |
{
"id": 6,
"code_window": [
"\n",
" if (forceRemount && playFunction) {\n",
" await runPhase('playing', () => playFunction(renderContext.storyContext));\n",
" if (ctrl.signal.aborted) return;\n",
" }\n",
"\n",
" await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await runPhase('played');\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "add",
"edit_start_line_idx": 562
}
|
/* eslint-disable no-underscore-dangle */
import { addons, Channel, StoryId } from '@storybook/addons';
import { once } from '@storybook/client-logger';
import {
FORCE_REMOUNT,
IGNORED_EXCEPTION,
SET_CURRENT_STORY,
STORY_RENDER_PHASE_CHANGED,
} from '@storybook/core-events';
import global from 'global';
import { Call, CallRef, CallStates, LogItem } from './types';
export const EVENTS = {
CALL: 'instrumenter/call',
SYNC: 'instrumenter/sync',
LOCK: 'instrumenter/lock',
START: 'instrumenter/start',
BACK: 'instrumenter/back',
GOTO: 'instrumenter/goto',
NEXT: 'instrumenter/next',
END: 'instrumenter/end',
};
export interface Options {
intercept?: boolean | ((method: string, path: Array<string | CallRef>) => boolean);
retain?: boolean;
mutate?: boolean;
path?: Array<string | CallRef>;
getArgs?: (call: Call, state: State) => Call['args'];
}
export interface State {
renderPhase: 'loading' | 'rendering' | 'playing' | 'completed' | 'aborted';
isDebugging: boolean;
cursor: number;
calls: Call[];
shadowCalls: Call[];
callRefsByResult: Map<any, CallRef & { retain: boolean }>;
chainedCallIds: Set<Call['id']>;
parentCall?: Call;
playUntil?: Call['id'];
resolvers: Record<Call['id'], Function>;
syncTimeout: ReturnType<typeof setTimeout>;
forwardedException?: Error;
}
export type PatchedObj<TObj> = {
[Property in keyof TObj]: TObj[Property] & { __originalFn__: PatchedObj<TObj> };
};
const alreadyCompletedException = new Error(
`This function ran after the play function completed. Did you forget to \`await\` it?`
);
const isObject = (o: unknown) => Object.prototype.toString.call(o) === '[object Object]';
const isModule = (o: unknown) => Object.prototype.toString.call(o) === '[object Module]';
const isInstrumentable = (o: unknown) => {
if (!isObject(o) && !isModule(o)) return false;
if (o.constructor === undefined) return true;
const proto = o.constructor.prototype;
if (!isObject(proto)) return false;
if (Object.prototype.hasOwnProperty.call(proto, 'isPrototypeOf') === false) return false;
return true;
};
const construct = (obj: any) => {
try {
return new obj.constructor();
} catch (e) {
return {};
}
};
const getInitialState = (): State => ({
renderPhase: undefined,
isDebugging: false,
cursor: 0,
calls: [],
shadowCalls: [],
callRefsByResult: new Map(),
chainedCallIds: new Set<Call['id']>(),
parentCall: undefined,
playUntil: undefined,
resolvers: {},
syncTimeout: undefined,
forwardedException: undefined,
});
const getRetainedState = (state: State, isDebugging = false) => {
const calls = (isDebugging ? state.shadowCalls : state.calls).filter((call) => call.retain);
if (!calls.length) return undefined;
const callRefsByResult = new Map(
Array.from(state.callRefsByResult.entries()).filter(([, ref]) => ref.retain)
);
return { cursor: calls.length, calls, callRefsByResult };
};
/**
* This class is not supposed to be used directly. Use the `instrument` function below instead.
*/
export class Instrumenter {
channel: Channel;
initialized = false;
// State is tracked per story to deal with multiple stories on the same canvas (i.e. docs mode)
state: Record<StoryId, State>;
constructor() {
this.channel = addons.getChannel();
// Restore state from the parent window in case the iframe was reloaded.
this.state = global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ || {};
// When called from `start`, isDebugging will be true
const resetState = ({ storyId, isDebugging }: { storyId?: StoryId; isDebugging?: boolean }) => {
const state = this.getState(storyId);
this.setState(storyId, {
...getInitialState(),
...getRetainedState(state, isDebugging),
shadowCalls: isDebugging ? state.shadowCalls : [],
chainedCallIds: isDebugging ? state.chainedCallIds : new Set<Call['id']>(),
playUntil: isDebugging ? state.playUntil : undefined,
isDebugging,
});
// Don't sync while debugging, as it'll cause flicker.
if (!isDebugging) this.channel.emit(EVENTS.SYNC, this.getLog(storyId));
};
// A forceRemount might be triggered for debugging (on `start`), or elsewhere in Storybook.
this.channel.on(FORCE_REMOUNT, resetState);
// Start with a clean slate before playing after a remount, and stop debugging when done.
this.channel.on(STORY_RENDER_PHASE_CHANGED, ({ storyId, newPhase }) => {
const { isDebugging, forwardedException } = this.getState(storyId);
this.setState(storyId, { renderPhase: newPhase });
if (newPhase === 'playing') {
resetState({ storyId, isDebugging });
}
if (newPhase === 'completed') {
this.setState(storyId, { isDebugging: false, forwardedException: undefined });
// Rethrow any unhandled forwarded exception so it doesn't go unnoticed.
if (forwardedException) throw forwardedException;
}
});
// Trash non-retained state and clear the log when switching stories, but not on initial boot.
this.channel.on(SET_CURRENT_STORY, () => {
if (this.initialized) this.cleanup();
else this.initialized = true;
});
const start = ({ storyId, playUntil }: { storyId: string; playUntil?: Call['id'] }) => {
if (!this.getState(storyId).isDebugging) {
this.setState(storyId, ({ calls }) => ({
calls: [],
shadowCalls: calls.map((call) => ({ ...call, state: CallStates.WAITING })),
isDebugging: true,
}));
}
const log = this.getLog(storyId);
this.setState(storyId, ({ shadowCalls }) => {
const firstRowIndex = shadowCalls.findIndex((call) => call.id === log[0].callId);
return {
playUntil:
playUntil ||
shadowCalls
.slice(0, firstRowIndex)
.filter((call) => call.interceptable)
.slice(-1)[0]?.id,
};
});
// Force remount may trigger a page reload if the play function can't be aborted.
this.channel.emit(FORCE_REMOUNT, { storyId, isDebugging: true });
};
const back = ({ storyId }: { storyId: string }) => {
const { isDebugging } = this.getState(storyId);
const log = this.getLog(storyId);
const next = isDebugging
? log.findIndex(({ state }) => state === CallStates.WAITING)
: log.length;
start({ storyId, playUntil: log[next - 2]?.callId });
};
const goto = ({ storyId, callId }: { storyId: string; callId: Call['id'] }) => {
const { calls, shadowCalls, resolvers } = this.getState(storyId);
const call = calls.find(({ id }) => id === callId);
const shadowCall = shadowCalls.find(({ id }) => id === callId);
if (!call && shadowCall) {
const nextCallId = this.getLog(storyId).find(({ state }) => state === CallStates.WAITING)
?.callId;
if (shadowCall.id !== nextCallId) this.setState(storyId, { playUntil: shadowCall.id });
Object.values(resolvers).forEach((resolve) => resolve());
} else {
start({ storyId, playUntil: callId });
}
};
const next = ({ storyId }: { storyId: string }) => {
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
const end = ({ storyId }: { storyId: string }) => {
this.setState(storyId, { playUntil: undefined, isDebugging: false });
Object.values(this.getState(storyId).resolvers).forEach((resolve) => resolve());
};
this.channel.on(EVENTS.START, start);
this.channel.on(EVENTS.BACK, back);
this.channel.on(EVENTS.GOTO, goto);
this.channel.on(EVENTS.NEXT, next);
this.channel.on(EVENTS.END, end);
}
getState(storyId: StoryId) {
return this.state[storyId] || getInitialState();
}
setState(storyId: StoryId, update: Partial<State> | ((state: State) => Partial<State>)) {
const state = this.getState(storyId);
const patch = typeof update === 'function' ? update(state) : update;
this.state = { ...this.state, [storyId]: { ...state, ...patch } };
// Track state on the parent window so we can reload the iframe without losing state.
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
cleanup() {
// Reset stories with retained state to their initial state, and drop the rest.
this.state = Object.entries(this.state).reduce((acc, [storyId, state]) => {
const retainedState = getRetainedState(state);
if (!retainedState) return acc;
acc[storyId] = Object.assign(getInitialState(), retainedState);
return acc;
}, {} as Record<StoryId, State>);
this.channel.emit(EVENTS.SYNC, []);
global.window.parent.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER_STATE__ = this.state;
}
getLog(storyId: string): LogItem[] {
const { calls, shadowCalls } = this.getState(storyId);
const merged = [...shadowCalls];
calls.forEach((call, index) => {
merged[index] = call;
});
const seen = new Set();
return merged.reduceRight<LogItem[]>((acc, call) => {
call.args.forEach((arg) => {
if (arg?.__callId__) {
seen.add(arg.__callId__);
}
});
call.path.forEach((node) => {
if ((node as CallRef).__callId__) {
seen.add((node as CallRef).__callId__);
}
});
if (call.interceptable && !seen.has(call.id) && !seen.has(call.parentId)) {
acc.unshift({ callId: call.id, state: call.state });
seen.add(call.id);
if (call.parentId) {
seen.add(call.parentId);
}
}
return acc;
}, []);
}
// Traverses the object structure to recursively patch all function properties.
// Returns the original object, or a new object with the same constructor,
// depending on whether it should mutate.
instrument<TObj extends { [x: string]: any }>(obj: TObj, options: Options): PatchedObj<TObj> {
if (!isInstrumentable(obj)) return obj;
const { mutate = false, path = [] } = options;
return Object.keys(obj).reduce(
(acc, key) => {
const value = (obj as Record<string, any>)[key];
// Nothing to patch, but might be instrumentable, so we recurse
if (typeof value !== 'function') {
acc[key] = this.instrument(value, { ...options, path: path.concat(key) });
return acc;
}
// Already patched, so we pass through unchanged
if (typeof value.__originalFn__ === 'function') {
acc[key] = value;
return acc;
}
// Patch the function and mark it "patched" by adding a reference to the original function
acc[key] = (...args: any[]) => this.track(key, value, args, options);
acc[key].__originalFn__ = value;
// Reuse the original name as the patched function's name
Object.defineProperty(acc[key], 'name', { value: key, writable: false });
// Deal with functions that also act like an object
if (Object.keys(value).length > 0) {
Object.assign(
acc[key],
this.instrument({ ...value }, { ...options, path: path.concat(key) })
);
}
return acc;
},
mutate ? obj : construct(obj)
);
}
// Monkey patch an object method to record calls.
// Returns a function that invokes the original function, records the invocation ("call") and
// returns the original result.
track(method: string, fn: Function, args: any[], options: Options) {
const storyId: StoryId =
args?.[0]?.__storyId__ || global.window.__STORYBOOK_PREVIEW__?.urlStore?.selection?.storyId;
const index = this.getState(storyId).cursor;
this.setState(storyId, { cursor: index + 1 });
const id = `${storyId} [${index}] ${method}`;
const { path = [], intercept = false, retain = false } = options;
const interceptable = typeof intercept === 'function' ? intercept(method, path) : intercept;
const call: Call = { id, path, method, storyId, args, interceptable, retain };
const result = (interceptable ? this.intercept : this.invoke).call(this, fn, call, options);
return this.instrument(result, { ...options, mutate: true, path: [{ __callId__: call.id }] });
}
intercept(fn: Function, call: Call, options: Options) {
const { chainedCallIds, isDebugging, playUntil } = this.getState(call.storyId);
// For a "jump to step" action, continue playing until we hit a call by that ID.
// For chained calls, we can only return a Promise for the last call in the chain.
const isChainedUpon = chainedCallIds.has(call.id);
if (!isDebugging || isChainedUpon || playUntil) {
if (playUntil === call.id) {
this.setState(call.storyId, { playUntil: undefined });
}
return this.invoke(fn, call, options);
}
// Instead of invoking the function, defer the function call until we continue playing.
return new Promise((resolve) => {
this.channel.emit(EVENTS.LOCK, false);
this.setState(call.storyId, ({ resolvers }) => ({
resolvers: { ...resolvers, [call.id]: resolve },
}));
}).then(() => {
this.channel.emit(EVENTS.LOCK, true);
this.setState(call.storyId, (state) => {
const { [call.id]: _, ...resolvers } = state.resolvers;
return { resolvers };
});
return this.invoke(fn, call, options);
});
}
invoke(fn: Function, call: Call, options: Options) {
const { abortSignal } = global.window.__STORYBOOK_PREVIEW__ || {};
if (abortSignal && abortSignal.aborted) throw IGNORED_EXCEPTION;
const { parentCall, callRefsByResult, forwardedException, renderPhase } = this.getState(
call.storyId
);
const callWithParent = { ...call, parentId: parentCall?.id };
const info: Call = {
...callWithParent,
// Map args that originate from a tracked function call to a call reference to enable nesting.
// These values are often not fully serializable anyway (e.g. HTML elements).
args: call.args.map((arg) => {
if (callRefsByResult.has(arg)) {
return callRefsByResult.get(arg);
}
if (arg instanceof global.window.HTMLElement) {
const { prefix, localName, id, classList, innerText } = arg;
const classNames = Array.from(classList);
return { __element__: { prefix, localName, id, classNames, innerText } };
}
return arg;
}),
};
// Mark any ancestor calls as "chained upon" so we won't attempt to defer it later.
call.path.forEach((ref: any) => {
if (ref?.__callId__) {
this.setState(call.storyId, ({ chainedCallIds }) => ({
chainedCallIds: new Set(Array.from(chainedCallIds).concat(ref.__callId__)),
}));
}
});
const handleException = (e: unknown) => {
if (e instanceof Error) {
const { name, message, stack } = e;
const exception = { name, message, stack, callId: call.id };
this.sync({ ...info, state: CallStates.ERROR, exception });
// Always track errors to their originating call.
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[e, { __callId__: call.id, retain: call.retain }],
]),
}));
// We need to throw to break out of the play function, but we don't want to trigger a redbox
// so we throw an ignoredException, which is caught and silently ignored by Storybook.
if (call.interceptable && e !== alreadyCompletedException) {
throw IGNORED_EXCEPTION;
}
// Non-interceptable calls need their exceptions forwarded to the next interceptable call.
// In case no interceptable call picks it up, it'll get rethrown in the "completed" phase.
this.setState(call.storyId, { forwardedException: e });
return e;
}
throw e;
};
try {
// An earlier, non-interceptable call might have forwarded an exception.
if (forwardedException) {
this.setState(call.storyId, { forwardedException: undefined });
throw forwardedException;
}
if (renderPhase === 'completed' && !call.retain) {
throw alreadyCompletedException;
}
const finalArgs = options.getArgs
? options.getArgs(callWithParent, this.getState(call.storyId))
: call.args;
const result = fn(
// Wrap any callback functions to provide a way to access their "parent" call.
...finalArgs.map((arg: any) => {
if (typeof arg !== 'function' || Object.keys(arg).length) return arg;
return (...args: any) => {
const prev = this.getState(call.storyId).parentCall;
this.setState(call.storyId, { parentCall: call });
const res = arg(...args);
this.setState(call.storyId, { parentCall: prev });
return res;
};
})
);
// Track the result so we can trace later uses of it back to the originating call.
// Primitive results (undefined, null, boolean, string, number, BigInt) are ignored.
if (result && ['object', 'function', 'symbol'].includes(typeof result)) {
this.setState(call.storyId, (state) => ({
callRefsByResult: new Map([
...Array.from(state.callRefsByResult.entries()),
[result, { __callId__: call.id, retain: call.retain }],
]),
}));
}
this.sync({
...info,
state: result instanceof Promise ? CallStates.ACTIVE : CallStates.DONE,
});
if (result instanceof Promise) {
return result.then((value) => {
this.sync({ ...info, state: CallStates.DONE });
return value;
}, handleException);
}
return result;
} catch (e) {
return handleException(e);
}
}
// Sends the call info and log to the manager.
// Uses a 0ms debounce because this might get called many times in one tick.
sync(call: Call) {
clearTimeout(this.getState(call.storyId).syncTimeout);
this.channel.emit(EVENTS.CALL, call);
this.setState(call.storyId, ({ calls }) => ({
calls: calls.concat(call),
syncTimeout: setTimeout(() => this.channel.emit(EVENTS.SYNC, this.getLog(call.storyId)), 0),
}));
}
}
/**
* Instruments an object or module by traversing its properties, patching any functions (methods)
* to enable debugging. Patched functions will emit a `call` event when invoked.
* When intercept = true, patched functions will return a Promise when the debugger stops before
* this function. As such, "interceptable" functions will have to be `await`-ed.
*/
export function instrument<TObj extends Record<string, any>>(
obj: TObj,
options: Options = {}
): TObj {
try {
// Don't do any instrumentation if not loaded in an iframe.
if (global.window.parent === global.window) return obj;
// Only create an instance if we don't have one (singleton) yet.
if (!global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__) {
global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__ = new Instrumenter();
}
const instrumenter: Instrumenter = global.window.__STORYBOOK_ADDON_INTERACTIONS_INSTRUMENTER__;
return instrumenter.instrument(obj, options);
} catch (e) {
// Access to the parent window might fail due to CORS restrictions.
once.warn(e);
return obj;
}
}
|
lib/instrumenter/src/instrumenter.ts
| 1 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.007044853642582893,
0.0006791157065890729,
0.00016154133481904864,
0.00017530775221530348,
0.0013547946000471711
] |
{
"id": 6,
"code_window": [
"\n",
" if (forceRemount && playFunction) {\n",
" await runPhase('playing', () => playFunction(renderContext.storyContext));\n",
" if (ctrl.signal.aborted) return;\n",
" }\n",
"\n",
" await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await runPhase('played');\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "add",
"edit_start_line_idx": 562
}
|
import global from 'global';
import renderStorybookUI from '@storybook/ui';
import Provider from './provider';
import { importPolyfills } from './conditional-polyfills';
const { document } = global;
importPolyfills().then(() => {
const rootEl = document.getElementById('root');
renderStorybookUI(rootEl, new Provider());
});
|
lib/core-client/src/manager/index.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017728931561578065,
0.00017556975944899023,
0.0001738502032821998,
0.00017556975944899023,
0.0000017195561667904258
] |
{
"id": 6,
"code_window": [
"\n",
" if (forceRemount && playFunction) {\n",
" await runPhase('playing', () => playFunction(renderContext.storyContext));\n",
" if (ctrl.signal.aborted) return;\n",
" }\n",
"\n",
" await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await runPhase('played');\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "add",
"edit_start_line_idx": 562
}
|
```md
<!--- YourComponent.stories.mdx -->
import { Meta, Story, Canvas } from '@storybook/addon-docs';
import YourComponent from './your-component.component';
<Meta title="Example of how to use argTypes and functions" component={YourComponent}/>
<!---👇 A function to apply some computations -->
export const someFunction = (valuePropertyA, valuePropertyB) => {
<!--- Makes some computations and returns something -->
};
export const Template = (args)=>{
const { propertyA, propertyB } = args;
<!---👇 Assigns the function result to a variable -->
const someFunctionResult = someFunction(propertyA, propertyB);
return {
props: {
...args,
someProperty: someFunctionResult,
},
};
}
<Canvas>
<Story
name="A complex case with a function"
argTypes={{
propertyA: {
options: [
'Item One',
'Item Two',
'Item Three',
],
},
propertyB: {
options: [
'Another Item One',
'Another Item Two',
'Another Item Three',
],
},
}}
args={{
propertyA: 'Item One',
propertyB: 'Another Item One',
}}>
{Template.bind({})}
</Story>
</Canvas>
```
|
docs/snippets/angular/component-story-custom-args-complex.mdx.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017601221043150872,
0.00017054153431672603,
0.00016461183258797973,
0.00016966991825029254,
0.000003931804258172633
] |
{
"id": 6,
"code_window": [
"\n",
" if (forceRemount && playFunction) {\n",
" await runPhase('playing', () => playFunction(renderContext.storyContext));\n",
" if (ctrl.signal.aborted) return;\n",
" }\n",
"\n",
" await runPhase('completed', () => this.channel.emit(Events.STORY_RENDERED, id));\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" await runPhase('played');\n"
],
"file_path": "lib/preview-web/src/PreviewWeb.tsx",
"type": "add",
"edit_start_line_idx": 562
}
|
import {
getPreviewBodyTemplate,
getPreviewHeadTemplate,
getManagerMainTemplate,
getPreviewMainTemplate,
loadCustomBabelConfig,
getStorybookBabelConfig,
loadEnvs,
Options,
} from '@storybook/core-common';
export const babel = async (_: unknown, options: Options) => {
const { configDir, presets } = options;
if (options.features?.babelModeV7) {
return presets.apply('babelDefault', {}, options);
}
return loadCustomBabelConfig(
configDir,
() => presets.apply('babelDefault', getStorybookBabelConfig(), options) as any
);
};
export const logLevel = (previous: any, options: Options) => previous || options.loglevel || 'info';
export const previewHead = async (base: any, { configDir, presets }: Options) => {
const interpolations = await presets.apply<Record<string, string>>('env');
return getPreviewHeadTemplate(configDir, interpolations);
};
export const env = async () => {
return loadEnvs({ production: true }).raw;
};
export const previewBody = async (base: any, { configDir, presets }: Options) => {
const interpolations = await presets.apply<Record<string, string>>('env');
return getPreviewBodyTemplate(configDir, interpolations);
};
export const previewMainTemplate = () => getPreviewMainTemplate();
export const managerMainTemplate = () => getManagerMainTemplate();
export const previewEntries = (entries: any[] = [], options: { modern?: boolean }) => {
if (!options.modern)
entries.push(require.resolve('@storybook/core-client/dist/esm/globals/polyfills'));
entries.push(require.resolve('@storybook/core-client/dist/esm/globals/globals'));
return entries;
};
export const typescript = () => ({
check: false,
// 'react-docgen' faster but produces lower quality typescript results
reactDocgen: 'react-docgen-typescript',
reactDocgenTypescriptOptions: {
shouldExtractLiteralValuesFromEnum: true,
shouldRemoveUndefinedFromOptional: true,
propFilter: (prop: any) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
// NOTE: this default cannot be changed
savePropValueAsString: true,
},
});
export const features = async (existing: Record<string, boolean>) => ({
...existing,
postcss: true,
});
|
lib/core-server/src/presets/common-preset.ts
| 0 |
https://github.com/storybookjs/storybook/commit/13512c68c6d8ee5b10663bd67e192b9b690191dc
|
[
0.00017600264982320368,
0.00017326332454103976,
0.00016950849385466427,
0.00017363914230372757,
0.0000024302603378600907
] |
{
"id": 0,
"code_window": [
"package main\n",
"\n",
"import (\n",
"\t\"os\"\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/build/env\"\n",
"\t\"github.com/grafana/grafana/pkg/build/git\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"fmt\"\n",
"\t\"log\"\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 3
}
|
package main
import (
"os"
"strconv"
"github.com/grafana/grafana/pkg/build/env"
"github.com/grafana/grafana/pkg/build/git"
"github.com/urfave/cli/v2"
)
// checkOpts are options used to create a new GitHub check for the enterprise downstream test.
type checkOpts struct {
SHA string
URL string
Branch string
PR int
}
func getCheckOpts(args []string) (*checkOpts, error) {
branch, ok := env.Lookup("DRONE_SOURCE_BRANCH", args)
if !ok {
return nil, cli.Exit("Unable to retrieve build source branch", 1)
}
var (
rgx = git.PRCheckRegexp()
matches = rgx.FindStringSubmatch(branch)
)
sha, ok := env.Lookup("SOURCE_COMMIT", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve source commit", 1)
}
sha = matches[2]
}
url, ok := env.Lookup("DRONE_BUILD_LINK", args)
if !ok {
return nil, cli.Exit(`missing environment variable "DRONE_BUILD_LINK"`, 1)
}
prStr, ok := env.Lookup("OSS_PULL_REQUEST", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve PR number", 1)
}
prStr = matches[1]
}
pr, err := strconv.Atoi(prStr)
if err != nil {
return nil, err
}
return &checkOpts{
Branch: branch,
PR: pr,
SHA: sha,
URL: url,
}, nil
}
// EnterpriseCheckBegin creates the GitHub check and signals the beginning of the downstream build / test process
func EnterpriseCheckBegin(c *cli.Context) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
if _, err = git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, "pending"); err != nil {
return err
}
return nil
}
func EnterpriseCheckSuccess(c *cli.Context) error {
return completeEnterpriseCheck(c, true)
}
func EnterpriseCheckFail(c *cli.Context) error {
return completeEnterpriseCheck(c, false)
}
func completeEnterpriseCheck(c *cli.Context, success bool) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
// Update the pull request labels
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
status := "failure"
if success {
status = "success"
}
// Update the GitHub check...
if _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {
return err
}
// Delete branch if needed
if git.PRCheckRegexp().MatchString(opts.Branch) {
if err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {
return nil
}
}
label := "enterprise-failed"
if success {
label = "enterprise-ok"
}
return git.AddLabelToPR(ctx, client.Issues, opts.PR, label)
}
|
pkg/build/cmd/enterprisecheck.go
| 1 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.957490086555481,
0.07385954260826111,
0.00016636175860185176,
0.0002010982861975208,
0.2550821900367737
] |
{
"id": 0,
"code_window": [
"package main\n",
"\n",
"import (\n",
"\t\"os\"\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/build/env\"\n",
"\t\"github.com/grafana/grafana/pkg/build/git\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"fmt\"\n",
"\t\"log\"\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 3
}
|
import { rangeUtil, dateTime } from '@grafana/data';
describe('rangeUtil', () => {
describe('Can get range text described', () => {
it('should handle simple old expression with only amount and unit', () => {
const info = rangeUtil.describeTextRange('5m');
expect(info.display).toBe('Last 5 minutes');
});
it('should have singular when amount is 1', () => {
const info = rangeUtil.describeTextRange('1h');
expect(info.display).toBe('Last 1 hour');
});
it('should handle non default amount', () => {
const info = rangeUtil.describeTextRange('13h');
expect(info.display).toBe('Last 13 hours');
expect(info.from).toBe('now-13h');
});
it('should handle non default future amount', () => {
const info = rangeUtil.describeTextRange('+3h');
expect(info.display).toBe('Next 3 hours');
expect(info.from).toBe('now');
expect(info.to).toBe('now+3h');
});
it('should handle now/d', () => {
const info = rangeUtil.describeTextRange('now/d');
expect(info.display).toBe('Today so far');
});
it('should handle now/w', () => {
const info = rangeUtil.describeTextRange('now/w');
expect(info.display).toBe('This week so far');
});
it('should handle now/M', () => {
const info = rangeUtil.describeTextRange('now/M');
expect(info.display).toBe('This month so far');
});
it('should handle now/y', () => {
const info = rangeUtil.describeTextRange('now/y');
expect(info.display).toBe('This year so far');
});
});
describe('Can get date range described', () => {
it('Date range with simple ranges', () => {
const text = rangeUtil.describeTimeRange({ from: 'now-1h', to: 'now' });
expect(text).toBe('Last 1 hour');
});
it('Date range with rounding ranges', () => {
const text = rangeUtil.describeTimeRange({ from: 'now/d+6h', to: 'now' });
expect(text).toBe('now/d+6h to now');
});
it('Date range with absolute to now', () => {
const text = rangeUtil.describeTimeRange({
from: dateTime([2014, 10, 10, 2, 3, 4]),
to: 'now',
});
expect(text).toBe('2014-11-10 02:03:04 to a few seconds ago');
});
it('Date range with absolute to relative', () => {
const text = rangeUtil.describeTimeRange({
from: dateTime([2014, 10, 10, 2, 3, 4]),
to: 'now-1d',
});
expect(text).toBe('2014-11-10 02:03:04 to a day ago');
});
it('Date range with relative to absolute', () => {
const text = rangeUtil.describeTimeRange({
from: 'now-7d',
to: dateTime([2014, 10, 10, 2, 3, 4]),
});
expect(text).toBe('7 days ago to 2014-11-10 02:03:04');
});
it('Date range with non matching default ranges', () => {
const text = rangeUtil.describeTimeRange({ from: 'now-13h', to: 'now' });
expect(text).toBe('Last 13 hours');
});
it('Date range with from and to both are in now-* format', () => {
const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now-3h' });
expect(text).toBe('now-6h to now-3h');
});
it('Date range with from and to both are either in now-* or now/* format', () => {
const text = rangeUtil.describeTimeRange({
from: 'now/d+6h',
to: 'now-3h',
});
expect(text).toBe('now/d+6h to now-3h');
});
it('Date range with from and to both are either in now-* or now+* format', () => {
const text = rangeUtil.describeTimeRange({ from: 'now-6h', to: 'now+1h' });
expect(text).toBe('now-6h to now+1h');
});
});
});
|
public/app/core/specs/rangeutil.test.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00018369680037721992,
0.00017495971405878663,
0.00017211685189977288,
0.0001743957691360265,
0.0000030445346510532545
] |
{
"id": 0,
"code_window": [
"package main\n",
"\n",
"import (\n",
"\t\"os\"\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/build/env\"\n",
"\t\"github.com/grafana/grafana/pkg/build/git\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"fmt\"\n",
"\t\"log\"\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 3
}
|
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { ComponentProps } from 'react';
import { selectOptionInTest } from 'test/helpers/selectOptionInTest';
import { getLabelSelects } from '../testUtils';
import { LabelFilters, MISSING_LABEL_FILTER_ERROR_MESSAGE } from './LabelFilters';
describe('LabelFilters', () => {
it('renders empty input without labels', async () => {
setup();
expect(screen.getAllByText('Select label')).toHaveLength(1);
expect(screen.getAllByText('Select value')).toHaveLength(1);
expect(screen.getByText(/=/)).toBeInTheDocument();
expect(getAddButton()).toBeInTheDocument();
});
it('renders multiple labels', async () => {
setup({
labelsFilters: [
{ label: 'foo', op: '=', value: 'bar' },
{ label: 'baz', op: '!=', value: 'qux' },
{ label: 'quux', op: '=~', value: 'quuz' },
],
});
expect(screen.getByText(/foo/)).toBeInTheDocument();
expect(screen.getByText(/bar/)).toBeInTheDocument();
expect(screen.getByText(/baz/)).toBeInTheDocument();
expect(screen.getByText(/qux/)).toBeInTheDocument();
expect(screen.getByText(/quux/)).toBeInTheDocument();
expect(screen.getByText(/quuz/)).toBeInTheDocument();
expect(getAddButton()).toBeInTheDocument();
});
it('renders multiple values for regex selectors', async () => {
setup({
labelsFilters: [
{ label: 'bar', op: '!~', value: 'baz|bat|bau' },
{ label: 'foo', op: '!~', value: 'fop|for|fos' },
],
});
expect(screen.getByText(/bar/)).toBeInTheDocument();
expect(screen.getByText(/baz/)).toBeInTheDocument();
expect(screen.getByText(/bat/)).toBeInTheDocument();
expect(screen.getByText(/bau/)).toBeInTheDocument();
expect(screen.getByText(/foo/)).toBeInTheDocument();
expect(screen.getByText(/for/)).toBeInTheDocument();
expect(screen.getByText(/fos/)).toBeInTheDocument();
expect(getAddButton()).toBeInTheDocument();
});
it('adds new label', async () => {
const { onChange } = setup({ labelsFilters: [{ label: 'foo', op: '=', value: 'bar' }] });
await userEvent.click(getAddButton());
expect(screen.getAllByText('Select label')).toHaveLength(1);
expect(screen.getAllByText('Select value')).toHaveLength(1);
const { name, value } = getLabelSelects(1);
await selectOptionInTest(name, 'baz');
await selectOptionInTest(value, 'qux');
expect(onChange).toBeCalledWith([
{ label: 'foo', op: '=', value: 'bar' },
{ label: 'baz', op: '=', value: 'qux' },
]);
});
it('removes label', async () => {
const { onChange } = setup({ labelsFilters: [{ label: 'foo', op: '=', value: 'bar' }] });
await userEvent.click(screen.getByLabelText(/remove/));
expect(onChange).toBeCalledWith([]);
});
it('renders empty input when labels are deleted from outside ', async () => {
const { rerender } = setup({ labelsFilters: [{ label: 'foo', op: '=', value: 'bar' }] });
expect(screen.getByText(/foo/)).toBeInTheDocument();
expect(screen.getByText(/bar/)).toBeInTheDocument();
rerender(
<LabelFilters
onChange={jest.fn()}
onGetLabelNames={jest.fn()}
getLabelValuesAutofillSuggestions={jest.fn()}
onGetLabelValues={jest.fn()}
labelsFilters={[]}
/>
);
expect(screen.getAllByText('Select label')).toHaveLength(1);
expect(screen.getAllByText('Select value')).toHaveLength(1);
expect(screen.getByText(/=/)).toBeInTheDocument();
expect(getAddButton()).toBeInTheDocument();
});
it('shows error when filter with empty strings and label filter is required', async () => {
setup({ labelsFilters: [{ label: '', op: '=', value: '' }], labelFilterRequired: true });
expect(screen.getByText(MISSING_LABEL_FILTER_ERROR_MESSAGE)).toBeInTheDocument();
});
it('shows error when no filter and label filter is required', async () => {
setup({ labelsFilters: [], labelFilterRequired: true });
expect(screen.getByText(MISSING_LABEL_FILTER_ERROR_MESSAGE)).toBeInTheDocument();
});
});
function setup(propOverrides?: Partial<ComponentProps<typeof LabelFilters>>) {
const defaultProps = {
onChange: jest.fn(),
getLabelValues: jest.fn(),
getLabelValuesAutofillSuggestions: async (query: string, labelName?: string) => [
{ label: 'bar', value: 'bar' },
{ label: 'qux', value: 'qux' },
{ label: 'quux', value: 'quux' },
],
onGetLabelNames: async () => [
{ label: 'foo', value: 'foo' },
{ label: 'bar', value: 'bar' },
{ label: 'baz', value: 'baz' },
],
onGetLabelValues: async () => [
{ label: 'bar', value: 'bar' },
{ label: 'qux', value: 'qux' },
{ label: 'quux', value: 'quux' },
],
labelsFilters: [],
};
const props = { ...defaultProps, ...propOverrides };
const { rerender } = render(<LabelFilters {...props} />);
return { ...props, rerender };
}
function getAddButton() {
return screen.getByLabelText(/Add/);
}
|
public/app/plugins/datasource/prometheus/querybuilder/components/LabelFilters.test.tsx
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017818853666540235,
0.00017463839321862906,
0.0001690591307124123,
0.0001758814323693514,
0.000002883194838432246
] |
{
"id": 0,
"code_window": [
"package main\n",
"\n",
"import (\n",
"\t\"os\"\n",
"\t\"strconv\"\n",
"\n",
"\t\"github.com/grafana/grafana/pkg/build/env\"\n",
"\t\"github.com/grafana/grafana/pkg/build/git\"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\"fmt\"\n",
"\t\"log\"\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 3
}
|
FROM debian:buster-slim
ENV DEBIAN_FRONTEND=noninteractive
COPY scripts scripts
COPY install /usr/local
RUN cd scripts && ./deploy.sh
ENV DEBIAN_FRONTEND=newt
|
packages/grafana-toolkit/docker/grafana-plugin-ci-e2e/Dockerfile
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.0002545259485486895,
0.0002545259485486895,
0.0002545259485486895,
0.0002545259485486895,
0
] |
{
"id": 1,
"code_window": [
"\tif _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\t// Delete branch if needed\n",
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\tlog.Printf(\"Checking branch '%s' against '%s'\", git.PRCheckRegexp().String(), opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 115
}
|
package main
import (
"os"
"strconv"
"github.com/grafana/grafana/pkg/build/env"
"github.com/grafana/grafana/pkg/build/git"
"github.com/urfave/cli/v2"
)
// checkOpts are options used to create a new GitHub check for the enterprise downstream test.
type checkOpts struct {
SHA string
URL string
Branch string
PR int
}
func getCheckOpts(args []string) (*checkOpts, error) {
branch, ok := env.Lookup("DRONE_SOURCE_BRANCH", args)
if !ok {
return nil, cli.Exit("Unable to retrieve build source branch", 1)
}
var (
rgx = git.PRCheckRegexp()
matches = rgx.FindStringSubmatch(branch)
)
sha, ok := env.Lookup("SOURCE_COMMIT", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve source commit", 1)
}
sha = matches[2]
}
url, ok := env.Lookup("DRONE_BUILD_LINK", args)
if !ok {
return nil, cli.Exit(`missing environment variable "DRONE_BUILD_LINK"`, 1)
}
prStr, ok := env.Lookup("OSS_PULL_REQUEST", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve PR number", 1)
}
prStr = matches[1]
}
pr, err := strconv.Atoi(prStr)
if err != nil {
return nil, err
}
return &checkOpts{
Branch: branch,
PR: pr,
SHA: sha,
URL: url,
}, nil
}
// EnterpriseCheckBegin creates the GitHub check and signals the beginning of the downstream build / test process
func EnterpriseCheckBegin(c *cli.Context) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
if _, err = git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, "pending"); err != nil {
return err
}
return nil
}
func EnterpriseCheckSuccess(c *cli.Context) error {
return completeEnterpriseCheck(c, true)
}
func EnterpriseCheckFail(c *cli.Context) error {
return completeEnterpriseCheck(c, false)
}
func completeEnterpriseCheck(c *cli.Context, success bool) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
// Update the pull request labels
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
status := "failure"
if success {
status = "success"
}
// Update the GitHub check...
if _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {
return err
}
// Delete branch if needed
if git.PRCheckRegexp().MatchString(opts.Branch) {
if err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {
return nil
}
}
label := "enterprise-failed"
if success {
label = "enterprise-ok"
}
return git.AddLabelToPR(ctx, client.Issues, opts.PR, label)
}
|
pkg/build/cmd/enterprisecheck.go
| 1 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.9983117580413818,
0.08281949162483215,
0.0001642515417188406,
0.0027155792340636253,
0.26461535692214966
] |
{
"id": 1,
"code_window": [
"\tif _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\t// Delete branch if needed\n",
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\tlog.Printf(\"Checking branch '%s' against '%s'\", git.PRCheckRegexp().String(), opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 115
}
|
package supportbundlesimpl
import (
"bytes"
"context"
"fmt"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/supportbundles"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
func dbCollector(sql db.DB) supportbundles.Collector {
collectorFn := func(ctx context.Context) (*supportbundles.SupportItem, error) {
dbType := string(sql.GetDBType())
// buffer writer
bWriter := bytes.NewBuffer(nil)
bWriter.WriteString("# Database information\n\n")
bWriter.WriteString("dbType: " + dbType + " \n")
logItems := make([]migrator.MigrationLog, 0)
version := []string{}
err := sql.WithDbSession(ctx, func(sess *db.Session) error {
rawSQL := ""
if dbType == migrator.MySQL {
rawSQL = "SELECT @@VERSION"
} else if dbType == migrator.Postgres {
rawSQL = "SELECT version()"
} else if dbType == migrator.SQLite {
rawSQL = "SELECT sqlite_version()"
} else {
return fmt.Errorf("unsupported dbType: %s", dbType)
}
return sess.Table("migration_log").SQL(rawSQL).Find(&version)
})
if err != nil {
return nil, err
}
for _, v := range version {
bWriter.WriteString("version: " + v + " \n")
}
errD := sql.WithDbSession(ctx, func(sess *db.Session) error {
return sess.Table("migration_log").Find(&logItems)
})
if errD != nil {
return nil, err
}
bWriter.WriteString("\n## Migration Log\n\n")
for _, logItem := range logItems {
bWriter.WriteString(fmt.Sprintf("**migrationId**: %s \nsuccess: %t \nerror: %s \ntimestamp: %s\n\n",
logItem.MigrationID, logItem.Success, logItem.Error, logItem.Timestamp.UTC()))
}
return &supportbundles.SupportItem{
Filename: "db.md",
FileBytes: bWriter.Bytes(),
}, nil
}
return supportbundles.Collector{
UID: "db",
Description: "Database information and migration log",
DisplayName: "Database and Migration information",
IncludedByDefault: false,
Default: true,
Fn: collectorFn,
}
}
|
pkg/infra/supportbundles/supportbundlesimpl/db_collector.go
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.0002885643334593624,
0.00020004234102088958,
0.00016812099784146994,
0.00017434879555366933,
0.00004425663792062551
] |
{
"id": 1,
"code_window": [
"\tif _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\t// Delete branch if needed\n",
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\tlog.Printf(\"Checking branch '%s' against '%s'\", git.PRCheckRegexp().String(), opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 115
}
|
import { createTransitions } from './createTransitions';
describe('transitions', () => {
const { duration, easing, getAutoHeightDuration, create } = createTransitions();
describe('create() function', () => {
it('should create default transition without arguments', () => {
const transition = create();
expect(transition).toEqual(`all ${duration.standard}ms ${easing.easeInOut} 0ms`);
});
it('should take string props as a first argument', () => {
const transition = create('color');
expect(transition).toEqual(`color ${duration.standard}ms ${easing.easeInOut} 0ms`);
});
it('should also take array of props as first argument', () => {
const options = { delay: 20 };
const multiple = create(['color', 'size'], options);
const single1 = create('color', options);
const single2 = create('size', options);
const expected = `${single1},${single2}`;
expect(multiple).toEqual(expected);
});
it('should optionally accept number "duration" option in second argument', () => {
const transition = create('font', { duration: 500 });
expect(transition).toEqual(`font 500ms ${easing.easeInOut} 0ms`);
});
it('should optionally accept string "duration" option in second argument', () => {
const transition = create('font', { duration: '500ms' });
expect(transition).toEqual(`font 500ms ${easing.easeInOut} 0ms`);
});
it('should round decimal digits of "duration" prop to whole numbers', () => {
const transition = create('font', { duration: 12.125 });
expect(transition).toEqual(`font 12ms ${easing.easeInOut} 0ms`);
});
it('should optionally accept string "easing" option in second argument', () => {
const transition = create('transform', { easing: easing.sharp });
expect(transition).toEqual(`transform ${duration.standard}ms ${easing.sharp} 0ms`);
});
it('should optionally accept number "delay" option in second argument', () => {
const transition = create('size', { delay: 150 });
expect(transition).toEqual(`size ${duration.standard}ms ${easing.easeInOut} 150ms`);
});
it('should optionally accept string "delay" option in second argument', () => {
const transition = create('size', { delay: '150ms' });
expect(transition).toEqual(`size ${duration.standard}ms ${easing.easeInOut} 150ms`);
});
it('should round decimal digits of "delay" prop to whole numbers', () => {
const transition = create('size', { delay: 1.547 });
expect(transition).toEqual(`size ${duration.standard}ms ${easing.easeInOut} 2ms`);
});
it('should return NaN when passed a negative number', () => {
const zeroHeightDurationNegativeOne = getAutoHeightDuration(-1);
// eslint-disable-next-line no-restricted-globals
expect(isNaN(zeroHeightDurationNegativeOne)).toEqual(true);
const zeroHeightDurationSmallNegative = getAutoHeightDuration(-0.000001);
// eslint-disable-next-line no-restricted-globals
expect(isNaN(zeroHeightDurationSmallNegative)).toEqual(true);
const zeroHeightDurationBigNegative = getAutoHeightDuration(-100000);
// eslint-disable-next-line no-restricted-globals
expect(isNaN(zeroHeightDurationBigNegative)).toEqual(true);
});
it('should return values for pre-calculated positive examples', () => {
let zeroHeightDuration = getAutoHeightDuration(14);
expect(zeroHeightDuration).toEqual(159);
zeroHeightDuration = getAutoHeightDuration(100);
expect(zeroHeightDuration).toEqual(239);
zeroHeightDuration = getAutoHeightDuration(0.0001);
expect(zeroHeightDuration).toEqual(46);
zeroHeightDuration = getAutoHeightDuration(100000);
expect(zeroHeightDuration).toEqual(6685);
});
});
});
|
packages/grafana-data/src/themes/createTransitions.test.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017832517914939672,
0.00017576239770278335,
0.00017030346498358995,
0.0001762787433108315,
0.000002323403577975114
] |
{
"id": 1,
"code_window": [
"\tif _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\t// Delete branch if needed\n",
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\tlog.Printf(\"Checking branch '%s' against '%s'\", git.PRCheckRegexp().String(), opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 115
}
|
import { RefObject, useEffect, useState } from 'react';
import { useEffectOnce } from 'react-use';
const modulo = (a: number, n: number) => ((a % n) + n) % n;
const UNFOCUSED = -1;
/** @internal */
export interface UseMenuFocusProps {
localRef: RefObject<HTMLDivElement>;
isMenuOpen?: boolean;
openedWithArrow?: boolean;
setOpenedWithArrow?: (openedWithArrow: boolean) => void;
close?: () => void;
onOpen?: (focusOnItem: (itemId: number) => void) => void;
onClose?: () => void;
onKeyDown?: React.KeyboardEventHandler;
}
/** @internal */
export type UseMenuFocusReturn = [(event: React.KeyboardEvent) => void, () => void];
/** @internal */
export const useMenuFocus = ({
localRef,
isMenuOpen,
openedWithArrow,
setOpenedWithArrow,
close,
onOpen,
onClose,
onKeyDown,
}: UseMenuFocusProps): UseMenuFocusReturn => {
const [focusedItem, setFocusedItem] = useState(UNFOCUSED);
useEffect(() => {
if (isMenuOpen && openedWithArrow) {
setFocusedItem(0);
setOpenedWithArrow?.(false);
}
}, [isMenuOpen, openedWithArrow, setOpenedWithArrow]);
useEffect(() => {
const menuItems = localRef?.current?.querySelectorAll<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
menuItems?.[focusedItem]?.focus();
menuItems?.forEach((menuItem, i) => {
menuItem.tabIndex = i === focusedItem ? 0 : -1;
});
}, [localRef, focusedItem]);
useEffectOnce(() => {
const firstMenuItem = localRef?.current?.querySelector<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
if (firstMenuItem) {
firstMenuItem.tabIndex = 0;
}
onOpen?.(setFocusedItem);
});
const handleKeys = (event: React.KeyboardEvent) => {
const menuItems = localRef?.current?.querySelectorAll<HTMLElement | HTMLButtonElement | HTMLAnchorElement>(
'[data-role="menuitem"]:not([data-disabled])'
);
const menuItemsCount = menuItems?.length ?? 0;
switch (event.key) {
case 'ArrowUp':
event.preventDefault();
event.stopPropagation();
setFocusedItem(modulo(focusedItem - 1, menuItemsCount));
break;
case 'ArrowDown':
event.preventDefault();
event.stopPropagation();
setFocusedItem(modulo(focusedItem + 1, menuItemsCount));
break;
case 'ArrowLeft':
event.preventDefault();
event.stopPropagation();
setFocusedItem(UNFOCUSED);
close?.();
break;
case 'Home':
event.preventDefault();
event.stopPropagation();
setFocusedItem(0);
break;
case 'End':
event.preventDefault();
event.stopPropagation();
setFocusedItem(menuItemsCount - 1);
break;
case 'Enter':
event.preventDefault();
event.stopPropagation();
menuItems?.[focusedItem]?.click();
break;
case 'Escape':
event.preventDefault();
event.stopPropagation();
onClose?.();
break;
case 'Tab':
onClose?.();
break;
default:
break;
}
// Forward event to parent
onKeyDown?.(event);
};
const handleFocus = () => {
if (focusedItem === UNFOCUSED) {
setFocusedItem(0);
}
};
return [handleKeys, handleFocus];
};
|
packages/grafana-ui/src/components/Menu/hooks.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.0001789267553249374,
0.00017485441640019417,
0.00016968250565696508,
0.00017481966642662883,
0.000002684388164198026
] |
{
"id": 2,
"code_window": [
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n",
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t\tlog.Println(\"Deleting branch\", opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 116
}
|
package main
import (
"os"
"strconv"
"github.com/grafana/grafana/pkg/build/env"
"github.com/grafana/grafana/pkg/build/git"
"github.com/urfave/cli/v2"
)
// checkOpts are options used to create a new GitHub check for the enterprise downstream test.
type checkOpts struct {
SHA string
URL string
Branch string
PR int
}
func getCheckOpts(args []string) (*checkOpts, error) {
branch, ok := env.Lookup("DRONE_SOURCE_BRANCH", args)
if !ok {
return nil, cli.Exit("Unable to retrieve build source branch", 1)
}
var (
rgx = git.PRCheckRegexp()
matches = rgx.FindStringSubmatch(branch)
)
sha, ok := env.Lookup("SOURCE_COMMIT", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve source commit", 1)
}
sha = matches[2]
}
url, ok := env.Lookup("DRONE_BUILD_LINK", args)
if !ok {
return nil, cli.Exit(`missing environment variable "DRONE_BUILD_LINK"`, 1)
}
prStr, ok := env.Lookup("OSS_PULL_REQUEST", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve PR number", 1)
}
prStr = matches[1]
}
pr, err := strconv.Atoi(prStr)
if err != nil {
return nil, err
}
return &checkOpts{
Branch: branch,
PR: pr,
SHA: sha,
URL: url,
}, nil
}
// EnterpriseCheckBegin creates the GitHub check and signals the beginning of the downstream build / test process
func EnterpriseCheckBegin(c *cli.Context) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
if _, err = git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, "pending"); err != nil {
return err
}
return nil
}
func EnterpriseCheckSuccess(c *cli.Context) error {
return completeEnterpriseCheck(c, true)
}
func EnterpriseCheckFail(c *cli.Context) error {
return completeEnterpriseCheck(c, false)
}
func completeEnterpriseCheck(c *cli.Context, success bool) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
// Update the pull request labels
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
status := "failure"
if success {
status = "success"
}
// Update the GitHub check...
if _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {
return err
}
// Delete branch if needed
if git.PRCheckRegexp().MatchString(opts.Branch) {
if err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {
return nil
}
}
label := "enterprise-failed"
if success {
label = "enterprise-ok"
}
return git.AddLabelToPR(ctx, client.Issues, opts.PR, label)
}
|
pkg/build/cmd/enterprisecheck.go
| 1 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.9980145692825317,
0.15401728451251984,
0.00016413112462032586,
0.0022643080446869135,
0.3521069288253784
] |
{
"id": 2,
"code_window": [
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n",
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t\tlog.Println(\"Deleting branch\", opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 116
}
|
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { createLokiDatasource } from '../../mocks';
import { LokiVisualQueryBinary } from '../types';
import { NestedQuery, Props as NestedQueryProps } from './NestedQuery';
type Operator = '+' | '-' | '*' | '/' | '%' | '^' | '==' | '!=' | '>' | '<' | '>=' | '<=';
type VectorMatchType = 'on' | 'ignoring';
const createMockProps = (
operator: Operator = '/',
vectorMatchesType: VectorMatchType = 'on',
showExplain = false
): NestedQueryProps => {
const nestedQuery: LokiVisualQueryBinary = {
operator: operator,
vectorMatchesType: vectorMatchesType,
query: {
labels: [],
operations: [],
},
};
const datasource = createLokiDatasource();
const props: NestedQueryProps = {
nestedQuery: nestedQuery,
index: 0,
datasource: datasource,
onChange: jest.fn(),
onRemove: jest.fn(),
onRunQuery: jest.fn(),
showExplain: showExplain,
};
return props;
};
// All test assertions need to be awaited for, because the component uses `useEffect` to update the state.
describe('render all elements', () => {
it('renders the operator label', async () => {
const props = createMockProps();
render(<NestedQuery {...props} />);
expect(await screen.findByText('Operator')).toBeInTheDocument();
});
it('renders the expected operator value', async () => {
const props = createMockProps('!=');
render(<NestedQuery {...props} />);
expect(await screen.findByText('!=')).toBeInTheDocument();
});
it('renders the vector matches label', async () => {
const props = createMockProps();
render(<NestedQuery {...props} />);
expect(await screen.findByText('Vector matches')).toBeInTheDocument();
});
it('renders the expected vector matches value', async () => {
const props = createMockProps(undefined, 'ignoring');
render(<NestedQuery {...props} />);
expect(await screen.findByText('ignoring')).toBeInTheDocument();
});
});
describe('exit the nested query', () => {
it('onRemove is called when clicking (x)', async () => {
const props = createMockProps();
render(<NestedQuery {...props} />);
fireEvent.click(await screen.findByLabelText('Remove nested query'));
await waitFor(() => expect(props.onRemove).toHaveBeenCalledTimes(1));
});
});
describe('change operator', () => {
it('onChange is called with the correct args', async () => {
const props = createMockProps('/', 'on');
render(<NestedQuery {...props} />);
userEvent.click(await screen.findByLabelText('Select operator'));
fireEvent.click(await screen.findByText('+'));
await waitFor(() => expect(props.onChange).toHaveBeenCalledTimes(1));
await waitFor(() =>
expect(props.onChange).toHaveBeenCalledWith(0, {
operator: '+',
vectorMatchesType: 'on',
query: { labels: [], operations: [] },
})
);
});
});
describe('explain mode', () => {
it('shows the explanation when set to true', async () => {
const props = createMockProps(undefined, undefined, true);
render(<NestedQuery {...props} />);
expect(await screen.findByText('Fetch all log lines matching label filters.')).toBeInTheDocument();
});
});
|
public/app/plugins/datasource/loki/querybuilder/components/NestedQuery.test.tsx
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017687056970316917,
0.00017256975115742534,
0.00016813588445074856,
0.00017265485075768083,
0.0000025877943699015304
] |
{
"id": 2,
"code_window": [
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n",
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t\tlog.Println(\"Deleting branch\", opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 116
}
|
export { HistorySrv, historySrv, RevisionsModel } from './HistorySrv';
export { VersionHistoryTable } from './VersionHistoryTable';
export { VersionHistoryHeader } from './VersionHistoryHeader';
export { VersionsHistoryButtons } from './VersionHistoryButtons';
export { VersionHistoryComparison } from './VersionHistoryComparison';
|
public/app/features/dashboard/components/VersionHistory/index.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017126815509982407,
0.00017126815509982407,
0.00017126815509982407,
0.00017126815509982407,
0
] |
{
"id": 2,
"code_window": [
"\tif git.PRCheckRegexp().MatchString(opts.Branch) {\n",
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t\tlog.Println(\"Deleting branch\", opts.Branch)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "add",
"edit_start_line_idx": 116
}
|
package secretscan
import (
"context"
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestService_CheckTokens(t *testing.T) {
type testCase struct {
desc string
retrievedTokens []apikey.APIKey
wantHashes []string
leakedTokens []Token
notify bool
revoke bool
}
ctx := context.Background()
falseBool := false
trueBool := true
testCases := []testCase{
{
desc: "no tokens",
retrievedTokens: []apikey.APIKey{},
leakedTokens: []Token{},
notify: false,
revoke: false,
},
{
desc: "one token leaked - no revoke, no notify",
retrievedTokens: []apikey.APIKey{{
Id: 1,
OrgId: 2,
Name: "test",
Key: "test-hash-1",
Role: "Viewer",
Expires: nil,
ServiceAccountId: new(int64),
IsRevoked: &falseBool,
}},
wantHashes: []string{"test-hash-1"},
leakedTokens: []Token{{Hash: "test-hash-1"}},
notify: false,
revoke: false,
},
{
desc: "one token leaked - revoke, no notify",
retrievedTokens: []apikey.APIKey{{
Id: 1,
OrgId: 2,
Name: "test",
Key: "test-hash-1",
Role: "Viewer",
Expires: nil,
ServiceAccountId: new(int64),
IsRevoked: &falseBool,
}},
wantHashes: []string{"test-hash-1"},
leakedTokens: []Token{{Hash: "test-hash-1"}},
notify: false,
revoke: true,
},
{
desc: "two tokens - one revoke, notify",
retrievedTokens: []apikey.APIKey{{
Id: 1,
OrgId: 2,
Name: "test",
Key: "test-hash-1",
Role: "Viewer",
Expires: nil,
ServiceAccountId: new(int64),
IsRevoked: &falseBool,
}, {
Id: 2,
OrgId: 4,
Name: "test-2",
Key: "test-hash-2",
Role: "Viewer",
Expires: nil,
ServiceAccountId: new(int64),
IsRevoked: &falseBool,
}},
wantHashes: []string{"test-hash-1", "test-hash-2"},
leakedTokens: []Token{{Hash: "test-hash-2"}},
notify: true,
revoke: true,
},
{
desc: "one token already revoked should not be checked",
retrievedTokens: []apikey.APIKey{{
Id: 1,
OrgId: 2,
Name: "test",
Key: "test-hash-1",
Role: "Viewer",
Expires: nil,
ServiceAccountId: new(int64),
IsRevoked: &trueBool,
}},
wantHashes: []string{},
leakedTokens: []Token{},
notify: false,
revoke: true,
},
{
desc: "one token expired should not be checked",
retrievedTokens: []apikey.APIKey{{
Id: 1,
OrgId: 2,
Name: "test",
Key: "test-hash-1",
Role: "Viewer",
Expires: new(int64),
ServiceAccountId: new(int64),
IsRevoked: &falseBool,
}},
wantHashes: []string{},
leakedTokens: []Token{},
notify: false,
revoke: true,
},
}
for _, tt := range testCases {
t.Run(tt.desc, func(t *testing.T) {
tokenStore := &MockTokenRetriever{keys: tt.retrievedTokens}
client := &MockSecretScanClient{tokens: tt.leakedTokens}
notifier := &MockSecretScanNotifier{}
service := &Service{
store: tokenStore,
client: client,
webHookClient: notifier,
logger: log.New("secretscan"),
webHookNotify: tt.notify,
revoke: tt.revoke,
}
err := service.CheckTokens(ctx)
require.NoError(t, err)
if len(tt.wantHashes) > 0 {
assert.Equal(t, tt.wantHashes, client.checkCalls[0].([]string))
} else {
assert.Empty(t, client.checkCalls)
}
if len(tt.leakedTokens) > 0 {
if tt.revoke {
assert.Len(t, tokenStore.revokeCalls, len(tt.leakedTokens))
} else {
assert.Empty(t, tokenStore.revokeCalls)
}
}
if tt.notify {
assert.Len(t, notifier.notifyCalls, len(tt.leakedTokens))
} else {
assert.Empty(t, notifier.notifyCalls)
}
})
}
}
|
pkg/services/serviceaccounts/secretscan/service_test.go
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00142021500505507,
0.0003026400809176266,
0.00016567188140470535,
0.0001698427804512903,
0.0003628955746535212
] |
{
"id": 3,
"code_window": [
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n",
"\t\t\treturn nil\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tlabel := \"enterprise-failed\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\treturn fmt.Errorf(\"error deleting enterprise branch: %w\", err)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "replace",
"edit_start_line_idx": 117
}
|
package main
import (
"os"
"strconv"
"github.com/grafana/grafana/pkg/build/env"
"github.com/grafana/grafana/pkg/build/git"
"github.com/urfave/cli/v2"
)
// checkOpts are options used to create a new GitHub check for the enterprise downstream test.
type checkOpts struct {
SHA string
URL string
Branch string
PR int
}
func getCheckOpts(args []string) (*checkOpts, error) {
branch, ok := env.Lookup("DRONE_SOURCE_BRANCH", args)
if !ok {
return nil, cli.Exit("Unable to retrieve build source branch", 1)
}
var (
rgx = git.PRCheckRegexp()
matches = rgx.FindStringSubmatch(branch)
)
sha, ok := env.Lookup("SOURCE_COMMIT", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve source commit", 1)
}
sha = matches[2]
}
url, ok := env.Lookup("DRONE_BUILD_LINK", args)
if !ok {
return nil, cli.Exit(`missing environment variable "DRONE_BUILD_LINK"`, 1)
}
prStr, ok := env.Lookup("OSS_PULL_REQUEST", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve PR number", 1)
}
prStr = matches[1]
}
pr, err := strconv.Atoi(prStr)
if err != nil {
return nil, err
}
return &checkOpts{
Branch: branch,
PR: pr,
SHA: sha,
URL: url,
}, nil
}
// EnterpriseCheckBegin creates the GitHub check and signals the beginning of the downstream build / test process
func EnterpriseCheckBegin(c *cli.Context) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
if _, err = git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, "pending"); err != nil {
return err
}
return nil
}
func EnterpriseCheckSuccess(c *cli.Context) error {
return completeEnterpriseCheck(c, true)
}
func EnterpriseCheckFail(c *cli.Context) error {
return completeEnterpriseCheck(c, false)
}
func completeEnterpriseCheck(c *cli.Context, success bool) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
// Update the pull request labels
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
status := "failure"
if success {
status = "success"
}
// Update the GitHub check...
if _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {
return err
}
// Delete branch if needed
if git.PRCheckRegexp().MatchString(opts.Branch) {
if err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {
return nil
}
}
label := "enterprise-failed"
if success {
label = "enterprise-ok"
}
return git.AddLabelToPR(ctx, client.Issues, opts.PR, label)
}
|
pkg/build/cmd/enterprisecheck.go
| 1 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.9971063733100891,
0.08260466158390045,
0.00016483833314850926,
0.0017163335578516126,
0.2642340064048767
] |
{
"id": 3,
"code_window": [
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n",
"\t\t\treturn nil\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tlabel := \"enterprise-failed\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\treturn fmt.Errorf(\"error deleting enterprise branch: %w\", err)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "replace",
"edit_start_line_idx": 117
}
|
import {
ColumnDefinition,
getStandardSQLCompletionProvider,
LanguageCompletionProvider,
LinkedToken,
TableDefinition,
TableIdentifier,
TokenType,
} from '@grafana/experimental';
import { DB, SQLQuery } from 'app/features/plugins/sql/types';
interface CompletionProviderGetterArgs {
getColumns: React.MutableRefObject<(t: SQLQuery) => Promise<ColumnDefinition[]>>;
getTables: React.MutableRefObject<(d?: string) => Promise<TableDefinition[]>>;
}
export const getSqlCompletionProvider: (args: CompletionProviderGetterArgs) => LanguageCompletionProvider =
({ getColumns, getTables }) =>
(monaco, language) => ({
...(language && getStandardSQLCompletionProvider(monaco, language)),
tables: {
resolve: async (identifier) => {
return await getTables.current(identifier.table);
},
parseName: (token: LinkedToken) => {
if (!token) {
return { table: '' };
}
let processedToken = token;
let tablePath = processedToken.value;
while (processedToken.next && processedToken.next.type !== TokenType.Whitespace) {
tablePath += processedToken.next.value;
processedToken = processedToken.next;
}
if (processedToken.value.endsWith('.')) {
tablePath = processedToken.value.slice(0, processedToken.value.length - 1);
}
return { table: tablePath };
},
},
columns: {
resolve: async (t: TableIdentifier | undefined) => {
if (!t?.table) {
return [];
}
// TODO: Use schema instead of table
const [database, schema, tableName] = t.table.split('.');
return await getColumns.current({ table: `${schema}.${tableName}`, dataset: database, refId: 'A' });
},
},
});
export async function fetchColumns(db: DB, q: SQLQuery) {
const cols = await db.fields(q);
if (cols.length > 0) {
return cols.map((c) => {
return { name: c.value, type: c.value, description: c.value };
});
} else {
return [];
}
}
export async function fetchTables(db: DB, dataset?: string) {
const tables = await db.lookup?.(dataset);
return tables || [];
}
|
public/app/plugins/datasource/mssql/sqlCompletionProvider.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00018441809515934438,
0.0001733481331029907,
0.00016662066627759486,
0.00017238143482245505,
0.0000050821545301005244
] |
{
"id": 3,
"code_window": [
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n",
"\t\t\treturn nil\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tlabel := \"enterprise-failed\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\treturn fmt.Errorf(\"error deleting enterprise branch: %w\", err)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "replace",
"edit_start_line_idx": 117
}
|
package dataframe
import (
"context"
"encoding/json"
"github.com/grafana/grafana-plugin-sdk-go/data"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/store"
)
func GetEntityKindInfo() models.EntityKindInfo {
return models.EntityKindInfo{
ID: models.StandardKindDataFrame,
Name: "Data frame",
Description: "Data frame",
}
}
func GetEntitySummaryBuilder() models.EntitySummaryBuilder {
return func(ctx context.Context, uid string, body []byte) (*models.EntitySummary, []byte, error) {
df := &data.Frame{}
err := json.Unmarshal(body, df)
if err != nil {
return nil, nil, err
}
rows, err := df.RowLen()
if err != nil {
return nil, nil, err
}
out, err := data.FrameToJSON(df, data.IncludeAll)
if err != nil {
return nil, nil, err
}
summary := &models.EntitySummary{
Kind: models.StandardKindDataFrame,
Name: df.Name,
UID: uid,
Fields: map[string]interface{}{
"rows": rows,
"cols": len(df.Fields),
},
}
if summary.Name == "" {
summary.Name = store.GuessNameFromUID(uid)
}
return summary, out, err
}
}
|
pkg/services/store/kind/dataframe/summary.go
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.0001795909774955362,
0.00017231766832992435,
0.0001675268285907805,
0.000170882762176916,
0.0000039788292269804515
] |
{
"id": 3,
"code_window": [
"\t\tif err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {\n",
"\t\t\treturn nil\n",
"\t\t}\n",
"\t}\n",
"\n",
"\tlabel := \"enterprise-failed\"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\t\treturn fmt.Errorf(\"error deleting enterprise branch: %w\", err)\n"
],
"file_path": "pkg/build/cmd/enterprisecheck.go",
"type": "replace",
"edit_start_line_idx": 117
}
|
import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks';
import { Checkbox } from './Checkbox';
<Meta title="MDX|Checkbox" component={Checkbox} />
# Checkbox
### When to use
Checked represents true, un-checked represent false. So you can use them to select a binary option or multiple options in a set. `Checkbox` can be used in groups, where the single checkboxes have no dependencies. That means that selecting one doesn’t affect any other `Checkbox`. When adding a description to your `Checkbox`, write positive statements so that "checked" means "yes" and not "no". That way, you can avoid confusion.
**DO:** [ ] Hide options
**DON'T:** [ ] Do not show options
Checkboxes typically only trigger changes after sending a form. If your component should trigger a change immediately, it's better to use a toggle switch instead. Furthermore, checkboxes are not mutually exclusive. That means that selecting one will not disable the others or impact them in any other way. If you want to offer a mutually exclusive choice, use `RadioButtonGroup` or a `Select` dropdown.
**DO:**
Show series
[ ] A-series
[ ] B-series
[ ] C-series
**DON'T:**
Show only
[ ] A-series
[ ] B-series
[ ] C-series
### Usage
```jsx
import { Forms } from '@grafana/ui';
<Checkbox value={true|false} label={...} description={...} onChange={...} />
```
### Props
<Props of={Checkbox} />
|
packages/grafana-ui/src/components/Forms/Checkbox.mdx
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017531141929794103,
0.00017233521793968976,
0.00016751514340285212,
0.0001732571836328134,
0.0000031271224543161225
] |
{
"id": 4,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func DeleteEnterpriseBranch(ctx context.Context, client GitService, branchName string) error {\n",
"\tref := \"heads/\" + branchName\n",
"\t_, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref)\n",
"\tif err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\treturn nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif _, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref); err != nil {\n"
],
"file_path": "pkg/build/git/git.go",
"type": "replace",
"edit_start_line_idx": 107
}
|
package main
import (
"os"
"strconv"
"github.com/grafana/grafana/pkg/build/env"
"github.com/grafana/grafana/pkg/build/git"
"github.com/urfave/cli/v2"
)
// checkOpts are options used to create a new GitHub check for the enterprise downstream test.
type checkOpts struct {
SHA string
URL string
Branch string
PR int
}
func getCheckOpts(args []string) (*checkOpts, error) {
branch, ok := env.Lookup("DRONE_SOURCE_BRANCH", args)
if !ok {
return nil, cli.Exit("Unable to retrieve build source branch", 1)
}
var (
rgx = git.PRCheckRegexp()
matches = rgx.FindStringSubmatch(branch)
)
sha, ok := env.Lookup("SOURCE_COMMIT", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve source commit", 1)
}
sha = matches[2]
}
url, ok := env.Lookup("DRONE_BUILD_LINK", args)
if !ok {
return nil, cli.Exit(`missing environment variable "DRONE_BUILD_LINK"`, 1)
}
prStr, ok := env.Lookup("OSS_PULL_REQUEST", args)
if !ok {
if matches == nil || len(matches) <= 1 {
return nil, cli.Exit("Unable to retrieve PR number", 1)
}
prStr = matches[1]
}
pr, err := strconv.Atoi(prStr)
if err != nil {
return nil, err
}
return &checkOpts{
Branch: branch,
PR: pr,
SHA: sha,
URL: url,
}, nil
}
// EnterpriseCheckBegin creates the GitHub check and signals the beginning of the downstream build / test process
func EnterpriseCheckBegin(c *cli.Context) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
if _, err = git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, "pending"); err != nil {
return err
}
return nil
}
func EnterpriseCheckSuccess(c *cli.Context) error {
return completeEnterpriseCheck(c, true)
}
func EnterpriseCheckFail(c *cli.Context) error {
return completeEnterpriseCheck(c, false)
}
func completeEnterpriseCheck(c *cli.Context, success bool) error {
var (
ctx = c.Context
client = git.NewGitHubClient(ctx, c.String("github-token"))
)
// Update the pull request labels
opts, err := getCheckOpts(os.Environ())
if err != nil {
return err
}
status := "failure"
if success {
status = "success"
}
// Update the GitHub check...
if _, err := git.CreateEnterpriseStatus(ctx, client.Repositories, opts.SHA, opts.URL, status); err != nil {
return err
}
// Delete branch if needed
if git.PRCheckRegexp().MatchString(opts.Branch) {
if err := git.DeleteEnterpriseBranch(ctx, client.Git, opts.Branch); err != nil {
return nil
}
}
label := "enterprise-failed"
if success {
label = "enterprise-ok"
}
return git.AddLabelToPR(ctx, client.Issues, opts.PR, label)
}
|
pkg/build/cmd/enterprisecheck.go
| 1 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.9990286827087402,
0.1559174358844757,
0.000169715509400703,
0.0006820737035013735,
0.3554465174674988
] |
{
"id": 4,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func DeleteEnterpriseBranch(ctx context.Context, client GitService, branchName string) error {\n",
"\tref := \"heads/\" + branchName\n",
"\t_, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref)\n",
"\tif err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\treturn nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif _, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref); err != nil {\n"
],
"file_path": "pkg/build/git/git.go",
"type": "replace",
"edit_start_line_idx": 107
}
|
package dashboardthumbsimpl
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/thumbs"
)
type xormStore struct {
db db.DB
}
func (ss *xormStore) Get(ctx context.Context, query *thumbs.GetDashboardThumbnailCommand) (*thumbs.DashboardThumbnail, error) {
err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
result, err := findThumbnailByMeta(sess, query.DashboardThumbnailMeta)
if err != nil {
return err
}
query.Result = result
return nil
})
return query.Result, err
}
func marshalDatasourceUids(dsUids []string) (string, error) {
if dsUids == nil {
return "", nil
}
b, err := json.Marshal(dsUids)
if err != nil {
return "", err
}
return string(b), nil
}
func (ss *xormStore) Save(ctx context.Context, cmd *thumbs.SaveDashboardThumbnailCommand) (*thumbs.DashboardThumbnail, error) {
err := ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existing, err := findThumbnailByMeta(sess, cmd.DashboardThumbnailMeta)
if err != nil && !errors.Is(err, dashboards.ErrDashboardThumbnailNotFound) {
return err
}
dsUids, err := marshalDatasourceUids(cmd.DatasourceUIDs)
if err != nil {
return err
}
if existing != nil {
existing.Image = cmd.Image
existing.MimeType = cmd.MimeType
existing.Updated = time.Now()
existing.DashboardVersion = cmd.DashboardVersion
existing.DsUIDs = dsUids
existing.State = thumbs.ThumbnailStateDefault
_, err = sess.ID(existing.Id).Update(existing)
cmd.Result = existing
return err
}
thumb := &thumbs.DashboardThumbnail{}
dash, err := findDashboardIdByThumbMeta(sess, cmd.DashboardThumbnailMeta)
if err != nil {
return err
}
thumb.Updated = time.Now()
thumb.Theme = cmd.Theme
thumb.Kind = cmd.Kind
thumb.Image = cmd.Image
thumb.DsUIDs = dsUids
thumb.MimeType = cmd.MimeType
thumb.DashboardId = dash.Id
thumb.DashboardVersion = cmd.DashboardVersion
thumb.State = thumbs.ThumbnailStateDefault
thumb.PanelId = cmd.PanelID
_, err = sess.Insert(thumb)
cmd.Result = thumb
return err
})
return cmd.Result, err
}
func (ss *xormStore) UpdateState(ctx context.Context, cmd *thumbs.UpdateThumbnailStateCommand) error {
err := ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
existing, err := findThumbnailByMeta(sess, cmd.DashboardThumbnailMeta)
if err != nil {
return err
}
existing.State = cmd.State
_, err = sess.ID(existing.Id).Update(existing)
return err
})
return err
}
func (ss *xormStore) Count(ctx context.Context, cmd *thumbs.FindDashboardThumbnailCountCommand) (int64, error) {
err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
count, err := sess.Count(&thumbs.DashboardThumbnail{})
if err != nil {
return err
}
cmd.Result = count
return nil
})
return cmd.Result, err
}
func (ss *xormStore) FindDashboardsWithStaleThumbnails(ctx context.Context, cmd *thumbs.FindDashboardsWithStaleThumbnailsCommand) ([]*thumbs.DashboardWithStaleThumbnail, error) {
err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
sess.Table("dashboard")
sess.Join("LEFT", "dashboard_thumbnail", "dashboard.id = dashboard_thumbnail.dashboard_id AND dashboard_thumbnail.theme = ? AND dashboard_thumbnail.kind = ?", cmd.Theme, cmd.Kind)
sess.Where("dashboard.is_folder = ?", ss.db.GetDialect().BooleanStr(false))
query := "(dashboard.version != dashboard_thumbnail.dashboard_version " +
"OR dashboard_thumbnail.state = ? " +
"OR dashboard_thumbnail.id IS NULL"
args := []interface{}{thumbs.ThumbnailStateStale}
if cmd.IncludeThumbnailsWithEmptyDsUIDs {
query += " OR dashboard_thumbnail.ds_uids = ? OR dashboard_thumbnail.ds_uids IS NULL"
args = append(args, "")
}
sess.Where(query+")", args...)
if !cmd.IncludeManuallyUploadedThumbnails {
sess.Where("(dashboard_thumbnail.id is not null AND dashboard_thumbnail.dashboard_version != ?) "+
"OR dashboard_thumbnail.id is null "+
"OR dashboard_thumbnail.state = ?", thumbs.DashboardVersionForManualThumbnailUpload, thumbs.ThumbnailStateStale)
}
sess.Where("(dashboard_thumbnail.id IS NULL OR dashboard_thumbnail.state != ?)", thumbs.ThumbnailStateLocked)
sess.Cols("dashboard.id",
"dashboard.uid",
"dashboard.org_id",
"dashboard.version",
"dashboard.slug")
var result = make([]*thumbs.DashboardWithStaleThumbnail, 0)
err := sess.Find(&result)
if err != nil {
return err
}
cmd.Result = result
return err
})
return cmd.Result, err
}
func findThumbnailByMeta(sess *db.Session, meta thumbs.DashboardThumbnailMeta) (*thumbs.DashboardThumbnail, error) {
result := &thumbs.DashboardThumbnail{}
sess.Table("dashboard_thumbnail")
sess.Join("INNER", "dashboard", "dashboard.id = dashboard_thumbnail.dashboard_id")
sess.Where("dashboard.uid = ? AND dashboard.org_id = ? AND panel_id = ? AND kind = ? AND theme = ?", meta.DashboardUID, meta.OrgId, meta.PanelID, meta.Kind, meta.Theme)
sess.Cols("dashboard_thumbnail.id",
"dashboard_thumbnail.dashboard_id",
"dashboard_thumbnail.panel_id",
"dashboard_thumbnail.image",
"dashboard_thumbnail.dashboard_version",
"dashboard_thumbnail.state",
"dashboard_thumbnail.kind",
"dashboard_thumbnail.ds_uids",
"dashboard_thumbnail.mime_type",
"dashboard_thumbnail.theme",
"dashboard_thumbnail.updated")
exists, err := sess.Get(result)
if !exists {
return nil, dashboards.ErrDashboardThumbnailNotFound
}
if err != nil {
return nil, err
}
return result, nil
}
type dash struct {
Id int64
}
func findDashboardIdByThumbMeta(sess *db.Session, meta thumbs.DashboardThumbnailMeta) (*dash, error) {
result := &dash{}
sess.Table("dashboard").Where("dashboard.uid = ? AND dashboard.org_id = ?", meta.DashboardUID, meta.OrgId).Cols("id")
exists, err := sess.Get(result)
if err != nil {
return nil, err
}
if !exists {
return nil, dashboards.ErrDashboardNotFound
}
return result, err
}
|
pkg/services/thumbs/dashboardthumbsimpl/xorm_store.go
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.46907588839530945,
0.021625887602567673,
0.0001587418228155002,
0.00016920952475629747,
0.09764283895492554
] |
{
"id": 4,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func DeleteEnterpriseBranch(ctx context.Context, client GitService, branchName string) error {\n",
"\tref := \"heads/\" + branchName\n",
"\t_, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref)\n",
"\tif err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\treturn nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif _, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref); err != nil {\n"
],
"file_path": "pkg/build/git/git.go",
"type": "replace",
"edit_start_line_idx": 107
}
|
import { DisplayProcessor } from '../types';
import { Vector } from '../types/vector';
import { formattedValueToString } from '../valueFormats';
import { FunctionalVector } from './FunctionalVector';
/**
* @public
*/
export class FormattedVector<T = any> extends FunctionalVector<string> {
constructor(private source: Vector<T>, private formatter: DisplayProcessor) {
super();
}
get length() {
return this.source.length;
}
get(index: number): string {
const v = this.source.get(index);
return formattedValueToString(this.formatter(v));
}
}
|
packages/grafana-data/src/vector/FormattedVector.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00017759842739906162,
0.00017664178449194878,
0.00017532898345962167,
0.00017699794261716306,
9.601146757631795e-7
] |
{
"id": 4,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func DeleteEnterpriseBranch(ctx context.Context, client GitService, branchName string) error {\n",
"\tref := \"heads/\" + branchName\n",
"\t_, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref)\n",
"\tif err != nil {\n",
"\t\treturn err\n",
"\t}\n",
"\n",
"\treturn nil\n",
"}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif _, err := client.DeleteRef(ctx, RepoOwner, EnterpriseRepo, ref); err != nil {\n"
],
"file_path": "pkg/build/git/git.go",
"type": "replace",
"edit_start_line_idx": 107
}
|
import { MetricsConfiguration } from '../../../types';
import {
defaultPipelineVariable,
generatePipelineVariableName,
} from './SettingsEditor/BucketScriptSettingsEditor/utils';
import {
isMetricAggregationWithField,
isPipelineAggregationWithMultipleBucketPaths,
MetricAggregation,
PipelineMetricAggregationType,
} from './aggregations';
export const metricAggregationConfig: MetricsConfiguration = {
count: {
label: 'Count',
requiresField: false,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: false,
hasMeta: false,
supportsInlineScript: false,
defaults: {},
},
avg: {
label: 'Average',
requiresField: true,
supportsInlineScript: true,
supportsMissing: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: false,
defaults: {},
},
sum: {
label: 'Sum',
requiresField: true,
supportsInlineScript: true,
supportsMissing: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: false,
defaults: {},
},
max: {
label: 'Max',
requiresField: true,
supportsInlineScript: true,
supportsMissing: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: false,
defaults: {},
},
min: {
label: 'Min',
requiresField: true,
supportsInlineScript: true,
supportsMissing: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: false,
defaults: {},
},
extended_stats: {
label: 'Extended Stats',
requiresField: true,
supportsMissing: true,
supportsInlineScript: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: true,
defaults: {
meta: {
std_deviation_bounds_lower: true,
std_deviation_bounds_upper: true,
},
},
},
percentiles: {
label: 'Percentiles',
requiresField: true,
supportsMissing: true,
supportsInlineScript: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
hasMeta: false,
defaults: {
settings: {
percents: ['25', '50', '75', '95', '99'],
},
},
},
cardinality: {
label: 'Unique Count',
requiresField: true,
supportsMissing: true,
isPipelineAgg: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {},
},
moving_avg: {
// deprecated in 6.4.0, removed in 8.0.0,
// recommended replacement is moving_fn
label: 'Moving Average',
requiresField: true,
isPipelineAgg: true,
versionRange: '<8.0.0',
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
model: 'simple',
window: '5',
},
},
},
moving_fn: {
// TODO: Check this
label: 'Moving Function',
requiresField: true,
isPipelineAgg: true,
supportsMultipleBucketPaths: false,
supportsInlineScript: false,
supportsMissing: false,
hasMeta: false,
hasSettings: true,
defaults: {},
},
derivative: {
label: 'Derivative',
requiresField: true,
isPipelineAgg: true,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {},
},
serial_diff: {
label: 'Serial Difference',
requiresField: true,
isPipelineAgg: true,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
lag: '1',
},
},
},
cumulative_sum: {
label: 'Cumulative Sum',
requiresField: true,
isPipelineAgg: true,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {},
},
bucket_script: {
label: 'Bucket Script',
requiresField: false,
isPipelineAgg: true,
supportsMissing: false,
supportsMultipleBucketPaths: true,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
pipelineVariables: [defaultPipelineVariable(generatePipelineVariableName([]))],
},
},
raw_document: {
label: 'Raw Document (legacy)',
requiresField: false,
isSingleMetric: true,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
size: '500',
},
},
},
raw_data: {
label: 'Raw Data',
requiresField: false,
isSingleMetric: true,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
size: '500',
},
},
},
logs: {
label: 'Logs',
requiresField: false,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
isSingleMetric: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
limit: '500',
},
},
},
top_metrics: {
label: 'Top Metrics',
xpack: true,
requiresField: false,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: false,
hasMeta: false,
defaults: {
settings: {
order: 'desc',
},
},
},
rate: {
label: 'Rate',
xpack: true,
requiresField: true,
isPipelineAgg: false,
supportsMissing: false,
supportsMultipleBucketPaths: false,
hasSettings: true,
supportsInlineScript: true,
hasMeta: false,
defaults: {},
},
};
interface PipelineOption {
label: string;
default?: string | number | boolean;
}
type PipelineOptions = {
[K in PipelineMetricAggregationType]: PipelineOption[];
};
export const pipelineOptions: PipelineOptions = {
moving_avg: [
{ label: 'window', default: 5 },
{ label: 'model', default: 'simple' },
{ label: 'predict' },
{ label: 'minimize', default: false },
],
moving_fn: [{ label: 'window', default: 5 }, { label: 'script' }],
derivative: [{ label: 'unit' }],
serial_diff: [{ label: 'lag' }],
cumulative_sum: [{ label: 'format' }],
bucket_script: [],
};
/**
* Given a metric `MetricA` and an array of metrics, returns all children of `MetricA`.
* `MetricB` is considered a child of `MetricA` if `MetricA` is referenced by `MetricB` in its `field` attribute
* (`MetricA.id === MetricB.field`) or in its pipeline aggregation variables (for bucket_scripts).
* @param metric
* @param metrics
*/
export const getChildren = (metric: MetricAggregation, metrics: MetricAggregation[]): MetricAggregation[] => {
const children = metrics.filter((m) => {
// TODO: Check this.
if (isPipelineAggregationWithMultipleBucketPaths(m)) {
return m.pipelineVariables?.some((pv) => pv.pipelineAgg === metric.id);
}
return isMetricAggregationWithField(m) && metric.id === m.field;
});
return [...children, ...children.flatMap((child) => getChildren(child, metrics))];
};
|
public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/utils.ts
| 0 |
https://github.com/grafana/grafana/commit/dc00f6dbe37c738c29b45b437863386090b42d69
|
[
0.00018001237185671926,
0.00017434866458643228,
0.00017087000014726073,
0.0001740292354952544,
0.0000018268447092850693
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".@{calendar-prefix-cls} {\n",
" position: relative;\n",
" width: 280px;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".calendar-selected-cell() {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
"}\n",
"\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "add",
"edit_start_line_idx": 133
}
|
.calendarLeftArrow() {
height: 100%;
&::before,
&::after {
position: relative;
top: -1px;
display: inline-block;
width: 8px;
height: 8px;
vertical-align: middle;
border: 0 solid #aaa;
border-width: 1.5px 0 0 1.5px;
border-radius: 1px;
transform: rotate(-45deg) scale(.8);
transition: all .3s;
content: '';
}
&:hover::before,
&:hover::after {
border-color: @text-color;
}
&::after {
display: none;
}
}
.calendarLeftDoubleArrow() {
.calendarLeftArrow;
&::after {
position: relative;
left: -3px;
display: inline-block;
}
}
.calendarRightArrow() {
.calendarLeftArrow;
&::before,
&::after {
transform: rotate(135deg) scale(.8);
}
}
.calendarRightDoubleArrow() {
.calendarRightArrow;
&::before {
position: relative;
left: 3px;
}
&::after {
display: inline-block;
}
}
.calendarPanelHeader(@calendar-prefix-cls) {
height: 40px;
line-height: 40px;
text-align: center;
border-bottom: @border-width-base @border-style-base @border-color-split;
user-select: none;
a:hover {
color: @link-hover-color;
}
.@{calendar-prefix-cls}-century-select,
.@{calendar-prefix-cls}-decade-select,
.@{calendar-prefix-cls}-year-select,
.@{calendar-prefix-cls}-month-select {
display: inline-block;
padding: 0 2px;
color: @heading-color;
font-weight: 500;
line-height: 40px;
}
.@{calendar-prefix-cls}-century-select-arrow,
.@{calendar-prefix-cls}-decade-select-arrow,
.@{calendar-prefix-cls}-year-select-arrow,
.@{calendar-prefix-cls}-month-select-arrow {
display: none;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-prev-month-btn,
.@{calendar-prefix-cls}-next-month-btn,
.@{calendar-prefix-cls}-prev-year-btn,
.@{calendar-prefix-cls}-next-year-btn {
position: absolute;
top: 0;
display: inline-block;
padding: 0 5px;
color: @text-color-secondary;
font-size: 16px;
font-family: Arial, 'Hiragino Sans GB', 'Microsoft Yahei', 'Microsoft Sans Serif', sans-serif;
line-height: 40px;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-prev-year-btn {
left: 7px;
.calendarLeftDoubleArrow;
}
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-next-year-btn {
right: 7px;
.calendarRightDoubleArrow;
}
.@{calendar-prefix-cls}-prev-month-btn {
left: 29px;
.calendarLeftArrow;
}
.@{calendar-prefix-cls}-next-month-btn {
right: 29px;
.calendarRightArrow;
}
}
.@{calendar-prefix-cls} {
position: relative;
width: 280px;
font-size: @font-size-base;
line-height: @line-height-base;
text-align: left;
list-style: none;
background-color: @component-background;
background-clip: padding-box;
border: @border-width-base @border-style-base @border-color-inverse;
border-radius: @border-radius-base;
outline: none;
box-shadow: @box-shadow-base;
&-input-wrap {
height: 34px;
padding: 6px @control-padding-horizontal - 2px;
border-bottom: @border-width-base @border-style-base @border-color-split;
}
&-input {
width: 100%;
height: 22px;
color: @input-color;
background: @input-bg;
border: 0;
outline: 0;
cursor: auto;
.placeholder;
}
&-week-number {
width: 286px;
&-cell {
text-align: center;
}
}
&-header {
.calendarPanelHeader(@calendar-prefix-cls);
}
&-body {
padding: 8px 12px;
}
table {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
}
table,
th,
td {
text-align: center;
border: 0;
}
&-calendar-table {
margin-bottom: 0;
border-spacing: 0;
}
&-column-header {
width: 33px;
padding: 6px 0;
line-height: 18px;
text-align: center;
.@{calendar-prefix-cls}-column-header-inner {
display: block;
font-weight: normal;
}
}
&-week-number-header {
.@{calendar-prefix-cls}-column-header-inner {
display: none;
}
}
&-cell {
height: 30px;
padding: 3px 0;
}
&-date {
display: block;
width: 24px;
height: 24px;
margin: 0 auto;
padding: 0;
color: @text-color;
line-height: 22px;
text-align: center;
background: transparent;
border: @border-width-base @border-style-base transparent;
border-radius: @border-radius-sm;
transition: background 0.3s ease;
&-panel {
position: relative;
outline: none;
}
&:hover {
background: @item-hover-bg;
cursor: pointer;
}
&:active {
color: @text-color-inverse;
background: @primary-5;
}
}
&-today &-date {
color: @primary-color;
font-weight: bold;
border-color: @primary-color;
}
&-last-month-cell &-date,
&-next-month-btn-day &-date {
color: @disabled-color;
}
&-selected-day &-date {
background: tint(@primary-color, 80%);
}
&-selected-date,
&-selected-start-date,
&-selected-end-date {
.@{calendar-prefix-cls}-date {
color: @text-color-inverse;
background: @primary-color;
border: @border-width-base @border-style-base transparent;
&:hover {
background: @primary-color;
}
}
}
&-disabled-cell &-date {
position: relative;
width: auto;
color: @disabled-color;
background: @disabled-bg;
border: @border-width-base @border-style-base transparent;
border-radius: 0;
cursor: not-allowed;
&:hover {
background: @disabled-bg;
}
}
&-disabled-cell&-selected-day &-date::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.1);
border-radius: @border-radius-sm;
content: '';
}
&-disabled-cell&-today &-date {
position: relative;
padding-right: 5px;
padding-left: 5px;
&::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
border: @border-width-base @border-style-base @disabled-color;
border-radius: @border-radius-sm;
content: ' ';
}
}
&-disabled-cell-first-of-row &-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&-disabled-cell-last-of-row &-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&-footer {
padding: 0 12px;
line-height: 38px;
border-top: @border-width-base @border-style-base @border-color-split;
&:empty {
border-top: 0;
}
&-btn {
display: block;
text-align: center;
}
&-extra {
text-align: left;
}
}
.@{calendar-prefix-cls}-today-btn,
.@{calendar-prefix-cls}-clear-btn {
display: inline-block;
margin: 0 0 0 8px;
text-align: center;
&-disabled {
color: @disabled-color;
cursor: not-allowed;
}
&:only-child {
margin: 0;
}
}
.@{calendar-prefix-cls}-clear-btn {
position: absolute;
top: 7px;
right: 5px;
display: none;
width: 20px;
height: 20px;
margin: 0;
overflow: hidden;
line-height: 20px;
text-align: center;
text-indent: -76px;
}
.@{calendar-prefix-cls}-clear-btn::after {
display: inline-block;
width: 20px;
color: @disabled-color;
font-size: @font-size-base;
line-height: 1;
text-indent: 43px;
transition: color 0.3s ease;
}
.@{calendar-prefix-cls}-clear-btn:hover::after {
color: @text-color-secondary;
}
.@{calendar-prefix-cls}-ok-btn {
.btn;
.btn-primary;
.button-size(@btn-height-sm; @btn-padding-sm; @font-size-base; @border-radius-base);
line-height: @btn-height-sm - 2px;
.button-disabled();
}
}
|
components/date-picker/style/Calendar.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.8010836839675903,
0.0211079902946949,
0.00016701787535566837,
0.0006363907596096396,
0.12490613758563995
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".@{calendar-prefix-cls} {\n",
" position: relative;\n",
" width: 280px;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".calendar-selected-cell() {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
"}\n",
"\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "add",
"edit_start_line_idx": 133
}
|
import * as React from 'react';
import { findDOMNode } from 'react-dom';
import ResizeObserver from 'resize-observer-polyfill';
type DomElement = Element | null;
interface ResizeObserverProps {
children?: React.ReactNode;
disabled?: boolean;
onResize?: () => void;
}
class ReactResizeObserver extends React.Component<ResizeObserverProps, {}> {
resizeObserver: ResizeObserver | null = null;
componentDidMount() {
this.onComponentUpdated();
}
componentDidUpdate() {
this.onComponentUpdated();
}
componentWillUnmount() {
this.destroyObserver();
}
onComponentUpdated() {
const { disabled } = this.props;
const element = findDOMNode(this) as DomElement;
if (!this.resizeObserver && !disabled && element) {
// Add resize observer
this.resizeObserver = new ResizeObserver(this.onResize);
this.resizeObserver.observe(element);
} else if (disabled) {
// Remove resize observer
this.destroyObserver();
}
}
onResize = () => {
const { onResize } = this.props;
if (onResize) {
onResize();
}
};
destroyObserver() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
this.resizeObserver = null;
}
}
render() {
const { children = null } = this.props;
return children;
}
}
export default ReactResizeObserver;
|
components/_util/resizeObserver.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017366779502481222,
0.00016978727944660932,
0.00016722390137147158,
0.00016937102191150188,
0.0000021632320112985326
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".@{calendar-prefix-cls} {\n",
" position: relative;\n",
" width: 280px;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".calendar-selected-cell() {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
"}\n",
"\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "add",
"edit_start_line_idx": 133
}
|
---
order: 3
title: Use in create-react-app
---
[create-react-app](https://github.com/facebookincubator/create-react-app) is one of the best React application development tools. We are going to use `antd` within it and modify the webpack config for some customized needs.
---
## Install and Initialization
Before all start, you may need install [yarn](https://github.com/yarnpkg/yarn/).
```bash
$ yarn create react-app antd-demo
```
The tool will create and initialize environment and dependencies automatically, please try config your proxy setting or use another npm registry if any network errors happen during it.
Then we go inside `antd-demo` and start it.
```bash
$ cd antd-demo
$ yarn start
```
Open the browser at http://localhost:3000/. It renders a header saying "Welcome to React" on the page.
## Import antd
Below is the default directory structure.
```
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ └── index.html
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ └── logo.svg
└── yarn.lock
```
Now we install `antd` from yarn or npm.
```bash
$ yarn add antd
```
Modify `src/App.js`, import Button component from `antd`.
```jsx
import React, { Component } from 'react';
import Button from 'antd/es/button';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
}
}
export default App;
```
Add `antd/dist/antd.css` at the top of `src/App.css`.
```css
@import '~antd/dist/antd.css';
.App {
text-align: center;
}
...
```
Ok, you should now see a blue primary button displayed on the page. Next you can choose any components of `antd` to develop your application. Visit other workflows of `create-react-app` at its [User Guide ](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
## Advanced Guides
We are successfully running antd components now but in the real world, there are still lots of problems about antd-demo. For instance, we actually import all styles of components in the project which may be a network performance issue.
Now we need to customize the default webpack config. We can achieve that by using [react-app-rewired](https://github.com/timarney/react-app-rewired) which is one of create-react-app's custom config solutions.
Import react-app-rewired and modify the `scripts` field in package.json. Due to new [[email protected]](https://github.com/timarney/react-app-rewired#alternatives) issue, you shall need [customize-cra](https://github.com/arackaf/customize-cra) along with react-app-rewired.
```
$ yarn add react-app-rewired customize-cra
```
```diff
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
}
```
Then create a `config-overrides.js` at root directory of your project for further overriding.
```js
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
```
### Use babel-plugin-import
> Note: antd support ES6 tree shaking by default even without this babel plugin for js part.
[babel-plugin-import](https://github.com/ant-design/babel-plugin-import) is a babel plugin for importing components on demand ([How does it work?](/docs/react/getting-started#Import-on-Demand)). We are now trying to install it and modify `config-overrides.js`.
```bash
$ yarn add babel-plugin-import
```
```diff
+ const { override, fixBabelImports } = require('customize-cra');
- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- return config;
- };
+ module.exports = override(
+ fixBabelImports('import', {
+ libraryName: 'antd',
+ libraryDirectory: 'es',
+ style: 'css',
+ }),
+ );
```
Remove the `@import '~antd/dist/antd.css';` statement added before because `babel-plugin-import` will import styles and import components like below:
```diff
// src/App.js
import React, { Component } from 'react';
- import Button from 'antd/es/button';
+ import { Button } from 'antd';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
}
}
export default App;
```
Then reboot with `yarn start` and visit the demo page, you should not find any [warning messages](https://zos.alipayobjects.com/rmsportal/vgcHJRVZFmPjAawwVoXK.png) in the console, which prove that the `import on demand` config is working now. You will find more info about it in [this guide](/docs/react/getting-started#Import-on-Demand).
### Customize Theme
According to the [Customize Theme documentation](/docs/react/customize-theme), to customize the theme, we need to modify `less` variables with tools such as [less-loader](https://github.com/webpack/less-loader). We can also use [addLessLoader](https://github.com/arackaf/customize-cra#addlessloaderloaderoptions) to achieve this. Import it and modify `config-overrides.js` like below.
```bash
$ yarn add less less-loader
```
```diff
- const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
- style: 'css',
+ style: true,
}),
+ addLessLoader({
+ javascriptEnabled: true,
+ modifyVars: { '@primary-color': '#1DA57A' },
+ }),
);
```
We use `modifyVars` option of [less-loader](https://github.com/webpack/less-loader#less-options) here, you can see a green button rendered on the page after rebooting the start server.
> You could also try [craco](https://github.com/sharegate/craco) and [craco-antd](https://github.com/FormAPI/craco-antd) to customize create-react-app webpack config same as customize-cra does.
## eject
You can also eject your application using [yarn run eject](https://facebook.github.io/create-react-app/docs/available-scripts#npm-run-eject) for a custom setup of create-react-app, although you should dig into it by yourself.
## Source code and other boilerplates
Finally, we used antd with create-react-app successfully, you can learn these practices for your own webpack workflow too, and find more webpack configs in the [atool-build](https://github.com/ant-tool/atool-build/blob/master/src/getWebpackCommonConfig.js). (For instance, add [moment noParse](https://github.com/ant-tool/atool-build/blob/e4bd2959689b6a95cb5c1c854a5db8c98676bdb3/src/getWebpackCommonConfig.js#L90) to avoid loading all language files.)
There are a lot of great boilerplates like create-react-app in the React community. There are some source code samples of importing antd in them if you encounter some problems.
- [create-react-app-antd](https://github.com/ant-design/create-react-app-antd)
- [comerc/cra-ts-antd](https://github.com/comerc/cra-ts-antd)
- [react-boilerplate/react-boilerplate](https://github.com/ant-design/react-boilerplate)
- [kriasoft/react-starter-kit](https://github.com/ant-design/react-starter-kit)
- [next.js](https://github.com/zeit/next.js/tree/master/examples/with-ant-design)
- [nwb](https://github.com/insin/nwb-examples/tree/master/react-app-antd)
- [antd-react-scripts](https://github.com/minesaner/create-react-app/tree/antd/packages/react-scripts)
|
docs/react/use-with-create-react-app.en-US.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017304923676420003,
0.0001691290526650846,
0.00016503602091688663,
0.00016903023060876876,
0.0000024422488422715105
] |
{
"id": 0,
"code_window": [
" }\n",
"}\n",
"\n",
".@{calendar-prefix-cls} {\n",
" position: relative;\n",
" width: 280px;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
".calendar-selected-cell() {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
"}\n",
"\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "add",
"edit_start_line_idx": 133
}
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Table.rowSelection fix selection column on the left 1`] = `
<div
class="ant-table-wrapper"
>
<div
class="ant-spin-nested-loading"
>
<div
class="ant-spin-container"
>
<div
class="ant-table ant-table-default ant-table-scroll-position-left"
>
<div
class="ant-table-content"
>
<div
class="ant-table-scroll"
>
<div
class="ant-table-body"
>
<table
class=""
>
<colgroup>
<col
class="ant-table-selection-col"
/>
<col />
</colgroup>
<thead
class="ant-table-thead"
>
<tr>
<th
class="ant-table-fixed-columns-in-body ant-table-selection-column"
>
<span
class="ant-table-header-column"
>
<div>
<span
class="ant-table-column-title"
>
<div
class="ant-table-selection"
>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</div>
</span>
<span
class="ant-table-column-sorter"
/>
</div>
</span>
</th>
<th
class=""
>
<span
class="ant-table-header-column"
>
<div>
<span
class="ant-table-column-title"
>
Name
</span>
<span
class="ant-table-column-sorter"
/>
</div>
</span>
</th>
</tr>
</thead>
<tbody
class="ant-table-tbody"
>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="0"
>
<td
class="ant-table-fixed-columns-in-body ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
<td
class=""
>
<span
class="ant-table-row-indent indent-level-0"
style="padding-left:0px"
/>
Jack
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="1"
>
<td
class="ant-table-fixed-columns-in-body ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
<td
class=""
>
<span
class="ant-table-row-indent indent-level-0"
style="padding-left:0px"
/>
Lucy
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="2"
>
<td
class="ant-table-fixed-columns-in-body ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
<td
class=""
>
<span
class="ant-table-row-indent indent-level-0"
style="padding-left:0px"
/>
Tom
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="3"
>
<td
class="ant-table-fixed-columns-in-body ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
<td
class=""
>
<span
class="ant-table-row-indent indent-level-0"
style="padding-left:0px"
/>
Jerry
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
class="ant-table-fixed-left"
>
<div
class="ant-table-body-outer"
style="-webkit-transform:translate3d (0, 0, 0)"
>
<div
class="ant-table-body-inner"
>
<table
class="ant-table-fixed"
>
<colgroup>
<col
class="ant-table-selection-col"
/>
</colgroup>
<thead
class="ant-table-thead"
>
<tr>
<th
class="ant-table-selection-column"
>
<span
class="ant-table-header-column"
>
<div>
<span
class="ant-table-column-title"
>
<div
class="ant-table-selection"
>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</div>
</span>
<span
class="ant-table-column-sorter"
/>
</div>
</span>
</th>
</tr>
</thead>
<tbody
class="ant-table-tbody"
>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="0"
>
<td
class="ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="1"
>
<td
class="ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="2"
>
<td
class="ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
</tr>
<tr
class="ant-table-row ant-table-row-level-0"
data-row-key="3"
>
<td
class="ant-table-selection-column"
>
<span>
<label
class="ant-checkbox-wrapper"
>
<span
class="ant-checkbox"
>
<input
class="ant-checkbox-input"
type="checkbox"
/>
<span
class="ant-checkbox-inner"
/>
</span>
</label>
</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<ul
class="ant-pagination ant-table-pagination"
unselectable="unselectable"
>
<li
aria-disabled="true"
class="ant-pagination-disabled ant-pagination-prev"
title="Previous Page"
>
<a
class="ant-pagination-item-link"
>
<i
aria-label="icon: left"
class="anticon anticon-left"
>
<svg
aria-hidden="true"
class=""
data-icon="left"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 0 0 0 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z"
/>
</svg>
</i>
</a>
</li>
<li
class="ant-pagination-item ant-pagination-item-1 ant-pagination-item-active"
tabindex="0"
title="1"
>
<a>
1
</a>
</li>
<li
aria-disabled="true"
class="ant-pagination-disabled ant-pagination-next"
title="Next Page"
>
<a
class="ant-pagination-item-link"
>
<i
aria-label="icon: right"
class="anticon anticon-right"
>
<svg
aria-hidden="true"
class=""
data-icon="right"
fill="currentColor"
focusable="false"
height="1em"
viewBox="64 64 896 896"
width="1em"
>
<path
d="M765.7 486.8L314.9 134.7A7.97 7.97 0 0 0 302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 0 0 0-50.4z"
/>
</svg>
</i>
</a>
</li>
</ul>
</div>
</div>
</div>
`;
exports[`Table.rowSelection render with default selection correctly 1`] = `
<div>
<div
class="ant-dropdown ant-dropdown-placement-bottomLeft ant-dropdown-hidden"
>
<ul
class="ant-dropdown-menu ant-table-selection-menu ant-dropdown-menu-light ant-dropdown-menu-root ant-dropdown-menu-vertical"
role="menu"
tabindex="0"
>
<li
class="ant-dropdown-menu-item"
role="menuitem"
>
<div>
Select current page
</div>
</li>
<li
class="ant-dropdown-menu-item"
role="menuitem"
>
<div>
Invert current page
</div>
</li>
</ul>
</div>
</div>
`;
|
components/table/__tests__/__snapshots__/Table.rowSelection.test.js.snap
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017523956194054335,
0.00016921731003094465,
0.0001663918956182897,
0.0001687296316958964,
0.0000017472628996983985
] |
{
"id": 1,
"code_window": [
" border-color: @primary-color;\n",
" }\n",
"\n",
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color;\n",
" }\n",
"\n",
" &-selected-day &-date {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 257
}
|
.calendarLeftArrow() {
height: 100%;
&::before,
&::after {
position: relative;
top: -1px;
display: inline-block;
width: 8px;
height: 8px;
vertical-align: middle;
border: 0 solid #aaa;
border-width: 1.5px 0 0 1.5px;
border-radius: 1px;
transform: rotate(-45deg) scale(.8);
transition: all .3s;
content: '';
}
&:hover::before,
&:hover::after {
border-color: @text-color;
}
&::after {
display: none;
}
}
.calendarLeftDoubleArrow() {
.calendarLeftArrow;
&::after {
position: relative;
left: -3px;
display: inline-block;
}
}
.calendarRightArrow() {
.calendarLeftArrow;
&::before,
&::after {
transform: rotate(135deg) scale(.8);
}
}
.calendarRightDoubleArrow() {
.calendarRightArrow;
&::before {
position: relative;
left: 3px;
}
&::after {
display: inline-block;
}
}
.calendarPanelHeader(@calendar-prefix-cls) {
height: 40px;
line-height: 40px;
text-align: center;
border-bottom: @border-width-base @border-style-base @border-color-split;
user-select: none;
a:hover {
color: @link-hover-color;
}
.@{calendar-prefix-cls}-century-select,
.@{calendar-prefix-cls}-decade-select,
.@{calendar-prefix-cls}-year-select,
.@{calendar-prefix-cls}-month-select {
display: inline-block;
padding: 0 2px;
color: @heading-color;
font-weight: 500;
line-height: 40px;
}
.@{calendar-prefix-cls}-century-select-arrow,
.@{calendar-prefix-cls}-decade-select-arrow,
.@{calendar-prefix-cls}-year-select-arrow,
.@{calendar-prefix-cls}-month-select-arrow {
display: none;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-prev-month-btn,
.@{calendar-prefix-cls}-next-month-btn,
.@{calendar-prefix-cls}-prev-year-btn,
.@{calendar-prefix-cls}-next-year-btn {
position: absolute;
top: 0;
display: inline-block;
padding: 0 5px;
color: @text-color-secondary;
font-size: 16px;
font-family: Arial, 'Hiragino Sans GB', 'Microsoft Yahei', 'Microsoft Sans Serif', sans-serif;
line-height: 40px;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-prev-year-btn {
left: 7px;
.calendarLeftDoubleArrow;
}
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-next-year-btn {
right: 7px;
.calendarRightDoubleArrow;
}
.@{calendar-prefix-cls}-prev-month-btn {
left: 29px;
.calendarLeftArrow;
}
.@{calendar-prefix-cls}-next-month-btn {
right: 29px;
.calendarRightArrow;
}
}
.@{calendar-prefix-cls} {
position: relative;
width: 280px;
font-size: @font-size-base;
line-height: @line-height-base;
text-align: left;
list-style: none;
background-color: @component-background;
background-clip: padding-box;
border: @border-width-base @border-style-base @border-color-inverse;
border-radius: @border-radius-base;
outline: none;
box-shadow: @box-shadow-base;
&-input-wrap {
height: 34px;
padding: 6px @control-padding-horizontal - 2px;
border-bottom: @border-width-base @border-style-base @border-color-split;
}
&-input {
width: 100%;
height: 22px;
color: @input-color;
background: @input-bg;
border: 0;
outline: 0;
cursor: auto;
.placeholder;
}
&-week-number {
width: 286px;
&-cell {
text-align: center;
}
}
&-header {
.calendarPanelHeader(@calendar-prefix-cls);
}
&-body {
padding: 8px 12px;
}
table {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
}
table,
th,
td {
text-align: center;
border: 0;
}
&-calendar-table {
margin-bottom: 0;
border-spacing: 0;
}
&-column-header {
width: 33px;
padding: 6px 0;
line-height: 18px;
text-align: center;
.@{calendar-prefix-cls}-column-header-inner {
display: block;
font-weight: normal;
}
}
&-week-number-header {
.@{calendar-prefix-cls}-column-header-inner {
display: none;
}
}
&-cell {
height: 30px;
padding: 3px 0;
}
&-date {
display: block;
width: 24px;
height: 24px;
margin: 0 auto;
padding: 0;
color: @text-color;
line-height: 22px;
text-align: center;
background: transparent;
border: @border-width-base @border-style-base transparent;
border-radius: @border-radius-sm;
transition: background 0.3s ease;
&-panel {
position: relative;
outline: none;
}
&:hover {
background: @item-hover-bg;
cursor: pointer;
}
&:active {
color: @text-color-inverse;
background: @primary-5;
}
}
&-today &-date {
color: @primary-color;
font-weight: bold;
border-color: @primary-color;
}
&-last-month-cell &-date,
&-next-month-btn-day &-date {
color: @disabled-color;
}
&-selected-day &-date {
background: tint(@primary-color, 80%);
}
&-selected-date,
&-selected-start-date,
&-selected-end-date {
.@{calendar-prefix-cls}-date {
color: @text-color-inverse;
background: @primary-color;
border: @border-width-base @border-style-base transparent;
&:hover {
background: @primary-color;
}
}
}
&-disabled-cell &-date {
position: relative;
width: auto;
color: @disabled-color;
background: @disabled-bg;
border: @border-width-base @border-style-base transparent;
border-radius: 0;
cursor: not-allowed;
&:hover {
background: @disabled-bg;
}
}
&-disabled-cell&-selected-day &-date::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.1);
border-radius: @border-radius-sm;
content: '';
}
&-disabled-cell&-today &-date {
position: relative;
padding-right: 5px;
padding-left: 5px;
&::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
border: @border-width-base @border-style-base @disabled-color;
border-radius: @border-radius-sm;
content: ' ';
}
}
&-disabled-cell-first-of-row &-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&-disabled-cell-last-of-row &-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&-footer {
padding: 0 12px;
line-height: 38px;
border-top: @border-width-base @border-style-base @border-color-split;
&:empty {
border-top: 0;
}
&-btn {
display: block;
text-align: center;
}
&-extra {
text-align: left;
}
}
.@{calendar-prefix-cls}-today-btn,
.@{calendar-prefix-cls}-clear-btn {
display: inline-block;
margin: 0 0 0 8px;
text-align: center;
&-disabled {
color: @disabled-color;
cursor: not-allowed;
}
&:only-child {
margin: 0;
}
}
.@{calendar-prefix-cls}-clear-btn {
position: absolute;
top: 7px;
right: 5px;
display: none;
width: 20px;
height: 20px;
margin: 0;
overflow: hidden;
line-height: 20px;
text-align: center;
text-indent: -76px;
}
.@{calendar-prefix-cls}-clear-btn::after {
display: inline-block;
width: 20px;
color: @disabled-color;
font-size: @font-size-base;
line-height: 1;
text-indent: 43px;
transition: color 0.3s ease;
}
.@{calendar-prefix-cls}-clear-btn:hover::after {
color: @text-color-secondary;
}
.@{calendar-prefix-cls}-ok-btn {
.btn;
.btn-primary;
.button-size(@btn-height-sm; @btn-padding-sm; @font-size-base; @border-radius-base);
line-height: @btn-height-sm - 2px;
.button-disabled();
}
}
|
components/date-picker/style/Calendar.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.9904468059539795,
0.02508850023150444,
0.0001647390308789909,
0.00018692039884626865,
0.1545814871788025
] |
{
"id": 1,
"code_window": [
" border-color: @primary-color;\n",
" }\n",
"\n",
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color;\n",
" }\n",
"\n",
" &-selected-day &-date {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 257
}
|
import demoTest from '../../../tests/shared/demoTest';
demoTest('table', {
skip: process.env.REACT === '15' ? ['edit-row', 'drag-sorting'] : [],
});
|
components/table/__tests__/demo.test.js
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017151134670712054,
0.00017151134670712054,
0.00017151134670712054,
0.00017151134670712054,
0
] |
{
"id": 1,
"code_window": [
" border-color: @primary-color;\n",
" }\n",
"\n",
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color;\n",
" }\n",
"\n",
" &-selected-day &-date {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 257
}
|
import demoTest from '../../../tests/shared/demoTest';
demoTest('list');
|
components/list/__tests__/demo.test.js
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0001748975191731006,
0.0001748975191731006,
0.0001748975191731006,
0.0001748975191731006,
0
] |
{
"id": 1,
"code_window": [
" border-color: @primary-color;\n",
" }\n",
"\n",
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color;\n",
" }\n",
"\n",
" &-selected-day &-date {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 257
}
|
const locale = {
placeholder: 'Izaberite vreme',
};
export default locale;
|
components/time-picker/locale/sr_RS.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0001742573076626286,
0.0001742573076626286,
0.0001742573076626286,
0.0001742573076626286,
0
] |
{
"id": 2,
"code_window": [
" &-selected-day &-date {\n",
" background: tint(@primary-color, 80%);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" background: @primary-2;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 263
}
|
.calendarLeftArrow() {
height: 100%;
&::before,
&::after {
position: relative;
top: -1px;
display: inline-block;
width: 8px;
height: 8px;
vertical-align: middle;
border: 0 solid #aaa;
border-width: 1.5px 0 0 1.5px;
border-radius: 1px;
transform: rotate(-45deg) scale(.8);
transition: all .3s;
content: '';
}
&:hover::before,
&:hover::after {
border-color: @text-color;
}
&::after {
display: none;
}
}
.calendarLeftDoubleArrow() {
.calendarLeftArrow;
&::after {
position: relative;
left: -3px;
display: inline-block;
}
}
.calendarRightArrow() {
.calendarLeftArrow;
&::before,
&::after {
transform: rotate(135deg) scale(.8);
}
}
.calendarRightDoubleArrow() {
.calendarRightArrow;
&::before {
position: relative;
left: 3px;
}
&::after {
display: inline-block;
}
}
.calendarPanelHeader(@calendar-prefix-cls) {
height: 40px;
line-height: 40px;
text-align: center;
border-bottom: @border-width-base @border-style-base @border-color-split;
user-select: none;
a:hover {
color: @link-hover-color;
}
.@{calendar-prefix-cls}-century-select,
.@{calendar-prefix-cls}-decade-select,
.@{calendar-prefix-cls}-year-select,
.@{calendar-prefix-cls}-month-select {
display: inline-block;
padding: 0 2px;
color: @heading-color;
font-weight: 500;
line-height: 40px;
}
.@{calendar-prefix-cls}-century-select-arrow,
.@{calendar-prefix-cls}-decade-select-arrow,
.@{calendar-prefix-cls}-year-select-arrow,
.@{calendar-prefix-cls}-month-select-arrow {
display: none;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-prev-month-btn,
.@{calendar-prefix-cls}-next-month-btn,
.@{calendar-prefix-cls}-prev-year-btn,
.@{calendar-prefix-cls}-next-year-btn {
position: absolute;
top: 0;
display: inline-block;
padding: 0 5px;
color: @text-color-secondary;
font-size: 16px;
font-family: Arial, 'Hiragino Sans GB', 'Microsoft Yahei', 'Microsoft Sans Serif', sans-serif;
line-height: 40px;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-prev-year-btn {
left: 7px;
.calendarLeftDoubleArrow;
}
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-next-year-btn {
right: 7px;
.calendarRightDoubleArrow;
}
.@{calendar-prefix-cls}-prev-month-btn {
left: 29px;
.calendarLeftArrow;
}
.@{calendar-prefix-cls}-next-month-btn {
right: 29px;
.calendarRightArrow;
}
}
.@{calendar-prefix-cls} {
position: relative;
width: 280px;
font-size: @font-size-base;
line-height: @line-height-base;
text-align: left;
list-style: none;
background-color: @component-background;
background-clip: padding-box;
border: @border-width-base @border-style-base @border-color-inverse;
border-radius: @border-radius-base;
outline: none;
box-shadow: @box-shadow-base;
&-input-wrap {
height: 34px;
padding: 6px @control-padding-horizontal - 2px;
border-bottom: @border-width-base @border-style-base @border-color-split;
}
&-input {
width: 100%;
height: 22px;
color: @input-color;
background: @input-bg;
border: 0;
outline: 0;
cursor: auto;
.placeholder;
}
&-week-number {
width: 286px;
&-cell {
text-align: center;
}
}
&-header {
.calendarPanelHeader(@calendar-prefix-cls);
}
&-body {
padding: 8px 12px;
}
table {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
}
table,
th,
td {
text-align: center;
border: 0;
}
&-calendar-table {
margin-bottom: 0;
border-spacing: 0;
}
&-column-header {
width: 33px;
padding: 6px 0;
line-height: 18px;
text-align: center;
.@{calendar-prefix-cls}-column-header-inner {
display: block;
font-weight: normal;
}
}
&-week-number-header {
.@{calendar-prefix-cls}-column-header-inner {
display: none;
}
}
&-cell {
height: 30px;
padding: 3px 0;
}
&-date {
display: block;
width: 24px;
height: 24px;
margin: 0 auto;
padding: 0;
color: @text-color;
line-height: 22px;
text-align: center;
background: transparent;
border: @border-width-base @border-style-base transparent;
border-radius: @border-radius-sm;
transition: background 0.3s ease;
&-panel {
position: relative;
outline: none;
}
&:hover {
background: @item-hover-bg;
cursor: pointer;
}
&:active {
color: @text-color-inverse;
background: @primary-5;
}
}
&-today &-date {
color: @primary-color;
font-weight: bold;
border-color: @primary-color;
}
&-last-month-cell &-date,
&-next-month-btn-day &-date {
color: @disabled-color;
}
&-selected-day &-date {
background: tint(@primary-color, 80%);
}
&-selected-date,
&-selected-start-date,
&-selected-end-date {
.@{calendar-prefix-cls}-date {
color: @text-color-inverse;
background: @primary-color;
border: @border-width-base @border-style-base transparent;
&:hover {
background: @primary-color;
}
}
}
&-disabled-cell &-date {
position: relative;
width: auto;
color: @disabled-color;
background: @disabled-bg;
border: @border-width-base @border-style-base transparent;
border-radius: 0;
cursor: not-allowed;
&:hover {
background: @disabled-bg;
}
}
&-disabled-cell&-selected-day &-date::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.1);
border-radius: @border-radius-sm;
content: '';
}
&-disabled-cell&-today &-date {
position: relative;
padding-right: 5px;
padding-left: 5px;
&::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
border: @border-width-base @border-style-base @disabled-color;
border-radius: @border-radius-sm;
content: ' ';
}
}
&-disabled-cell-first-of-row &-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&-disabled-cell-last-of-row &-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&-footer {
padding: 0 12px;
line-height: 38px;
border-top: @border-width-base @border-style-base @border-color-split;
&:empty {
border-top: 0;
}
&-btn {
display: block;
text-align: center;
}
&-extra {
text-align: left;
}
}
.@{calendar-prefix-cls}-today-btn,
.@{calendar-prefix-cls}-clear-btn {
display: inline-block;
margin: 0 0 0 8px;
text-align: center;
&-disabled {
color: @disabled-color;
cursor: not-allowed;
}
&:only-child {
margin: 0;
}
}
.@{calendar-prefix-cls}-clear-btn {
position: absolute;
top: 7px;
right: 5px;
display: none;
width: 20px;
height: 20px;
margin: 0;
overflow: hidden;
line-height: 20px;
text-align: center;
text-indent: -76px;
}
.@{calendar-prefix-cls}-clear-btn::after {
display: inline-block;
width: 20px;
color: @disabled-color;
font-size: @font-size-base;
line-height: 1;
text-indent: 43px;
transition: color 0.3s ease;
}
.@{calendar-prefix-cls}-clear-btn:hover::after {
color: @text-color-secondary;
}
.@{calendar-prefix-cls}-ok-btn {
.btn;
.btn-primary;
.button-size(@btn-height-sm; @btn-padding-sm; @font-size-base; @border-radius-base);
line-height: @btn-height-sm - 2px;
.button-disabled();
}
}
|
components/date-picker/style/Calendar.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.9834024906158447,
0.02512008510529995,
0.00016593655163887888,
0.00016980910731945187,
0.15345482528209686
] |
{
"id": 2,
"code_window": [
" &-selected-day &-date {\n",
" background: tint(@primary-color, 80%);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" background: @primary-2;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 263
}
|
import '../../style/index.less';
import './index.less';
|
components/timeline/style/index.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017916336946655065,
0.00017916336946655065,
0.00017916336946655065,
0.00017916336946655065,
0
] |
{
"id": 2,
"code_window": [
" &-selected-day &-date {\n",
" background: tint(@primary-color, 80%);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" background: @primary-2;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 263
}
|
@import '../../style/themes/index';
@import '../../style/mixins/index';
@notification-prefix-cls: ~'@{ant-prefix}-notification';
@notification-width: 384px;
@notification-padding-vertical: 16px;
@notification-padding-horizontal: 24px;
@notification-padding: @notification-padding-vertical @notification-padding-horizontal;
@notification-margin-bottom: 16px;
.@{notification-prefix-cls} {
.reset-component;
position: fixed;
z-index: @zindex-notification;
width: @notification-width;
max-width: ~'calc(100vw - 32px)';
margin-right: 24px;
&-topLeft,
&-bottomLeft {
margin-right: 0;
margin-left: 24px;
.@{notification-prefix-cls}-fade-enter.@{notification-prefix-cls}-fade-enter-active,
.@{notification-prefix-cls}-fade-appear.@{notification-prefix-cls}-fade-appear-active {
animation-name: NotificationLeftFadeIn;
}
}
&-close-icon {
font-size: @font-size-base;
cursor: pointer;
}
&-notice {
position: relative;
margin-bottom: @notification-margin-bottom;
padding: @notification-padding;
overflow: hidden;
line-height: 1.5;
background: @component-background;
border-radius: @border-radius-base;
box-shadow: @shadow-2;
&-message {
display: inline-block;
margin-bottom: 8px;
color: @heading-color;
font-size: @font-size-lg;
line-height: 24px;
// https://github.com/ant-design/ant-design/issues/5846#issuecomment-296244140
&-single-line-auto-margin {
display: block;
width: ~'calc(@{notification-width} - @{notification-padding-horizontal} * 2 - 24px - 48px - 100%)';
max-width: 4px;
background-color: transparent;
pointer-events: none;
&::before {
display: block;
content: '';
}
}
}
&-description {
font-size: @font-size-base;
}
&-closable &-message {
padding-right: 24px;
}
&-with-icon &-message {
margin-bottom: 4px;
margin-left: 48px;
font-size: @font-size-lg;
}
&-with-icon &-description {
margin-left: 48px;
font-size: @font-size-base;
}
// Icon & color style in different selector level
// https://github.com/ant-design/ant-design/issues/16503
// https://github.com/ant-design/ant-design/issues/15512
&-icon {
position: absolute;
margin-left: 4px;
font-size: 24px;
line-height: 24px;
}
.@{iconfont-css-prefix}&-icon {
&-success {
color: @success-color;
}
&-info {
color: @info-color;
}
&-warning {
color: @warning-color;
}
&-error {
color: @error-color;
}
}
&-close {
position: absolute;
top: 16px;
right: 22px;
color: @text-color-secondary;
outline: none;
&:hover {
color: shade(@text-color-secondary, 40%);
}
}
&-btn {
float: right;
margin-top: 16px;
}
}
.notification-fade-effect {
animation-duration: 0.24s;
animation-timing-function: @ease-in-out;
animation-fill-mode: both;
}
&-fade-enter,
&-fade-appear {
opacity: 0;
.notification-fade-effect();
animation-play-state: paused;
}
&-fade-leave {
.notification-fade-effect();
animation-duration: 0.2s;
animation-play-state: paused;
}
&-fade-enter&-fade-enter-active,
&-fade-appear&-fade-appear-active {
animation-name: NotificationFadeIn;
animation-play-state: running;
}
&-fade-leave&-fade-leave-active {
animation-name: NotificationFadeOut;
animation-play-state: running;
}
}
@keyframes NotificationFadeIn {
0% {
left: @notification-width;
opacity: 0;
}
100% {
left: 0;
opacity: 1;
}
}
@keyframes NotificationLeftFadeIn {
0% {
right: @notification-width;
opacity: 0;
}
100% {
right: 0;
opacity: 1;
}
}
@keyframes NotificationFadeOut {
0% {
max-height: 150px;
margin-bottom: @notification-margin-bottom;
padding-top: @notification-padding;
padding-bottom: @notification-padding;
opacity: 1;
}
100% {
max-height: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
opacity: 0;
}
}
|
components/notification/style/index.less
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00029820058261975646,
0.00017878772632684559,
0.000167004662216641,
0.00016931720892898738,
0.00002946493805211503
] |
{
"id": 2,
"code_window": [
" &-selected-day &-date {\n",
" background: tint(@primary-color, 80%);\n",
" }\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" background: @primary-2;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 263
}
|
/* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import CopyToClipboard from 'react-copy-to-clipboard';
import classNames from 'classnames';
import LZString from 'lz-string';
import { Icon, Tooltip } from 'antd';
import EditButton from './EditButton';
import ErrorBoundary from './ErrorBoundary';
import BrowserFrame from '../BrowserFrame';
function compress(string) {
return LZString.compressToBase64(string)
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
}
export default class Demo extends React.Component {
static contextTypes = {
intl: PropTypes.object,
};
state = {
codeExpand: false,
copied: false,
copyTooltipVisible: false,
};
componentDidMount() {
const { meta, location } = this.props;
if (meta.id === location.hash.slice(1)) {
this.anchor.click();
}
}
shouldComponentUpdate(nextProps, nextState) {
const { codeExpand, copied, copyTooltipVisible } = this.state;
const { expand } = this.props;
return (
(codeExpand || expand) !== (nextState.codeExpand || nextProps.expand) ||
copied !== nextState.copied ||
copyTooltipVisible !== nextState.copyTooltipVisible
);
}
getSourceCode() {
const { highlightedCode } = this.props;
if (typeof document !== 'undefined') {
const div = document.createElement('div');
div.innerHTML = highlightedCode[1].highlighted;
return div.textContent;
}
return '';
}
handleCodeExpand = demo => {
const { codeExpand } = this.state;
this.setState({ codeExpand: !codeExpand });
this.track({
type: 'expand',
demo,
});
};
saveAnchor = anchor => {
this.anchor = anchor;
};
handleCodeCopied = demo => {
this.setState({ copied: true });
this.track({
type: 'copy',
demo,
});
};
onCopyTooltipVisibleChange = visible => {
if (visible) {
this.setState({
copyTooltipVisible: visible,
copied: false,
});
return;
}
this.setState({
copyTooltipVisible: visible,
});
};
// eslint-disable-next-line
track({ type, demo }) {
if (!window.gtag) {
return;
}
window.gtag('event', 'demo', {
event_category: type,
event_label: demo,
});
}
render() {
const { state } = this;
const { props } = this;
const { meta, src, content, preview, highlightedCode, style, highlightedStyle, expand } = props;
const { copied } = state;
if (!this.liveDemo) {
this.liveDemo = meta.iframe ? (
<BrowserFrame>
<iframe src={src} height={meta.iframe} title="demo" />
</BrowserFrame>
) : (
preview(React, ReactDOM)
);
}
const codeExpand = state.codeExpand || expand;
const codeBoxClass = classNames('code-box', {
expand: codeExpand,
'code-box-debug': meta.debug,
});
const {
intl: { locale },
} = this.context;
const localizedTitle = meta.title[locale] || meta.title;
const localizeIntro = content[locale] || content;
const introChildren = props.utils.toReactComponent(['div'].concat(localizeIntro));
const highlightClass = classNames({
'highlight-wrapper': true,
'highlight-wrapper-expand': codeExpand,
});
const prefillStyle = `@import 'antd/dist/antd.css';\n\n${style || ''}`.replace(
new RegExp(`#${meta.id}\\s*`, 'g'),
'',
);
const html = `<div id="container" style="padding: 24px"></div>
<script>
var mountNode = document.getElementById('container');
</script>`;
const sourceCode = this.getSourceCode();
const codepenPrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
html,
js: sourceCode
.replace(/import\s+\{\s+(.*)\s+\}\s+from\s+'antd';/, 'const { $1 } = antd;')
.replace("import moment from 'moment';", '')
.replace(/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router';/, 'const { $1 } = ReactRouter;')
.replace(
/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router-dom';/,
'const { $1 } = ReactRouterDOM;',
)
.replace(/([a-zA-Z]*)\s+as\s+([a-zA-Z]*)/, '$1:$2'),
css: prefillStyle,
editors: '001',
css_external: 'https://unpkg.com/antd/dist/antd.css',
js_external: [
'[email protected]/umd/react.development.js',
'[email protected]/umd/react-dom.development.js',
'moment/min/moment-with-locales.js',
'antd/dist/antd-with-locales.js',
'react-router-dom/umd/react-router-dom.min.js',
'[email protected]/umd/ReactRouter.min.js',
]
.map(url => `https://unpkg.com/${url}`)
.join(';'),
js_pre_processor: 'typescript',
};
const riddlePrefillConfig = {
title: `${localizedTitle} - Ant Design Demo`,
js: sourceCode,
css: prefillStyle,
};
const dependencies = sourceCode.split('\n').reduce(
(acc, line) => {
const matches = line.match(/import .+? from '(.+)';$/);
if (matches && matches[1] && !line.includes('antd')) {
const [dep] = matches[1].split('/');
if (dep) {
acc[dep] = 'latest';
}
}
return acc;
},
{ react: 'latest', 'react-dom': 'latest', antd: 'latest' },
);
const codesanboxPrefillConfig = {
files: {
'package.json': {
content: {
dependencies,
},
},
'index.css': {
content: (style || '').replace(new RegExp(`#${meta.id}\\s*`, 'g'), ''),
},
'index.js': {
content: `
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
${sourceCode.replace('mountNode', "document.getElementById('container')")}
`,
},
'index.html': {
content: html,
},
},
};
return (
<section className={codeBoxClass} id={meta.id}>
<section className="code-box-demo">
<ErrorBoundary>{this.liveDemo}</ErrorBoundary>
{style ? (
<style dangerouslySetInnerHTML={{ __html: style }} /> // eslint-disable-line
) : null}
</section>
<section className="code-box-meta markdown">
<div className="code-box-title">
<Tooltip title={meta.debug ? <FormattedMessage id="app.demo.debug" /> : ''}>
<a href={`#${meta.id}`} ref={this.saveAnchor}>
{localizedTitle}
</a>
</Tooltip>
<EditButton
title={<FormattedMessage id="app.content.edit-demo" />}
filename={meta.filename}
/>
</div>
<div className="code-box-description">{introChildren}</div>
<div className="code-box-actions">
<form
action="//riddle.alibaba-inc.com/riddles/define"
method="POST"
target="_blank"
onClick={() => this.track({ type: 'riddle', demo: meta.id })}
>
<input type="hidden" name="data" value={JSON.stringify(riddlePrefillConfig)} />
<Tooltip title={<FormattedMessage id="app.demo.riddle" />}>
<input
type="submit"
value="Create New Riddle with Prefilled Data"
className="code-box-riddle"
/>
</Tooltip>
</form>
<form
action="https://codepen.io/pen/define"
method="POST"
target="_blank"
onClick={() => this.track({ type: 'codepen', demo: meta.id })}
>
<input type="hidden" name="data" value={JSON.stringify(codepenPrefillConfig)} />
<Tooltip title={<FormattedMessage id="app.demo.codepen" />}>
<input
type="submit"
value="Create New Pen with Prefilled Data"
className="code-box-codepen"
/>
</Tooltip>
</form>
<form
action="https://codesandbox.io/api/v1/sandboxes/define"
method="POST"
target="_blank"
onClick={() => this.track({ type: 'codesandbox', demo: meta.id })}
>
<input
type="hidden"
name="parameters"
value={compress(JSON.stringify(codesanboxPrefillConfig))}
/>
<Tooltip title={<FormattedMessage id="app.demo.codesandbox" />}>
<input
type="submit"
value="Create New Sandbox with Prefilled Data"
className="code-box-codesandbox"
/>
</Tooltip>
</form>
<CopyToClipboard text={sourceCode} onCopy={() => this.handleCodeCopied(meta.id)}>
<Tooltip
visible={state.copyTooltipVisible}
onVisibleChange={this.onCopyTooltipVisibleChange}
title={<FormattedMessage id={`app.demo.${copied ? 'copied' : 'copy'}`} />}
>
<Icon
type={state.copied && state.copyTooltipVisible ? 'check' : 'snippets'}
className="code-box-code-copy"
/>
</Tooltip>
</CopyToClipboard>
<Tooltip
title={<FormattedMessage id={`app.demo.code.${codeExpand ? 'hide' : 'show'}`} />}
>
<span className="code-expand-icon">
<img
alt="expand code"
src="https://gw.alipayobjects.com/zos/rmsportal/wSAkBuJFbdxsosKKpqyq.svg"
className={codeExpand ? 'code-expand-icon-hide' : 'code-expand-icon-show'}
onClick={() => this.handleCodeExpand(meta.id)}
/>
<img
alt="expand code"
src="https://gw.alipayobjects.com/zos/rmsportal/OpROPHYqWmrMDBFMZtKF.svg"
className={codeExpand ? 'code-expand-icon-show' : 'code-expand-icon-hide'}
onClick={() => this.handleCodeExpand(meta.id)}
/>
</span>
</Tooltip>
</div>
</section>
<section className={highlightClass} key="code">
<div className="highlight">{props.utils.toReactComponent(highlightedCode)}</div>
{highlightedStyle ? (
<div key="style" className="highlight">
<pre>
<code className="css" dangerouslySetInnerHTML={{ __html: highlightedStyle }} />
</pre>
</div>
) : null}
</section>
</section>
);
}
}
|
site/theme/template/Content/Demo.jsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00018610275583341718,
0.00017114753427449614,
0.00016550009604543447,
0.000170005951076746,
0.000004313427325541852
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &-selected-date,\n",
" &-selected-start-date,\n",
" &-selected-end-date {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" &-selected-date {\n",
" .calendar-selected-cell;\n",
" }\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 266
}
|
.calendarLeftArrow() {
height: 100%;
&::before,
&::after {
position: relative;
top: -1px;
display: inline-block;
width: 8px;
height: 8px;
vertical-align: middle;
border: 0 solid #aaa;
border-width: 1.5px 0 0 1.5px;
border-radius: 1px;
transform: rotate(-45deg) scale(.8);
transition: all .3s;
content: '';
}
&:hover::before,
&:hover::after {
border-color: @text-color;
}
&::after {
display: none;
}
}
.calendarLeftDoubleArrow() {
.calendarLeftArrow;
&::after {
position: relative;
left: -3px;
display: inline-block;
}
}
.calendarRightArrow() {
.calendarLeftArrow;
&::before,
&::after {
transform: rotate(135deg) scale(.8);
}
}
.calendarRightDoubleArrow() {
.calendarRightArrow;
&::before {
position: relative;
left: 3px;
}
&::after {
display: inline-block;
}
}
.calendarPanelHeader(@calendar-prefix-cls) {
height: 40px;
line-height: 40px;
text-align: center;
border-bottom: @border-width-base @border-style-base @border-color-split;
user-select: none;
a:hover {
color: @link-hover-color;
}
.@{calendar-prefix-cls}-century-select,
.@{calendar-prefix-cls}-decade-select,
.@{calendar-prefix-cls}-year-select,
.@{calendar-prefix-cls}-month-select {
display: inline-block;
padding: 0 2px;
color: @heading-color;
font-weight: 500;
line-height: 40px;
}
.@{calendar-prefix-cls}-century-select-arrow,
.@{calendar-prefix-cls}-decade-select-arrow,
.@{calendar-prefix-cls}-year-select-arrow,
.@{calendar-prefix-cls}-month-select-arrow {
display: none;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-prev-month-btn,
.@{calendar-prefix-cls}-next-month-btn,
.@{calendar-prefix-cls}-prev-year-btn,
.@{calendar-prefix-cls}-next-year-btn {
position: absolute;
top: 0;
display: inline-block;
padding: 0 5px;
color: @text-color-secondary;
font-size: 16px;
font-family: Arial, 'Hiragino Sans GB', 'Microsoft Yahei', 'Microsoft Sans Serif', sans-serif;
line-height: 40px;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-prev-year-btn {
left: 7px;
.calendarLeftDoubleArrow;
}
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-next-year-btn {
right: 7px;
.calendarRightDoubleArrow;
}
.@{calendar-prefix-cls}-prev-month-btn {
left: 29px;
.calendarLeftArrow;
}
.@{calendar-prefix-cls}-next-month-btn {
right: 29px;
.calendarRightArrow;
}
}
.@{calendar-prefix-cls} {
position: relative;
width: 280px;
font-size: @font-size-base;
line-height: @line-height-base;
text-align: left;
list-style: none;
background-color: @component-background;
background-clip: padding-box;
border: @border-width-base @border-style-base @border-color-inverse;
border-radius: @border-radius-base;
outline: none;
box-shadow: @box-shadow-base;
&-input-wrap {
height: 34px;
padding: 6px @control-padding-horizontal - 2px;
border-bottom: @border-width-base @border-style-base @border-color-split;
}
&-input {
width: 100%;
height: 22px;
color: @input-color;
background: @input-bg;
border: 0;
outline: 0;
cursor: auto;
.placeholder;
}
&-week-number {
width: 286px;
&-cell {
text-align: center;
}
}
&-header {
.calendarPanelHeader(@calendar-prefix-cls);
}
&-body {
padding: 8px 12px;
}
table {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
}
table,
th,
td {
text-align: center;
border: 0;
}
&-calendar-table {
margin-bottom: 0;
border-spacing: 0;
}
&-column-header {
width: 33px;
padding: 6px 0;
line-height: 18px;
text-align: center;
.@{calendar-prefix-cls}-column-header-inner {
display: block;
font-weight: normal;
}
}
&-week-number-header {
.@{calendar-prefix-cls}-column-header-inner {
display: none;
}
}
&-cell {
height: 30px;
padding: 3px 0;
}
&-date {
display: block;
width: 24px;
height: 24px;
margin: 0 auto;
padding: 0;
color: @text-color;
line-height: 22px;
text-align: center;
background: transparent;
border: @border-width-base @border-style-base transparent;
border-radius: @border-radius-sm;
transition: background 0.3s ease;
&-panel {
position: relative;
outline: none;
}
&:hover {
background: @item-hover-bg;
cursor: pointer;
}
&:active {
color: @text-color-inverse;
background: @primary-5;
}
}
&-today &-date {
color: @primary-color;
font-weight: bold;
border-color: @primary-color;
}
&-last-month-cell &-date,
&-next-month-btn-day &-date {
color: @disabled-color;
}
&-selected-day &-date {
background: tint(@primary-color, 80%);
}
&-selected-date,
&-selected-start-date,
&-selected-end-date {
.@{calendar-prefix-cls}-date {
color: @text-color-inverse;
background: @primary-color;
border: @border-width-base @border-style-base transparent;
&:hover {
background: @primary-color;
}
}
}
&-disabled-cell &-date {
position: relative;
width: auto;
color: @disabled-color;
background: @disabled-bg;
border: @border-width-base @border-style-base transparent;
border-radius: 0;
cursor: not-allowed;
&:hover {
background: @disabled-bg;
}
}
&-disabled-cell&-selected-day &-date::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.1);
border-radius: @border-radius-sm;
content: '';
}
&-disabled-cell&-today &-date {
position: relative;
padding-right: 5px;
padding-left: 5px;
&::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
border: @border-width-base @border-style-base @disabled-color;
border-radius: @border-radius-sm;
content: ' ';
}
}
&-disabled-cell-first-of-row &-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&-disabled-cell-last-of-row &-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&-footer {
padding: 0 12px;
line-height: 38px;
border-top: @border-width-base @border-style-base @border-color-split;
&:empty {
border-top: 0;
}
&-btn {
display: block;
text-align: center;
}
&-extra {
text-align: left;
}
}
.@{calendar-prefix-cls}-today-btn,
.@{calendar-prefix-cls}-clear-btn {
display: inline-block;
margin: 0 0 0 8px;
text-align: center;
&-disabled {
color: @disabled-color;
cursor: not-allowed;
}
&:only-child {
margin: 0;
}
}
.@{calendar-prefix-cls}-clear-btn {
position: absolute;
top: 7px;
right: 5px;
display: none;
width: 20px;
height: 20px;
margin: 0;
overflow: hidden;
line-height: 20px;
text-align: center;
text-indent: -76px;
}
.@{calendar-prefix-cls}-clear-btn::after {
display: inline-block;
width: 20px;
color: @disabled-color;
font-size: @font-size-base;
line-height: 1;
text-indent: 43px;
transition: color 0.3s ease;
}
.@{calendar-prefix-cls}-clear-btn:hover::after {
color: @text-color-secondary;
}
.@{calendar-prefix-cls}-ok-btn {
.btn;
.btn-primary;
.button-size(@btn-height-sm; @btn-padding-sm; @font-size-base; @border-radius-base);
line-height: @btn-height-sm - 2px;
.button-disabled();
}
}
|
components/date-picker/style/Calendar.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.27533313632011414,
0.007215362973511219,
0.0001663918956182897,
0.00021653299336321652,
0.042934395372867584
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &-selected-date,\n",
" &-selected-start-date,\n",
" &-selected-end-date {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" &-selected-date {\n",
" .calendar-selected-cell;\n",
" }\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 266
}
|
---
order: 0
title:
zh-CN: 按钮类型
en-US: Type
---
## zh-CN
按钮有五种类型:主按钮、次按钮、虚线按钮、危险按钮和链接按钮。主按钮在同一个操作区域最多出现一次。
## en-US
There are `primary` button, `default` button, `dashed` button, `danger` button and `link` button in antd.
```jsx
import { Button } from 'antd';
ReactDOM.render(
<div>
<Button type="primary">Primary</Button>
<Button>Default</Button>
<Button type="dashed">Dashed</Button>
<Button type="danger">Danger</Button>
<Button type="link">Link</Button>
</div>,
mountNode,
);
```
|
components/button/demo/basic.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017215394473169,
0.0001693426165729761,
0.00016747874906286597,
0.0001683951704762876,
0.0000020228051198500907
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &-selected-date,\n",
" &-selected-start-date,\n",
" &-selected-end-date {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" &-selected-date {\n",
" .calendar-selected-cell;\n",
" }\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 266
}
|
import demoTest from '../../../tests/shared/demoTest';
demoTest('select');
|
components/select/__tests__/demo.test.js
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017316776211373508,
0.00017316776211373508,
0.00017316776211373508,
0.00017316776211373508,
0
] |
{
"id": 3,
"code_window": [
" }\n",
"\n",
" &-selected-date,\n",
" &-selected-start-date,\n",
" &-selected-end-date {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @text-color-inverse;\n",
" background: @primary-color;\n",
" border: @border-width-base @border-style-base transparent;\n",
"\n"
],
"labels": [
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" &-selected-date {\n",
" .calendar-selected-cell;\n",
" }\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 266
}
|
import React from 'react';
import { mount } from 'enzyme';
import Drawer from '..';
import Button from '../../button';
class MultiDrawer extends React.Component {
state = { visible: false, childrenDrawer: false, hasChildren: true };
showDrawer = () => {
this.setState({
visible: true,
hasChildren: true,
});
};
onClose = () => {
this.setState({
visible: false,
});
};
showChildrenDrawer = () => {
this.setState({
childrenDrawer: true,
hasChildren: true,
});
};
onChildrenDrawerClose = () => {
this.setState({
childrenDrawer: false,
});
};
onRemoveChildDrawer = () => {
this.setState({
hasChildren: false,
});
};
render() {
const { childrenDrawer, visible, hasChildren } = this.state;
const { placement } = this.props;
return (
<div>
<Button type="primary" id="open_drawer" onClick={this.showDrawer}>
Open drawer
</Button>
<Button type="primary" id="remove_drawer" onClick={this.onRemoveChildDrawer}>
rm child drawer
</Button>
<Drawer
title="Multi-level drawer"
className="test_drawer"
width={520}
onClose={this.onClose}
getContainer={false}
placement={placement}
visible={visible}
>
<Button type="primary" id="open_two_drawer" onClick={this.showChildrenDrawer}>
Two-level drawer
</Button>
{hasChildren && (
<Drawer
title="Two-level Drawer"
width={320}
className="Two-level"
getContainer={false}
placement={placement}
onClose={this.onChildrenDrawerClose}
visible={childrenDrawer}
>
<div id="two_drawer_text">This is two-level drawer</div>
</Drawer>
)}
<div
style={{
position: 'absolute',
bottom: 0,
width: '100%',
borderTop: '1px solid #e8e8e8',
padding: '10px 16px',
textAlign: 'right',
left: 0,
background: '#fff',
borderRadius: '0 0 4px 4px',
}}
>
<Button
style={{
marginRight: 8,
}}
onClick={this.onClose}
>
Cancel
</Button>
<Button onClick={this.onClose} type="primary">
Submit
</Button>
</div>
</Drawer>
</div>
);
}
}
describe('Drawer', () => {
it('render right MultiDrawer', () => {
const wrapper = mount(<MultiDrawer placement="right" />);
wrapper.find('button#open_drawer').simulate('click');
wrapper.find('button#open_two_drawer').simulate('click');
const translateX = wrapper.find('.ant-drawer.test_drawer').get(0).props.style.transform;
expect(translateX).toEqual('translateX(-180px)');
expect(wrapper.find('#two_drawer_text').exists()).toBe(true);
});
it('render left MultiDrawer', () => {
const wrapper = mount(<MultiDrawer placement="left" />);
wrapper.find('button#open_drawer').simulate('click');
wrapper.find('button#open_two_drawer').simulate('click');
const translateX = wrapper.find('.ant-drawer.test_drawer').get(0).props.style.transform;
expect(translateX).toEqual('translateX(180px)');
expect(wrapper.find('#two_drawer_text').exists()).toBe(true);
wrapper.find('.Two-level .ant-drawer-close').simulate('click');
expect(wrapper.state().childrenDrawer).toBe(false);
});
it('render top MultiDrawer', () => {
const wrapper = mount(<MultiDrawer placement="top" />);
wrapper.find('button#open_drawer').simulate('click');
wrapper.find('button#open_two_drawer').simulate('click');
const translateX = wrapper.find('.ant-drawer.test_drawer').get(0).props.style.transform;
expect(translateX).toEqual('translateY(180px)');
expect(wrapper.find('#two_drawer_text').exists()).toBe(true);
});
it('render MultiDrawer is child in unmount', () => {
const wrapper = mount(<MultiDrawer placement="top" mask={false} />);
wrapper.find('button#open_drawer').simulate('click');
wrapper.find('button#open_two_drawer').simulate('click');
wrapper.find('button#remove_drawer').simulate('click');
let translateX = wrapper.find('.ant-drawer.test_drawer').get(0).props.style.transform;
expect(translateX).toEqual(undefined);
wrapper.find('button#open_two_drawer').simulate('click');
translateX = wrapper.find('.ant-drawer.test_drawer').get(0).props.style.transform;
expect(translateX).toEqual('translateY(180px)');
expect(wrapper.find('#two_drawer_text').exists()).toBe(true);
});
});
|
components/drawer/__tests__/MultiDrawer.test.js
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0001792414695955813,
0.00017287960508838296,
0.0001682442962191999,
0.00017230756930075586,
0.000003629837692642468
] |
{
"id": 4,
"code_window": [
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-disabled-cell &-date {\n",
" position: relative;\n",
" width: auto;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color !important;\n",
" background: transparent !important;;\n",
" border-color: transparent !important;;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 274
}
|
@input-box-height: 34px;
.@{calendar-prefix-cls}-range-picker-input {
width: 44%;
height: 99%;
text-align: center;
background-color: transparent;
border: 0;
outline: 0;
.placeholder();
&[disabled] {
cursor: not-allowed;
}
}
.@{calendar-prefix-cls}-range-picker-separator {
display: inline-block;
min-width: 10px;
height: 100%;
color: @text-color-secondary;
white-space: nowrap;
text-align: center;
vertical-align: top;
pointer-events: none;
}
.@{calendar-prefix-cls}-range {
width: 552px;
overflow: hidden;
.@{calendar-prefix-cls}-date-panel {
&::after {
display: block;
clear: both;
height: 0;
visibility: hidden;
content: '.';
}
}
&-part {
position: relative;
width: 50%;
}
&-left {
float: left;
.@{calendar-prefix-cls} {
&-time-picker-inner {
border-right: 1px solid @border-color-split;
}
}
}
&-right {
float: right;
.@{calendar-prefix-cls} {
&-time-picker-inner {
border-left: 1px solid @border-color-split;
}
}
}
&-middle {
position: absolute;
left: 50%;
z-index: 1;
height: @input-box-height;
margin: 1px 0 0 0;
padding: 0 200px 0 0;
color: @text-color-secondary;
line-height: @input-box-height;
text-align: center;
transform: translateX(-50%);
pointer-events: none;
}
&-right .@{calendar-prefix-cls}-date-input-wrap {
margin-left: -90px;
}
&.@{calendar-prefix-cls}-time &-middle {
padding: 0 10px 0 0;
transform: translateX(-50%);
}
&.@{calendar-prefix-cls}-time &-right .@{calendar-prefix-cls}-date-input-wrap {
margin-left: 0;
}
.@{calendar-prefix-cls}-input-wrap {
position: relative;
height: @input-box-height;
}
.@{calendar-prefix-cls}-input,
.@{calendar-timepicker-prefix-cls}-input {
.input;
height: @input-height-sm;
padding-right: 0;
padding-left: 0;
line-height: @input-height-sm;
border: 0;
box-shadow: none;
&:focus {
box-shadow: none;
}
}
.@{calendar-timepicker-prefix-cls}-icon {
display: none;
}
&.@{calendar-prefix-cls}-week-number {
width: 574px;
.@{calendar-prefix-cls}-range-part {
width: 286px;
}
}
.@{calendar-prefix-cls}-year-panel,
.@{calendar-prefix-cls}-month-panel,
.@{calendar-prefix-cls}-decade-panel {
top: @input-box-height;
}
.@{calendar-prefix-cls}-month-panel .@{calendar-prefix-cls}-year-panel {
top: 0;
}
.@{calendar-prefix-cls}-decade-panel-table,
.@{calendar-prefix-cls}-year-panel-table,
.@{calendar-prefix-cls}-month-panel-table {
height: 208px;
}
.@{calendar-prefix-cls}-in-range-cell {
position: relative;
border-radius: 0;
> div {
position: relative;
z-index: 1;
}
&::before {
position: absolute;
top: 4px;
right: 0;
bottom: 4px;
left: 0;
display: block;
background: @item-active-bg;
border: 0;
border-radius: 0;
content: '';
}
}
.@{calendar-prefix-cls}-footer-extra {
float: left;
}
// `div` for selector specificity
div&-quick-selector {
text-align: left;
> a {
margin-right: 8px;
}
}
.@{calendar-prefix-cls},
.@{calendar-prefix-cls}-month-panel,
.@{calendar-prefix-cls}-year-panel {
&-header {
border-bottom: 0;
}
&-body {
border-top: @border-width-base @border-style-base @border-color-split;
}
}
&.@{calendar-prefix-cls}-time {
.@{calendar-timepicker-prefix-cls} {
top: 68px;
z-index: 2; // cover .ant-calendar-range .ant-calendar-in-range-cell > div (z-index: 1)
width: 100%;
height: 207px;
&-panel {
height: 267px;
margin-top: -34px;
}
&-inner {
height: 100%;
padding-top: 40px;
background: none;
}
&-combobox {
display: inline-block;
height: 100%;
background-color: @component-background;
border-top: @border-width-base @border-style-base @border-color-split;
}
&-select {
height: 100%;
ul {
max-height: 100%;
}
}
}
.@{calendar-prefix-cls}-footer .@{calendar-prefix-cls}-time-picker-btn {
margin-right: 8px;
}
.@{calendar-prefix-cls}-today-btn {
height: 22px;
margin: 8px 12px;
line-height: 22px;
}
}
&-with-ranges.@{calendar-prefix-cls}-time .@{calendar-timepicker-prefix-cls} {
height: 233px;
}
}
.@{calendar-prefix-cls}-range.@{calendar-prefix-cls}-show-time-picker {
.@{calendar-prefix-cls}-body {
border-top-color: transparent;
}
}
|
components/date-picker/style/RangePicker.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0051959180273115635,
0.0006187311955727637,
0.00016253961075562984,
0.0001677801919868216,
0.0013724551536142826
] |
{
"id": 4,
"code_window": [
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-disabled-cell &-date {\n",
" position: relative;\n",
" width: auto;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color !important;\n",
" background: transparent !important;;\n",
" border-color: transparent !important;;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 274
}
|
---
order: 99
title:
zh-CN: 提交修改前看看这个对不对
en-US: Please check this before commit
debug: true
---
## zh-CN
提交修改前看看这个对不对。
## en-US
Please check this before commit.
```jsx
import { Button, Modal, Form, Row, Col, Input, Select, InputNumber, Radio, DatePicker } from 'antd';
const ColSpan = { lg: 12, md: 24 };
class App extends React.Component {
constructor() {
super();
this.state = {
visible: false,
};
}
handleClick = () => {
this.setState({
visible: true,
});
};
handleCancel = () => {
this.setState({
visible: false,
});
};
handleSubmit = e => {
e.preventDefault();
const { form } = this.props;
form.validateFields((error, values) => {
console.log(error, values);
});
};
render() {
const {
form: { getFieldDecorator },
} = this.props;
const { Item } = Form;
const itemLayout = {
labelCol: { span: 6 },
wrapperCol: { span: 16 },
};
const span = 12;
return (
<div>
{/* Case 1: Form in modal */}
<Button onClick={this.handleClick}>打开</Button>
<Modal
onOk={this.handleSubmit}
onCancel={this.handleCancel}
title="弹出层"
visible={this.state.visible}
>
<Form layout="horizontal" onSubmit={this.handleSubmit}>
<Row>
<Col span={span}>
<Item colon={false} {...itemLayout} label="测试字段">
{getFieldDecorator('item1', {
rules: [{ required: true, message: '请必须填写此字段' }],
})(<Input />)}
</Item>
</Col>
<Col span={span}>
<Item {...itemLayout} label="测试字段">
{getFieldDecorator('item2', {
rules: [{ required: true, message: '请必须填写此字段' }],
})(<Input />)}
</Item>
</Col>
<Col span={span}>
<Item {...itemLayout} label="测试字段">
{getFieldDecorator('item3')(<Input />)}
</Item>
</Col>
<Col span={span}>
<Item {...itemLayout} label="测试字段">
{getFieldDecorator('item4', {
rules: [{ required: true, message: '请必须填写此字段' }],
})(<Input />)}
</Item>
</Col>
<Col span={span}>
<Item {...itemLayout} label="测试字段">
{getFieldDecorator('item5', {
rules: [{ required: true, message: '请必须填写此字段' }],
})(<Input />)}
</Item>
</Col>
<Col span={span}>
<Item {...itemLayout} label="测试字段">
{getFieldDecorator('item6', {
rules: [{ required: true, message: '请必须填写此字段' }],
})(<Input />)}
</Item>
</Col>
</Row>
</Form>
</Modal>
{/* case 2: Form different item */}
<Form>
<Row gutter={16}>
<Col {...ColSpan}>
<Item colon={false} label="input:64.5px">
<Input />
</Item>
</Col>
<Col {...ColSpan}>
<Item label="select:64px">
<Select />
</Item>
</Col>
<Col {...ColSpan}>
<Item label="InputNumber:64px">
<InputNumber />
</Item>
</Col>
<Col {...ColSpan}>
<Item label="DatePicker: 64.5px">
<DatePicker />
</Item>
</Col>
<Col {...ColSpan}>
<Item label="RadioGroup: 64px">
<Radio.Group>
<Radio value={0}>男</Radio>
<Radio value={1}>女</Radio>
</Radio.Group>
</Item>
</Col>
</Row>
</Form>
</div>
);
}
}
const WrapApp = Form.create()(App);
ReactDOM.render(<WrapApp />, mountNode);
```
|
components/form/demo/style-check-debug.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017572849174030125,
0.00017153513908851892,
0.00016619922826066613,
0.00017203015158884227,
0.0000027535302251635585
] |
{
"id": 4,
"code_window": [
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-disabled-cell &-date {\n",
" position: relative;\n",
" width: auto;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color !important;\n",
" background: transparent !important;;\n",
" border-color: transparent !important;;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 274
}
|
import CalendarLocale from 'rc-calendar/lib/locale/nl_NL';
import TimePickerLocale from '../../time-picker/locale/nl_NL';
// Merge into a locale object
const locale = {
lang: {
placeholder: 'Selecteer datum',
rangePlaceholder: ['Begin datum', 'Eind datum'],
...CalendarLocale,
},
timePickerLocale: {
...TimePickerLocale,
},
};
// All settings at:
// https://github.com/ant-design/ant-design/issues/424
export default locale;
|
components/date-picker/locale/nl_NL.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0001711875229375437,
0.00016887288074940443,
0.00016655823856126517,
0.00016887288074940443,
0.00000231464218813926
] |
{
"id": 4,
"code_window": [
"\n",
" &:hover {\n",
" background: @primary-color;\n",
" }\n",
" }\n",
" }\n",
"\n",
" &-disabled-cell &-date {\n",
" position: relative;\n",
" width: auto;\n"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" &-last-month-cell &-date,\n",
" &-next-month-btn-day &-date {\n",
" color: @disabled-color !important;\n",
" background: transparent !important;;\n",
" border-color: transparent !important;;\n"
],
"file_path": "components/date-picker/style/Calendar.less",
"type": "replace",
"edit_start_line_idx": 274
}
|
import * as React from 'react';
import { polyfill } from 'react-lifecycles-compat';
import TimePickerPanel from 'rc-time-picker/lib/Panel';
import classNames from 'classnames';
import * as moment from 'moment';
import enUS from './locale/en_US';
import interopDefault from '../_util/interopDefault';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import { generateShowHourMinuteSecond } from '../time-picker';
import { ConfigConsumer, ConfigConsumerProps } from '../config-provider';
import warning from '../_util/warning';
type PickerType = 'date' | 'week' | 'month';
interface PickerMap {
[name: string]: string;
}
const DEFAULT_FORMAT: PickerMap = {
date: 'YYYY-MM-DD',
dateTime: 'YYYY-MM-DD HH:mm:ss',
week: 'gggg-wo',
month: 'YYYY-MM',
};
const LOCALE_FORMAT_MAPPING: PickerMap = {
date: 'dateFormat',
dateTime: 'dateTimeFormat',
week: 'weekFormat',
month: 'monthFormat',
};
function getColumns({ showHour, showMinute, showSecond, use12Hours }: any) {
let column = 0;
if (showHour) {
column += 1;
}
if (showMinute) {
column += 1;
}
if (showSecond) {
column += 1;
}
if (use12Hours) {
column += 1;
}
return column;
}
function checkValidate(value: any, propName: string) {
const values: any[] = Array.isArray(value) ? value : [value];
values.forEach(val => {
if (!val) return;
warning(
!interopDefault(moment).isMoment(val) || val.isValid(),
'DatePicker',
`\`${propName}\` provides invalidate moment time. If you want to set empty value, use \`null\` instead.`,
);
});
}
export default function wrapPicker(Picker: React.ComponentClass<any>, pickerType: PickerType): any {
class PickerWrapper extends React.Component<any, any> {
static defaultProps = {
transitionName: 'slide-up',
popupStyle: {},
onChange() {},
onOk() {},
onOpenChange() {},
locale: {},
};
static getDerivedStateFromProps({ value, defaultValue }: any) {
checkValidate(defaultValue, 'defaultValue');
checkValidate(value, 'value');
return {};
}
// Since we need call `getDerivedStateFromProps` for check. Need leave an empty `state` here.
state = {};
private picker: any;
componentDidMount() {
const { autoFocus, disabled } = this.props;
if (autoFocus && !disabled) {
this.focus();
}
}
handleOpenChange = (open: boolean) => {
const { onOpenChange } = this.props;
onOpenChange(open);
};
handleFocus: React.FocusEventHandler<HTMLInputElement> = e => {
const { onFocus } = this.props;
if (onFocus) {
onFocus(e);
}
};
handleBlur: React.FocusEventHandler<HTMLInputElement> = e => {
const { onBlur } = this.props;
if (onBlur) {
onBlur(e);
}
};
handleMouseEnter: React.MouseEventHandler<HTMLInputElement> = e => {
const { onMouseEnter } = this.props;
if (onMouseEnter) {
onMouseEnter(e);
}
};
handleMouseLeave: React.MouseEventHandler<HTMLInputElement> = e => {
const { onMouseLeave } = this.props;
if (onMouseLeave) {
onMouseLeave(e);
}
};
focus() {
this.picker.focus();
}
blur() {
this.picker.blur();
}
savePicker = (node: any) => {
this.picker = node;
};
getDefaultLocale = () => {
const result = {
...enUS,
...this.props.locale,
};
result.lang = {
...result.lang,
...(this.props.locale || {}).lang,
};
return result;
};
renderPicker = (locale: any, localeCode: string) => {
const { format, showTime } = this.props;
const mergedPickerType = showTime ? `${pickerType}Time` : pickerType;
const mergedFormat =
format ||
locale[LOCALE_FORMAT_MAPPING[mergedPickerType]] ||
DEFAULT_FORMAT[mergedPickerType];
return (
<ConfigConsumer>
{({ getPrefixCls, getPopupContainer: getContextPopupContainer }: ConfigConsumerProps) => {
const {
prefixCls: customizePrefixCls,
inputPrefixCls: customizeInputPrefixCls,
getCalendarContainer,
size,
disabled,
} = this.props;
const getPopupContainer = getCalendarContainer || getContextPopupContainer;
const prefixCls = getPrefixCls('calendar', customizePrefixCls);
const inputPrefixCls = getPrefixCls('input', customizeInputPrefixCls);
const pickerClass = classNames(`${prefixCls}-picker`, {
[`${prefixCls}-picker-${size}`]: !!size,
});
const pickerInputClass = classNames(`${prefixCls}-picker-input`, inputPrefixCls, {
[`${inputPrefixCls}-lg`]: size === 'large',
[`${inputPrefixCls}-sm`]: size === 'small',
[`${inputPrefixCls}-disabled`]: disabled,
});
const timeFormat = (showTime && showTime.format) || 'HH:mm:ss';
const rcTimePickerProps = {
...generateShowHourMinuteSecond(timeFormat),
format: timeFormat,
use12Hours: showTime && showTime.use12Hours,
};
const columns = getColumns(rcTimePickerProps);
const timePickerCls = `${prefixCls}-time-picker-column-${columns}`;
const timePicker = showTime ? (
<TimePickerPanel
{...rcTimePickerProps}
{...showTime}
prefixCls={`${prefixCls}-time-picker`}
className={timePickerCls}
placeholder={locale.timePickerLocale.placeholder}
transitionName="slide-up"
/>
) : null;
return (
<Picker
{...this.props}
getCalendarContainer={getPopupContainer}
format={mergedFormat}
ref={this.savePicker}
pickerClass={pickerClass}
pickerInputClass={pickerInputClass}
locale={locale}
localeCode={localeCode}
timePicker={timePicker}
onOpenChange={this.handleOpenChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
/>
);
}}
</ConfigConsumer>
);
};
render() {
return (
<LocaleReceiver componentName="DatePicker" defaultLocale={this.getDefaultLocale}>
{this.renderPicker}
</LocaleReceiver>
);
}
}
polyfill(PickerWrapper);
return PickerWrapper;
}
|
components/date-picker/wrapPicker.tsx
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.000292001583147794,
0.000178771311766468,
0.00016677168605383486,
0.00017101364210247993,
0.000025333287339890376
] |
{
"id": 5,
"code_window": [
" &.@{calendar-prefix-cls}-time &-middle {\n",
" padding: 0 10px 0 0;\n",
" transform: translateX(-50%);\n",
" }\n",
"\n",
" &.@{calendar-prefix-cls}-time &-right .@{calendar-prefix-cls}-date-input-wrap {\n",
" margin-left: 0;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .@{calendar-prefix-cls}-today {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @primary-color;\n",
" background: @primary-2;\n",
" border-color: @primary-color;\n",
" }\n",
" }\n",
"\n",
" .@{calendar-prefix-cls}-selected-start-date,\n",
" .@{calendar-prefix-cls}-selected-end-date {\n",
" .calendar-selected-cell;\n",
" }\n",
"\n"
],
"file_path": "components/date-picker/style/RangePicker.less",
"type": "add",
"edit_start_line_idx": 86
}
|
.calendarLeftArrow() {
height: 100%;
&::before,
&::after {
position: relative;
top: -1px;
display: inline-block;
width: 8px;
height: 8px;
vertical-align: middle;
border: 0 solid #aaa;
border-width: 1.5px 0 0 1.5px;
border-radius: 1px;
transform: rotate(-45deg) scale(.8);
transition: all .3s;
content: '';
}
&:hover::before,
&:hover::after {
border-color: @text-color;
}
&::after {
display: none;
}
}
.calendarLeftDoubleArrow() {
.calendarLeftArrow;
&::after {
position: relative;
left: -3px;
display: inline-block;
}
}
.calendarRightArrow() {
.calendarLeftArrow;
&::before,
&::after {
transform: rotate(135deg) scale(.8);
}
}
.calendarRightDoubleArrow() {
.calendarRightArrow;
&::before {
position: relative;
left: 3px;
}
&::after {
display: inline-block;
}
}
.calendarPanelHeader(@calendar-prefix-cls) {
height: 40px;
line-height: 40px;
text-align: center;
border-bottom: @border-width-base @border-style-base @border-color-split;
user-select: none;
a:hover {
color: @link-hover-color;
}
.@{calendar-prefix-cls}-century-select,
.@{calendar-prefix-cls}-decade-select,
.@{calendar-prefix-cls}-year-select,
.@{calendar-prefix-cls}-month-select {
display: inline-block;
padding: 0 2px;
color: @heading-color;
font-weight: 500;
line-height: 40px;
}
.@{calendar-prefix-cls}-century-select-arrow,
.@{calendar-prefix-cls}-decade-select-arrow,
.@{calendar-prefix-cls}-year-select-arrow,
.@{calendar-prefix-cls}-month-select-arrow {
display: none;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-prev-month-btn,
.@{calendar-prefix-cls}-next-month-btn,
.@{calendar-prefix-cls}-prev-year-btn,
.@{calendar-prefix-cls}-next-year-btn {
position: absolute;
top: 0;
display: inline-block;
padding: 0 5px;
color: @text-color-secondary;
font-size: 16px;
font-family: Arial, 'Hiragino Sans GB', 'Microsoft Yahei', 'Microsoft Sans Serif', sans-serif;
line-height: 40px;
}
.@{calendar-prefix-cls}-prev-century-btn,
.@{calendar-prefix-cls}-prev-decade-btn,
.@{calendar-prefix-cls}-prev-year-btn {
left: 7px;
.calendarLeftDoubleArrow;
}
.@{calendar-prefix-cls}-next-century-btn,
.@{calendar-prefix-cls}-next-decade-btn,
.@{calendar-prefix-cls}-next-year-btn {
right: 7px;
.calendarRightDoubleArrow;
}
.@{calendar-prefix-cls}-prev-month-btn {
left: 29px;
.calendarLeftArrow;
}
.@{calendar-prefix-cls}-next-month-btn {
right: 29px;
.calendarRightArrow;
}
}
.@{calendar-prefix-cls} {
position: relative;
width: 280px;
font-size: @font-size-base;
line-height: @line-height-base;
text-align: left;
list-style: none;
background-color: @component-background;
background-clip: padding-box;
border: @border-width-base @border-style-base @border-color-inverse;
border-radius: @border-radius-base;
outline: none;
box-shadow: @box-shadow-base;
&-input-wrap {
height: 34px;
padding: 6px @control-padding-horizontal - 2px;
border-bottom: @border-width-base @border-style-base @border-color-split;
}
&-input {
width: 100%;
height: 22px;
color: @input-color;
background: @input-bg;
border: 0;
outline: 0;
cursor: auto;
.placeholder;
}
&-week-number {
width: 286px;
&-cell {
text-align: center;
}
}
&-header {
.calendarPanelHeader(@calendar-prefix-cls);
}
&-body {
padding: 8px 12px;
}
table {
width: 100%;
max-width: 100%;
background-color: transparent;
border-collapse: collapse;
}
table,
th,
td {
text-align: center;
border: 0;
}
&-calendar-table {
margin-bottom: 0;
border-spacing: 0;
}
&-column-header {
width: 33px;
padding: 6px 0;
line-height: 18px;
text-align: center;
.@{calendar-prefix-cls}-column-header-inner {
display: block;
font-weight: normal;
}
}
&-week-number-header {
.@{calendar-prefix-cls}-column-header-inner {
display: none;
}
}
&-cell {
height: 30px;
padding: 3px 0;
}
&-date {
display: block;
width: 24px;
height: 24px;
margin: 0 auto;
padding: 0;
color: @text-color;
line-height: 22px;
text-align: center;
background: transparent;
border: @border-width-base @border-style-base transparent;
border-radius: @border-radius-sm;
transition: background 0.3s ease;
&-panel {
position: relative;
outline: none;
}
&:hover {
background: @item-hover-bg;
cursor: pointer;
}
&:active {
color: @text-color-inverse;
background: @primary-5;
}
}
&-today &-date {
color: @primary-color;
font-weight: bold;
border-color: @primary-color;
}
&-last-month-cell &-date,
&-next-month-btn-day &-date {
color: @disabled-color;
}
&-selected-day &-date {
background: tint(@primary-color, 80%);
}
&-selected-date,
&-selected-start-date,
&-selected-end-date {
.@{calendar-prefix-cls}-date {
color: @text-color-inverse;
background: @primary-color;
border: @border-width-base @border-style-base transparent;
&:hover {
background: @primary-color;
}
}
}
&-disabled-cell &-date {
position: relative;
width: auto;
color: @disabled-color;
background: @disabled-bg;
border: @border-width-base @border-style-base transparent;
border-radius: 0;
cursor: not-allowed;
&:hover {
background: @disabled-bg;
}
}
&-disabled-cell&-selected-day &-date::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.1);
border-radius: @border-radius-sm;
content: '';
}
&-disabled-cell&-today &-date {
position: relative;
padding-right: 5px;
padding-left: 5px;
&::before {
position: absolute;
top: -1px;
left: 5px;
width: 24px;
height: 24px;
border: @border-width-base @border-style-base @disabled-color;
border-radius: @border-radius-sm;
content: ' ';
}
}
&-disabled-cell-first-of-row &-date {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
&-disabled-cell-last-of-row &-date {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
&-footer {
padding: 0 12px;
line-height: 38px;
border-top: @border-width-base @border-style-base @border-color-split;
&:empty {
border-top: 0;
}
&-btn {
display: block;
text-align: center;
}
&-extra {
text-align: left;
}
}
.@{calendar-prefix-cls}-today-btn,
.@{calendar-prefix-cls}-clear-btn {
display: inline-block;
margin: 0 0 0 8px;
text-align: center;
&-disabled {
color: @disabled-color;
cursor: not-allowed;
}
&:only-child {
margin: 0;
}
}
.@{calendar-prefix-cls}-clear-btn {
position: absolute;
top: 7px;
right: 5px;
display: none;
width: 20px;
height: 20px;
margin: 0;
overflow: hidden;
line-height: 20px;
text-align: center;
text-indent: -76px;
}
.@{calendar-prefix-cls}-clear-btn::after {
display: inline-block;
width: 20px;
color: @disabled-color;
font-size: @font-size-base;
line-height: 1;
text-indent: 43px;
transition: color 0.3s ease;
}
.@{calendar-prefix-cls}-clear-btn:hover::after {
color: @text-color-secondary;
}
.@{calendar-prefix-cls}-ok-btn {
.btn;
.btn-primary;
.button-size(@btn-height-sm; @btn-padding-sm; @font-size-base; @border-radius-base);
line-height: @btn-height-sm - 2px;
.button-disabled();
}
}
|
components/date-picker/style/Calendar.less
| 1 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00790395587682724,
0.000837907544337213,
0.0001640982663957402,
0.0002948693872895092,
0.0014484154526144266
] |
{
"id": 5,
"code_window": [
" &.@{calendar-prefix-cls}-time &-middle {\n",
" padding: 0 10px 0 0;\n",
" transform: translateX(-50%);\n",
" }\n",
"\n",
" &.@{calendar-prefix-cls}-time &-right .@{calendar-prefix-cls}-date-input-wrap {\n",
" margin-left: 0;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .@{calendar-prefix-cls}-today {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @primary-color;\n",
" background: @primary-2;\n",
" border-color: @primary-color;\n",
" }\n",
" }\n",
"\n",
" .@{calendar-prefix-cls}-selected-start-date,\n",
" .@{calendar-prefix-cls}-selected-end-date {\n",
" .calendar-selected-cell;\n",
" }\n",
"\n"
],
"file_path": "components/date-picker/style/RangePicker.less",
"type": "add",
"edit_start_line_idx": 86
}
|
---
order: 3
title:
zh-CN: 日期时间选择
en-US: Choose Time
---
## zh-CN
增加选择时间功能,当 `showTime` 为一个对象时,其属性会传递给内建的 `TimePicker`。
## en-US
This property provide an additional time selection. When `showTime` is an Object, its properties will be passed on to built-in `TimePicker`.
```jsx
import { DatePicker } from 'antd';
const { RangePicker } = DatePicker;
function onChange(value, dateString) {
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}
function onOk(value) {
console.log('onOk: ', value);
}
ReactDOM.render(
<div>
<DatePicker showTime placeholder="Select Time" onChange={onChange} onOk={onOk} />
<br />
<RangePicker
showTime={{ format: 'HH:mm' }}
format="YYYY-MM-DD HH:mm"
placeholder={['Start Time', 'End Time']}
onChange={onChange}
onOk={onOk}
/>
</div>,
mountNode,
);
```
|
components/date-picker/demo/time.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.0001729484647512436,
0.00016849106759764254,
0.000163082338985987,
0.0001678699627518654,
0.000003331417474328191
] |
{
"id": 5,
"code_window": [
" &.@{calendar-prefix-cls}-time &-middle {\n",
" padding: 0 10px 0 0;\n",
" transform: translateX(-50%);\n",
" }\n",
"\n",
" &.@{calendar-prefix-cls}-time &-right .@{calendar-prefix-cls}-date-input-wrap {\n",
" margin-left: 0;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .@{calendar-prefix-cls}-today {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @primary-color;\n",
" background: @primary-2;\n",
" border-color: @primary-color;\n",
" }\n",
" }\n",
"\n",
" .@{calendar-prefix-cls}-selected-start-date,\n",
" .@{calendar-prefix-cls}-selected-end-date {\n",
" .calendar-selected-cell;\n",
" }\n",
"\n"
],
"file_path": "components/date-picker/style/RangePicker.less",
"type": "add",
"edit_start_line_idx": 86
}
|
---
category: Ant Design
order: 1
title: Design Values
---
Ant Design provides a practical evaluation of better design for both designers of Ant Design and designers who are using it. At the same time, it builds a foundation for design principles and design patterns which could provide guideline and general solutions for specified design goal.
<div>
<img src="https://gw.alipayobjects.com/zos/rmsportal/kEwBspjVFChYqhqafCiW.png" />
</div>
Here is our design values:
## Nature
<div>
<img src="https://gw.alipayobjects.com/zos/rmsportal/cdaxgaTMQCGTqjdlwwgt.png" alt="Nature" />
</div>
As a part of nature, it will have deep influence on user behavior, and designers should draw inspiration from it and apply it to our daily design work. We have started exploring and will pursue nature as our future direction.
- The visual system plays the most important role in human perception and cognition. By refining the objective laws in nature and applying it to the interface design, a more layered product experience is created. In addition, hearing systems or tactile systems could be added in future to bring more dimensions and more real product experience. See visual language.
- In the real product design, a series of methods such as behavior analysis, artificial intelligence and sensors could be applied to assist users to make effective decisions and reduce extra operations of users, so as to save users' mental and physical resources and make human-computer interaction more natural.
## Determinacy
<div>
<img src="https://gw.alipayobjects.com/zos/rmsportal/ZxgRAMzXNrxHTcvMLchq.png" alt="Determine" />
</div>
The designers needs to make better design decisions and create a high-definition and low-entropy atmosphere for developer team. Meanwhile, different designers could produce the same design output which fit business needs based on the same understanding of business requirements and design system.
- **Keep restraint:** Don't make decision until we have to. Designers should focus on the valuable product features using minimal design elements to express. As Antoine de St.Exupery said: [“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”](https://www.goodreads.com/quotes/19905-perfection-is-achieved-not-when-there-is-nothing-more-to)
- **Object-oriented:** Explore design rules and abstract them as "objects" to enhance the flexibility and maintainability of user interface design while reducing designer's subjective judgement and uncertainty of real world system. For example: color value conversion, spacing typesetting.
- **Modular:** Encapsulate the complex or reusable parts could provide limited interfaces to interact with other modules, ultimately reducing overall system complexity, resulting in better reliability and maintainability. Designers can use existed resources or abstract their own reusable resources, save unnecessary and low additional design to keep their focus on where creativity most needed.
|
docs/spec/values.en-US.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017337444296572357,
0.00016809221415314823,
0.0001613538188394159,
0.00016882031923159957,
0.000004355670625955099
] |
{
"id": 5,
"code_window": [
" &.@{calendar-prefix-cls}-time &-middle {\n",
" padding: 0 10px 0 0;\n",
" transform: translateX(-50%);\n",
" }\n",
"\n",
" &.@{calendar-prefix-cls}-time &-right .@{calendar-prefix-cls}-date-input-wrap {\n",
" margin-left: 0;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" .@{calendar-prefix-cls}-today {\n",
" .@{calendar-prefix-cls}-date {\n",
" color: @primary-color;\n",
" background: @primary-2;\n",
" border-color: @primary-color;\n",
" }\n",
" }\n",
"\n",
" .@{calendar-prefix-cls}-selected-start-date,\n",
" .@{calendar-prefix-cls}-selected-end-date {\n",
" .calendar-selected-cell;\n",
" }\n",
"\n"
],
"file_path": "components/date-picker/style/RangePicker.less",
"type": "add",
"edit_start_line_idx": 86
}
|
---
category: Components
type: Feedback
title: Spin
---
A spinner for displaying loading state of a page or a section.
## When To Use
When part of the page is waiting for asynchronous data or during a rendering process, an appropriate loading animation can effectively alleviate users' inquietude.
## API
| Property | Description | Type | Default Value | Version |
| --- | --- | --- | --- | --- |
| delay | specifies a delay in milliseconds for loading state (prevent flush) | number (milliseconds) | - | |
| indicator | React node of the spinning indicator | ReactElement | - | |
| size | size of Spin, options: `small`, `default` and `large` | string | `default` | |
| spinning | whether Spin is spinning | boolean | true | |
| tip | customize description content when Spin has children | string | - | |
| wrapperClassName | className of wrapper when Spin has children | string | - | |
### Static Method
- `Spin.setDefaultIndicator(indicator: ReactElement)`
As `indicator`, you can define the global default spin element
|
components/spin/index.en-US.md
| 0 |
https://github.com/ant-design/ant-design/commit/da741ecf8482608dbabea9bf1c1c84b2da28f668
|
[
0.00017147503967862576,
0.00016960584616754204,
0.00016720604617148638,
0.0001701364672044292,
0.0000017827397869041306
] |
{
"id": 0,
"code_window": [
" // For efficiency, filter nodes to keep only those large enough to see.\n",
" const nodes = partition.nodes(root).filter(d => d.dx > 0.005); // 0.005 radians = 0.29 degrees\n",
"\n",
" if (metrics[0] !== metrics[1] && metrics[1] && !colorScheme) {\n",
" colorByCategory = false;\n",
" const ext = d3.extent(nodes, d => d.m2 / d.m1);\n",
" linearColorScale = getSequentialSchemeRegistry()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (metrics[0] !== metrics[1] && metrics[1]) {\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js",
"type": "replace",
"edit_start_line_idx": 491
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint-disable no-param-reassign, react/sort-prop-types */
import d3 from 'd3';
import PropTypes from 'prop-types';
import {
getNumberFormatter,
NumberFormats,
CategoricalColorNamespace,
getSequentialSchemeRegistry,
} from '@superset-ui/core';
import wrapSvgText from './utils/wrapSvgText';
const propTypes = {
// Each row is an array of [hierarchy-lvl1, hierarchy-lvl2, metric1, metric2]
// hierarchy-lvls are string. metrics are number
data: PropTypes.arrayOf(PropTypes.array),
width: PropTypes.number,
height: PropTypes.number,
colorScheme: PropTypes.string,
linearColorScheme: PropTypes.string,
numberFormat: PropTypes.string,
metrics: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.string,
PropTypes.object, // The metric object
]),
),
};
function metricLabel(metric) {
return typeof metric === 'string' || metric instanceof String
? metric
: metric.label;
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
const path = [];
let current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function buildHierarchy(rows) {
const root = {
name: 'root',
children: [],
};
// each record [groupby1val, groupby2val, (<string> or 0)n, m1, m2]
rows.forEach(row => {
const m1 = Number(row[row.length - 2]);
const m2 = Number(row[row.length - 1]);
const levels = row.slice(0, -2);
if (Number.isNaN(m1)) {
// e.g. if this is a header row
return;
}
let currentNode = root;
for (let level = 0; level < levels.length; level += 1) {
const children = currentNode.children || [];
const nodeName = levels[level].toString();
// If the next node has the name '0', it will
const isLeafNode = level >= levels.length - 1 || levels[level + 1] === 0;
let childNode;
if (!isLeafNode) {
childNode = children.find(
child => child.name === nodeName && child.level === level,
);
if (!childNode) {
childNode = {
name: nodeName,
children: [],
level,
};
children.push(childNode);
}
currentNode = childNode;
} else if (nodeName !== 0) {
// Reached the end of the sequence; create a leaf node.
childNode = {
name: nodeName,
m1,
m2,
};
children.push(childNode);
}
}
});
function recurse(node) {
if (node.children) {
let sums;
let m1 = 0;
let m2 = 0;
for (let i = 0; i < node.children.length; i += 1) {
sums = recurse(node.children[i]);
m1 += sums[0];
m2 += sums[1];
}
node.m1 = m1;
node.m2 = m2;
}
return [node.m1, node.m2];
}
recurse(root);
return root;
}
function getResponsiveContainerClass(width) {
if (width > 500) {
return 'l';
}
if (width > 200 && width <= 500) {
return 'm';
}
return 's';
}
function getYOffset(width) {
if (width > 500) {
return ['0', '20', '40', '60'];
}
if (width > 200 && width <= 500) {
return ['0', '15', '30', '45'];
}
return ['0', '10', '20', '30'];
}
// Modified from http://bl.ocks.org/kerryrodden/7090426
function Sunburst(element, props) {
const container = d3.select(element);
const {
data,
width,
height,
colorScheme,
linearColorScheme,
metrics,
numberFormat,
sliceId,
} = props;
const responsiveClass = getResponsiveContainerClass(width);
const isSmallWidth = responsiveClass === 's';
container.attr('class', `superset-legacy-chart-sunburst ${responsiveClass}`);
// vars with shared scope within this function
const margin = { top: 10, right: 5, bottom: 10, left: 5 };
const containerWidth = width;
const containerHeight = height;
const breadcrumbHeight = containerHeight * 0.085;
const visWidth = containerWidth - margin.left - margin.right;
const visHeight =
containerHeight - margin.top - margin.bottom - breadcrumbHeight;
const radius = Math.min(visWidth, visHeight) / 2;
let colorByCategory = true; // color by category if primary/secondary metrics match
let maxBreadcrumbs;
let breadcrumbDims; // set based on data
let totalSize; // total size of all segments; set after loading the data.
let breadcrumbs;
let vis;
let arcs;
let gMiddleText; // dom handles
const categoricalColorScale = CategoricalColorNamespace.getScale(colorScheme);
let linearColorScale;
// Helper + path gen functions
const partition = d3.layout
.partition()
.size([2 * Math.PI, radius * radius])
.value(d => d.m1);
const arc = d3.svg
.arc()
.startAngle(d => d.x)
.endAngle(d => d.x + d.dx)
.innerRadius(d => Math.sqrt(d.y))
.outerRadius(d => Math.sqrt(d.y + d.dy));
const formatNum = getNumberFormatter(
numberFormat || NumberFormats.SI_3_DIGIT,
);
const formatPerc = getNumberFormatter(NumberFormats.PERCENT_3_POINT);
container.select('svg').remove();
const svg = container
.append('svg:svg')
.attr('width', containerWidth)
.attr('height', containerHeight);
function createBreadcrumbs(firstRowData) {
// -2 bc row contains 2x metrics, +extra for %label and buffer
maxBreadcrumbs = firstRowData.length - 2 + 1;
breadcrumbDims = {
width: visWidth / maxBreadcrumbs,
height: breadcrumbHeight * 0.8, // more margin
spacing: 3,
tipTailWidth: 10,
};
breadcrumbs = svg
.append('svg:g')
.attr('class', 'breadcrumbs')
.attr('transform', `translate(${margin.left},${margin.top})`);
breadcrumbs.append('svg:text').attr('class', 'end-label');
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
const points = [];
if (isSmallWidth) {
points.push('0,0');
points.push(`${width},0`);
points.push(`${width},0`);
points.push(`${width},${breadcrumbDims.height}`);
points.push(`0,${breadcrumbDims.height}`);
if (i > 0) {
// Leftmost breadcrumb; don't include 6th vertex.
// points.push(`${breadcrumbDims.tipTailWidth},${breadcrumbDims.height / 2}`);
}
} else {
points.push('0,0');
points.push(`${breadcrumbDims.width},0`);
points.push(
`${breadcrumbDims.width + breadcrumbDims.tipTailWidth},${
breadcrumbDims.height / 2
}`,
);
points.push(`${breadcrumbDims.width},${breadcrumbDims.height}`);
points.push(`0,${breadcrumbDims.height}`);
if (i > 0) {
// Leftmost breadcrumb; don't include 6th vertex.
points.push(
`${breadcrumbDims.tipTailWidth},${breadcrumbDims.height / 2}`,
);
}
}
return points.join(' ');
}
function updateBreadcrumbs(sequenceArray, percentageString) {
const breadcrumbWidth = isSmallWidth ? width : breadcrumbDims.width;
const g = breadcrumbs
.selectAll('g')
.data(sequenceArray, d => d.name + d.depth);
// Add breadcrumb and label for entering nodes.
const entering = g.enter().append('svg:g');
entering
.append('svg:polygon')
.attr('points', breadcrumbPoints)
.style('fill', d =>
colorByCategory
? categoricalColorScale(d.name, sliceId)
: linearColorScale(d.m2 / d.m1),
);
entering
.append('svg:text')
.attr('x', (breadcrumbWidth + breadcrumbDims.tipTailWidth) / 2)
.attr('y', breadcrumbDims.height / 4)
.attr('dy', '0.35em')
.style('fill', d => {
// Make text white or black based on the lightness of the background
const col = d3.hsl(
colorByCategory
? categoricalColorScale(d.name, sliceId)
: linearColorScale(d.m2 / d.m1),
);
return col.l < 0.5 ? 'white' : 'black';
})
.attr('class', 'step-label')
.text(d => d.name.replace(/_/g, ' '))
.call(wrapSvgText, breadcrumbWidth, breadcrumbDims.height / 2);
// Set position for entering and updating nodes.
g.attr('transform', (d, i) => {
if (isSmallWidth) {
return `translate(0, ${
i * (breadcrumbDims.height + breadcrumbDims.spacing)
})`;
}
return `translate(${
i * (breadcrumbDims.width + breadcrumbDims.spacing)
}, 0)`;
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
breadcrumbs
.select('.end-label')
.attr('x', () => {
if (isSmallWidth) {
return (breadcrumbWidth + breadcrumbDims.tipTailWidth) / 2;
}
return (
(sequenceArray.length + 0.5) *
(breadcrumbDims.width + breadcrumbDims.spacing)
);
})
.attr('y', () => {
if (isSmallWidth) {
return (sequenceArray.length + 1) * breadcrumbDims.height;
}
return breadcrumbDims.height / 2;
})
.attr('dy', '0.35em')
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
breadcrumbs.style('visibility', null);
}
// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseenter(d) {
const sequenceArray = getAncestors(d);
const parentOfD = sequenceArray[sequenceArray.length - 2] || null;
const absolutePercentage = (d.m1 / totalSize).toPrecision(3);
const conditionalPercentage = parentOfD
? (d.m1 / parentOfD.m1).toPrecision(3)
: null;
const absolutePercString = formatPerc(absolutePercentage);
const conditionalPercString = parentOfD
? formatPerc(conditionalPercentage)
: '';
// 3 levels of text if inner-most level, 4 otherwise
const yOffsets = getYOffset(width);
let offsetIndex = 0;
// If metrics match, assume we are coloring by category
const metricsMatch = Math.abs(d.m1 - d.m2) < 0.00001;
gMiddleText.selectAll('*').remove();
offsetIndex += 1;
gMiddleText
.append('text')
.attr('class', 'path-abs-percent')
.attr('y', yOffsets[offsetIndex])
.text(`${absolutePercString} of total`);
if (conditionalPercString) {
offsetIndex += 1;
gMiddleText
.append('text')
.attr('class', 'path-cond-percent')
.attr('y', yOffsets[offsetIndex])
.text(`${conditionalPercString} of parent`);
}
offsetIndex += 1;
gMiddleText
.append('text')
.attr('class', 'path-metrics')
.attr('y', yOffsets[offsetIndex])
.text(
`${metricLabel(metrics[0])}: ${formatNum(d.m1)}${
metricsMatch ? '' : `, ${metricLabel(metrics[1])}: ${formatNum(d.m2)}`
}`,
);
offsetIndex += 1;
gMiddleText
.append('text')
.attr('class', 'path-ratio')
.attr('y', yOffsets[offsetIndex])
.text(
metricsMatch
? ''
: `${metricLabel(metrics[1])}/${metricLabel(
metrics[0],
)}: ${formatPerc(d.m2 / d.m1)}`,
);
// Reset and fade all the segments.
arcs
.selectAll('path')
.style('stroke-width', null)
.style('stroke', null)
.style('opacity', 0.3);
// Then highlight only those that are an ancestor of the current segment.
arcs
.selectAll('path')
.filter(node => sequenceArray.includes(node))
.style('opacity', 1)
.style('stroke', '#aaa');
updateBreadcrumbs(sequenceArray, absolutePercString);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave() {
// Hide the breadcrumb trail
breadcrumbs.style('visibility', 'hidden');
gMiddleText.selectAll('*').remove();
// Deactivate all segments during transition.
arcs.selectAll('path').on('mouseenter', null);
// Transition each segment to full opacity and then reactivate it.
arcs
.selectAll('path')
.transition()
.duration(200)
.style('opacity', 1)
.style('stroke', null)
.style('stroke-width', null)
.each('end', function end() {
d3.select(this).on('mouseenter', mouseenter);
});
}
// Main function to draw and set up the visualization, once we have the data.
function createVisualization(rows) {
const root = buildHierarchy(rows);
maxBreadcrumbs = rows[0].length - 2;
vis = svg
.append('svg:g')
.attr('class', 'sunburst-vis')
.attr(
'transform',
'translate(' +
`${margin.left + visWidth / 2},` +
`${
margin.top +
(isSmallWidth
? breadcrumbHeight * maxBreadcrumbs
: breadcrumbHeight) +
visHeight / 2
}` +
')',
)
.on('mouseleave', mouseleave);
arcs = vis.append('svg:g').attr('id', 'arcs');
gMiddleText = vis.append('svg:g').attr('class', 'center-label');
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
arcs.append('svg:circle').attr('r', radius).style('opacity', 0);
// For efficiency, filter nodes to keep only those large enough to see.
const nodes = partition.nodes(root).filter(d => d.dx > 0.005); // 0.005 radians = 0.29 degrees
if (metrics[0] !== metrics[1] && metrics[1] && !colorScheme) {
colorByCategory = false;
const ext = d3.extent(nodes, d => d.m2 / d.m1);
linearColorScale = getSequentialSchemeRegistry()
.get(linearColorScheme)
.createLinearScale(ext);
}
arcs
.selectAll('path')
.data(nodes)
.enter()
.append('svg:path')
.attr('display', d => (d.depth ? null : 'none'))
.attr('d', arc)
.attr('fill-rule', 'evenodd')
.style('fill', d =>
colorByCategory
? categoricalColorScale(d.name, sliceId)
: linearColorScale(d.m2 / d.m1),
)
.style('opacity', 1)
.on('mouseenter', mouseenter);
// Get total size of the tree = value of root node from partition.
totalSize = root.value;
}
createBreadcrumbs(data[0]);
createVisualization(data);
}
Sunburst.displayName = 'Sunburst';
Sunburst.propTypes = propTypes;
export default Sunburst;
|
superset-frontend/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js
| 1 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.9982419013977051,
0.12865419685840607,
0.00016356339619960636,
0.00017537646635901183,
0.3280181288719177
] |
{
"id": 0,
"code_window": [
" // For efficiency, filter nodes to keep only those large enough to see.\n",
" const nodes = partition.nodes(root).filter(d => d.dx > 0.005); // 0.005 radians = 0.29 degrees\n",
"\n",
" if (metrics[0] !== metrics[1] && metrics[1] && !colorScheme) {\n",
" colorByCategory = false;\n",
" const ext = d3.extent(nodes, d => d.m2 / d.m1);\n",
" linearColorScale = getSequentialSchemeRegistry()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (metrics[0] !== metrics[1] && metrics[1]) {\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js",
"type": "replace",
"edit_start_line_idx": 491
}
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
|
superset/migrations/shared/__init__.py
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.00017908499285113066,
0.00017868043505586684,
0.00017827589181251824,
0.00017868043505586684,
4.0455051930621266e-7
] |
{
"id": 0,
"code_window": [
" // For efficiency, filter nodes to keep only those large enough to see.\n",
" const nodes = partition.nodes(root).filter(d => d.dx > 0.005); // 0.005 radians = 0.29 degrees\n",
"\n",
" if (metrics[0] !== metrics[1] && metrics[1] && !colorScheme) {\n",
" colorByCategory = false;\n",
" const ext = d3.extent(nodes, d => d.m2 / d.m1);\n",
" linearColorScale = getSequentialSchemeRegistry()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (metrics[0] !== metrics[1] && metrics[1]) {\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js",
"type": "replace",
"edit_start_line_idx": 491
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import styled from '@emotion/styled';
import { List } from 'antd';
import Layout from '@theme/Layout';
const links = [
[
'https://join.slack.com/t/apache-superset/shared_invite/zt-16jvzmoi8-sI7jKWp~xc2zYRe~NqiY9Q',
'Slack',
'interact with other Superset users and community members',
],
[
'https://github.com/apache/superset',
'GitHub',
'create tickets to report issues, report bugs, and suggest new features',
],
[
'https://lists.apache.org/[email protected]',
'dev@ Mailing List',
'participate in conversations with committers and contributors',
],
[
'https://stackoverflow.com/questions/tagged/superset+apache-superset',
'Stack Overflow',
'our growing knowledge base',
],
[
'https://www.meetup.com/Global-Apache-Superset-Community-Meetup/',
'Superset Meetup Group',
'join our monthly virtual meetups and register for any upcoming events',
],
[
'https://github.com/apache/superset/blob/master/RESOURCES/INTHEWILD.md',
'Organizations',
'a list of some of the organizations using Superset in production',
],
[
'https://github.com/apache-superset/awesome-apache-superset',
'Contributors Guide',
'Interested in contributing? Learn how to contribute and best practices',
],
];
const StyledMain = styled('main')`
padding-bottom: 60px;
padding-left: 16px;
padding-right: 16px;
section {
width: 100%;
max-width: 800px;
margin: 0 auto;
padding: 60px 0 0 0;
font-size: 17px;
&:first-of-type{
padding: 40px;
background-image: linear-gradient(120deg, #d6f2f8, #52c6e3);
border-radius: 0 0 10px;
}
}
`;
const StyledGetInvolved = styled('div')`
margin-bottom: 25px;
`;
const Community = () => {
return (
<Layout
title="Community"
description="Community website for Apache Superset, a data visualization and data exploration platform"
>
<StyledMain>
<section>
<h1 className="title">Community</h1>
Get involved in our welcoming, fast growing community!
</section>
<section className="joinCommunity">
<StyledGetInvolved>
<h2>Get involved!</h2>
<List
size="small"
bordered
dataSource={links}
renderItem={([href, link, post]) => (
<List.Item>
<a href={href}>{link}</a>
{' '}
-
{' '}
{post}
</List.Item>
)}
/>
</StyledGetInvolved>
</section>
</StyledMain>
</Layout>
);
};
export default Community;
|
docs/src/pages/community.tsx
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0001781243336154148,
0.00017570816271472722,
0.00017262273468077183,
0.0001757106074364856,
0.0000014221259334590286
] |
{
"id": 0,
"code_window": [
" // For efficiency, filter nodes to keep only those large enough to see.\n",
" const nodes = partition.nodes(root).filter(d => d.dx > 0.005); // 0.005 radians = 0.29 degrees\n",
"\n",
" if (metrics[0] !== metrics[1] && metrics[1] && !colorScheme) {\n",
" colorByCategory = false;\n",
" const ext = d3.extent(nodes, d => d.m2 / d.m1);\n",
" linearColorScale = getSequentialSchemeRegistry()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (metrics[0] !== metrics[1] && metrics[1]) {\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/Sunburst.js",
"type": "replace",
"edit_start_line_idx": 491
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { SupersetClient } from '../../../connection';
import { BaseParams } from '../types';
import { QueryFormData } from '../../types/QueryFormData';
export interface Params extends BaseParams {
sliceId: number;
overrideFormData?: Partial<QueryFormData>;
}
export default function getFormData({
client = SupersetClient,
sliceId,
overrideFormData,
requestConfig,
}: Params) {
const promise = client
.get({
endpoint: `/api/v1/form_data/?slice_id=${sliceId}`,
...requestConfig,
})
.then(({ json }) => json as QueryFormData);
return overrideFormData
? promise.then(formData => ({ ...formData, ...overrideFormData }))
: promise;
}
|
superset-frontend/packages/superset-ui-core/src/query/api/legacy/getFormData.ts
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.000177431182237342,
0.00017549455515109003,
0.0001718162966426462,
0.00017569446936249733,
0.0000019795502339547966
] |
{
"id": 1,
"code_window": [
" * under the License.\n",
" */\n",
"import { t } from '@superset-ui/core';\n",
"import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';\n",
"\n",
"const config: ControlPanelConfig = {\n",
" controlPanelSections: [\n",
" sections.legacyRegularTime,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" ControlPanelConfig,\n",
" ControlPanelsContainerProps,\n",
" sections,\n",
"} from '@superset-ui/chart-controls';\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "replace",
"edit_start_line_idx": 19
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { t } from '@superset-ui/core';
import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';
const config: ControlPanelConfig = {
controlPanelSections: [
sections.legacyRegularTime,
{
label: t('Query'),
expanded: true,
controlSetRows: [
['groupby'],
['metric'],
['secondary_metric'],
['adhoc_filters'],
['row_limit'],
[
{
name: 'sort_by_metric',
config: {
type: 'CheckboxControl',
label: t('Sort by metric'),
description: t(
'Whether to sort results by the selected metric in descending order.',
),
},
},
],
],
},
{
label: t('Chart Options'),
expanded: true,
controlSetRows: [['color_scheme'], ['linear_color_scheme']],
},
],
controlOverrides: {
metric: {
label: t('Primary Metric'),
description: t(
'The primary metric is used to define the arc segment sizes',
),
},
secondary_metric: {
label: t('Secondary Metric'),
default: null,
description: t(
'[optional] this secondary metric is used to ' +
'define the color as a ratio against the primary metric. ' +
'When omitted, the color is categorical and based on labels',
),
},
color_scheme: {
description: t(
'When only a primary metric is provided, a categorical color scale is used.',
),
},
linear_color_scheme: {
description: t(
'When a secondary metric is provided, a linear color scale is used.',
),
},
groupby: {
label: t('Hierarchy'),
description: t('This defines the level of the hierarchy'),
},
},
};
export default config;
|
superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts
| 1 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.9971460700035095,
0.11124411225318909,
0.00016592405154369771,
0.0001743952598189935,
0.31321436166763306
] |
{
"id": 1,
"code_window": [
" * under the License.\n",
" */\n",
"import { t } from '@superset-ui/core';\n",
"import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';\n",
"\n",
"const config: ControlPanelConfig = {\n",
" controlPanelSections: [\n",
" sections.legacyRegularTime,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" ControlPanelConfig,\n",
" ControlPanelsContainerProps,\n",
" sections,\n",
"} from '@superset-ui/chart-controls';\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "replace",
"edit_start_line_idx": 19
}
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""empty message
Revision ID: ea033256294a
Revises: ('732f1c06bcbf', 'b318dfe5fb6c')
Create Date: 2017-03-16 14:55:59.431283
"""
# revision identifiers, used by Alembic.
revision = "ea033256294a"
down_revision = ("732f1c06bcbf", "b318dfe5fb6c")
import sqlalchemy as sa
from alembic import op
def upgrade():
pass
def downgrade():
pass
|
superset/migrations/versions/ea033256294a_.py
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0001777863217284903,
0.0001755249686539173,
0.00017312368436250836,
0.00017559491971042007,
0.0000016639085060887737
] |
{
"id": 1,
"code_window": [
" * under the License.\n",
" */\n",
"import { t } from '@superset-ui/core';\n",
"import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';\n",
"\n",
"const config: ControlPanelConfig = {\n",
" controlPanelSections: [\n",
" sections.legacyRegularTime,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" ControlPanelConfig,\n",
" ControlPanelsContainerProps,\n",
" sections,\n",
"} from '@superset-ui/chart-controls';\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "replace",
"edit_start_line_idx": 19
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { REPORT_LIST } from './alert_report.helper';
describe('report list view', () => {
beforeEach(() => {
cy.login();
});
afterEach(() => {
cy.eyesClose();
});
it('should load report lists', () => {
cy.visit(REPORT_LIST);
cy.get('[data-test="listview-table"]').should('be.visible');
// check report list view header
cy.get('[data-test="sort-header"]').eq(1).contains('Last run');
cy.get('[data-test="sort-header"]').eq(2).contains('Name');
cy.get('[data-test="sort-header"]').eq(3).contains('Schedule');
cy.get('[data-test="sort-header"]').eq(4).contains('Notification method');
cy.get('[data-test="sort-header"]').eq(5).contains('Created by');
cy.get('[data-test="sort-header"]').eq(6).contains('Owners');
cy.get('[data-test="sort-header"]').eq(7).contains('Active');
// TODO: this assert is flaky, we need to find a way to make it work consistenly
// cy.get('[data-test="sort-header"]').eq(8).contains('Actions');
});
});
|
superset-frontend/cypress-base/cypress/integration/alerts_and_reports/reports.test.ts
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0001787431101547554,
0.000176688889041543,
0.0001743952598189935,
0.00017714398563839495,
0.0000017723588143780944
] |
{
"id": 1,
"code_window": [
" * under the License.\n",
" */\n",
"import { t } from '@superset-ui/core';\n",
"import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';\n",
"\n",
"const config: ControlPanelConfig = {\n",
" controlPanelSections: [\n",
" sections.legacyRegularTime,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import {\n",
" ControlPanelConfig,\n",
" ControlPanelsContainerProps,\n",
" sections,\n",
"} from '@superset-ui/chart-controls';\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "replace",
"edit_start_line_idx": 19
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { SyntheticEvent, MutableRefObject, ComponentType } from 'react';
import { merge } from 'lodash';
import BasicSelect, {
OptionTypeBase,
MultiValueProps,
FormatOptionLabelMeta,
ValueType,
SelectComponentsConfig,
components as defaultComponents,
createFilter,
Props as SelectProps,
} from 'react-select';
import Async from 'react-select/async';
import Creatable from 'react-select/creatable';
import AsyncCreatable from 'react-select/async-creatable';
import type { SelectComponents } from 'react-select/src/components';
import {
SortableContainer,
SortableElement,
SortableContainerProps,
} from 'react-sortable-hoc';
import arrayMove from 'array-move';
import { useTheme } from '@superset-ui/core';
import {
WindowedSelectComponentType,
WindowedSelectProps,
WindowedSelect,
WindowedCreatableSelect,
WindowedAsyncCreatableSelect,
} from './WindowedSelect';
import {
DEFAULT_CLASS_NAME,
DEFAULT_CLASS_NAME_PREFIX,
DEFAULT_STYLES,
DEFAULT_COMPONENTS,
VALUE_LABELED_STYLES,
PartialThemeConfig,
PartialStylesConfig,
SelectComponentsType,
InputProps,
defaultTheme,
} from './styles';
import { findValue } from './utils';
type AnyReactSelect<OptionType extends OptionTypeBase> =
| BasicSelect<OptionType>
| Async<OptionType>
| Creatable<OptionType>
| AsyncCreatable<OptionType>;
export type SupersetStyledSelectProps<
OptionType extends OptionTypeBase,
T extends WindowedSelectProps<OptionType> = WindowedSelectProps<OptionType>,
> = T & {
// additional props for easier usage or backward compatibility
labelKey?: string;
valueKey?: string;
assistiveText?: string;
multi?: boolean;
clearable?: boolean;
sortable?: boolean;
ignoreAccents?: boolean;
creatable?: boolean;
selectRef?:
| React.RefCallback<AnyReactSelect<OptionType>>
| MutableRefObject<AnyReactSelect<OptionType>>;
getInputValue?: (selectBalue: ValueType<OptionType>) => string | undefined;
optionRenderer?: (option: OptionType) => React.ReactNode;
valueRenderer?: (option: OptionType) => React.ReactNode;
valueRenderedAsLabel?: boolean;
// callback for paste event
onPaste?: (e: SyntheticEvent) => void;
forceOverflow?: boolean;
// for simplier theme overrides
themeConfig?: PartialThemeConfig;
stylesConfig?: PartialStylesConfig;
};
function styled<
OptionType extends OptionTypeBase,
SelectComponentType extends
| WindowedSelectComponentType<OptionType>
| ComponentType<
SelectProps<OptionType>
> = WindowedSelectComponentType<OptionType>,
>(SelectComponent: SelectComponentType) {
type SelectProps = SupersetStyledSelectProps<OptionType>;
type Components = SelectComponents<OptionType>;
const SortableSelectComponent = SortableContainer(SelectComponent, {
withRef: true,
});
// default components for the given OptionType
const supersetDefaultComponents: SelectComponentsConfig<OptionType> =
DEFAULT_COMPONENTS;
const getSortableMultiValue = (MultiValue: Components['MultiValue']) =>
SortableElement((props: MultiValueProps<OptionType>) => {
const onMouseDown = (e: SyntheticEvent) => {
e.preventDefault();
e.stopPropagation();
};
const innerProps = { onMouseDown };
return <MultiValue {...props} innerProps={innerProps} />;
});
/**
* Superset styled `Select` component. Apply Superset themed stylesheets and
* consolidate props API for backward compatibility with react-select v1.
*/
function StyledSelect(selectProps: SelectProps) {
let stateManager: AnyReactSelect<OptionType>; // reference to react-select StateManager
const {
// additional props for Superset Select
selectRef,
labelKey = 'label',
valueKey = 'value',
themeConfig,
stylesConfig = {},
optionRenderer,
valueRenderer,
// whether value is rendered as `option-label` in input,
// useful for AdhocMetric and AdhocFilter
valueRenderedAsLabel: valueRenderedAsLabel_,
onPaste,
multi = false, // same as `isMulti`, used for backward compatibility
clearable, // same as `isClearable`
sortable = true, // whether to enable drag & drop sorting
forceOverflow, // whether the dropdown should be forcefully overflowing
// react-select props
className = DEFAULT_CLASS_NAME,
classNamePrefix = DEFAULT_CLASS_NAME_PREFIX,
options,
value: value_,
components: components_,
isMulti: isMulti_,
isClearable: isClearable_,
minMenuHeight = 100, // apply different defaults
maxMenuHeight = 220,
filterOption,
ignoreAccents = false, // default is `true`, but it is slow
getOptionValue = option =>
typeof option === 'string' ? option : option[valueKey],
getOptionLabel = option =>
typeof option === 'string'
? option
: option[labelKey] || option[valueKey],
formatOptionLabel = (
option: OptionType,
{ context }: FormatOptionLabelMeta<OptionType>,
) => {
if (context === 'value') {
return valueRenderer ? valueRenderer(option) : getOptionLabel(option);
}
return optionRenderer ? optionRenderer(option) : getOptionLabel(option);
},
...restProps
} = selectProps;
// `value` may be rendered values (strings), we want option objects
const value: OptionType[] = findValue(value_, options || [], valueKey);
// Add backward compability to v1 API
const isMulti = isMulti_ === undefined ? multi : isMulti_;
const isClearable = isClearable_ === undefined ? clearable : isClearable_;
// Sort is only applied when there are multiple selected values
const shouldAllowSort =
isMulti && sortable && Array.isArray(value) && value.length > 1;
const MaybeSortableSelect = shouldAllowSort
? SortableSelectComponent
: SelectComponent;
const components = { ...supersetDefaultComponents, ...components_ };
// Make multi-select sortable as per https://react-select.netlify.app/advanced
if (shouldAllowSort) {
components.MultiValue = getSortableMultiValue(
components.MultiValue || defaultComponents.MultiValue,
);
const sortableContainerProps: Partial<SortableContainerProps> = {
getHelperDimensions: ({ node }) => node.getBoundingClientRect(),
axis: 'xy',
onSortEnd: ({ oldIndex, newIndex }) => {
const newValue = arrayMove(value, oldIndex, newIndex);
if (restProps.onChange) {
restProps.onChange(newValue, { action: 'set-value' });
}
},
distance: 4,
};
Object.assign(restProps, sortableContainerProps);
}
// When values are rendered as labels, adjust valueContainer padding
const valueRenderedAsLabel =
valueRenderedAsLabel_ === undefined ? isMulti : valueRenderedAsLabel_;
if (valueRenderedAsLabel && !stylesConfig.valueContainer) {
Object.assign(stylesConfig, VALUE_LABELED_STYLES);
}
// Handle onPaste event
if (onPaste) {
const Input =
(components.Input as SelectComponentsType['Input']) ||
(defaultComponents.Input as SelectComponentsType['Input']);
components.Input = (props: InputProps) => (
<Input {...props} onPaste={onPaste} />
);
}
// for CreaTable
if (SelectComponent === WindowedCreatableSelect) {
restProps.getNewOptionData = (inputValue: string, label: string) => ({
label: label || inputValue,
[valueKey]: inputValue,
isNew: true,
});
}
// handle forcing dropdown overflow
// use only when setting overflow:visible isn't possible on the container element
if (forceOverflow) {
Object.assign(restProps, {
closeMenuOnScroll: (e: Event) => {
// ensure menu is open
const menuIsOpen = (stateManager as BasicSelect<OptionType>)?.state
?.menuIsOpen;
const target = e.target as HTMLElement;
return (
menuIsOpen &&
target &&
!target.classList?.contains('Select__menu-list')
);
},
menuPosition: 'fixed',
});
}
// Make sure always return StateManager for the refs.
// To get the real `Select` component, keep tap into `obj.select`:
// - for normal <Select /> component: StateManager -> Select,
// - for <Creatable />: StateManager -> Creatable -> Select
const setRef = (instance: any) => {
stateManager =
shouldAllowSort && instance && 'refs' in instance
? instance.refs.wrappedInstance // obtain StateManger from SortableContainer
: instance;
if (typeof selectRef === 'function') {
selectRef(stateManager);
} else if (selectRef && 'current' in selectRef) {
selectRef.current = stateManager;
}
};
const theme = useTheme();
return (
<MaybeSortableSelect
ref={setRef}
className={className}
classNamePrefix={classNamePrefix}
isMulti={isMulti}
isClearable={isClearable}
options={options}
value={value}
minMenuHeight={minMenuHeight}
maxMenuHeight={maxMenuHeight}
filterOption={
// filterOption may be NULL
filterOption !== undefined
? filterOption
: createFilter({ ignoreAccents })
}
styles={{ ...DEFAULT_STYLES, ...stylesConfig } as SelectProps['styles']}
// merge default theme from `react-select`, default theme for Superset,
// and the theme from props.
theme={reactSelectTheme =>
merge(reactSelectTheme, defaultTheme(theme), themeConfig)
}
formatOptionLabel={formatOptionLabel}
getOptionLabel={getOptionLabel}
getOptionValue={getOptionValue}
components={components}
{...restProps}
/>
);
}
// React.memo makes sure the component does no rerender given the same props
return React.memo(StyledSelect);
}
export const Select = styled(WindowedSelect);
export const CreatableSelect = styled(WindowedCreatableSelect);
export const AsyncCreatableSelect = styled(WindowedAsyncCreatableSelect);
export default Select;
|
superset-frontend/src/components/Select/DeprecatedSelect.tsx
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0004927252302877605,
0.0001878741750260815,
0.00016331140068359673,
0.0001743952598189935,
0.000058418503613211215
] |
{
"id": 2,
"code_window": [
" color_scheme: {\n",
" description: t(\n",
" 'When only a primary metric is provided, a categorical color scale is used.',\n",
" ),\n",
" },\n",
" linear_color_scheme: {\n",
" description: t(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" !controls?.secondary_metric?.value ||\n",
" controls?.secondary_metric?.value === controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 73
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { t } from '@superset-ui/core';
import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';
const config: ControlPanelConfig = {
controlPanelSections: [
sections.legacyRegularTime,
{
label: t('Query'),
expanded: true,
controlSetRows: [
['groupby'],
['metric'],
['secondary_metric'],
['adhoc_filters'],
['row_limit'],
[
{
name: 'sort_by_metric',
config: {
type: 'CheckboxControl',
label: t('Sort by metric'),
description: t(
'Whether to sort results by the selected metric in descending order.',
),
},
},
],
],
},
{
label: t('Chart Options'),
expanded: true,
controlSetRows: [['color_scheme'], ['linear_color_scheme']],
},
],
controlOverrides: {
metric: {
label: t('Primary Metric'),
description: t(
'The primary metric is used to define the arc segment sizes',
),
},
secondary_metric: {
label: t('Secondary Metric'),
default: null,
description: t(
'[optional] this secondary metric is used to ' +
'define the color as a ratio against the primary metric. ' +
'When omitted, the color is categorical and based on labels',
),
},
color_scheme: {
description: t(
'When only a primary metric is provided, a categorical color scale is used.',
),
},
linear_color_scheme: {
description: t(
'When a secondary metric is provided, a linear color scale is used.',
),
},
groupby: {
label: t('Hierarchy'),
description: t('This defines the level of the hierarchy'),
},
},
};
export default config;
|
superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts
| 1 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.8711671829223633,
0.10946384072303772,
0.0001563713449286297,
0.00017991835193242878,
0.27135542035102844
] |
{
"id": 2,
"code_window": [
" color_scheme: {\n",
" description: t(\n",
" 'When only a primary metric is provided, a categorical color scale is used.',\n",
" ),\n",
" },\n",
" linear_color_scheme: {\n",
" description: t(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" !controls?.secondary_metric?.value ||\n",
" controls?.secondary_metric?.value === controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 73
}
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from flask_babel import lazy_gettext as _
from superset.commands.exceptions import CommandException, CreateFailedError
class ExplorePermalinkInvalidStateError(CreateFailedError):
message = _("Invalid state.")
class ExplorePermalinkCreateFailedError(CreateFailedError):
message = _("An error occurred while creating the value.")
class ExplorePermalinkGetFailedError(CommandException):
message = _("An error occurred while accessing the value.")
|
superset/explore/permalink/exceptions.py
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0012580461334437132,
0.00044532513129524887,
0.00017153113731183112,
0.00017586165631655604,
0.00046922831097617745
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.