diff --git a/.editorconfig b/.editorconfig index 12375bf30..f5e8e9f86 100644 --- a/.editorconfig +++ b/.editorconfig @@ -8,7 +8,7 @@ end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -max_line_length = 100 +max_line_length = 80 [*.md] trim_trailing_whitespace = false \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js index 96d0d5d09..46734e64d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -15,7 +15,10 @@ module.exports = { "import/no-unresolved": [2, { ignore: ["victory*"] }], "max-statements": 0, complexity: ["error", { max: 16 }], - "no-magic-numbers": ["error", { ignore: [-1, 0, 0.5, 1, 2, 90, 180, 270, 360] }] + "no-magic-numbers": [ + "error", + { ignore: [-1, 0, 0.5, 1, 2, 90, 180, 270, 360] } + ] }, overrides: [ { diff --git a/.prettierrc.json b/.prettierrc.json index 71ff61956..0f11fc25a 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,4 +1,5 @@ { "arrowParens": "always", - "trailingComma": "none" + "trailingComma": "none", + "printWidth": 80 } diff --git a/config/karma/karma.conf.dev.js b/config/karma/karma.conf.dev.js index a58f78a64..3b8c89f7e 100644 --- a/config/karma/karma.conf.dev.js +++ b/config/karma/karma.conf.dev.js @@ -2,7 +2,10 @@ var path = require("path"); var MAIN_PATH = path.join(process.cwd(), "test/client/main.js"); -var POLYFILL_PATH = path.join(path.dirname(require.resolve("core-js/package.json")), "es6/**/*.js"); +var POLYFILL_PATH = path.join( + path.dirname(require.resolve("core-js/package.json")), + "es6/**/*.js" +); var PREPROCESSORS = {}; PREPROCESSORS[MAIN_PATH] = ["webpack"]; PREPROCESSORS[POLYFILL_PATH] = ["webpack"]; diff --git a/config/karma/karma.conf.js b/config/karma/karma.conf.js index 931396e8e..484a2b0ba 100644 --- a/config/karma/karma.conf.js +++ b/config/karma/karma.conf.js @@ -10,7 +10,10 @@ var path = require("path"); var webpackCfg = require("../webpack/webpack.config.test"); var MAIN_PATH = path.join(process.cwd(), "test/client/main.js"); -var POLYFILL_PATH = path.join(path.dirname(require.resolve("core-js/package.json")), "es6/**/*.js"); +var POLYFILL_PATH = path.join( + path.dirname(require.resolve("core-js/package.json")), + "es6/**/*.js" +); var PREPROCESSORS = {}; PREPROCESSORS[MAIN_PATH] = ["webpack"]; PREPROCESSORS[POLYFILL_PATH] = ["webpack"]; diff --git a/demo/js/app.js b/demo/js/app.js index 4eeea9a02..fda259af0 100644 --- a/demo/js/app.js +++ b/demo/js/app.js @@ -56,17 +56,38 @@ const MAP = { "/group": { component: GroupDemo, name: "GroupDemo" }, "/voronoi": { component: VoronoiDemo, name: "VoronoiDemo" }, "/tooltip": { component: TooltipDemo, name: "TooltipDemo" }, - "/zoom-container": { component: ZoomContainerDemo, name: "ZoomContainerDemo" }, - "/voronoi-container": { component: VoronoiContainerDemo, name: "VoronoiContainerDemo" }, - "/cursor-container": { component: CursorContainerDemo, name: "CursorContainerDemo" }, - "/brush-container": { component: BrushContainerDemo, name: "BrushContainerDemo" }, + "/zoom-container": { + component: ZoomContainerDemo, + name: "ZoomContainerDemo" + }, + "/voronoi-container": { + component: VoronoiContainerDemo, + name: "VoronoiContainerDemo" + }, + "/cursor-container": { + component: CursorContainerDemo, + name: "CursorContainerDemo" + }, + "/brush-container": { + component: BrushContainerDemo, + name: "BrushContainerDemo" + }, "/animation": { component: AnimationDemo, name: "AnimationDemo" }, "/selection-container": { component: SelectionDemo, name: "SelectionDemo" }, - "/create-container": { component: CreateContainerDemo, name: "CreateContainerDemo" }, + "/create-container": { + component: CreateContainerDemo, + name: "CreateContainerDemo" + }, "/polar": { component: PolarDemo, name: "PolarDemo" }, "/immutable": { component: ImmutableDemo, name: "ImmutableDemo" }, - "/external-events": { component: ExternalEventsDemo, name: "ExternalEventsDemo" }, - "/victory-brush-line": { component: VictoryBrushLineDemo, name: "BrushLineDemo" }, + "/external-events": { + component: ExternalEventsDemo, + name: "ExternalEventsDemo" + }, + "/victory-brush-line": { + component: VictoryBrushLineDemo, + name: "BrushLineDemo" + }, "/performance": { component: PerformanceDemo, name: "PerformanceDemo" }, "/debug": { component: DebugDemo, name: "DebugDemo" }, "/label": { component: VictoryLabelDemo, name: "LabelDemo" }, diff --git a/demo/js/components/accessibility-demo.js b/demo/js/components/accessibility-demo.js index 64d5fc034..21bdd6bb2 100644 --- a/demo/js/components/accessibility-demo.js +++ b/demo/js/components/accessibility-demo.js @@ -117,19 +117,25 @@ export default class App extends React.Component { } q3Component={ `${datum.x} q3 value is ${datum._q3}`} + ariaLabel={({ datum }) => + `${datum.x} q3 value is ${datum._q3}` + } tabIndex={({ index }) => index + 6.1} /> } medianComponent={ `${datum.x} median value is ${datum._median}`} + ariaLabel={({ datum }) => + `${datum.x} median value is ${datum._median}` + } tabIndex={({ index }) => index + 5.1} /> } q1Component={ `${datum.x} q1 value is ${datum._q1}`} + ariaLabel={({ datum }) => + `${datum.x} q1 value is ${datum._q1}` + } tabIndex={({ index }) => index + 6.2} /> } @@ -152,7 +158,9 @@ export default class App extends React.Component { data={accessibilityAreaData.a} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20} /> } @@ -161,7 +169,9 @@ export default class App extends React.Component { data={accessibilityAreaData.b} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.1} /> } @@ -170,7 +180,9 @@ export default class App extends React.Component { data={accessibilityAreaData.c} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.2} /> } @@ -179,7 +191,9 @@ export default class App extends React.Component { data={accessibilityAreaData.d} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.3} /> } @@ -206,9 +220,9 @@ export default class App extends React.Component { ariaLabel={({ data }) => data.map( (dataPoint, i) => - `data point ${i + 1} x value is ${dataPoint.x} and y value is ${ - dataPoint.y - }` + `data point ${i + 1} x value is ${ + dataPoint.x + } and y value is ${dataPoint.y}` ) } /> @@ -246,7 +260,9 @@ export default class App extends React.Component { data={accessibilityScatterData} dataComponent={ `scatter point x: ${datum.x}, y:${datum.y}`} + ariaLabel={({ datum }) => + `scatter point x: ${datum.x}, y:${datum.y}` + } tabIndex={({ index }) => index + 28} /> } @@ -263,7 +279,9 @@ export default class App extends React.Component { data={accessibilityVoronoiData} dataComponent={ `voronoi chart, x ${datum.x}, y ${datum.y}`} + ariaLabel={({ datum }) => + `voronoi chart, x ${datum.x}, y ${datum.y}` + } tabIndex={({ index }) => index + 35} /> } diff --git a/demo/js/components/animation-demo.js b/demo/js/components/animation-demo.js index dc795d8b9..4daa7ab4f 100644 --- a/demo/js/components/animation-demo.js +++ b/demo/js/components/animation-demo.js @@ -122,16 +122,25 @@ export default class App extends React.Component { - + {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} diff --git a/demo/js/components/create-container-demo.js b/demo/js/components/create-container-demo.js index c02038ba2..d661b1924 100644 --- a/demo/js/components/create-container-demo.js +++ b/demo/js/components/create-container-demo.js @@ -41,7 +41,12 @@ const Charts = ({ behaviors }) => { `y: ${datum.y}`} - labelComponent={} + labelComponent={ + + } selectedDomain={{ x: [1.5, 2] }} /> } @@ -139,7 +144,9 @@ const Charts = ({ behaviors }) => { {/* C */} } + containerComponent={ + + } > { {/* D */} } + containerComponent={ + + } > - }> + } + > "HELLO"} />} + containerComponent={ + "HELLO"} /> + } > (active ? "red" : "black") } }} + style={{ + data: { fill: ({ active }) => (active ? "red" : "black") } + }} data={[ { x: 0, y: 3.5, y0: 2.5 }, { x: 0, y: 11, y0: 5 }, @@ -98,7 +107,9 @@ class App extends React.Component { ]} /> (active ? "black" : "red") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "red") } + }} data={[ { x: 0, y: 3.5 }, { x: 0, y: 11 }, diff --git a/demo/js/components/draggable-demo.js b/demo/js/components/draggable-demo.js index ed31f84a8..3399f79cf 100644 --- a/demo/js/components/draggable-demo.js +++ b/demo/js/components/draggable-demo.js @@ -6,7 +6,11 @@ import { VictoryAxis } from "Packages/victory-axis/src/index"; import { VictoryBar } from "Packages/victory-bar/src/index"; import { VictoryBrushLine } from "Packages/victory-brush-line/src/index"; import { VictoryScatter } from "Packages/victory-scatter/src/index"; -import { VictoryClipContainer, Point, Selection } from "Packages/victory-core/src/index"; +import { + VictoryClipContainer, + Point, + Selection +} from "Packages/victory-core/src/index"; import { VictoryZoomContainer } from "Packages/victory-zoom-container/src/index"; import { VictoryBrushContainer } from "Packages/victory-brush-container/src/index"; @@ -61,14 +65,22 @@ class DraggablePoint extends React.Component { onMouseUp: (evt, targetProps) => { return [ { - mutation: () => Object.assign({}, targetProps, { dragging: false, active: false }) + mutation: () => + Object.assign({}, targetProps, { + dragging: false, + active: false + }) } ]; }, onMouseLeave: (evt, targetProps) => { return [ { - mutation: () => Object.assign({}, targetProps, { dragging: false, active: false }) + mutation: () => + Object.assign({}, targetProps, { + dragging: false, + active: false + }) } ]; } @@ -100,7 +112,9 @@ class App extends React.Component { } onPointChange(point) { - const newPoints = this.state.points.map((p) => (p.name === point.name ? point : p)); + const newPoints = this.state.points.map((p) => + p.name === point.name ? point : p + ); this.setState({ points: newPoints }); } @@ -170,7 +184,9 @@ class App extends React.Component { ))} } + dataComponent={ + + } style={{ data: { fill: "skyBlue", diff --git a/demo/js/components/events-demo.js b/demo/js/components/events-demo.js index fb5f3e9e4..e8f8dce26 100644 --- a/demo/js/components/events-demo.js +++ b/demo/js/components/events-demo.js @@ -18,7 +18,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -101,7 +103,9 @@ class App extends React.Component { childName: "line", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -203,7 +207,9 @@ class App extends React.Component { target: "data", mutation: (props) => { const fill = props.style && props.style.fill; - return fill === "gold" ? null : { style: { fill: "gold" } }; + return fill === "gold" + ? null + : { style: { fill: "gold" } }; } } ]; diff --git a/demo/js/components/external-events-demo.js b/demo/js/components/external-events-demo.js index 81164f899..4f14a0634 100644 --- a/demo/js/components/external-events-demo.js +++ b/demo/js/components/external-events-demo.js @@ -85,17 +85,23 @@ class App extends React.Component { alignItems: "center", justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "35%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "35%" } + }; return (

Debug

  • - +
  • - +
@@ -152,7 +154,10 @@ class App extends React.Component { Math.sin(2 * Math.PI * data.x)}> - } labels={({ datum }) => datum.y} /> + } + labels={({ datum }) => datum.y} + />
diff --git a/demo/js/components/horizontal-demo.js b/demo/js/components/horizontal-demo.js index 691a3ef92..139d665a2 100644 --- a/demo/js/components/horizontal-demo.js +++ b/demo/js/components/horizontal-demo.js @@ -42,7 +42,9 @@ class App extends React.Component { alignItems: "center", justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -176,7 +178,11 @@ class App extends React.Component { - + "yo"} data={[ { x: new Date(2014, 6, 1), open: 9, close: 30, high: 56, low: 7 }, - { x: new Date(2015, 6, 2), open: 80, close: 40, high: 120, low: 10 }, - { x: new Date(2016, 6, 3), open: 50, close: 80, high: 90, low: 20 }, - { x: new Date(2017, 6, 4), open: 70, close: 22, high: 70, low: 5 }, - { x: new Date(2018, 6, 5), open: 20, close: 35, high: 50, low: 10 }, - { x: new Date(2019, 6, 6), open: 35, close: 30, high: 40, low: 3 }, - { x: new Date(2020, 6, 7), open: 30, close: 90, high: 95, low: 30 }, - { x: new Date(2021, 6, 8), open: 80, close: 81, high: 83, low: 75 } + { + x: new Date(2015, 6, 2), + open: 80, + close: 40, + high: 120, + low: 10 + }, + { + x: new Date(2016, 6, 3), + open: 50, + close: 80, + high: 90, + low: 20 + }, + { + x: new Date(2017, 6, 4), + open: 70, + close: 22, + high: 70, + low: 5 + }, + { + x: new Date(2018, 6, 5), + open: 20, + close: 35, + high: 50, + low: 10 + }, + { + x: new Date(2019, 6, 6), + open: 35, + close: 30, + high: 40, + low: 3 + }, + { + x: new Date(2020, 6, 7), + open: 30, + close: 90, + high: 95, + low: 30 + }, + { + x: new Date(2021, 6, 8), + open: 80, + close: 81, + high: 83, + low: 75 + } ]} /> @@ -410,7 +458,11 @@ class App extends React.Component { ]} /> - + } + containerComponent={ + + } > { @@ -203,7 +218,9 @@ class App extends React.Component { childName: "area-2", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { @@ -274,8 +291,16 @@ class App extends React.Component { - - + + {this.state.multiTransitionData.map((data, index) => { return ( @@ -326,14 +351,62 @@ class App extends React.Component { { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -397,7 +472,9 @@ class App extends React.Component { childName: "line", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -501,7 +578,12 @@ class App extends React.Component { { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { @@ -665,7 +749,10 @@ class App extends React.Component { { x: 3, y: -2, l: "three" } ])} style={{ - data: { stroke: "tomato", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "tomato", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "tomato" } }} /> @@ -676,7 +763,10 @@ class App extends React.Component { { x: 3, y: 3, l: "blue" } ])} style={{ - data: { stroke: "blue", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "blue", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "blue" } }} /> @@ -687,7 +777,10 @@ class App extends React.Component { { x: 3, y: -2, l: "bird" } ])} style={{ - data: { stroke: "black", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "black", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "black" } }} /> @@ -700,7 +793,9 @@ class App extends React.Component { padding={{ top: 100, bottom: 40, left: 50, right: 50 }} containerComponent={ `${round(datum.x, 2)} , ${round(datum.y, 2)}`} + cursorLabel={(datum) => + `${round(datum.x, 2)} , ${round(datum.y, 2)}` + } /> } > @@ -719,7 +814,9 @@ class App extends React.Component { ]} /> ({ x, y: x + 10 * Math.random() })))} + data={fromJS( + range(1500).map((x) => ({ x, y: x + 10 * Math.random() })) + )} /> @@ -733,7 +830,9 @@ class App extends React.Component { responsive={false} zoomDomain={this.state.zoomDomain} zoomDimension="x" - onZoomDomainChange={(domain) => this.setState({ zoomDomain: domain })} + onZoomDomainChange={(domain) => + this.setState({ zoomDomain: domain }) + } /> } > @@ -764,7 +863,9 @@ class App extends React.Component { responsive={false} brushDomain={this.state.zoomDomain} brushDimension="x" - onBrushDomainChange={(domain) => this.setState({ zoomDomain: domain })} + onBrushDomainChange={(domain) => + this.setState({ zoomDomain: domain }) + } /> } > @@ -797,15 +898,28 @@ class App extends React.Component {
- + {this.state.multiTransitionAreaData.map((data, index) => { - return ; + return ( + + ); })} - }> + } + > (active ? "tomato" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "tomato" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -829,7 +945,9 @@ class App extends React.Component { > (active ? "blue" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "blue" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -843,7 +961,9 @@ class App extends React.Component { > (active ? "black" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -864,7 +984,9 @@ class App extends React.Component { style={{ axisLabel: { padding: 10 } }} - tickLabelComponent={} + tickLabelComponent={ + + } labelPlacement="perpendicular" axisValue={i + 1} label={key} diff --git a/demo/js/components/performance.js b/demo/js/components/performance.js index a5dafd002..6f6855ee3 100644 --- a/demo/js/components/performance.js +++ b/demo/js/components/performance.js @@ -5,7 +5,10 @@ import { VictorySelectionContainer } from "Packages/victory-selection-container/ import { VictoryScatter } from "Packages/victory-scatter/src/index"; import { VictoryChart } from "Packages/victory-chart/src/index"; -const scatterData = range(4000).map(() => ({ x: Math.random(), y: Math.random() })); +const scatterData = range(4000).map(() => ({ + x: Math.random(), + y: Math.random() +})); class App extends React.Component { constructor() { @@ -49,7 +52,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
diff --git a/demo/js/components/selection-demo.js b/demo/js/components/selection-demo.js index 9034fce70..505dfa442 100644 --- a/demo/js/components/selection-demo.js +++ b/demo/js/components/selection-demo.js @@ -52,7 +52,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -131,7 +133,10 @@ class App extends React.Component { /> - }> + } + > (active ? "tomato" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "tomato" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -156,7 +163,9 @@ class App extends React.Component { > (active ? "blue" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "blue" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -171,7 +180,9 @@ class App extends React.Component { > (active ? "black" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> diff --git a/demo/js/components/victory-area-demo.js b/demo/js/components/victory-area-demo.js index 7081fa191..63e6fc5b6 100644 --- a/demo/js/components/victory-area-demo.js +++ b/demo/js/components/victory-area-demo.js @@ -6,7 +6,10 @@ import { VictoryChart } from "Packages/victory-chart/src/index"; import { VictoryStack } from "Packages/victory-stack/src/index"; import { VictoryGroup } from "Packages/victory-group/src/index"; import { VictoryArea } from "Packages/victory-area/src/index"; -import { VictoryContainer, VictoryTheme } from "Packages/victory-core/src/index"; +import { + VictoryContainer, + VictoryTheme +} from "Packages/victory-core/src/index"; export default class App extends React.Component { constructor() { @@ -165,7 +168,9 @@ export default class App extends React.Component { } > {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} @@ -276,7 +281,9 @@ export default class App extends React.Component { { target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { @@ -363,11 +370,16 @@ export default class App extends React.Component { } > {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} - + } + containerComponent={ + + } events={[ { target: "grid", @@ -115,7 +121,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -164,7 +172,12 @@ export default class App extends React.Component { - +
diff --git a/demo/js/components/victory-bar-demo.js b/demo/js/components/victory-bar-demo.js index 2b8347b6d..5aa57a251 100644 --- a/demo/js/components/victory-bar-demo.js +++ b/demo/js/components/victory-bar-demo.js @@ -8,12 +8,19 @@ import { VictoryGroup } from "Packages/victory-group/src/index"; import { VictoryBar } from "Packages/victory-bar/src/index"; import { VictorySharedEvents } from "Packages/victory-shared-events/src/index"; -import { VictoryContainer, VictoryTheme, VictoryLabel } from "Packages/victory-core/src/index"; +import { + VictoryContainer, + VictoryTheme, + VictoryLabel +} from "Packages/victory-core/src/index"; import { assign, random, range, merge } from "lodash"; class Wrapper extends React.Component { static propTypes = { - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]) + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]) }; renderChildren(props) { @@ -110,7 +117,11 @@ export default class App extends React.Component { } render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; const containerStyle = { display: "flex", @@ -206,7 +217,10 @@ export default class App extends React.Component { />
- + "HELLO"} - labelComponent={} + labelComponent={ + + } animate={{ duration: 500, onExit: { @@ -246,7 +262,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { @@ -264,7 +282,10 @@ export default class App extends React.Component { x="a" y="b" /> - + {this.state.multiTransitionData.map((data, index) => { return ( @@ -279,7 +300,11 @@ export default class App extends React.Component { domainPadding={{ x: 30 }} theme={VictoryTheme.material} > - + {this.state.multiTransitionData.map((data, index) => { return ( @@ -297,7 +322,9 @@ export default class App extends React.Component { animate={{ duration: 2000 }} > {this.getBarData().map((data, index) => { - return ; + return ( + + ); })} @@ -372,7 +399,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } } ]; @@ -396,7 +425,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "blue" }) }; + return { + style: merge({}, props.style, { fill: "blue" }) + }; } } ]; @@ -418,7 +449,9 @@ export default class App extends React.Component { return { childName: "secondBar", mutation: (props) => { - return { style: merge({}, props.style, { fill: "blue" }) }; + return { + style: merge({}, props.style, { fill: "blue" }) + }; } }; } @@ -436,12 +469,16 @@ export default class App extends React.Component { mutation: (props) => { return props.style.fill === "cyan" ? null - : { style: merge({}, props.style, { fill: "cyan" }) }; + : { + style: merge({}, props.style, { fill: "cyan" }) + }; } }, { mutation: (props) => { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { @@ -571,7 +608,11 @@ class ChartWrap extends React.Component { // renders both a standalone chart, and a version wrapped in VictoryChart, // to test both cases at once render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; return (
diff --git a/demo/js/components/victory-box-plot-demo.js b/demo/js/components/victory-box-plot-demo.js index 03079d654..23f43595d 100644 --- a/demo/js/components/victory-box-plot-demo.js +++ b/demo/js/components/victory-box-plot-demo.js @@ -45,11 +45,17 @@ export default class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
- + - + - +
); } diff --git a/demo/js/components/victory-brush-container-demo.js b/demo/js/components/victory-brush-container-demo.js index e8b85adea..8397778e3 100644 --- a/demo/js/components/victory-brush-container-demo.js +++ b/demo/js/components/victory-brush-container-demo.js @@ -30,7 +30,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -111,7 +113,10 @@ class App extends React.Component { height={400} padding={{ top: 100, bottom: 50, left: 50, right: 50 }} containerComponent={ - + } > @@ -179,7 +184,10 @@ class App extends React.Component { }} domain={{ x: [0, 10], y: [-5, 5] }} containerComponent={ - + } size={({ active }) => (active ? 5 : 3)} data={[ @@ -200,14 +208,18 @@ class App extends React.Component { fill: ({ active }) => (active ? "tomato" : "black") } }} - containerComponent={} + containerComponent={ + + } size={({ active }) => (active ? 5 : 3)} y={(d) => d.x * d.x} /> } + containerComponent={ + + } > - }> + } + > d.x === name); return ( - point && Math.max(...filters[name]) >= point.y && Math.min(...filters[name]) <= point.y + point && + Math.max(...filters[name]) >= point.y && + Math.min(...filters[name]) <= point.y ); }, true); }; @@ -88,17 +90,22 @@ class App extends React.Component { onDomainChange(domain, props) { const filters = this.addNewFilters(domain, props); const isFiltered = !_.isEmpty(_.values(filters).filter(Boolean)); - const activeDatasets = isFiltered ? this.getActiveDatasets(filters) : this.state.datasets; + const activeDatasets = isFiltered + ? this.getActiveDatasets(filters) + : this.state.datasets; this.setState({ activeDatasets, filters, isFiltered }); } isActive(dataset) { // Determine whether a given dataset is active - return !this.state.isFiltered ? true : _.includes(this.state.activeDatasets, dataset.name); + return !this.state.isFiltered + ? true + : _.includes(this.state.activeDatasets, dataset.name); } getAxisOffset(index) { - const step = (width - padding.left - padding.right) / (attributes.length - 1); + const step = + (width - padding.left - padding.right) / (attributes.length - 1); return step * index + padding.left; } @@ -136,7 +143,9 @@ class App extends React.Component { alignItems: "center", justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (

VictoryBrushLine

@@ -185,10 +194,16 @@ class App extends React.Component { } offsetX={this.getAxisOffset(index)} style={{ - tickLabels: { fontSize: 15, padding: 15, pointerEvents: "none" } + tickLabels: { + fontSize: 15, + padding: 15, + pointerEvents: "none" + } }} tickValues={[0.2, 0.4, 0.6, 0.8, 1]} - tickFormat={(tick) => Math.round(tick * this.state.maximumValues[index])} + tickFormat={(tick) => + Math.round(tick * this.state.maximumValues[index]) + } /> ))} @@ -217,7 +232,9 @@ class App extends React.Component { /> } + axisComponent={ + + } /> @@ -247,7 +264,9 @@ class App extends React.Component { } + gridComponent={ + + } />
diff --git a/demo/js/components/victory-candlestick-demo.js b/demo/js/components/victory-candlestick-demo.js index 45bb6eef1..890df5271 100644 --- a/demo/js/components/victory-candlestick-demo.js +++ b/demo/js/components/victory-candlestick-demo.js @@ -99,7 +99,9 @@ export default class App extends React.Component { { mutation: (props) => { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -148,7 +150,9 @@ export default class App extends React.Component { { mutation: (props) => { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -175,7 +179,11 @@ export default class App extends React.Component { ]} /> - + - + { const scaledIndex = Math.floor(index % 7); @@ -330,7 +345,11 @@ class App extends React.Component { - + - + - + - 0.5 * d.x + 0.5} style={{ data: { stroke: "red" } }} /> - d.x * d.x} style={{ data: { stroke: "red" } }} /> + 0.5 * d.x + 0.5} + style={{ data: { stroke: "red" } }} + /> + d.x * d.x} + style={{ data: { stroke: "red" } }} + /> - + {this.state.barData.map((data, index) => { @@ -551,7 +588,9 @@ class App extends React.Component { target: "data", eventKey: "all", mutation: (props) => { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -597,7 +636,11 @@ class App extends React.Component { style={{ data: { stroke: "blue", strokeWidth: 5 } }} /> - + {this.getBarData().map((data, index) => { @@ -631,7 +674,9 @@ class App extends React.Component { childName: "area-2", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { diff --git a/demo/js/components/victory-cursor-container-demo.js b/demo/js/components/victory-cursor-container-demo.js index c26e0c5a0..5c9aa9a44 100644 --- a/demo/js/components/victory-cursor-container-demo.js +++ b/demo/js/components/victory-cursor-container-demo.js @@ -13,7 +13,8 @@ import { VictoryTooltip } from "Packages/victory-tooltip/src/index"; import { VictoryLegend } from "Packages/victory-legend/src/index"; import { VictoryTheme } from "Packages/victory-core/src/index"; -const makeData = () => range(1500).map((x) => ({ x, y: x + 10 * Math.random() })); +const makeData = () => + range(1500).map((x) => ({ x, y: x + 10 * Math.random() })); class App extends React.Component { constructor() { @@ -55,9 +56,12 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; - const cursorLabel = ({ datum }) => `${round(datum.x, 2)} , ${round(datum.y, 2)}`; + const cursorLabel = ({ datum }) => + `${round(datum.x, 2)} , ${round(datum.y, 2)}`; return (
@@ -67,7 +71,9 @@ class App extends React.Component { theme={VictoryTheme.material} height={400} padding={{ top: 100, bottom: 40, left: 50, right: 50 }} - containerComponent={} + containerComponent={ + + } > - }> + } + > { return range(4).map(() => { diff --git a/demo/js/components/victory-histogram-demo.js b/demo/js/components/victory-histogram-demo.js index bc2f1f8be..a4d4fd495 100644 --- a/demo/js/components/victory-histogram-demo.js +++ b/demo/js/components/victory-histogram-demo.js @@ -12,7 +12,9 @@ import { VictoryStack } from "Packages/victory-stack/src/index"; import { VictoryVoronoiContainer } from "Packages/victory-voronoi-container/src/index"; const randomDate = (start, end) => { - return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); + return new Date( + start.getTime() + Math.random() * (end.getTime() - start.getTime()) + ); }; const getData = ({ length = 100, min = 0, max = 10, dates = false } = {}) => { @@ -25,7 +27,11 @@ const getData = ({ length = 100, min = 0, max = 10, dates = false } = {}) => { export default class App extends React.Component { data = getData(); data2 = getData({ max: 100 }); - dateData = getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }); + dateData = getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }); constructor() { super(); @@ -61,12 +67,20 @@ export default class App extends React.Component { }, dateDynamicBinsBasedOnData: { - data: getData({ dates: true, min: new Date(2012, 2, 1), max: new Date(2015, 1, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 2, 1), + max: new Date(2015, 1, 1) + }), bins: undefined }, dateDynamicBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2012, 12, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2012, 12, 1) + }), bins: range(random(1, 12)).map((i) => new Date(2012, i, 1)) }, @@ -101,12 +115,24 @@ export default class App extends React.Component { }, dateDataLoadedInWithBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }), - bins: [new Date(2012, 0, 1), new Date(2013, 0, 1), new Date(2014, 0, 1)] + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }), + bins: [ + new Date(2012, 0, 1), + new Date(2013, 0, 1), + new Date(2014, 0, 1) + ] }, dateDataLoadedInWithoutBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }), bins: undefined }, @@ -120,7 +146,11 @@ export default class App extends React.Component { }, dateDynamicBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2012, 12, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2012, 12, 1) + }), bins: range(random(1, 12)).map((i) => new Date(2012, i, 1)) }, @@ -134,7 +164,14 @@ export default class App extends React.Component { } getStyles() { - const colors = ["palevioletred", "orange", "cyan", "green", "blue", "purple"]; + const colors = [ + "palevioletred", + "orange", + "cyan", + "green", + "blue", + "purple" + ]; return { stroke: colors[random(0, 5)], strokeWidth: random(1, 5) @@ -142,7 +179,11 @@ export default class App extends React.Component { } render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; const containerStyle = { display: "flex", flexDirection: "row", @@ -163,14 +204,18 @@ export default class App extends React.Component { onMouseOver: () => [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "pink" }) }; + return { + style: merge({}, props.style, { fill: "pink" }) + }; } } ], onMouseOut: () => [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "yellow" }) }; + return { + style: merge({}, props.style, { fill: "yellow" }) + }; } } ] @@ -268,7 +313,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "pink" }) }; + return { + style: merge({}, props.style, { fill: "pink" }) + }; } }, { @@ -435,7 +482,10 @@ export default class App extends React.Component { /> - + - + - + - + - } /> + } + /> } + labelComponent={ + + } /> } /> @@ -97,7 +104,9 @@ export default class App extends React.Component { lineHeight={[1, 3, 1]} textAnchor="start" verticalAnchor="end" - text={"Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?" + } /> } /> @@ -109,7 +118,9 @@ export default class App extends React.Component { lineHeight={[1, 3, 1]} textAnchor="start" verticalAnchor="end" - text={"Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?" + } /> } /> @@ -132,7 +143,9 @@ export default class App extends React.Component { lineHeight={2} textAnchor="middle" verticalAnchor="end" - text={"Victory is awesome.\nThis is (middle, end) anchoring.\nGot it?"} + text={ + "Victory is awesome.\nThis is (middle, end) anchoring.\nGot it?" + } /> } /> @@ -143,7 +156,9 @@ export default class App extends React.Component { backgroundStyle={{ fill: "pink" }} textAnchor="start" verticalAnchor="end" - text={"Victory is awesome.\nThis is (start, end) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, end) anchoring.\nCapisce?" + } /> } /> @@ -154,7 +169,9 @@ export default class App extends React.Component { backgroundStyle={{ fill: "pink" }} textAnchor="end" verticalAnchor="middle" - text={"Victory is awesome.\nThis is (end, middle) anchoring.\nOK?"} + text={ + "Victory is awesome.\nThis is (end, middle) anchoring.\nOK?" + } /> } /> @@ -166,7 +183,9 @@ export default class App extends React.Component { textAnchor="middle" backgroundStyle={{ fill: "cyan", opacity: 0.4 }} verticalAnchor="middle" - text={"Victory is awesome.\nThis is (middle, middle) anchoring.\nGot it?"} + text={ + "Victory is awesome.\nThis is (middle, middle) anchoring.\nGot it?" + } /> } /> @@ -176,7 +195,9 @@ export default class App extends React.Component { } /> @@ -186,7 +207,10 @@ export default class App extends React.Component { labelComponent={ @@ -231,7 +255,12 @@ export default class App extends React.Component { { fill: "purple", opacity: 0.4 }, { fill: "red", opacity: 0.4 } ]} - text={["Victory is awesome.", "This is variable", "lineHeight", "as an array."]} + text={[ + "Victory is awesome.", + "This is variable", + "lineHeight", + "as an array." + ]} style={[{ fontSize: 20, fill: "green" }, { fontSize: 30 }]} // eslint-disable-next-line no-magic-numbers lineHeight={[2, 2, 3, 1]} @@ -278,7 +307,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="start" /> @@ -296,7 +329,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} verticalAnchor="middle" /> } @@ -314,7 +351,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - text={["Victory is awesome!!!! ", "inline labels ", "+ backgrounds"]} + text={[ + "Victory is awesome!!!! ", + "inline labels ", + "+ backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="start" /> @@ -332,7 +373,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "green", opacity: 0.2 } ]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="end" /> @@ -350,7 +395,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="start" /> @@ -367,7 +416,11 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="start" /> @@ -383,8 +436,16 @@ export default class App extends React.Component { { fill: "orange", opacity: 0.2 }, { fill: "cyan", opacity: 0.2 } ]} - style={[{ letterSpacing: 2, fontSize: 15 }, { fontSize: 20 }, { fontSize: 12 }]} - text={["Victory is awesome. ", "inline labels ", "with multiple backgrounds"]} + style={[ + { letterSpacing: 2, fontSize: 15 }, + { fontSize: 20 }, + { fontSize: 12 } + ]} + text={[ + "Victory is awesome. ", + "inline labels ", + "with multiple backgrounds" + ]} lineHeight={[1, 2, 2]} verticalAnchor="start" /> diff --git a/demo/js/components/victory-legend-demo.js b/demo/js/components/victory-legend-demo.js index 45a1bfe34..1570ec81c 100644 --- a/demo/js/components/victory-legend-demo.js +++ b/demo/js/components/victory-legend-demo.js @@ -83,7 +83,11 @@ const data = [ const LegendDemo = () => (
- + ( data={data} symbolSpacer={symbolSpacer} style={legendStyle} - titleComponent={} + titleComponent={ + + } events={[ { target: "data", diff --git a/demo/js/components/victory-line-demo.js b/demo/js/components/victory-line-demo.js index 44179a4ea..314438ebd 100644 --- a/demo/js/components/victory-line-demo.js +++ b/demo/js/components/victory-line-demo.js @@ -5,7 +5,11 @@ import PropTypes from "prop-types"; import { merge, random, range } from "lodash"; import { VictoryChart } from "Packages/victory-chart/src/index"; import { VictoryLine, Curve } from "Packages/victory-line/src/index"; -import { VictoryContainer, VictoryTheme, Point } from "Packages/victory-core/src/index"; +import { + VictoryContainer, + VictoryTheme, + Point +} from "Packages/victory-core/src/index"; class PointedLine extends React.Component { static propTypes = { @@ -108,7 +112,11 @@ export default class App extends React.Component { } render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; const containerStyle = { display: "flex", flexDirection: "row", @@ -138,7 +146,9 @@ export default class App extends React.Component { return [ { mutation: (props) => { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -165,7 +175,12 @@ export default class App extends React.Component { dataComponent={} /> - + - + @@ -210,7 +228,10 @@ export default class App extends React.Component { theme={VictoryTheme.grayscale} /> - + @@ -251,7 +272,10 @@ export default class App extends React.Component { ]} /> - + - + - + diff --git a/demo/js/components/victory-pie-demo.js b/demo/js/components/victory-pie-demo.js index 2d484b952..39d3c9498 100644 --- a/demo/js/components/victory-pie-demo.js +++ b/demo/js/components/victory-pie-demo.js @@ -12,7 +12,15 @@ export default class App extends React.Component { this.state = { data: this.getData(), transitionData: this.getTransitionData(), - colorScale: ["#D85F49", "#F66D3B", "#D92E1D", "#D73C4C", "#FFAF59", "#E28300", "#F6A57F"], + colorScale: [ + "#D85F49", + "#F66D3B", + "#D92E1D", + "#D73C4C", + "#FFAF59", + "#E28300", + "#F6A57F" + ], sliceWidth: 60, style: { parent: { @@ -87,14 +95,20 @@ export default class App extends React.Component { datum.radius - 12} padding={{ bottom: 50, left: 50, right: 10 }} width={400} @@ -120,7 +134,11 @@ export default class App extends React.Component { width={200} height={400} /> - + @@ -193,7 +211,11 @@ export default class App extends React.Component { colorScale="grayscale" /> - + diff --git a/demo/js/components/victory-polar-chart-demo.js b/demo/js/components/victory-polar-chart-demo.js index 8af7b81d7..27e6e8ec6 100644 --- a/demo/js/components/victory-polar-chart-demo.js +++ b/demo/js/components/victory-polar-chart-demo.js @@ -94,7 +94,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -113,7 +115,9 @@ class App extends React.Component { style={{ axisLabel: { padding: 10 } }} - tickLabelComponent={} + tickLabelComponent={ + + } labelPlacement="perpendicular" axisValue={i + 1} label={key} @@ -148,7 +152,9 @@ class App extends React.Component { > (active ? "tomato" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "tomato" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -166,7 +172,9 @@ class App extends React.Component { > (active ? "blue" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "blue" : "gray") } + }} labels={({ datum }) => `y: ${datum.y}`} labelComponent={} /> @@ -183,7 +191,9 @@ class App extends React.Component { > (active ? "black" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -302,13 +312,17 @@ class App extends React.Component { { childName: "bar-2", mutation: () => { - return { style: merge({}, props.style, { fill: "cyan" }) }; + return { + style: merge({}, props.style, { fill: "cyan" }) + }; } }, { childName: "bar-3", mutation: () => { - return { style: merge({}, props.style, { fill: "blue" }) }; + return { + style: merge({}, props.style, { fill: "blue" }) + }; } } ]; @@ -393,7 +407,10 @@ class App extends React.Component { { mutation: () => { return { - style: merge({}, props.style, { fill: "cyan", stroke: "cyan" }) + style: merge({}, props.style, { + fill: "cyan", + stroke: "cyan" + }) }; } } @@ -427,7 +444,12 @@ class App extends React.Component { name="area-1" interpolation="cardinal" style={{ - data: { fill: "tomato", stroke: "tomato", fillOpacity: 0.5, strokeWidth: 2 } + data: { + fill: "tomato", + stroke: "tomato", + fillOpacity: 0.5, + strokeWidth: 2 + } }} data={[ { x: 45, y: 20 }, @@ -442,7 +464,12 @@ class App extends React.Component { name="area-2" interpolation="cardinal" style={{ - data: { fill: "orange", stroke: "orange", fillOpacity: 0.5, strokeWidth: 2 } + data: { + fill: "orange", + stroke: "orange", + fillOpacity: 0.5, + strokeWidth: 2 + } }} data={[ { x: 45, y: 20 }, @@ -457,7 +484,12 @@ class App extends React.Component { name="area-3" interpolation="cardinal" style={{ - data: { fill: "gold", stroke: "gold", fillOpacity: 0.5, strokeWidth: 2 } + data: { + fill: "gold", + stroke: "gold", + fillOpacity: 0.5, + strokeWidth: 2 + } }} data={[ { x: 45, y: 20 }, @@ -593,7 +625,9 @@ class App extends React.Component { /> datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 45, y: 20, label: 1, fill: "red" }, { x: 90, y: 30, label: 2, fill: "orange" }, @@ -619,7 +653,9 @@ class App extends React.Component { datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 15, y: 20, label: 1, fill: "red" }, { x: 25, y: 30, label: 2, fill: "orange" }, @@ -724,7 +760,13 @@ class App extends React.Component { /> { "tomato", "greenyellow" ]; - const symbols = ["circle", "star", "square", "triangleUp", "triangleDown", "diamond", "plus"]; + const symbols = [ + "circle", + "star", + "square", + "triangleUp", + "triangleDown", + "diamond", + "plus" + ]; // symbol: symbols[scaledIndex], return range(100).map((index) => { const scaledIndex = Math.floor(index % 7); @@ -230,7 +242,9 @@ export default class App extends React.Component { style={style} theme={VictoryTheme.material} data={range(0, 200).map((i) => { - return { a: { b: [{ y: i * Math.sin(i * 0.3) }], x: Math.cos(i * 0.3) } }; + return { + a: { b: [{ y: i * Math.sin(i * 0.3) }], x: Math.cos(i * 0.3) } + }; })} x="a.x" y="a.b[0]y" diff --git a/demo/js/components/victory-tooltip-demo.js b/demo/js/components/victory-tooltip-demo.js index 87cf7c5e4..57d181b90 100644 --- a/demo/js/components/victory-tooltip-demo.js +++ b/demo/js/components/victory-tooltip-demo.js @@ -20,7 +20,11 @@ class App extends React.Component { justifyContent: "center" }; - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; return (
@@ -52,7 +56,11 @@ class App extends React.Component { + } labels={({ datum }) => `hello000000 #${datum.x}`} size={({ active }) => (active ? 5 : 3)} diff --git a/demo/js/components/victory-voronoi-container-demo.js b/demo/js/components/victory-voronoi-container-demo.js index a60cea13a..72a6e33f9 100644 --- a/demo/js/components/victory-voronoi-container-demo.js +++ b/demo/js/components/victory-voronoi-container-demo.js @@ -50,7 +50,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; const dy = 13; const CustomLabel = (props) => { @@ -92,7 +94,9 @@ class App extends React.Component { labelComponent={ { - return activePoints.map(({ y }) => `value: ${y}`).join(" - "); + return activePoints + .map(({ y }) => `value: ${y}`) + .join(" - "); }} /> } @@ -125,7 +129,9 @@ class App extends React.Component { `I'm kind of a long label ${datum.y}`} mouseFollowTooltips - labelComponent={} + labelComponent={ + + } /> } > @@ -165,7 +171,9 @@ class App extends React.Component { height={450} domain={{ y: [0, 1] }} style={chartStyle} - containerComponent={ datum.y} />} + containerComponent={ + datum.y} /> + } > (active ? 4 : 2) }, + data: { + stroke: "tomato", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "tomato" } }} /> @@ -224,7 +235,10 @@ class App extends React.Component { { x: 3, y: 3, l: "blue" } ]} style={{ - data: { stroke: "blue", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "blue", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "blue" } }} /> @@ -237,7 +251,10 @@ class App extends React.Component { { x: 3, y: -2, l: "bird" } ]} style={{ - data: { stroke: "black", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "black", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "black" } }} /> @@ -266,7 +283,10 @@ class App extends React.Component { + } > (active ? 8 : 3)} /> - + } + containerComponent={ + + } > } + containerComponent={ + + } > - }> + } + > (active ? 4 : 2) } + data: { + stroke: "red", + strokeWidth: ({ active }) => (active ? 4 : 2) + } }} /> @@ -588,7 +621,10 @@ class App extends React.Component { { x: 3, y: 3, c: "green", l: "success" } ]} style={{ - data: { stroke: "green", strokeWidth: ({ active }) => (active ? 4 : 2) } + data: { + stroke: "green", + strokeWidth: ({ active }) => (active ? 4 : 2) + } }} /> diff --git a/demo/js/components/victory-voronoi-demo.js b/demo/js/components/victory-voronoi-demo.js index 52d274974..0cdf5bb2a 100644 --- a/demo/js/components/victory-voronoi-demo.js +++ b/demo/js/components/victory-voronoi-demo.js @@ -47,8 +47,17 @@ class App extends React.Component { justifyContent: "center" }; - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; - const visible = { fill: "gray", opacity: 0.1, stroke: "black", strokeWidth: 2 }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; + const visible = { + fill: "gray", + opacity: 0.1, + stroke: "black", + strokeWidth: 2 + }; return (
diff --git a/demo/js/components/victory-zoom-container-demo.js b/demo/js/components/victory-zoom-container-demo.js index 58d5d3df6..42e4939e3 100644 --- a/demo/js/components/victory-zoom-container-demo.js +++ b/demo/js/components/victory-zoom-container-demo.js @@ -14,7 +14,11 @@ import { VictoryScatter } from "Packages/victory-scatter/src/index"; import { VictoryZoomContainer } from "Packages/victory-zoom-container/src/index"; import { VictoryTooltip } from "Packages/victory-tooltip/src/index"; import { VictoryLegend } from "Packages/victory-legend/src/index"; -import { VictoryTheme, VictoryClipContainer, VictoryPortal } from "Packages/victory-core/src/index"; +import { + VictoryTheme, + VictoryClipContainer, + VictoryPortal +} from "Packages/victory-core/src/index"; const allData = range(0, 10, 0.001).map((x) => ({ x, @@ -45,7 +49,9 @@ class CustomChart extends React.Component { getData() { const { zoomedXDomain } = this.state; const { data, maxPoints } = this.props; - const filtered = data.filter((d) => d.x >= zoomedXDomain[0] && d.x <= zoomedXDomain[1]); + const filtered = data.filter( + (d) => d.x >= zoomedXDomain[0] && d.x <= zoomedXDomain[1] + ); if (filtered.length > maxPoints) { const k = Math.ceil(filtered.length / maxPoints); @@ -149,7 +155,11 @@ export default class App extends React.Component { }; } render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; const containerStyle = { display: "flex", flexDirection: "row", @@ -160,14 +170,21 @@ export default class App extends React.Component { return (
- + } style={{ parent: parentStyle }} data={this.state.transitionData} > - + - }> + } + > { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -285,26 +307,42 @@ export default class App extends React.Component { /> - }> + } + > - + - + } animate={{ duration: 500 }} style={{ parent: parentStyle }} @@ -334,7 +372,9 @@ export default class App extends React.Component { childName: "area-2", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { diff --git a/demo/ts/app.tsx b/demo/ts/app.tsx index de4e4933e..d3c80c67a 100644 --- a/demo/ts/app.tsx +++ b/demo/ts/app.tsx @@ -42,14 +42,20 @@ const MAP = { "/axis": { component: AxisDemo, name: "AxisDemo" }, "/bar": { component: BarDemo, name: "BarDemo" }, "/box-plot": { component: BoxPlotDemo, name: "BoxPlotDemo" }, - "/brush-container": { component: BrushContainerDemo, name: "BrushContainerDemo" }, + "/brush-container": { + component: BrushContainerDemo, + name: "BrushContainerDemo" + }, "/brush-line": { component: BrushLineDemo, name: "BrushLineDemo" }, "/group-demo": { component: GroupDemo, name: "GroupDemo" }, "/horizontal-demo": { component: HorizontalDemo, name: "HorizontalDemo" }, "/histogram-demo": { component: HistogramDemo, name: "HistogramDemo" }, "/candlestick": { component: CandlestickDemo, name: "CandlestickDemo" }, "/chart": { component: ChartDemo, name: "ChartDemo" }, - "/cursor-container": { component: CursorContainerDemo, name: "CursorContainerDemo" }, + "/cursor-container": { + component: CursorContainerDemo, + name: "CursorContainerDemo" + }, "/draggable-demo": { component: DraggableDemo, name: "DraggableDemo" }, "/error-bar": { component: ErrorBarDemo, name: "ErrorBarDemo" }, "/events-demo": { component: EventsDemo, name: "EventsDemo" }, @@ -68,10 +74,19 @@ const MAP = { component: VictorySelectionContainerDemo, name: "VictorySelectionContainerDemo" }, - "/victory-shared-events": { component: VictorySharedEventsDemo, name: "VictorySharedEventsDemo" }, + "/victory-shared-events": { + component: VictorySharedEventsDemo, + name: "VictorySharedEventsDemo" + }, "/voronoi": { component: VoronoiDemo, name: "VoronoiDemo" }, - "/voronoi-container": { component: VoronoiContainerDemo, name: "VoronoiContainerDemo" }, - "/zoom-container": { component: ZoomContainerDemo, name: "ZoomContainerDemo" }, + "/voronoi-container": { + component: VoronoiContainerDemo, + name: "VoronoiContainerDemo" + }, + "/zoom-container": { + component: ZoomContainerDemo, + name: "ZoomContainerDemo" + }, "/ouia-demo": { component: OuiaDemo, name: "OuiaDemo" } }; diff --git a/demo/ts/components/accessibility-demo.tsx b/demo/ts/components/accessibility-demo.tsx index 50ba956dd..d38bd3297 100644 --- a/demo/ts/components/accessibility-demo.tsx +++ b/demo/ts/components/accessibility-demo.tsx @@ -64,7 +64,10 @@ const chartContainerStyle: React.CSSProperties = { padding: "25px" }; -export const assignIndexValue = (index: number | string, value: number): number => { +export const assignIndexValue = ( + index: number | string, + value: number +): number => { const determineValidNumber = Number(index); return isNumber(determineValidNumber) ? determineValidNumber + value : 1; }; @@ -78,7 +81,10 @@ export default class VictoryAccessibilityDemo extends React.Component {
{/**BAR */} -
+

Bar chart

{ } q3Component={ `${datum.x} q3 value is ${datum._q3}`} + ariaLabel={({ datum }) => + `${datum.x} q3 value is ${datum._q3}` + } tabIndex={({ index }) => assignIndexValue(index, 6.1)} /> } medianComponent={ `${datum.x} median value is ${datum._median}`} + ariaLabel={({ datum }) => + `${datum.x} median value is ${datum._median}` + } tabIndex={({ index }) => assignIndexValue(index, 5.1)} /> } q1Component={ `${datum.x} q1 value is ${datum._q1}`} + ariaLabel={({ datum }) => + `${datum.x} q1 value is ${datum._q1}` + } tabIndex={({ index }) => assignIndexValue(index, 6.2)} /> } @@ -167,7 +179,9 @@ export default class VictoryAccessibilityDemo extends React.Component { style={{ data: { fill: "#c43a31" } }} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20} /> } @@ -177,7 +191,9 @@ export default class VictoryAccessibilityDemo extends React.Component { data={accessibilityAreaData.b} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.1} /> } @@ -187,7 +203,9 @@ export default class VictoryAccessibilityDemo extends React.Component { style={{ data: { fill: "#c43a31", opacity: 0.8 } }} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.2} /> } @@ -197,7 +215,9 @@ export default class VictoryAccessibilityDemo extends React.Component { style={{ data: { fill: "#c43a31", opacity: 0.6 } }} dataComponent={ `area chart stack ${data[0]._stack}`} + ariaLabel={({ data }) => + `area chart stack ${data[0]._stack}` + } tabIndex={20.3} /> } @@ -224,9 +244,9 @@ export default class VictoryAccessibilityDemo extends React.Component { ariaLabel={({ data }) => data.map( (dataPoint: any, i: number) => - `data point ${i + 1} x value is ${dataPoint.x} and y value is ${ - dataPoint.y - }` + `data point ${i + 1} x value is ${ + dataPoint.x + } and y value is ${dataPoint.y}` ) } /> @@ -264,7 +284,9 @@ export default class VictoryAccessibilityDemo extends React.Component { data={accessibilityScatterData} dataComponent={ `scatter point x: ${datum.x}, y:${datum.y}`} + ariaLabel={({ datum }) => + `scatter point x: ${datum.x}, y:${datum.y}` + } tabIndex={({ index }) => assignIndexValue(index, 28)} /> } @@ -281,7 +303,9 @@ export default class VictoryAccessibilityDemo extends React.Component { data={accessibilityVoronoiData} dataComponent={ `voronoi chart, x ${datum.x}, y ${datum.y}`} + ariaLabel={({ datum }) => + `voronoi chart, x ${datum.x}, y ${datum.y}` + } tabIndex={({ index }) => assignIndexValue(index, 35)} /> } diff --git a/demo/ts/components/draggable-demo.tsx b/demo/ts/components/draggable-demo.tsx index a3fe8e718..29b6b83a9 100644 --- a/demo/ts/components/draggable-demo.tsx +++ b/demo/ts/components/draggable-demo.tsx @@ -95,14 +95,16 @@ class DraggablePoint extends React.Component { onMouseUp: (evt: any, targetProps: any) => { return [ { - mutation: () => merge(targetProps, { dragging: false, active: false }) + mutation: () => + merge(targetProps, { dragging: false, active: false }) } ]; }, onMouseLeave: (evt: any, targetProps: any) => { return [ { - mutation: () => merge(targetProps, { dragging: false, active: false }) + mutation: () => + merge(targetProps, { dragging: false, active: false }) } ]; } @@ -135,7 +137,9 @@ class App extends React.Component { } onPointChange(point: PointDataType) { - const newPoints = this.state.points.map((p) => (p.name === point.name ? point : p)); + const newPoints = this.state.points.map((p) => + p.name === point.name ? point : p + ); this.setState({ points: newPoints }); } @@ -210,7 +214,9 @@ class App extends React.Component { ))} } + dataComponent={ + + } style={{ data: { fill: "skyBlue", diff --git a/demo/ts/components/events-demo.tsx b/demo/ts/components/events-demo.tsx index 7f219c87f..1e51d4dcd 100644 --- a/demo/ts/components/events-demo.tsx +++ b/demo/ts/components/events-demo.tsx @@ -3,7 +3,10 @@ import React from "react"; import { VictoryChart } from "@packages/victory-chart/src/index"; import { VictoryStack } from "@packages/victory-stack/src/index"; import { VictoryArea } from "@packages/victory-area/src/index"; -import { VictoryBar, VictoryBarTTargetType } from "@packages/victory-bar/src/index"; +import { + VictoryBar, + VictoryBarTTargetType +} from "@packages/victory-bar/src/index"; import { VictoryLine } from "@packages/victory-line/src/index"; import { VictoryTheme, VictoryLabel } from "@packages/victory-core/src/index"; import { merge } from "lodash"; @@ -18,7 +21,9 @@ class EventsDemo extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; const barTarget: VictoryBarTTargetType = "data"; return ( @@ -102,7 +107,9 @@ class EventsDemo extends React.Component { childName: "line", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -204,7 +211,9 @@ class EventsDemo extends React.Component { target: "data", mutation: (props) => { const fill = props.style && props.style.fill; - return fill === "gold" ? null : { style: { fill: "gold" } }; + return fill === "gold" + ? null + : { style: { fill: "gold" } }; } } ]; diff --git a/demo/ts/components/group-demo.tsx b/demo/ts/components/group-demo.tsx index 759016245..7378e3107 100644 --- a/demo/ts/components/group-demo.tsx +++ b/demo/ts/components/group-demo.tsx @@ -49,7 +49,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -152,7 +154,10 @@ class App extends React.Component { Math.sin(2 * Math.PI * data.x)}> - } labels={({ datum }) => datum.y} /> + } + labels={({ datum }) => datum.y} + />
diff --git a/demo/ts/components/horizontal-demo.tsx b/demo/ts/components/horizontal-demo.tsx index 86c9e48da..04568d09f 100644 --- a/demo/ts/components/horizontal-demo.tsx +++ b/demo/ts/components/horizontal-demo.tsx @@ -43,7 +43,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
@@ -177,7 +179,11 @@ class App extends React.Component { - + "yo"} data={[ { x: new Date(2014, 6, 1), open: 9, close: 30, high: 56, low: 7 }, - { x: new Date(2015, 6, 2), open: 80, close: 40, high: 120, low: 10 }, - { x: new Date(2016, 6, 3), open: 50, close: 80, high: 90, low: 20 }, - { x: new Date(2017, 6, 4), open: 70, close: 22, high: 70, low: 5 }, - { x: new Date(2018, 6, 5), open: 20, close: 35, high: 50, low: 10 }, - { x: new Date(2019, 6, 6), open: 35, close: 30, high: 40, low: 3 }, - { x: new Date(2020, 6, 7), open: 30, close: 90, high: 95, low: 30 }, - { x: new Date(2021, 6, 8), open: 80, close: 81, high: 83, low: 75 } + { + x: new Date(2015, 6, 2), + open: 80, + close: 40, + high: 120, + low: 10 + }, + { + x: new Date(2016, 6, 3), + open: 50, + close: 80, + high: 90, + low: 20 + }, + { + x: new Date(2017, 6, 4), + open: 70, + close: 22, + high: 70, + low: 5 + }, + { + x: new Date(2018, 6, 5), + open: 20, + close: 35, + high: 50, + low: 10 + }, + { + x: new Date(2019, 6, 6), + open: 35, + close: 30, + high: 40, + low: 3 + }, + { + x: new Date(2020, 6, 7), + open: 30, + close: 90, + high: 95, + low: 30 + }, + { + x: new Date(2021, 6, 8), + open: 80, + close: 81, + high: 83, + low: 75 + } ]} /> @@ -411,7 +459,11 @@ class App extends React.Component { ]} /> - + } + containerComponent={ + + } > { +export default class ImmutableDemo extends React.Component< + any, + ImmutableDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -116,7 +119,15 @@ export default class ImmutableDemo extends React.Component { @@ -156,10 +167,13 @@ export default class ImmutableDemo extends React.Component { - memo[key] = data.map((d) => d[key]); - return memo; - }, {}); + const groupedData = keys(data[0]).reduce( + (memo: any, key: string | number) => { + memo[key] = data.map((d) => d[key]); + return memo; + }, + {} + ); return keys(groupedData).reduce((memo: any, key: string | number) => { memo[key] = Math.max(...groupedData[key]); return memo; @@ -236,7 +250,9 @@ export default class ImmutableDemo extends React.Component { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { @@ -307,8 +323,16 @@ export default class ImmutableDemo extends React.Component - - + + {this.state.multiTransitionData.map((data, index) => { return ( @@ -359,14 +383,62 @@ export default class ImmutableDemo extends React.Component { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -430,7 +504,9 @@ export default class ImmutableDemo extends React.Component { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -534,7 +610,12 @@ export default class ImmutableDemo extends React.Component { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { @@ -698,7 +781,10 @@ export default class ImmutableDemo extends React.Component (active ? 4 : 2) }, + data: { + stroke: "tomato", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "tomato" } }} /> @@ -709,7 +795,10 @@ export default class ImmutableDemo extends React.Component (active ? 4 : 2) }, + data: { + stroke: "blue", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "blue" } }} /> @@ -720,7 +809,10 @@ export default class ImmutableDemo extends React.Component (active ? 4 : 2) }, + data: { + stroke: "black", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "black" } }} /> @@ -733,7 +825,9 @@ export default class ImmutableDemo extends React.Component `${round(datum.x, 2)} , ${round(datum.y, 2)}`} + cursorLabel={(datum) => + `${round(datum.x, 2)} , ${round(datum.y, 2)}` + } /> } > @@ -752,7 +846,9 @@ export default class ImmutableDemo extends React.Component ({ x, y: x + 10 * Math.random() })))} + data={fromJS( + range(1500).map((x) => ({ x, y: x + 10 * Math.random() })) + )} /> @@ -766,7 +862,9 @@ export default class ImmutableDemo extends React.Component this.setState({ zoomDomain: domain })} + onZoomDomainChange={(domain) => + this.setState({ zoomDomain: domain }) + } /> } > @@ -797,7 +895,9 @@ export default class ImmutableDemo extends React.Component this.setState({ zoomDomain: domain })} + onBrushDomainChange={(domain) => + this.setState({ zoomDomain: domain }) + } /> } > @@ -830,15 +930,28 @@ export default class ImmutableDemo extends React.Component
- + {this.state.multiTransitionAreaData.map((data, index) => { - return ; + return ( + + ); })} - }> + } + > (active ? "tomato" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "tomato" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -862,7 +977,9 @@ export default class ImmutableDemo extends React.Component (active ? "blue" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "blue" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -876,7 +993,9 @@ export default class ImmutableDemo extends React.Component (active ? "black" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -897,7 +1016,9 @@ export default class ImmutableDemo extends React.Component} + tickLabelComponent={ + + } labelPlacement="perpendicular" axisValue={i + 1} label={key} diff --git a/demo/ts/components/primitives-demo.tsx b/demo/ts/components/primitives-demo.tsx index b81605cd1..6566cc69a 100644 --- a/demo/ts/components/primitives-demo.tsx +++ b/demo/ts/components/primitives-demo.tsx @@ -44,7 +44,9 @@ class App extends React.Component { handleClick() { const newBackgroundColor = - this.state.axisBackgroundColor === "mediumseagreen" ? "paleturquoise" : "mediumseagreen"; + this.state.axisBackgroundColor === "mediumseagreen" + ? "paleturquoise" + : "mediumseagreen"; this.setState({ axisBackgroundColor: newBackgroundColor }); } @@ -75,7 +77,11 @@ class App extends React.Component { background: { fill: this.state.axisBackgroundColor } }; - const lineSegmentStyle = { stroke: "white", strokeWidth: 5, cursor: "pointer" }; + const lineSegmentStyle = { + stroke: "white", + strokeWidth: 5, + cursor: "pointer" + }; return (
@@ -148,7 +154,9 @@ class App extends React.Component { minComponent={} /> - +
); diff --git a/demo/ts/components/selection-demo.tsx b/demo/ts/components/selection-demo.tsx index e586d322a..9c85b1b3d 100644 --- a/demo/ts/components/selection-demo.tsx +++ b/demo/ts/components/selection-demo.tsx @@ -18,7 +18,10 @@ interface DataSet { data?: { x: number; y: number }[]; } -export default class SelectionDemo extends React.Component { +export default class SelectionDemo extends React.Component< + any, + SelectionDemoState +> { constructor(props: any) { super(props); this.state = { @@ -39,9 +42,11 @@ export default class SelectionDemo extends React.Component { - return
  • {`${point.x}, ${point.y}`}
  • ; - }); + const points = this.state.points.map( + (point: { x: number; y: number }, index: number) => { + return
  • {`${point.x}, ${point.y}`}
  • ; + } + ); return (
    @@ -60,7 +65,9 @@ export default class SelectionDemo extends React.Component @@ -139,7 +146,10 @@ export default class SelectionDemo extends React.Component - }> + } + > (active ? "tomato" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "tomato" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -164,7 +176,9 @@ export default class SelectionDemo extends React.Component (active ? "blue" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "blue" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> @@ -179,7 +193,9 @@ export default class SelectionDemo extends React.Component (active ? "black" : "gray") } }} + style={{ + data: { fill: ({ active }) => (active ? "black" : "gray") } + }} labels={({ datum }) => datum.y} labelComponent={} /> diff --git a/demo/ts/components/victory-area-demo.tsx b/demo/ts/components/victory-area-demo.tsx index 3d8d52b1e..9f04daabd 100644 --- a/demo/ts/components/victory-area-demo.tsx +++ b/demo/ts/components/victory-area-demo.tsx @@ -28,7 +28,10 @@ interface VictoryAreaDemoState { style?: React.CSSProperties; } -export default class VictoryAreaDemo extends React.Component { +export default class VictoryAreaDemo extends React.Component< + any, + VictoryAreaDemoState +> { constructor(props: any) { super(props); @@ -185,7 +188,9 @@ export default class VictoryAreaDemo extends React.Component {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} @@ -295,7 +300,9 @@ export default class VictoryAreaDemo extends React.Component { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { @@ -382,11 +389,16 @@ export default class VictoryAreaDemo extends React.Component {this.state.multiTransitionData.map((data, index) => { - return ; + return ( + + ); })} - + { +export default class VictoryAxisDemo extends React.Component< + any, + VictoryAxisDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -69,7 +76,8 @@ export default class VictoryAxisDemo extends React.Component (tick === "Mariners\nSEA" ? "red" : "grey") }, tickLabels: { - fontWeight: ({ tick }: any) => (tick === "Mariners\nSEA" ? "bold" : "normal") + fontWeight: ({ tick }: any) => + tick === "Mariners\nSEA" ? "bold" : "normal" } }; @@ -112,7 +120,9 @@ export default class VictoryAxisDemo extends React.Component} + containerComponent={ + + } events={[ { target: "grid", @@ -121,7 +131,9 @@ export default class VictoryAxisDemo extends React.Component { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -170,7 +182,12 @@ export default class VictoryAxisDemo extends React.Component - +
    diff --git a/demo/ts/components/victory-bar-demo.tsx b/demo/ts/components/victory-bar-demo.tsx index e33186c05..b7031726c 100644 --- a/demo/ts/components/victory-bar-demo.tsx +++ b/demo/ts/components/victory-bar-demo.tsx @@ -5,7 +5,11 @@ import { VictoryStack } from "@packages/victory-stack"; import { VictoryGroup } from "@packages/victory-group"; import { VictoryBar } from "@packages/victory-bar"; -import { VictoryContainer, VictoryTheme, VictoryLabel } from "@packages/victory-core"; +import { + VictoryContainer, + VictoryTheme, + VictoryLabel +} from "@packages/victory-core"; import { assign, random, range, merge } from "lodash"; interface WrapperProps { @@ -14,7 +18,10 @@ interface WrapperProps { class Wrapper extends React.Component { static propTypes = { - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]) + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]) }; renderChildren(props: WrapperProps) { @@ -44,7 +51,10 @@ interface VictoryBarDemoState { numericBarData: BarData; } -export default class VictoryBarDemo extends React.Component { +export default class VictoryBarDemo extends React.Component< + any, + VictoryBarDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -127,7 +137,11 @@ export default class VictoryBarDemo extends React.Component - + "HELLO"} - labelComponent={} + labelComponent={ + + } animate={{ duration: 500, onExit: { @@ -263,7 +282,9 @@ export default class VictoryBarDemo extends React.Component { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { @@ -281,7 +302,10 @@ export default class VictoryBarDemo extends React.Component - + {this.state.multiTransitionData.map((data, index) => { return ( @@ -296,7 +320,11 @@ export default class VictoryBarDemo extends React.Component - + {this.state.multiTransitionData.map((data, index) => { return ( @@ -314,7 +342,9 @@ export default class VictoryBarDemo extends React.Component {this.getBarData().map((data, index) => { - return ; + return ( + + ); })} @@ -389,7 +419,9 @@ export default class VictoryBarDemo extends React.Component { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } } ]; @@ -413,7 +445,9 @@ export default class VictoryBarDemo extends React.Component { - return { style: merge({}, props.style, { fill: "blue" }) }; + return { + style: merge({}, props.style, { fill: "blue" }) + }; } } ]; @@ -517,7 +551,11 @@ class ChartWrap extends React.Component { // renders both a standalone chart, and a version wrapped in VictoryChart, // to test both cases at once render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; return (
    diff --git a/demo/ts/components/victory-box-plot-demo.tsx b/demo/ts/components/victory-box-plot-demo.tsx index 1711b163f..01a5244aa 100644 --- a/demo/ts/components/victory-box-plot-demo.tsx +++ b/demo/ts/components/victory-box-plot-demo.tsx @@ -13,7 +13,10 @@ interface VictoryBoxPlotDemoState { }[]; } -export default class VictoryBoxPlotDemo extends React.Component { +export default class VictoryBoxPlotDemo extends React.Component< + any, + VictoryBoxPlotDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -53,11 +56,17 @@ export default class VictoryBoxPlotDemo extends React.Component - + - + - +
    ); } diff --git a/demo/ts/components/victory-brush-container-demo.tsx b/demo/ts/components/victory-brush-container-demo.tsx index f69ec4f76..7dd299a13 100644 --- a/demo/ts/components/victory-brush-container-demo.tsx +++ b/demo/ts/components/victory-brush-container-demo.tsx @@ -40,7 +40,9 @@ export default class VictoryBrushContainerDemo extends React.Component< justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; return (
    @@ -121,7 +123,10 @@ export default class VictoryBrushContainerDemo extends React.Component< height={400} padding={{ top: 100, bottom: 50, left: 50, right: 50 }} containerComponent={ - + } > @@ -189,7 +194,10 @@ export default class VictoryBrushContainerDemo extends React.Component< }} domain={{ x: [0, 10], y: [-5, 5] }} containerComponent={ - + } size={({ active }) => (active ? 5 : 3)} data={[ @@ -210,14 +218,18 @@ export default class VictoryBrushContainerDemo extends React.Component< fill: ({ active }) => (active ? "tomato" : "black") } }} - containerComponent={} + containerComponent={ + + } size={({ active }) => (active ? 5 : 3)} y={(d) => d.x * d.x} /> } + containerComponent={ + + } > - }> + } + > [] | undefined; } -const attributes: [string, string, string, string] = ["strength", "intelligence", "speed", "luck"]; +const attributes: [string, string, string, string] = [ + "strength", + "intelligence", + "speed", + "luck" +]; const height = 500; const width = 500; -const padding: { [key: string]: number } = { top: 100, left: 50, right: 50, bottom: 50 }; +const padding: { [key: string]: number } = { + top: 100, + left: 50, + right: 50, + bottom: 50 +}; class App extends React.Component { constructor(props: any) { @@ -99,7 +109,9 @@ class App extends React.Component { } const point = _.find(dataset.data, (d) => d.x === name); return ( - point && Math.max(...filters[name]) >= point.y && Math.min(...filters[name]) <= point.y + point && + Math.max(...filters[name]) >= point.y && + Math.min(...filters[name]) <= point.y ); }, true); }; @@ -112,17 +124,22 @@ class App extends React.Component { onDomainChange(domain: DomainPropType, props: any) { const filters = this.addNewFilters(domain, props); const isFiltered = !_.isEmpty(_.values(filters).filter(Boolean)); - const activeDatasets = isFiltered ? this.getActiveDatasets(filters) : this.state.datasets; + const activeDatasets = isFiltered + ? this.getActiveDatasets(filters) + : this.state.datasets; this.setState({ activeDatasets, filters, isFiltered }); } isActive(dataset: any) { // Determine whether a given dataset is active - return !this.state.isFiltered ? true : _.includes(this.state.activeDatasets, dataset.name); + return !this.state.isFiltered + ? true + : _.includes(this.state.activeDatasets, dataset.name); } getAxisOffset(index: number) { - const step = (width - padding.left - padding.right) / (attributes.length - 1); + const step = + (width - padding.left - padding.right) / (attributes.length - 1); return step * index + padding.left; } @@ -216,7 +233,11 @@ class App extends React.Component { } offsetX={this.getAxisOffset(index)} style={{ - tickLabels: { fontSize: 15, padding: 15, pointerEvents: "none" } + tickLabels: { + fontSize: 15, + padding: 15, + pointerEvents: "none" + } }} tickValues={[0.2, 0.4, 0.6, 0.8, 1]} tickFormat={(tick) => Math.round(tick * max[index])} @@ -250,7 +271,9 @@ class App extends React.Component { /> } + axisComponent={ + + } /> @@ -280,7 +303,9 @@ class App extends React.Component { } + gridComponent={ + + } />
    diff --git a/demo/ts/components/victory-candlestick-demo.tsx b/demo/ts/components/victory-candlestick-demo.tsx index 157493190..1247dbd02 100644 --- a/demo/ts/components/victory-candlestick-demo.tsx +++ b/demo/ts/components/victory-candlestick-demo.tsx @@ -112,7 +112,9 @@ export default class VictoryCandlestickDemo extends React.Component< { mutation: (props) => { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -161,7 +163,9 @@ export default class VictoryCandlestickDemo extends React.Component< { mutation: (props) => { return { - style: merge({}, props.style.labels, { fill: "orange" }) + style: merge({}, props.style.labels, { + fill: "orange" + }) }; } } @@ -188,7 +192,11 @@ export default class VictoryCandlestickDemo extends React.Component< ]} /> - + - + { "tomato", "greenyellow" ]; - const symbols = ["circle", "star", "square", "triangleUp", "triangleDown", "diamond", "plus"]; + const symbols = [ + "circle", + "star", + "square", + "triangleUp", + "triangleDown", + "diamond", + "plus" + ]; const elementNum = random(10, 40); return range(elementNum).map((index) => { const scaledIndex = Math.floor(index % 7); @@ -360,7 +368,11 @@ class VictoryChartDemo extends React.Component { - + { - + { orientation="left" style={{ grid: { strokeWidth: 1 } }} /> - + { - 0.5 * d.x + 0.5} style={{ data: { stroke: "red" } }} /> - d.x * d.x} style={{ data: { stroke: "red" } }} /> + 0.5 * d.x + 0.5} + style={{ data: { stroke: "red" } }} + /> + d.x * d.x} + style={{ data: { stroke: "red" } }} + /> - + {this.state.barData.map((data, index) => { @@ -581,7 +611,9 @@ class VictoryChartDemo extends React.Component { target: "data", eventKey: "all", mutation: (props) => { - return { style: merge({}, props.style, { stroke: "lime" }) }; + return { + style: merge({}, props.style, { stroke: "lime" }) + }; } }, { @@ -627,7 +659,11 @@ class VictoryChartDemo extends React.Component { style={{ data: { stroke: "blue", strokeWidth: 5 } }} /> - + {this.getBarData().map((data, index) => { @@ -661,7 +697,9 @@ class VictoryChartDemo extends React.Component { childName: "area-2", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { diff --git a/demo/ts/components/victory-cursor-container-demo.tsx b/demo/ts/components/victory-cursor-container-demo.tsx index 3a816a322..e36696595 100644 --- a/demo/ts/components/victory-cursor-container-demo.tsx +++ b/demo/ts/components/victory-cursor-container-demo.tsx @@ -19,7 +19,8 @@ interface VictoryCursorContainerStateInterface { bigData: CoordinatesPropType[]; } -const makeData = () => range(1500).map((x) => ({ x, y: x + 10 * Math.random() })); +const makeData = () => + range(1500).map((x) => ({ x, y: x + 10 * Math.random() })); class App extends React.Component { defaultCursorValue?: CoordinatesPropType = undefined; @@ -65,7 +66,9 @@ class App extends React.Component { justifyContent: "center" }; - const chartStyle = { parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } }; + const chartStyle = { + parent: { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" } + }; const cursorLabel = (datum: CoordinatesPropType) => round(datum.x, 2); @@ -77,7 +80,9 @@ class App extends React.Component { theme={VictoryTheme.material} height={400} padding={{ top: 100, bottom: 40, left: 50, right: 50 }} - containerComponent={} + containerComponent={ + + } > { - }> + } + > { +export default class VictoryErrorBarDemo extends React.Component< + any, + VictoryErrorBarState +> { setStateInterval?: number = undefined; constructor(props: any) { diff --git a/demo/ts/components/victory-histogram-demo.tsx b/demo/ts/components/victory-histogram-demo.tsx index 1ff827276..53a0a803b 100644 --- a/demo/ts/components/victory-histogram-demo.tsx +++ b/demo/ts/components/victory-histogram-demo.tsx @@ -10,7 +10,9 @@ import { VictoryStack } from "@packages/victory-stack"; import { VictoryVoronoiContainer } from "@packages/victory-voronoi-container"; const randomDate = (start: Date, end: Date) => { - return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); + return new Date( + start.getTime() + Math.random() * (end.getTime() - start.getTime()) + ); }; const getData = ({ @@ -55,7 +57,11 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { data = getData(); data2 = getData({ max: 100 }); - dateData = getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }); + dateData = getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }); constructor(props: any) { super(props); @@ -91,12 +97,20 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { }, dateDynamicBinsBasedOnData: { - data: getData({ dates: true, min: new Date(2012, 2, 1), max: new Date(2015, 1, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 2, 1), + max: new Date(2015, 1, 1) + }), bins: undefined }, dateDynamicBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2012, 12, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2012, 12, 1) + }), bins: range(random(1, 12)).map((i) => new Date(2012, i, 1)) }, @@ -131,12 +145,24 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { }, dateDataLoadedInWithBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }), - bins: [new Date(2012, 0, 1), new Date(2013, 0, 1), new Date(2014, 0, 1)] + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }), + bins: [ + new Date(2012, 0, 1), + new Date(2013, 0, 1), + new Date(2014, 0, 1) + ] }, dateDataLoadedInWithoutBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2014, 0, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2014, 0, 1) + }), bins: undefined }, @@ -150,7 +176,11 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { }, dateDynamicBins: { - data: getData({ dates: true, min: new Date(2012, 0, 1), max: new Date(2012, 12, 1) }), + data: getData({ + dates: true, + min: new Date(2012, 0, 1), + max: new Date(2012, 12, 1) + }), bins: range(random(1, 12)).map((i) => new Date(2012, i, 1)) }, @@ -164,7 +194,14 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { } getStyles() { - const colors = ["palevioletred", "orange", "cyan", "green", "blue", "purple"]; + const colors = [ + "palevioletred", + "orange", + "cyan", + "green", + "blue", + "purple" + ]; return { stroke: colors[random(0, 5)], strokeWidth: random(1, 5) @@ -172,7 +209,11 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { } render() { - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; const containerStyle: React.CSSProperties = { display: "flex", flexDirection: "row", @@ -193,14 +234,18 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { onMouseOver: () => [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "pink" }) }; + return { + style: merge({}, props.style, { fill: "pink" }) + }; } } ], onMouseOut: () => [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "yellow" }) }; + return { + style: merge({}, props.style, { fill: "yellow" }) + }; } } ] @@ -298,7 +343,9 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { return [ { mutation: (props) => { - return { style: merge({}, props.style, { fill: "pink" }) }; + return { + style: merge({}, props.style, { fill: "pink" }) + }; } }, { @@ -465,7 +512,10 @@ export default class App extends React.Component<{}, VictoryBarDemoState> { /> - + { /> - + { /> - + { /> - + { render() { return (
    -

    VictoryLabel demo! The little circles show the anchor points for each label.

    - +

    + VictoryLabel demo! The little circles show the anchor points for each + label. +

    + { textAnchor="middle" verticalAnchor="start" style={{ padding: 15 }} - text={"Victory is awesome.\nThis is (middle, start) anchoring.\nGot it?"} + text={ + "Victory is awesome.\nThis is (middle, start) anchoring.\nGot it?" + } /> @@ -67,7 +76,9 @@ export default class App extends React.Component { y={450} textAnchor="start" verticalAnchor="start" - text={"Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, start) anchoring.\nCapisce?" + } /> @@ -88,7 +99,9 @@ export default class App extends React.Component { lineHeight={2} textAnchor="middle" verticalAnchor="end" - text={"Victory is awesome.\nThis is (middle, end) anchoring.\nGot it?"} + text={ + "Victory is awesome.\nThis is (middle, end) anchoring.\nGot it?" + } /> @@ -98,7 +111,9 @@ export default class App extends React.Component { y={900} textAnchor="start" verticalAnchor="end" - text={"Victory is awesome.\nThis is (start, end) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, end) anchoring.\nCapisce?" + } /> @@ -118,7 +133,9 @@ export default class App extends React.Component { lineHeight={2} textAnchor="middle" verticalAnchor="middle" - text={"Victory is awesome.\nThis is (middle, middle) anchoring.\nGot it?"} + text={ + "Victory is awesome.\nThis is (middle, middle) anchoring.\nGot it?" + } /> @@ -127,7 +144,9 @@ export default class App extends React.Component { y={1350} textAnchor="start" verticalAnchor="middle" - text={"Victory is awesome.\nThis is (start, middle) anchoring.\nCapisce?"} + text={ + "Victory is awesome.\nThis is (start, middle) anchoring.\nCapisce?" + } /> {/* examples for inlining VictoryLabel with mutlitple labels */} @@ -162,7 +181,15 @@ export default class App extends React.Component { textAnchor="start" verticalAnchor="start" backgroundStyle={{ fill: "lavender" }} - text={["Use", "dx", "attribute", "to", "shift", "labels", "relative to one another."]} + text={[ + "Use", + "dx", + "attribute", + "to", + "shift", + "labels", + "relative to one another." + ]} inline dx={10} /> @@ -182,7 +209,12 @@ export default class App extends React.Component { { fill: "red" } ]} backgroundPadding={[{ right: -25 }, { right: -80, bottom: -30 }]} - text={["Victory is awesome.", "This is variable", "lineHeight", "as an array."]} + text={[ + "Victory is awesome.", + "This is variable", + "lineHeight", + "as an array." + ]} style={[{ fontSize: 50, fill: "green" }, { fontSize: 60 }]} // eslint-disable-next-line no-magic-numbers lineHeight={[2, 2, 3, 1]} diff --git a/demo/ts/components/victory-legend-demo.tsx b/demo/ts/components/victory-legend-demo.tsx index 74e2a0a82..1694410ca 100644 --- a/demo/ts/components/victory-legend-demo.tsx +++ b/demo/ts/components/victory-legend-demo.tsx @@ -93,7 +93,9 @@ const LegendDemo = () => ( data={data} symbolSpacer={symbolSpacer} style={legendStyle} - titleComponent={} + titleComponent={ + + } events={[ { target: "data", diff --git a/demo/ts/components/victory-line-demo.tsx b/demo/ts/components/victory-line-demo.tsx index a36fabd45..cd9f889f2 100644 --- a/demo/ts/components/victory-line-demo.tsx +++ b/demo/ts/components/victory-line-demo.tsx @@ -2,7 +2,11 @@ import React from "react"; import { merge, random, range } from "lodash"; import { VictoryChart } from "@packages/victory-chart/src/index"; import { VictoryLine, Curve } from "@packages/victory-line/src/index"; -import { VictoryContainer, VictoryTheme, Point } from "@packages/victory-core/src/index"; +import { + VictoryContainer, + VictoryTheme, + Point +} from "@packages/victory-core/src/index"; interface PointedLineProps { index?: string | number; @@ -66,7 +70,10 @@ interface VictoryLineDemoState { style: React.CSSProperties; } -export default class VictoryLineDemo extends React.Component { +export default class VictoryLineDemo extends React.Component< + any, + VictoryLineDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -124,7 +131,11 @@ export default class VictoryLineDemo extends React.Component { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -181,7 +194,12 @@ export default class VictoryLineDemo extends React.Component} /> - + - + @@ -226,7 +247,10 @@ export default class VictoryLineDemo extends React.Component - + @@ -267,7 +291,10 @@ export default class VictoryLineDemo extends React.Component - + - + - + diff --git a/demo/ts/components/victory-pie-demo.tsx b/demo/ts/components/victory-pie-demo.tsx index 9d4fa7d12..5ce390452 100644 --- a/demo/ts/components/victory-pie-demo.tsx +++ b/demo/ts/components/victory-pie-demo.tsx @@ -23,7 +23,10 @@ interface VictoryPieDemoState { }; } -export default class VictoryPieDemo extends React.Component { +export default class VictoryPieDemo extends React.Component< + any, + VictoryPieDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { @@ -31,7 +34,15 @@ export default class VictoryPieDemo extends React.Component datum.radius - 12} padding={{ bottom: 50, left: 50, right: 10 }} width={400} @@ -139,7 +156,11 @@ export default class VictoryPieDemo extends React.Component - + @@ -212,7 +233,11 @@ export default class VictoryPieDemo extends React.Component - + diff --git a/demo/ts/components/victory-polar-axis-demo.tsx b/demo/ts/components/victory-polar-axis-demo.tsx index afeec9c97..42b0801ed 100644 --- a/demo/ts/components/victory-polar-axis-demo.tsx +++ b/demo/ts/components/victory-polar-axis-demo.tsx @@ -82,11 +82,14 @@ class App extends React.Component { } getMaxData(data: multiAxisDataListType) { - const groupedData = keys(data[0]).reduce((memo: any, key: string | number) => { - memo[key] = data.map((d) => d[key]); + const groupedData = keys(data[0]).reduce( + (memo: any, key: string | number) => { + memo[key] = data.map((d) => d[key]); - return memo; - }, {}); + return memo; + }, + {} + ); return keys(groupedData).reduce((memo: any, key: string | number) => { memo[key] = Math.max(...groupedData[key]); @@ -244,7 +247,9 @@ class App extends React.Component { /> datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 45, y: 20, label: 1, fill: "red" }, { x: 90, y: 30, label: 2, fill: "orange" }, @@ -270,7 +275,9 @@ class App extends React.Component { datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 15, y: 20, label: 1, fill: "red" }, { x: 25, y: 30, label: 2, fill: "orange" }, @@ -375,7 +382,13 @@ class App extends React.Component { /> { startAngle={20} endAngle={380} domain={[0, 360]} - tickValues={[0, 20, 45, 65, 90, 120, 135, 180, 225, 250, 270, 300, 315]} + tickValues={[ + 0, 20, 45, 65, 90, 120, 135, 180, 225, 250, 270, 300, 315 + ]} /> { "tomato", "greenyellow" ]; - const symbols = ["circle", "star", "square", "triangleUp", "triangleDown", "diamond", "plus"]; + const symbols = [ + "circle", + "star", + "square", + "triangleUp", + "triangleDown", + "diamond", + "plus" + ]; // symbol: symbols[scaledIndex], return range(100).map((index) => { const scaledIndex = Math.floor(index % 7); @@ -106,11 +114,16 @@ class CatPoint extends React.Component { }; renderSymbol(symbol: ScatterSymbolType): string { - const codePointHigh = (point: number) => Math.floor((point - 0x10000) / 0x400) + 0xd800; - const codePointLow = (point: number) => ((point - 0x10000) % 0x400) + 0xdc00; + const codePointHigh = (point: number) => + Math.floor((point - 0x10000) / 0x400) + 0xd800; + const codePointLow = (point: number) => + ((point - 0x10000) % 0x400) + 0xdc00; const symbolCode = CatPoint.symbolMap[symbol]; - return String.fromCharCode(codePointHigh(symbolCode), codePointLow(symbolCode)); + return String.fromCharCode( + codePointHigh(symbolCode), + codePointLow(symbolCode) + ); } render() { @@ -124,7 +137,10 @@ class CatPoint extends React.Component { } } -export default class VictoryScatterDemo extends React.Component { +export default class VictoryScatterDemo extends React.Component< + any, + VictoryScatterDemoState +> { setStateInterval?: number = undefined; constructor(props: any) { super(props); @@ -265,7 +281,9 @@ export default class VictoryScatterDemo extends React.Component { - return { a: { b: [{ y: i * Math.sin(i * 0.3) }], x: Math.cos(i * 0.3) } }; + return { + a: { b: [{ y: i * Math.sin(i * 0.3) }], x: Math.cos(i * 0.3) } + }; })} x="a.x" y="a.b[0]y" diff --git a/demo/ts/components/victory-selection-container-demo.tsx b/demo/ts/components/victory-selection-container-demo.tsx index ca3f06512..740f0f25b 100644 --- a/demo/ts/components/victory-selection-container-demo.tsx +++ b/demo/ts/components/victory-selection-container-demo.tsx @@ -6,7 +6,11 @@ import { VictoryLine } from "@packages/victory-line"; import { VictoryPolarAxis } from "@packages/victory-polar-axis"; import { VictoryScatter } from "@packages/victory-scatter"; import { VictorySelectionContainer } from "@packages/victory-selection-container"; -import { VictoryTheme, VictoryLabel, VictoryStyleInterface } from "@packages/victory-core"; +import { + VictoryTheme, + VictoryLabel, + VictoryStyleInterface +} from "@packages/victory-core"; import { VictoryVoronoiContainer } from "@packages/victory-voronoi-container"; import { VictoryZoomContainer } from "@packages/victory-zoom-container"; import { random, range, keys } from "lodash"; @@ -69,11 +73,14 @@ class VictorySelectionContainerDemo extends React.Component { } getMaxData(data: multiAxisDataListType) { - const groupedData = keys(data[0]).reduce((memo: any, key: string | number) => { - memo[key] = data.map((d) => d[key]); + const groupedData = keys(data[0]).reduce( + (memo: any, key: string | number) => { + memo[key] = data.map((d) => d[key]); - return memo; - }, {}); + return memo; + }, + {} + ); return keys(groupedData).reduce((memo: any, key: string | number) => { memo[key] = Math.max(...groupedData[key]); @@ -232,7 +239,9 @@ class VictorySelectionContainerDemo extends React.Component { /> datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 45, y: 20, label: 1, fill: "red" }, { x: 90, y: 30, label: 2, fill: "orange" }, @@ -258,7 +267,9 @@ class VictorySelectionContainerDemo extends React.Component { datum.fill, opacity: 0.5 } }} + style={{ + data: { fill: ({ datum }) => datum.fill, opacity: 0.5 } + }} data={[ { x: 15, y: 20, label: 1, fill: "red" }, { x: 25, y: 30, label: 2, fill: "orange" }, @@ -363,7 +374,13 @@ class VictorySelectionContainerDemo extends React.Component { /> { startAngle={20} endAngle={380} domain={[0, 360]} - tickValues={[0, 20, 45, 65, 90, 120, 135, 180, 225, 250, 270, 300, 315]} + tickValues={[ + 0, 20, 45, 65, 90, 120, 135, 180, 225, 250, 270, 300, 315 + ]} /> { return { childName: "secondBar", mutation: (props) => { - return { style: merge({}, props.style, { fill: "blue" }) }; + return { + style: merge({}, props.style, { fill: "blue" }) + }; } }; } @@ -45,12 +47,16 @@ export default class VictorySharedEventsDemo extends React.Component { mutation: (props) => { return props.style.fill === "cyan" ? null - : { style: merge({}, props.style, { fill: "cyan" }) }; + : { + style: merge({}, props.style, { fill: "cyan" }) + }; } }, { mutation: (props) => { - return { style: merge({}, props.style, { fill: "orange" }) }; + return { + style: merge({}, props.style, { fill: "orange" }) + }; } }, { diff --git a/demo/ts/components/victory-tooltip-demo.tsx b/demo/ts/components/victory-tooltip-demo.tsx index 500013778..feb0f9317 100644 --- a/demo/ts/components/victory-tooltip-demo.tsx +++ b/demo/ts/components/victory-tooltip-demo.tsx @@ -17,7 +17,11 @@ class App extends React.Component { justifyContent: "center" }; - const parentStyle = { border: "1px solid #ccc", margin: "2%", maxWidth: "40%" }; + const parentStyle = { + border: "1px solid #ccc", + margin: "2%", + maxWidth: "40%" + }; return (
    @@ -65,7 +69,11 @@ class App extends React.Component { + } labels={({ datum }) => `hello000000 #${datum.x}`} size={({ active }) => (active ? 5 : 3)} diff --git a/demo/ts/components/victory-voronoi-container-demo.tsx b/demo/ts/components/victory-voronoi-container-demo.tsx index 36d9389ee..8eeba33e6 100644 --- a/demo/ts/components/victory-voronoi-container-demo.tsx +++ b/demo/ts/components/victory-voronoi-container-demo.tsx @@ -68,7 +68,8 @@ export default class VictoryVoronoiContainerDemo extends React.Component< render() { const dy = 13; const CustomLabel = (props: any) => { - const x = props.x - 2 - 4 * Math.max(...props.text.map((t: string) => t.length)); + const x = + props.x - 2 - 4 * Math.max(...props.text.map((t: string) => t.length)); const startY = 2 + props.y - (props.text.length * dy) / 2; return ( @@ -133,7 +134,9 @@ export default class VictoryVoronoiContainerDemo extends React.Component< `I'm kind of a long label ${datum.y}`} mouseFollowTooltips - labelComponent={} + labelComponent={ + + } /> } > @@ -173,7 +176,9 @@ export default class VictoryVoronoiContainerDemo extends React.Component< height={450} domain={{ y: [0, 1] }} style={chartStyle} - containerComponent={ datum.y} />} + containerComponent={ + datum.y} /> + } > (active ? 4 : 2) }, + data: { + stroke: "tomato", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "tomato" } }} /> @@ -232,7 +240,10 @@ export default class VictoryVoronoiContainerDemo extends React.Component< { x: 3, y: 3, l: "blue" } ]} style={{ - data: { stroke: "blue", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "blue", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "blue" } }} /> @@ -245,7 +256,10 @@ export default class VictoryVoronoiContainerDemo extends React.Component< { x: 3, y: -2, l: "bird" } ]} style={{ - data: { stroke: "black", strokeWidth: ({ active }) => (active ? 4 : 2) }, + data: { + stroke: "black", + strokeWidth: ({ active }) => (active ? 4 : 2) + }, labels: { fill: "black" } }} /> @@ -274,7 +288,10 @@ export default class VictoryVoronoiContainerDemo extends React.Component< + } > (active ? 8 : 3)} /> - + } + containerComponent={ + + } > } + containerComponent={ + + } > - }> + } + > (active ? 4 : 2) } + data: { + stroke: "red", + strokeWidth: ({ active }) => (active ? 4 : 2) + } }} /> @@ -596,7 +626,10 @@ export default class VictoryVoronoiContainerDemo extends React.Component< { x: 3, y: 3, c: "green", l: "success" } ]} style={{ - data: { stroke: "green", strokeWidth: ({ active }) => (active ? 4 : 2) } + data: { + stroke: "green", + strokeWidth: ({ active }) => (active ? 4 : 2) + } }} /> diff --git a/demo/ts/components/victory-zoom-container-demo.tsx b/demo/ts/components/victory-zoom-container-demo.tsx index fa9901e67..1c8aa4728 100644 --- a/demo/ts/components/victory-zoom-container-demo.tsx +++ b/demo/ts/components/victory-zoom-container-demo.tsx @@ -213,14 +213,21 @@ export default class VictoryZoomContainerDemo extends React.Component< render() { return (
    - + } style={{ parent: parentStyle }} data={this.state.transitionData} > - + - }> + } + > { - return { style: merge({}, props.style, { stroke: "orange" }) }; + return { + style: merge({}, props.style, { stroke: "orange" }) + }; } }, { @@ -339,26 +351,42 @@ export default class VictoryZoomContainerDemo extends React.Component< /> - }> + } + > - + - + } animate={{ duration: 500 }} style={{ parent: parentStyle }} @@ -388,7 +416,9 @@ export default class VictoryZoomContainerDemo extends React.Component< childName: "area-2", target: "data", mutation: (props) => { - return { style: merge({}, props.style, { fill: "gold" }) }; + return { + style: merge({}, props.style, { fill: "gold" }) + }; } }, { diff --git a/docs/src/app.js b/docs/src/app.js index 5860604e2..b77f6cba8 100644 --- a/docs/src/app.js +++ b/docs/src/app.js @@ -20,7 +20,10 @@ const SCROLL_PIXEL_OFFSET = 25; const DEFAULT_PAGE_CONTENT_CLASS = ".Page-content"; const ROUTES = ["docs", "faq", "guides"]; -const scrollContent = async (hash, contentPaneClass = DEFAULT_PAGE_CONTENT_CLASS) => { +const scrollContent = async ( + hash, + contentPaneClass = DEFAULT_PAGE_CONTENT_CLASS +) => { const item = document.querySelector(`${contentPaneClass} ${hash}`); if (!item) { @@ -40,7 +43,8 @@ const scrollContent = async (hash, contentPaneClass = DEFAULT_PAGE_CONTENT_CLASS }); }; -const checkScrollRoutes = (pathname, routes = ROUTES) => routes.some((r) => pathname.includes(r)); +const checkScrollRoutes = (pathname, routes = ROUTES) => + routes.some((r) => pathname.includes(r)); const ScrollToCurrentSection = ({ location, children }) => { const { pathname, hash = "" } = location; @@ -93,7 +97,11 @@ const App = () => { {(props) => { const Comp = getComponentForPath(routePath) || ; - return {Comp}; + return ( + + {Comp} + + ); }} )} diff --git a/docs/src/html.js b/docs/src/html.js index aedf83384..e71c48791 100644 --- a/docs/src/html.js +++ b/docs/src/html.js @@ -6,11 +6,29 @@ export default ({ Html, Head, Body, children }) => ( - - - + + + - + diff --git a/docs/src/index.js b/docs/src/index.js index 8e280736b..377902a67 100644 --- a/docs/src/index.js +++ b/docs/src/index.js @@ -13,7 +13,9 @@ export default App; if (typeof document !== "undefined") { const target = document.getElementById("root"); - const renderMethod = target.hasChildNodes() ? ReactDOM.hydrate : ReactDOM.render; + const renderMethod = target.hasChildNodes() + ? ReactDOM.hydrate + : ReactDOM.render; const render = (Comp) => { renderMethod( diff --git a/docs/src/pages/about.js b/docs/src/pages/about.js index 4221d3ab3..b69b6bcac 100644 --- a/docs/src/pages/about.js +++ b/docs/src/pages/about.js @@ -71,14 +71,15 @@ const About = ({ sidebarContent }) => {

    - Victory is a set of modular charting components for React and React Native. Victory makes it - easy to get started without sacrificing flexibility. Create one of a kind data - visualizations with fully customizable styles and behaviors. Victory uses the same API for - web and React Native applications for easy cross-platform charting. + Victory is a set of modular charting components for React and React + Native. Victory makes it easy to get started without sacrificing + flexibility. Create one of a kind data visualizations with fully + customizable styles and behaviors. Victory uses the same API for web and + React Native applications for easy cross-platform charting.

    - Victory is helmed by Formidable’s Lauren Eastridge - . + Victory is helmed by Formidable’s{" "} + Lauren Eastridge.

    @@ -91,8 +92,8 @@ const About = ({ sidebarContent }) => {

    Victory in Use

    - Victory is used for charting across the web, from publicly-consumed informational graphs - to internal tracking and reporting. + Victory is used for charting across the web, from publicly-consumed + informational graphs to internal tracking and reporting.

    @@ -101,10 +102,12 @@ const About = ({ sidebarContent }) => {
    About Formidable

    - Formidable is a Seattle-based consultancy and development shop, focused on open-source, - full-stack JavaScript using React.js and Node.js, and the architecture of large-scale - JavaScript applications. We build products for some of the world’s biggest companies, - while helping their internal teams develop smart, thoughtful, and scalable systems. + Formidable is a Seattle-based consultancy and development shop, + focused on open-source, full-stack JavaScript using React.js and + Node.js, and the architecture of large-scale JavaScript applications. + We build products for some of the world’s biggest companies, while + helping their internal teams develop smart, thoughtful, and scalable + systems.

    diff --git a/docs/src/pages/gallery.js b/docs/src/pages/gallery.js index 9b03f8d40..25a9077ff 100644 --- a/docs/src/pages/gallery.js +++ b/docs/src/pages/gallery.js @@ -111,15 +111,17 @@ const Gallery = ({ gallery, sidebarContent }) => { ); }; - const previews = gallery.map((item, index) =>
    {renderPreviewItem(item)}
    ); + const previews = gallery.map((item, index) => ( +
    {renderPreviewItem(item)}
    + )); return ( Victory Gallery

    - Here are some examples to help you get started. Each example below links to a live, editable - playground. Code samples provided in these examples are free to use or modify however you - like. + Here are some examples to help you get started. Each example below links + to a live, editable playground. Code samples provided in these examples + are free to use or modify however you like.

    {previews} diff --git a/docs/src/pages/themes-template.js b/docs/src/pages/themes-template.js index cc04e85b1..f96e4f6a0 100644 --- a/docs/src/pages/themes-template.js +++ b/docs/src/pages/themes-template.js @@ -105,8 +105,10 @@ const ThemesTemplate = (props) => {

    Themes

    Try out the Victory themes and make your own. Check out the{" "} - VictoryTheme documentation more details - on themes. + + VictoryTheme documentation + {" "} + more details on themes.

    {renderMenu()} diff --git a/docs/src/partials/about/showcase-app.js b/docs/src/partials/about/showcase-app.js index 547a99367..5144619b9 100644 --- a/docs/src/partials/about/showcase-app.js +++ b/docs/src/partials/about/showcase-app.js @@ -30,7 +30,11 @@ const ShowcaseApp = (props) => { {props.company} {props.description}
    - {props.screenshot.alt} + {props.screenshot.alt} ); }; diff --git a/docs/src/partials/button.js b/docs/src/partials/button.js index 58ea917c8..90a7e9fd4 100644 --- a/docs/src/partials/button.js +++ b/docs/src/partials/button.js @@ -17,7 +17,9 @@ const StyledButton = styled.button` } `; -const Button = ({ children, onClick }) => {children}; +const Button = ({ children, onClick }) => ( + {children} +); Button.propTypes = { children: PropTypes.node, diff --git a/docs/src/partials/footer.js b/docs/src/partials/footer.js index 269fe9026..02d6fd3b8 100644 --- a/docs/src/partials/footer.js +++ b/docs/src/partials/footer.js @@ -61,24 +61,37 @@ const Footer = ({ className = "" }) => ( - + - + CONTACT - + CAREERS - Formidable is a Seattle, Denver, Phoenix and London-based engineering consultancy and open - source software organization, specializing in React.js, React Native, GraphQL, Node.js, and - the extended JavaScript ecosystem. We build products for some of the world’s biggest - companies, while helping their internal teams develop smart, thoughtful, and scalable - systems. + Formidable is a Seattle, Denver, Phoenix and London-based engineering + consultancy and open source software organization, specializing in + React.js, React Native, GraphQL, Node.js, and the extended JavaScript + ecosystem. We build products for some of the world’s biggest companies, + while helping their internal teams develop smart, thoughtful, and + scalable systems. diff --git a/docs/src/partials/gallery/preview.js b/docs/src/partials/gallery/preview.js index 94f64eb72..b44222e28 100644 --- a/docs/src/partials/gallery/preview.js +++ b/docs/src/partials/gallery/preview.js @@ -59,8 +59,12 @@ const Preview = (props) => { const compiledCode = compileCode(); if (noRender) { /* eslint-disable no-eval, prefer-spread */ - const Comp = React.createElement(eval(compiledCode).apply(null, tempScope)); - ReactDOMServer.renderToString(React.createElement(previewComponent, {}, Comp)); + const Comp = React.createElement( + eval(compiledCode).apply(null, tempScope) + ); + ReactDOMServer.renderToString( + React.createElement(previewComponent, {}, Comp) + ); render(React.createElement(previewComponent, {}, Comp), mountNode); } else { eval(compiledCode).apply(null, tempScope); diff --git a/docs/src/partials/gallery/slider.js b/docs/src/partials/gallery/slider.js index 337b653f3..6942df4c0 100644 --- a/docs/src/partials/gallery/slider.js +++ b/docs/src/partials/gallery/slider.js @@ -122,7 +122,8 @@ const Tooltip = styled.div` z-index: 100; box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28); transition: transform 0.3s ease-out; - transform: ${({ dragging }) => `translate(-50%, ${dragging ? "-36px" : "-25px"})`}; + transform: ${({ dragging }) => + `translate(-50%, ${dragging ? "-36px" : "-25px"})`}; border-radius: 3px; font-weight: bold; font-size: 16px; @@ -139,7 +140,8 @@ const Triangle = styled.div` border-left: solid transparent 14px; border-right: solid transparent 14px; border-top: solid ${({ color }) => color} 14px; - transform: ${({ dragging }) => `translate(-50%, ${dragging ? "-36px" : "-25px"})`}; + transform: ${({ dragging }) => + `translate(-50%, ${dragging ? "-36px" : "-25px"})`}; transition: color 0.3s ease-out, transform 0.3s ease-out; `; @@ -171,7 +173,9 @@ const Slider = ({ tooltipValues, color, value, maxValue, onChange }) => { if (dragging) { const left = containerRef.current.getBoundingClientRect().left; const sliderWidth = containerRef.current.clientWidth; - const location = isTouchEvent(ev) ? ev.touches[0].clientX - left : ev.clientX - left; + const location = isTouchEvent(ev) + ? ev.touches[0].clientX - left + : ev.clientX - left; const newPercentage = clamp(location / sliderWidth, 0, 1); @@ -192,7 +196,9 @@ const Slider = ({ tooltipValues, color, value, maxValue, onChange }) => { const handleDragStart = (ev) => { const left = containerRef.current.getBoundingClientRect().left; const sliderWidth = containerRef.current.clientWidth; - const location = isTouchEvent(ev) ? ev.touches[0].clientX - left : ev.clientX - left; + const location = isTouchEvent(ev) + ? ev.touches[0].clientX - left + : ev.clientX - left; const newPercentage = location / sliderWidth; @@ -223,7 +229,11 @@ const Slider = ({ tooltipValues, color, value, maxValue, onChange }) => { }, [handleDrag, handleDragDone]); return ( - + diff --git a/docs/src/partials/header.js b/docs/src/partials/header.js index f7a1311d2..3191f730e 100644 --- a/docs/src/partials/header.js +++ b/docs/src/partials/header.js @@ -71,7 +71,8 @@ const NavLinksList = styled.ul` `; const navItemStyle = css` - color: ${({ active, theme }) => (active ? theme.color.red : theme.color.darkBrown)}; + color: ${({ active, theme }) => + active ? theme.color.red : theme.color.darkBrown}; font-size: 1.4rem; letter-spacing: 0.1rem; margin-right: 2rem; @@ -129,7 +130,10 @@ const Header = ({ className = "", onMenuClick }) => { Victory - + About {/* /faq is nested under /docs but is at top-level for convenience @@ -145,26 +149,45 @@ const Header = ({ className = "", onMenuClick }) => { > Docs - + Gallery {config.projectLinks.map((link) => ( - + {link.label} ))} - + FAQs - + - + diff --git a/docs/src/partials/home/_content.js b/docs/src/partials/home/_content.js index 4662fb93d..3aa7c9253 100644 --- a/docs/src/partials/home/_content.js +++ b/docs/src/partials/home/_content.js @@ -5,7 +5,8 @@ const content = { background: require("../../../static/hero-background.svg"), cornerText: "ANOTHER OSS \n PROJECT BY", cornerIcon: require("../../../static/logos/logo-formidable-icon.svg"), - description: "React.js components for modular charting and data visualization.", + description: + "React.js components for modular charting and data visualization.", code: "npm install victory", link: { text: "DOCUMENTATION", @@ -87,7 +88,8 @@ const content = { }, { title: "Renature", - description: "A physics-based animation library for React inspired by the natural world.", + description: + "A physics-based animation library for React inspired by the natural world.", link: "https://formidable.com/open-source/renature", featured: true }, diff --git a/docs/src/partials/home/companies.js b/docs/src/partials/home/companies.js index 8c5936352..d50722cab 100644 --- a/docs/src/partials/home/companies.js +++ b/docs/src/partials/home/companies.js @@ -14,7 +14,11 @@ import TUNE from "../../../static/logos/logo-tune.svg"; import ZILLOW from "../../../static/logos/logo-zillow.svg"; import BENAROYA from "../../../static/logos/logo-benaroya.png"; import importedTheme from "../../styles/theme"; -import { LinkButton, LandingSectionWrapper, LandingSectionContent } from "./styles"; +import { + LinkButton, + LandingSectionWrapper, + LandingSectionContent +} from "./styles"; const SectionHeading = styled.h2` color: ${({ theme }) => theme.color.darkBrown}; @@ -83,7 +87,10 @@ const Companies = () => ( - + SEE SHOWCASE diff --git a/docs/src/partials/home/demo-animation.js b/docs/src/partials/home/demo-animation.js index ffafa881f..3a75f6b5e 100644 --- a/docs/src/partials/home/demo-animation.js +++ b/docs/src/partials/home/demo-animation.js @@ -36,7 +36,15 @@ export default class App extends React.Component { importedTheme.color.red, importedTheme.color.accentBrown ]; - const symbols = ["circle", "star", "square", "triangleUp", "triangleDown", "diamond", "plus"]; + const symbols = [ + "circle", + "star", + "square", + "triangleUp", + "triangleDown", + "diamond", + "plus" + ]; return range(25).map((index) => { const scaledIndex = Math.floor(index % 7); return { diff --git a/docs/src/partials/home/demo-custom-chart.js b/docs/src/partials/home/demo-custom-chart.js index e932e94b4..24f440dca 100644 --- a/docs/src/partials/home/demo-custom-chart.js +++ b/docs/src/partials/home/demo-custom-chart.js @@ -274,8 +274,20 @@ class MultipleAxes extends React.Component { return ( {/* Create stylistic elements */} - - + + {/* Define labels */} @@ -286,7 +298,12 @@ class MultipleAxes extends React.Component { style={styles.labelOne} text={"Economy \n % change on a year earlier"} /> - + {/* Add shared independent axis */} diff --git a/docs/src/partials/home/demo-custom-components.js b/docs/src/partials/home/demo-custom-components.js index 5bb35b286..f72897c2a 100644 --- a/docs/src/partials/home/demo-custom-components.js +++ b/docs/src/partials/home/demo-custom-components.js @@ -2,7 +2,13 @@ /*eslint-disable no-magic-numbers */ import React from "react"; import { range, random } from "lodash"; -import { Area, VictoryArea, VictoryAxis, VictoryChart, VictoryLine } from "victory"; +import { + Area, + VictoryArea, + VictoryAxis, + VictoryChart, + VictoryLine +} from "victory"; import importedTheme from "../../styles/theme"; @@ -20,7 +26,8 @@ const GradientPath = (props) => { const { percent, style = {}, ...rest } = props; const gradientId = `gradient-${Math.random()}`; - const isBrowser = typeof window !== "undefined" && window.__STATIC_GENERATOR !== true; + const isBrowser = + typeof window !== "undefined" && window.__STATIC_GENERATOR !== true; const loc = isBrowser ? window.location.href : ""; const areaStyle = Object.assign({}, style, { fill: `url(${loc}#${gradientId})`, @@ -113,7 +120,11 @@ export default class App extends React.Component { interpolation="monotoneX" data={d} style={{ data: { fill: colors[i] } }} - dataComponent={} />} + dataComponent={ + } + /> + } /> ))} theme.color.darkBrown}; diff --git a/docs/src/partials/home/get-started.js b/docs/src/partials/home/get-started.js index d81958dfc..b5c39ff51 100644 --- a/docs/src/partials/home/get-started.js +++ b/docs/src/partials/home/get-started.js @@ -1,7 +1,11 @@ import React from "react"; import styled, { css } from "styled-components"; import createPath from "../../helpers/path-helpers"; -import { LinkButton, LandingSectionWrapper, LandingSectionContent } from "./styles"; +import { + LinkButton, + LandingSectionWrapper, + LandingSectionContent +} from "./styles"; import importedTheme from "../../styles/theme"; import PropTypes from "prop-types"; const stripeStyle = css` @@ -34,7 +38,10 @@ const GetStarted = ({ description, link }) => { Get Started {description} - + {link.text} diff --git a/docs/src/partials/home/guides.js b/docs/src/partials/home/guides.js index 78206e19e..d36158414 100644 --- a/docs/src/partials/home/guides.js +++ b/docs/src/partials/home/guides.js @@ -2,7 +2,11 @@ import React from "react"; import { Link } from "react-router-dom"; import LazyRender from "../lazy-render"; -import { LandingSectionWrapper, LandingSectionContent, DropShadow } from "./styles"; +import { + LandingSectionWrapper, + LandingSectionContent, + DropShadow +} from "./styles"; import createPath from "../../helpers/path-helpers"; @@ -85,19 +89,25 @@ const Guides = () => ( - Custom Charts + + Custom Charts +
  • - Brush and Zoom + + Brush and Zoom +
  • - Custom Components + + Custom Components +
  • @@ -115,7 +125,9 @@ const Guides = () => ( - Animations + + Animations +
  • diff --git a/docs/src/partials/home/hero-demo.js b/docs/src/partials/home/hero-demo.js index ef70f0fc5..324c03ffd 100644 --- a/docs/src/partials/home/hero-demo.js +++ b/docs/src/partials/home/hero-demo.js @@ -36,24 +36,30 @@ const font = (color) => ({ fontFamily: "Helvetica" }); -const numberWithCommas = (x) => x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); +const numberWithCommas = (x) => + x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); const groupDownloadsByWeek = (dates) => { const downloadsGroupedByPeriod = {}; const today = new Date(); dates.forEach((date) => { - const start = format(startOfWeek(parse(date.day, "yyyy-MM-dd", today)), "yyyy-MM-dd"); + const start = format( + startOfWeek(parse(date.day, "yyyy-MM-dd", today)), + "yyyy-MM-dd" + ); downloadsGroupedByPeriod[start] = downloadsGroupedByPeriod[start] ? downloadsGroupedByPeriod[start] + date.downloads : date.downloads; }); - const weeklyDownloads = Object.entries(downloadsGroupedByPeriod).map(([key, value]) => ({ - date: key, - downloads: value - })); + const weeklyDownloads = Object.entries(downloadsGroupedByPeriod).map( + ([key, value]) => ({ + date: key, + downloads: value + }) + ); // remove the last element in the array, as it may not be a full week weeklyDownloads.pop(); return weeklyDownloads; @@ -162,9 +168,27 @@ const HeroDemo = () => { /> } > - - - + + + { ]} /> } - labels={({ datum }) => `${numberWithCommas(datum.downloads)}\nDOWNLOADS / WEEK`} + labels={({ datum }) => + `${numberWithCommas(datum.downloads)}\nDOWNLOADS / WEEK` + } /> diff --git a/docs/src/partials/home/hero.js b/docs/src/partials/home/hero.js index 42e7a33dc..7cdc481b5 100644 --- a/docs/src/partials/home/hero.js +++ b/docs/src/partials/home/hero.js @@ -216,12 +216,24 @@ const LearnMore = styled(Link)` } `; -const Hero = ({ background, code, cornerIcon, cornerText, description, linksArray, link }) => ( +const Hero = ({ + background, + code, + cornerIcon, + cornerText, + description, + linksArray, + link +}) => ( <> {cornerText} - + @@ -247,7 +259,12 @@ const Hero = ({ background, code, cornerIcon, cornerText, description, linksArra {linksArray.map((l) => { return l.external ? ( - + {l.text} ) : ( diff --git a/docs/src/partials/home/more-oss.js b/docs/src/partials/home/more-oss.js index 6ecdcbf32..316f0c007 100644 --- a/docs/src/partials/home/more-oss.js +++ b/docs/src/partials/home/more-oss.js @@ -2,7 +2,11 @@ import React from "react"; import PropTypes from "prop-types"; import { FeaturedBadge, ProjectBadge } from "formidable-oss-badges"; import styled from "styled-components"; -import { LinkButton, LandingSectionWrapper, LandingSectionContent } from "./styles"; +import { + LinkButton, + LandingSectionWrapper, + LandingSectionContent +} from "./styles"; import importedTheme from "../../styles/theme"; const SectionHeading = styled.h2` @@ -115,7 +119,11 @@ const MoreOSS = ({ ossArray, link }) => ( )} - + {card.title} {card.description} diff --git a/docs/src/partials/home/npm-copy.js b/docs/src/partials/home/npm-copy.js index 5d2928f0d..d7ae89c63 100644 --- a/docs/src/partials/home/npm-copy.js +++ b/docs/src/partials/home/npm-copy.js @@ -78,7 +78,9 @@ const NpmCopy = ({ text }) => { {text} - {copied ? "Copied" : "Copy"} + + {copied ? "Copied" : "Copy"} + diff --git a/docs/src/partials/home/styles/bounce-animation.js b/docs/src/partials/home/styles/bounce-animation.js index 18a2e3c2c..81a5f1b21 100644 --- a/docs/src/partials/home/styles/bounce-animation.js +++ b/docs/src/partials/home/styles/bounce-animation.js @@ -3,5 +3,6 @@ import styled from "styled-components"; export default styled.span` display: block; transition: all 0.1s; - transform: ${(props) => (props.bouncing ? "translateY(-0.6rem)" : "translateY(0)")}; + transform: ${(props) => + props.bouncing ? "translateY(-0.6rem)" : "translateY(0)"}; `; diff --git a/docs/src/partials/home/styles/index.js b/docs/src/partials/home/styles/index.js index 01e5beefe..c8b6b3c85 100644 --- a/docs/src/partials/home/styles/index.js +++ b/docs/src/partials/home/styles/index.js @@ -4,4 +4,10 @@ import LandingSectionContent from "./landing-section-content"; import DropShadow from "./drop-shadow"; import BounceAnimation from "./bounce-animation"; -export { LinkButton, LandingSectionWrapper, LandingSectionContent, DropShadow, BounceAnimation }; +export { + LinkButton, + LandingSectionWrapper, + LandingSectionContent, + DropShadow, + BounceAnimation +}; diff --git a/docs/src/partials/icon.js b/docs/src/partials/icon.js index 42add37fb..8f6953098 100644 --- a/docs/src/partials/icon.js +++ b/docs/src/partials/icon.js @@ -79,7 +79,12 @@ class Icon extends React.Component { } Icon.propTypes = { - glyph: PropTypes.oneOf(["back", "coming-soon", "external-link", "internal-link"]), + glyph: PropTypes.oneOf([ + "back", + "coming-soon", + "external-link", + "internal-link" + ]), style: PropTypes.object }; diff --git a/docs/src/partials/markdown/index.js b/docs/src/partials/markdown/index.js index 9271a0006..7b646b0b1 100644 --- a/docs/src/partials/markdown/index.js +++ b/docs/src/partials/markdown/index.js @@ -32,7 +32,12 @@ const Pre = styled.pre` const renderPlayground = (props, scope, theme) => { const scopeObject = - (scope && scope.reduce((obj, key) => Object.assign(obj, { [key]: scopeMap[key] }), {})) || {}; + (scope && + scope.reduce( + (obj, key) => Object.assign(obj, { [key]: scopeMap[key] }), + {} + )) || + {}; const playgroundScope = Object.assign({}, scopeObject, { ...Victory, @@ -164,7 +169,12 @@ const Markdown = (props) => { }; return ( - + ); }; diff --git a/docs/src/partials/page.js b/docs/src/partials/page.js index a9097488b..ab6d2a0a5 100644 --- a/docs/src/partials/page.js +++ b/docs/src/partials/page.js @@ -101,7 +101,11 @@ const Page = (props) => { const ref = useRef(); const handleOutsideClick = (e) => { - if (ref.current && !ref.current.contains(e.target) && sidebarOpen === true) { + if ( + ref.current && + !ref.current.contains(e.target) && + sidebarOpen === true + ) { setSidebarOpen(false); } }; @@ -116,7 +120,10 @@ const Page = (props) => { return ( -
    setSidebarOpen(true)} /> +
    setSidebarOpen(true)} + /> diff --git a/docs/src/partials/seo/index.js b/docs/src/partials/seo/index.js index 7f3ac9094..a6a56523c 100644 --- a/docs/src/partials/seo/index.js +++ b/docs/src/partials/seo/index.js @@ -19,7 +19,9 @@ class SEO extends Component { const { postNode, postSEO } = this.props; let description; if (postSEO) { - description = postNode.description ? postNode.description : postNode.excerpt; + description = postNode.description + ? postNode.description + : postNode.excerpt; } else { description = config.siteDescription; } @@ -41,7 +43,9 @@ class SEO extends Component { render() { const { postPath, postSEO } = this.props; - const postURL = postSEO ? config.siteUrl + config.pathPrefix + postPath : null; + const postURL = postSEO + ? config.siteUrl + config.pathPrefix + postPath + : null; const blogURL = config.siteUrl + config.pathPrefix; const title = this.generateTitle(); const description = this.generateDescription(); @@ -96,7 +100,9 @@ class SEO extends Component { {/* Schema.org tags */} - + {/* OpenGraph tags */} @@ -104,7 +110,10 @@ class SEO extends Component { - + ); } diff --git a/docs/src/partials/sidebar/components/category.js b/docs/src/partials/sidebar/components/category.js index 58497e379..e5d9ba3b2 100644 --- a/docs/src/partials/sidebar/components/category.js +++ b/docs/src/partials/sidebar/components/category.js @@ -2,7 +2,11 @@ import React from "react"; import PropTypes from "prop-types"; import isEmpty from "lodash/isEmpty"; -import { SidebarSectionHeading, SidebarSectionList, SidebarSectionSublist } from "../styles"; +import { + SidebarSectionHeading, + SidebarSectionList, + SidebarSectionSublist +} from "../styles"; const Category = ({ content, title, subCategories }) => { if (isEmpty(subCategories) && isEmpty(content)) { diff --git a/docs/src/partials/sidebar/components/introduction.js b/docs/src/partials/sidebar/components/introduction.js index ba1bb417b..95e9924c8 100644 --- a/docs/src/partials/sidebar/components/introduction.js +++ b/docs/src/partials/sidebar/components/introduction.js @@ -24,7 +24,11 @@ const renderMobileSidebarLinks = (mobileLinks) => { return ( {isExternal ? ( - + {link.title} ) : ( @@ -57,7 +61,9 @@ const Introduction = ({ content }) => { Introduction {content} - {renderMobileSidebarLinks(mobileLinks)} + + {renderMobileSidebarLinks(mobileLinks)} + ); diff --git a/docs/src/partials/sidebar/components/table-of-contents.js b/docs/src/partials/sidebar/components/table-of-contents.js index 68e0fb7a7..04b511431 100644 --- a/docs/src/partials/sidebar/components/table-of-contents.js +++ b/docs/src/partials/sidebar/components/table-of-contents.js @@ -30,7 +30,8 @@ const getLinkStylesByDepth = (depth, theme) => { const SubItemListItem = styled.li` padding-left: ${({ depth }) => (depth === 3 ? "7.7rem" : "5.3rem")}; line-height: ${({ depth }) => (depth === 3 ? "1.3rem" : "2.3rem")}; - margin: ${({ depth }) => (depth === 3 ? "0 .7rem 1.3rem 0" : "0 0.7rem 0.7rem 0")}; + margin: ${({ depth }) => + depth === 3 ? "0 .7rem 1.3rem 0" : "0 0.7rem 0.7rem 0"}; display: block; hyphens: auto; `; @@ -67,7 +68,10 @@ const TableOfContents = ({ active, link, headings }) => { return memo; }, []); return parentIndices.reduce((memo, curr, index) => { - const lastChild = index === parentIndices.length + 1 ? undefined : parentIndices[index + 1]; + const lastChild = + index === parentIndices.length + 1 + ? undefined + : parentIndices[index + 1]; const children = [treeHeadings.slice(curr + 1, lastChild)]; memo = children.length > 0 @@ -91,7 +95,9 @@ const TableOfContents = ({ active, link, headings }) => { // and take a long sip from a mint julep while mumbling something about the brittleness of scope and the joys of // referential transparency, but we're not generalizing this behavior and location-injection is table stakes // for front-end routing - return location.pathname.includes(absPath) ? hashPath : `${absPath}${hashPath}`; + return location.pathname.includes(absPath) + ? hashPath + : `${absPath}${hashPath}`; }; const getTOC = (tocLink, tocHeadings, i = 0) => { diff --git a/docs/src/partials/sidebar/index.js b/docs/src/partials/sidebar/index.js index 1c400ede5..5f6595d7f 100644 --- a/docs/src/partials/sidebar/index.js +++ b/docs/src/partials/sidebar/index.js @@ -15,7 +15,11 @@ import SearchInput from "./components/search-input"; import TableOfContents from "./components/table-of-contents"; import { TABLE_OF_CONTENTS_SECTIONS } from "./constants"; -import { SidebarSectionHeading, SidebarListItemLink, SidebarListItem } from "./styles"; +import { + SidebarSectionHeading, + SidebarListItemLink, + SidebarListItem +} from "./styles"; // was gonna pass this but I'm leaning towards this being an internal detail since at the end of the day the proper // behavior is based on a bunch of magic strings for a non-configurable internal method @@ -81,18 +85,25 @@ const getMatchTree = (link, filterTerm) => { if (!isEmpty(matches)) { const maxDepth = maxBy(matches, "depth").depth; let matchIndices = matches.map((match) => - findIndex(link.subHeadings, (heading) => includes(heading.value, match.value)) + findIndex(link.subHeadings, (heading) => + includes(heading.value, match.value) + ) ); matchIndices = matchIndices.sort((a, b) => a - b); - return link.subHeadings.slice(0, last(matchIndices) + 1).reduce((memo, curr, i) => { - const useHeading = i === matchIndices[0] || (i < matchIndices[0] && curr.depth < maxDepth); - if (useHeading && curr.value !== "Props") { - memo = memo.concat(curr); - matchIndices = i === matchIndices[0] ? matchIndices.slice(1) : matchIndices; - } - return memo; - }, []); + return link.subHeadings + .slice(0, last(matchIndices) + 1) + .reduce((memo, curr, i) => { + const useHeading = + i === matchIndices[0] || + (i < matchIndices[0] && curr.depth < maxDepth); + if (useHeading && curr.value !== "Props") { + memo = memo.concat(curr); + matchIndices = + i === matchIndices[0] ? matchIndices.slice(1) : matchIndices; + } + return memo; + }, []); } return []; }; @@ -131,9 +142,10 @@ const Sidebar = ({ className, content, onCloseClick }) => { return edge.data && edge.data.type === sectionCategory.type; }); return filteredEdges - ? (filteredByCategory[[sectionCategory.category]] = filteredEdges.filter((edge) => - sectionCategory.category.includes(edge.data.category) - )) + ? (filteredByCategory[[sectionCategory.category]] = + filteredEdges.filter((edge) => + sectionCategory.category.includes(edge.data.category) + )) : null; }); @@ -158,7 +170,8 @@ const Sidebar = ({ className, content, onCloseClick }) => { location.pathname.includes(`/${link.type}/${link.slug}`) ? true : filterTerm !== ""; - const headings = filterTerm !== "" ? getMatchTree(link, filterTerm) : link.subHeadings; + const headings = + filterTerm !== "" ? getMatchTree(link, filterTerm) : link.subHeadings; return ( @@ -202,8 +215,16 @@ const Sidebar = ({ className, content, onCloseClick }) => { ) : ( <> - - + + { diff --git a/docs/static.config.js b/docs/static.config.js index fdfa7fa3a..473dde831 100644 --- a/docs/static.config.js +++ b/docs/static.config.js @@ -57,7 +57,13 @@ export default { const commonPropsIntro = commonProps[0]; const orderById = (items) => _.orderBy(items, ["data.id"], ["asc"]); - const allSidebarItems = [...introduction, ...faq, ...guides, commonPropsIntro, ...trueDocs]; + const allSidebarItems = [ + ...introduction, + ...faq, + ...guides, + commonPropsIntro, + ...trueDocs + ]; // eslint-disable-next-line max-params const sidebarContent = allSidebarItems.reduce((av, cv, i, arr) => { diff --git a/package-scripts.js b/package-scripts.js index c6d0f81ca..a305cae3c 100644 --- a/package-scripts.js +++ b/package-scripts.js @@ -36,14 +36,25 @@ module.exports = { stories: "eslint --color stories", test: "eslint --color test", ts: npsUtils.series.nps("build-package-libs", "compile-ts"), - default: npsUtils.series.nps("lint.test", "lint.stories", "lint.demo", "lint.src") + default: npsUtils.series.nps( + "lint.test", + "lint.stories", + "lint.demo", + "lint.src" + ) }, format: { default: 'prettier --write "./**/*.{js,jsx,json,ts,tsx}"', ci: 'prettier --list-different "./**/*.{js,jsx,json,ts,tsx}"' }, check: { - ci: npsUtils.series.nps("format.ci", "lint", "build-package-libs", "karma.ci", "compile-ts"), + ci: npsUtils.series.nps( + "format.ci", + "lint", + "build-package-libs", + "karma.ci", + "compile-ts" + ), cov: npsUtils.series.nps("lint", "test.cov"), dev: npsUtils.series.nps("lint", "test.dev"), default: npsUtils.series.nps("lint", "test") @@ -65,13 +76,16 @@ module.exports = { "lerna-dry-run": "lerna publish --skip-git --skip-npm --loglevel silly", // TODO: organize build scripts once build perf is sorted out "babel-es": "cross-env BABEL_ENV=es babel src --out-dir es --copy-files", - "babel-lib": "cross-env BABEL_ENV=commonjs babel src --out-dir lib --copy-files", + "babel-lib": + "cross-env BABEL_ENV=commonjs babel src --out-dir lib --copy-files", "build-es": npsUtils.series.nps("clean.es", "babel-es"), "build-lib": npsUtils.series.nps("clean.lib", "babel-lib"), "build-libs": npsUtils.series.nps("build-lib", "build-es"), "build-package-libs": "lerna exec --parallel -- nps build-libs", - "build-dist-dev": "webpack --bail --config ../../config/webpack/webpack.config.dev.js --colors", - "build-dist-min": "webpack --bail --config ../../config/webpack/webpack.config.js --colors", + "build-dist-dev": + "webpack --bail --config ../../config/webpack/webpack.config.dev.js --colors", + "build-dist-min": + "webpack --bail --config ../../config/webpack/webpack.config.js --colors", "build-dists": npsUtils.concurrent.nps("build-dist-min", "build-dist-dev"), "build-dist": npsUtils.series.nps("clean.dist", "build-dists") } diff --git a/packages/victory-area/src/area.js b/packages/victory-area/src/area.js index 5070991b1..c59e50f29 100644 --- a/packages/victory-area/src/area.js +++ b/packages/victory-area/src/area.js @@ -37,7 +37,8 @@ const toNewName = (interpolation) => { const getLineFunction = (props) => { const { polar, scale, horizontal } = props; - const interpolationFunction = typeof props.interpolation === "function" && props.interpolation; + const interpolationFunction = + typeof props.interpolation === "function" && props.interpolation; const interpolationName = typeof props.interpolation === "string" && toNewName(props.interpolation); return polar @@ -57,7 +58,8 @@ const getLineFunction = (props) => { const getCartesianArea = (props, interpolation) => { const { horizontal, scale } = props; - const interpolationFunction = typeof interpolation === "function" && interpolation; + const interpolationFunction = + typeof interpolation === "function" && interpolation; const interpolationName = typeof interpolation === "string" && interpolation; return horizontal ? d3Shape @@ -78,7 +80,8 @@ const getCartesianArea = (props, interpolation) => { const getAreaFunction = (props) => { const { polar, scale } = props; - const interpolationFunction = typeof props.interpolation === "function" && props.interpolation; + const interpolationFunction = + typeof props.interpolation === "function" && props.interpolation; const interpolationName = typeof props.interpolation === "string" && toNewName(props.interpolation); const interpolation = interpolationFunction || interpolationName; @@ -105,7 +108,10 @@ const evaluateProps = (props) => { const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const desc = Helpers.evaluateProp(props.desc, props); const id = Helpers.evaluateProp(props.id, props); - const style = Helpers.evaluateStyle(assign({ fill: "black" }, props.style), props); + const style = Helpers.evaluateStyle( + assign({ fill: "black" }, props.style), + props + ); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); return assign({}, props, { ariaLabel, desc, id, style, tabIndex }); @@ -130,9 +136,11 @@ const Area = (props) => { desc, tabIndex } = props; - const defaultTransform = polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; + const defaultTransform = + polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; const transform = props.transform || defaultTransform; - const renderLine = style.stroke && style.stroke !== "none" && style.stroke !== "transparent"; + const renderLine = + style.stroke && style.stroke !== "none" && style.stroke !== "transparent"; const areaFunction = getAreaFunction(props); const lineFunction = renderLine && getLineFunction(props); @@ -176,7 +184,9 @@ const Area = (props) => { ) : null; - return renderLine ? React.cloneElement(groupComponent, {}, [area, line]) : area; + return renderLine + ? React.cloneElement(groupComponent, {}, [area, line]) + : area; }; Area.propTypes = { diff --git a/packages/victory-area/src/helper-methods.js b/packages/victory-area/src/helper-methods.js index 47704a712..df2cfe21b 100644 --- a/packages/victory-area/src/helper-methods.js +++ b/packages/victory-area/src/helper-methods.js @@ -1,5 +1,12 @@ import { assign, isNil } from "lodash"; -import { Helpers, LabelHelpers, Data, Domain, Scale, Collection } from "victory-core"; +import { + Helpers, + LabelHelpers, + Data, + Domain, + Scale, + Collection +} from "victory-core"; const getDataWithBaseline = (props, scale) => { let data = Data.getData(props); @@ -7,7 +14,8 @@ const getDataWithBaseline = (props, scale) => { data = []; } const getDefaultMin = (axis) => { - const defaultZero = Scale.getType(scale[axis]) === "log" ? 1 / Number.MAX_SAFE_INTEGER : 0; + const defaultZero = + Scale.getType(scale[axis]) === "log" ? 1 / Number.MAX_SAFE_INTEGER : 0; const domain = scale[axis].domain(); const minY = Collection.getMinValue(domain); const maxY = Collection.getMaxValue(domain); @@ -49,7 +57,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; const data = getDataWithBaseline(props, scale); return { style, data, scale, domain, origin }; }; @@ -110,7 +120,10 @@ const getBaseProps = (props, fallbackProps) => { }; return data.reduce((childProps, datum, index) => { const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { const eventKey = !isNil(datum.eventKey) ? datum.eventKey : index; childProps[eventKey] = { labels: LabelHelpers.getProps(props, index) }; } diff --git a/packages/victory-area/src/victory-area.js b/packages/victory-area/src/victory-area.js index b87295fd4..2646b364a 100644 --- a/packages/victory-area/src/victory-area.js +++ b/packages/victory-area/src/victory-area.js @@ -32,7 +32,14 @@ const options = { }; class VictoryArea extends React.Component { - static animationWhitelist = ["data", "domain", "height", "padding", "style", "width"]; + static animationWhitelist = [ + "data", + "domain", + "height", + "padding", + "style", + "width" + ]; static propTypes = { ...CommonProps.baseProps, @@ -74,7 +81,8 @@ class VictoryArea extends React.Component { static role = "area"; static continuous = true; static defaultTransitions = DefaultTransitions.continuousTransitions(); - static defaultPolarTransitions = DefaultTransitions.continuousPolarTransitions(); + static defaultPolarTransitions = + DefaultTransitions.continuousPolarTransitions(); static getDomain = Domain.getDomainWithZero; static getData = Data.getData; static getBaseProps = (props) => getBaseProps(props, fallbackProps); @@ -99,7 +107,9 @@ class VictoryArea extends React.Component { } const children = this.renderContinuousData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-axis/src/helper-methods.js b/packages/victory-axis/src/helper-methods.js index c222d1fe9..a657c4c96 100644 --- a/packages/victory-axis/src/helper-methods.js +++ b/packages/victory-axis/src/helper-methods.js @@ -36,9 +36,20 @@ const getStyleObject = (props) => { const specificAxisStyle = theme && theme[axisType] && theme[axisType].style; const mergeStyles = () => { - const styleNamespaces = ["axis", "axisLabel", "grid", "parent", "tickLabels", "ticks"]; + const styleNamespaces = [ + "axis", + "axisLabel", + "grid", + "parent", + "tickLabels", + "ticks" + ]; return styleNamespaces.reduce((memo, curr) => { - memo[curr] = defaults({}, specificAxisStyle[curr], generalAxisStyle[curr]); + memo[curr] = defaults( + {}, + specificAxisStyle[curr], + generalAxisStyle[curr] + ); return memo; }, {}); }; @@ -107,9 +118,13 @@ const getAxisProps = (modifiedProps, calculatedValues, globalTransform) => { return { style: style.axis, x1: isVertical ? globalTransform.x : padding.left + globalTransform.x, - x2: isVertical ? globalTransform.x : width - padding.right + globalTransform.x, + x2: isVertical + ? globalTransform.x + : width - padding.right + globalTransform.x, y1: isVertical ? padding.top + globalTransform.y : globalTransform.y, - y2: isVertical ? height - padding.bottom + globalTransform.y : globalTransform.y + y2: isVertical + ? height - padding.bottom + globalTransform.y + : globalTransform.y }; }; @@ -122,7 +137,8 @@ const getEvaluatedStyles = (style, props) => { }; const getAxisLabelProps = (props, calculatedValues, globalTransform) => { - const { style, orientation, padding, labelPadding, isVertical } = calculatedValues; + const { style, orientation, padding, labelPadding, isVertical } = + calculatedValues; const sign = orientationSign[orientation]; const hPadding = padding.left + padding.right; const vPadding = padding.top + padding.bottom; @@ -148,7 +164,12 @@ const getAxisLabelProps = (props, calculatedValues, globalTransform) => { }; const getAnchors = (orientation, isVertical) => { - const anchorOrientation = { top: "end", left: "end", right: "start", bottom: "start" }; + const anchorOrientation = { + top: "end", + left: "end", + right: "start", + bottom: "start" + }; const anchor = anchorOrientation[orientation]; return { textAnchor: isVertical ? anchor : "middle", @@ -179,22 +200,48 @@ const getDefaultOrientations = (axis, originSign, horizontal) => { positive: { x: "left", y: "bottom" }, negative: { x: "right", y: "top" } }; - return horizontal ? horizontalOrientations[sign][axis] : orientations[sign][axis]; + return horizontal + ? horizontalOrientations[sign][axis] + : orientations[sign][axis]; }; const getStandaloneOffset = (props, calculatedValues) => { - const { style, scale, orientation, padding, axis, ticks, stringTicks, isVertical, labelPadding } = - calculatedValues; + const { + style, + scale, + orientation, + padding, + axis, + ticks, + stringTicks, + isVertical, + labelPadding + } = calculatedValues; const { polar, horizontal } = props; - const sharedProps = { scale: { [axis]: scale }, polar, horizontal, ticks, stringTicks }; + const sharedProps = { + scale: { [axis]: scale }, + polar, + horizontal, + ticks, + stringTicks + }; const xPadding = orientation === "right" ? padding.right : padding.left; const yPadding = orientation === "top" ? padding.top : padding.bottom; - const offsetX = props.offsetX !== null && props.offsetX !== undefined ? props.offsetX : xPadding; - const offsetY = props.offsetY !== null && props.offsetY !== undefined ? props.offsetY : yPadding; + const offsetX = + props.offsetX !== null && props.offsetX !== undefined + ? props.offsetX + : xPadding; + const offsetY = + props.offsetY !== null && props.offsetY !== undefined + ? props.offsetY + : yPadding; const fontSize = style.axisLabel.fontSize || 14; // eslint-disable-line no-magic-numbers const tickSizes = ticks.map((data, index) => { const tick = stringTicks ? props.tickValues[data - 1] : data; - const tickStyle = Helpers.evaluateStyle(style.ticks, assign({}, sharedProps, { tick, index })); + const tickStyle = Helpers.evaluateStyle( + style.ticks, + assign({}, sharedProps, { tick, index }) + ); return tickStyle.size || 0; }); const totalPadding = fontSize + 2 * Math.max(...tickSizes) + labelPadding; @@ -210,12 +257,19 @@ const getStandaloneOffset = (props, calculatedValues) => { // eslint-disable-next-line complexity const getOffset = (props, calculatedValues) => { - const { scale, origin, orientation, orientations, domain, padding } = calculatedValues; + const { scale, origin, orientation, orientations, domain, padding } = + calculatedValues; const { top, bottom, left, right } = padding; const calculatedOrientation = { - x: orientation === "bottom" || orientation === "top" ? orientation : orientations.x, - y: orientation === "left" || orientation === "right" ? orientation : orientations.y + x: + orientation === "bottom" || orientation === "top" + ? orientation + : orientations.x, + y: + orientation === "left" || orientation === "right" + ? orientation + : orientations.y }; // make the axes line up, and cross when appropriate @@ -228,14 +282,30 @@ const getOffset = (props, calculatedValues) => { y: calculatedOrientation.x === "bottom" ? props.height : 0 }; const originPosition = { - x: origin.x === domain.x[0] || origin.x === domain.x[1] ? 0 : scale.x(origin.x), - y: origin.y === domain.y[0] || origin.y === domain.y[1] ? 0 : scale.y(origin.y) - }; - - const x = originPosition.x ? Math.abs(originOffset.x - originPosition.x) : orientationOffset.x; - const y = originPosition.y ? Math.abs(originOffset.y - originPosition.y) : orientationOffset.y; - const offsetX = props.offsetX !== null && props.offsetX !== undefined ? x - props.offsetX : x; - const offsetY = props.offsetY !== null && props.offsetY !== undefined ? y - props.offsetY : y; + x: + origin.x === domain.x[0] || origin.x === domain.x[1] + ? 0 + : scale.x(origin.x), + y: + origin.y === domain.y[0] || origin.y === domain.y[1] + ? 0 + : scale.y(origin.y) + }; + + const x = originPosition.x + ? Math.abs(originOffset.x - originPosition.x) + : orientationOffset.x; + const y = originPosition.y + ? Math.abs(originOffset.y - originPosition.y) + : orientationOffset.y; + const offsetX = + props.offsetX !== null && props.offsetX !== undefined + ? x - props.offsetX + : x; + const offsetY = + props.offsetY !== null && props.offsetY !== undefined + ? y - props.offsetY + : y; return { x: offsetX, @@ -245,12 +315,19 @@ const getOffset = (props, calculatedValues) => { // eslint-disable-next-line complexity const getHorizontalOffset = (props, calculatedValues) => { - const { scale, origin, orientation, orientations, domain, padding } = calculatedValues; + const { scale, origin, orientation, orientations, domain, padding } = + calculatedValues; const { top, bottom, left, right } = padding; const calculatedOrientation = { - y: orientation === "bottom" || orientation === "top" ? orientation : orientations.x, - x: orientation === "left" || orientation === "right" ? orientation : orientations.y + y: + orientation === "bottom" || orientation === "top" + ? orientation + : orientations.x, + x: + orientation === "left" || orientation === "right" + ? orientation + : orientations.y }; // make the axes line up, and cross when appropriate @@ -263,14 +340,30 @@ const getHorizontalOffset = (props, calculatedValues) => { x: calculatedOrientation.y === "bottom" ? props.height : 0 }; const originPosition = { - x: origin.x === domain.x[0] || origin.x === domain.x[1] ? 0 : scale.x(origin.x), - y: origin.y === domain.y[0] || origin.y === domain.y[1] ? 0 : scale.y(origin.y) - }; - - const y = originPosition.x ? Math.abs(originOffset.x - originPosition.x) : orientationOffset.x; - const x = originPosition.y ? Math.abs(originOffset.y - originPosition.y) : orientationOffset.y; - const offsetX = props.offsetX !== null && props.offsetX !== undefined ? x - props.offsetX : x; - const offsetY = props.offsetY !== null && props.offsetY !== undefined ? y - props.offsetY : y; + x: + origin.x === domain.x[0] || origin.x === domain.x[1] + ? 0 + : scale.x(origin.x), + y: + origin.y === domain.y[0] || origin.y === domain.y[1] + ? 0 + : scale.y(origin.y) + }; + + const y = originPosition.x + ? Math.abs(originOffset.x - originPosition.x) + : orientationOffset.x; + const x = originPosition.y + ? Math.abs(originOffset.y - originPosition.y) + : orientationOffset.y; + const offsetX = + props.offsetX !== null && props.offsetX !== undefined + ? x - props.offsetX + : x; + const offsetY = + props.offsetY !== null && props.offsetY !== undefined + ? y - props.offsetY + : y; return { x: offsetX, @@ -326,8 +419,12 @@ const getTickTransform = (tick, globalTransform, isVertical) => { const getGridEdge = (props, calculatedValues) => { const { orientation, padding, isVertical } = calculatedValues; const sign = -orientationSign[orientation]; - const x = isVertical ? sign * (props.width - (padding.left + padding.right)) : 0; - const y = isVertical ? 0 : sign * (props.height - (padding.top + padding.bottom)); + const x = isVertical + ? sign * (props.width - (padding.left + padding.right)) + : 0; + const y = isVertical + ? 0 + : sign * (props.height - (padding.top + padding.bottom)); return { x, y }; }; @@ -365,7 +462,9 @@ const getOrientation = (props) => { dependent: props.horizontal ? "bottom" : "left", independent: props.horizontal ? "left" : "bottom" }; - return props.dependentAxis ? defaultOrientations.dependent : defaultOrientations.independent; + return props.dependentAxis + ? defaultOrientations.dependent + : defaultOrientations.independent; }; // eslint-disable-next-line complexity @@ -382,7 +481,8 @@ const getCalculatedValues = (props) => { const yAxisDomain = axis === "y" ? axisDomain : undefined; const xAxisScale = axis === "x" ? axisScale : undefined; const yAxisScale = axis === "y" ? axisScale : undefined; - const crossAxis = props.crossAxis === false || props.standalone === true ? false : true; + const crossAxis = + props.crossAxis === false || props.standalone === true ? false : true; const ticks = Axis.getTicks(props, axisScale, crossAxis); const tickFormat = Axis.getTickFormat(props, axisScale); const range = { @@ -465,14 +565,38 @@ const getBaseProps = (props, fallbackProps) => { name } = calculatedValues; const otherAxis = axis === "x" ? "y" : "x"; - const { width, height, standalone, theme, polar, padding, horizontal } = props; - const { globalTransform, gridOffset, gridEdge } = getLayoutProps(props, calculatedValues); - const sharedProps = { scale: { [axis]: scale[axis] }, polar, horizontal, ticks, stringTicks }; + const { width, height, standalone, theme, polar, padding, horizontal } = + props; + const { globalTransform, gridOffset, gridEdge } = getLayoutProps( + props, + calculatedValues + ); + const sharedProps = { + scale: { [axis]: scale[axis] }, + polar, + horizontal, + ticks, + stringTicks + }; const axisProps = getAxisProps(props, calculatedValues, globalTransform); - const axisLabelProps = getAxisLabelProps(props, calculatedValues, globalTransform); + const axisLabelProps = getAxisLabelProps( + props, + calculatedValues, + globalTransform + ); const initialChildProps = { parent: assign( - { style: style.parent, ticks, standalone, theme, width, height, padding, domain, name }, + { + style: style.parent, + ticks, + standalone, + theme, + width, + height, + padding, + domain, + name + }, sharedProps ) }; @@ -480,7 +604,9 @@ const getBaseProps = (props, fallbackProps) => { dimension: otherAxis, range: { [otherAxis]: Helpers.getRange(props, otherAxis) }, scale: - props.scale && props.scale[otherAxis] ? { [otherAxis]: props.scale[otherAxis] } : undefined + props.scale && props.scale[otherAxis] + ? { [otherAxis]: props.scale[otherAxis] } + : undefined }; return ticks.reduce((childProps, tickValue, index) => { const tick = stringTicks ? stringTicks[index] : tickValue; @@ -491,7 +617,11 @@ const getBaseProps = (props, fallbackProps) => { ); const tickLayout = { position: getTickPosition(styles, orientation, isVertical), - transform: getTickTransform(scale[axis](tickValue), globalTransform, isVertical) + transform: getTickTransform( + scale[axis](tickValue), + globalTransform, + isVertical + ) }; const gridLayout = { @@ -508,11 +638,21 @@ const getBaseProps = (props, fallbackProps) => { childProps[index] = { axis: assign({ dimension: axis }, sharedProps, axisProps), axisLabel: assign({}, sharedProps, axisLabelProps), - ticks: assign({}, sharedProps, getTickProps(tickLayout, styles.tickStyle, tickValue)), + ticks: assign( + {}, + sharedProps, + getTickProps(tickLayout, styles.tickStyle, tickValue) + ), tickLabels: assign( {}, sharedProps, - getTickLabelProps(tickLayout, styles.labelStyle, anchors, tickValue, text) + getTickLabelProps( + tickLayout, + styles.labelStyle, + anchors, + tickValue, + text + ) ), grid: assign( {}, diff --git a/packages/victory-axis/src/victory-axis.js b/packages/victory-axis/src/victory-axis.js index 2227f638f..7319ab64f 100644 --- a/packages/victory-axis/src/victory-axis.js +++ b/packages/victory-axis/src/victory-axis.js @@ -62,7 +62,11 @@ class VictoryAxis extends React.Component { ...CommonProps.baseProps, axisComponent: PropTypes.element, axisLabelComponent: PropTypes.element, - axisValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]), + axisValue: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.string, + PropTypes.object + ]), categories: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.shape({ @@ -74,10 +78,19 @@ class VictoryAxis extends React.Component { dependentAxis: PropTypes.bool, events: PropTypes.arrayOf( PropTypes.shape({ - target: PropTypes.oneOf(["axis", "axisLabel", "grid", "ticks", "tickLabels"]), + target: PropTypes.oneOf([ + "axis", + "axisLabel", + "grid", + "ticks", + "tickLabels" + ]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -106,7 +119,10 @@ class VictoryAxis extends React.Component { CustomPropTypes.integer, CustomPropTypes.greaterThanZero ]), - tickFormat: PropTypes.oneOfType([PropTypes.func, CustomPropTypes.homogeneousArray]), + tickFormat: PropTypes.oneOfType([ + PropTypes.func, + CustomPropTypes.homogeneousArray + ]), tickLabelComponent: PropTypes.element, tickValues: CustomPropTypes.homogeneousArray }; @@ -149,7 +165,11 @@ class VictoryAxis extends React.Component { if (!label) { return null; } - const axisLabelProps = this.getComponentProps(axisLabelComponent, "axisLabel", 0); + const axisLabelProps = this.getComponentProps( + axisLabelComponent, + "axisLabel", + 0 + ); return React.cloneElement(axisLabelComponent, axisLabelProps); } @@ -158,20 +178,32 @@ class VictoryAxis extends React.Component { const shouldRender = (componentProps) => { const { style = {}, events = {} } = componentProps; const visible = - style.stroke !== "transparent" && style.stroke !== "none" && style.strokeWidth !== 0; + style.stroke !== "transparent" && + style.stroke !== "none" && + style.strokeWidth !== 0; return visible || !isEmpty(events); }; return this.dataKeys.map((key, index) => { const tickProps = this.getComponentProps(tickComponent, "ticks", index); const BaseTickComponent = React.cloneElement(tickComponent, tickProps); - const TickComponent = shouldRender(BaseTickComponent.props) ? BaseTickComponent : undefined; + const TickComponent = shouldRender(BaseTickComponent.props) + ? BaseTickComponent + : undefined; const gridProps = this.getComponentProps(gridComponent, "grid", index); const BaseGridComponent = React.cloneElement(gridComponent, gridProps); - const GridComponent = shouldRender(BaseGridComponent.props) ? BaseGridComponent : undefined; - const tickLabelProps = this.getComponentProps(tickLabelComponent, "tickLabels", index); + const GridComponent = shouldRender(BaseGridComponent.props) + ? BaseGridComponent + : undefined; + const tickLabelProps = this.getComponentProps( + tickLabelComponent, + "tickLabels", + index + ); const TickLabel = React.cloneElement(tickLabelComponent, tickLabelProps); - const children = [GridComponent, TickComponent, TickLabel].filter(Boolean); + const children = [GridComponent, TickComponent, TickLabel].filter( + Boolean + ); return React.cloneElement( props.groupComponent, { key: `${name}-tick-group-${key}` }, @@ -208,12 +240,17 @@ class VictoryAxis extends React.Component { : labelSize.width + padding.right + padding.left) ); }, 0); - const availiableLabelCount = Math.floor((size * gridAndTicks.length) / labelsSumSize); + const availiableLabelCount = Math.floor( + (size * gridAndTicks.length) / labelsSumSize + ); const divider = Math.ceil(gridAndTicks.length / availiableLabelCount) || 1; const getLabelCoord = (gridAndTick) => gridAndTick.props.children .filter(isVictoryLabel) - .reduce((prev, child) => (isVertical ? child.props.y : child.props.x) || 0, 0); + .reduce( + (prev, child) => (isVertical ? child.props.y : child.props.x) || 0, + 0 + ); const sorted = gridAndTicks.sort( (a, b) => isVertical @@ -240,7 +277,11 @@ class VictoryAxis extends React.Component { const modifiedGridAndTicks = props.fixLabelOverlap ? this.fixLabelOverlap(gridAndTicks, props) : gridAndTicks; - const children = [this.renderLine(props), this.renderLabel(props), ...modifiedGridAndTicks]; + const children = [ + this.renderLine(props), + this.renderLabel(props), + ...modifiedGridAndTicks + ]; return props.standalone ? this.renderContainer(props.containerComponent, children) : React.cloneElement(props.groupComponent, {}, children); diff --git a/packages/victory-bar/src/bar.js b/packages/victory-bar/src/bar.js index 2f29bef89..8586d6cb5 100644 --- a/packages/victory-bar/src/bar.js +++ b/packages/victory-bar/src/bar.js @@ -36,17 +36,29 @@ const getBarWidth = (barWidth, props) => { const extent = Math.abs(range[1] - range[0]); const bars = data.length + 2; const barRatio = props.barRatio || 0.5; - const defaultWidth = barRatio * (data.length < 2 ? defaultBarWidth : extent / bars); + const defaultWidth = + barRatio * (data.length < 2 ? defaultBarWidth : extent / bars); return Math.max(1, defaultWidth); }; const getCornerRadiusFromObject = (cornerRadius, props) => { - const realCornerRadius = { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 }; + const realCornerRadius = { + topLeft: 0, + topRight: 0, + bottomLeft: 0, + bottomRight: 0 + }; const updateCornerRadius = (corner, fallback) => { if (!isNil(cornerRadius[corner])) { - realCornerRadius[corner] = Helpers.evaluateProp(cornerRadius[corner], props); + realCornerRadius[corner] = Helpers.evaluateProp( + cornerRadius[corner], + props + ); } else if (!isNil(cornerRadius[fallback])) { - realCornerRadius[corner] = Helpers.evaluateProp(cornerRadius[fallback], props); + realCornerRadius[corner] = Helpers.evaluateProp( + cornerRadius[fallback], + props + ); } }; updateCornerRadius("topLeft", "top"); @@ -57,7 +69,12 @@ const getCornerRadiusFromObject = (cornerRadius, props) => { }; const getCornerRadius = (cornerRadius, props) => { - const realCornerRadius = { topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0 }; + const realCornerRadius = { + topLeft: 0, + topRight: 0, + bottomLeft: 0, + bottomRight: 0 + }; if (!cornerRadius) { return realCornerRadius; } @@ -94,14 +111,25 @@ const evaluateProps = (props) => { */ const style = getStyle(props.style, props); const barWidth = getBarWidth(props.barWidth, assign({}, props, { style })); - const cornerRadius = getCornerRadius(props.cornerRadius, assign({}, props, { style, barWidth })); + const cornerRadius = getCornerRadius( + props.cornerRadius, + assign({}, props, { style, barWidth }) + ); const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const desc = Helpers.evaluateProp(props.desc, props); const id = Helpers.evaluateProp(props.id, props); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); - return assign({}, props, { ariaLabel, style, barWidth, cornerRadius, desc, id, tabIndex }); + return assign({}, props, { + ariaLabel, + style, + barWidth, + cornerRadius, + desc, + id, + tabIndex + }); }; const Bar = (props) => { @@ -111,7 +139,8 @@ const Bar = (props) => { const path = polar ? getPolarBarPath(props, cornerRadius) : getBarPath(props, barWidth, cornerRadius); - const defaultTransform = polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; + const defaultTransform = + polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; return React.cloneElement(props.pathComponent, { ...props.events, "aria-label": props.ariaLabel, diff --git a/packages/victory-bar/src/geometry-helper-methods.js b/packages/victory-bar/src/geometry-helper-methods.js index 262ef3eab..ec0501c84 100644 --- a/packages/victory-bar/src/geometry-helper-methods.js +++ b/packages/victory-bar/src/geometry-helper-methods.js @@ -96,11 +96,15 @@ const circle = function (center, radius) { return P3s; }, solveX(y) { - const sqrt = Math.sqrt(Math.pow(this.radius, 2) - Math.pow(y - this.center.y, 2)); + const sqrt = Math.sqrt( + Math.pow(this.radius, 2) - Math.pow(y - this.center.y, 2) + ); return [this.center.x - sqrt, this.center.x + sqrt]; }, solveY(x) { - const sqrt = Math.sqrt(Math.pow(this.radius, 2) - Math.pow(x - this.center.x, 2)); + const sqrt = Math.sqrt( + Math.pow(this.radius, 2) - Math.pow(x - this.center.x, 2) + ); return [this.center.y - sqrt, this.center.y + sqrt]; } }; diff --git a/packages/victory-bar/src/helper-methods.js b/packages/victory-bar/src/helper-methods.js index 634799970..2f0411c4d 100644 --- a/packages/victory-bar/src/helper-methods.js +++ b/packages/victory-bar/src/helper-methods.js @@ -1,10 +1,19 @@ import { assign, isNil } from "lodash"; -import { Helpers, LabelHelpers, Data, Domain, Scale, Collection } from "victory-core"; +import { + Helpers, + LabelHelpers, + Data, + Domain, + Scale, + Collection +} from "victory-core"; const getBarPosition = (props, datum) => { const getDefaultMin = (axis) => { const defaultZero = - Scale.getType(props.scale[axis]) === "log" ? 1 / Number.MAX_SAFE_INTEGER : 0; + Scale.getType(props.scale[axis]) === "log" + ? 1 / Number.MAX_SAFE_INTEGER + : 0; let defaultMin = defaultZero; const minY = Collection.getMinValue(props.domain[axis]); const maxY = Collection.getMaxValue(props.domain[axis]); @@ -15,7 +24,9 @@ const getBarPosition = (props, datum) => { defaultMin = minY; } - return datum[`_${axis}`] instanceof Date ? new Date(defaultMin) : defaultMin; + return datum[`_${axis}`] instanceof Date + ? new Date(defaultMin) + : defaultMin; }; const _y0 = datum._y0 !== undefined ? datum._y0 : getDefaultMin("y"); const _x0 = datum._x0 !== undefined ? datum._x0 : getDefaultMin("x"); @@ -25,7 +36,9 @@ const getBarPosition = (props, datum) => { const getCalculatedValues = (props) => { const { polar } = props; const defaultStyles = Helpers.getDefaultStyles(props, "bar"); - const style = !props.disableInlineStyles ? Helpers.getStyles(props.style, defaultStyles) : {}; + const style = !props.disableInlineStyles + ? Helpers.getStyles(props.style, defaultStyles) + : {}; const range = props.range || { x: Helpers.getRange(props, "x"), y: Helpers.getRange(props, "y") @@ -42,7 +55,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; let data = Data.getData(props); data = Data.formatDataFromDomain(data, domain, 0); @@ -127,7 +142,10 @@ const getBaseProps = (props, fallbackProps) => { }; const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { childProps[eventKey].labels = LabelHelpers.getProps(props, index); } diff --git a/packages/victory-bar/src/index.d.ts b/packages/victory-bar/src/index.d.ts index 0be29d39c..87e6fdd91 100644 --- a/packages/victory-bar/src/index.d.ts +++ b/packages/victory-bar/src/index.d.ts @@ -30,7 +30,10 @@ export interface VictoryBarProps bottomLeft?: NumberOrCallback; bottomRight?: NumberOrCallback; }; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryBarTTargetType, + number | string | number[] | string[] + >[]; eventKey?: StringOrNumberOrCallback; horizontal?: boolean; style?: VictoryStyleInterface; diff --git a/packages/victory-bar/src/path-helper-methods.js b/packages/victory-bar/src/path-helper-methods.js index 5c562e9f7..11dfd2389 100644 --- a/packages/victory-bar/src/path-helper-methods.js +++ b/packages/victory-bar/src/path-helper-methods.js @@ -53,7 +53,9 @@ const getStartAngle = (props, index) => { const currentAngle = getAngle(props, index); const angularRange = Math.abs(scale.x.range()[1] - scale.x.range()[0]); const previousAngle = - index === 0 ? getAngle(props, data.length - 1) - Math.PI * 2 : getAngle(props, index - 1); + index === 0 + ? getAngle(props, data.length - 1) - Math.PI * 2 + : getAngle(props, index - 1); if (index === 0 && angularRange < 2 * Math.PI) { return scale.x.range()[0]; } else if (alignment === "start" || alignment === "end") { @@ -68,9 +70,13 @@ const getEndAngle = (props, index) => { const currentAngle = getAngle(props, index); const angularRange = Math.abs(scale.x.range()[1] - scale.x.range()[0]); const lastAngle = - scale.x.range()[1] === 2 * Math.PI ? getAngle(props, 0) + Math.PI * 2 : scale.x.range()[1]; + scale.x.range()[1] === 2 * Math.PI + ? getAngle(props, 0) + Math.PI * 2 + : scale.x.range()[1]; const nextAngle = - index === data.length - 1 ? getAngle(props, 0) + Math.PI * 2 : getAngle(props, index + 1); + index === data.length - 1 + ? getAngle(props, 0) + Math.PI * 2 + : getAngle(props, index + 1); if (index === data.length - 1 && angularRange < 2 * Math.PI) { return lastAngle; } else if (alignment === "start" || alignment === "end") { @@ -120,9 +126,15 @@ const getVerticalBarPoints = (position, sign, cr) => { ? y0 - cr[`bottom${side}`] < y1 + cr[`top${side}`] : y0 + cr[`bottom${side}`] > y1 - cr[`top${side}`]; if (hasIntersection) { - const topCenter = point(x + signL * cr[`top${side}`], y1 + sign * cr[`top${side}`]); + const topCenter = point( + x + signL * cr[`top${side}`], + y1 + sign * cr[`top${side}`] + ); const topCircle = circle(topCenter, cr[`top${side}`]); - const bottomCenter = point(x + signL * cr[`bottom${side}`], y0 - sign * cr[`bottom${side}`]); + const bottomCenter = point( + x + signL * cr[`bottom${side}`], + y0 - sign * cr[`bottom${side}`] + ); const bottomCircle = circle(bottomCenter, cr[`bottom${side}`]); const circleIntersection = topCircle.intersection(bottomCircle); const hasArcIntersection = circleIntersection.length > 0; @@ -131,7 +143,8 @@ const getVerticalBarPoints = (position, sign, cr) => { bottomMiddlePoint = { x: arcIntersection.x, y: arcIntersection.y }; topMiddlePoint = { x: arcIntersection.x, y: arcIntersection.y }; } else { - const hasBottomLineTopArcIntersection = cr[`top${side}`] > cr[`bottom${side}`]; + const hasBottomLineTopArcIntersection = + cr[`top${side}`] > cr[`bottom${side}`]; if (hasBottomLineTopArcIntersection) { const newX = topCircle.solveX(y0)[isLeft ? 0 : 1]; bottomPoint = { x: newX, y: y0 }; @@ -168,9 +181,15 @@ const getHorizontalBarPoints = (position, sign, cr) => { let rightPoint = { x: x1, y: y - signL * cr[`${side}Right`] }; const hasIntersection = leftMiddlePoint.x > rightMiddlePoint.x; if (hasIntersection) { - const leftCenter = point(x0 + cr[`${side}Left`], y - signL * cr[`${side}Left`]); + const leftCenter = point( + x0 + cr[`${side}Left`], + y - signL * cr[`${side}Left`] + ); const leftCircle = circle(leftCenter, cr[`${side}Left`]); - const rightCenter = point(x1 - cr[`${side}Right`], y - signL * cr[`${side}Right`]); + const rightCenter = point( + x1 - cr[`${side}Right`], + y - signL * cr[`${side}Right`] + ); const rightCircle = circle(rightCenter, cr[`${side}Right`]); const circleIntersection = leftCircle.intersection(rightCircle); const hasArcIntersection = circleIntersection.length > 0; @@ -179,7 +198,8 @@ const getHorizontalBarPoints = (position, sign, cr) => { leftMiddlePoint = { x: arcIntersection.x, y: arcIntersection.y }; rightMiddlePoint = { x: arcIntersection.x, y: arcIntersection.y }; } else { - const hasLeftLineRightArcIntersection = cr[`${side}Right`] > cr[`${side}Left`]; + const hasLeftLineRightArcIntersection = + cr[`${side}Right`] > cr[`${side}Left`]; if (hasLeftLineRightArcIntersection) { const newY = rightCircle.solveY(x0)[isTop ? 0 : 1]; leftPoint = { x: x0, y: newY }; @@ -198,7 +218,13 @@ const getHorizontalBarPoints = (position, sign, cr) => { const topPoints = getHalfPoints("top"); const bottomPoints = getHalfPoints("bottom"); // eslint-disable-next-line no-magic-numbers - return [bottomPoints[1], bottomPoints[0], ...topPoints, bottomPoints[3], bottomPoints[2]]; + return [ + bottomPoints[1], + bottomPoints[0], + ...topPoints, + bottomPoints[3], + bottomPoints[2] + ]; }; // eslint-disable-next-line max-params @@ -264,15 +290,28 @@ export const getVerticalPolarBarPath = (props, cornerRadius) => { const leftMoves = leftPath.match(/[A-Z]/g); const leftCoords = leftPath.split(/[A-Z]/).slice(1); const leftMiddle = leftMoves.indexOf("L"); - return { rightMoves, rightCoords, rightMiddle, leftMoves, leftCoords, leftMiddle }; + return { + rightMoves, + rightCoords, + rightMiddle, + leftMoves, + leftCoords, + leftMiddle + }; }; // eslint-disable-next-line max-statements const getTopPath = () => { const { topRight, topLeft } = cornerRadius; const arcLength = r2 * Math.abs(end - start); - const { rightMoves, rightCoords, rightMiddle, leftMoves, leftCoords, leftMiddle } = - getPathData("top"); + const { + rightMoves, + rightCoords, + rightMiddle, + leftMoves, + leftCoords, + leftMiddle + } = getPathData("top"); let moves; let coords; if (topRight === topLeft || arcLength < 2 * topRight + 2 * topLeft) { @@ -284,31 +323,51 @@ export const getVerticalPolarBarPath = (props, cornerRadius) => { const rightOffset = topLeft > topRight && isShort(rightMiddle) ? 1 : 2; let leftOffset; if (topRight > topLeft) { - const defaultOffset = isShort(rightMiddle) ? leftMiddle : leftMiddle - 2; + const defaultOffset = isShort(rightMiddle) + ? leftMiddle + : leftMiddle - 2; leftOffset = isShort(leftMiddle) ? leftMiddle - 1 : defaultOffset; } else { const defaultOffset = isShort(leftMiddle) ? 1 : 2; leftOffset = isShort(rightMiddle) ? defaultOffset : leftMiddle - 2; } - moves = [...rightMoves.slice(0, rightOffset), ...leftMoves.slice(leftOffset)]; - coords = [...rightCoords.slice(0, rightOffset), ...leftCoords.slice(leftOffset)]; + moves = [ + ...rightMoves.slice(0, rightOffset), + ...leftMoves.slice(leftOffset) + ]; + coords = [ + ...rightCoords.slice(0, rightOffset), + ...leftCoords.slice(leftOffset) + ]; } const middle = moves.indexOf("L"); const subMoves = moves.slice(0, middle); const subCoords = coords.slice(0, middle); - return subMoves.map((m, i) => ({ command: m, coords: subCoords[i].split(",") })); + return subMoves.map((m, i) => ({ + command: m, + coords: subCoords[i].split(",") + })); }; // eslint-disable-next-line max-statements const getBottomPath = () => { const { bottomRight, bottomLeft } = cornerRadius; const arcLength = r1 * Math.abs(end - start); - const { rightMoves, rightCoords, rightMiddle, leftMoves, leftCoords, leftMiddle } = - getPathData("bottom"); + const { + rightMoves, + rightCoords, + rightMiddle, + leftMoves, + leftCoords, + leftMiddle + } = getPathData("bottom"); let moves; let coords; - if (bottomRight === bottomLeft || arcLength < 2 * bottomRight + 2 * bottomLeft) { + if ( + bottomRight === bottomLeft || + arcLength < 2 * bottomRight + 2 * bottomLeft + ) { moves = bottomRight > bottomLeft ? rightMoves : leftMoves; coords = bottomRight > bottomLeft ? rightCoords : leftCoords; } else { @@ -321,13 +380,22 @@ export const getVerticalPolarBarPath = (props, cornerRadius) => { // eslint-disable-next-line no-magic-numbers const rightOffset = shortPath ? -1 : -3; - moves = [...leftMoves.slice(0, leftMiddle + 2), ...rightMoves.slice(rightOffset)]; - coords = [...leftCoords.slice(0, leftMiddle + 2), ...rightCoords.slice(rightOffset)]; + moves = [ + ...leftMoves.slice(0, leftMiddle + 2), + ...rightMoves.slice(rightOffset) + ]; + coords = [ + ...leftCoords.slice(0, leftMiddle + 2), + ...rightCoords.slice(rightOffset) + ]; } const middle = moves.indexOf("L"); const subMoves = moves.slice(middle, -1); const subCoords = coords.slice(middle, -1); - return subMoves.map((m, i) => ({ command: m, coords: subCoords[i].split(",") })); + return subMoves.map((m, i) => ({ + command: m, + coords: subCoords[i].split(",") + })); }; const topPath = getTopPath(); diff --git a/packages/victory-bar/src/victory-bar.js b/packages/victory-bar/src/victory-bar.js index f72cd72ad..dd276513a 100644 --- a/packages/victory-bar/src/victory-bar.js +++ b/packages/victory-bar/src/victory-bar.js @@ -27,7 +27,14 @@ const defaultData = [ ]; class VictoryBar extends React.Component { - static animationWhitelist = ["data", "domain", "height", "padding", "style", "width"]; + static animationWhitelist = [ + "data", + "domain", + "height", + "padding", + "style", + "width" + ]; static displayName = "VictoryBar"; @@ -108,7 +115,9 @@ class VictoryBar extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-box-plot/src/helper-methods.js b/packages/victory-box-plot/src/helper-methods.js index 31a78648e..816363127 100644 --- a/packages/victory-box-plot/src/helper-methods.js +++ b/packages/victory-box-plot/src/helper-methods.js @@ -1,4 +1,13 @@ -import { orderBy, defaults, assign, uniq, groupBy, keys, isNaN, isNil } from "lodash"; +import { + orderBy, + defaults, + assign, + uniq, + groupBy, + keys, + isNaN, + isNil +} from "lodash"; import { Helpers, Scale, Domain, Data, Collection } from "victory-core"; import { min as d3Min, max as d3Max, quantile as d3Quantile } from "d3-array"; @@ -58,7 +67,9 @@ const processData = (data) => { /* generate summary statistics for each datum. to do this, flatten the depedentVarArray and process each datum separately */ return data.map((datum) => { - const dataArray = datum[sortKey].map((d) => assign({}, datum, { [sortKey]: d })); + const dataArray = datum[sortKey].map((d) => + assign({}, datum, { [sortKey]: d }) + ); const sortedData = orderBy(dataArray, sortKey); return getSummaryStatistics(sortedData); }); @@ -154,7 +165,11 @@ const getStyles = (props, styleObject) => { const style = props.style || {}; styleObject = styleObject || {}; const parentStyles = { height: "100%", width: "100%" }; - const labelStyles = defaults({}, style.labels, getLabelStyle(props, styleObject)); + const labelStyles = defaults( + {}, + style.labels, + getLabelStyle(props, styleObject) + ); const boxStyles = defaults({}, style.boxes, styleObject.boxes); const whiskerStyles = defaults({}, style.whiskers, styleObject.whiskers); return { @@ -162,7 +177,12 @@ const getStyles = (props, styleObject) => { labels: labelStyles, parent: defaults({}, style.parent, styleObject.parent, parentStyles), max: defaults({}, style.max, styleObject.max, whiskerStyles), - maxLabels: defaults({}, style.maxLabels, getLabelStyle(props, styleObject, "max"), labelStyles), + maxLabels: defaults( + {}, + style.maxLabels, + getLabelStyle(props, styleObject, "max"), + labelStyles + ), median: defaults({}, style.median, styleObject.median, whiskerStyles), medianLabels: defaults( {}, @@ -171,11 +191,26 @@ const getStyles = (props, styleObject) => { labelStyles ), min: defaults({}, style.min, styleObject.min, whiskerStyles), - minLabels: defaults({}, style.minLabels, getLabelStyle(props, styleObject, "min"), labelStyles), + minLabels: defaults( + {}, + style.minLabels, + getLabelStyle(props, styleObject, "min"), + labelStyles + ), q1: defaults({}, style.q1, styleObject.q1, boxStyles), - q1Labels: defaults({}, style.q1Labels, getLabelStyle(props, styleObject, "q1"), labelStyles), + q1Labels: defaults( + {}, + style.q1Labels, + getLabelStyle(props, styleObject, "q1"), + labelStyles + ), q3: defaults({}, style.q3, styleObject.q3, boxStyles), - q3Labels: defaults({}, style.q3Labels, getLabelStyle(props, styleObject, "q3"), labelStyles), + q3Labels: defaults( + {}, + style.q3Labels, + getLabelStyle(props, styleObject, "q3"), + labelStyles + ), whiskers: whiskerStyles }; }; @@ -199,7 +234,8 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const defaultStyles = theme && theme.boxplot && theme.boxplot.style ? theme.boxplot.style : {}; + const defaultStyles = + theme && theme.boxplot && theme.boxplot.style ? theme.boxplot.style : {}; const style = getStyles(props, defaultStyles); const defaultOrientation = props.horizontal ? "top" : "right"; const labelOrientation = props.labelOrientation || defaultOrientation; @@ -209,8 +245,16 @@ const getCalculatedValues = (props) => { // eslint-disable-next-line complexity const getWhiskerProps = (props, type) => { - const { horizontal, style, boxWidth, whiskerWidth, datum, scale, index, disableInlineStyles } = - props; + const { + horizontal, + style, + boxWidth, + whiskerWidth, + datum, + scale, + index, + disableInlineStyles + } = props; const { min, max, q1, q3, x, y } = props.positions; const boxValue = type === "min" ? q1 : q3; const whiskerValue = type === "min" ? min : max; @@ -237,7 +281,15 @@ const getWhiskerProps = (props, type) => { }; const getBoxProps = (props, type) => { - const { horizontal, boxWidth, style, scale, datum, index, disableInlineStyles } = props; + const { + horizontal, + boxWidth, + style, + scale, + datum, + index, + disableInlineStyles + } = props; const { median, q1, q3, x, y } = props.positions; const defaultX = type === "q1" ? q1 : median; const defaultY = type === "q1" ? median : q3; @@ -257,7 +309,15 @@ const getBoxProps = (props, type) => { }; const getMedianProps = (props) => { - const { boxWidth, horizontal, style, datum, scale, index, disableInlineStyles } = props; + const { + boxWidth, + horizontal, + style, + datum, + scale, + index, + disableInlineStyles + } = props; const { median, x, y } = props.positions; return { datum, @@ -286,7 +346,8 @@ const getText = (props, type) => { }; const getOrientation = (labelOrientation, type) => - (typeof labelOrientation === "object" && labelOrientation[type]) || labelOrientation; + (typeof labelOrientation === "object" && labelOrientation[type]) || + labelOrientation; const getLabelProps = (props, text, type) => { const { @@ -303,9 +364,20 @@ const getLabelProps = (props, text, type) => { const orientation = getOrientation(labelOrientation, type); const namespace = `${type}Labels`; const labelStyle = style[namespace] || style.labels; - const defaultVerticalAnchors = { top: "end", bottom: "start", left: "middle", right: "middle" }; - const defaultTextAnchors = { left: "end", right: "start", top: "middle", bottom: "middle" }; - const whiskerWidth = typeof props.whiskerWidth === "number" ? props.whiskerWidth : boxWidth; + const defaultVerticalAnchors = { + top: "end", + bottom: "start", + left: "middle", + right: "middle" + }; + const defaultTextAnchors = { + left: "end", + right: "start", + top: "middle", + bottom: "middle" + }; + const whiskerWidth = + typeof props.whiskerWidth === "number" ? props.whiskerWidth : boxWidth; const width = type === "min" || type === "max" ? whiskerWidth : boxWidth; const getOffset = (coord) => { @@ -327,7 +399,8 @@ const getLabelProps = (props, text, type) => { dy: horizontal ? getOffset("y") : 0, dx: horizontal ? 0 : getOffset("x"), textAnchor: labelStyle.textAnchor || defaultTextAnchors[orientation], - verticalAnchor: labelStyle.verticalAnchor || defaultVerticalAnchors[orientation], + verticalAnchor: + labelStyle.verticalAnchor || defaultVerticalAnchors[orientation], angle: labelStyle.angle, horizontal, disableInlineStyles @@ -371,7 +444,10 @@ const isDatumOutOfBounds = (datum, domain) => { // if x is out of the bounds of the domain if (isUnderMinX(_x) || isOverMaxX(_x)) xOutOfBounds = true; // if min/max are out of the bounds of the domain - if ((isUnderMinY(_min) && isUnderMinY(_max)) || (isOverMaxY(_min) && isOverMaxY(_max))) + if ( + (isUnderMinY(_min) && isUnderMinY(_max)) || + (isOverMaxY(_min) && isOverMaxY(_max)) + ) yOutOfBounds = true; return yOutOfBounds || xOutOfBounds; @@ -443,7 +519,11 @@ const getBaseProps = (props, fallbackProps) => { (labelProp && (events || sharedEvents)) ) { const target = `${type}Labels`; - acc[eventKey][target] = getLabelProps(assign({}, props, dataProps), labelText, type); + acc[eventKey][target] = getLabelProps( + assign({}, props, dataProps), + labelText, + type + ); } }); diff --git a/packages/victory-box-plot/src/index.d.ts b/packages/victory-box-plot/src/index.d.ts index 396eb9302..1e8813dc3 100644 --- a/packages/victory-box-plot/src/index.d.ts +++ b/packages/victory-box-plot/src/index.d.ts @@ -39,7 +39,9 @@ export interface VictoryBoxPlotLabelOrientationInterface { q3?: OrientationTypes; } -export interface VictoryBoxPlotProps extends VictoryCommonProps, VictoryDatableProps { +export interface VictoryBoxPlotProps + extends VictoryCommonProps, + VictoryDatableProps { boxWidth?: number; domain?: DomainPropType; domainPadding?: DomainPaddingPropType; diff --git a/packages/victory-box-plot/src/victory-box-plot.js b/packages/victory-box-plot/src/victory-box-plot.js index 30667bb4f..7b4e37216 100644 --- a/packages/victory-box-plot/src/victory-box-plot.js +++ b/packages/victory-box-plot/src/victory-box-plot.js @@ -49,7 +49,14 @@ const options = { }; class VictoryBoxPlot extends React.Component { - static animationWhitelist = ["data", "domain", "height", "padding", "style", "width"]; + static animationWhitelist = [ + "data", + "domain", + "height", + "padding", + "style", + "width" + ]; static displayName = "VictoryBoxPlot"; static role = "boxplot"; @@ -75,7 +82,10 @@ class VictoryBoxPlot extends React.Component { ]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -95,49 +105,84 @@ class VictoryBoxPlot extends React.Component { labels: PropTypes.bool, max: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), maxComponent: PropTypes.element, maxLabelComponent: PropTypes.element, - maxLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + maxLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), median: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), medianComponent: PropTypes.element, medianLabelComponent: PropTypes.element, - medianLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + medianLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), min: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), minComponent: PropTypes.element, minLabelComponent: PropTypes.element, - minLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + minLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), q1: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), q1Component: PropTypes.element, q1LabelComponent: PropTypes.element, - q1Labels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + q1Labels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), q3: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), q3Component: PropTypes.element, q3LabelComponent: PropTypes.element, - q3Labels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + q3Labels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), style: PropTypes.shape({ boxes: PropTypes.object, labels: PropTypes.object, @@ -203,9 +248,15 @@ class VictoryBoxPlot extends React.Component { types.map((type) => { return this.dataKeys.reduce((validDataComponents, _key, index) => { const baseComponent = props[`${type}Component`]; - const componentProps = this.getComponentProps(baseComponent, type, index); + const componentProps = this.getComponentProps( + baseComponent, + type, + index + ); if (this.shouldRenderDatum(componentProps.datum)) { - validDataComponents.push(React.cloneElement(baseComponent, componentProps)); + validDataComponents.push( + React.cloneElement(baseComponent, componentProps) + ); } return validDataComponents; }, []); @@ -257,7 +308,9 @@ class VictoryBoxPlot extends React.Component { } const children = this.renderBoxPlot(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-brush-container/src/brush-helpers.js b/packages/victory-brush-container/src/brush-helpers.js index 7f75c1f7b..2944b49d9 100644 --- a/packages/victory-brush-container/src/brush-helpers.js +++ b/packages/victory-brush-container/src/brush-helpers.js @@ -28,13 +28,28 @@ const Helpers = { fullDomain = defaults({}, fullDomain, props.domain); selectedDomain = defaults({}, selectedDomain, fullDomain); const fullCoords = Selection.getDomainCoordinates(props, fullDomain); - const selectedCoords = Selection.getDomainCoordinates(props, selectedDomain); + const selectedCoords = Selection.getDomainCoordinates( + props, + selectedDomain + ); return { - x1: brushDimension !== "y" ? Math.min(...selectedCoords.x) : Math.min(...fullCoords.x), - x2: brushDimension !== "y" ? Math.max(...selectedCoords.x) : Math.max(...fullCoords.x), - y1: brushDimension !== "x" ? Math.min(...selectedCoords.y) : Math.min(...fullCoords.y), - y2: brushDimension !== "x" ? Math.max(...selectedCoords.y) : Math.max(...fullCoords.y) + x1: + brushDimension !== "y" + ? Math.min(...selectedCoords.x) + : Math.min(...fullCoords.x), + x2: + brushDimension !== "y" + ? Math.max(...selectedCoords.x) + : Math.max(...fullCoords.x), + y1: + brushDimension !== "x" + ? Math.min(...selectedCoords.y) + : Math.min(...fullCoords.y), + y2: + brushDimension !== "x" + ? Math.max(...selectedCoords.y) + : Math.max(...fullCoords.y) }; }, @@ -47,19 +62,45 @@ const Helpers = { const maxY = Math.max(y1, y2); const handleWidth = props.handleWidth / 2; return { - left: brushDimension !== "y" && { x1: minX - handleWidth, x2: minX + handleWidth, y1, y2 }, - right: brushDimension !== "y" && { x1: maxX - handleWidth, x2: maxX + handleWidth, y1, y2 }, - top: brushDimension !== "x" && { x1, x2, y1: minY - handleWidth, y2: minY + handleWidth }, - bottom: brushDimension !== "x" && { x1, x2, y1: maxY - handleWidth, y2: maxY + handleWidth } + left: brushDimension !== "y" && { + x1: minX - handleWidth, + x2: minX + handleWidth, + y1, + y2 + }, + right: brushDimension !== "y" && { + x1: maxX - handleWidth, + x2: maxX + handleWidth, + y1, + y2 + }, + top: brushDimension !== "x" && { + x1, + x2, + y1: minY - handleWidth, + y2: minY + handleWidth + }, + bottom: brushDimension !== "x" && { + x1, + x2, + y1: maxY - handleWidth, + y2: maxY + handleWidth + } }; }, getActiveHandles(point, props, domainBox) { const handles = this.getHandles(props, domainBox); - const activeHandles = ["top", "bottom", "left", "right"].reduce((memo, opt) => { - memo = handles[opt] && this.withinBounds(point, handles[opt]) ? memo.concat(opt) : memo; - return memo; - }, []); + const activeHandles = ["top", "bottom", "left", "right"].reduce( + (memo, opt) => { + memo = + handles[opt] && this.withinBounds(point, handles[opt]) + ? memo.concat(opt) + : memo; + return memo; + }, + [] + ); return activeHandles.length && activeHandles; }, @@ -86,7 +127,9 @@ const Helpers = { getDefaultBrushArea(targetProps, cachedDomain, evt) { const { domain, fullDomain, scale, horizontal, allowResize } = targetProps; const defaultBrushArea = - !allowResize && !targetProps.defaultBrushArea ? "move" : targetProps.defaultBrushArea; + !allowResize && !targetProps.defaultBrushArea + ? "move" + : targetProps.defaultBrushArea; if (defaultBrushArea === "none") { return this.getMinimumDomain(); } else if (defaultBrushArea === "disable") { @@ -104,7 +147,8 @@ const Helpers = { }, Selection.getSVGEventCoordinates(evt, parentSVG) ); - const fullDomainBox = targetProps.fullDomainBox || this.getDomainBox(targetProps, fullDomain); + const fullDomainBox = + targetProps.fullDomainBox || this.getDomainBox(targetProps, fullDomain); const constrainedBox = this.constrainBox(pannedBox, fullDomainBox); return Selection.getBounds({ ...constrainedBox, scale, horizontal }); } else { @@ -128,7 +172,9 @@ const Helpers = { const brushDimension = this.getDimension(props); const brushDomain = defaults({}, props.brushDomain, domain); const fullDomain = defaults({}, props.fullDomain, domain); - const { x1, x2, y1, y2 } = props.x1 ? props : this.getDomainBox(props, fullDomain, brushDomain); + const { x1, x2, y1, y2 } = props.x1 + ? props + : this.getDomainBox(props, fullDomain, brushDomain); const { x, y } = point; const delta = { @@ -136,9 +182,12 @@ const Helpers = { y: startY ? startY - y : 0 }; return { - x1: brushDimension !== "y" ? Math.min(x1, x2) - delta.x : Math.min(x1, x2), - x2: brushDimension !== "y" ? Math.max(x1, x2) - delta.x : Math.max(x1, x2), - y1: brushDimension !== "x" ? Math.min(y1, y2) - delta.y : Math.min(y1, y2), + x1: + brushDimension !== "y" ? Math.min(x1, x2) - delta.x : Math.min(x1, x2), + x2: + brushDimension !== "y" ? Math.max(x1, x2) - delta.x : Math.max(x1, x2), + y1: + brushDimension !== "x" ? Math.min(y1, y2) - delta.y : Math.min(y1, y2), y2: brushDimension !== "x" ? Math.max(y1, y2) - delta.y : Math.max(y1, y2) }; }, @@ -179,17 +228,26 @@ const Helpers = { // eslint-disable-next-line max-statements, complexity onMouseDown(evt, targetProps) { evt.preventDefault(); - const { handleWidth, cachedBrushDomain, domain, allowResize, allowDrag, allowDraw } = - targetProps; + const { + handleWidth, + cachedBrushDomain, + domain, + allowResize, + allowDrag, + allowDraw + } = targetProps; const brushDimension = this.getDimension(targetProps); const defaultBrushArea = - !allowResize && !targetProps.defaultBrushArea ? "move" : targetProps.defaultBrushArea; + !allowResize && !targetProps.defaultBrushArea + ? "move" + : targetProps.defaultBrushArea; // Don't trigger events for static brushes if (!allowResize && !allowDrag) { return {}; } - const fullDomainBox = targetProps.fullDomainBox || this.getDomainBox(targetProps, domain); + const fullDomainBox = + targetProps.fullDomainBox || this.getDomainBox(targetProps, domain); const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); const { x, y } = Selection.getSVGEventCoordinates(evt, parentSVG); // Ignore events that occur outside of the maximum domain region @@ -205,7 +263,8 @@ const Helpers = { const domainBox = this.getDomainBox(targetProps, domain, currentDomain); - const activeHandles = allowResize && this.getActiveHandles({ x, y }, targetProps, domainBox); + const activeHandles = + allowResize && this.getActiveHandles({ x, y }, targetProps, domainBox); // If the event occurs in any of the handle regions, start a resize if (activeHandles) { return [ @@ -224,7 +283,10 @@ const Helpers = { } } ]; - } else if (this.withinBounds({ x, y }, domainBox) && !isEqual(domain, currentDomain)) { + } else if ( + this.withinBounds({ x, y }, domainBox) && + !isEqual(domain, currentDomain) + ) { // if the event occurs within a selected region start a panning event, unless the whole // domain is selected return [ @@ -258,7 +320,11 @@ const Helpers = { cachedBrushDomain: brushDomain, cachedCurrentDomain: currentDomain, currentDomain: this.getMinimumDomain(), - ...this.getSelectionMutation({ x, y }, domainBox, brushDimension) + ...this.getSelectionMutation( + { x, y }, + domainBox, + brushDimension + ) }) } ] @@ -284,7 +350,8 @@ const Helpers = { const { x, y } = Selection.getSVGEventCoordinates(evt, parentSVG); if ( (!allowResize && !allowDrag) || - (mouseMoveThreshold > 0 && !this.hasMoved({ ...targetProps, x2: x, y2: y })) + (mouseMoveThreshold > 0 && + !this.hasMoved({ ...targetProps, x2: x, y2: y })) ) { return {}; } @@ -292,17 +359,30 @@ const Helpers = { const { startX, startY } = targetProps; const pannedBox = this.panBox(targetProps, { x, y }); const constrainedBox = this.constrainBox(pannedBox, fullDomainBox); - const currentDomain = Selection.getBounds({ ...constrainedBox, scale, horizontal }); + const currentDomain = Selection.getBounds({ + ...constrainedBox, + scale, + horizontal + }); const mutatedProps = { currentDomain, parentSVG, - startX: pannedBox.x2 >= fullDomainBox.x2 || pannedBox.x1 <= fullDomainBox.x1 ? startX : x, - startY: pannedBox.y2 >= fullDomainBox.y2 || pannedBox.y1 <= fullDomainBox.y1 ? startY : y, + startX: + pannedBox.x2 >= fullDomainBox.x2 || pannedBox.x1 <= fullDomainBox.x1 + ? startX + : x, + startY: + pannedBox.y2 >= fullDomainBox.y2 || pannedBox.y1 <= fullDomainBox.y1 + ? startY + : y, ...constrainedBox }; if (isFunction(onBrushDomainChange)) { - onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -329,7 +409,10 @@ const Helpers = { const mutatedProps = { x2, y2, currentDomain, parentSVG }; if (isFunction(onBrushDomainChange)) { - onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -363,27 +446,43 @@ const Helpers = { allowDrag } = targetProps; const defaultBrushArea = - !allowResize && !targetProps.defaultBrushArea ? "move" : targetProps.defaultBrushArea; - const defaultBrushHasArea = defaultBrushArea !== undefined && defaultBrushArea !== "none"; + !allowResize && !targetProps.defaultBrushArea + ? "move" + : targetProps.defaultBrushArea; + const defaultBrushHasArea = + defaultBrushArea !== undefined && defaultBrushArea !== "none"; const mutatedProps = { isPanning: false, isSelecting: false }; // if the mouse hasn't moved since a mouseDown event, select the default brush area if ((allowResize || defaultBrushHasArea) && (x1 === x2 || y1 === y2)) { const cachedDomain = targetProps.cachedCurrentDomain || currentDomain; - const defaultDomain = this.getDefaultBrushArea(targetProps, cachedDomain, evt); + const defaultDomain = this.getDefaultBrushArea( + targetProps, + cachedDomain, + evt + ); mutatedProps.currentDomain = defaultDomain; if (isFunction(onBrushDomainChange)) { - onBrushDomainChange(defaultDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + defaultDomain, + defaults({}, mutatedProps, targetProps) + ); } if (isFunction(onBrushDomainChangeEnd)) { - onBrushDomainChangeEnd(defaultDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChangeEnd( + defaultDomain, + defaults({}, mutatedProps, targetProps) + ); } if (isFunction(onBrushCleared)) { onBrushCleared(defaultDomain, defaults({}, mutatedProps, targetProps)); } } else if ((allowDrag && isPanning) || (allowResize && isSelecting)) { if (isFunction(onBrushDomainChangeEnd)) { - onBrushDomainChangeEnd(currentDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChangeEnd( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } } diff --git a/packages/victory-brush-container/src/index.d.ts b/packages/victory-brush-container/src/index.d.ts index 39fd0b791..7a6cdbcc5 100644 --- a/packages/victory-brush-container/src/index.d.ts +++ b/packages/victory-brush-container/src/index.d.ts @@ -27,4 +27,7 @@ export interface VictoryBrushContainerProps extends VictoryContainerProps { ) => void; } -export class VictoryBrushContainer extends React.Component {} +export class VictoryBrushContainer extends React.Component< + VictoryBrushContainerProps, + any +> {} diff --git a/packages/victory-brush-container/src/index.js b/packages/victory-brush-container/src/index.js index bf9dde532..3228046ad 100644 --- a/packages/victory-brush-container/src/index.js +++ b/packages/victory-brush-container/src/index.js @@ -1,2 +1,5 @@ -export { brushContainerMixin, default as VictoryBrushContainer } from "./victory-brush-container"; +export { + brushContainerMixin, + default as VictoryBrushContainer +} from "./victory-brush-container"; export { default as BrushHelpers } from "./brush-helpers"; diff --git a/packages/victory-brush-container/src/victory-brush-container.js b/packages/victory-brush-container/src/victory-brush-container.js index c894b359e..65985c07c 100644 --- a/packages/victory-brush-container/src/victory-brush-container.js +++ b/packages/victory-brush-container/src/victory-brush-container.js @@ -55,29 +55,41 @@ export const brushContainerMixin = (base) => target: "parent", eventHandlers: { onMouseDown: (evt, targetProps) => { - return props.disable ? {} : BrushHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : BrushHelpers.onMouseDown(evt, targetProps); }, onTouchStart: (evt, targetProps) => { - return props.disable ? {} : BrushHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : BrushHelpers.onMouseDown(evt, targetProps); }, onGlobalMouseMove: (evt, targetProps) => { - return props.disable || (!targetProps.isPanning && !targetProps.isSelecting) + return props.disable || + (!targetProps.isPanning && !targetProps.isSelecting) ? {} : BrushHelpers.onGlobalMouseMove(evt, targetProps); }, onGlobalTouchMove: (evt, targetProps) => { - return props.disable || (!targetProps.isPanning && !targetProps.isSelecting) + return props.disable || + (!targetProps.isPanning && !targetProps.isSelecting) ? {} : BrushHelpers.onGlobalMouseMove(evt, targetProps); }, onGlobalMouseUp: (evt, targetProps) => { - return props.disable ? {} : BrushHelpers.onGlobalMouseUp(evt, targetProps); + return props.disable + ? {} + : BrushHelpers.onGlobalMouseUp(evt, targetProps); }, onGlobalTouchEnd: (evt, targetProps) => { - return props.disable ? {} : BrushHelpers.onGlobalMouseUp(evt, targetProps); + return props.disable + ? {} + : BrushHelpers.onGlobalMouseUp(evt, targetProps); }, onGlobalTouchCancel: (evt, targetProps) => { - return props.disable ? {} : BrushHelpers.onGlobalMouseUp(evt, targetProps); + return props.disable + ? {} + : BrushHelpers.onGlobalMouseUp(evt, targetProps); } } } @@ -87,7 +99,8 @@ export const brushContainerMixin = (base) => getSelectBox(props, coordinates) { const { x, y } = coordinates; const { brushStyle, brushComponent, name } = props; - const brushComponentStyle = brushComponent.props && brushComponent.props.style; + const brushComponentStyle = + brushComponent.props && brushComponent.props.style; const cursor = !props.allowDrag && !props.allowResize ? "auto" : "move"; return x[0] !== x[1] && y[0] !== y[1] ? React.cloneElement(brushComponent, { @@ -121,15 +134,29 @@ export const brushContainerMixin = (base) => const { handleWidth, handleStyle, handleComponent, name } = props; const domainBox = BrushHelpers.getDomainBox(props, domain); const { x1, x2, y1, y2 } = domainBox; - const { top, bottom, left, right } = BrushHelpers.getHandles(props, domainBox); + const { top, bottom, left, right } = BrushHelpers.getHandles( + props, + domainBox + ); const width = Math.abs(x2 - x1) || 1; const height = Math.abs(y2 - y1) || 1; - const handleComponentStyle = (handleComponent.props && handleComponent.props.style) || {}; + const handleComponentStyle = + (handleComponent.props && handleComponent.props.style) || {}; const style = defaults({}, handleComponentStyle, handleStyle); const cursors = this.getCursorPointers(props); - const yProps = { style, width, height: handleWidth, cursor: cursors.yProps }; - const xProps = { style, width: handleWidth, height, cursor: cursors.xProps }; + const yProps = { + style, + width, + height: handleWidth, + cursor: cursors.yProps + }; + const xProps = { + style, + width: handleWidth, + height, + cursor: cursors.xProps + }; const handleProps = { top: top && assign({ x: top.x1, y: top.y1 }, yProps), @@ -137,17 +164,20 @@ export const brushContainerMixin = (base) => left: left && assign({ y: left.y1, x: left.x1 }, xProps), right: right && assign({ y: right.y1, x: right.x1 }, xProps) }; - const handles = ["top", "bottom", "left", "right"].reduce((memo, curr) => { - memo = handleProps[curr] - ? memo.concat( - React.cloneElement( - handleComponent, - assign({ key: `${name}-handle-${curr}` }, handleProps[curr]) + const handles = ["top", "bottom", "left", "right"].reduce( + (memo, curr) => { + memo = handleProps[curr] + ? memo.concat( + React.cloneElement( + handleComponent, + assign({ key: `${name}-handle-${curr}` }, handleProps[curr]) + ) ) - ) - : memo; - return memo; - }, []); + : memo; + return memo; + }, + [] + ); return handles.length ? handles : null; } @@ -164,7 +194,10 @@ export const brushContainerMixin = (base) => // Overrides method in VictoryContainer getChildren(props) { - return [...React.Children.toArray(props.children), ...this.getRect(props)]; + return [ + ...React.Children.toArray(props.children), + ...this.getRect(props) + ]; } }; diff --git a/packages/victory-brush-line/src/index.d.ts b/packages/victory-brush-line/src/index.d.ts index aabc9cdeb..28fd6f35e 100644 --- a/packages/victory-brush-line/src/index.d.ts +++ b/packages/victory-brush-line/src/index.d.ts @@ -22,10 +22,16 @@ export interface VictoryBrushLineProps { id?: string | number; lineComponent?: React.ReactElement; name?: string; - onBrushDomainChange?: (domain: DomainTuple, props?: VictoryBrushLineProps) => void; + onBrushDomainChange?: ( + domain: DomainTuple, + props?: VictoryBrushLineProps + ) => void; style?: VictoryStyleObject; type?: string; width?: number; } -export class VictoryBrushLine extends React.Component {} +export class VictoryBrushLine extends React.Component< + VictoryBrushLineProps, + any +> {} diff --git a/packages/victory-brush-line/src/victory-brush-line.js b/packages/victory-brush-line/src/victory-brush-line.js index 7e1147c55..f1da08093 100644 --- a/packages/victory-brush-line/src/victory-brush-line.js +++ b/packages/victory-brush-line/src/victory-brush-line.js @@ -1,6 +1,14 @@ import React from "react"; import PropTypes from "prop-types"; -import { Selection, Helpers, Collection, LineSegment, Scale, Domain, Box } from "victory-core"; +import { + Selection, + Helpers, + Collection, + LineSegment, + Scale, + Domain, + Box +} from "victory-core"; import { assign, defaults, isFunction, pick } from "lodash"; import isEqual from "react-fast-compare"; @@ -47,7 +55,10 @@ const getFullDomain = (props) => { }; const withinBound = (value, bound) => { - return value >= Collection.getMinValue(bound) && value <= Collection.getMaxValue(bound); + return ( + value >= Collection.getMinValue(bound) && + value <= Collection.getMaxValue(bound) + ); }; const getBrushDomain = (brushDomain, fullDomain) => { @@ -56,8 +67,10 @@ const getBrushDomain = (brushDomain, fullDomain) => { const brushMax = Collection.getMaxValue(brushDomain); const domainMin = Collection.getMinValue(fullDomain); const domainMax = Collection.getMaxValue(fullDomain); - const defaultMin = brushMin < domainMin ? domainMin : domainMax - SMALL_NUMBER; - const defaultMax = brushMax > domainMax ? domainMax : domainMin + SMALL_NUMBER; + const defaultMin = + brushMin < domainMin ? domainMin : domainMax - SMALL_NUMBER; + const defaultMax = + brushMax > domainMax ? domainMax : domainMin + SMALL_NUMBER; const min = withinBound(brushMin, fullDomain) ? brushMin : defaultMin; const max = withinBound(brushMax, fullDomain) ? brushMax : defaultMax; return [min, max]; @@ -96,8 +109,10 @@ const panBox = (props, position) => { const delta = startPosition ? startPosition - position : 0; const min = Math.min(...range) - delta; const max = Math.max(...range) - delta; - const constrainedMin = min > globalMax - size ? globalMax - size : Math.max(min, globalMin); - const constrainedMax = max < globalMin + size ? globalMin + size : Math.min(max, globalMax); + const constrainedMin = + min > globalMax - size ? globalMax - size : Math.max(min, globalMin); + const constrainedMax = + max < globalMin + size ? globalMin + size : Math.min(max, globalMax); return [constrainedMin, constrainedMax]; }; @@ -175,15 +190,22 @@ export default class VictoryBrushLine extends React.Component { evt.preventDefault(); const { allowResize, brushDomain } = targetProps; const dimension = getDimension(targetProps); - const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); - const position = Selection.getSVGEventCoordinates(evt, parentSVG)[dimension]; + const parentSVG = + targetProps.parentSVG || Selection.getParentSVG(evt); + const position = Selection.getSVGEventCoordinates( + evt, + parentSVG + )[dimension]; const fullDomain = getFullDomain(targetProps); const currentDomain = getBrushDomain(brushDomain, fullDomain); const range = toRange(targetProps, currentDomain); - const activeHandle = allowResize && getActiveHandle(targetProps, position, range); + const activeHandle = + allowResize && getActiveHandle(targetProps, position, range); const activeBrushes = { brushArea: !targetProps.brushDomain, - brush: withinBound(position, range) && !isEqual(fullDomain, currentDomain), + brush: + withinBound(position, range) && + !isEqual(fullDomain, currentDomain), minHandle: activeHandle === "min" || activeHandle === "both", maxHandle: activeHandle === "min" || activeHandle === "both" }; @@ -199,8 +221,13 @@ export default class VictoryBrushLine extends React.Component { }, onMouseDown: (evt, targetProps) => { evt.preventDefault(); - const { allowResize, allowDrag, allowDraw, activeBrushes, brushDomain } = - targetProps; + const { + allowResize, + allowDrag, + allowDraw, + activeBrushes, + brushDomain + } = targetProps; const dimension = getDimension(targetProps); // Don't trigger events for static brushes @@ -210,10 +237,15 @@ export default class VictoryBrushLine extends React.Component { const fullDomain = getFullDomain(targetProps); const currentDomain = getBrushDomain(brushDomain, fullDomain); - const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); - const position = Selection.getSVGEventCoordinates(evt, parentSVG)[dimension]; + const parentSVG = + targetProps.parentSVG || Selection.getParentSVG(evt); + const position = Selection.getSVGEventCoordinates( + evt, + parentSVG + )[dimension]; const range = toRange(targetProps, currentDomain); - const activeHandle = allowResize && getActiveHandle(targetProps, position, range); + const activeHandle = + allowResize && getActiveHandle(targetProps, position, range); // If the event occurs in any of the handle regions, start a resize if (activeHandle) { return [ @@ -230,7 +262,10 @@ export default class VictoryBrushLine extends React.Component { } } ]; - } else if (withinBound(position, range) && !isEqual(fullDomain, currentDomain)) { + } else if ( + withinBound(position, range) && + !isEqual(fullDomain, currentDomain) + ) { // if the event occurs within a selected region start a panning event, unless the whole // domain is selected return [ @@ -278,15 +313,25 @@ export default class VictoryBrushLine extends React.Component { evt.preventDefault(); evt.stopPropagation(); } - const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); - const position = Selection.getSVGEventCoordinates(evt, parentSVG)[dimension]; + const parentSVG = + targetProps.parentSVG || Selection.getParentSVG(evt); + const position = Selection.getSVGEventCoordinates( + evt, + parentSVG + )[dimension]; const fullDomain = getFullDomain(targetProps); const domain = getBrushDomain(brushDomain, fullDomain); const initialRange = toRange(targetProps, domain); - const activeHandle = getActiveHandle(targetProps, position, initialRange); + const activeHandle = getActiveHandle( + targetProps, + position, + initialRange + ); const activeBrushes = { brushArea: !targetProps.brushDomain, - brush: withinBound(position, initialRange) && !isEqual(fullDomain, domain), + brush: + withinBound(position, initialRange) && + !isEqual(fullDomain, domain), minHandle: activeHandle === "min" || activeHandle === "both", maxHandle: activeHandle === "max" || activeHandle === "both" }; @@ -319,7 +364,10 @@ export default class VictoryBrushLine extends React.Component { }; if (isFunction(onBrushDomainChange)) { - onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -329,17 +377,27 @@ export default class VictoryBrushLine extends React.Component { } else if (allowResize && isSelecting) { let currentDomain = brushDomain || getMinimumDomain(); const range = toRange(targetProps, currentDomain); - const oppositeHandle = targetProps.activeHandle === "min" ? "max" : "min"; + const oppositeHandle = + targetProps.activeHandle === "min" ? "max" : "min"; const handle = targetProps.activeHandle && getActiveHandle(targetProps, position, range) === "both" ? oppositeHandle : targetProps.activeHandle; if (!handle) { - currentDomain = toDomain(targetProps, [targetProps.startPosition, position]); + currentDomain = toDomain(targetProps, [ + targetProps.startPosition, + position + ]); } else { - const rangeMax = dimension === "x" ? Math.max(...range) : Math.min(...range); - const rangeMin = dimension === "x" ? Math.min(...range) : Math.max(...range); + const rangeMax = + dimension === "x" + ? Math.max(...range) + : Math.min(...range); + const rangeMin = + dimension === "x" + ? Math.min(...range) + : Math.max(...range); const min = handle === "max" ? rangeMin : position; const max = handle === "min" ? rangeMax : position; currentDomain = toDomain(targetProps, [min, max]); @@ -357,7 +415,10 @@ export default class VictoryBrushLine extends React.Component { } }; if (isFunction(onBrushDomainChange)) { - onBrushDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -368,8 +429,12 @@ export default class VictoryBrushLine extends React.Component { return []; }, onMouseUp(evt, targetProps) { - const { onBrushDomainChange, brushDomain, allowResize, activeBrushes } = - targetProps; + const { + onBrushDomainChange, + brushDomain, + allowResize, + activeBrushes + } = targetProps; // if the mouse hasn't moved since a mouseDown event, select the whole domain region const mutatedProps = { isPanning: false, @@ -380,7 +445,10 @@ export default class VictoryBrushLine extends React.Component { activeBrushes }; if (allowResize && isFunction(onBrushDomainChange)) { - onBrushDomainChange(brushDomain, defaults({}, mutatedProps, targetProps)); + onBrushDomainChange( + brushDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -477,25 +545,44 @@ export default class VictoryBrushLine extends React.Component { } renderHandles(props) { - const { handleComponent, handleStyle, id, brushDomain, datum = {}, activeBrushes = {} } = props; + const { + handleComponent, + handleStyle, + id, + brushDomain, + datum = {}, + activeBrushes = {} + } = props; if (!brushDomain) { return null; } const handleDimensions = this.getHandleDimensions(props); const style = assign({}, fallbackProps.handleStyle, handleStyle); - const minDatum = assign({ handleValue: Collection.getMinValue(brushDomain) }, datum); - const maxDatum = assign({ handleValue: Collection.getMaxValue(brushDomain) }, datum); + const minDatum = assign( + { handleValue: Collection.getMinValue(brushDomain) }, + datum + ); + const maxDatum = assign( + { handleValue: Collection.getMaxValue(brushDomain) }, + datum + ); const minHandleProps = assign( { key: `${id}-min`, - style: Helpers.evaluateStyle(style, { datum: minDatum, active: activeBrushes.minHandle }) + style: Helpers.evaluateStyle(style, { + datum: minDatum, + active: activeBrushes.minHandle + }) }, handleDimensions.min ); const maxHandleProps = assign( { key: `${id}-max`, - style: Helpers.evaluateStyle(style, { datum: maxDatum, active: activeBrushes.maxHandle }) + style: Helpers.evaluateStyle(style, { + datum: maxDatum, + active: activeBrushes.maxHandle + }) }, handleDimensions.max ); @@ -506,25 +593,50 @@ export default class VictoryBrushLine extends React.Component { } renderBrush(props) { - const { brushComponent, brushStyle, activeBrushes = {}, datum = {}, brushDomain } = props; + const { + brushComponent, + brushStyle, + activeBrushes = {}, + datum = {}, + brushDomain + } = props; if (!brushDomain) { return null; } const brushWidth = props.brushWidth || props.width; const rectDimensions = this.getRectDimensions(props, brushWidth); const baseStyle = assign({}, fallbackProps.brushStyle, brushStyle); - const style = Helpers.evaluateStyle(baseStyle, { datum, active: activeBrushes.brush }); + const style = Helpers.evaluateStyle(baseStyle, { + datum, + active: activeBrushes.brush + }); const brushProps = assign({ style }, rectDimensions); return React.cloneElement(brushComponent, brushProps); } renderBrushArea(props) { - const { brushAreaComponent, brushAreaStyle, activeBrushes = {}, datum = {} } = props; + const { + brushAreaComponent, + brushAreaStyle, + activeBrushes = {}, + datum = {} + } = props; const brushAreaWidth = props.brushAreaWidth || props.width; const cursor = this.getCursor(props); - const rectDimensions = this.getRectDimensions(props, brushAreaWidth, getFullDomain(props)); - const baseStyle = assign({ cursor }, fallbackProps.brushAreaStyle, brushAreaStyle); - const style = Helpers.evaluateStyle(baseStyle, { datum, active: activeBrushes.brushArea }); + const rectDimensions = this.getRectDimensions( + props, + brushAreaWidth, + getFullDomain(props) + ); + const baseStyle = assign( + { cursor }, + fallbackProps.brushAreaStyle, + brushAreaStyle + ); + const style = Helpers.evaluateStyle(baseStyle, { + datum, + active: activeBrushes.brushArea + }); const brushAreaProps = assign({ style }, rectDimensions); return React.cloneElement(brushAreaComponent, brushAreaProps); } diff --git a/packages/victory-candlestick/src/candle.js b/packages/victory-candlestick/src/candle.js index f6d0331be..f97d049a4 100644 --- a/packages/victory-candlestick/src/candle.js +++ b/packages/victory-candlestick/src/candle.js @@ -7,7 +7,9 @@ import { assign, defaults, isFunction } from "lodash"; const getCandleWidth = (candleWidth, props) => { const { style } = props; if (candleWidth) { - return isFunction(candleWidth) ? Helpers.evaluateProp(candleWidth, props) : candleWidth; + return isFunction(candleWidth) + ? Helpers.evaluateProp(candleWidth, props) + : candleWidth; } else if (style.width) { return style.width; } @@ -63,15 +65,28 @@ const evaluateProps = (props) => { * `id` * `tabIndex` */ - const style = Helpers.evaluateStyle(assign({ stroke: "black" }, props.style), props); - const candleWidth = getCandleWidth(props.candleWidth, assign({}, props, { style })); + const style = Helpers.evaluateStyle( + assign({ stroke: "black" }, props.style), + props + ); + const candleWidth = getCandleWidth( + props.candleWidth, + assign({}, props, { style }) + ); const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const desc = Helpers.evaluateProp(props.desc, props); const id = Helpers.evaluateProp(props.id, props); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); - return assign({}, props, { ariaLabel, style, candleWidth, desc, id, tabIndex }); + return assign({}, props, { + ariaLabel, + style, + candleWidth, + desc, + id, + tabIndex + }); }; const Candle = (props) => { diff --git a/packages/victory-candlestick/src/helper-methods.js b/packages/victory-candlestick/src/helper-methods.js index ac744994e..57d9c970c 100644 --- a/packages/victory-candlestick/src/helper-methods.js +++ b/packages/victory-candlestick/src/helper-methods.js @@ -1,5 +1,12 @@ import { assign, defaults, isNil, isFunction, isPlainObject } from "lodash"; -import { Helpers, Scale, Domain, Data, LabelHelpers, Collection } from "victory-core"; +import { + Helpers, + Scale, + Domain, + Data, + LabelHelpers, + Collection +} from "victory-core"; const TYPES = ["close", "open", "high", "low"]; @@ -14,7 +21,8 @@ const reduceData = (dataset, axis, type) => { const baseCondition = type === "min" ? Infinity : -Infinity; return dataset.reduce((memo, datum) => { const current = datum[dataType]; - return (memo < current && type === "min") || (memo > current && type === "max") + return (memo < current && type === "min") || + (memo > current && type === "max") ? memo : current; }, baseCondition); @@ -29,8 +37,10 @@ const getDomainFromData = (props, axis) => { ? Domain.getDomainFromMinMax(minDomain, maxDomain) : undefined; } - const min = minDomain !== undefined ? minDomain : reduceData(dataset, axis, "min"); - const max = maxDomain !== undefined ? maxDomain : reduceData(dataset, axis, "max"); + const min = + minDomain !== undefined ? minDomain : reduceData(dataset, axis, "min"); + const max = + maxDomain !== undefined ? maxDomain : reduceData(dataset, axis, "max"); return Domain.getDomainFromMinMax(min, max); }; @@ -118,9 +128,19 @@ const formatDataFromDomain = (datum, domain) => { if (_x < minDomainX || _x > maxDomainX) _x = null; // if all values fall outside of domain, null the data point - if (_low < minDomainY && _open < minDomainY && _close < minDomainY && _high < minDomainY) + if ( + _low < minDomainY && + _open < minDomainY && + _close < minDomainY && + _high < minDomainY + ) _low = _open = _close = _high = null; - if (_low > maxDomainY && _open > maxDomainY && _close > maxDomainY && _high > maxDomainY) + if ( + _low > maxDomainY && + _open > maxDomainY && + _close > maxDomainY && + _high > maxDomainY + ) _low = _open = _close = _high = null; return Object.assign({}, datum, { _x, _low, _open, _close, _high }); @@ -147,7 +167,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; const defaultOrientation = props.horizontal ? "top" : "right"; const labelOrientation = props.labelOrientation || defaultOrientation; return { domain, data, scale, style, origin, labelOrientation }; @@ -163,7 +185,9 @@ const getDataStyles = (datum, style, props) => { } style = style || {}; const candleColor = - datum._open > datum._close ? props.candleColors.negative : props.candleColors.positive; + datum._open > datum._close + ? props.candleColors.negative + : props.candleColors.positive; const fill = style.fill || candleColor; const strokeColor = style.stroke; const stroke = isTransparent(strokeColor) ? fill : strokeColor || "black"; @@ -186,7 +210,9 @@ const getText = (props, type) => { const getCandleWidth = (props, style) => { const { data, candleWidth, scale, defaultCandleWidth } = props; if (candleWidth) { - return isFunction(candleWidth) ? Helpers.evaluateProp(candleWidth, props) : candleWidth; + return isFunction(candleWidth) + ? Helpers.evaluateProp(candleWidth, props) + : candleWidth; } else if (style && style.width) { return style.width; } @@ -194,17 +220,28 @@ const getCandleWidth = (props, style) => { const extent = Math.abs(range[1] - range[0]); const candles = data.length + 2; const candleRatio = props.candleRatio || 0.5; - const defaultWidth = candleRatio * (data.length < 2 ? defaultCandleWidth : extent / candles); + const defaultWidth = + candleRatio * (data.length < 2 ? defaultCandleWidth : extent / candles); return Math.max(1, defaultWidth); }; const getOrientation = (labelOrientation, type = "labels") => { - return isPlainObject(labelOrientation) ? labelOrientation[type] : labelOrientation; + return isPlainObject(labelOrientation) + ? labelOrientation[type] + : labelOrientation; }; /* eslint-disable complexity*/ const calculatePlotValues = (props) => { - const { positions, labelStyle, x, horizontal, computedType, candleWidth, orientation } = props; + const { + positions, + labelStyle, + x, + horizontal, + computedType, + candleWidth, + orientation + } = props; positions.labels = (positions.open + positions.close) / 2; const signX = orientation === "left" ? -1 : 1; @@ -220,7 +257,9 @@ const calculatePlotValues = (props) => { : 0; const dx = - orientation === "top" || orientation === "bottom" ? 0 : signX * (labelStyle.padding || 1); + orientation === "top" || orientation === "bottom" + ? 0 + : signX * (labelStyle.padding || 1); return { yValue, xValue, dx, dy }; } else { @@ -228,7 +267,9 @@ const calculatePlotValues = (props) => { const yValue = positions[computedType]; const dy = - orientation === "top" || orientation === "bottom" ? signY * (labelStyle.padding || 1) : 0; + orientation === "top" || orientation === "bottom" + ? signY * (labelStyle.padding || 1) + : 0; const dx = orientation === "top" || orientation === "bottom" @@ -267,8 +308,18 @@ const getLabelProps = (props, text, style, type) => { const positions = { high, low, open, close }; const namespace = type ? `${type}Labels` : "labels"; const labelStyle = style[namespace] || style.labels; - const defaultVerticalAnchors = { top: "end", bottom: "start", left: "middle", right: "middle" }; - const defaultTextAnchors = { left: "end", right: "start", top: "middle", bottom: "middle" }; + const defaultVerticalAnchors = { + top: "end", + bottom: "start", + left: "middle", + right: "middle" + }; + const defaultTextAnchors = { + left: "end", + right: "start", + top: "middle", + bottom: "middle" + }; const computedType = type ? type : "labels"; const plotProps = { @@ -295,7 +346,8 @@ const getLabelProps = (props, text, style, type) => { data, orientation, textAnchor: labelStyle.textAnchor || defaultTextAnchors[orientation], - verticalAnchor: labelStyle.verticalAnchor || defaultVerticalAnchors[orientation], + verticalAnchor: + labelStyle.verticalAnchor || defaultVerticalAnchors[orientation], angle: labelStyle.angle, horizontal }; @@ -312,7 +364,8 @@ const getBaseProps = (props, fallbackProps) => { // eslint-disable-line max-statements props = Helpers.modifyProps(props, fallbackProps, "candlestick"); const calculatedValues = getCalculatedValues(props); - const { data, style, scale, domain, origin, labelOrientation } = calculatedValues; + const { data, style, scale, domain, origin, labelOrientation } = + calculatedValues; const { groupComponent, width, @@ -392,7 +445,10 @@ const getBaseProps = (props, fallbackProps) => { if (labels) { const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { childProps[eventKey].labels = getLabelProps(extendedProps, text, style); } } @@ -405,7 +461,12 @@ const getBaseProps = (props, fallbackProps) => { (labelProp && (events || sharedEvents)) ) { const target = `${type}Labels`; - childProps[eventKey][target] = getLabelProps(extendedProps, labelText, style, type); + childProps[eventKey][target] = getLabelProps( + extendedProps, + labelText, + style, + type + ); } }); diff --git a/packages/victory-candlestick/src/index.d.ts b/packages/victory-candlestick/src/index.d.ts index 813e868ea..f56658a88 100644 --- a/packages/victory-candlestick/src/index.d.ts +++ b/packages/victory-candlestick/src/index.d.ts @@ -26,7 +26,10 @@ export interface VictoryCandlestickStyleInterface { parent?: VictoryStyleObject; } -export type VictoryCandlestickLabelsType = (string | number)[] | boolean | ((datum: any) => number); +export type VictoryCandlestickLabelsType = + | (string | number)[] + | boolean + | ((datum: any) => number); export interface VictoryCandlestickProps extends Omit, @@ -83,7 +86,10 @@ export interface VictoryCandlestickProps * VictoryCandlestick can be composed with VictoryChart to create candlestick charts. */ -export class VictoryCandlestick extends React.Component {} +export class VictoryCandlestick extends React.Component< + VictoryCandlestickProps, + any +> {} export interface CandleProps extends VictoryCommonPrimitiveProps { candleRatio?: number; diff --git a/packages/victory-candlestick/src/victory-candlestick.js b/packages/victory-candlestick/src/victory-candlestick.js index ce1315c74..e766c21f9 100644 --- a/packages/victory-candlestick/src/victory-candlestick.js +++ b/packages/victory-candlestick/src/victory-candlestick.js @@ -71,17 +71,27 @@ class VictoryCandlestick extends React.Component { static propTypes = { ...CommonProps.baseProps, ...CommonProps.dataProps, - candleColors: PropTypes.shape({ positive: PropTypes.string, negative: PropTypes.string }), + candleColors: PropTypes.shape({ + positive: PropTypes.string, + negative: PropTypes.string + }), candleRatio: PropTypes.number, candleWidth: PropTypes.oneOfType([PropTypes.func, PropTypes.number]), close: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), closeLabelComponent: PropTypes.element, - closeLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + closeLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), events: PropTypes.arrayOf( PropTypes.shape({ target: PropTypes.oneOf([ @@ -98,7 +108,10 @@ class VictoryCandlestick extends React.Component { ]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -106,12 +119,19 @@ class VictoryCandlestick extends React.Component { ), high: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), highLabelComponent: PropTypes.element, - highLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + highLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), labelOrientation: PropTypes.oneOfType([ PropTypes.oneOf(["top", "bottom", "left", "right"]), PropTypes.shape({ @@ -123,20 +143,34 @@ class VictoryCandlestick extends React.Component { ]), low: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), lowLabelComponent: PropTypes.element, - lowLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + lowLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), open: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), openLabelComponent: PropTypes.element, - openLabels: PropTypes.oneOfType([PropTypes.func, PropTypes.array, PropTypes.bool]), + openLabels: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.array, + PropTypes.bool + ]), style: PropTypes.shape({ data: PropTypes.object, labels: PropTypes.object, @@ -202,13 +236,18 @@ class VictoryCandlestick extends React.Component { const { dataComponent, labelComponent, groupComponent } = props; const types = ["close", "open", "low", "high"]; - const dataComponents = this.dataKeys.reduce((validDataComponents, _dataKey, index) => { - const dataProps = this.getComponentProps(dataComponent, "data", index); - if (shouldRenderDatum(dataProps.datum)) { - validDataComponents.push(React.cloneElement(dataComponent, dataProps)); - } - return validDataComponents; - }, []); + const dataComponents = this.dataKeys.reduce( + (validDataComponents, _dataKey, index) => { + const dataProps = this.getComponentProps(dataComponent, "data", index); + if (shouldRenderDatum(dataProps.datum)) { + validDataComponents.push( + React.cloneElement(dataComponent, dataProps) + ); + } + return validDataComponents; + }, + [] + ); const labelComponents = flatten( types.map((type) => { @@ -227,7 +266,11 @@ class VictoryCandlestick extends React.Component { const labelsComponents = this.dataKeys .map((_dataKey, index) => { - const labelProps = this.getComponentProps(labelComponent, "labels", index); + const labelProps = this.getComponentProps( + labelComponent, + "labels", + index + ); if (labelProps.text !== undefined && labelProps.text !== null) { return React.cloneElement(labelComponent, labelProps); } @@ -235,7 +278,11 @@ class VictoryCandlestick extends React.Component { }) .filter(Boolean); - const children = [...dataComponents, ...labelComponents, ...labelsComponents]; + const children = [ + ...dataComponents, + ...labelComponents, + ...labelsComponents + ]; return this.renderContainer(groupComponent, children); } @@ -248,7 +295,9 @@ class VictoryCandlestick extends React.Component { } const children = this.renderCandleData(props, this.shouldRenderDatum); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-chart/src/helper-methods.js b/packages/victory-chart/src/helper-methods.js index 72ec0f0c8..31e16e789 100644 --- a/packages/victory-chart/src/helper-methods.js +++ b/packages/victory-chart/src/helper-methods.js @@ -66,7 +66,8 @@ function getChildProps(child, props, calculatedProps) { if (axisChild.length > 0) { return getAxisProps(axisChild[0], props, calculatedProps); } - const { categories, domain, range, scale, stringMap, horizontal } = calculatedProps; + const { categories, domain, range, scale, stringMap, horizontal } = + calculatedProps; return { categories, domain, range, scale, stringMap, horizontal }; } @@ -126,7 +127,8 @@ function getCalculatedProps(props, childComponents) { function getChildren(props, childComponents, calculatedProps) { childComponents = childComponents || getChildComponents(props); - calculatedProps = calculatedProps || getCalculatedProps(props, childComponents); + calculatedProps = + calculatedProps || getCalculatedProps(props, childComponents); const baseStyle = calculatedProps.style.parent; const { height, polar, theme, width } = props; const { origin, horizontal } = calculatedProps; @@ -168,13 +170,24 @@ const getChildComponents = (props, defaultAxes) => { } else { const axisComponents = { dependent: Axis.getAxisComponentsWithParent(childComponents, "dependent"), - independent: Axis.getAxisComponentsWithParent(childComponents, "independent") + independent: Axis.getAxisComponentsWithParent( + childComponents, + "independent" + ) }; - if (axisComponents.dependent.length === 0 && axisComponents.independent.length === 0) { + if ( + axisComponents.dependent.length === 0 && + axisComponents.independent.length === 0 + ) { newChildComponents = props.prependDefaultAxes - ? [defaultAxes.independent, defaultAxes.dependent].concat(newChildComponents) - : newChildComponents.concat([defaultAxes.independent, defaultAxes.dependent]); + ? [defaultAxes.independent, defaultAxes.dependent].concat( + newChildComponents + ) + : newChildComponents.concat([ + defaultAxes.independent, + defaultAxes.dependent + ]); } } @@ -185,7 +198,8 @@ const getDomain = (props, axis, childComponents) => { childComponents = childComponents || React.Children.toArray(props.children); const domain = Wrapper.getDomain(props, axis, childComponents); const axisComponent = Axis.getAxisComponent(childComponents, axis); - const invertDomain = axisComponent && axisComponent.props && axisComponent.props.invertAxis; + const invertDomain = + axisComponent && axisComponent.props && axisComponent.props.invertAxis; return invertDomain ? domain.concat().reverse() : domain; }; @@ -208,4 +222,9 @@ const createStringMap = (props, childComponents, allStrings) => { return { x, y }; }; -export { getBackgroundWithProps, getChildren, getCalculatedProps, getChildComponents }; +export { + getBackgroundWithProps, + getChildren, + getCalculatedProps, + getChildComponents +}; diff --git a/packages/victory-chart/src/index.d.ts b/packages/victory-chart/src/index.d.ts index 9c26fe8bf..03573ee63 100644 --- a/packages/victory-chart/src/index.d.ts +++ b/packages/victory-chart/src/index.d.ts @@ -23,11 +23,16 @@ export interface VictoryChartProps extends VictoryCommonProps { domain?: DomainPropType; endAngle?: number; eventKey?: StringOrNumberOrCallback; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + string, + string[] | number[] | string | number + >[]; innerRadius?: number; prependDefaultAxes?: boolean; startAngle?: number; - style?: Pick & { background?: VictoryStyleObject }; + style?: Pick & { + background?: VictoryStyleObject; + }; } export class VictoryChart extends React.Component {} diff --git a/packages/victory-chart/src/victory-chart.js b/packages/victory-chart/src/victory-chart.js index 977abb2f9..7810b4bbe 100644 --- a/packages/victory-chart/src/victory-chart.js +++ b/packages/victory-chart/src/victory-chart.js @@ -33,7 +33,10 @@ export default class VictoryChart extends React.Component { static propTypes = { ...CommonProps.baseProps, backgroundComponent: PropTypes.element, - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), defaultAxes: PropTypes.shape({ independent: PropTypes.element, dependent: PropTypes.element @@ -94,12 +97,18 @@ export default class VictoryChart extends React.Component { const getAnimationProps = Wrapper.getAnimationProps.bind(this); const newChildren = children.map((child, index) => { - const childProps = assign({ animate: getAnimationProps(props, child, index) }, child.props); + const childProps = assign( + { animate: getAnimationProps(props, child, index) }, + child.props + ); return React.cloneElement(child, childProps); }); if (props.style && props.style.background) { - const backgroundComponent = getBackgroundWithProps(props, calculatedProps); + const backgroundComponent = getBackgroundWithProps( + props, + calculatedProps + ); newChildren.unshift(backgroundComponent); } @@ -114,7 +123,8 @@ export default class VictoryChart extends React.Component { getContainerProps(props, calculatedProps) { const { width, height, standalone, theme, polar, name } = props; - const { domain, scale, style, origin, radius, horizontal } = calculatedProps; + const { domain, scale, style, origin, radius, horizontal } = + calculatedProps; return { domain, scale, @@ -133,15 +143,30 @@ export default class VictoryChart extends React.Component { render() { const props = - this.state && this.state.nodesWillExit ? this.state.oldProps || this.props : this.props; + this.state && this.state.nodesWillExit + ? this.state.oldProps || this.props + : this.props; const modifiedProps = Helpers.modifyProps(props, fallbackProps, "chart"); - const { eventKey, containerComponent, groupComponent, standalone, externalEventMutations } = - modifiedProps; - const axes = props.polar ? modifiedProps.defaultPolarAxes : modifiedProps.defaultAxes; + const { + eventKey, + containerComponent, + groupComponent, + standalone, + externalEventMutations + } = modifiedProps; + const axes = props.polar + ? modifiedProps.defaultPolarAxes + : modifiedProps.defaultAxes; const childComponents = getChildComponents(modifiedProps, axes); const calculatedProps = getCalculatedProps(modifiedProps, childComponents); - const newChildren = this.getNewChildren(modifiedProps, childComponents, calculatedProps); - const containerProps = standalone ? this.getContainerProps(modifiedProps, calculatedProps) : {}; + const newChildren = this.getNewChildren( + modifiedProps, + childComponents, + calculatedProps + ); + const containerProps = standalone + ? this.getContainerProps(modifiedProps, calculatedProps) + : {}; const container = standalone ? this.renderContainer(containerComponent, containerProps) : groupComponent; diff --git a/packages/victory-core/src/index.d.ts b/packages/victory-core/src/index.d.ts index 80e4a1bf2..37a693295 100644 --- a/packages/victory-core/src/index.d.ts +++ b/packages/victory-core/src/index.d.ts @@ -104,18 +104,31 @@ export interface CallbackArgs { export type OrientationTypes = "top" | "bottom" | "left" | "right"; -export type VictoryStringOrNumberCallback = (args: CallbackArgs) => string | number; +export type VictoryStringOrNumberCallback = ( + args: CallbackArgs +) => string | number; export type VictoryNumberCallback = (args: CallbackArgs) => number; export type VictoryStringCallback = (args: CallbackArgs) => string; -export type VictoryPaddingCallback = (args: CallbackArgs) => number | BlockProps; -export type VictoryOrientationCallback = (args: CallbackArgs) => OrientationTypes; -export type StringOrNumberOrCallback = string | number | VictoryStringOrNumberCallback; +export type VictoryPaddingCallback = ( + args: CallbackArgs +) => number | BlockProps; +export type VictoryOrientationCallback = ( + args: CallbackArgs +) => OrientationTypes; +export type StringOrNumberOrCallback = + | string + | number + | VictoryStringOrNumberCallback; export type NumberOrCallback = number | VictoryNumberCallback; export type StringOrCallback = string | VictoryStringCallback; export type PaddingOrCallback = number | BlockProps | VictoryPaddingCallback; -export type OrientationOrCallback = OrientationTypes | VictoryOrientationCallback; +export type OrientationOrCallback = + | OrientationTypes + | VictoryOrientationCallback; -export type SliceNumberOrCallback = number | ((props: Omit) => number); +export type SliceNumberOrCallback = + | number + | ((props: Omit) => number); export type StringOrNumberOrList = string | number | (string | number)[]; @@ -124,14 +137,18 @@ export type CoordinatesPropType = { y: number; }; -export type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; +export type VictoryStyleObject = { + [K in keyof React.CSSProperties]: StringOrNumberOrCallback; +}; export type LabelProps = React.CSSProperties & { angle?: number; verticalAnchor?: VerticalAnchorType; }; -export type VictoryLabelStyleObject = { [K in keyof LabelProps]: StringOrNumberOrCallback }; +export type VictoryLabelStyleObject = { + [K in keyof LabelProps]: StringOrNumberOrCallback; +}; /** * Style interface used in components/themeing @@ -156,7 +173,10 @@ export interface VictoryAnimationProps { data?: AnimationData; } -export class VictoryAnimation extends React.Component {} +export class VictoryAnimation extends React.Component< + VictoryAnimationProps, + any +> {} // #endregion @@ -164,7 +184,9 @@ export class VictoryAnimation extends React.Component {} +export class VictoryContainer extends React.Component< + VictoryContainerProps, + any +> {} // #endregion @@ -298,7 +325,10 @@ export interface VictoryClipContainerProps { translateY?: number; } -export class VictoryClipContainer extends React.Component {} +export class VictoryClipContainer extends React.Component< + VictoryClipContainerProps, + any +> {} // #endregion @@ -313,7 +343,10 @@ export interface VictoryAccessibleGroupProps { tabIndex?: number; } -export class VictoryAccessibleGroup extends React.Component {} +export class VictoryAccessibleGroup extends React.Component< + VictoryAccessibleGroupProps, + any +> {} // #endregion @@ -543,16 +576,16 @@ export interface EventPropTypeInterface { eventHandlers: { [key: string]: | { - (event: React.SyntheticEvent, props?: any): EventCallbackInterface< - TTarget, - TEventKey - >; + ( + event: React.SyntheticEvent, + props?: any + ): EventCallbackInterface; } | { - (event: React.SyntheticEvent, props?: any): EventCallbackInterface< - TTarget, - TEventKey - >[]; + ( + event: React.SyntheticEvent, + props?: any + ): EventCallbackInterface[]; } | { (event: React.SyntheticEvent, props?: any): void; @@ -646,7 +679,10 @@ export interface VictoryCommonThemeProps { colorScale?: ColorScalePropType; containerComponent?: React.ReactElement; domainPadding?: DomainPaddingPropType; - externalEventMutations?: EventCallbackInterface[]; + externalEventMutations?: EventCallbackInterface< + string | string[], + StringOrNumberOrList + >[]; groupComponent?: React.ReactElement; height?: number; horizontal?: boolean; @@ -714,7 +750,10 @@ export interface VictoryLabelableProps { } export interface VictoryMultiLabelableProps extends VictoryLabelableProps { - labels?: string[] | number[] | { (data: any): string | string[] | number | number[] | null }; + labels?: + | string[] + | number[] + | { (data: any): string | string[] | number | number[] | null }; } export interface VictorySingleLabelableProps extends VictoryLabelableProps { @@ -727,7 +766,10 @@ export namespace Selection { evt: React.SyntheticEvent, svg?: SVGElement ): SVGCoordinateType; - export function getDomainCoordinates(props: any, domain?: DomainPropType): DomainPropType; + export function getDomainCoordinates( + props: any, + domain?: DomainPropType + ): DomainPropType; export function getDataCoordinates( props: any, scale: ScalePropType, @@ -751,7 +793,10 @@ export namespace TextSize { text: string, style?: TextSizeStyleInterface ): { width: number; height: number }; - export function convertLengthToPixels(length: string, fontSize: number): number; + export function convertLengthToPixels( + length: string, + fontSize: number + ): number; } // #endregion @@ -868,7 +913,8 @@ export interface WhiskerProps extends VictoryCommonPrimitiveProps { export class Whisker extends React.Component {} -export interface VictoryPrimitiveShapeProps extends VictoryCommonPrimitiveProps { +export interface VictoryPrimitiveShapeProps + extends VictoryCommonPrimitiveProps { desc?: string; } diff --git a/packages/victory-core/src/victory-accessible-group/victory-accessible-group.js b/packages/victory-core/src/victory-accessible-group/victory-accessible-group.js index 1fc723bd6..3df88e02d 100644 --- a/packages/victory-core/src/victory-accessible-group/victory-accessible-group.js +++ b/packages/victory-core/src/victory-accessible-group/victory-accessible-group.js @@ -6,7 +6,10 @@ class VictoryAccessibleGroup extends React.Component { static propTypes = { "aria-describedby": PropTypes.string, "aria-label": PropTypes.string, - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), className: PropTypes.string, desc: PropTypes.string, tabIndex: PropTypes.number @@ -18,7 +21,8 @@ class VictoryAccessibleGroup extends React.Component { render() { const { desc, children, className, tabIndex } = this.props; - const descId = desc && (this.props["aria-describedby"] || desc.split(" ").join("-")); + const descId = + desc && (this.props["aria-describedby"] || desc.split(" ").join("-")); return desc ? ( { - this.loopID = this.timer.subscribe(this.functionToBeRunEachFrame, this.props.duration); + this.loopID = this.timer.subscribe( + this.functionToBeRunEachFrame, + this.props.duration + ); }, this.props.delay); } else { - this.loopID = this.timer.subscribe(this.functionToBeRunEachFrame, this.props.duration); + this.loopID = this.timer.subscribe( + this.functionToBeRunEachFrame, + this.props.duration + ); } } else if (this.props.onEnd) { this.props.onEnd(); diff --git a/packages/victory-core/src/victory-clip-container/victory-clip-container.js b/packages/victory-core/src/victory-clip-container/victory-clip-container.js index 29b667147..e58c44d6f 100644 --- a/packages/victory-core/src/victory-clip-container/victory-clip-container.js +++ b/packages/victory-core/src/victory-clip-container/victory-clip-container.js @@ -12,7 +12,10 @@ export default class VictoryClipContainer extends React.Component { static role = "container"; static propTypes = { "aria-label": PropTypes.string, - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), circleComponent: PropTypes.element, className: PropTypes.string, clipHeight: CustomPropTypes.nonNegative, @@ -27,7 +30,10 @@ export default class VictoryClipContainer extends React.Component { clipWidth: CustomPropTypes.nonNegative, events: PropTypes.object, groupComponent: PropTypes.element, - origin: PropTypes.shape({ x: CustomPropTypes.nonNegative, y: CustomPropTypes.nonNegative }), + origin: PropTypes.shape({ + x: CustomPropTypes.nonNegative, + y: CustomPropTypes.nonNegative + }), polar: PropTypes.bool, radius: CustomPropTypes.nonNegative, style: PropTypes.object, @@ -47,23 +53,46 @@ export default class VictoryClipContainer extends React.Component { constructor(props) { super(props); this.clipId = - !isObject(props) || props.clipId === undefined ? uniqueId("victory-clip-") : props.clipId; + !isObject(props) || props.clipId === undefined + ? uniqueId("victory-clip-") + : props.clipId; } calculateAttributes(props) { - const { polar, origin, clipWidth = 0, clipHeight = 0, translateX = 0, translateY = 0 } = props; + const { + polar, + origin, + clipWidth = 0, + clipHeight = 0, + translateX = 0, + translateY = 0 + } = props; const clipPadding = Helpers.getPadding({ padding: props.clipPadding }); const radius = props.radius || Helpers.getRadius(props); return { x: (polar ? origin.x : translateX) - clipPadding.left, y: (polar ? origin.y : translateY) - clipPadding.top, - width: Math.max((polar ? radius : clipWidth) + clipPadding.left + clipPadding.right, 0), - height: Math.max((polar ? radius : clipHeight) + clipPadding.top + clipPadding.bottom, 0) + width: Math.max( + (polar ? radius : clipWidth) + clipPadding.left + clipPadding.right, + 0 + ), + height: Math.max( + (polar ? radius : clipHeight) + clipPadding.top + clipPadding.bottom, + 0 + ) }; } renderClippedGroup(props, clipId) { - const { style, events, transform, children, className, groupComponent, tabIndex } = props; + const { + style, + events, + transform, + children, + className, + groupComponent, + tabIndex + } = props; const clipComponent = this.renderClipComponent(props, clipId); const groupProps = assign( { @@ -83,10 +112,27 @@ export default class VictoryClipContainer extends React.Component { } renderGroup(props) { - const { style, events, transform, children, className, groupComponent, tabIndex } = props; + const { + style, + events, + transform, + children, + className, + groupComponent, + tabIndex + } = props; return React.cloneElement( groupComponent, - assign({ className, style, transform, "aria-label": props["aria-label"], tabIndex }, events), + assign( + { + className, + style, + transform, + "aria-label": props["aria-label"], + tabIndex + }, + events + ), children ); } @@ -103,7 +149,9 @@ export default class VictoryClipContainer extends React.Component { rectComponent, clipPathComponent } = props; - const { top, bottom, left, right } = Helpers.getPadding({ padding: props.clipPadding }); + const { top, bottom, left, right } = Helpers.getPadding({ + padding: props.clipPadding + }); let child; if (polar) { const radius = props.radius || Helpers.getRadius(props); @@ -155,7 +203,12 @@ export default class VictoryClipContainer extends React.Component { } const translateX = this.getTranslateValue(this.props, "x"); const translateY = this.getTranslateValue(this.props, "y"); - const clipProps = defaults({}, this.props, { clipHeight, clipWidth, translateX, translateY }); + const clipProps = defaults({}, this.props, { + clipHeight, + clipWidth, + translateX, + translateY + }); return this.renderClippedGroup(clipProps, this.clipId); } } diff --git a/packages/victory-core/src/victory-container/victory-container.js b/packages/victory-core/src/victory-container/victory-container.js index d079fcbbf..749dde777 100644 --- a/packages/victory-core/src/victory-container/victory-container.js +++ b/packages/victory-core/src/victory-container/victory-container.js @@ -13,7 +13,10 @@ export default class VictoryContainer extends React.Component { static propTypes = { "aria-describedby": PropTypes.string, "aria-labelledby": PropTypes.string, - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), className: PropTypes.string, containerId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), containerRef: PropTypes.func, @@ -112,10 +115,20 @@ export default class VictoryContainer extends React.Component { } renderContainer(props, svgProps, style) { - const { title, desc, portalComponent, className, width, height, portalZIndex, responsive } = - props; + const { + title, + desc, + portalComponent, + className, + width, + height, + portalZIndex, + responsive + } = props; const children = this.getChildren(props); - const dimensions = responsive ? { width: "100%", height: "100%" } : { width, height }; + const dimensions = responsive + ? { width: "100%", height: "100%" } + : { width, height }; const divStyle = assign( { pointerEvents: "none", touchAction: "none", position: "relative" }, dimensions @@ -148,8 +161,12 @@ export default class VictoryContainer extends React.Component { {...this.getOUIAProps(props)} > - {title ? {title} : null} - {desc ? {desc} : null} + {title ? ( + {title} + ) : null} + {desc ? ( + {desc} + ) : null} {children}
    @@ -164,8 +181,17 @@ export default class VictoryContainer extends React.Component { } render() { - const { width, height, responsive, events, title, desc, tabIndex, preserveAspectRatio, role } = - this.props; + const { + width, + height, + responsive, + events, + title, + desc, + tabIndex, + preserveAspectRatio, + role + } = this.props; const style = responsive ? this.props.style : Helpers.omit(this.props.style, ["height", "width"]); @@ -176,7 +202,10 @@ export default class VictoryContainer extends React.Component { tabIndex, role, "aria-labelledby": - [title && this.getIdForElement("title"), this.props["aria-labelledby"]] + [ + title && this.getIdForElement("title"), + this.props["aria-labelledby"] + ] .filter(Boolean) .join(" ") || undefined, "aria-describedby": diff --git a/packages/victory-core/src/victory-label/victory-label.js b/packages/victory-core/src/victory-label/victory-label.js index 9570dda58..769611a93 100644 --- a/packages/victory-core/src/victory-label/victory-label.js +++ b/packages/victory-core/src/victory-label/victory-label.js @@ -16,7 +16,8 @@ import { assign, defaults, isEmpty } from "lodash"; const defaultStyles = { fill: "#252525", fontSize: 14, - fontFamily: "'Gill Sans', 'Gill Sans MT', 'Ser­avek', 'Trebuchet MS', sans-serif", + fontFamily: + "'Gill Sans', 'Gill Sans MT', 'Ser­avek', 'Trebuchet MS', sans-serif", stroke: "transparent" }; @@ -125,9 +126,15 @@ const getDy = (props, verticalAnchor, lineHeight) => { const dy = props.dy ? Helpers.evaluateProp(props.dy, props) : 0; const length = props.inline ? 1 : props.text.length; const capHeight = Helpers.evaluateProp(props.capHeight, props); - const anchor = verticalAnchor ? Helpers.evaluateProp(verticalAnchor, props) : "middle"; - const fontSizes = [...Array(length).keys()].map((i) => getSingleValue(props.style, i).fontSize); - const lineHeights = [...Array(length).keys()].map((i) => getSingleValue(lineHeight, i)); + const anchor = verticalAnchor + ? Helpers.evaluateProp(verticalAnchor, props) + : "middle"; + const fontSizes = [...Array(length).keys()].map( + (i) => getSingleValue(props.style, i).fontSize + ); + const lineHeights = [...Array(length).keys()].map((i) => + getSingleValue(lineHeight, i) + ); if (anchor === "start") { return dy + (capHeight / 2 + lineHeights[0] / 2) * fontSizes[0]; @@ -138,14 +145,21 @@ const getDy = (props, verticalAnchor, lineHeight) => { } else if (length === 1) { return anchor === "end" ? dy + (capHeight / 2 + (0.5 - length) * lineHeights[0]) * fontSizes[0] - : dy + (capHeight / 2 + (0.5 - length / 2) * lineHeights[0]) * fontSizes[0]; + : dy + + (capHeight / 2 + (0.5 - length / 2) * lineHeights[0]) * fontSizes[0]; } else { const allHeights = [...Array(length).keys()].reduce((memo, i) => { - return memo + ((capHeight / 2 + (0.5 - length) * lineHeights[i]) * fontSizes[i]) / length; + return ( + memo + + ((capHeight / 2 + (0.5 - length) * lineHeights[i]) * fontSizes[i]) / + length + ); }, 0); return anchor === "end" ? dy + allHeights - : dy + allHeights / 2 + (capHeight / 2) * lineHeights[length - 1] * fontSizes[length - 1]; + : dy + + allHeights / 2 + + (capHeight / 2) * lineHeights[length - 1] * fontSizes[length - 1]; } }; @@ -154,12 +168,16 @@ const getTransform = (props, x, y) => { const style = getSingleValue(props.style); const defaultAngle = polar ? LabelHelpers.getPolarAngle(props) : 0; const baseAngle = - style.angle === undefined ? Helpers.evaluateProp(props.angle, props) : style.angle; + style.angle === undefined + ? Helpers.evaluateProp(props.angle, props) + : style.angle; const angle = baseAngle === undefined ? defaultAngle : baseAngle; const transform = props.transform || style.transform; const transformPart = transform && Helpers.evaluateProp(transform, props); const rotatePart = angle && { rotate: [angle, x, y] }; - return transformPart || angle ? Style.toTransformString(transformPart, rotatePart) : undefined; + return transformPart || angle + ? Style.toTransformString(transformPart, rotatePart) + : undefined; }; const getXCoordinate = (calculatedProps, labelSizeWidth) => { @@ -212,7 +230,9 @@ const getFullBackground = (calculatedProps, tspanValues) => { ? Math.max(...textSizes.map((size) => size.height)) : textSizes.reduce((memo, size, i) => { const capHeightAdjustment = i ? 0 : capHeight / 2; - return memo + size.height * (tspanValues[i].lineHeight - capHeightAdjustment); + return ( + memo + size.height * (tspanValues[i].lineHeight - capHeightAdjustment) + ); }, 0); const width = inline @@ -231,7 +251,9 @@ const getFullBackground = (calculatedProps, tspanValues) => { style: backgroundStyle, transform, width: width + backgroundPadding.left + backgroundPadding.right, - x: inline ? xCoordinate - backgroundPadding.left : xCoordinate + dx - backgroundPadding.left, + x: inline + ? xCoordinate - backgroundPadding.left + : xCoordinate + dx - backgroundPadding.left, y: yCoordinate }; @@ -268,8 +290,16 @@ const getInlineXOffset = (calculatedProps, textElements, index) => { }; const getChildBackgrounds = (calculatedProps, tspanValues) => { - const { dy, dx, transform, backgroundStyle, backgroundPadding, backgroundComponent, inline, y } = - calculatedProps; + const { + dy, + dx, + transform, + backgroundStyle, + backgroundPadding, + backgroundComponent, + inline, + y + } = calculatedProps; const textElements = tspanValues.map((current, i) => { const previous = getSingleValue(tspanValues, i - 1); @@ -282,14 +312,17 @@ const getChildBackgrounds = (calculatedProps, tspanValues) => { const childDy = i && !inline - ? previous.fontSize * previous.lineHeight + prevPadding.top + prevPadding.bottom + ? previous.fontSize * previous.lineHeight + + prevPadding.top + + prevPadding.bottom : dy - totalLineHeight * 0.5 - (current.fontSize - current.capHeight); return { textHeight, labelSize, heightWithPadding: textHeight + padding.top + padding.bottom, - widthWithPadding: labelSize.width + padding.left + padding.right + xOffset, + widthWithPadding: + labelSize.width + padding.left + padding.right + xOffset, y, fontSize: current.fontSize, dy: childDy @@ -297,16 +330,23 @@ const getChildBackgrounds = (calculatedProps, tspanValues) => { }); return textElements.map((textElement, i) => { - const xCoordinate = getXCoordinate(calculatedProps, textElement.labelSize.width); + const xCoordinate = getXCoordinate( + calculatedProps, + textElement.labelSize.width + ); const yCoordinate = textElements.slice(0, i + 1).reduce((prev, curr) => { return prev + curr.dy; }, y); const padding = getSingleValue(backgroundPadding, i); const height = textElement.heightWithPadding; const xCoord = inline - ? getInlineXOffset(calculatedProps, textElements, i) + xCoordinate - padding.left + ? getInlineXOffset(calculatedProps, textElements, i) + + xCoordinate - + padding.left : xCoordinate; - const yCoord = inline ? getYCoordinate(calculatedProps, height) - padding.top : yCoordinate; + const yCoord = inline + ? getYCoordinate(calculatedProps, height) - padding.top + : yCoordinate; const backgroundProps = { key: `tspan-background-${i}`, height, @@ -348,7 +388,9 @@ const calculateSpanDy = (tspanValues, i, calculatedProps) => { previousCaps / 2; return useMultiLineBackgrounds(calculatedProps) - ? textHeight + current.backgroundPadding.top + previous.backgroundPadding.bottom + ? textHeight + + current.backgroundPadding.top + + previous.backgroundPadding.bottom : textHeight; }; @@ -381,14 +423,22 @@ const evaluateProps = (props) => { assign({}, props, { text, style, backgroundStyle }) ); const id = Helpers.evaluateProp(props.id, props); - return assign({}, props, { backgroundStyle, backgroundPadding, style, text, id }); + return assign({}, props, { + backgroundStyle, + backgroundPadding, + style, + text, + id + }); }; const getCalculatedProps = (props) => { const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const style = getSingleValue(props.style); const lineHeight = getLineHeight(props); - const direction = props.direction ? Helpers.evaluateProp(props.direction, props) : "inherit"; + const direction = props.direction + ? Helpers.evaluateProp(props.direction, props) + : "inherit"; const textAnchor = props.textAnchor ? Helpers.evaluateProp(props.textAnchor, props) : style.textAnchor || "start"; @@ -478,11 +528,15 @@ const VictoryLabel = (props) => { return null; } const calculatedProps = getCalculatedProps(props); - const { text, style, capHeight, backgroundPadding, lineHeight } = calculatedProps; + const { text, style, capHeight, backgroundPadding, lineHeight } = + calculatedProps; const tspanValues = text.map((line, i) => { const currentStyle = getSingleValue(style, i); - const capHeightPx = TextSize.convertLengthToPixels(`${capHeight}em`, currentStyle.fontSize); + const capHeightPx = TextSize.convertLengthToPixels( + `${capHeight}em`, + currentStyle.fontSize + ); const currentLineHeight = getSingleValue(lineHeight, i); return { style: currentStyle, @@ -498,9 +552,16 @@ const VictoryLabel = (props) => { const label = renderLabel(calculatedProps, tspanValues); if (props.backgroundStyle) { - const backgroundElement = getBackgroundElement(calculatedProps, tspanValues); + const backgroundElement = getBackgroundElement( + calculatedProps, + tspanValues + ); const children = [backgroundElement, label]; - const backgroundWithLabel = React.cloneElement(props.groupComponent, {}, children); + const backgroundWithLabel = React.cloneElement( + props.groupComponent, + {}, + children + ); return props.renderInPortal ? ( {backgroundWithLabel} @@ -517,12 +578,24 @@ VictoryLabel.role = "label"; VictoryLabel.defaultStyles = defaultStyles; VictoryLabel.propTypes = { active: PropTypes.bool, - angle: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.func]), + angle: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.number, + PropTypes.func + ]), ariaLabel: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), backgroundComponent: PropTypes.element, - backgroundPadding: PropTypes.oneOfType([PropTypes.number, PropTypes.object, PropTypes.array]), + backgroundPadding: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.object, + PropTypes.array + ]), backgroundStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), - capHeight: PropTypes.oneOfType([PropTypes.string, CustomPropTypes.nonNegative, PropTypes.func]), + capHeight: PropTypes.oneOfType([ + PropTypes.string, + CustomPropTypes.nonNegative, + PropTypes.func + ]), className: PropTypes.string, data: PropTypes.array, datum: PropTypes.any, @@ -554,14 +627,23 @@ VictoryLabel.propTypes = { }), style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), - text: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.func, PropTypes.array]), + text: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.number, + PropTypes.func, + PropTypes.array + ]), textAnchor: PropTypes.oneOfType([ PropTypes.oneOf(["start", "middle", "end", "inherit"]), PropTypes.func ]), textComponent: PropTypes.element, title: PropTypes.string, - transform: PropTypes.oneOfType([PropTypes.string, PropTypes.object, PropTypes.func]), + transform: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object, + PropTypes.func + ]), tspanComponent: PropTypes.element, verticalAnchor: PropTypes.oneOfType([ PropTypes.oneOf(["start", "middle", "end"]), diff --git a/packages/victory-core/src/victory-portal/victory-portal.js b/packages/victory-core/src/victory-portal/victory-portal.js index f6ba6a162..6664b0714 100644 --- a/packages/victory-core/src/victory-portal/victory-portal.js +++ b/packages/victory-core/src/victory-portal/victory-portal.js @@ -63,7 +63,9 @@ export default class VictoryPortal extends React.Component { : this.props.children; const { groupComponent } = this.props; const childProps = (children && children.props) || {}; - const standardProps = childProps.groupComponent ? { groupComponent, standalone: false } : {}; + const standardProps = childProps.groupComponent + ? { groupComponent, standalone: false } + : {}; const newProps = defaults( standardProps, childProps, diff --git a/packages/victory-core/src/victory-primitives/arc.js b/packages/victory-core/src/victory-primitives/arc.js index c1bf39a24..d1c8a1103 100644 --- a/packages/victory-core/src/victory-primitives/arc.js +++ b/packages/victory-core/src/victory-primitives/arc.js @@ -18,7 +18,9 @@ const getArcPath = (props) => { const y3 = cy - r * Math.sin(Helpers.degreesToRadians(endAngle)); const largerArcFlag1 = halfAngle - startAngle <= 180 ? 0 : 1; const largerArcFlag2 = endAngle - halfAngle <= 180 ? 0 : 1; - const arcStart = closedPath ? ` M ${cx}, ${cy} L ${x1}, ${y1}` : `M ${x1}, ${y1}`; + const arcStart = closedPath + ? ` M ${cx}, ${cy} L ${x1}, ${y1}` + : `M ${x1}, ${y1}`; const arc1 = `A ${r}, ${r}, 0, ${largerArcFlag1}, 0, ${x2}, ${y2}`; const arc2 = `A ${r}, ${r}, 0, ${largerArcFlag2}, 0, ${x3}, ${y3}`; const arcEnd = closedPath ? "Z" : ""; diff --git a/packages/victory-core/src/victory-primitives/border.js b/packages/victory-core/src/victory-primitives/border.js index 35e7bf70d..382782f5b 100644 --- a/packages/victory-core/src/victory-primitives/border.js +++ b/packages/victory-core/src/victory-primitives/border.js @@ -17,7 +17,10 @@ const evaluateProps = (props) => { const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const desc = Helpers.evaluateProp(props.desc, props); const id = Helpers.evaluateProp(props.id, props); - const style = Helpers.evaluateStyle(assign({ fill: "none" }, props.style), props); + const style = Helpers.evaluateStyle( + assign({ fill: "none" }, props.style), + props + ); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); return assign({}, props, { ariaLabel, desc, id, style, tabIndex }); diff --git a/packages/victory-core/src/victory-primitives/clip-path.js b/packages/victory-core/src/victory-primitives/clip-path.js index 56f2522e1..68a2ae670 100644 --- a/packages/victory-core/src/victory-primitives/clip-path.js +++ b/packages/victory-core/src/victory-primitives/clip-path.js @@ -8,7 +8,10 @@ const ClipPath = (props) => ( ); ClipPath.propTypes = { - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), clipId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }; diff --git a/packages/victory-core/src/victory-primitives/line-segment.js b/packages/victory-core/src/victory-primitives/line-segment.js index 061de26ea..42989eaa3 100644 --- a/packages/victory-core/src/victory-primitives/line-segment.js +++ b/packages/victory-core/src/victory-primitives/line-segment.js @@ -17,7 +17,10 @@ const evaluateProps = (props) => { const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const desc = Helpers.evaluateProp(props.desc, props); const id = Helpers.evaluateProp(props.id, props); - const style = Helpers.evaluateStyle(assign({ stroke: "black" }, props.style), props); + const style = Helpers.evaluateStyle( + assign({ stroke: "black" }, props.style), + props + ); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); return assign({}, props, { ariaLabel, desc, id, style, tabIndex }); diff --git a/packages/victory-core/src/victory-primitives/point.js b/packages/victory-core/src/victory-primitives/point.js index c5e14e0c9..f6503f0a0 100644 --- a/packages/victory-core/src/victory-primitives/point.js +++ b/packages/victory-core/src/victory-primitives/point.js @@ -23,7 +23,9 @@ const getPath = (props) => { cross: pathHelpers.cross }; const symbolFunction = - typeof pathFunctions[symbol] === "function" ? pathFunctions[symbol] : pathFunctions.circle; + typeof pathFunctions[symbol] === "function" + ? pathFunctions[symbol] + : pathFunctions.circle; return symbolFunction(x, y, size); }; @@ -46,7 +48,15 @@ const evaluateProps = (props) => { const symbol = Helpers.evaluateProp(props.symbol, props); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); - return assign({}, props, { ariaLabel, desc, id, size, style, symbol, tabIndex }); + return assign({}, props, { + ariaLabel, + desc, + id, + size, + style, + symbol, + tabIndex + }); }; const Point = (props) => { diff --git a/packages/victory-core/src/victory-primitives/whisker.js b/packages/victory-core/src/victory-primitives/whisker.js index eda8bc3a2..83ac291c6 100644 --- a/packages/victory-core/src/victory-primitives/whisker.js +++ b/packages/victory-core/src/victory-primitives/whisker.js @@ -56,11 +56,19 @@ const Whisker = (props) => { return React.cloneElement(groupComponent, {}, [ React.cloneElement( lineComponent, - assign({ key: "major-whisker", "aria-label": ariaLabel }, baseProps, majorWhisker) + assign( + { key: "major-whisker", "aria-label": ariaLabel }, + baseProps, + majorWhisker + ) ), React.cloneElement( lineComponent, - assign({ key: "minor-whisker", "aria-label": ariaLabel }, baseProps, minorWhisker) + assign( + { key: "minor-whisker", "aria-label": ariaLabel }, + baseProps, + minorWhisker + ) ) ]); }; diff --git a/packages/victory-core/src/victory-theme/grayscale.js b/packages/victory-core/src/victory-theme/grayscale.js index 8ccc1af50..4faf212a5 100644 --- a/packages/victory-core/src/victory-theme/grayscale.js +++ b/packages/victory-core/src/victory-theme/grayscale.js @@ -3,7 +3,15 @@ import { assign } from "lodash"; // * // * Colors // * -const colors = ["#252525", "#525252", "#737373", "#969696", "#bdbdbd", "#d9d9d9", "#f0f0f0"]; +const colors = [ + "#252525", + "#525252", + "#737373", + "#969696", + "#bdbdbd", + "#d9d9d9", + "#f0f0f0" +]; const charcoal = "#252525"; const grey = "#969696"; @@ -241,7 +249,10 @@ export default { stroke: "transparent", strokeWidth: 0 }, - labels: assign({}, baseLabelStyles, { padding: 5, pointerEvents: "none" }), + labels: assign({}, baseLabelStyles, { + padding: 5, + pointerEvents: "none" + }), flyout: { stroke: charcoal, strokeWidth: 1, diff --git a/packages/victory-core/src/victory-theme/material.js b/packages/victory-core/src/victory-theme/material.js index 5b2529e1c..947287bc3 100644 --- a/packages/victory-core/src/victory-theme/material.js +++ b/packages/victory-core/src/victory-theme/material.js @@ -9,7 +9,14 @@ const lime300 = "#DCE775"; const lightGreen500 = "#8BC34A"; const teal700 = "#00796B"; const cyan900 = "#006064"; -const colors = [deepOrange600, yellow200, lime300, lightGreen500, teal700, cyan900]; +const colors = [ + deepOrange600, + yellow200, + lime300, + lightGreen500, + teal700, + cyan900 +]; const blueGrey50 = "#ECEFF1"; const blueGrey300 = "#90A4AE"; const blueGrey700 = "#455A64"; @@ -270,7 +277,10 @@ export default { stroke: "transparent", strokeWidth: 0 }, - labels: assign({}, baseLabelStyles, { padding: 5, pointerEvents: "none" }), + labels: assign({}, baseLabelStyles, { + padding: 5, + pointerEvents: "none" + }), flyout: { stroke: grey900, strokeWidth: 1, diff --git a/packages/victory-core/src/victory-transition/victory-transition.js b/packages/victory-core/src/victory-transition/victory-transition.js index ba1bef998..eaa68c9b4 100644 --- a/packages/victory-core/src/victory-transition/victory-transition.js +++ b/packages/victory-core/src/victory-transition/victory-transition.js @@ -61,8 +61,12 @@ export default class VictoryTransition extends React.Component { } else { const oldChildren = React.Children.toArray(props.children); const nextChildren = React.Children.toArray(nextProps.children); - const { nodesWillExit, nodesWillEnter, childrenTransitions, nodesShouldEnter } = - Transitions.getInitialTransitionState(oldChildren, nextChildren); + const { + nodesWillExit, + nodesWillEnter, + childrenTransitions, + nodesShouldEnter + } = Transitions.getInitialTransitionState(oldChildren, nextChildren); return { nodesWillExit, nodesWillEnter, @@ -78,10 +82,13 @@ export default class VictoryTransition extends React.Component { const getChildDomains = (children) => { return children.reduce((memo, child) => { if (child.type && isFunction(child.type.getDomain)) { - const childDomain = child.props && child.type.getDomain(child.props, axis); + const childDomain = + child.props && child.type.getDomain(child.props, axis); return childDomain ? memo.concat(childDomain) : memo; } else if (child.props && child.props.children) { - return memo.concat(getChildDomains(React.Children.toArray(child.props.children))); + return memo.concat( + getChildDomains(React.Children.toArray(child.props.children)) + ); } return memo; }, []); @@ -98,7 +105,10 @@ export default class VictoryTransition extends React.Component { const childDomains = getChildDomains([child]); return childDomains.length === 0 ? [0, 1] - : [Collection.getMinValue(childDomains), Collection.getMaxValue(childDomains)]; + : [ + Collection.getMinValue(childDomains), + Collection.getMaxValue(childDomains) + ]; } } @@ -106,7 +116,9 @@ export default class VictoryTransition extends React.Component { if (!this.state) { return this.props; } - return this.state.nodesWillExit ? this.state.oldProps || this.props : this.props; + return this.state.nodesWillExit + ? this.state.oldProps || this.props + : this.props; } pickDomainProps(props) { @@ -116,7 +128,9 @@ export default class VictoryTransition extends React.Component { ? parentState.nextProps || this.state.nextProps || props : props; } - return this.continuous && this.state.nodesWillExit ? this.state.nextProps || props : props; + return this.continuous && this.state.nodesWillExit + ? this.state.nextProps || props + : props; } getClipWidth(props, child) { @@ -124,7 +138,9 @@ export default class VictoryTransition extends React.Component { const range = Helpers.getRange(child.props, "x"); return range ? Math.abs(range[1] - range[0]) : props.width; }; - const clipWidth = this.transitionProps ? this.transitionProps.clipWidth : undefined; + const clipWidth = this.transitionProps + ? this.transitionProps.clipWidth + : undefined; return clipWidth !== undefined ? clipWidth : getDefaultClipWidth(); } @@ -144,10 +160,16 @@ export default class VictoryTransition extends React.Component { y: this.getDomainFromChildren(props, "y") }; const clipWidth = this.getClipWidth(props, child); - const combinedProps = defaults({ domain, clipWidth }, transitionProps, child.props); + const combinedProps = defaults( + { domain, clipWidth }, + transitionProps, + child.props + ); const animationWhitelist = props.animationWhitelist || []; const whitelist = animationWhitelist.concat(["clipWidth"]); - const propsToAnimate = whitelist.length ? pick(combinedProps, whitelist) : combinedProps; + const propsToAnimate = whitelist.length + ? pick(combinedProps, whitelist) + : combinedProps; return ( {(newProps) => { @@ -159,12 +181,20 @@ export default class VictoryTransition extends React.Component { : child.props.groupComponent; return React.cloneElement( child, - defaults({ animate: null, animating: true, groupComponent }, newProps, combinedProps) + defaults( + { animate: null, animating: true, groupComponent }, + newProps, + combinedProps + ) ); } return React.cloneElement( child, - defaults({ animate: null, animating: true }, newProps, combinedProps) + defaults( + { animate: null, animating: true }, + newProps, + combinedProps + ) ); }} diff --git a/packages/victory-core/src/victory-util/add-events.js b/packages/victory-core/src/victory-util/add-events.js index e5eb195ba..c1790ef19 100644 --- a/packages/victory-core/src/victory-util/add-events.js +++ b/packages/victory-core/src/victory-util/add-events.js @@ -78,9 +78,15 @@ export default (WrappedComponent, options) => { const calculatedState = this.getStateChanges(prevProps); this.calculatedState = calculatedState; const globalEventKeys = keys(this.globalEvents); - const removedGlobalEventKeys = difference(this.prevGlobalEventKeys, globalEventKeys); + const removedGlobalEventKeys = difference( + this.prevGlobalEventKeys, + globalEventKeys + ); removedGlobalEventKeys.forEach((key) => this.removeGlobalListener(key)); - const addedGlobalEventKeys = difference(globalEventKeys, this.prevGlobalEventKeys); + const addedGlobalEventKeys = difference( + globalEventKeys, + this.prevGlobalEventKeys + ); addedGlobalEventKeys.forEach((key) => this.addGlobalListener(key)); this.prevGlobalEventKeys = globalEventKeys; } @@ -95,7 +101,10 @@ export default (WrappedComponent, options) => { return listener && listener(Events.emulateReactEvent(event)); }; this.boundGlobalEvents[key] = boundListener; - window.addEventListener(Events.getGlobalEventNameFromKey(key), boundListener); + window.addEventListener( + Events.getGlobalEventNameFromKey(key), + boundListener + ); } removeGlobalListener(key) { @@ -131,7 +140,9 @@ export default (WrappedComponent, options) => { } else { return component.index !== undefined ? getState(component.index, component.name) - : this.dataKeys.map((key) => getState(key, component.name)).filter(Boolean); + : this.dataKeys + .map((key) => getState(key, component.name)) + .filter(Boolean); } }) .filter(Boolean); @@ -140,10 +151,15 @@ export default (WrappedComponent, options) => { applyExternalMutations(props, externalMutations) { if (!isEmpty(externalMutations)) { - const callbacks = props.externalEventMutations.reduce((memo, mutation) => { - memo = isFunction(mutation.callback) ? memo.concat(mutation.callback) : memo; - return memo; - }, []); + const callbacks = props.externalEventMutations.reduce( + (memo, mutation) => { + memo = isFunction(mutation.callback) + ? memo.concat(mutation.callback) + : memo; + return memo; + }, + [] + ); const compiledCallbacks = callbacks.length ? () => { callbacks.forEach((c) => c()); @@ -179,7 +195,11 @@ export default (WrappedComponent, options) => { const { sharedEvents, externalEventMutations } = props; return isEmpty(externalEventMutations) || sharedEvents ? undefined - : Events.getExternalMutations(externalEventMutations, this.baseProps, this.state); + : Events.getExternalMutations( + externalEventMutations, + this.baseProps, + this.state + ); } cacheValues(obj) { @@ -194,7 +214,9 @@ export default (WrappedComponent, options) => { const parentState = this.getEventState("parent", "parent"); const baseParentProps = defaults({}, parentState, sharedParentState); const parentPropsList = baseParentProps.parentControlledProps; - const parentProps = parentPropsList ? pick(baseParentProps, parentPropsList) : {}; + const parentProps = parentPropsList + ? pick(baseParentProps, parentPropsList) + : {}; const modifiedProps = defaults({}, parentProps, props); return isFunction(WrappedComponent.getBaseProps) @@ -216,7 +238,9 @@ export default (WrappedComponent, options) => { const key = (this.dataKeys && this.dataKeys[index]) || index; const id = `${name}-${type}-${key}`; - const baseProps = (this.baseProps[key] && this.baseProps[key][type]) || this.baseProps[key]; + const baseProps = + (this.baseProps[key] && this.baseProps[key][type]) || + this.baseProps[key]; if (!baseProps && !this.hasEvents) { return undefined; @@ -247,7 +271,9 @@ export default (WrappedComponent, options) => { renderContainer(component, children) { const isContainer = component.type && component.type.role === "container"; - const parentProps = isContainer ? this.getComponentProps(component, "parent", "parent") : {}; + const parentProps = isContainer + ? this.getComponentProps(component, "parent", "parent") + : {}; if (parentProps.events) { this.globalEvents = Events.getGlobalEvents(parentProps.events); parentProps.events = Events.omitGlobalEvents(parentProps.events); @@ -262,7 +288,10 @@ export default (WrappedComponent, options) => { : defaultAnimationWhitelist; return ( - + {React.createElement(this.constructor, props)} ); @@ -273,32 +302,56 @@ export default (WrappedComponent, options) => { const { dataComponent, labelComponent, groupComponent } = props; const dataKeys = without(this.dataKeys, "all"); const labelComponents = dataKeys.reduce((memo, key) => { - const labelProps = this.getComponentProps(labelComponent, "labels", key); - if (labelProps && labelProps.text !== undefined && labelProps.text !== null) { + const labelProps = this.getComponentProps( + labelComponent, + "labels", + key + ); + if ( + labelProps && + labelProps.text !== undefined && + labelProps.text !== null + ) { memo = memo.concat(React.cloneElement(labelComponent, labelProps)); } return memo; }, []); const dataProps = this.getComponentProps(dataComponent, "data", "all"); - const children = [React.cloneElement(dataComponent, dataProps), ...labelComponents]; + const children = [ + React.cloneElement(dataComponent, dataProps), + ...labelComponents + ]; return this.renderContainer(groupComponent, children); } renderData(props, shouldRenderDatum = datumHasXandY) { const { dataComponent, labelComponent, groupComponent } = props; - const dataComponents = this.dataKeys.reduce((validDataComponents, _dataKey, index) => { - const dataProps = this.getComponentProps(dataComponent, "data", index); - if (shouldRenderDatum(dataProps.datum)) { - validDataComponents.push(React.cloneElement(dataComponent, dataProps)); - } - return validDataComponents; - }, []); + const dataComponents = this.dataKeys.reduce( + (validDataComponents, _dataKey, index) => { + const dataProps = this.getComponentProps( + dataComponent, + "data", + index + ); + if (shouldRenderDatum(dataProps.datum)) { + validDataComponents.push( + React.cloneElement(dataComponent, dataProps) + ); + } + return validDataComponents; + }, + [] + ); const labelComponents = this.dataKeys .map((_dataKey, index) => { - const labelProps = this.getComponentProps(labelComponent, "labels", index); + const labelProps = this.getComponentProps( + labelComponent, + "labels", + index + ); if (labelProps.text !== undefined && labelProps.text !== null) { return React.cloneElement(labelComponent, labelProps); } diff --git a/packages/victory-core/src/victory-util/axis.js b/packages/victory-core/src/victory-util/axis.js index 50989952f..dbc22c4bb 100644 --- a/packages/victory-core/src/victory-util/axis.js +++ b/packages/victory-core/src/victory-util/axis.js @@ -42,7 +42,9 @@ function findAxisComponents(childComponents, predicate) { if (child.type && child.type.role === "axis" && predicate(child)) { return memo.concat(child); } else if (child.props && child.props.children) { - return memo.concat(findAxes(React.Children.toArray(child.props.children))); + return memo.concat( + findAxes(React.Children.toArray(child.props.children)) + ); } return memo; }, []); @@ -74,7 +76,9 @@ function getAxisComponent(childComponents, axis) { */ function getAxisComponentsWithParent(childComponents, type) { const matchesType = (child) => { - return type === "dependent" ? child.props.dependentAxis : !child.props.dependentAxis; + return type === "dependent" + ? child.props.dependentAxis + : !child.props.dependentAxis; }; const findComponents = (children) => { @@ -82,7 +86,9 @@ function getAxisComponentsWithParent(childComponents, type) { if (child.type && child.type.role === "axis" && matchesType(child)) { return memo.concat(child); } else if (child.props && child.props.children) { - const childAxis = findComponents(React.Children.toArray(child.props.children)); + const childAxis = findComponents( + React.Children.toArray(child.props.children) + ); return childAxis.length > 0 ? memo.concat(child) : memo; } return memo; @@ -121,7 +127,8 @@ function getOriginSign(origin, domain) { * @returns {Boolean} true when the axis is vertical */ function isVertical(props) { - const orientation = props.orientation || (props.dependentAxis ? "left" : "bottom"); + const orientation = + props.orientation || (props.dependentAxis ? "left" : "bottom"); const vertical = { top: false, bottom: false, left: true, right: true }; return vertical[orientation]; } @@ -131,16 +138,22 @@ function isVertical(props) { * @returns {Boolean} true when tickValues contain strings */ function stringTicks(props) { - return props.tickValues !== undefined && Collection.containsStrings(props.tickValues); + return ( + props.tickValues !== undefined && + Collection.containsStrings(props.tickValues) + ); } function getDefaultTickFormat(props) { const { tickValues } = props; const axis = getAxis(props); const stringMap = props.stringMap && props.stringMap[axis]; - const fallbackFormat = tickValues && !Collection.containsDates(tickValues) ? (x) => x : undefined; + const fallbackFormat = + tickValues && !Collection.containsDates(tickValues) ? (x) => x : undefined; if (!stringMap) { - return stringTicks(props) ? (x, index) => tickValues[index] : fallbackFormat; + return stringTicks(props) + ? (x, index) => tickValues[index] + : fallbackFormat; } else { const invertedStringMap = stringMap && invert(stringMap); const tickValueArray = orderBy(values(stringMap), (n) => n); @@ -175,7 +188,9 @@ function getTickArray(props) { if (!tickFormat || !Array.isArray(tickFormat)) { return undefined; } - return Collection.containsStrings(tickFormat) ? tickFormat.map((t, i) => i) : tickFormat; + return Collection.containsStrings(tickFormat) + ? tickFormat.map((t, i) => i) + : tickFormat; }; let ticks = tickValues; @@ -183,7 +198,9 @@ function getTickArray(props) { ticks = getStringTicks(props); } if (tickValues && Collection.containsStrings(tickValues)) { - ticks = stringMap ? tickValues.map((tick) => stringMap[tick]) : range(1, tickValues.length + 1); + ticks = stringMap + ? tickValues.map((tick) => stringMap[tick]) + : range(1, tickValues.length + 1); } const tickArray = ticks ? uniq(ticks) : getTicksFromFormat(props); const buildTickArray = (arr) => { @@ -192,7 +209,10 @@ function getTickArray(props) { if (arr) { arr.forEach(function (t, index) { if (Array.isArray(domain)) { - if (t >= Collection.getMinValue(domain) && t <= Collection.getMaxValue(domain)) { + if ( + t >= Collection.getMinValue(domain) && + t <= Collection.getMaxValue(domain) + ) { newTickArray.push({ value: t, index @@ -208,7 +228,9 @@ function getTickArray(props) { return newTickArray; } else return undefined; }; - return Array.isArray(tickArray) && tickArray.length ? buildTickArray(tickArray) : undefined; + return Array.isArray(tickArray) && tickArray.length + ? buildTickArray(tickArray) + : undefined; } function getTickFormat(props, scale) { @@ -218,12 +240,18 @@ function getTickFormat(props, scale) { if (!tickFormat) { const defaultTickFormat = getDefaultTickFormat(props); const scaleTickFormat = - scale.tickFormat && isFunction(scale.tickFormat) ? scale.tickFormat() : (x) => x; + scale.tickFormat && isFunction(scale.tickFormat) + ? scale.tickFormat() + : (x) => x; return defaultTickFormat || scaleTickFormat; } else if (tickFormat && Array.isArray(tickFormat)) { const tickArray = getTickArray(props); - const tickArrayIndices = tickArray ? tickArray.map((v) => v.index) : undefined; - const filteredTickFormat = tickFormat.filter((t, index) => tickArrayIndices.includes(index)); + const tickArrayIndices = tickArray + ? tickArray.map((v) => v.index) + : undefined; + const filteredTickFormat = tickFormat.filter((t, index) => + tickArrayIndices.includes(index) + ); return (x, index) => filteredTickFormat[index]; } else if (tickFormat && isFunction(tickFormat)) { const applyStringTicks = (tick, index, ticks) => { @@ -256,7 +284,9 @@ function getTicks(props, scale, filterZero) { const defaultTickCount = tickCount || 5; const scaleTicks = scale.ticks(defaultTickCount); const scaledTickArray = - Array.isArray(scaleTicks) && scaleTicks.length ? scaleTicks : scale.domain(); + Array.isArray(scaleTicks) && scaleTicks.length + ? scaleTicks + : scale.domain(); const ticks = downsampleTicks(scaledTickArray, tickCount); if (filterZero) { const filteredTicks = includes(ticks, 0) ? without(ticks, 0) : ticks; @@ -286,7 +316,9 @@ function getDomainFromData(props, axis) { const tickStrings = stringTicks(props); const ticks = tickValues.map((value) => +value); const defaultMin = tickStrings ? 1 : Collection.getMinValue(ticks); - const defaultMax = tickStrings ? tickValues.length : Collection.getMaxValue(ticks); + const defaultMax = tickStrings + ? tickValues.length + : Collection.getMaxValue(ticks); const min = minDomain !== undefined ? minDomain : defaultMin; const max = maxDomain !== undefined ? maxDomain : defaultMax; const initialDomain = Domain.getDomainFromMinMax(min, max); @@ -324,7 +356,9 @@ function getAxisValue(props, axis) { const stringMapAxis = axis === "x" ? "y" : "x"; const stringMap = isObject(props.stringMap) && props.stringMap[stringMapAxis]; const axisValue = - stringMap && typeof props.axisValue === "string" ? stringMap[props.axisValue] : props.axisValue; + stringMap && typeof props.axisValue === "string" + ? stringMap[props.axisValue] + : props.axisValue; return scale(axisValue); } @@ -343,7 +377,11 @@ function modifyProps(props, fallbackProps) { } const axisTheme = defaults({}, props.theme[role], props.theme.axis); const theme = assign({}, props.theme, { axis: axisTheme }); - return Helpers.modifyProps(assign({}, props, { theme }), fallbackProps, "axis"); + return Helpers.modifyProps( + assign({}, props, { theme }), + fallbackProps, + "axis" + ); } export default { diff --git a/packages/victory-core/src/victory-util/collection.js b/packages/victory-core/src/victory-util/collection.js index b66dfb895..cd4706127 100644 --- a/packages/victory-core/src/victory-util/collection.js +++ b/packages/victory-core/src/victory-util/collection.js @@ -6,19 +6,31 @@ function isNonEmptyArray(collection) { } function containsStrings(collection) { - return Array.isArray(collection) && collection.some((value) => typeof value === "string"); + return ( + Array.isArray(collection) && + collection.some((value) => typeof value === "string") + ); } function containsDates(collection) { - return Array.isArray(collection) && collection.some((value) => value instanceof Date); + return ( + Array.isArray(collection) && + collection.some((value) => value instanceof Date) + ); } function containsNumbers(collection) { - return Array.isArray(collection) && collection.some((value) => typeof value === "number"); + return ( + Array.isArray(collection) && + collection.some((value) => typeof value === "number") + ); } function containsOnlyStrings(collection) { - return isNonEmptyArray(collection) && collection.every((value) => typeof value === "string"); + return ( + isNonEmptyArray(collection) && + collection.every((value) => typeof value === "string") + ); } function isArrayOfArrays(collection) { @@ -31,12 +43,16 @@ function removeUndefined(arr) { function getMaxValue(arr, ...values) { const array = arr.concat(values); - return containsDates(array) ? new Date(Math.max(...array)) : Math.max(...array); + return containsDates(array) + ? new Date(Math.max(...array)) + : Math.max(...array); } function getMinValue(arr, ...values) { const array = arr.concat(values); - return containsDates(array) ? new Date(Math.min(...array)) : Math.min(...array); + return containsDates(array) + ? new Date(Math.min(...array)) + : Math.min(...array); } export default { diff --git a/packages/victory-core/src/victory-util/common-props.js b/packages/victory-core/src/victory-util/common-props.js index 776787d8d..f2766fe0e 100644 --- a/packages/victory-core/src/victory-util/common-props.js +++ b/packages/victory-core/src/victory-util/common-props.js @@ -17,7 +17,10 @@ const dataProps = { samples: CustomPropTypes.nonNegative, sortKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), @@ -29,19 +32,28 @@ const dataProps = { }), x: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), y: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), y0: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]) @@ -72,15 +84,24 @@ const baseProps = { ]), domainPadding: PropTypes.oneOfType([ PropTypes.shape({ - x: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]), - y: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]) + x: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.arrayOf(PropTypes.number) + ]), + y: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.arrayOf(PropTypes.number) + ]) }), PropTypes.number, PropTypes.arrayOf(PropTypes.number) ]), eventKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), events: PropTypes.arrayOf( @@ -88,7 +109,10 @@ const baseProps = { target: PropTypes.oneOf(["data", "labels", "parent"]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -100,7 +124,10 @@ const baseProps = { childName: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), mutation: PropTypes.function, diff --git a/packages/victory-core/src/victory-util/data.js b/packages/victory-core/src/victory-util/data.js index 801877d9d..073bd55c6 100644 --- a/packages/victory-core/src/victory-util/data.js +++ b/packages/victory-core/src/victory-util/data.js @@ -40,7 +40,9 @@ function getLength(data) { // Returns generated data for a given axis based on domain and sample from props function generateDataArray(props, axis) { - const propsDomain = isPlainObject(props.domain) ? props.domain[axis] : props.domain; + const propsDomain = isPlainObject(props.domain) + ? props.domain[axis] + : props.domain; const domain = propsDomain || Scale.getBaseScale(props, axis).domain(); const samples = props.samples || 1; const domainMax = Math.max(...domain); @@ -123,7 +125,8 @@ function formatDataFromDomain(dataset, domain, defaultBaseline) { if (!exists(value)) return datum; // value only and less than min domain or greater than max domain - if (!exists(baseline) && (isUnderMinY(value) || isOverMaxY(value))) _y = null; + if (!exists(baseline) && (isUnderMinY(value) || isOverMaxY(value))) + _y = null; // baseline and value are both less than min domain or both greater than max domain if ( @@ -183,7 +186,11 @@ function createStringMap(props, axis) { const stringsFromCategories = getStringsFromCategories(props, axis); const stringsFromData = getStringsFromData(props, axis); - const allStrings = uniq([...stringsFromAxes, ...stringsFromCategories, ...stringsFromData]); + const allStrings = uniq([ + ...stringsFromAxes, + ...stringsFromCategories, + ...stringsFromData + ]); return allStrings.length === 0 ? null : allStrings.reduce((memo, string, index) => { @@ -223,7 +230,8 @@ function downsample(data, maxPoints, startingIndex = 0) { * @returns {Array} the formatted data */ function formatData(dataset, props, expectedKeys) { - const isArrayOrIterable = Array.isArray(dataset) || Immutable.isIterable(dataset); + const isArrayOrIterable = + Array.isArray(dataset) || Immutable.isIterable(dataset); if (!isArrayOrIterable || getLength(dataset) < 1) { return []; } @@ -232,7 +240,9 @@ function formatData(dataset, props, expectedKeys) { expectedKeys = Array.isArray(expectedKeys) ? expectedKeys : defaultKeys; const createAccessor = (name) => { - return Helpers.createAccessor(props[name] !== undefined ? props[name] : name); + return Helpers.createAccessor( + props[name] !== undefined ? props[name] : name + ); }; const accessor = expectedKeys.reduce((memo, type) => { @@ -250,9 +260,18 @@ function formatData(dataset, props, expectedKeys) { if (preformattedData === false) { // stringMap is not required if the data is preformatted stringMap = { - x: expectedKeys.indexOf("x") !== -1 ? createStringMap(props, "x") : undefined, - y: expectedKeys.indexOf("y") !== -1 ? createStringMap(props, "y") : undefined, - y0: expectedKeys.indexOf("y0") !== -1 ? createStringMap(props, "y") : undefined + x: + expectedKeys.indexOf("x") !== -1 + ? createStringMap(props, "x") + : undefined, + y: + expectedKeys.indexOf("y") !== -1 + ? createStringMap(props, "y") + : undefined, + y0: + expectedKeys.indexOf("y0") !== -1 + ? createStringMap(props, "y") + : undefined }; } @@ -264,7 +283,10 @@ function formatData(dataset, props, expectedKeys) { const fallbackValues = { x: index, y: datum }; const processedValues = expectedKeys.reduce((memo, type) => { const processedValue = accessor[type](datum); - const value = processedValue !== undefined ? processedValue : fallbackValues[type]; + const value = + processedValue !== undefined + ? processedValue + : fallbackValues[type]; if (value !== undefined) { if (typeof value === "string" && stringMap[type]) { memo[`${type}Name`] = value; @@ -321,7 +343,9 @@ function getCategories(props, axis) { * @returns {Array} an array of data */ function getData(props) { - return props.data ? formatData(props.data, props) : formatData(generateData(props), props); + return props.data + ? formatData(props.data, props) + : formatData(generateData(props), props); } /** @@ -352,7 +376,8 @@ function getStringsFromCategories(props, axis) { return []; } const categories = getCategories(props, axis); - const categoryStrings = categories && categories.filter((val) => typeof val === "string"); + const categoryStrings = + categories && categories.filter((val) => typeof val === "string"); return categoryStrings ? Collection.removeUndefined(categoryStrings) : []; } @@ -363,7 +388,8 @@ function getStringsFromCategories(props, axis) { * @returns {Array} an array of strings */ function getStringsFromData(props, axis) { - const isArrayOrIterable = Array.isArray(props.data) || Immutable.isIterable(props.data); + const isArrayOrIterable = + Array.isArray(props.data) || Immutable.isIterable(props.data); if (!isArrayOrIterable) { return []; } diff --git a/packages/victory-core/src/victory-util/default-transitions.js b/packages/victory-core/src/victory-util/default-transitions.js index 20c9d3632..424bd7026 100644 --- a/packages/victory-core/src/victory-util/default-transitions.js +++ b/packages/victory-core/src/victory-util/default-transitions.js @@ -28,7 +28,11 @@ export default { const adj = index === 0 ? data[index + 1] : data[index - 1]; return adj[attr]; }; - return { _x: adjacent("_x"), _y: adjacent("_y"), _y0: adjacent("_y0") }; + return { + _x: adjacent("_x"), + _y: adjacent("_y"), + _y0: adjacent("_y0") + }; } }, onEnter: { @@ -38,9 +42,18 @@ export default { const adj = index === 0 ? data[index + 1] : data[index - 1]; return adj[attr]; }; - return { _x: adjacent("_x"), _y: adjacent("_y"), _y0: adjacent("_y0") }; + return { + _x: adjacent("_x"), + _y: adjacent("_y"), + _y0: adjacent("_y0") + }; }, - after: (datum) => ({ _x: datum._x, _y: datum._y, _y1: datum._y1, _y0: datum._y0 }) + after: (datum) => ({ + _x: datum._x, + _y: datum._y, + _y1: datum._y1, + _y0: datum._y0 + }) } }; }, diff --git a/packages/victory-core/src/victory-util/domain.js b/packages/victory-core/src/victory-util/domain.js index 07b90628e..627a25300 100644 --- a/packages/victory-core/src/victory-util/domain.js +++ b/packages/victory-core/src/victory-util/domain.js @@ -1,7 +1,14 @@ /* eslint-disable func-style */ /* eslint-disable no-use-before-define */ import React from "react"; -import { flatten, isPlainObject, sortedUniq, isFunction, includes, isDate } from "lodash"; +import { + flatten, + isPlainObject, + sortedUniq, + isFunction, + includes, + isDate +} from "lodash"; import Data from "./data"; import Scale from "./scale"; import Helpers from "./helpers"; @@ -18,7 +25,9 @@ function cleanDomain(domain, props, axis) { const rules = (dom) => { const almostZero = - dom[0] < 0 || dom[1] < 0 ? -1 / Number.MAX_SAFE_INTEGER : 1 / Number.MAX_SAFE_INTEGER; + dom[0] < 0 || dom[1] < 0 + ? -1 / Number.MAX_SAFE_INTEGER + : 1 / Number.MAX_SAFE_INTEGER; const domainOne = dom[0] === 0 ? almostZero : dom[0]; const domainTwo = dom[1] === 0 ? almostZero : dom[1]; return [domainOne, domainTwo]; @@ -48,14 +57,18 @@ function getFlatData(dataset, axis) { } function getExtremeFromData(dataset, axis, type = "min") { - const getExtreme = (arr) => (type === "max" ? Math.max(...arr) : Math.min(...arr)); + const getExtreme = (arr) => + type === "max" ? Math.max(...arr) : Math.min(...arr); const initialValue = type === "max" ? -Infinity : Infinity; let containsDate = false; const result = flatten(dataset).reduce((memo, datum) => { - const current0 = datum[`_${axis}0`] !== undefined ? datum[`_${axis}0`] : datum[`_${axis}`]; - const current1 = datum[`_${axis}1`] !== undefined ? datum[`_${axis}1`] : datum[`_${axis}`]; + const current0 = + datum[`_${axis}0`] !== undefined ? datum[`_${axis}0`] : datum[`_${axis}`]; + const current1 = + datum[`_${axis}1`] !== undefined ? datum[`_${axis}1`] : datum[`_${axis}`]; const current = getExtreme([current0, current1]); - containsDate = containsDate || current0 instanceof Date || current1 instanceof Date; + containsDate = + containsDate || current0 instanceof Date || current1 instanceof Date; return getExtreme([memo, current]); }, initialValue); return containsDate ? new Date(result) : result; @@ -80,7 +93,10 @@ function padDomain(domain, props, axis) { const range = Helpers.getRange(props, currentAxis); const rangeExtent = Math.abs(range[0] - range[1]); - const paddedRangeExtent = Math.max(rangeExtent - padding.left - padding.right, 1); + const paddedRangeExtent = Math.max( + rangeExtent - padding.left - padding.right, + 1 + ); const paddedDomainExtent = (Math.abs(max.valueOf() - min.valueOf()) / paddedRangeExtent) * rangeExtent; @@ -94,15 +110,19 @@ function padDomain(domain, props, axis) { max: max.valueOf() + simplePadding.right }; - const singleQuadrantDomainPadding = isPlainObject(props.singleQuadrantDomainPadding) + const singleQuadrantDomainPadding = isPlainObject( + props.singleQuadrantDomainPadding + ) ? props.singleQuadrantDomainPadding[axis] : props.singleQuadrantDomainPadding; - const addsQuadrants = (min >= 0 && paddedDomain.min <= 0) || (max <= 0 && paddedDomain.max >= 0); + const addsQuadrants = + (min >= 0 && paddedDomain.min <= 0) || (max <= 0 && paddedDomain.max >= 0); const adjust = (val, type) => { const coerce = - (type === "min" && min >= 0 && val <= 0) || (type === "max" && max <= 0 && val >= 0); + (type === "min" && min >= 0 && val <= 0) || + (type === "max" && max <= 0 && val >= 0); return coerce ? 0 : val; }; @@ -121,8 +141,12 @@ function padDomain(domain, props, axis) { // re-calculate padding, taking the adjusted domain into account const finalPadding = { - left: (Math.abs(adjustedDomain.max - adjustedDomain.min) * padding.left) / rangeExtent, - right: (Math.abs(adjustedDomain.max - adjustedDomain.min) * padding.right) / rangeExtent + left: + (Math.abs(adjustedDomain.max - adjustedDomain.min) * padding.left) / + rangeExtent, + right: + (Math.abs(adjustedDomain.max - adjustedDomain.min) * padding.right) / + rangeExtent }; // Adjust the domain by the final padding @@ -157,7 +181,9 @@ function createDomainFunction(getDomainFromDataFunction, formatDomainFunction) { getDomainFromDataFunction = isFunction(getDomainFromDataFunction) ? getDomainFromDataFunction : getDomainFromData; - formatDomainFunction = isFunction(formatDomainFunction) ? formatDomainFunction : formatDomain; + formatDomainFunction = isFunction(formatDomainFunction) + ? formatDomainFunction + : formatDomain; return (props, axis) => { const propsDomain = getDomainFromProps(props, axis); if (propsDomain) { @@ -217,9 +243,17 @@ function getDomainFromCategories(props, axis, categories) { memo[string] = index + 1; return memo; }, {}); - const categoryValues = stringMap ? categories.map((value) => stringMap[value]) : categories; - const min = minDomain !== undefined ? minDomain : Collection.getMinValue(categoryValues); - const max = maxDomain !== undefined ? maxDomain : Collection.getMaxValue(categoryValues); + const categoryValues = stringMap + ? categories.map((value) => stringMap[value]) + : categories; + const min = + minDomain !== undefined + ? minDomain + : Collection.getMinValue(categoryValues); + const max = + maxDomain !== undefined + ? maxDomain + : Collection.getMaxValue(categoryValues); const categoryDomain = getDomainFromMinMax(min, max); return polar && axis === "x" && Math.abs(startAngle - endAngle) === 360 ? getSymmetricDomain(categoryDomain, categoryValues) @@ -243,8 +277,14 @@ function getDomainFromData(props, axis, dataset) { ? getDomainFromMinMax(minDomain, maxDomain) : undefined; } - const min = minDomain !== undefined ? minDomain : getExtremeFromData(dataset, axis, "min"); - const max = maxDomain !== undefined ? maxDomain : getExtremeFromData(dataset, axis, "max"); + const min = + minDomain !== undefined + ? minDomain + : getExtremeFromData(dataset, axis, "min"); + const max = + maxDomain !== undefined + ? maxDomain + : getExtremeFromData(dataset, axis, "max"); const domain = getDomainFromMinMax(min, max); return polar && axis === "x" && Math.abs(startAngle - endAngle) === 360 ? getSymmetricDomain(domain, getFlatData(dataset, axis)) @@ -261,10 +301,17 @@ function getDomainFromMinMax(min, max) { const getSinglePointDomain = (val) => { // d3-scale does not properly resolve very small differences. // eslint-disable-next-line no-magic-numbers - const verySmallNumber = val === 0 ? 2 * Math.pow(10, -10) : Math.pow(10, -10); + const verySmallNumber = + val === 0 ? 2 * Math.pow(10, -10) : Math.pow(10, -10); const verySmallDate = 1; - const minVal = val instanceof Date ? new Date(+val - verySmallDate) : +val - verySmallNumber; - const maxVal = val instanceof Date ? new Date(+val + verySmallDate) : +val + verySmallNumber; + const minVal = + val instanceof Date + ? new Date(+val - verySmallDate) + : +val - verySmallNumber; + const maxVal = + val instanceof Date + ? new Date(+val + verySmallDate) + : +val + verySmallNumber; return val === 0 ? [0, maxVal] : [minVal, maxVal]; }; return +min === +max ? getSinglePointDomain(max) : [min, max]; @@ -303,7 +350,10 @@ function getDomainWithZero(props, axis) { } const dataset = Data.getData(props); - const y0Min = dataset.reduce((min, datum) => (datum._y0 < min ? datum._y0 : min), Infinity); + const y0Min = dataset.reduce( + (min, datum) => (datum._y0 < min ? datum._y0 : min), + Infinity + ); const ensureZero = (domain) => { if (axis === "x") { @@ -314,9 +364,13 @@ function getDomainWithZero(props, axis) { const maxDomainProp = getMaxFromProps(props, axis); const minDomainProp = getMinFromProps(props, axis); const max = - maxDomainProp !== undefined ? maxDomainProp : Collection.getMaxValue(domain, defaultMin); + maxDomainProp !== undefined + ? maxDomainProp + : Collection.getMaxValue(domain, defaultMin); const min = - minDomainProp !== undefined ? minDomainProp : Collection.getMinValue(domain, defaultMin); + minDomainProp !== undefined + ? minDomainProp + : Collection.getMinValue(domain, defaultMin); return getDomainFromMinMax(min, max); }; @@ -329,7 +383,10 @@ function getDomainWithZero(props, axis) { return formatDomain(ensureZero(domain), props, axis); }; - return createDomainFunction(getDomainFunction, formatDomainFunction)(props, axis); + return createDomainFunction(getDomainFunction, formatDomainFunction)( + props, + axis + ); } /** diff --git a/packages/victory-core/src/victory-util/events.js b/packages/victory-core/src/victory-util/events.js index f67a32771..799bd70aa 100644 --- a/packages/victory-core/src/victory-util/events.js +++ b/packages/victory-core/src/victory-util/events.js @@ -1,4 +1,14 @@ -import { assign, isEmpty, isFunction, without, pickBy, omitBy, uniq, includes, keys } from "lodash"; +import { + assign, + isEmpty, + isFunction, + without, + pickBy, + omitBy, + uniq, + includes, + keys +} from "lodash"; const GLOBAL_EVENT_REGEX = /^onGlobal(.*)$/; @@ -100,7 +110,9 @@ export default { // applied to the appropriate property on the state object const parseEvent = (eventReturn, eventKey) => { const childNames = - namespace === "parent" ? eventReturn.childName : eventReturn.childName || childType; + namespace === "parent" + ? eventReturn.childName + : eventReturn.childName || childType; const target = eventReturn.target || namespace; // returns all eventKeys to modify for a targeted childName @@ -112,10 +124,17 @@ export default { return baseProps[childName] ? without(keys(baseProps[childName]), "parent") : without(keys(baseProps), "parent"); - } else if (eventReturn.eventKey === undefined && eventKey === "parent") { - return baseProps[childName] ? keys(baseProps[childName]) : keys(baseProps); + } else if ( + eventReturn.eventKey === undefined && + eventKey === "parent" + ) { + return baseProps[childName] + ? keys(baseProps[childName]) + : keys(baseProps); } - return eventReturn.eventKey !== undefined ? eventReturn.eventKey : eventKey; + return eventReturn.eventKey !== undefined + ? eventReturn.eventKey + : eventKey; }; // returns the state object with mutated props applied for a single key @@ -124,8 +143,14 @@ export default { if (!isFunction(eventReturn.mutation)) { return baseState; } - const mutationTargetProps = getTargetProps({ childName, key, target }, "props"); - const mutationTargetState = getTargetProps({ childName, key, target }, "state"); + const mutationTargetProps = getTargetProps( + { childName, key, target }, + "props" + ); + const mutationTargetState = getTargetProps( + { childName, key, target }, + "state" + ); const mutatedProps = eventReturn.mutation( assign({}, mutationTargetProps, mutationTargetState), baseProps @@ -145,7 +170,9 @@ export default { const extendState = (state) => { return target === "parent" ? assign(state, { [key]: assign(state[key], mutatedProps) }) - : assign(state, { [key]: assign(state[key], { [target]: mutatedProps }) }); + : assign(state, { + [key]: assign(state[key], { [target]: mutatedProps }) + }); }; const updateState = (state) => { @@ -168,7 +195,8 @@ export default { }; // returns an entire mutated state for all children - const allChildNames = childNames === "all" ? without(keys(baseProps), "parent") : childNames; + const allChildNames = + childNames === "all" ? without(keys(baseProps), "parent") : childNames; return Array.isArray(allChildNames) ? allChildNames.reduce((memo, childName) => { return assign(memo, getReturnByChild(childName)); @@ -221,7 +249,8 @@ export default { getPartialEvents(events, eventKey, childProps) { return events ? keys(events).reduce((memo, eventName) => { - const appliedEvent = (evt) => events[eventName](evt, childProps, eventKey, eventName); + const appliedEvent = (evt) => + events[eventName](evt, childProps, eventKey, eventName); memo[eventName] = appliedEvent; return memo; }, {}) @@ -238,7 +267,11 @@ export default { ? (state[eventKey] && state[eventKey][namespace]) || state[eventKey] : state[eventKey] && state[eventKey][namespace]; } - return state[childType] && state[childType][eventKey] && state[childType][eventKey][namespace]; + return ( + state[childType] && + state[childType][eventKey] && + state[childType][eventKey][namespace] + ); }, /** @@ -252,7 +285,12 @@ export default { * @return {Object} a object describing all mutations for VictorySharedEvents */ // eslint-disable-next-line max-params - getExternalMutationsWithChildren(mutations, baseProps, baseState, childNames) { + getExternalMutationsWithChildren( + mutations, + baseProps, + baseState, + childNames + ) { baseProps = baseProps || {}; baseState = baseState || {}; @@ -290,8 +328,14 @@ export default { const keyProps = baseProps[eventKey] || {}; if (eventKey === "parent") { const identifier = { eventKey, target: "parent" }; - const mutation = this.getExternalMutation(mutations, keyProps, keyState, identifier); - memo[eventKey] = mutation !== undefined ? assign({}, keyState, mutation) : keyState; + const mutation = this.getExternalMutation( + mutations, + keyProps, + keyState, + identifier + ); + memo[eventKey] = + mutation !== undefined ? assign({}, keyState, mutation) : keyState; } else { // use keys from both state and props so that elements not intially included in baseProps // will be used. (i.e. labels) @@ -305,7 +349,9 @@ export default { identifier ); m[target] = - mutation !== undefined ? assign({}, keyState[target], mutation) : keyState[target]; + mutation !== undefined + ? assign({}, keyState[target], mutation) + : keyState[target]; return pickBy(m, (v) => !isEmpty(v)); }, {}); } @@ -340,20 +386,29 @@ export default { mutations = Array.isArray(mutations) ? mutations : [mutations]; let scopedMutations = mutations; if (identifier.childName) { - scopedMutations = mutations.filter((m) => filterMutations(m, "childName")); + scopedMutations = mutations.filter((m) => + filterMutations(m, "childName") + ); } // find any mutation objects that match the target - const targetMutations = scopedMutations.filter((m) => filterMutations(m, "target")); + const targetMutations = scopedMutations.filter((m) => + filterMutations(m, "target") + ); if (isEmpty(targetMutations)) { return undefined; } - const keyMutations = targetMutations.filter((m) => filterMutations(m, "eventKey")); + const keyMutations = targetMutations.filter((m) => + filterMutations(m, "eventKey") + ); if (isEmpty(keyMutations)) { return undefined; } return keyMutations.reduce((memo, curr) => { - const mutationFunction = curr && isFunction(curr.mutation) ? curr.mutation : () => undefined; - const currentMutation = mutationFunction(assign({}, baseProps, baseState)); + const mutationFunction = + curr && isFunction(curr.mutation) ? curr.mutation : () => undefined; + const currentMutation = mutationFunction( + assign({}, baseProps, baseState) + ); return assign({}, memo, currentMutation); }, {}); }, @@ -366,11 +421,14 @@ export default { Array.isArray(components) && components.reduce((memo, componentName) => { const component = props[componentName]; - const defaultEvents = component && component.type && component.type.defaultEvents; + const defaultEvents = + component && component.type && component.type.defaultEvents; const componentEvents = isFunction(defaultEvents) ? defaultEvents(component.props) : defaultEvents; - memo = Array.isArray(componentEvents) ? memo.concat(...componentEvents) : memo; + memo = Array.isArray(componentEvents) + ? memo.concat(...componentEvents) + : memo; return memo; }, []); return events && events.length ? events : undefined; @@ -381,8 +439,10 @@ export default { return match && match[1] && match[1].toLowerCase(); }, - getGlobalEvents: (events) => pickBy(events, (_, key) => GLOBAL_EVENT_REGEX.test(key)), - omitGlobalEvents: (events) => omitBy(events, (_, key) => GLOBAL_EVENT_REGEX.test(key)), + getGlobalEvents: (events) => + pickBy(events, (_, key) => GLOBAL_EVENT_REGEX.test(key)), + omitGlobalEvents: (events) => + omitBy(events, (_, key) => GLOBAL_EVENT_REGEX.test(key)), emulateReactEvent: (event) => assign(event, { nativeEvent: event }) }; diff --git a/packages/victory-core/src/victory-util/helpers.js b/packages/victory-core/src/victory-util/helpers.js index eaf9e464c..91d10200e 100644 --- a/packages/victory-core/src/victory-util/helpers.js +++ b/packages/victory-core/src/victory-util/helpers.js @@ -172,7 +172,9 @@ function getRange(props, axis) { } else if (props.range && Array.isArray(props.range)) { return props.range; } - return props.polar ? getPolarRange(props, axis) : getCartesianRange(props, axis); + return props.polar + ? getPolarRange(props, axis) + : getCartesianRange(props, axis); } function createAccessor(key) { @@ -240,18 +242,32 @@ function reduceChildren( const childRole = child.type && child.type.role; const childName = child.props.name || `${childRole}-${names[index]}`; if (child.props && child.props.children) { - const childProps = assign({}, child.props, pick(parentProps, sharedProps)); + const childProps = assign( + {}, + child.props, + pick(parentProps, sharedProps) + ); const nestedChildren = - child.type && child.type.role === "stack" && isFunction(child.type.getChildren) + child.type && + child.type.role === "stack" && + isFunction(child.type.getChildren) ? child.type.getChildren(childProps) : React.Children.toArray(child.props.children).map((c) => { - const nestedChildProps = assign({}, c.props, pick(childProps, sharedProps)); + const nestedChildProps = assign( + {}, + c.props, + pick(childProps, sharedProps) + ); return React.cloneElement(c, nestedChildProps); }); const childNames = nestedChildren.map((c, i) => `${childName}-${i}`); - const nestedResults = traverseChildren(nestedChildren, childNames, child); + const nestedResults = traverseChildren( + nestedChildren, + childNames, + child + ); memo = combine(memo, nestedResults); } else { const result = iteratee(child, childName, parent); diff --git a/packages/victory-core/src/victory-util/label-helpers.js b/packages/victory-core/src/victory-util/label-helpers.js index 1b426551d..11a8bed76 100644 --- a/packages/victory-core/src/victory-util/label-helpers.js +++ b/packages/victory-core/src/victory-util/label-helpers.js @@ -93,7 +93,8 @@ function getLabelPlacement(props) { const defaultLabelPlacement = polar ? "perpendicular" : "vertical"; return labelPlacement ? labelPlacement - : (labelComponent.props && labelComponent.props.labelPlacement) || defaultLabelPlacement; + : (labelComponent.props && labelComponent.props.labelPlacement) || + defaultLabelPlacement; } function getPolarOrientation(degrees) { @@ -135,7 +136,11 @@ function getPolarTextAnchor(props, degrees) { function getPolarVerticalAnchor(props, degrees) { const labelPlacement = getLabelPlacement(props); const orientation = getPolarOrientation(degrees); - if (labelPlacement === "parallel" || orientation === "left" || orientation === "right") { + if ( + labelPlacement === "parallel" || + orientation === "left" || + orientation === "right" + ) { return "middle"; } return orientation === "top" ? "end" : "start"; @@ -146,7 +151,8 @@ function getPolarAngle(props, baseAngle) { if (!labelPlacement || labelPlacement === "vertical") { return 0; } - const degrees = baseAngle !== undefined ? baseAngle % 360 : getDegrees(props, datum); + const degrees = + baseAngle !== undefined ? baseAngle % 360 : getDegrees(props, datum); const sign = (degrees > 90 && degrees < 180) || degrees > 270 ? 1 : -1; let angle = 0; if (degrees === 0 || degrees === 180) { @@ -180,7 +186,9 @@ function getProps(props, index) { } = props; const datum = data[index]; const degrees = getDegrees(props, datum); - const textAnchor = polar ? getPolarTextAnchor(props, degrees) : getTextAnchor(props, datum); + const textAnchor = polar + ? getPolarTextAnchor(props, degrees) + : getTextAnchor(props, datum); const verticalAnchor = polar ? getPolarVerticalAnchor(props, degrees) : getVerticalAnchor(props, datum); diff --git a/packages/victory-core/src/victory-util/prop-types.js b/packages/victory-core/src/victory-util/prop-types.js index 73749faee..f2a8972b3 100644 --- a/packages/victory-core/src/victory-util/prop-types.js +++ b/packages/victory-core/src/victory-util/prop-types.js @@ -12,11 +12,19 @@ import PropTypes from "prop-types"; */ const makeChainable = function (validator) { /* eslint-disable max-params */ - const _chainable = function (isRequired, props, propName, componentName, ...rest) { + const _chainable = function ( + isRequired, + props, + propName, + componentName, + ...rest + ) { const value = props[propName]; if (value === undefined || value === null) { if (isRequired) { - return new Error(`Required \`${propName}\` was not specified in \`${componentName}\`.`); + return new Error( + `Required \`${propName}\` was not specified in \`${componentName}\`.` + ); } return null; } @@ -74,9 +82,16 @@ export default { return (props, propName, componentName) => { const value = props[propName]; if (value !== null && value !== undefined) { - Log.warn(`"${propName}" property of "${componentName}" has been deprecated ${explanation}`); + Log.warn( + `"${propName}" property of "${componentName}" has been deprecated ${explanation}` + ); } - return PropTypes.checkPropTypes({ [propName]: propType }, props, propName, componentName); + return PropTypes.checkPropTypes( + { [propName]: propType }, + props, + propName, + componentName + ); }; }, @@ -90,7 +105,8 @@ export default { allOfType(validators) { return makeChainable((props, propName, componentName, ...rest) => validators.reduce( - (result, validator) => result || validator(props, propName, componentName, ...rest), + (result, validator) => + result || validator(props, propName, componentName, ...rest), undefined ) ); @@ -102,7 +118,9 @@ export default { nonNegative: makeChainable((props, propName, componentName) => { const value = props[propName]; if (typeof value !== "number" || value < 0) { - return new Error(`\`${propName}\` in \`${componentName}\` must be a non-negative number.`); + return new Error( + `\`${propName}\` in \`${componentName}\` must be a non-negative number.` + ); } return undefined; }), @@ -113,7 +131,9 @@ export default { integer: makeChainable((props, propName, componentName) => { const value = props[propName]; if (typeof value !== "number" || value % 1 !== 0) { - return new Error(`\`${propName}\` in \`${componentName}\` must be an integer.`); + return new Error( + `\`${propName}\` in \`${componentName}\` must be an integer.` + ); } return undefined; }), @@ -151,7 +171,11 @@ export default { const supportedScaleStrings = ["linear", "time", "log", "sqrt"]; const validScale = (scl) => { if (isFunction(scl)) { - return isFunction(scl.copy) && isFunction(scl.domain) && isFunction(scl.range); + return ( + isFunction(scl.copy) && + isFunction(scl.domain) && + isFunction(scl.range) + ); } else if (typeof scl === "string") { return supportedScaleStrings.indexOf(scl) !== -1; } @@ -160,7 +184,9 @@ export default { const value = props[propName]; if (!validScale(value)) { - return new Error(`\`${propName}\` in \`${componentName}\` must be a d3 scale.`); + return new Error( + `\`${propName}\` in \`${componentName}\` must be a d3 scale.` + ); } return undefined; }), @@ -171,7 +197,9 @@ export default { homogeneousArray: makeChainable((props, propName, componentName) => { const values = props[propName]; if (!Array.isArray(values)) { - return new Error(`\`${propName}\` in \`${componentName}\` must be an array.`); + return new Error( + `\`${propName}\` in \`${componentName}\` must be an array.` + ); } if (values.length < 2) { @@ -216,7 +244,9 @@ export default { */ regExp: makeChainable((props, propName, componentName) => { if (props[propName] && !isRegExp(props[propName])) { - return new Error(`\`${propName}\` in \`${componentName}\` must be a regular expression.`); + return new Error( + `\`${propName}\` in \`${componentName}\` must be a regular expression.` + ); } return undefined; }) diff --git a/packages/victory-core/src/victory-util/scale.js b/packages/victory-core/src/victory-util/scale.js index add6b832d..2b43fbfd7 100644 --- a/packages/victory-core/src/victory-util/scale.js +++ b/packages/victory-core/src/victory-util/scale.js @@ -17,7 +17,11 @@ function toNewName(scale) { function validScale(scale) { if (typeof scale === "function") { - return isFunction(scale.copy) && isFunction(scale.domain) && isFunction(scale.range); + return ( + isFunction(scale.copy) && + isFunction(scale.domain) && + isFunction(scale.range) + ); } else if (typeof scale === "string") { return includes(supportedScaleStrings, scale); } @@ -60,7 +64,9 @@ function getScaleTypeFromData(props, axis) { } const accessor = Helpers.createAccessor(props[axis]); const axisData = props.data.map((datum) => { - const processedData = isPlainObject(accessor(datum)) ? accessor(datum)[axis] : accessor(datum); + const processedData = isPlainObject(accessor(datum)) + ? accessor(datum)[axis] + : accessor(datum); return processedData !== undefined ? processedData : datum[axis]; }); return Collection.containsDates(axisData) ? "time" : "linear"; @@ -77,7 +83,8 @@ function getBaseScale(props, axis) { if (scale) { return typeof scale === "string" ? getScaleFromName(scale) : scale; } - const defaultScale = getScaleFromDomain(props, axis) || getScaleTypeFromData(props, axis); + const defaultScale = + getScaleFromDomain(props, axis) || getScaleTypeFromData(props, axis); return d3Scale[toNewName(defaultScale)](); } @@ -98,7 +105,9 @@ function getScaleFromProps(props, axis) { function getScaleType(props, axis) { // if the scale was not given in props, it will be set to linear or time depending on data - return getScaleTypeFromProps(props, axis) || getScaleTypeFromData(props, axis); + return ( + getScaleTypeFromProps(props, axis) || getScaleTypeFromData(props, axis) + ); } function getType(scale) { diff --git a/packages/victory-core/src/victory-util/selection.js b/packages/victory-core/src/victory-util/selection.js index e0156e62b..cfc3de070 100644 --- a/packages/victory-core/src/victory-util/selection.js +++ b/packages/victory-core/src/victory-util/selection.js @@ -39,7 +39,10 @@ function getSVGEventCoordinates(evt, svg) { y: evt.nativeEvent.locationY }; } - evt = evt.changedTouches && evt.changedTouches.length ? evt.changedTouches[0] : evt; + evt = + evt.changedTouches && evt.changedTouches.length + ? evt.changedTouches[0] + : evt; svg = svg || getParentSVG(evt); const matrix = getTransformationMatrix(svg); return { diff --git a/packages/victory-core/src/victory-util/textsize.js b/packages/victory-core/src/victory-util/textsize.js index b8d92e7f2..8ef116d8e 100644 --- a/packages/victory-core/src/victory-util/textsize.js +++ b/packages/victory-core/src/victory-util/textsize.js @@ -154,7 +154,8 @@ const _splitToLines = (text) => { const _getSizeWithRotate = (axisSize, dependentSize, angle) => { const angleInRadian = _degreeToRadian(angle); return ( - Math.abs(Math.cos(angleInRadian) * axisSize) + Math.abs(Math.sin(angleInRadian) * dependentSize) + Math.abs(Math.cos(angleInRadian) * axisSize) + + Math.abs(Math.sin(angleInRadian) * dependentSize) ); }; @@ -205,7 +206,10 @@ const _approximateTextWidthInternal = (text, style) => { const widths = _splitToLines(text).map((line, index) => { const len = line.toString().length; - const { fontSize, letterSpacing, fontFamily } = _prepareParams(style, index); + const { fontSize, letterSpacing, fontFamily } = _prepareParams( + style, + index + ); const fontData = _getFontData(fontFamily); const width = line @@ -248,11 +252,17 @@ const _approximateTextHeightInternal = (text, style) => { * @returns {number} Approximate text label height. */ const approximateTextSize = (text, style) => { - const angle = Array.isArray(style) ? style[0] && style[0].angle : style && style.angle; + const angle = Array.isArray(style) + ? style[0] && style[0].angle + : style && style.angle; const height = _approximateTextHeightInternal(text, style); const width = _approximateTextWidthInternal(text, style); - const widthWithRotate = angle ? _getSizeWithRotate(width, height, angle) : width; - const heightWithRotate = angle ? _getSizeWithRotate(height, width, angle) : height; + const widthWithRotate = angle + ? _getSizeWithRotate(width, height, angle) + : width; + const heightWithRotate = angle + ? _getSizeWithRotate(height, width, angle) + : height; return { width: widthWithRotate, height: heightWithRotate * coefficients.heightOverlapCoef diff --git a/packages/victory-core/src/victory-util/transitions.js b/packages/victory-core/src/victory-util/transitions.js index 99799ccd7..f3659cf31 100644 --- a/packages/victory-core/src/victory-util/transitions.js +++ b/packages/victory-core/src/victory-util/transitions.js @@ -44,8 +44,10 @@ function getNodeTransitions(oldData, nextData) { const nextDataKeyed = nextData && getKeyedData(nextData); return { - entering: oldDataKeyed && getKeyedDataDifference(nextDataKeyed, oldDataKeyed), - exiting: nextDataKeyed && getKeyedDataDifference(oldDataKeyed, nextDataKeyed) + entering: + oldDataKeyed && getKeyedDataDifference(nextDataKeyed, oldDataKeyed), + exiting: + nextDataKeyed && getKeyedDataDifference(oldDataKeyed, nextDataKeyed) }; } @@ -121,7 +123,8 @@ function getInitialTransitionState(oldChildren, nextChildren) { } function getInitialChildProps(animate, data) { - const after = animate.onEnter && animate.onEnter.after ? animate.onEnter.after : identity; + const after = + animate.onEnter && animate.onEnter.after ? animate.onEnter.after : identity; return { data: data.map((datum, idx) => assign({}, datum, after(datum, idx, data))) }; @@ -133,7 +136,8 @@ function getChildBeforeLoad(animate, child, data, cb) { if (animate && animate.onLoad && !animate.onLoad.duration) { return { animate, data }; } - const before = animate.onLoad && animate.onLoad.before ? animate.onLoad.before : identity; + const before = + animate.onLoad && animate.onLoad.before ? animate.onLoad.before : identity; // If nodes need to exit, transform them with the provided onLoad.before function. data = data.map((datum, idx) => { return assign({}, datum, before(datum, idx, data)); @@ -148,7 +152,8 @@ function getChildOnLoad(animate, data, cb) { if (animate && animate.onLoad && !animate.onLoad.duration) { return { animate, data }; } - const after = animate.onLoad && animate.onLoad.after ? animate.onLoad.after : identity; + const after = + animate.onLoad && animate.onLoad.after ? animate.onLoad.after : identity; // If nodes need to exit, transform them with the provided onLoad.after function. data = data.map((datum, idx) => { return assign({}, datum, after(datum, idx, data)); @@ -168,11 +173,16 @@ function getChildPropsOnExit(animate, child, data, exitingNodes, cb) { // After the exit transition occurs, trigger the animations for // nodes that are neither exiting or entering. animate.onEnd = cb; - const before = animate.onExit && animate.onExit.before ? animate.onExit.before : identity; + const before = + animate.onExit && animate.onExit.before + ? animate.onExit.before + : identity; // If nodes need to exit, transform them with the provided onExit.before function. data = data.map((datum, idx) => { const key = (datum.key || idx).toString(); - return exitingNodes[key] ? assign({}, datum, before(datum, idx, data)) : datum; + return exitingNodes[key] + ? assign({}, datum, before(datum, idx, data)) + : datum; }); } @@ -185,13 +195,18 @@ function getChildPropsBeforeEnter(animate, child, data, enteringNodes, cb) { // Perform a normal animation here, except - when it finishes - trigger // the transition for entering nodes. animate = assign({}, animate, { onEnd: cb }); - const before = animate.onEnter && animate.onEnter.before ? animate.onEnter.before : identity; + const before = + animate.onEnter && animate.onEnter.before + ? animate.onEnter.before + : identity; // We want the entering nodes to be included in the transition target // domain. However, we may not want these nodes to be displayed initially, // so perform the `onEnter.before` transformation on each node. data = data.map((datum, idx) => { const key = (datum.key || idx).toString(); - return enteringNodes[key] ? assign({}, datum, before(datum, idx, data)) : datum; + return enteringNodes[key] + ? assign({}, datum, before(datum, idx, data)) + : datum; }); } @@ -210,10 +225,15 @@ function getChildPropsOnEnter(animate, data, enteringNodes, cb) { // domain should encompass the nodes that will now enter. So perform // the `onEnter.after` transformation on each node. animate.onEnd = cb; - const after = animate.onEnter && animate.onEnter.after ? animate.onEnter.after : identity; + const after = + animate.onEnter && animate.onEnter.after + ? animate.onEnter.after + : identity; data = data.map((datum, idx) => { const key = getDatumKey(datum, idx); - return enteringNodes[key] ? assign({}, datum, after(datum, idx, data)) : datum; + return enteringNodes[key] + ? assign({}, datum, after(datum, idx, data)) + : datum; }); } return { animate, data }; @@ -245,9 +265,12 @@ function getTransitionPropsFactory(props, state, setState) { const nodesDoneLoad = state && state.nodesDoneLoad; const childrenTransitions = (state && state.childrenTransitions) || []; const transitionDurations = { - enter: props.animate && props.animate.onEnter && props.animate.onEnter.duration, - exit: props.animate && props.animate.onExit && props.animate.onExit.duration, - load: props.animate && props.animate.onLoad && props.animate.onLoad.duration, + enter: + props.animate && props.animate.onEnter && props.animate.onEnter.duration, + exit: + props.animate && props.animate.onExit && props.animate.onExit.duration, + load: + props.animate && props.animate.onLoad && props.animate.onLoad.duration, move: props.animate && props.animate.duration }; @@ -310,15 +333,24 @@ function getTransitionPropsFactory(props, state, setState) { ? child.type.defaultPolarTransitions || child.type.defaultTransitions : child.type.defaultTransitions; - animate.onExit = defaults({}, animate.onExit, defaultTransitions && defaultTransitions.onExit); + animate.onExit = defaults( + {}, + animate.onExit, + defaultTransitions && defaultTransitions.onExit + ); animate.onEnter = defaults( {}, animate.onEnter, defaultTransitions && defaultTransitions.onEnter ); - animate.onLoad = defaults({}, animate.onLoad, defaultTransitions && defaultTransitions.onLoad); + animate.onLoad = defaults( + {}, + animate.onLoad, + defaultTransitions && defaultTransitions.onLoad + ); - const childTransitions = childrenTransitions[index] || childrenTransitions[0]; + const childTransitions = + childrenTransitions[index] || childrenTransitions[0]; if (!nodesDoneLoad) { // should do onLoad animation const load = @@ -349,7 +381,12 @@ function getTransitionPropsFactory(props, state, setState) { const animation = { duration: nodesShouldEnter && enteringNodes ? enter : move }; - return onEnter(enteringNodes, child, data, assign({}, animate, animation)); + return onEnter( + enteringNodes, + child, + data, + assign({}, animate, animation) + ); } else if (!state && animate && animate.onExit) { // This is the initial render, and nodes may enter when props change. Because // animation interpolation is determined by old- and next- props, data may need diff --git a/packages/victory-core/src/victory-util/wrapper.js b/packages/victory-core/src/victory-util/wrapper.js index 502ba2385..135b373a6 100644 --- a/packages/victory-core/src/victory-util/wrapper.js +++ b/packages/victory-core/src/victory-util/wrapper.js @@ -49,21 +49,31 @@ export default { const firstChild = Array.isArray(children) && children[0]; let barWidth = firstChild.props.barWidth; - let dataLength = (firstChild.props.data && firstChild.props.data.length) || 1; + let dataLength = + (firstChild.props.data && firstChild.props.data.length) || 1; if (firstChild && firstChild.type.role === "stack") { - const nestedChild = firstChild.props.children && firstChild.props.children[0]; + const nestedChild = + firstChild.props.children && firstChild.props.children[0]; barWidth = nestedChild.props.barWidth; dataLength = firstChild.props.children.length; } const width = barWidth || this.getWidth(props, children.length, dataLength); - return { x: (width * children.length) / 2 + (offset - width * ((children.length - 1) / 2)) }; + return { + x: + (width * children.length) / 2 + + (offset - width * ((children.length - 1) / 2)) + }; }, getDomain(props, axis, childComponents) { childComponents = childComponents || React.Children.toArray(props.children); const propsDomain = Domain.getDomainFromProps(props, axis); - const domainPadding = this.getDefaultDomainPadding(props, axis, childComponents); + const domainPadding = this.getDefaultDomainPadding( + props, + axis, + childComponents + ); let domain; if (propsDomain) { @@ -72,10 +82,18 @@ export default { const minDomain = Domain.getMinFromProps(props, axis); const maxDomain = Domain.getMaxFromProps(props, axis); const dataset = (props.data || props.y) && Data.getData(props); - const dataDomain = dataset ? Domain.getDomainFromData(props, axis, dataset) : []; - const childDomain = this.getDomainFromChildren(props, axis, childComponents); - const min = minDomain || Collection.getMinValue([...dataDomain, ...childDomain]); - const max = maxDomain || Collection.getMaxValue([...dataDomain, ...childDomain]); + const dataDomain = dataset + ? Domain.getDomainFromData(props, axis, dataset) + : []; + const childDomain = this.getDomainFromChildren( + props, + axis, + childComponents + ); + const min = + minDomain || Collection.getMinValue([...dataDomain, ...childDomain]); + const max = + maxDomain || Collection.getMaxValue([...dataDomain, ...childDomain]); domain = Domain.getDomainFromMinMax(min, max); } return Domain.formatDomain(domain, assign({ domainPadding }, props), axis); @@ -89,7 +107,9 @@ export default { ? childComponents.slice(0) : React.Children.toArray(props.children); const iteratee = (child) => { - const sharedProps = assign({}, child.props, { horizontal: props.horizontal }); + const sharedProps = assign({}, child.props, { + horizontal: props.horizontal + }); return Scale.getScaleType(sharedProps, axis); }; const childScale = uniq(Helpers.reduceChildren(children, iteratee, props)); @@ -107,7 +127,9 @@ export default { if (props.animate.parentState) { const nodesWillExit = props.animate.parentState.nodesWillExit; const oldProps = nodesWillExit ? props : null; - this.setState(defaults({ oldProps, nextProps }, props.animate.parentState)); + this.setState( + defaults({ oldProps, nextProps }, props.animate.parentState) + ); } else { const oldChildren = React.Children.toArray(props.children); const nextChildren = React.Children.toArray(nextProps.children); @@ -120,11 +142,16 @@ export default { !props.polar && some(oldChildren, (child) => { return ( - isContinuous(child) || (child.props.children && isContinuous(child.props.children)) + isContinuous(child) || + (child.props.children && isContinuous(child.props.children)) ); }); - const { nodesWillExit, nodesWillEnter, childrenTransitions, nodesShouldEnter } = - Transitions.getInitialTransitionState(oldChildren, nextChildren); + const { + nodesWillExit, + nodesWillEnter, + childrenTransitions, + nodesShouldEnter + } = Transitions.getInitialTransitionState(oldChildren, nextChildren); this.setState({ nodesWillExit, @@ -141,7 +168,11 @@ export default { }, getAllEvents(props) { - const components = ["groupComponent", "containerComponent", "labelComponent"]; + const components = [ + "groupComponent", + "containerComponent", + "labelComponent" + ]; this.componentEvents = Events.getComponentEvents(props, components); let events = props.events; if (Array.isArray(this.componentEvents)) { @@ -168,12 +199,19 @@ export default { const state = getFilteredState(); const parentState = (props.animate && props.animate.parentState) || state; if (!getTransitions) { - const getTransitionProps = Transitions.getTransitionPropsFactory(props, state, (newState) => - this.setState(newState) + const getTransitionProps = Transitions.getTransitionPropsFactory( + props, + state, + (newState) => this.setState(newState) ); - getTransitions = (childComponent) => getTransitionProps(childComponent, index); + getTransitions = (childComponent) => + getTransitionProps(childComponent, index); } - return defaults({ getTransitions, parentState }, props.animate, child.props.animate); + return defaults( + { getTransitions, parentState }, + props.animate, + child.props.animate + ); }, getDomainFromChildren(props, axis, childComponents) { @@ -182,7 +220,15 @@ export default { ? childComponents.slice(0) : React.Children.toArray(props.children); const parentData = props.data ? Data.getData(props, axis) : undefined; - const { polar, startAngle, endAngle, categories, minDomain, maxDomain, horizontal } = props; + const { + polar, + startAngle, + endAngle, + categories, + minDomain, + maxDomain, + horizontal + } = props; const baseParentProps = { horizontal, polar, @@ -208,12 +254,19 @@ export default { }; const childDomains = Helpers.reduceChildren(children, iteratee, props); - const min = childDomains.length === 0 ? 0 : Collection.getMinValue(childDomains); - const max = childDomains.length === 0 ? 1 : Collection.getMaxValue(childDomains); + const min = + childDomains.length === 0 ? 0 : Collection.getMinValue(childDomains); + const max = + childDomains.length === 0 ? 1 : Collection.getMaxValue(childDomains); return [min, max]; }, - addBinsToParentPropsIfHistogram({ children, props, childComponents, parentProps }) { + addBinsToParentPropsIfHistogram({ + children, + props, + childComponents, + parentProps + }) { const someChildrenAreHistograms = children.some((child) => { return child.type && child.type.role === "histogram"; }); @@ -243,14 +296,20 @@ export default { if (!Array.isArray(childBins)) { const combinedData = children.reduce((memo, child) => { const xAccessor = Helpers.createAccessor(child.props.x || "x"); - return memo.concat(child.props.data.map((datum) => ({ x: xAccessor(datum) }))); + return memo.concat( + child.props.data.map((datum) => ({ x: xAccessor(datum) })) + ); }, []); // use the same function to generate bins as VictoryHistogram but with // the combined data from above, then get explicit bins from that const getFormattedHistogramData = children[0].type.getFormattedData; - childBins = getFormattedHistogramData({ data: combinedData, bins: childBins }).reduce( - (memo, { x0, x1 }, index) => (index === 0 ? memo.concat([x0, x1]) : memo.concat(x1)), + childBins = getFormattedHistogramData({ + data: combinedData, + bins: childBins + }).reduce( + (memo, { x0, x1 }, index) => + index === 0 ? memo.concat([x0, x1]) : memo.concat(x1), [] ); } @@ -259,8 +318,16 @@ export default { }, getDataFromChildren(props, childComponents) { - const { polar, startAngle, endAngle, categories, minDomain, maxDomain } = props; - let parentProps = { polar, startAngle, endAngle, categories, minDomain, maxDomain }; + const { polar, startAngle, endAngle, categories, minDomain, maxDomain } = + props; + let parentProps = { + polar, + startAngle, + endAngle, + categories, + minDomain, + maxDomain + }; let stack = 0; const children = childComponents ? childComponents.slice(0) @@ -285,12 +352,22 @@ export default { childData = Data.getData(childProps); } stack += 1; - return childData.map((datum, index) => assign({ _stack: stack, _group: index }, datum)); + return childData.map((datum, index) => + assign({ _stack: stack, _group: index }, datum) + ); }; - const stacked = children.filter((c) => c.type && c.type.role === "stack").length; + const stacked = children.filter( + (c) => c.type && c.type.role === "stack" + ).length; const combine = (memo, val) => memo.concat(uniqBy(val, "_group")); - const datasets = Helpers.reduceChildren(children, iteratee, props, [], combine); + const datasets = Helpers.reduceChildren( + children, + iteratee, + props, + [], + combine + ); const group = stacked ? "_group" : "_stack"; return values(groupBy(datasets, group)); }, @@ -302,18 +379,25 @@ export default { if (style && style.data && style.data.fill) { return style.data.fill; } - colorScale = child.props && child.props.colorScale ? child.props.colorScale : colorScale; + colorScale = + child.props && child.props.colorScale + ? child.props.colorScale + : colorScale; color = child.props && child.props.color ? child.props.color : color; if (!colorScale && !color) { return undefined; } - const colors = Array.isArray(colorScale) ? colorScale : Style.getColorScale(colorScale); + const colors = Array.isArray(colorScale) + ? colorScale + : Style.getColorScale(colorScale); return color || colors[index % colors.length]; }, getWidth(props, groupLength, seriesLength) { const { datasets, horizontal } = props; - const range = horizontal ? Helpers.getRange(props, "y") : Helpers.getRange(props, "x"); + const range = horizontal + ? Helpers.getRange(props, "y") + : Helpers.getRange(props, "x"); const extent = Math.abs(range[1] - range[0]); seriesLength = seriesLength !== undefined @@ -326,7 +410,8 @@ export default { }, getStyle(theme, style, role) { - const defaultStyle = theme && theme[role] && theme[role].style ? theme[role].style : {}; + const defaultStyle = + theme && theme[role] && theme[role].style ? theme[role].style : {}; return Helpers.getStyles(style, defaultStyle); }, @@ -338,10 +423,15 @@ export default { } const childRole = child.type && child.type.role; const defaultFill = - childRole === "stack" ? undefined : this.getColor(calculatedProps, child, index); + childRole === "stack" + ? undefined + : this.getColor(calculatedProps, child, index); const defaultColor = - childRole === "line" ? { fill: "none", stroke: defaultFill } : { fill: defaultFill }; - const dataWidth = role === "stack" ? {} : { width: this.getWidth(calculatedProps) }; + childRole === "line" + ? { fill: "none", stroke: defaultFill } + : { fill: defaultFill }; + const dataWidth = + role === "stack" ? {} : { width: this.getWidth(calculatedProps) }; const dataStyle = defaults( {}, childStyle.data, @@ -365,8 +455,11 @@ export default { childProps.categories && !Array.isArray(childProps.categories) ? childProps.categories[axis] : childProps.props.categories; - const categoryStrings = categories && categories.filter((val) => typeof val === "string"); - return categoryStrings ? Collection.removeUndefined(categoryStrings) : []; + const categoryStrings = + categories && categories.filter((val) => typeof val === "string"); + return categoryStrings + ? Collection.removeUndefined(categoryStrings) + : []; } }; return Helpers.reduceChildren(childComponents.slice(0), iteratee); @@ -388,29 +481,52 @@ export default { const initialMemo = { x: [], y: [] }; const combine = (memo, datum) => { - const x = Array.isArray(datum) ? datum.map((d) => d.x).filter(Boolean) : datum.x; - const y = Array.isArray(datum) ? datum.map((d) => d.y).filter(Boolean) : datum.y; + const x = Array.isArray(datum) + ? datum.map((d) => d.x).filter(Boolean) + : datum.x; + const y = Array.isArray(datum) + ? datum.map((d) => d.y).filter(Boolean) + : datum.y; return { x: x !== undefined ? memo.x.concat(x) : memo.x, y: y !== undefined ? memo.y.concat(y) : memo.y }; }; - return Helpers.reduceChildren(childComponents.slice(0), iteratee, {}, initialMemo, combine); + return Helpers.reduceChildren( + childComponents.slice(0), + iteratee, + {}, + initialMemo, + combine + ); }, getCategoryAndAxisStringsFromChildren(props, axis, childComponents) { - const categories = isPlainObject(props.categories) ? props.categories[axis] : props.categories; + const categories = isPlainObject(props.categories) + ? props.categories[axis] + : props.categories; const axisComponent = Axis.getAxisComponent(childComponents, axis); - const axisStrings = axisComponent ? Data.getStringsFromAxes(axisComponent.props, axis) : []; - const categoryStrings = categories || this.getStringsFromCategories(childComponents, axis); + const axisStrings = axisComponent + ? Data.getStringsFromAxes(axisComponent.props, axis) + : []; + const categoryStrings = + categories || this.getStringsFromCategories(childComponents, axis); return uniq(flatten([...categoryStrings, ...axisStrings])); }, getStringsFromChildren(props, childComponents) { childComponents = childComponents || React.Children.toArray(props.children); - const xStrings = this.getCategoryAndAxisStringsFromChildren(props, "x", childComponents); - const yStrings = this.getCategoryAndAxisStringsFromChildren(props, "y", childComponents); + const xStrings = this.getCategoryAndAxisStringsFromChildren( + props, + "x", + childComponents + ); + const yStrings = this.getCategoryAndAxisStringsFromChildren( + props, + "y", + childComponents + ); const dataStrings = this.getStringsFromData(childComponents); @@ -422,10 +538,14 @@ export default { getCategories(props, childComponents, allStrings) { const xPropCategories = - props.categories && !Array.isArray(props.categories) ? props.categories.x : props.categories; + props.categories && !Array.isArray(props.categories) + ? props.categories.x + : props.categories; const yPropCategories = - props.categories && !Array.isArray(props.categories) ? props.categories.y : props.categories; + props.categories && !Array.isArray(props.categories) + ? props.categories.y + : props.categories; const fallbackRequired = !xPropCategories || !yPropCategories; diff --git a/packages/victory-create-container/src/create-container.js b/packages/victory-create-container/src/create-container.js index 74fc712dd..354f3fdbb 100644 --- a/packages/victory-create-container/src/create-container.js +++ b/packages/victory-create-container/src/create-container.js @@ -1,4 +1,13 @@ -import { toPairs, groupBy, forOwn, includes, flow, isEmpty, isFunction, keys } from "lodash"; +import { + toPairs, + groupBy, + forOwn, + includes, + flow, + isEmpty, + isFunction, + keys +} from "lodash"; import { VictoryContainer, Log } from "victory-core"; import { voronoiContainerMixin } from "victory-voronoi-container"; import { zoomContainerMixin } from "victory-zoom-container"; @@ -49,7 +58,9 @@ const combineDefaultEvents = (defaultEvents) => { ? null : { target, - eventHandlers: combineEventHandlers(eventsArray.map((event) => event.eventHandlers)) + eventHandlers: combineEventHandlers( + eventsArray.map((event) => event.eventHandlers) + ) // note: does not currently handle eventKey or childName }; }); @@ -106,7 +117,11 @@ const combineContainerMixins = (mixins, Container) => { const checkBehaviorName = (behavior, behaviors) => { if (behavior && !includes(behaviors, behavior)) { - Log.warn(`"${behavior}" is not a valid behavior. Choose from [${behaviors.join(", ")}].`); + Log.warn( + `"${behavior}" is not a valid behavior. Choose from [${behaviors.join( + ", " + )}].` + ); } }; @@ -120,7 +135,9 @@ const makeCreateContainerFunction = checkBehaviorName(behaviorB, behaviors); if (invalid.length) { - Log.warn("too many arguments given to createContainer (maximum accepted: 2)."); + Log.warn( + "too many arguments given to createContainer (maximum accepted: 2)." + ); } const firstMixins = mixinMap[behaviorA]; diff --git a/packages/victory-create-container/src/index.d.ts b/packages/victory-create-container/src/index.d.ts index 82f3bb7a1..cc6309ab4 100644 --- a/packages/victory-create-container/src/index.d.ts +++ b/packages/victory-create-container/src/index.d.ts @@ -1,6 +1,11 @@ import * as React from "react"; -export type ContainerType = "brush" | "cursor" | "selection" | "voronoi" | "zoom"; +export type ContainerType = + | "brush" + | "cursor" + | "selection" + | "voronoi" + | "zoom"; export function createContainer( c1: ContainerType, c2: ContainerType diff --git a/packages/victory-cursor-container/src/cursor-helpers.js b/packages/victory-cursor-container/src/cursor-helpers.js index 00431ffda..0a85eaaf4 100644 --- a/packages/victory-cursor-container/src/cursor-helpers.js +++ b/packages/victory-cursor-container/src/cursor-helpers.js @@ -48,7 +48,9 @@ const CursorHelpers = { if (isFunction(onCursorChange)) { if (inBounds) { - const value = cursorDimension ? cursorValue[cursorDimension] : cursorValue; + const value = cursorDimension + ? cursorValue[cursorDimension] + : cursorValue; onCursorChange(value, targetProps); } else if (cursorValue !== targetProps.cursorValue) { onCursorChange(targetProps.defaultCursorValue || null, targetProps); @@ -83,10 +85,14 @@ const CursorHelpers = { export default { ...CursorHelpers, - onMouseMove: throttle(CursorHelpers.onMouseMove.bind(CursorHelpers), ON_MOUSE_MOVE_THROTTLE_MS, { - leading: true, - trailing: false - }), + onMouseMove: throttle( + CursorHelpers.onMouseMove.bind(CursorHelpers), + ON_MOUSE_MOVE_THROTTLE_MS, + { + leading: true, + trailing: false + } + ), onMouseLeave: CursorHelpers.onMouseMove.bind(CursorHelpers), onTouchEnd: CursorHelpers.onTouchEnd.bind(CursorHelpers) }; diff --git a/packages/victory-cursor-container/src/index.d.ts b/packages/victory-cursor-container/src/index.d.ts index cd979e553..fa7079d34 100644 --- a/packages/victory-cursor-container/src/index.d.ts +++ b/packages/victory-cursor-container/src/index.d.ts @@ -1,5 +1,9 @@ import * as React from "react"; -import { VictoryContainerProps, CoordinatesPropType, CallbackArgs } from "victory-core"; +import { + VictoryContainerProps, + CoordinatesPropType, + CallbackArgs +} from "victory-core"; export type CursorCoordinatesPropType = CoordinatesPropType | number; @@ -11,7 +15,13 @@ export interface VictoryCursorContainerProps extends VictoryContainerProps { cursorLabelOffset?: CursorCoordinatesPropType; defaultCursorValue?: CursorCoordinatesPropType; disable?: boolean; - onCursorChange?: (value: CursorCoordinatesPropType, props: VictoryCursorContainerProps) => void; + onCursorChange?: ( + value: CursorCoordinatesPropType, + props: VictoryCursorContainerProps + ) => void; } -export class VictoryCursorContainer extends React.Component {} +export class VictoryCursorContainer extends React.Component< + VictoryCursorContainerProps, + any +> {} diff --git a/packages/victory-cursor-container/src/victory-cursor-container.js b/packages/victory-cursor-container/src/victory-cursor-container.js index 14c198955..6d5bf442d 100644 --- a/packages/victory-cursor-container/src/victory-cursor-container.js +++ b/packages/victory-cursor-container/src/victory-cursor-container.js @@ -1,6 +1,11 @@ import PropTypes from "prop-types"; import React from "react"; -import { VictoryContainer, VictoryLabel, LineSegment, Helpers } from "victory-core"; +import { + VictoryContainer, + VictoryLabel, + LineSegment, + Helpers +} from "victory-core"; import { defaults, assign, isObject } from "lodash"; import CursorHelpers from "./cursor-helpers"; @@ -45,16 +50,22 @@ export const cursorContainerMixin = (base) => target: "parent", eventHandlers: { onMouseLeave: (evt, targetProps) => { - return props.disable ? {} : CursorHelpers.onMouseLeave(evt, targetProps); + return props.disable + ? {} + : CursorHelpers.onMouseLeave(evt, targetProps); }, onTouchCancel: () => { return []; }, onMouseMove: (evt, targetProps) => { - return props.disable ? {} : CursorHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : CursorHelpers.onMouseMove(evt, targetProps); }, onTouchMove: (evt, targetProps) => { - return props.disable ? {} : CursorHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : CursorHelpers.onMouseMove(evt, targetProps); } } } @@ -62,7 +73,8 @@ export const cursorContainerMixin = (base) => }; getCursorPosition(props) { - const { cursorValue, defaultCursorValue, domain, cursorDimension } = props; + const { cursorValue, defaultCursorValue, domain, cursorDimension } = + props; if (cursorValue) { return cursorValue; } @@ -130,13 +142,17 @@ export const cursorContainerMixin = (base) => y: horizontal ? scale.x(cursorValue.x) : scale.y(cursorValue.y) }; if (cursorLabel) { - let labelProps = defaults({ active: true }, cursorLabelComponent.props, { - x: cursorCoordinates.x + cursorLabelOffset.x, - y: cursorCoordinates.y + cursorLabelOffset.y, - datum: cursorValue, - active: true, - key: `${name}-cursor-label` - }); + let labelProps = defaults( + { active: true }, + cursorLabelComponent.props, + { + x: cursorCoordinates.x + cursorLabelOffset.x, + y: cursorCoordinates.y + cursorLabelOffset.y, + datum: cursorValue, + active: true, + key: `${name}-cursor-label` + } + ); if (Helpers.isTooltip(cursorLabelComponent)) { const tooltipTheme = (theme && theme.tooltip) || {}; labelProps = defaults({}, labelProps, tooltipTheme); @@ -144,12 +160,17 @@ export const cursorContainerMixin = (base) => newElements.push( React.cloneElement( cursorLabelComponent, - defaults({}, labelProps, { text: Helpers.evaluateProp(cursorLabel, labelProps) }) + defaults({}, labelProps, { + text: Helpers.evaluateProp(cursorLabel, labelProps) + }) ) ); } - const cursorStyle = assign({ stroke: "black" }, cursorComponent.props.style); + const cursorStyle = assign( + { stroke: "black" }, + cursorComponent.props.style + ); if (cursorDimension === "x" || cursorDimension === undefined) { newElements.push( React.cloneElement(cursorComponent, { @@ -179,7 +200,10 @@ export const cursorContainerMixin = (base) => // Overrides method in VictoryContainer getChildren(props) { - return [...React.Children.toArray(props.children), ...this.getCursorElements(props)]; + return [ + ...React.Children.toArray(props.children), + ...this.getCursorElements(props) + ]; } }; diff --git a/packages/victory-errorbar/src/error-bar.js b/packages/victory-errorbar/src/error-bar.js index d00e64bd3..6502d17bd 100644 --- a/packages/victory-errorbar/src/error-bar.js +++ b/packages/victory-errorbar/src/error-bar.js @@ -69,7 +69,10 @@ const evaluateProps = (props) => { */ const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const id = Helpers.evaluateProp(props.id, props); - const style = Helpers.evaluateStyle(assign({ stroke: "black" }, props.style), props); + const style = Helpers.evaluateStyle( + assign({ stroke: "black" }, props.style), + props + ); const tabIndex = Helpers.evaluateProp(props.tabIndex, props); return assign({}, props, { ariaLabel, id, style, tabIndex }); @@ -89,15 +92,27 @@ const ErrorBar = (props) => { error.bottom ? renderCross(props, error, "bottom") : null, error.top ? renderCross(props, error, "top") : null ].filter(Boolean); - return React.cloneElement(props.groupComponent, { "aria-label": ariaLabel, tabIndex }, children); + return React.cloneElement( + props.groupComponent, + { "aria-label": ariaLabel, tabIndex }, + children + ); }; ErrorBar.propTypes = { ...CommonProps.primitiveProps, borderWidth: PropTypes.number, datum: PropTypes.object, - errorX: PropTypes.oneOfType([PropTypes.number, PropTypes.array, PropTypes.bool]), - errorY: PropTypes.oneOfType([PropTypes.number, PropTypes.array, PropTypes.bool]), + errorX: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.array, + PropTypes.bool + ]), + errorY: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.array, + PropTypes.bool + ]), groupComponent: PropTypes.element, lineComponent: PropTypes.element, x: PropTypes.number, diff --git a/packages/victory-errorbar/src/helper-methods.js b/packages/victory-errorbar/src/helper-methods.js index 3d1117c0c..d5df173f6 100644 --- a/packages/victory-errorbar/src/helper-methods.js +++ b/packages/victory-errorbar/src/helper-methods.js @@ -1,5 +1,12 @@ import { defaults, assign, isNil } from "lodash"; -import { Helpers, LabelHelpers, Scale, Domain, Data, Collection } from "victory-core"; +import { + Helpers, + LabelHelpers, + Scale, + Domain, + Data, + Collection +} from "victory-core"; const getErrors = (props, datum, axis) => { /** @@ -29,7 +36,8 @@ const getData = (props) => { if (props.data) { return Data.formatData(props.data, props, accessorTypes); } else { - const generatedData = props.errorX || props.errorY ? Data.generateData(props) : []; + const generatedData = + props.errorX || props.errorY ? Data.generateData(props) : []; return Data.formatData(generatedData, props, accessorTypes); } }; @@ -49,9 +57,12 @@ const getDomainFromData = (props, axis) => { const errorIndex = type === "min" ? 1 : 0; const sign = type === "min" ? -1 : 1; return dataset.reduce((memo, datum) => { - const currentError = Array.isArray(datum[error]) ? datum[error][errorIndex] : datum[error]; + const currentError = Array.isArray(datum[error]) + ? datum[error][errorIndex] + : datum[error]; const current = datum[`_${axis}`] + sign * (currentError || 0); - return (memo < current && type === "min") || (memo > current && type === "max") + return (memo < current && type === "min") || + (memo > current && type === "max") ? memo : current; }, baseCondition); @@ -75,7 +86,8 @@ const formatDataFromDomain = (datum, domain) => { let { _x, _y } = datum; // if either x or y center point is outside of the domain, null the entire data point - if (_x < minDomainX || _x > maxDomainX || _y < minDomainY || _y > maxDomainY) _x = _y = null; + if (_x < minDomainX || _x > maxDomainX || _y < minDomainY || _y > maxDomainY) + _x = _y = null; return Object.assign({}, datum, { _x, _y }); }; @@ -100,7 +112,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = props.polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = props.polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; return { domain, data, scale, style, origin }; }; @@ -119,7 +133,8 @@ const getLabelProps = (dataProps, text, style) => { } = dataProps; const getError = (type = "x") => { const baseError = type === "y" ? errorY : errorX; - const error = baseError && Array.isArray(baseError) ? baseError[0] : baseError; + const error = + baseError && Array.isArray(baseError) ? baseError[0] : baseError; return error || dataProps[type]; }; const labelStyle = style.labels || {}; @@ -219,8 +234,15 @@ const getBaseProps = (props, fallbackProps) => { data: dataProps }; const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { - childProps[eventKey].labels = getLabelProps(assign({}, props, dataProps), text, style); + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { + childProps[eventKey].labels = getLabelProps( + assign({}, props, dataProps), + text, + style + ); } return childProps; diff --git a/packages/victory-errorbar/src/index.d.ts b/packages/victory-errorbar/src/index.d.ts index 09e867b04..34eee8695 100644 --- a/packages/victory-errorbar/src/index.d.ts +++ b/packages/victory-errorbar/src/index.d.ts @@ -12,7 +12,9 @@ import { } from "victory-core"; export type VictoryErrorBarTTargetType = "data" | "labels" | "parent"; -export type ErrorType = StringOrNumberOrList | ((...args: any[]) => StringOrNumberOrList); +export type ErrorType = + | StringOrNumberOrList + | ((...args: any[]) => StringOrNumberOrList); export interface VictoryErrorBarProps extends Omit, @@ -22,11 +24,17 @@ export interface VictoryErrorBarProps borderWidth?: number; errorX?: ErrorType; errorY?: ErrorType; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryErrorBarTTargetType, + StringOrNumberOrCallback + >[]; style?: VictoryStyleInterface; } -export class VictoryErrorBar extends React.Component {} +export class VictoryErrorBar extends React.Component< + VictoryErrorBarProps, + any +> {} export interface ErrorBarProps extends VictoryCommonPrimitiveProps { borderWidth?: number; diff --git a/packages/victory-errorbar/src/victory-errorbar.js b/packages/victory-errorbar/src/victory-errorbar.js index 89e3b49ab..7cf817b67 100644 --- a/packages/victory-errorbar/src/victory-errorbar.js +++ b/packages/victory-errorbar/src/victory-errorbar.js @@ -50,13 +50,19 @@ class VictoryErrorBar extends React.Component { borderWidth: PropTypes.number, errorX: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), errorY: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), @@ -99,7 +105,9 @@ class VictoryErrorBar extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-group/src/helper-methods.js b/packages/victory-group/src/helper-methods.js index 67d295bc9..adf12390d 100644 --- a/packages/victory-group/src/helper-methods.js +++ b/packages/victory-group/src/helper-methods.js @@ -17,11 +17,20 @@ function getCalculatedProps(props, childComponents) { props = Helpers.modifyProps(props, fallbackProps, role); const style = Wrapper.getStyle(props.theme, props.style, role); const { offset, colorScale, color, polar, horizontal } = props; - const categories = props.categories || Wrapper.getCategories(props, childComponents); + const categories = + props.categories || Wrapper.getCategories(props, childComponents); const datasets = props.datasets || Wrapper.getDataFromChildren(props); const domain = { - x: Wrapper.getDomain(assign({}, props, { categories }), "x", childComponents), - y: Wrapper.getDomain(assign({}, props, { categories }), "y", childComponents) + x: Wrapper.getDomain( + assign({}, props, { categories }), + "x", + childComponents + ), + y: Wrapper.getDomain( + assign({}, props, { categories }), + "y", + childComponents + ) }; const range = props.range || { x: Helpers.getRange(props, "x"), @@ -69,7 +78,9 @@ function pixelsToValue(props, axis, calculatedProps) { // eslint-disable-next-line max-params function getX0(props, calculatedProps, index, role) { const groupLength = - role === "stack" ? calculatedProps.datasets[0].length : calculatedProps.datasets.length; + role === "stack" + ? calculatedProps.datasets[0].length + : calculatedProps.datasets.length; const center = (groupLength - 1) / 2; const totalWidth = pixelsToValue(props, "x", calculatedProps); return (index - center) * totalWidth; @@ -78,7 +89,9 @@ function getX0(props, calculatedProps, index, role) { // eslint-disable-next-line max-params function getPolarX0(props, calculatedProps, index, role) { const groupLength = - role === "stack" ? calculatedProps.datasets[0].length : calculatedProps.datasets.length; + role === "stack" + ? calculatedProps.datasets[0].length + : calculatedProps.datasets.length; const center = (groupLength - 1) / 2; const width = getAngularWidth(props, calculatedProps); return (index - center) * width; @@ -99,7 +112,8 @@ function getLabels(props, datasets, index) { } function getChildProps(props, calculatedProps) { - const { categories, domain, range, scale, horizontal, origin, padding } = calculatedProps; + const { categories, domain, range, scale, horizontal, origin, padding } = + calculatedProps; const { width, height, theme, polar } = props; return { height, @@ -133,7 +147,9 @@ function getDataWithOffset(props, defaultDataset = [], offset) { const xOffset = offset || 0; return dataset.map((datum) => { const _x1 = - datum._x instanceof Date ? new Date(datum._x.getTime() + xOffset) : datum._x + xOffset; + datum._x instanceof Date + ? new Date(datum._x.getTime() + xOffset) + : datum._x + xOffset; return assign({}, datum, { _x1 }); }); @@ -142,7 +158,8 @@ function getDataWithOffset(props, defaultDataset = [], offset) { function getChildren(props, childComponents, calculatedProps) { props = Helpers.modifyProps(props, fallbackProps, "stack"); childComponents = childComponents || React.Children.toArray(props.children); - calculatedProps = calculatedProps || getCalculatedProps(props, childComponents); + calculatedProps = + calculatedProps || getCalculatedProps(props, childComponents); const { datasets } = calculatedProps; const { labelComponent, polar } = props; const childProps = getChildProps(props, calculatedProps); @@ -156,7 +173,9 @@ function getChildren(props, childComponents, calculatedProps) { role === "voronoi" || role === "tooltip" || role === "label" ? child.props.style : Wrapper.getChildStyle(child, index, calculatedProps); - const labels = props.labels ? getLabels(props, datasets, index) : child.props.labels; + const labels = props.labels + ? getLabels(props, datasets, index) + : child.props.labels; const name = child.props.name || `${parentName}-${role}-${index}`; return React.cloneElement( child, diff --git a/packages/victory-group/src/index.d.ts b/packages/victory-group/src/index.d.ts index dace2b905..d564642d4 100644 --- a/packages/victory-group/src/index.d.ts +++ b/packages/victory-group/src/index.d.ts @@ -23,7 +23,10 @@ export interface VictoryGroupProps colorScale?: ColorScalePropType; domain?: DomainPropType; domainPadding?: DomainPaddingPropType; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryGroupTTargetType, + StringOrNumberOrCallback + >[]; eventKey?: StringOrNumberOrCallback; horizontal?: boolean; offset?: number; diff --git a/packages/victory-group/src/victory-group.js b/packages/victory-group/src/victory-group.js index 5daf85bf0..34a4a25a2 100644 --- a/packages/victory-group/src/victory-group.js +++ b/packages/victory-group/src/victory-group.js @@ -1,7 +1,13 @@ import { assign, defaults, isEmpty } from "lodash"; import PropTypes from "prop-types"; import React from "react"; -import { Helpers, VictoryContainer, VictoryTheme, CommonProps, Wrapper } from "victory-core"; +import { + Helpers, + VictoryContainer, + VictoryTheme, + CommonProps, + Wrapper +} from "victory-core"; import { VictorySharedEvents } from "victory-shared-events"; import { getChildren, getCalculatedProps } from "./helper-methods"; import isEqual from "react-fast-compare"; @@ -21,7 +27,10 @@ export default class VictoryGroup extends React.Component { static propTypes = { ...CommonProps.baseProps, ...CommonProps.dataProps, - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), color: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), colorScale: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), @@ -49,7 +58,11 @@ export default class VictoryGroup extends React.Component { theme: VictoryTheme.grayscale }; - static expectedComponents = ["groupComponent", "containerComponent", "labelComponent"]; + static expectedComponents = [ + "groupComponent", + "containerComponent", + "labelComponent" + ]; static getChildren = getChildren; @@ -79,7 +92,10 @@ export default class VictoryGroup extends React.Component { const children = getChildren(props, childComponents, calculatedProps); const getAnimationProps = Wrapper.getAnimationProps.bind(this); return children.map((child, index) => { - const childProps = assign({ animate: getAnimationProps(props, child, index) }, child.props); + const childProps = assign( + { animate: getAnimationProps(props, child, index) }, + child.props + ); return React.cloneElement(child, childProps); }); } @@ -110,14 +126,27 @@ export default class VictoryGroup extends React.Component { render() { const { role } = this.constructor; const props = - this.state && this.state.nodesWillExit ? this.state.oldProps || this.props : this.props; + this.state && this.state.nodesWillExit + ? this.state.oldProps || this.props + : this.props; const modifiedProps = Helpers.modifyProps(props, fallbackProps, role); - const { eventKey, containerComponent, standalone, groupComponent, externalEventMutations } = - modifiedProps; + const { + eventKey, + containerComponent, + standalone, + groupComponent, + externalEventMutations + } = modifiedProps; const childComponents = React.Children.toArray(modifiedProps.children); const calculatedProps = getCalculatedProps(modifiedProps, childComponents); - const newChildren = this.getNewChildren(modifiedProps, childComponents, calculatedProps); - const containerProps = standalone ? this.getContainerProps(modifiedProps, calculatedProps) : {}; + const newChildren = this.getNewChildren( + modifiedProps, + childComponents, + calculatedProps + ); + const containerProps = standalone + ? this.getContainerProps(modifiedProps, calculatedProps) + : {}; const container = standalone ? this.renderContainer(containerComponent, containerProps) : groupComponent; diff --git a/packages/victory-histogram/src/helper-methods.js b/packages/victory-histogram/src/helper-methods.js index 1aa27ab9e..b13938e48 100644 --- a/packages/victory-histogram/src/helper-methods.js +++ b/packages/victory-histogram/src/helper-methods.js @@ -28,7 +28,8 @@ const cacheLastValue = (func) => { const dataOrBinsContainDates = ({ data, bins, x }) => { const xAccessor = Helpers.createAccessor(x || "x"); const dataIsDates = data.some((datum) => xAccessor(datum) instanceof Date); - const binsHasDates = Array.isArray(bins) && bins.some((bin) => bin instanceof Date); + const binsHasDates = + Array.isArray(bins) && bins.some((bin) => bin instanceof Date); return dataIsDates || binsHasDates; }; @@ -37,7 +38,9 @@ const getBinningFunc = ({ data, x, bins, dataOrBinsContainsDates }) => { const xAccessor = Helpers.createAccessor(x || "x"); const bin = d3Array.bin().value(xAccessor); - const niceScale = (dataOrBinsContainsDates ? d3Scale.scaleTime() : d3Scale.scaleLinear()) + const niceScale = ( + dataOrBinsContainsDates ? d3Scale.scaleTime() : d3Scale.scaleLinear() + ) .domain(d3Array.extent(data, xAccessor)) .nice(); @@ -89,7 +92,9 @@ export const getFormattedData = cacheLastValue(({ data = [], x, bins }) => { return { x0, x1, - x: dataOrBinsContainsDates ? new Date((x0.getTime() + x1.getTime()) / 2) : (x0 + x1) / 2, + x: dataOrBinsContainsDates + ? new Date((x0.getTime() + x1.getTime()) / 2) + : (x0 + x1) / 2, y: bin.length, binnedData: [...bin] }; @@ -102,7 +107,9 @@ const getData = (props) => { const { bins, data, x } = props; const dataIsPreformatted = data.some(({ _y }) => !isNil(_y)); - const formattedData = dataIsPreformatted ? data : getFormattedData({ data, x, bins }); + const formattedData = dataIsPreformatted + ? data + : getFormattedData({ data, x, bins }); return Data.getData({ ...props, data: formattedData, x: "x" }); }; @@ -123,7 +130,9 @@ const getDomain = (props, axis) => { ); } - return props.data.length ? Domain.getDomainWithZero({ ...props, data }, "y") : [0, 1]; + return props.data.length + ? Domain.getDomainWithZero({ ...props, data }, "y") + : [0, 1]; }; const getCalculatedValues = (props) => { @@ -240,7 +249,10 @@ const getBaseProps = (props, fallbackProps) => { }; const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { childProps[eventKey].labels = LabelHelpers.getProps(props, index); } diff --git a/packages/victory-histogram/src/index.d.ts b/packages/victory-histogram/src/index.d.ts index 2cd47c00a..da271e11f 100644 --- a/packages/victory-histogram/src/index.d.ts +++ b/packages/victory-histogram/src/index.d.ts @@ -40,4 +40,7 @@ export interface VictoryHistogramProps * Draw SVG histogram charts with React. VictoryHistogram is a composable component, so it doesn't include axes * Check out VictoryChart for complete histogram charts and more. */ -export class VictoryHistogram extends React.Component {} +export class VictoryHistogram extends React.Component< + VictoryHistogramProps, + any +> {} diff --git a/packages/victory-histogram/src/victory-histogram.js b/packages/victory-histogram/src/victory-histogram.js index 8cba45364..cbad55f12 100644 --- a/packages/victory-histogram/src/victory-histogram.js +++ b/packages/victory-histogram/src/victory-histogram.js @@ -10,7 +10,12 @@ import { addEvents, PropTypes as CustomPropTypes } from "victory-core"; -import { getBaseProps, getData, getDomain, getFormattedData } from "./helper-methods"; +import { + getBaseProps, + getData, + getDomain, + getFormattedData +} from "./helper-methods"; const fallbackProps = { width: 450, @@ -21,7 +26,14 @@ const fallbackProps = { const defaultData = []; export class VictoryHistogram extends React.Component { - static animationWhitelist = ["data", "domain", "height", "padding", "style", "width"]; + static animationWhitelist = [ + "data", + "domain", + "height", + "padding", + "style", + "width" + ]; static displayName = "VictoryHistogram"; @@ -51,7 +63,9 @@ export class VictoryHistogram extends React.Component { ...CommonProps.dataProps, binSpacing: CustomPropTypes.nonNegative, bins: PropTypes.oneOfType([ - PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.instanceOf(Date)])), + PropTypes.arrayOf( + PropTypes.oneOfType([PropTypes.number, PropTypes.instanceOf(Date)]) + ), CustomPropTypes.nonNegative ]), cornerRadius: PropTypes.oneOfType([ @@ -106,7 +120,9 @@ export class VictoryHistogram extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-legend/src/helper-methods.js b/packages/victory-legend/src/helper-methods.js index df5436379..5ed6471c9 100644 --- a/packages/victory-legend/src/helper-methods.js +++ b/packages/victory-legend/src/helper-methods.js @@ -3,7 +3,9 @@ import { Helpers, Style, TextSize } from "victory-core"; const getColorScale = (props) => { const { colorScale } = props; - return typeof colorScale === "string" ? Style.getColorScale(colorScale) : colorScale || []; + return typeof colorScale === "string" + ? Style.getColorScale(colorScale) + : colorScale || []; }; const getLabelStyles = (props) => { @@ -29,7 +31,8 @@ const getStyles = (props, styleObject) => { const getCalculatedValues = (props) => { const { orientation, theme } = props; - const defaultStyles = theme && theme.legend && theme.legend.style ? theme.legend.style : {}; + const defaultStyles = + theme && theme.legend && theme.legend.style ? theme.legend.style : {}; const style = getStyles(props, defaultStyles); const colorScale = getColorScale(props); const isHorizontal = orientation === "horizontal"; @@ -78,7 +81,9 @@ const groupData = (props) => { const getColumnWidths = (props, data) => { const gutter = props.gutter || {}; const gutterWidth = - typeof gutter === "object" ? (gutter.left || 0) + (gutter.right || 0) : gutter || 0; + typeof gutter === "object" + ? (gutter.left || 0) + (gutter.right || 0) + : gutter || 0; const dataByColumn = groupBy(data, "column"); const columns = keys(dataByColumn); return columns.reduce((memo, curr, index) => { @@ -93,7 +98,9 @@ const getColumnWidths = (props, data) => { const getRowHeights = (props, data) => { const gutter = props.rowGutter || {}; const gutterHeight = - typeof gutter === "object" ? (gutter.top || 0) + (gutter.bottom || 0) : gutter || 0; + typeof gutter === "object" + ? (gutter.top || 0) + (gutter.bottom || 0) + : gutter || 0; const dataByRow = groupBy(data, "row"); return keys(dataByRow).reduce((memo, curr, index) => { const rows = dataByRow[curr]; @@ -109,7 +116,10 @@ const getTitleDimensions = (props) => { const style = (props.style && props.style.title) || {}; const textSize = TextSize.approximateTextSize(props.title, style); const padding = style.padding || 0; - return { height: textSize.height + 2 * padding || 0, width: textSize.width + 2 * padding || 0 }; + return { + height: textSize.height + 2 * padding || 0, + width: textSize.width + 2 * padding || 0 + }; }; const getOffset = (datum, rowHeights, columnWidths) => { @@ -132,7 +142,8 @@ const getAnchors = (titleOrientation, centerTitle) => { verticalAnchor: titleOrientation === "bottom" ? "end" : "start" }; if (centerTitle) { - const horizontal = titleOrientation === "top" || titleOrientation === "bottom"; + const horizontal = + titleOrientation === "top" || titleOrientation === "bottom"; return { textAnchor: horizontal ? "middle" : standardAnchors.textAnchor, verticalAnchor: horizontal ? standardAnchors.verticalAnchor : "middle" @@ -145,7 +156,8 @@ const getAnchors = (titleOrientation, centerTitle) => { const getTitleStyle = (props) => { const { titleOrientation, centerTitle, titleComponent } = props; const baseStyle = (props.style && props.style.title) || {}; - const componentStyle = (titleComponent.props && titleComponent.props.style) || {}; + const componentStyle = + (titleComponent.props && titleComponent.props.style) || {}; const anchors = getAnchors(titleOrientation, centerTitle); return Array.isArray(componentStyle) ? componentStyle.map((obj) => defaults({}, obj, baseStyle, anchors)) @@ -158,7 +170,8 @@ const getTitleProps = (props, borderProps) => { const { height, width } = borderProps; const style = getTitleStyle(props); const padding = Array.isArray(style) ? style[0].padding : style.padding; - const horizontal = titleOrientation === "top" || titleOrientation === "bottom"; + const horizontal = + titleOrientation === "top" || titleOrientation === "bottom"; const xOrientation = titleOrientation === "bottom" ? "bottom" : "top"; const yOrientation = titleOrientation === "right" ? "right" : "left"; const standardPadding = { @@ -172,8 +185,14 @@ const getTitleProps = (props, borderProps) => { const yOffset = horizontal ? getPadding() : standardPadding.y; return { - x: titleOrientation === "right" ? props.x + width - xOffset : props.x + xOffset, - y: titleOrientation === "bottom" ? props.y + height - yOffset : props.y + yOffset, + x: + titleOrientation === "right" + ? props.x + width - xOffset + : props.x + xOffset, + y: + titleOrientation === "bottom" + ? props.y + height - yOffset + : props.y + yOffset, style, text: title }; @@ -181,7 +200,8 @@ const getTitleProps = (props, borderProps) => { const getBorderProps = (props, contentHeight, contentWidth) => { const { x, y, borderPadding, style } = props; - const height = (contentHeight || 0) + borderPadding.top + borderPadding.bottom; + const height = + (contentHeight || 0) + borderPadding.top + borderPadding.bottom; const width = (contentWidth || 0) + borderPadding.left + borderPadding.right; return { x, y, height, width, style: assign({ fill: "none" }, style.border) }; }; @@ -193,7 +213,9 @@ const getDimensions = (props, fallbackProps) => { const groupedData = groupData(props); const columnWidths = getColumnWidths(props, groupedData); const rowHeights = getRowHeights(props, groupedData); - const titleDimensions = title ? getTitleDimensions(props) : { height: 0, width: 0 }; + const titleDimensions = title + ? getTitleDimensions(props) + : { height: 0, width: 0 }; return { height: @@ -230,7 +252,9 @@ const getBaseProps = (props, fallbackProps) => { const columnWidths = getColumnWidths(props, groupedData); const rowHeights = getRowHeights(props, groupedData); const labelStyles = getLabelStyles(props); - const titleDimensions = title ? getTitleDimensions(props) : { height: 0, width: 0 }; + const titleDimensions = title + ? getTitleDimensions(props) + : { height: 0, width: 0 }; const titleOffset = { x: titleOrientation === "left" ? titleDimensions.width : 0, y: titleOrientation === "top" ? titleDimensions.height : 0 diff --git a/packages/victory-legend/src/index.d.ts b/packages/victory-legend/src/index.d.ts index 83637c2dc..3332075b0 100644 --- a/packages/victory-legend/src/index.d.ts +++ b/packages/victory-legend/src/index.d.ts @@ -36,12 +36,17 @@ export interface VictoryLegendProps }>; dataComponent?: React.ReactElement; eventKey?: StringOrNumberOrCallback | string[]; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryLegendTTargetType, + StringOrNumberOrCallback + >[]; gutter?: number | { left: number; right: number }; itemsPerRow?: number; orientation?: VictoryLegendOrientationType; rowGutter?: number | Omit; - style?: VictoryStyleInterface & { title?: VictoryLabelStyleObject | VictoryLabelStyleObject[] }; + style?: VictoryStyleInterface & { + title?: VictoryLabelStyleObject | VictoryLabelStyleObject[]; + }; symbolSpacer?: number; title?: string | string[]; titleComponent?: React.ReactElement; diff --git a/packages/victory-legend/src/victory-legend.js b/packages/victory-legend/src/victory-legend.js index 7529c6fc0..41c401f1d 100644 --- a/packages/victory-legend/src/victory-legend.js +++ b/packages/victory-legend/src/victory-legend.js @@ -64,7 +64,10 @@ class VictoryLegend extends React.Component { dataComponent: PropTypes.element, eventKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), events: PropTypes.arrayOf( @@ -72,7 +75,10 @@ class VictoryLegend extends React.Component { target: PropTypes.oneOf(["data", "labels", "parent"]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -84,7 +90,10 @@ class VictoryLegend extends React.Component { childName: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), mutation: PropTypes.function, @@ -182,19 +191,38 @@ class VictoryLegend extends React.Component { if (_dataKey === "all") { return undefined; } - const labelProps = this.getComponentProps(labelComponent, "labels", index); + const labelProps = this.getComponentProps( + labelComponent, + "labels", + index + ); if (labelProps.text !== undefined && labelProps.text !== null) { return React.cloneElement(labelComponent, labelProps); } return undefined; }) .filter(Boolean); - const borderProps = this.getComponentProps(props.borderComponent, "border", "all"); - const borderComponent = React.cloneElement(props.borderComponent, borderProps); + const borderProps = this.getComponentProps( + props.borderComponent, + "border", + "all" + ); + const borderComponent = React.cloneElement( + props.borderComponent, + borderProps + ); if (title) { const titleProps = this.getComponentProps(props.title, "title", "all"); - const titleComponent = React.cloneElement(props.titleComponent, titleProps); - return [borderComponent, ...dataComponents, titleComponent, ...labelComponents]; + const titleComponent = React.cloneElement( + props.titleComponent, + titleProps + ); + return [ + borderComponent, + ...dataComponents, + titleComponent, + ...labelComponents + ]; } return [borderComponent, ...dataComponents, ...labelComponents]; } diff --git a/packages/victory-line/src/curve.js b/packages/victory-line/src/curve.js index 307730623..4d311fba7 100644 --- a/packages/victory-line/src/curve.js +++ b/packages/victory-line/src/curve.js @@ -34,11 +34,15 @@ const toNewName = (interpolation) => { const getLineFunction = (props) => { const { polar, scale, horizontal } = props; const defaultOpenCurve = polar ? false : true; - const openCurve = props.openCurve === undefined ? defaultOpenCurve : props.openCurve; - const interpolationFunction = typeof props.interpolation === "function" && props.interpolation; + const openCurve = + props.openCurve === undefined ? defaultOpenCurve : props.openCurve; + const interpolationFunction = + typeof props.interpolation === "function" && props.interpolation; const interpolationName = typeof props.interpolation === "string" && - (!openCurve ? `${toNewName(props.interpolation)}Closed` : toNewName(props.interpolation)); + (!openCurve + ? `${toNewName(props.interpolation)}Closed` + : toNewName(props.interpolation)); return polar ? d3Shape .lineRadial() @@ -77,7 +81,8 @@ const Curve = (props) => { props = evaluateProps(props); const { polar, origin } = props; const lineFunction = getLineFunction(props); - const defaultTransform = polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; + const defaultTransform = + polar && origin ? `translate(${origin.x}, ${origin.y})` : undefined; return React.cloneElement(props.pathComponent, { ...props.events, diff --git a/packages/victory-line/src/helper-methods.js b/packages/victory-line/src/helper-methods.js index 085d17222..23659ca13 100644 --- a/packages/victory-line/src/helper-methods.js +++ b/packages/victory-line/src/helper-methods.js @@ -24,7 +24,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = props.polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = props.polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; const defaultStyles = Helpers.getDefaultStyles(props, "line"); const style = Helpers.getStyles(props.style, defaultStyles); @@ -87,7 +89,10 @@ const getBaseProps = (props, fallbackProps) => { }; return data.reduce((childProps, datum, index) => { const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { const eventKey = !isNil(datum.eventKey) ? datum.eventKey : index; childProps[eventKey] = { labels: LabelHelpers.getProps(props, index) }; } diff --git a/packages/victory-line/src/victory-line.js b/packages/victory-line/src/victory-line.js index 4207bd46a..e46cbc1c0 100644 --- a/packages/victory-line/src/victory-line.js +++ b/packages/victory-line/src/victory-line.js @@ -32,12 +32,21 @@ const options = { }; class VictoryLine extends React.Component { - static animationWhitelist = ["data", "domain", "height", "padding", "samples", "style", "width"]; + static animationWhitelist = [ + "data", + "domain", + "height", + "padding", + "samples", + "style", + "width" + ]; static displayName = "VictoryLine"; static role = "line"; static defaultTransitions = DefaultTransitions.continuousTransitions(); - static defaultPolarTransitions = DefaultTransitions.continuousPolarTransitions(); + static defaultPolarTransitions = + DefaultTransitions.continuousPolarTransitions(); static continuous = true; static propTypes = { @@ -101,7 +110,9 @@ class VictoryLine extends React.Component { } const children = this.renderContinuousData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } export default addEvents(VictoryLine, options); diff --git a/packages/victory-pie/src/helper-methods.js b/packages/victory-pie/src/helper-methods.js index 314ab5354..5c91ce927 100644 --- a/packages/victory-pie/src/helper-methods.js +++ b/packages/victory-pie/src/helper-methods.js @@ -35,8 +35,14 @@ const getOrigin = (props, padding) => { const { width, height } = props; const origin = isPlainObject(props.origin) ? props.origin : {}; return { - x: origin.x !== undefined ? origin.x : (padding.left - padding.right + width) / 2, - y: origin.y !== undefined ? origin.y : (padding.top - padding.bottom + height) / 2 + x: + origin.x !== undefined + ? origin.x + : (padding.left - padding.right + width) / 2, + y: + origin.y !== undefined + ? origin.y + : (padding.top - padding.bottom + height) / 2 }; }; @@ -58,7 +64,9 @@ const getCalculatedValues = (props) => { const { colorScale } = props; const styleObject = Helpers.getDefaultStyles(props, "pie"); const style = Helpers.getStyles(props.style, styleObject, "auto", "100%"); - const colors = Array.isArray(colorScale) ? colorScale : Style.getColorScale(colorScale); + const colors = Array.isArray(colorScale) + ? colorScale + : Style.getColorScale(colorScale); const padding = Helpers.getPadding(props); const defaultRadius = getRadius(props, padding); const origin = getOrigin(props, padding); @@ -144,7 +152,9 @@ const getBaseLabelAngle = (slice, labelPosition, labelStyle) => { if (labelPosition.angle !== undefined) { baseAngle = labelStyle.angle; } else if (labelPosition === "centroid") { - baseAngle = Helpers.radiansToDegrees((slice.startAngle + slice.endAngle) / 2); + baseAngle = Helpers.radiansToDegrees( + (slice.startAngle + slice.endAngle) / 2 + ); } else { baseAngle = labelPosition === "startAngle" @@ -173,10 +183,15 @@ const getLabelProps = (text, dataProps, calculatedValues) => { assign({ text }, dataProps) ); const labelPosition = - Helpers.evaluateProp(calculatedValues.labelPosition, assign({ text }, dataProps)) || "centroid"; + Helpers.evaluateProp( + calculatedValues.labelPosition, + assign({ text }, dataProps) + ) || "centroid"; const labelPlacement = - Helpers.evaluateProp(calculatedValues.labelPlacement, assign({ text }, dataProps)) || - "vertical"; + Helpers.evaluateProp( + calculatedValues.labelPlacement, + assign({ text }, dataProps) + ) || "vertical"; const labelStyle = assign({ padding: 0 }, style.labels); const evaluatedStyle = Helpers.evaluateStyle( labelStyle, @@ -188,7 +203,8 @@ const getLabelProps = (text, dataProps, calculatedValues) => { const labelAngle = getLabelAngle(baseAngle, labelPlacement); const orientation = getLabelOrientation(baseAngle, labelPlacement); const textAnchor = labelStyle.textAnchor || getTextAnchor(orientation); - const verticalAnchor = labelStyle.verticalAnchor || getVerticalAnchor(orientation); + const verticalAnchor = + labelStyle.verticalAnchor || getVerticalAnchor(orientation); const labelProps = { width, @@ -264,7 +280,10 @@ export const getBaseProps = (props, fallbackProps) => { data: dataProps }; const text = getLabelText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { const evaluatedText = Helpers.evaluateProp(text, dataProps); childProps[eventKey].labels = getLabelProps( evaluatedText, diff --git a/packages/victory-pie/src/index.d.ts b/packages/victory-pie/src/index.d.ts index c50091662..a2d066e2f 100644 --- a/packages/victory-pie/src/index.d.ts +++ b/packages/victory-pie/src/index.d.ts @@ -15,8 +15,14 @@ import { VictoryStyleInterface } from "victory-core"; -export type VictorySliceLabelPositionType = "startAngle" | "centroid" | "endAngle"; -export type VictorySliceLabelPlacementType = "vertical" | "parallel" | "perpendicular"; +export type VictorySliceLabelPositionType = + | "startAngle" + | "centroid" + | "endAngle"; +export type VictorySliceLabelPlacementType = + | "vertical" + | "parallel" + | "perpendicular"; export type VictorySliceTTargetType = "data" | "labels" | "parent"; export interface SliceProps extends VictoryCommonProps { diff --git a/packages/victory-pie/src/slice.js b/packages/victory-pie/src/slice.js index be2e34e8f..9ebe57f87 100644 --- a/packages/victory-pie/src/slice.js +++ b/packages/victory-pie/src/slice.js @@ -37,8 +37,14 @@ const evaluateProps = (props) => { * `tabIndex` */ const style = Helpers.evaluateStyle(props.style, props); - const radius = Helpers.evaluateProp(props.radius, assign({}, props, { style })); - const innerRadius = Helpers.evaluateProp(props.innerRadius, assign({}, props, { style, radius })); + const radius = Helpers.evaluateProp( + props.radius, + assign({}, props, { style }) + ); + const innerRadius = Helpers.evaluateProp( + props.innerRadius, + assign({}, props, { style, radius }) + ); const ariaLabel = Helpers.evaluateProp(props.ariaLabel, props); const id = Helpers.evaluateProp(props.id, props); diff --git a/packages/victory-pie/src/victory-pie.js b/packages/victory-pie/src/victory-pie.js index 53e8b1ff9..2cd2c762f 100644 --- a/packages/victory-pie/src/victory-pie.js +++ b/packages/victory-pie/src/victory-pie.js @@ -86,14 +86,20 @@ class VictoryPie extends React.Component { ]) ]), containerComponent: PropTypes.element, - cornerRadius: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + cornerRadius: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), data: PropTypes.array, dataComponent: PropTypes.element, disableInlineStyes: PropTypes.bool, endAngle: PropTypes.number, eventKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), events: PropTypes.arrayOf( @@ -101,7 +107,10 @@ class VictoryPie extends React.Component { target: PropTypes.oneOf(["data", "labels", "parent"]), eventKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -113,7 +122,10 @@ class VictoryPie extends React.Component { childName: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), mutation: PropTypes.function, @@ -122,7 +134,10 @@ class VictoryPie extends React.Component { ), groupComponent: PropTypes.element, height: CustomPropTypes.nonNegative, - innerRadius: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + innerRadius: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), labelComponent: PropTypes.element, labelPlacement: PropTypes.oneOfType([ PropTypes.func, @@ -132,14 +147,20 @@ class VictoryPie extends React.Component { PropTypes.func, PropTypes.oneOf(["startAngle", "centroid", "endAngle"]) ]), - labelRadius: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + labelRadius: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), labels: PropTypes.oneOfType([PropTypes.func, PropTypes.array]), name: PropTypes.string, origin: PropTypes.shape({ x: CustomPropTypes.nonNegative, y: CustomPropTypes.nonNegative }), - padAngle: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + padAngle: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), padding: PropTypes.oneOfType([ PropTypes.number, PropTypes.shape({ @@ -156,7 +177,10 @@ class VictoryPie extends React.Component { }), sortKey: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), @@ -172,13 +196,19 @@ class VictoryPie extends React.Component { width: CustomPropTypes.nonNegative, x: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), y: PropTypes.oneOfType([ PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]) @@ -224,7 +254,9 @@ class VictoryPie extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-polar-axis/src/helper-methods.js b/packages/victory-polar-axis/src/helper-methods.js index 0496fa2d2..28138fb59 100644 --- a/packages/victory-polar-axis/src/helper-methods.js +++ b/packages/victory-polar-axis/src/helper-methods.js @@ -27,17 +27,31 @@ const getEvaluatedStyles = (style, props) => { const getStyleObject = (props) => { const { theme = {}, dependentAxis } = props; const generalAxisStyle = - (theme.polarAxis && theme.polarAxis.style) || (theme.axis && theme.axis.style); - const polarAxisType = dependentAxis ? "polarDependentAxis" : "polarIndependentAxis"; + (theme.polarAxis && theme.polarAxis.style) || + (theme.axis && theme.axis.style); + const polarAxisType = dependentAxis + ? "polarDependentAxis" + : "polarIndependentAxis"; const standardAxisType = dependentAxis ? "dependentAxis" : "independentAxis"; const specificAxisStyle = (theme[polarAxisType] && theme[polarAxisType].style) || (theme[standardAxisType] && theme[standardAxisType].style); const mergeStyles = () => { - const styleNamespaces = ["axis", "axisLabel", "grid", "parent", "tickLabels", "ticks"]; + const styleNamespaces = [ + "axis", + "axisLabel", + "grid", + "parent", + "tickLabels", + "ticks" + ]; return styleNamespaces.reduce((memo, curr) => { - memo[curr] = defaults({}, specificAxisStyle[curr], generalAxisStyle[curr]); + memo[curr] = defaults( + {}, + specificAxisStyle[curr], + generalAxisStyle[curr] + ); return memo; }, {}); }; @@ -110,8 +124,16 @@ const getAxisAngle = (props) => { //eslint-disable-next-line max-params const getTickProps = (props, calculatedValues, tickValue, index) => { - const { axisType, radius, scale, style, stringTicks, ticks, tickFormat, origin } = - calculatedValues; + const { + axisType, + radius, + scale, + style, + stringTicks, + ticks, + tickFormat, + origin + } = calculatedValues; const text = tickFormat(tickValue, index, ticks); const tick = stringTicks ? stringTicks[index] : tickValue; const { tickStyle } = getEvaluatedStyles(style, { @@ -125,11 +147,14 @@ const getTickProps = (props, calculatedValues, tickValue, index) => { axisType, text }); - const axisAngle = axisType === "radial" ? getAxisAngle(props, scale) : undefined; + const axisAngle = + axisType === "radial" ? getAxisAngle(props, scale) : undefined; const tickPadding = tickStyle.padding || tickStyle.size || 0; const padAngle = Helpers.degreesToRadians(90 - axisAngle); const tickAngle = - axisType === "angular" ? scale(tickValue) : Helpers.degreesToRadians(-1 * axisAngle); + axisType === "angular" + ? scale(tickValue) + : Helpers.degreesToRadians(-1 * axisAngle); const tickRadius = axisType === "angular" ? radius : scale(tickValue); return axisType === "angular" @@ -146,17 +171,37 @@ const getTickProps = (props, calculatedValues, tickValue, index) => { index, datum: tick, style: tickStyle, - x1: tickRadius * Math.cos(tickAngle) + Math.cos(padAngle) * tickPadding + origin.x, - x2: tickRadius * Math.cos(tickAngle) - Math.cos(padAngle) * tickPadding + origin.x, - y1: tickRadius * Math.sin(tickAngle) + Math.sin(padAngle) * tickPadding + origin.y, - y2: tickRadius * Math.sin(tickAngle) - Math.sin(padAngle) * tickPadding + origin.y + x1: + tickRadius * Math.cos(tickAngle) + + Math.cos(padAngle) * tickPadding + + origin.x, + x2: + tickRadius * Math.cos(tickAngle) - + Math.cos(padAngle) * tickPadding + + origin.x, + y1: + tickRadius * Math.sin(tickAngle) + + Math.sin(padAngle) * tickPadding + + origin.y, + y2: + tickRadius * Math.sin(tickAngle) - + Math.sin(padAngle) * tickPadding + + origin.y }; }; //eslint-disable-next-line max-params const getTickLabelProps = (props, calculatedValues, tickValue, index) => { - const { axisType, radius, tickFormat, style, scale, ticks, stringTicks, origin } = - calculatedValues; + const { + axisType, + radius, + tickFormat, + style, + scale, + ticks, + stringTicks, + origin + } = calculatedValues; const text = tickFormat(tickValue, index, ticks); const tick = stringTicks ? stringTicks[index] : tickValue; const { labelStyle } = getEvaluatedStyles(style, { @@ -177,19 +222,27 @@ const getTickLabelProps = (props, calculatedValues, tickValue, index) => { : props.labelPlacement; const tickPadding = labelStyle.padding || 0; const angularPadding = 0; // TODO: do some geometry - const axisAngle = axisType === "radial" ? getAxisAngle(props, scale) : undefined; + const axisAngle = + axisType === "radial" ? getAxisAngle(props, scale) : undefined; const labelAngle = axisType === "angular" ? Helpers.radiansToDegrees(scale(tickValue)) : axisAngle + angularPadding; const textAngle = labelStyle.angle === undefined - ? LabelHelpers.getPolarAngle(assign({}, props, { labelPlacement }), labelAngle) + ? LabelHelpers.getPolarAngle( + assign({}, props, { labelPlacement }), + labelAngle + ) : labelStyle.angle; - const labelRadius = axisType === "angular" ? radius + tickPadding : scale(tickValue); + const labelRadius = + axisType === "angular" ? radius + tickPadding : scale(tickValue); const textAnchor = labelStyle.textAnchor || - LabelHelpers.getPolarTextAnchor(assign({}, props, { labelPlacement }), labelAngle); + LabelHelpers.getPolarTextAnchor( + assign({}, props, { labelPlacement }), + labelAngle + ); return { index, datum: tick, @@ -204,8 +257,16 @@ const getTickLabelProps = (props, calculatedValues, tickValue, index) => { //eslint-disable-next-line max-params const getGridProps = (props, calculatedValues, tickValue, index) => { - const { axisType, radius, style, scale, stringTicks, ticks, tickFormat, origin } = - calculatedValues; + const { + axisType, + radius, + style, + scale, + stringTicks, + ticks, + tickFormat, + origin + } = calculatedValues; const text = tickFormat(tickValue, index, ticks); const { startAngle, endAngle, innerRadius = 0 } = props; const tick = stringTicks ? stringTicks[index] : tickValue; @@ -254,26 +315,40 @@ const getAxisLabelProps = (props, calculatedValues) => { ? axisLabelComponent.props.labelPlacement : props.labelPlacement; const labelStyle = (style && style.axisLabel) || {}; - const axisAngle = axisType === "radial" ? getAxisAngle(props, scale) : undefined; + const axisAngle = + axisType === "radial" ? getAxisAngle(props, scale) : undefined; const textAngle = labelStyle.angle === undefined - ? LabelHelpers.getPolarAngle(assign({}, props, { labelPlacement }), axisAngle) + ? LabelHelpers.getPolarAngle( + assign({}, props, { labelPlacement }), + axisAngle + ) : labelStyle.angle; const labelRadius = radius + (labelStyle.padding || 0); const textAnchor = labelStyle.textAnchor || - LabelHelpers.getTextPolarAnchor(assign({}, props, { labelPlacement }), axisAngle); + LabelHelpers.getTextPolarAnchor( + assign({}, props, { labelPlacement }), + axisAngle + ); const verticalAnchor = labelStyle.verticalAnchor || - LabelHelpers.getPolarVerticalAnchor(assign({}, props, { labelPlacement }), axisAngle); + LabelHelpers.getPolarVerticalAnchor( + assign({}, props, { labelPlacement }), + axisAngle + ); return { style: labelStyle, angle: textAngle, textAnchor, verticalAnchor, text: props.label, - x: getPosition(labelRadius, Helpers.degreesToRadians(axisAngle), "x") + origin.x, - y: getPosition(labelRadius, Helpers.degreesToRadians(axisAngle), "y") + origin.y + x: + getPosition(labelRadius, Helpers.degreesToRadians(axisAngle), "x") + + origin.x, + y: + getPosition(labelRadius, Helpers.degreesToRadians(axisAngle), "y") + + origin.y }; }; @@ -314,7 +389,8 @@ const getCalculatedValues = (props) => { const range = getRange(props, axis); const scale = getScale(props); const initialTicks = Axis.getTicks(props, scale); - const ticks = axisType === "angular" ? filterTicks(initialTicks, scale) : initialTicks; + const ticks = + axisType === "angular" ? filterTicks(initialTicks, scale) : initialTicks; const tickFormat = Axis.getTickFormat(props, scale); const radius = getRadius(props); const origin = Helpers.getPolarOrigin(props); diff --git a/packages/victory-polar-axis/src/index.d.ts b/packages/victory-polar-axis/src/index.d.ts index 869a6d2be..b53d75550 100644 --- a/packages/victory-polar-axis/src/index.d.ts +++ b/packages/victory-polar-axis/src/index.d.ts @@ -19,7 +19,12 @@ import { VictorySingleLabelableProps } from "victory-core"; -export type VictoryPolarAxisTTargetType = "axis" | "axisLabel" | "grid" | "ticks" | "tickLabels"; +export type VictoryPolarAxisTTargetType = + | "axis" + | "axisLabel" + | "grid" + | "ticks" + | "tickLabels"; export interface VictoryPolarAxisProps extends VictoryAxisCommonProps, @@ -31,7 +36,10 @@ export interface VictoryPolarAxisProps circularGridComponent?: React.ReactElement; domain?: DomainPropType; endAngle?: number; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryPolarAxisTTargetType, + string | number + >[]; gridComponent?: React.ReactElement; innerRadius?: number; labelOrientation?: LabelOrientationType; @@ -39,4 +47,7 @@ export interface VictoryPolarAxisProps startAngle?: number; } -export class VictoryPolarAxis extends React.Component {} +export class VictoryPolarAxis extends React.Component< + VictoryPolarAxisProps, + any +> {} diff --git a/packages/victory-polar-axis/src/victory-polar-axis.js b/packages/victory-polar-axis/src/victory-polar-axis.js index 45657527d..fd262e9b0 100644 --- a/packages/victory-polar-axis/src/victory-polar-axis.js +++ b/packages/victory-polar-axis/src/victory-polar-axis.js @@ -61,7 +61,11 @@ class VictoryPolarAxis extends React.Component { axisAngle: PropTypes.number, axisComponent: PropTypes.element, axisLabelComponent: PropTypes.element, - axisValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]), + axisValue: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.string, + PropTypes.object + ]), categories: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.shape({ @@ -77,10 +81,19 @@ class VictoryPolarAxis extends React.Component { endAngle: PropTypes.number, events: PropTypes.arrayOf( PropTypes.shape({ - target: PropTypes.oneOf(["axis", "axisLabel", "grid", "ticks", "tickLabels"]), + target: PropTypes.oneOf([ + "axis", + "axisLabel", + "grid", + "ticks", + "tickLabels" + ]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), eventHandlers: PropTypes.object @@ -104,7 +117,10 @@ class VictoryPolarAxis extends React.Component { CustomPropTypes.integer, CustomPropTypes.greaterThanZero ]), - tickFormat: PropTypes.oneOfType([PropTypes.func, CustomPropTypes.homogeneousArray]), + tickFormat: PropTypes.oneOfType([ + PropTypes.func, + CustomPropTypes.homogeneousArray + ]), tickLabelComponent: PropTypes.element, tickValues: CustomPropTypes.homogeneousArray }; @@ -144,7 +160,9 @@ class VictoryPolarAxis extends React.Component { renderAxisLine(props) { const { dependentAxis } = props; - const axisComponent = dependentAxis ? props.axisComponent : props.circularAxisComponent; + const axisComponent = dependentAxis + ? props.axisComponent + : props.circularAxisComponent; const axisProps = this.getComponentProps(axisComponent, "axis", 0); return React.cloneElement(axisComponent, axisProps); } @@ -154,7 +172,11 @@ class VictoryPolarAxis extends React.Component { if (!label || !dependentAxis) { return null; } - const axisLabelProps = this.getComponentProps(axisLabelComponent, "axisLabel", 0); + const axisLabelProps = this.getComponentProps( + axisLabelComponent, + "axisLabel", + 0 + ); return React.cloneElement(axisLabelComponent, axisLabelProps); } @@ -163,11 +185,14 @@ class VictoryPolarAxis extends React.Component { const shouldRender = (componentProps) => { const { style = {}, events = {} } = componentProps; const visible = - style.stroke !== "transparent" && style.stroke !== "none" && style.strokeWidth !== 0; + style.stroke !== "transparent" && + style.stroke !== "none" && + style.strokeWidth !== 0; return visible || !isEmpty(events); }; const axisType = props.dependentAxis ? "radial" : "angular"; - const gridComponent = axisType === "radial" ? props.circularGridComponent : props.gridComponent; + const gridComponent = + axisType === "radial" ? props.circularGridComponent : props.gridComponent; const tickComponents = this.dataKeys .map((key, index) => { const tickProps = assign( @@ -227,7 +252,9 @@ class VictoryPolarAxis extends React.Component { return this.animateComponent(props, animationWhitelist); } const children = this.renderAxis(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-scatter/src/helper-methods.js b/packages/victory-scatter/src/helper-methods.js index 276945b72..05ce72966 100644 --- a/packages/victory-scatter/src/helper-methods.js +++ b/packages/victory-scatter/src/helper-methods.js @@ -33,7 +33,9 @@ const getBubbleSize = (datum, props) => { const getSize = (datum, props) => { const { size, z } = props; if (datum.size) { - return typeof datum.size === "function" ? datum.size : Math.max(datum.size, 1); + return typeof datum.size === "function" + ? datum.size + : Math.max(datum.size, 1); } else if (typeof props.size === "function") { return size; } else if (datum[z]) { @@ -62,7 +64,9 @@ const getCalculatedValues = (props) => { .domain(domain.y) .range(props.horizontal ? range.x : range.y) }; - const origin = props.polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = props.polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; const z = props.bubbleProperty || "z"; let data = Data.getData(props); @@ -132,7 +136,10 @@ const getBaseProps = (props, fallbackProps) => { childProps[eventKey] = { data: dataProps }; const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { childProps[eventKey].labels = LabelHelpers.getProps(props, index); } diff --git a/packages/victory-scatter/src/index.d.ts b/packages/victory-scatter/src/index.d.ts index bb43de547..aa7498b96 100644 --- a/packages/victory-scatter/src/index.d.ts +++ b/packages/victory-scatter/src/index.d.ts @@ -16,7 +16,10 @@ export interface VictoryScatterProps VictoryDatableProps, VictoryMultiLabelableProps { bubbleProperty?: string; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryScatterTTargetType, + StringOrNumberOrCallback + >[]; eventKey?: StringOrNumberOrCallback; maxBubbleSize?: number; minBubbleSize?: number; diff --git a/packages/victory-scatter/src/victory-scatter.js b/packages/victory-scatter/src/victory-scatter.js index f157d3718..11cc88fbb 100644 --- a/packages/victory-scatter/src/victory-scatter.js +++ b/packages/victory-scatter/src/victory-scatter.js @@ -98,7 +98,9 @@ class VictoryScatter extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-selection-container/src/selection-helpers.js b/packages/victory-selection-container/src/selection-helpers.js index 92231de7d..068e70de6 100644 --- a/packages/victory-selection-container/src/selection-helpers.js +++ b/packages/victory-selection-container/src/selection-helpers.js @@ -34,7 +34,11 @@ const SelectionHelpers = { return childData ? { childName, data: childData } : null; } }; - return Helpers.reduceChildren(React.Children.toArray(props.children), iteratee, props); + return Helpers.reduceChildren( + React.Children.toArray(props.children), + iteratee, + props + ); }, filterDatasets(props, datasets, bounds) { @@ -80,17 +84,30 @@ const SelectionHelpers = { // eslint-disable-next-line complexity, max-statements onMouseDown(evt, targetProps) { evt.preventDefault(); - const { activateSelectedData, allowSelection, polar, selectedData } = targetProps; + const { activateSelectedData, allowSelection, polar, selectedData } = + targetProps; if (!allowSelection) { return {}; } const dimension = this.getDimension(targetProps); const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); const { x, y } = Selection.getSVGEventCoordinates(evt, parentSVG); - const x1 = polar || dimension !== "y" ? x : Selection.getDomainCoordinates(targetProps).x[0]; - const y1 = polar || dimension !== "x" ? y : Selection.getDomainCoordinates(targetProps).y[0]; - const x2 = polar || dimension !== "y" ? x : Selection.getDomainCoordinates(targetProps).x[1]; - const y2 = polar || dimension !== "x" ? y : Selection.getDomainCoordinates(targetProps).y[1]; + const x1 = + polar || dimension !== "y" + ? x + : Selection.getDomainCoordinates(targetProps).x[0]; + const y1 = + polar || dimension !== "x" + ? y + : Selection.getDomainCoordinates(targetProps).y[0]; + const x2 = + polar || dimension !== "y" + ? x + : Selection.getDomainCoordinates(targetProps).x[1]; + const y2 = + polar || dimension !== "x" + ? y + : Selection.getDomainCoordinates(targetProps).y[1]; const mutatedProps = { x1, y1, select: true, x2, y2, parentSVG }; if (selectedData && isFunction(targetProps.onSelectionCleared)) { @@ -120,8 +137,14 @@ const SelectionHelpers = { } else { const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); const { x, y } = Selection.getSVGEventCoordinates(evt, parentSVG); - const x2 = polar || dimension !== "y" ? x : Selection.getDomainCoordinates(targetProps).x[1]; - const y2 = polar || dimension !== "x" ? y : Selection.getDomainCoordinates(targetProps).y[1]; + const x2 = + polar || dimension !== "y" + ? x + : Selection.getDomainCoordinates(targetProps).x[1]; + const y2 = + polar || dimension !== "x" + ? y + : Selection.getDomainCoordinates(targetProps).y[1]; return { target: "parent", mutation: () => { @@ -160,7 +183,11 @@ const SelectionHelpers = { }; const callbackMutation = selectedData && isFunction(targetProps.onSelection) - ? targetProps.onSelection(selectedData, bounds, defaults({}, mutatedProps, targetProps)) + ? targetProps.onSelection( + selectedData, + bounds, + defaults({}, mutatedProps, targetProps) + ) : {}; const parentMutation = [ { diff --git a/packages/victory-selection-container/src/victory-selection-container.js b/packages/victory-selection-container/src/victory-selection-container.js index 90ceaf51e..6028e3858 100644 --- a/packages/victory-selection-container/src/victory-selection-container.js +++ b/packages/victory-selection-container/src/victory-selection-container.js @@ -36,22 +36,34 @@ export const selectionContainerMixin = (base) => target: "parent", eventHandlers: { onMouseDown: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseDown(evt, targetProps); }, onTouchStart: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseDown(evt, targetProps); }, onMouseMove: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseMove(evt, targetProps); }, onTouchMove: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseMove(evt, targetProps); }, onMouseUp: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseUp(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseUp(evt, targetProps); }, onTouchEnd: (evt, targetProps) => { - return props.disable ? {} : SelectionHelpers.onMouseUp(evt, targetProps); + return props.disable + ? {} + : SelectionHelpers.onMouseUp(evt, targetProps); } } } @@ -59,7 +71,8 @@ export const selectionContainerMixin = (base) => }; getRect(props) { - const { x1, x2, y1, y2, selectionStyle, selectionComponent, name } = props; + const { x1, x2, y1, y2, selectionStyle, selectionComponent, name } = + props; const width = Math.abs(x2 - x1) || 1; const height = Math.abs(y2 - y1) || 1; const x = Math.min(x1, x2); diff --git a/packages/victory-shared-events/src/index.d.ts b/packages/victory-shared-events/src/index.d.ts index 68c106485..1fcdb72dd 100644 --- a/packages/victory-shared-events/src/index.d.ts +++ b/packages/victory-shared-events/src/index.d.ts @@ -17,4 +17,7 @@ export type VictorySharedEventsProps = { >[]; }; -export class VictorySharedEvents extends React.Component {} +export class VictorySharedEvents extends React.Component< + VictorySharedEventsProps, + any +> {} diff --git a/packages/victory-shared-events/src/victory-shared-events.js b/packages/victory-shared-events/src/victory-shared-events.js index a04afe266..956e192d8 100644 --- a/packages/victory-shared-events/src/victory-shared-events.js +++ b/packages/victory-shared-events/src/victory-shared-events.js @@ -1,8 +1,21 @@ /*global window:false */ -import { assign, isFunction, defaults, isEmpty, fromPairs, keys, difference } from "lodash"; +import { + assign, + isFunction, + defaults, + isEmpty, + fromPairs, + keys, + difference +} from "lodash"; import React from "react"; import PropTypes from "prop-types"; -import { PropTypes as CustomPropTypes, Events, Helpers, TimerContext } from "victory-core"; +import { + PropTypes as CustomPropTypes, + Events, + Helpers, + TimerContext +} from "victory-core"; import isEqual from "react-fast-compare"; import stringify from "json-stringify-safe"; @@ -12,12 +25,18 @@ export default class VictorySharedEvents extends React.Component { static role = "shared-event-wrapper"; static propTypes = { - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), container: PropTypes.node, eventKey: PropTypes.oneOfType([ PropTypes.array, PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), events: PropTypes.arrayOf( @@ -27,7 +46,10 @@ export default class VictorySharedEvents extends React.Component { eventKey: PropTypes.oneOfType([ PropTypes.array, PropTypes.func, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), target: PropTypes.string @@ -39,7 +61,10 @@ export default class VictorySharedEvents extends React.Component { childName: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), eventKey: PropTypes.oneOfType([ PropTypes.array, - CustomPropTypes.allOfType([CustomPropTypes.integer, CustomPropTypes.nonNegative]), + CustomPropTypes.allOfType([ + CustomPropTypes.integer, + CustomPropTypes.nonNegative + ]), PropTypes.string ]), mutation: PropTypes.function, @@ -70,7 +95,10 @@ export default class VictorySharedEvents extends React.Component { shouldComponentUpdate(nextProps) { if (!isEqual(this.props, nextProps)) { this.baseProps = this.getBaseProps(nextProps); - const externalMutations = this.getExternalMutations(nextProps, this.baseProps); + const externalMutations = this.getExternalMutations( + nextProps, + this.baseProps + ); this.applyExternalMutations(nextProps, externalMutations); } return true; @@ -84,9 +112,15 @@ export default class VictorySharedEvents extends React.Component { componentDidUpdate() { const globalEventKeys = keys(this.globalEvents); - const removedGlobalEventKeys = difference(this.prevGlobalEventKeys, globalEventKeys); + const removedGlobalEventKeys = difference( + this.prevGlobalEventKeys, + globalEventKeys + ); removedGlobalEventKeys.forEach((key) => this.removeGlobalListener(key)); - const addedGlobalEventKeys = difference(globalEventKeys, this.prevGlobalEventKeys); + const addedGlobalEventKeys = difference( + globalEventKeys, + this.prevGlobalEventKeys + ); addedGlobalEventKeys.forEach((key) => this.addGlobalListener(key)); this.prevGlobalEventKeys = globalEventKeys; } @@ -101,11 +135,17 @@ export default class VictorySharedEvents extends React.Component { return listener && listener(Events.emulateReactEvent(event)); }; this.boundGlobalEvents[key] = boundListener; - window.addEventListener(Events.getGlobalEventNameFromKey(key), boundListener); + window.addEventListener( + Events.getGlobalEventNameFromKey(key), + boundListener + ); } removeGlobalListener(key) { - window.removeEventListener(Events.getGlobalEventNameFromKey(key), this.boundGlobalEvents[key]); + window.removeEventListener( + Events.getGlobalEventNameFromKey(key), + this.boundGlobalEvents[key] + ); } getAllEvents(props) { @@ -121,10 +161,15 @@ export default class VictorySharedEvents extends React.Component { applyExternalMutations(props, externalMutations) { if (!isEmpty(externalMutations)) { - const callbacks = props.externalEventMutations.reduce((memo, mutation) => { - memo = isFunction(mutation.callback) ? memo.concat(mutation.callback) : memo; - return memo; - }, []); + const callbacks = props.externalEventMutations.reduce( + (memo, mutation) => { + memo = isFunction(mutation.callback) + ? memo.concat(mutation.callback) + : memo; + return memo; + }, + [] + ); const compiledCallbacks = callbacks.length ? () => { callbacks.forEach((c) => c()); @@ -189,7 +234,11 @@ export default class VictorySharedEvents extends React.Component { if (child.props.children) { const newChildren = React.Children.toArray(child.props.children); const names = childNames.slice(index, index + newChildren.length); - const results = React.cloneElement(child, child.props, alterChildren(newChildren, names)); + const results = React.cloneElement( + child, + child.props, + alterChildren(newChildren, names) + ); return memo.concat(results); } else if ( childNames[index] !== "parent" && @@ -215,12 +264,17 @@ export default class VictorySharedEvents extends React.Component { stringify(this.state[name]) ]; - const sharedEvents = this.getCachedSharedEvents(name, sharedEventsCacheValues) || { + const sharedEvents = this.getCachedSharedEvents( + name, + sharedEventsCacheValues + ) || { events: childEvents, // partially apply child name and baseProps, - getEvents: (evts, target) => this.getScopedEvents(evts, target, name, baseProps), + getEvents: (evts, target) => + this.getScopedEvents(evts, target, name, baseProps), // partially apply child name - getEventState: (key, target) => this.getEventState(key, target, name) + getEventState: (key, target) => + this.getEventState(key, target, name) }; this.cacheSharedEvents(name, sharedEvents, sharedEventsCacheValues); @@ -228,7 +282,10 @@ export default class VictorySharedEvents extends React.Component { return memo.concat( React.cloneElement( child, - assign({ key: `events-${name}`, sharedEvents, eventKey, name }, child.props) + assign( + { key: `events-${name}`, sharedEvents, eventKey, name }, + child.props + ) ) ); } else { @@ -243,14 +300,17 @@ export default class VictorySharedEvents extends React.Component { getContainer(props, baseProps, events) { const children = this.getNewChildren(props, baseProps); - const parents = Array.isArray(events) && events.filter((event) => event.target === "parent"); + const parents = + Array.isArray(events) && + events.filter((event) => event.target === "parent"); const sharedEvents = parents.length > 0 ? { events: parents, // partially apply childName (null) and baseProps, - getEvents: (evts, target) => this.getScopedEvents(evts, target, null, baseProps), + getEvents: (evts, target) => + this.getScopedEvents(evts, target, null, baseProps), getEventState: this.getEventState } : null; @@ -258,7 +318,8 @@ export default class VictorySharedEvents extends React.Component { const role = container.type && container.type.role; const containerProps = container.props || {}; const boundGetEvents = Events.getEvents.bind(this); - const parentEvents = sharedEvents && boundGetEvents({ sharedEvents }, "parent"); + const parentEvents = + sharedEvents && boundGetEvents({ sharedEvents }, "parent"); const parentProps = defaults( {}, this.getEventState("parent", "parent"), @@ -274,7 +335,10 @@ export default class VictorySharedEvents extends React.Component { this.globalEvents = Events.getGlobalEvents(containerEvents); const localEvents = Events.omitGlobalEvents(containerEvents); return role === "container" - ? React.cloneElement(container, assign({}, parentProps, { events: localEvents })) + ? React.cloneElement( + container, + assign({}, parentProps, { events: localEvents }) + ) : React.cloneElement(container, localEvents, children); } @@ -283,6 +347,8 @@ export default class VictorySharedEvents extends React.Component { if (events) { return this.getContainer(this.props, this.baseProps, events); } - return React.cloneElement(this.props.container, { children: this.props.children }); + return React.cloneElement(this.props.container, { + children: this.props.children + }); } } diff --git a/packages/victory-stack/src/helper-methods.js b/packages/victory-stack/src/helper-methods.js index 72eb32638..44adfa6b6 100644 --- a/packages/victory-stack/src/helper-methods.js +++ b/packages/victory-stack/src/helper-methods.js @@ -77,7 +77,9 @@ function getY0(datum, index, datasets) { const sameSign = (y < 0 && value < 0) || (y >= 0 && value >= 0); return sameSign ? +value + memo : memo; }, firstDatasetBaseline[group] || 0); - return previousPoints.some((point) => point instanceof Date) ? new Date(y0) : y0; + return previousPoints.some((point) => point instanceof Date) + ? new Date(y0) + : y0; } /* eslint-disable no-nested-ternary */ @@ -86,7 +88,11 @@ function addLayoutData(props, datasets, index) { return datasets[index].map((datum) => { const yOffset = getY0(datum, index, datasets) || 0; return assign({}, datum, { - _y0: !(datum._y instanceof Date) ? yOffset : yOffset ? new Date(yOffset) : datum._y, + _y0: !(datum._y instanceof Date) + ? yOffset + : yOffset + ? new Date(yOffset) + : datum._y, _y1: datum._y === null ? null @@ -118,7 +124,8 @@ function getCalculatedProps(props, childComponents) { const role = "stack"; props = Helpers.modifyProps(props, fallbackProps, role); const style = Wrapper.getStyle(props.theme, props.style, role); - const categories = props.categories || Wrapper.getCategories(props, childComponents); + const categories = + props.categories || Wrapper.getCategories(props, childComponents); const datasets = props.datasets || stackData(props, childComponents); const children = childComponents.map((c, i) => { return React.cloneElement(c, { data: datasets[i] }); @@ -140,7 +147,17 @@ function getCalculatedProps(props, childComponents) { y: baseScale.y.domain(domain.y).range(props.horizontal ? range.x : range.y) }; const { colorScale, horizontal } = props; - return { datasets, categories, range, domain, horizontal, scale, style, colorScale, role }; + return { + datasets, + categories, + range, + domain, + horizontal, + scale, + style, + colorScale, + role + }; } function getLabels(props, datasets, index) { @@ -172,13 +189,16 @@ function getColorScale(props, child) { if (role !== "group" && role !== "stack") { return undefined; } - return props.theme ? colorScaleOptions || props.theme.props.colorScale : colorScaleOptions; + return props.theme + ? colorScaleOptions || props.theme.props.colorScale + : colorScaleOptions; } function getChildren(props, childComponents, calculatedProps) { props = Helpers.modifyProps(props, fallbackProps, "stack"); childComponents = childComponents || React.Children.toArray(props.children); - calculatedProps = calculatedProps || getCalculatedProps(props, childComponents); + calculatedProps = + calculatedProps || getCalculatedProps(props, childComponents); const { datasets } = calculatedProps; const childProps = getChildProps(props, calculatedProps); const parentName = props.name || "stack"; @@ -186,7 +206,9 @@ function getChildren(props, childComponents, calculatedProps) { const role = child.type && child.type.role; const data = datasets[index]; const style = Wrapper.getChildStyle(child, index, calculatedProps); - const labels = props.labels ? getLabels(props, datasets, index) : child.props.labels; + const labels = props.labels + ? getLabels(props, datasets, index) + : child.props.labels; const name = child.props.name || `${parentName}-${role}-${index}`; return React.cloneElement( child, diff --git a/packages/victory-stack/src/index.d.ts b/packages/victory-stack/src/index.d.ts index 73d76aa05..9a366ce20 100644 --- a/packages/victory-stack/src/index.d.ts +++ b/packages/victory-stack/src/index.d.ts @@ -22,7 +22,10 @@ export interface VictoryStackProps children?: React.ReactNode | React.ReactNode[]; colorScale?: ColorScalePropType; domain?: DomainPropType; - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + VictoryStackTTargetType, + StringOrNumberOrCallback + >[]; eventKey?: StringOrNumberOrCallback; fillInMissingData?: boolean; style?: VictoryStyleInterface; diff --git a/packages/victory-stack/src/victory-stack.js b/packages/victory-stack/src/victory-stack.js index a7910a797..727994237 100644 --- a/packages/victory-stack/src/victory-stack.js +++ b/packages/victory-stack/src/victory-stack.js @@ -28,7 +28,10 @@ export default class VictoryStack extends React.Component { ...CommonProps.baseProps, bins: PropTypes.oneOfType([ PropTypes.arrayOf( - PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.instanceOf(Date)]) + PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.instanceOf(Date) + ]) ), CustomPropTypes.nonNegative ]), @@ -39,7 +42,10 @@ export default class VictoryStack extends React.Component { y: PropTypes.arrayOf(PropTypes.string) }) ]), - children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]), + children: PropTypes.oneOfType([ + PropTypes.arrayOf(PropTypes.node), + PropTypes.node + ]), colorScale: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.oneOf([ @@ -73,7 +79,11 @@ export default class VictoryStack extends React.Component { fillInMissingData: true }; - static expectedComponents = ["groupComponent", "containerComponent", "labelComponent"]; + static expectedComponents = [ + "groupComponent", + "containerComponent", + "labelComponent" + ]; static getChildren = getChildren; @@ -103,7 +113,10 @@ export default class VictoryStack extends React.Component { const children = getChildren(props, childComponents, calculatedProps); const getAnimationProps = Wrapper.getAnimationProps.bind(this); const newChildren = children.map((child, index) => { - const childProps = assign({ animate: getAnimationProps(props, child, index) }, child.props); + const childProps = assign( + { animate: getAnimationProps(props, child, index) }, + child.props + ); return React.cloneElement(child, childProps); }); /* @@ -140,14 +153,27 @@ export default class VictoryStack extends React.Component { render() { const { role } = this.constructor; const props = - this.state && this.state.nodesWillExit ? this.state.oldProps || this.props : this.props; + this.state && this.state.nodesWillExit + ? this.state.oldProps || this.props + : this.props; const modifiedProps = Helpers.modifyProps(props, fallbackProps, role); - const { eventKey, containerComponent, standalone, groupComponent, externalEventMutations } = - modifiedProps; + const { + eventKey, + containerComponent, + standalone, + groupComponent, + externalEventMutations + } = modifiedProps; const childComponents = React.Children.toArray(modifiedProps.children); const calculatedProps = getCalculatedProps(modifiedProps, childComponents); - const newChildren = this.getNewChildren(modifiedProps, childComponents, calculatedProps); - const containerProps = standalone ? this.getContainerProps(modifiedProps, calculatedProps) : {}; + const newChildren = this.getNewChildren( + modifiedProps, + childComponents, + calculatedProps + ); + const containerProps = standalone + ? this.getContainerProps(modifiedProps, calculatedProps) + : {}; const container = standalone ? this.renderContainer(containerComponent, containerProps) : groupComponent; diff --git a/packages/victory-tooltip/src/flyout.js b/packages/victory-tooltip/src/flyout.js index b0a501145..d207b2724 100644 --- a/packages/victory-tooltip/src/flyout.js +++ b/packages/victory-tooltip/src/flyout.js @@ -5,7 +5,8 @@ import { Helpers, CommonProps, Path } from "victory-core"; import { isPlainObject, assign } from "lodash"; const getVerticalPath = (props) => { - const { pointerWidth, cornerRadius, orientation, width, height, center } = props; + const { pointerWidth, cornerRadius, orientation, width, height, center } = + props; const sign = orientation === "bottom" ? 1 : -1; const x = props.x + (props.dx || 0); const y = props.y + (props.dy || 0); @@ -19,7 +20,9 @@ const getVerticalPath = (props) => { const direction = orientation === "bottom" ? "0 0 0" : "0 0 1"; const arc = `${cornerRadius} ${cornerRadius} ${direction}`; return `M ${centerX - pointerWidth / 2}, ${pointerEdge} - L ${pointerLength ? x : centerX + pointerWidth / 2}, ${pointerLength ? y : pointerEdge} + L ${pointerLength ? x : centerX + pointerWidth / 2}, ${ + pointerLength ? y : pointerEdge + } L ${centerX + pointerWidth / 2}, ${pointerEdge} L ${rightEdge - cornerRadius}, ${pointerEdge} A ${arc} ${rightEdge}, ${pointerEdge - sign * cornerRadius} @@ -33,7 +36,8 @@ const getVerticalPath = (props) => { }; const getHorizontalPath = (props) => { - const { pointerWidth, cornerRadius, orientation, width, height, center } = props; + const { pointerWidth, cornerRadius, orientation, width, height, center } = + props; const sign = orientation === "left" ? 1 : -1; const x = props.x + (props.dx || 0); const y = props.y + (props.dy || 0); @@ -47,7 +51,9 @@ const getHorizontalPath = (props) => { const direction = orientation === "left" ? "0 0 0" : "0 0 1"; const arc = `${cornerRadius} ${cornerRadius} ${direction}`; return `M ${pointerEdge}, ${centerY - pointerWidth / 2} - L ${pointerLength ? x : pointerEdge}, ${pointerLength ? y : centerY + pointerWidth / 2} + L ${pointerLength ? x : pointerEdge}, ${ + pointerLength ? y : centerY + pointerWidth / 2 + } L ${pointerEdge}, ${centerY + pointerWidth / 2} L ${pointerEdge}, ${bottomEdge - cornerRadius} A ${arc} ${pointerEdge + sign * cornerRadius}, ${bottomEdge} diff --git a/packages/victory-tooltip/src/index.d.ts b/packages/victory-tooltip/src/index.d.ts index cdc5ac03f..f987fc938 100644 --- a/packages/victory-tooltip/src/index.d.ts +++ b/packages/victory-tooltip/src/index.d.ts @@ -40,7 +40,9 @@ export interface VictoryTooltipProps extends VictoryLabelableProps { index?: number | string; orientation?: OrientationTypes | ((...args: any[]) => OrientationTypes); pointerLength?: NumberOrCallback; - pointerOrientation?: OrientationTypes | ((...args: any[]) => OrientationTypes); + pointerOrientation?: + | OrientationTypes + | ((...args: any[]) => OrientationTypes); pointerWidth?: NumberOrCallback; renderInPortal?: boolean; style?: VictoryLabelStyleObject | VictoryLabelStyleObject[]; @@ -83,5 +85,8 @@ export interface FlyoutProps extends VictoryCommonProps { export class Flyout extends React.Component {} export class VictoryTooltip extends React.Component { - static defaultEvents: EventPropTypeInterface[]; + static defaultEvents: EventPropTypeInterface< + string, + StringOrNumberOrCallback + >[]; } diff --git a/packages/victory-tooltip/src/victory-tooltip.js b/packages/victory-tooltip/src/victory-tooltip.js index 34ce18857..eae6530cf 100644 --- a/packages/victory-tooltip/src/victory-tooltip.js +++ b/packages/victory-tooltip/src/victory-tooltip.js @@ -26,20 +26,29 @@ export default class VictoryTooltip extends React.Component { active: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), activePoints: PropTypes.array, angle: PropTypes.number, - center: PropTypes.shape({ x: CustomPropTypes.nonNegative, y: CustomPropTypes.nonNegative }), + center: PropTypes.shape({ + x: CustomPropTypes.nonNegative, + y: CustomPropTypes.nonNegative + }), centerOffset: PropTypes.shape({ x: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), y: PropTypes.oneOfType([PropTypes.number, PropTypes.func]) }), constrainToVisibleArea: PropTypes.bool, - cornerRadius: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + cornerRadius: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), data: PropTypes.array, datum: PropTypes.object, dx: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), dy: PropTypes.oneOfType([PropTypes.number, PropTypes.func]), events: PropTypes.object, flyoutComponent: PropTypes.element, - flyoutHeight: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + flyoutHeight: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), flyoutPadding: PropTypes.oneOfType([ PropTypes.func, PropTypes.number, @@ -51,7 +60,10 @@ export default class VictoryTooltip extends React.Component { }) ]), flyoutStyle: PropTypes.object, - flyoutWidth: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + flyoutWidth: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), groupComponent: PropTypes.element, height: PropTypes.number, horizontal: PropTypes.bool, @@ -62,12 +74,18 @@ export default class VictoryTooltip extends React.Component { PropTypes.oneOf(["top", "bottom", "left", "right"]), PropTypes.func ]), - pointerLength: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + pointerLength: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), pointerOrientation: PropTypes.oneOfType([ PropTypes.oneOf(["top", "bottom", "left", "right"]), PropTypes.func ]), - pointerWidth: PropTypes.oneOfType([CustomPropTypes.nonNegative, PropTypes.func]), + pointerWidth: PropTypes.oneOfType([ + CustomPropTypes.nonNegative, + PropTypes.func + ]), polar: PropTypes.bool, renderInPortal: PropTypes.bool, scale: PropTypes.shape({ @@ -174,14 +192,19 @@ export default class VictoryTooltip extends React.Component { ? props.style.map((s) => defaults({}, s, defaultLabelStyles)) : defaults({}, props.style, defaultLabelStyles); const defaultFlyoutStyles = - theme && theme.tooltip && theme.tooltip.flyoutStyle ? theme.tooltip.flyoutStyle : {}; + theme && theme.tooltip && theme.tooltip.flyoutStyle + ? theme.tooltip.flyoutStyle + : {}; const baseFlyoutStyle = props.flyoutStyle ? defaults({}, props.flyoutStyle, defaultFlyoutStyles) : defaultFlyoutStyles; const style = Array.isArray(baseLabelStyle) ? baseLabelStyle.map((s) => Helpers.evaluateStyle(s, props)) : Helpers.evaluateStyle(baseLabelStyle, props); - const flyoutStyle = Helpers.evaluateStyle(baseFlyoutStyle, assign({}, props, { style })); + const flyoutStyle = Helpers.evaluateStyle( + baseFlyoutStyle, + assign({}, props, { style }) + ); return { style, flyoutStyle }; } @@ -189,8 +212,13 @@ export default class VictoryTooltip extends React.Component { const { cornerRadius, centerOffset, dx, dy } = props; const active = Helpers.evaluateProp(props.active, props); - const text = Helpers.evaluateProp(props.text, assign({}, props, { active })); - const { style, flyoutStyle } = this.getStyles(assign({}, props, { active, text })); + const text = Helpers.evaluateProp( + props.text, + assign({}, props, { active }) + ); + const { style, flyoutStyle } = this.getStyles( + assign({}, props, { active, text }) + ); const orientation = Helpers.evaluateProp( props.orientation, @@ -280,7 +308,8 @@ export default class VictoryTooltip extends React.Component { getTransform(props) { const { x, y, style } = props; const labelStyle = style || {}; - const angle = labelStyle.angle || props.angle || this.getDefaultAngle(props); + const angle = + labelStyle.angle || props.angle || this.getDefaultAngle(props); return angle ? `rotate(${angle} ${x} ${y})` : undefined; } @@ -333,8 +362,16 @@ export default class VictoryTooltip extends React.Component { // eslint-disable-next-line complexity getFlyoutCenter(props, dimensions) { - const { x, y, dx, dy, pointerLength, orientation, constrainToVisibleArea, centerOffset } = - props; + const { + x, + y, + dx, + dy, + pointerLength, + orientation, + constrainToVisibleArea, + centerOffset + } = props; const { height, width } = dimensions; const xSign = orientation === "left" ? -1 : 1; const ySign = orientation === "bottom" ? -1 : 1; @@ -374,16 +411,25 @@ export default class VictoryTooltip extends React.Component { if (!style) { return 0; } - const paddings = Array.isArray(style) ? style.map((s) => s.padding) : [style.padding]; + const paddings = Array.isArray(style) + ? style.map((s) => s.padding) + : [style.padding]; return Math.max(...paddings, 0); } getDimensions(props, labelSize) { - const { orientation, pointerLength, pointerWidth, flyoutHeight, flyoutWidth, flyoutPadding } = - props; + const { + orientation, + pointerLength, + pointerWidth, + flyoutHeight, + flyoutWidth, + flyoutPadding + } = props; const cornerRadius = Helpers.evaluateProp(props.cornerRadius, props); const getHeight = () => { - const calculatedHeight = labelSize.height + flyoutPadding.top + flyoutPadding.bottom; + const calculatedHeight = + labelSize.height + flyoutPadding.top + flyoutPadding.bottom; const minHeight = orientation === "top" || orientation === "bottom" @@ -392,7 +438,8 @@ export default class VictoryTooltip extends React.Component { return Math.max(minHeight, calculatedHeight); }; const getWidth = () => { - const calculatedWidth = labelSize.width + flyoutPadding.left + flyoutPadding.right; + const calculatedWidth = + labelSize.width + flyoutPadding.left + flyoutPadding.right; const minWidth = orientation === "left" || orientation === "right" @@ -412,9 +459,12 @@ export default class VictoryTooltip extends React.Component { getLabelProps(props, calculatedValues) { const { flyoutCenter, style, labelSize, dy = 0, dx = 0 } = calculatedValues; - const { text, datum, activePoints, labelComponent, index, flyoutPadding } = props; + const { text, datum, activePoints, labelComponent, index, flyoutPadding } = + props; const textAnchor = - (Array.isArray(style) && style.length ? style[0].textAnchor : style.textAnchor) || "middle"; + (Array.isArray(style) && style.length + ? style[0].textAnchor + : style.textAnchor) || "middle"; const getLabelX = () => { if (!textAnchor || textAnchor === "middle") { return flyoutCenter.x; @@ -448,8 +498,14 @@ export default class VictoryTooltip extends React.Component { const gaps = [ { side: "top", val: edges.top > point.y ? edges.top - point.y : -1 }, - { side: "bottom", val: edges.bottom < point.y ? point.y - edges.bottom : -1 }, - { side: "right", val: edges.right < point.x ? point.x - edges.right : -1 }, + { + side: "bottom", + val: edges.bottom < point.y ? point.y - edges.bottom : -1 + }, + { + side: "right", + val: edges.right < point.x ? point.x - edges.right : -1 + }, { side: "left", val: edges.left > point.x ? edges.left - point.x : -1 } ]; @@ -472,7 +528,10 @@ export default class VictoryTooltip extends React.Component { events, flyoutComponent } = props; - const pointerOrientation = Helpers.evaluateProp(props.pointerOrientation, props); + const pointerOrientation = Helpers.evaluateProp( + props.pointerOrientation, + props + ); return defaults({}, flyoutComponent.props, { x, y, @@ -486,7 +545,8 @@ export default class VictoryTooltip extends React.Component { cornerRadius, events, orientation: - pointerOrientation || this.getPointerOrientation({ x, y }, flyoutCenter, flyoutDimensions), + pointerOrientation || + this.getPointerOrientation({ x, y }, flyoutCenter, flyoutDimensions), key: `${this.id}-tooltip-${index}`, width: flyoutDimensions.width, height: flyoutDimensions.height, @@ -498,15 +558,26 @@ export default class VictoryTooltip extends React.Component { // Overridden in victory-core-native renderTooltip(props) { const evaluatedProps = this.getEvaluatedProps(props); - const { flyoutComponent, labelComponent, groupComponent, active, renderInPortal } = - evaluatedProps; + const { + flyoutComponent, + labelComponent, + groupComponent, + active, + renderInPortal + } = evaluatedProps; if (!active) { return renderInPortal ? {null} : null; } const calculatedValues = this.getCalculatedValues(evaluatedProps); const children = [ - React.cloneElement(flyoutComponent, this.getFlyoutProps(evaluatedProps, calculatedValues)), - React.cloneElement(labelComponent, this.getLabelProps(evaluatedProps, calculatedValues)) + React.cloneElement( + flyoutComponent, + this.getFlyoutProps(evaluatedProps, calculatedValues) + ), + React.cloneElement( + labelComponent, + this.getLabelProps(evaluatedProps, calculatedValues) + ) ]; const tooltip = React.cloneElement( groupComponent, diff --git a/packages/victory-voronoi-container/src/index.d.ts b/packages/victory-voronoi-container/src/index.d.ts index 3cf1f670d..f5a736292 100644 --- a/packages/victory-voronoi-container/src/index.d.ts +++ b/packages/victory-voronoi-container/src/index.d.ts @@ -16,4 +16,7 @@ export interface VictoryVoronoiContainerProps extends VictoryContainerProps { voronoiPadding?: PaddingProps; } -export class VictoryVoronoiContainer extends React.Component {} +export class VictoryVoronoiContainer extends React.Component< + VictoryVoronoiContainerProps, + any +> {} diff --git a/packages/victory-voronoi-container/src/victory-voronoi-container.js b/packages/victory-voronoi-container/src/victory-voronoi-container.js index f0226ec81..bab7d5e4b 100644 --- a/packages/victory-voronoi-container/src/victory-voronoi-container.js +++ b/packages/victory-voronoi-container/src/victory-voronoi-container.js @@ -2,7 +2,11 @@ import PropTypes from "prop-types"; import React from "react"; import { defaults, isFunction, pick } from "lodash"; import { VictoryTooltip } from "victory-tooltip"; -import { VictoryContainer, Helpers, PropTypes as CustomPropTypes } from "victory-core"; +import { + VictoryContainer, + Helpers, + PropTypes as CustomPropTypes +} from "victory-core"; import VoronoiHelpers from "./voronoi-helpers"; export const voronoiContainerMixin = (base) => @@ -47,16 +51,24 @@ export const voronoiContainerMixin = (base) => target: "parent", eventHandlers: { onMouseLeave: (evt, targetProps) => { - return props.disable ? {} : VoronoiHelpers.onMouseLeave(evt, targetProps); + return props.disable + ? {} + : VoronoiHelpers.onMouseLeave(evt, targetProps); }, onTouchCancel: (evt, targetProps) => { - return props.disable ? {} : VoronoiHelpers.onMouseLeave(evt, targetProps); + return props.disable + ? {} + : VoronoiHelpers.onMouseLeave(evt, targetProps); }, onMouseMove: (evt, targetProps) => { - return props.disable ? {} : VoronoiHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : VoronoiHelpers.onMouseMove(evt, targetProps); }, onTouchMove: (evt, targetProps) => { - return props.disable ? {} : VoronoiHelpers.onMouseMove(evt, targetProps); + return props.disable + ? {} + : VoronoiHelpers.onMouseMove(evt, targetProps); } } }, @@ -94,7 +106,10 @@ export const voronoiContainerMixin = (base) => let center = mouseFollowTooltips ? mousePosition : undefined; if (!voronoiDimension || points.length < 2) { - return { ...basePosition, center: defaults({}, labelProps.center, center) }; + return { + ...basePosition, + center: defaults({}, labelProps.center, center) + }; } const x = voronoiDimension === "y" ? mousePosition.x : basePosition.x; @@ -106,11 +121,17 @@ export const voronoiContainerMixin = (base) => getStyle(props, points, type) { const { labels, labelComponent, theme } = props; const componentProps = labelComponent.props || {}; - const themeStyles = theme && theme.voronoi && theme.voronoi.style ? theme.voronoi.style : {}; + const themeStyles = + theme && theme.voronoi && theme.voronoi.style + ? theme.voronoi.style + : {}; const componentStyleArray = type === "flyout" ? componentProps.flyoutStyle : componentProps.style; return points.reduce((memo, datum, index) => { - const labelProps = defaults({}, componentProps, { datum, active: true }); + const labelProps = defaults({}, componentProps, { + datum, + active: true + }); const text = isFunction(labels) ? labels(labelProps) : undefined; const textArray = text !== undefined ? `${text}`.split("\n") : []; const baseStyle = (datum.style && datum.style[type]) || {}; @@ -121,7 +142,9 @@ export const voronoiContainerMixin = (base) => defaults({}, componentStyle, baseStyle, themeStyles[type]), labelProps ); - const styleArray = textArray.length ? textArray.map(() => style) : [style]; + const styleArray = textArray.length + ? textArray.map(() => style) + : [style]; memo = memo.concat(styleArray); return memo; }, []); @@ -134,12 +157,15 @@ export const voronoiContainerMixin = (base) => const y = point._y1 !== undefined ? point._y1 : point._y; const defaultHorizontalOrientation = y < 0 ? "left" : "right"; const defaultOrientation = y < 0 ? "bottom" : "top"; - const labelOrientation = horizontal ? defaultHorizontalOrientation : defaultOrientation; + const labelOrientation = horizontal + ? defaultHorizontalOrientation + : defaultOrientation; const orientation = mouseFollowTooltips ? undefined : labelOrientation; return { orientation, pointerLength: multiPoint ? 0 : undefined, - constrainToVisibleArea: multiPoint || mouseFollowTooltips ? true : undefined + constrainToVisibleArea: + multiPoint || mouseFollowTooltips ? true : undefined }; } @@ -147,7 +173,10 @@ export const voronoiContainerMixin = (base) => const { labels, scale, labelComponent, theme, width, height } = props; const componentProps = labelComponent.props || {}; const text = points.reduce((memo, datum) => { - const labelProps = defaults({}, componentProps, { datum, active: true }); + const labelProps = defaults({}, componentProps, { + datum, + active: true + }); const t = isFunction(labels) ? labels(labelProps) : null; if (t === null || t === undefined) { return memo; @@ -159,7 +188,8 @@ export const voronoiContainerMixin = (base) => // remove properties from first point to make datum // eslint-disable-next-line no-unused-vars const { childName, eventKey, style, continuous, ...datum } = points[0]; - const name = props.name === childName ? childName : `${props.name}-${childName}`; + const name = + props.name === childName ? childName : `${props.name}-${childName}`; const labelProps = defaults( { key: `${name}-${eventKey}-voronoi-tooltip`, @@ -193,8 +223,12 @@ export const voronoiContainerMixin = (base) => if (Array.isArray(activePoints) && activePoints.length) { const labelProps = this.getLabelProps(props, activePoints); const { text } = labelProps; - const showLabel = Array.isArray(text) ? text.filter(Boolean).length : text; - return showLabel ? React.cloneElement(labelComponent, labelProps) : null; + const showLabel = Array.isArray(text) + ? text.filter(Boolean).length + : text; + return showLabel + ? React.cloneElement(labelComponent, labelProps) + : null; } else { return null; } @@ -202,7 +236,10 @@ export const voronoiContainerMixin = (base) => // Overrides method in VictoryContainer getChildren(props) { - return [...React.Children.toArray(props.children), this.getTooltip(props)]; + return [ + ...React.Children.toArray(props.children), + this.getTooltip(props) + ]; } }; diff --git a/packages/victory-voronoi-container/src/voronoi-helpers.js b/packages/victory-voronoi-container/src/voronoi-helpers.js index f15e63275..802b6797c 100644 --- a/packages/victory-voronoi-container/src/voronoi-helpers.js +++ b/packages/victory-voronoi-container/src/voronoi-helpers.js @@ -1,5 +1,13 @@ import { Selection, Data, Helpers } from "victory-core"; -import { assign, throttle, isFunction, isEmpty, includes, isString, isRegExp } from "lodash"; +import { + assign, + throttle, + isFunction, + isEmpty, + includes, + isString, + isRegExp +} from "lodash"; import isEqual from "react-fast-compare"; import Delaunay from "delaunay-find/lib/index.js"; import React from "react"; @@ -10,7 +18,8 @@ const VoronoiHelpers = { const padding = Helpers.getPadding(props, "voronoiPadding"); const { x, y } = point; if (polar) { - const distanceSquared = Math.pow(x - origin.x, 2) + Math.pow(y - origin.y, 2); + const distanceSquared = + Math.pow(x - origin.x, 2) + Math.pow(y - origin.y, 2); const radius = Math.max(...scale.y.range()); return distanceSquared < Math.pow(radius, 2); } else { @@ -62,11 +71,17 @@ const VoronoiHelpers = { const blacklistStr = blacklist.filter(isString); const blacklistRegExp = blacklist.filter(isRegExp); const isRegExpMatch = blacklistRegExp.some((regExp) => regExp.test(name)); - if (!Data.isDataComponent(child) || includes(blacklistStr, name) || isRegExpMatch) { + if ( + !Data.isDataComponent(child) || + includes(blacklistStr, name) || + isRegExpMatch + ) { return null; } const getChildData = - child.type && isFunction(child.type.getData) ? child.type.getData : getData; + child.type && isFunction(child.type.getData) + ? child.type.getData + : getData; const childData = getChildData(child.props); return childData ? addMeta(childData, name, child) : null; }; @@ -88,7 +103,8 @@ const VoronoiHelpers = { return true; } const { x, y } = mousePosition; - const distanceSquared = Math.pow(x - point[0], 2) + Math.pow(y - point[1], 2); + const distanceSquared = + Math.pow(x - point[0], 2) + Math.pow(y - point[1], 2); return distanceSquared < Math.pow(radius, 2); }, @@ -100,8 +116,14 @@ const VoronoiHelpers = { }); const delaunay = Delaunay.from(scaledData); const index = delaunay.find(mousePosition.x, mousePosition.y); - const withinRadius = this.withinRadius(scaledData[index], mousePosition, props.radius); - const points = withinRadius ? this.findPoints(datasets, datasets[index]) : []; + const withinRadius = this.withinRadius( + scaledData[index], + mousePosition, + props.radius + ); + const points = withinRadius + ? this.findPoints(datasets, datasets[index]) + : []; return { points, index }; }, @@ -112,12 +134,16 @@ const VoronoiHelpers = { return []; } const defaultTarget = activateData ? ["data"] : []; - const targets = labels && !activateLabels ? defaultTarget : defaultTarget.concat("labels"); + const targets = + labels && !activateLabels + ? defaultTarget + : defaultTarget.concat("labels"); if (isEmpty(targets)) { return []; } return targets.map((target) => { - const eventKey = continuous === true && target === "data" ? "all" : point.eventKey; + const eventKey = + continuous === true && target === "data" ? "all" : point.eventKey; return { childName, eventKey, @@ -134,7 +160,10 @@ const VoronoiHelpers = { return []; } const defaultTarget = activateData ? ["data"] : []; - const targets = labels && !activateLabels ? defaultTarget : defaultTarget.concat("labels"); + const targets = + labels && !activateLabels + ? defaultTarget + : defaultTarget.concat("labels"); if (isEmpty(targets)) { return []; } @@ -176,7 +205,9 @@ const VoronoiHelpers = { const activePoints = targetProps.activePoints || []; this.onDeactivated(targetProps, activePoints); const inactiveMutations = activePoints.length - ? activePoints.map((point) => this.getInactiveMutations(targetProps, point)) + ? activePoints.map((point) => + this.getInactiveMutations(targetProps, point) + ) : []; return this.getParentMutation([]).concat(...inactiveMutations); }, @@ -189,12 +220,24 @@ const VoronoiHelpers = { if (!this.withinBounds(targetProps, mousePosition)) { this.onDeactivated(targetProps, activePoints); const inactiveMutations = activePoints.length - ? activePoints.map((point) => this.getInactiveMutations(targetProps, point)) + ? activePoints.map((point) => + this.getInactiveMutations(targetProps, point) + ) : []; - return this.getParentMutation([], mousePosition, parentSVG).concat(...inactiveMutations); + return this.getParentMutation([], mousePosition, parentSVG).concat( + ...inactiveMutations + ); } - const { points = [], index } = this.getVoronoiPoints(targetProps, mousePosition); - const parentMutations = this.getParentMutation(points, mousePosition, parentSVG, index); + const { points = [], index } = this.getVoronoiPoints( + targetProps, + mousePosition + ); + const parentMutations = this.getParentMutation( + points, + mousePosition, + parentSVG, + index + ); if (activePoints.length && isEqual(points, activePoints)) { return parentMutations; } else { @@ -204,7 +247,9 @@ const VoronoiHelpers = { ? points.map((point) => this.getActiveMutations(targetProps, point)) : []; const inactiveMutations = activePoints.length - ? activePoints.map((point) => this.getInactiveMutations(targetProps, point)) + ? activePoints.map((point) => + this.getInactiveMutations(targetProps, point) + ) : []; return parentMutations.concat(...inactiveMutations, ...activeMutations); } diff --git a/packages/victory-voronoi/src/helper-methods.js b/packages/victory-voronoi/src/helper-methods.js index ae5fadbdb..2c856cc36 100644 --- a/packages/victory-voronoi/src/helper-methods.js +++ b/packages/victory-voronoi/src/helper-methods.js @@ -53,7 +53,9 @@ const getCalculatedValues = (props) => { const voronoi = getVoronoi(props, range, scale); const polygons = voronoi.polygons(data); - const origin = props.polar ? props.origin || Helpers.getPolarOrigin(props) : undefined; + const origin = props.polar + ? props.origin || Helpers.getPolarOrigin(props) + : undefined; return { domain, data, scale, style, polygons, origin }; }; @@ -114,7 +116,10 @@ const getBaseProps = (props, fallbackProps) => { childProps[eventKey] = { data: dataProps }; const text = LabelHelpers.getText(props, datum, index); - if ((text !== undefined && text !== null) || (labels && (events || sharedEvents))) { + if ( + (text !== undefined && text !== null) || + (labels && (events || sharedEvents)) + ) { childProps[eventKey].labels = LabelHelpers.getProps(props, index); } diff --git a/packages/victory-voronoi/src/index.d.ts b/packages/victory-voronoi/src/index.d.ts index ec5e12cd3..312663250 100644 --- a/packages/victory-voronoi/src/index.d.ts +++ b/packages/victory-voronoi/src/index.d.ts @@ -17,7 +17,10 @@ export interface VictoryVoronoiProps VictoryDatableProps, VictoryLabelableProps, VictoryMultiLabelableProps { - events?: EventPropTypeInterface[]; + events?: EventPropTypeInterface< + string, + string | number | (string | number)[] + >[]; type?: number; sortKey?: StringOrNumberOrCallback | string[]; sortOrder?: VictoryVoronoiSortOrderType; diff --git a/packages/victory-voronoi/src/victory-voronoi.js b/packages/victory-voronoi/src/victory-voronoi.js index 27b547f0a..c3493f0fb 100644 --- a/packages/victory-voronoi/src/victory-voronoi.js +++ b/packages/victory-voronoi/src/victory-voronoi.js @@ -77,7 +77,9 @@ class VictoryVoronoi extends React.Component { } const children = this.renderData(props); - return props.standalone ? this.renderContainer(props.containerComponent, children) : children; + return props.standalone + ? this.renderContainer(props.containerComponent, children) + : children; } } diff --git a/packages/victory-voronoi/src/voronoi.js b/packages/victory-voronoi/src/voronoi.js index 3f1c090ca..4a9b3d737 100644 --- a/packages/victory-voronoi/src/voronoi.js +++ b/packages/victory-voronoi/src/voronoi.js @@ -6,7 +6,9 @@ import { Helpers, CommonProps, ClipPath, Path, Circle } from "victory-core"; const getVoronoiPath = (props) => { const { polygon } = props; - return Array.isArray(polygon) && polygon.length ? `M ${props.polygon.join("L")} Z` : ""; + return Array.isArray(polygon) && polygon.length + ? `M ${props.polygon.join("L")} Z` + : ""; }; const evaluateProps = (props) => { @@ -29,8 +31,17 @@ const evaluateProps = (props) => { const Voronoi = (props) => { props = evaluateProps(props); - const { ariaLabel, role, shapeRendering, className, events, transform, style, size, tabIndex } = - props; + const { + ariaLabel, + role, + shapeRendering, + className, + events, + transform, + style, + size, + tabIndex + } = props; const voronoiPath = getVoronoiPath(props); const sharedProps = { "aria-label": ariaLabel, @@ -59,10 +70,16 @@ const Voronoi = (props) => { React.cloneElement(props.pathComponent, { d: voronoiPath, className }) ); - return React.cloneElement(props.groupComponent, {}, [voronoiClipPath, circle]); + return React.cloneElement(props.groupComponent, {}, [ + voronoiClipPath, + circle + ]); } - return React.cloneElement(props.pathComponent, { ...sharedProps, d: voronoiPath }); + return React.cloneElement(props.pathComponent, { + ...sharedProps, + d: voronoiPath + }); }; Voronoi.propTypes = { diff --git a/packages/victory-zoom-container/src/index.d.ts b/packages/victory-zoom-container/src/index.d.ts index b251dd473..1463287f5 100644 --- a/packages/victory-zoom-container/src/index.d.ts +++ b/packages/victory-zoom-container/src/index.d.ts @@ -18,4 +18,7 @@ export interface VictoryZoomContainerProps extends VictoryContainerProps { zoomDomain?: { x?: DomainTuple; y?: DomainTuple }; } -export class VictoryZoomContainer extends React.Component {} +export class VictoryZoomContainer extends React.Component< + VictoryZoomContainerProps, + any +> {} diff --git a/packages/victory-zoom-container/src/index.js b/packages/victory-zoom-container/src/index.js index ec080df69..45fc52d9e 100644 --- a/packages/victory-zoom-container/src/index.js +++ b/packages/victory-zoom-container/src/index.js @@ -1,2 +1,5 @@ -export { zoomContainerMixin, default as VictoryZoomContainer } from "./victory-zoom-container"; +export { + zoomContainerMixin, + default as VictoryZoomContainer +} from "./victory-zoom-container"; export { default as ZoomHelpers, RawZoomHelpers } from "./zoom-helpers"; diff --git a/packages/victory-zoom-container/src/victory-zoom-container.js b/packages/victory-zoom-container/src/victory-zoom-container.js index 09c3dfede..455b215cd 100644 --- a/packages/victory-zoom-container/src/victory-zoom-container.js +++ b/packages/victory-zoom-container/src/victory-zoom-container.js @@ -48,22 +48,34 @@ export const zoomContainerMixin = (base) => target: "parent", eventHandlers: { onMouseDown: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseDown(evt, targetProps); }, onTouchStart: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseDown(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseDown(evt, targetProps); }, onMouseUp: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseUp(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseUp(evt, targetProps); }, onTouchEnd: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseUp(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseUp(evt, targetProps); }, onMouseLeave: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseLeave(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseLeave(evt, targetProps); }, onTouchCancel: (evt, targetProps) => { - return props.disable ? {} : ZoomHelpers.onMouseLeave(evt, targetProps); + return props.disable + ? {} + : ZoomHelpers.onMouseLeave(evt, targetProps); }, // eslint-disable-next-line max-params onMouseMove: (evt, targetProps, eventKey, ctx) => { @@ -80,14 +92,17 @@ export const zoomContainerMixin = (base) => evt.preventDefault(); return ZoomHelpers.onMouseMove(evt, targetProps, eventKey, ctx); }, - ...(props.disable || !props.allowZoom ? {} : { onWheel: ZoomHelpers.onWheel }) + ...(props.disable || !props.allowZoom + ? {} + : { onWheel: ZoomHelpers.onWheel }) } } ]; }; clipDataComponents(children, props) { - const { scale, clipContainerComponent, polar, origin, horizontal } = props; + const { scale, clipContainerComponent, polar, origin, horizontal } = + props; const rangeX = horizontal ? scale.y.range() : scale.x.range(); const rangeY = horizontal ? scale.x.range() : scale.y.range(); const plottableWidth = Math.abs(rangeX[0] - rangeX[1]); @@ -126,9 +141,13 @@ export const zoomContainerMixin = (base) => const getData = (childProps) => { const { data, x, y } = childProps; const defaultGetData = - child.type && isFunction(child.type.getData) ? child.type.getData : () => undefined; + child.type && isFunction(child.type.getData) + ? child.type.getData + : () => undefined; // skip costly data formatting if x and y accessors are not present - return Array.isArray(data) && !x && !y ? data : defaultGetData(childProps); + return Array.isArray(data) && !x && !y + ? data + : defaultGetData(childProps); }; const data = getData(child.props); @@ -143,7 +162,9 @@ export const zoomContainerMixin = (base) => // important: assumes data is ordered by dimension // get the start and end of the data that is in the current visible domain - let startIndex = data.findIndex((d) => d[dimension] >= domain[dimension][0]); + let startIndex = data.findIndex( + (d) => d[dimension] >= domain[dimension][0] + ); let endIndex = data.findIndex((d) => d[dimension] > domain[dimension][1]); // pick one more point (if available) at each end so that VictoryLine, VictoryArea connect if (startIndex !== 0) { @@ -167,7 +188,11 @@ export const zoomContainerMixin = (base) => const { currentDomain, zoomActive, allowZoom } = props; const originalDomain = defaults({}, props.originalDomain, props.domain); const zoomDomain = defaults({}, props.zoomDomain, props.domain); - const cachedZoomDomain = defaults({}, props.cachedZoomDomain, props.domain); + const cachedZoomDomain = defaults( + {}, + props.cachedZoomDomain, + props.domain + ); let domain; if (!ZoomHelpers.checkDomainEquality(zoomDomain, cachedZoomDomain)) { // if zoomDomain has been changed, use it @@ -180,7 +205,9 @@ export const zoomContainerMixin = (base) => domain = defaults({}, currentDomain, originalDomain); } - let newDomain = props.polar ? this.modifyPolarDomain(domain, originalDomain) : domain; + let newDomain = props.polar + ? this.modifyPolarDomain(domain, originalDomain) + : domain; if (newDomain && props.zoomDimension) { // if zooming is restricted to a dimension, don't squash changes to zoomDomain in other dim newDomain = { diff --git a/packages/victory-zoom-container/src/zoom-helpers.js b/packages/victory-zoom-container/src/zoom-helpers.js index 3c3f809a3..dc87a1094 100644 --- a/packages/victory-zoom-container/src/zoom-helpers.js +++ b/packages/victory-zoom-container/src/zoom-helpers.js @@ -38,13 +38,18 @@ const RawZoomHelpers = { const percent = this.getScalePercent(evt, props, axis); const point = factor * from + percent * (factor * range); const minDomain = this.getMinimumDomain(point, props, axis); - const [newMin, newMax] = this.getScaledDomain(currentDomain, factor, percent); + const [newMin, newMax] = this.getScaledDomain( + currentDomain, + factor, + percent + ); const newDomain = [ newMin > fromBound && newMin < toBound ? newMin : fromBound, newMax < toBound && newMax > fromBound ? newMax : toBound ]; const domain = - Math.abs(minDomain[1] - minDomain[0]) > Math.abs(newDomain[1] - newDomain[0]) + Math.abs(minDomain[1] - minDomain[0]) > + Math.abs(newDomain[1] - newDomain[0]) ? minDomain : newDomain; return Collection.containsDates([fromBound, toBound]) @@ -128,7 +133,8 @@ const RawZoomHelpers = { } else { newDomain = currentDomain; } - return Collection.containsDates(currentDomain) || Collection.containsDates(originalDomain) + return Collection.containsDates(currentDomain) || + Collection.containsDates(originalDomain) ? newDomain.map((val) => new Date(val)) : newDomain; }, @@ -171,7 +177,11 @@ const RawZoomHelpers = { if (childComponents.length) { childrenDomain = zoomDimension ? { - [zoomDimension]: Wrapper.getDomainFromChildren(props, zoomDimension, childComponents) + [zoomDimension]: Wrapper.getDomainFromChildren( + props, + zoomDimension, + childComponents + ) } : { x: Wrapper.getDomainFromChildren(props, "x", childComponents), @@ -235,19 +245,34 @@ const RawZoomHelpers = { // eslint-disable-next-line max-params, max-statements onMouseMove(evt, targetProps, eventKey, ctx) { if (targetProps.panning && targetProps.allowPan) { - const { scale, startX, startY, onZoomDomainChange, zoomDomain, zoomDimension, horizontal } = - targetProps; + const { + scale, + startX, + startY, + onZoomDomainChange, + zoomDomain, + zoomDimension, + horizontal + } = targetProps; const parentSVG = targetProps.parentSVG || Selection.getParentSVG(evt); const { x, y } = Selection.getSVGEventCoordinates(evt, parentSVG); const originalDomain = this.getDomain(targetProps); const lastDomain = this.getLastDomain(targetProps, originalDomain); const deltaX = horizontal ? y - startY : startX - x; const deltaY = horizontal ? startX - x : y - startY; - const dx = deltaX / this.getDomainScale(lastDomain, scale, "x", horizontal); - const dy = deltaY / this.getDomainScale(lastDomain, scale, "y", horizontal); + const dx = + deltaX / this.getDomainScale(lastDomain, scale, "x", horizontal); + const dy = + deltaY / this.getDomainScale(lastDomain, scale, "y", horizontal); const currentDomain = { - x: zoomDimension === "y" ? originalDomain.x : this.pan(lastDomain.x, originalDomain.x, dx), - y: zoomDimension === "x" ? originalDomain.y : this.pan(lastDomain.y, originalDomain.y, dy) + x: + zoomDimension === "y" + ? originalDomain.x + : this.pan(lastDomain.x, originalDomain.x, dx), + y: + zoomDimension === "x" + ? originalDomain.y + : this.pan(lastDomain.y, originalDomain.y, dy) }; const resumeAnimation = this.handleAnimation(ctx); @@ -265,7 +290,10 @@ const RawZoomHelpers = { }; if (isFunction(onZoomDomainChange)) { - onZoomDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onZoomDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ { @@ -288,15 +316,22 @@ const RawZoomHelpers = { const lastDomain = this.getLastDomain(targetProps, originalDomain); const { x, y } = lastDomain; const currentDomain = { - x: zoomDimension === "y" ? lastDomain.x : this.scale(x, evt, targetProps, "x"), - y: zoomDimension === "x" ? lastDomain.y : this.scale(y, evt, targetProps, "y") + x: + zoomDimension === "y" + ? lastDomain.x + : this.scale(x, evt, targetProps, "x"), + y: + zoomDimension === "x" + ? lastDomain.y + : this.scale(y, evt, targetProps, "y") }; const resumeAnimation = this.handleAnimation(ctx); const zoomActive = !this.zoommingOut(evt) || // if zoomming in or // if zoomActive is already set AND user hasn't zoommed out all the way - (targetProps.zoomActive && !this.checkDomainEquality(originalDomain, lastDomain)); + (targetProps.zoomActive && + !this.checkDomainEquality(originalDomain, lastDomain)); const mutatedProps = { currentDomain, @@ -308,7 +343,10 @@ const RawZoomHelpers = { }; if (isFunction(onZoomDomainChange)) { - onZoomDomainChange(currentDomain, defaults({}, mutatedProps, targetProps)); + onZoomDomainChange( + currentDomain, + defaults({}, mutatedProps, targetProps) + ); } return [ diff --git a/packages/victory/src/index.d.ts b/packages/victory/src/index.d.ts index 6e466758b..2cca4df2d 100644 --- a/packages/victory/src/index.d.ts +++ b/packages/victory/src/index.d.ts @@ -72,14 +72,29 @@ declare module "victory" { Candle, CandleProps } from "victory-candlestick"; - import { VictoryErrorBar, ErrorBar, VictoryErrorBarProps, ErrorBarProps } from "victory-errorbar"; + import { + VictoryErrorBar, + ErrorBar, + VictoryErrorBarProps, + ErrorBarProps + } from "victory-errorbar"; - import { VictoryLine, Curve, VictoryLineProps, CurveProps } from "victory-line"; + import { + VictoryLine, + Curve, + VictoryLineProps, + CurveProps + } from "victory-line"; import { VictoryHistogram, VictoryHistogramProps } from "victory-histogram"; import { VictoryScatter, VictoryScatterProps } from "victory-scatter"; import { VictoryBoxPlot, VictoryBoxPlotProps } from "victory-box-plot"; import { VictoryBrushLine, VictoryBrushLineProps } from "victory-brush-line"; - import { Voronoi, VictoryVoronoi, VoronoiProps, VictoryVoronoiProps } from "victory-voronoi"; + import { + Voronoi, + VictoryVoronoi, + VoronoiProps, + VictoryVoronoiProps + } from "victory-voronoi"; import { VictoryBrushContainer, @@ -119,7 +134,12 @@ declare module "victory" { createContainer } from "victory-create-container"; - import { VictoryTooltip, Flyout, VictoryTooltipProps, FlyoutProps } from "victory-tooltip"; + import { + VictoryTooltip, + Flyout, + VictoryTooltipProps, + FlyoutProps + } from "victory-tooltip"; import { VictoryLegend, VictoryLegendProps } from "victory-legend"; // import { VictorySharedEvents } from "victory-shared-events"; diff --git a/packages/victory/src/index.js b/packages/victory/src/index.js index 909a3d60e..ceeca167e 100644 --- a/packages/victory/src/index.js +++ b/packages/victory/src/index.js @@ -54,7 +54,11 @@ import { VictoryScatter } from "victory-scatter"; import { VictoryBoxPlot } from "victory-box-plot"; import { VictoryVoronoi, Voronoi } from "victory-voronoi"; import { VictoryBrushLine } from "victory-brush-line"; -import { VictoryBrushContainer, BrushHelpers, brushContainerMixin } from "victory-brush-container"; +import { + VictoryBrushContainer, + BrushHelpers, + brushContainerMixin +} from "victory-brush-container"; import { VictoryCursorContainer, CursorHelpers, diff --git a/stories/containers-and-addons.js b/stories/containers-and-addons.js index 3d97e19b7..868b956b8 100644 --- a/stories/containers-and-addons.js +++ b/stories/containers-and-addons.js @@ -16,19 +16,25 @@ storiesOf("Containers and Addons.VictoryBrushContainer", module) )) .add("with VictoryBrushContainer with domain", () => ( } + containerComponent={ + + } /> )) .add("with VictoryBrushContainer with domain (horizontal)", () => ( } + containerComponent={ + + } /> )) .add("with VictoryBrushContainer with brushStyle", () => ( + } /> )); @@ -36,11 +42,17 @@ storiesOf("Containers and Addons.VictoryBrushContainer", module) storiesOf("Containers and Addons.VictoryBrushLine", module) .add("brush axis", () => } />) .add("brush axis with initial brush", () => ( - } /> + } + /> + )) + .add("brush gridline", () => ( + } /> )) - .add("brush gridline", () => } />) .add("brush gridline with initial brushes", () => ( - } /> + } + /> )) .add("brush gridline with styles", () => ( )) - .add("with VictoryCursorContainer with defaultCursorValue (horizontal)", () => ( - datum.x} - defaultCursorValue={{ x: 0.25, y: 0.75 }} - /> - } - /> - )); + .add( + "with VictoryCursorContainer with defaultCursorValue (horizontal)", + () => ( + datum.x} + defaultCursorValue={{ x: 0.25, y: 0.75 }} + /> + } + /> + ) + ); storiesOf("Containers and Addons.VictoryZoomContainer", module).add( "with VictoryZoomContainer with initial zoom", diff --git a/stories/victory-area.stories.js b/stories/victory-area.stories.js index 1b51daa88..1f6e5641f 100644 --- a/stories/victory-area.stories.js +++ b/stories/victory-area.stories.js @@ -6,7 +6,13 @@ import { VictoryArea } from "../packages/victory-area/src"; import { VictoryTooltip } from "../packages/victory-tooltip/src"; import { VictoryTheme, VictoryLabel } from "../packages/victory-core/src"; import { VictoryChart } from "../packages/victory-chart/src"; -import { getData, getMixedData, getTimeData, getLogData, getDataWithBaseline } from "./data"; +import { + getData, + getMixedData, + getTimeData, + getLogData, + getDataWithBaseline +} from "./data"; import { fromJS } from "immutable"; import Area from "../packages/victory-area/src/area"; import styled from "styled-components"; @@ -73,7 +79,12 @@ export const Theme = () => { export const Interpolation = () => { const makeInterpolationChart = (interpolation) => ( - + ); @@ -98,7 +109,12 @@ export const Interpolation = () => { export const PolarInterpolation = () => { const makeInterpolationChart = (interpolation) => ( - + ); @@ -211,7 +227,10 @@ export const PlottingFunctions = () => { Math.sin(Math.PI * d.x)} /> - Math.sin(Math.PI * d.x)} y0={(d) => Math.sin(Math.PI * d.x) - 0.5} /> + Math.sin(Math.PI * d.x)} + y0={(d) => Math.sin(Math.PI * d.x) - 0.5} + />
    ); @@ -221,10 +240,16 @@ export const Labels = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - + { labels={({ datum }) => datum.x} style={{ labels: { fontSize: 20, fill: "tomato", fontFamily: "monospace" }, - data: { fill: "tomato", fillOpacity: 0.7, stroke: "tomato", strokeWidth: 2 } + data: { + fill: "tomato", + fillOpacity: 0.7, + stroke: "tomato", + strokeWidth: 2 + } }} /> @@ -368,10 +398,16 @@ export const TimeScale = () => { return (
    - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> datum.x.getFullYear()}> @@ -395,10 +431,16 @@ export const LogScale = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> @@ -464,7 +506,10 @@ export const DisableInlineStyles = () => { return (
    - } /> + } + />
    ); }; diff --git a/stories/victory-axis.stories.js b/stories/victory-axis.stories.js index f4168ba63..816e9c66f 100644 --- a/stories/victory-axis.stories.js +++ b/stories/victory-axis.stories.js @@ -116,7 +116,10 @@ export const TickValues = () => {
    - + @@ -154,9 +157,21 @@ export const WithDomain = () => { return (
    - - - + + + { export const FixLabelOverlap = () => { return (
    - + - + { export const Orientation = () => { return (
    - - - - + + + + diff --git a/stories/victory-bar.stories.js b/stories/victory-bar.stories.js index 9eeb850e6..8d9d2018d 100644 --- a/stories/victory-bar.stories.js +++ b/stories/victory-bar.stories.js @@ -217,14 +217,24 @@ export const CornerRadius = () => { @@ -238,7 +248,12 @@ export const CornerRadius = () => { { x: 315, y: 30 } ]} style={{ data: { fill: "tomato", width: 40 } }} - cornerRadius={{ topRight: 1, topLeft: 20, bottomRight: 5, bottomLeft: 0 }} + cornerRadius={{ + topRight: 1, + topLeft: 20, + bottomRight: 5, + bottomLeft: 0 + }} /> { { x: 315, y: 30 } ]} style={{ data: { fill: "tomato", width: 40 } }} - cornerRadius={{ topRight: 1, topLeft: 20, bottomRight: 5, bottomLeft: 0 }} + cornerRadius={{ + topRight: 1, + topLeft: 20, + bottomRight: 5, + bottomLeft: 0 + }} /> { `x: ${datum.x}`} /> - + { labels={({ datum }) => datum.y} style={{ labels: { fontSize: 20, fill: "tomato", fontFamily: "monospace" }, - data: { fill: "tomato", fillOpacity: 0.7, stroke: "tomato", strokeWidth: 2 } + data: { + fill: "tomato", + fillOpacity: 0.7, + stroke: "tomato", + strokeWidth: 2 + } }} /> @@ -476,16 +504,33 @@ export const Scale = () => { return (
    - datum.y.toPrecision(1)} /> + datum.y.toPrecision(1)} + /> - - datum.y.toPrecision(1)} /> + + datum.y.toPrecision(1)} + /> - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> datum.x.getFullYear()}> @@ -666,7 +711,11 @@ export const GroupedBars = () => { - datum.x} style={{ data: { width: 15 } }}> + datum.x} + style={{ data: { width: 15 } }} + > @@ -685,7 +734,11 @@ export const GroupedBars = () => { - datum.x} style={{ data: { width: 15 } }}> + datum.x} + style={{ data: { width: 15 } }} + > @@ -802,7 +855,11 @@ export const PolarBars = () => { - + @@ -810,14 +867,23 @@ export const PolarBars = () => { - + - + @@ -899,7 +965,11 @@ export const Regressions = () => { - datum.x}> + datum.x} + > @@ -924,7 +994,11 @@ export const Regressions = () => { export const Domain = () => { return (
    - + diff --git a/stories/victory-box-plot.stories.js b/stories/victory-box-plot.stories.js index d90557d72..ef634e590 100644 --- a/stories/victory-box-plot.stories.js +++ b/stories/victory-box-plot.stories.js @@ -4,7 +4,12 @@ import React from "react"; import { VictoryBoxPlot } from "../packages/victory-box-plot/src/index"; import { VictoryChart } from "../packages/victory-chart/src/index"; import { VictoryTooltip } from "../packages/victory-tooltip/src/index"; -import { VictoryTheme, Box, Whisker, LineSegment } from "../packages/victory-core/src/index"; +import { + VictoryTheme, + Box, + Whisker, + LineSegment +} from "../packages/victory-core/src/index"; import { range } from "lodash"; import seedrandom from "seedrandom"; import { getArrayData } from "./data"; @@ -290,8 +295,14 @@ export const Style = () => { style={{ min: { stroke: "#FF530D", strokeWidth: 2 }, max: { stroke: "#2bbee0", strokeWidth: 2 }, - q1: { fill: "#FF530D", fillOpacity: ({ datum }) => (datum.q1 < 10 ? 1 : 0.5) }, - q3: { fill: "#2bbee0", fillOpacity: ({ datum }) => (datum.q3 > 15 ? 1 : 0.5) }, + q1: { + fill: "#FF530D", + fillOpacity: ({ datum }) => (datum.q1 < 10 ? 1 : 0.5) + }, + q3: { + fill: "#2bbee0", + fillOpacity: ({ datum }) => (datum.q3 > 15 ? 1 : 0.5) + }, median: { stroke: "#fff", strokeWidth: 2 }, minLabels: { fill: "#FF530D", padding: 10 }, maxLabels: { fill: "#2bbee0", padding: 10 } diff --git a/stories/victory-candlestick.stories.js b/stories/victory-candlestick.stories.js index 67a21284b..c14898d2f 100644 --- a/stories/victory-candlestick.stories.js +++ b/stories/victory-candlestick.stories.js @@ -1,7 +1,10 @@ /*eslint-disable no-magic-numbers*/ /*eslint-disable react/no-multi-comp*/ import React from "react"; -import { VictoryCandlestick, Candle } from "../packages/victory-candlestick/src/index"; +import { + VictoryCandlestick, + Candle +} from "../packages/victory-candlestick/src/index"; import { VictoryChart } from "../packages/victory-chart/src/index"; import { VictoryTooltip } from "../packages/victory-tooltip/src/index"; import { VictoryTheme } from "../packages/victory-core/src/index"; @@ -176,10 +179,16 @@ export const Labels = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> { labels={({ datum }) => datum.x} style={{ labels: { fontSize: 20, fill: "tomato", fontFamily: "monospace" }, - data: { fill: "tomato", fillOpacity: 0.7, stroke: "tomato", strokeWidth: 2 } + data: { + fill: "tomato", + fillOpacity: 0.7, + stroke: "tomato", + strokeWidth: 2 + } }} /> @@ -294,7 +308,8 @@ export const Style = () => { fill: ({ datum }) => (datum.x === 3 ? "red" : "black") }, data: { - stroke: ({ datum }) => (datum.open > datum.close ? "red" : "black") + stroke: ({ datum }) => + datum.open > datum.close ? "red" : "black" } }} labels={({ datum }) => datum.x} @@ -309,7 +324,10 @@ export const Scale = () => { return (
    - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> { - + { - + @@ -127,10 +135,19 @@ export const Domain = () => { - + - +
    @@ -142,13 +159,27 @@ export const DomainFromData = () => {
    - - 10 * Math.sin(13 * Math.PI * d.x)} /> + + 10 * Math.sin(13 * Math.PI * d.x)} + /> - - 10 * Math.sin(13 * Math.PI * d.x)} /> + + 10 * Math.sin(13 * Math.PI * d.x)} + /> @@ -283,7 +314,11 @@ export const Style = () => { background: { fill: "pink" } }} > - + { export const Orientations = () => { return (
    - + - - + + { } + containerComponent={ + + } > - + } + containerComponent={ + + } > - +
    ); diff --git a/stories/victory-errorbar.stories.js b/stories/victory-errorbar.stories.js index aef825b42..8136a3f29 100644 --- a/stories/victory-errorbar.stories.js +++ b/stories/victory-errorbar.stories.js @@ -1,7 +1,10 @@ /*eslint-disable no-magic-numbers*/ /*eslint-disable react/no-multi-comp*/ import React from "react"; -import { VictoryErrorBar, ErrorBar } from "../packages/victory-errorbar/src/index"; +import { + VictoryErrorBar, + ErrorBar +} from "../packages/victory-errorbar/src/index"; import { VictoryChart } from "../packages/victory-chart/src/index"; import { VictoryTooltip } from "../packages/victory-tooltip/src/index"; import { VictoryTheme } from "../packages/victory-core/src/index"; @@ -131,7 +134,10 @@ export const Labels = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> { labels={({ datum }) => datum.x} style={{ labels: { fontSize: 20, fill: "tomato", fontFamily: "monospace" }, - data: { fill: "tomato", fillOpacity: 0.7, stroke: "tomato", strokeWidth: 2 } + data: { + fill: "tomato", + fillOpacity: 0.7, + stroke: "tomato", + strokeWidth: 2 + } }} /> @@ -196,10 +207,12 @@ export const Style = () => { (datum.errorX > datum.errorY ? "red" : "black") + fill: ({ datum }) => + datum.errorX > datum.errorY ? "red" : "black" }, data: { - stroke: ({ datum }) => (datum.errorX > datum.errorY ? "red" : "black") + stroke: ({ datum }) => + datum.errorX > datum.errorY ? "red" : "black" } }} labels={({ datum }) => datum.x} @@ -272,7 +285,10 @@ export const DisableInlineStyles = () => { - } /> + } + />
    ); diff --git a/stories/victory-histogram.stories.js b/stories/victory-histogram.stories.js index be0c8d43d..4484558de 100644 --- a/stories/victory-histogram.stories.js +++ b/stories/victory-histogram.stories.js @@ -41,7 +41,11 @@ export const DefaultRendering = () => { - + @@ -104,7 +108,10 @@ export const Data = () => {
    - ({ value: x }))} x={({ value }) => value} /> + ({ value: x }))} + x={({ value }) => value} + /> {
    @@ -155,13 +170,21 @@ export const DateBins = () => { @@ -177,13 +200,22 @@ export const DateBins = () => { - + - + - +
    ); @@ -238,7 +270,9 @@ export const Styles = () => { @@ -247,7 +281,9 @@ export const Styles = () => { style={{ labels: { fill: ({ datum }) => - datum.binnedData.some(({ x }) => x === 22) ? "palevioletred" : "black" + datum.binnedData.some(({ x }) => x === 22) + ? "palevioletred" + : "black" }, data: { stroke: ({ datum }) => (datum.y > 3 ? "red" : "transparent"), @@ -278,10 +314,16 @@ export const CornerRadius = () => { - + - +
    ); @@ -336,10 +378,18 @@ export const Labels = () => { />
    - + - + { binSpacing={10} data={timeData} bins="year" - labels={({ datum }) => `${datum.x0.getFullYear()}\n|\n${datum.x1.getFullYear()}`} + labels={({ datum }) => + `${datum.x0.getFullYear()}\n|\n${datum.x1.getFullYear()}` + } /> @@ -377,13 +429,24 @@ export const Scale = () => { binSpacing={10} data={timeData} bins="year" - labels={({ datum }) => `${datum.x0.getFullYear()} - ${datum.x1.getFullYear()}`} + labels={({ datum }) => + `${datum.x0.getFullYear()} - ${datum.x1.getFullYear()}` + } /> - + - +
    @@ -429,7 +492,9 @@ export const MixedCharts = () => { export const Stacked = () => { const stackedData = [ - ...[50, 30, 100, 32, 50, 10, 49, 78, 20].map((count) => getData(count, count, 100)), + ...[50, 30, 100, 32, 50, 10, 49, 78, 20].map((count) => + getData(count, count, 100) + ), [{ x: 1 }, { x: 3 }, { x: 1 }, { x: 2 }] ]; @@ -452,7 +517,11 @@ export const Stacked = () => { {stackedData.map((d, index) => ( - + ))} @@ -465,7 +534,10 @@ export const Stacked = () => { - ({ a: { b: { c: x } } }))} x="a.b.c" /> + ({ a: { b: { c: x } } }))} + x="a.b.c" + /> {stackedData.map((d, index) => ( ))} @@ -473,7 +545,10 @@ export const Stacked = () => { - ({ a: { b: { c: x } } }))} x="a.b.c" /> + ({ a: { b: { c: x } } }))} + x="a.b.c" + /> {stackedData.map((d, index) => ( ))} @@ -486,7 +561,11 @@ export const Stacked = () => { export const Domain = () => { return (
    - + @@ -512,7 +591,10 @@ export const DisableInlineStyles = () => { - } /> + } + />
    ); diff --git a/stories/victory-label.stories.js b/stories/victory-label.stories.js index 037f65d07..8d827d3b0 100644 --- a/stories/victory-label.stories.js +++ b/stories/victory-label.stories.js @@ -36,7 +36,10 @@ export default { export const DefaultRendering = () => { return (
    - } /> + } + />
    ); }; @@ -62,11 +65,15 @@ export const Positioning = () => { /> datum.x + 50} text="dx function" />} + labelComponent={ + datum.x + 50} text="dx function" /> + } /> datum.x - 20} text="dy function" />} + labelComponent={ + datum.x - 20} text="dy function" /> + } />
    ); @@ -251,7 +258,10 @@ export const Styles = () => { {...defaultScatterProps} labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }} + style={{ + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + }} text={["object", "with", "functions"]} backgroundStyle={{ stroke: "blue", fill: "none" }} /> @@ -261,7 +271,12 @@ export const Styles = () => { {...defaultScatterProps} labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }]} + style={[ + { + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + } + ]} text={["single array", "with", "functions"]} backgroundStyle={{ stroke: "blue", fill: "none" }} /> @@ -272,8 +287,14 @@ export const Styles = () => { labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }, - { fill: ({ datum }) => (datum.y === 0 ? "red" : "blue"), fontFamily: "arial" } + { + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + }, + { + fill: ({ datum }) => (datum.y === 0 ? "red" : "blue"), + fontFamily: "arial" + } ]} text={["multi array", "with", "functions"]} backgroundStyle={{ stroke: "blue", fill: "none" }} @@ -284,7 +305,10 @@ export const Styles = () => { {...defaultScatterProps} labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }} + style={{ + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + }} text={["object", "with", "functions"]} backgroundStyle={[{ stroke: "blue", fill: "none" }]} /> @@ -294,7 +318,12 @@ export const Styles = () => { {...defaultScatterProps} labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }]} + style={[ + { + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + } + ]} text={["single array", "with", "functions"]} backgroundStyle={[{ stroke: "blue", fill: "none" }]} /> @@ -305,8 +334,14 @@ export const Styles = () => { labelComponent={ (datum.y === 0 ? 12 : 15), fontFamily: "arial" }, - { fill: ({ datum }) => (datum.y === 0 ? "red" : "blue"), fontFamily: "arial" } + { + fontSize: ({ datum }) => (datum.y === 0 ? 12 : 15), + fontFamily: "arial" + }, + { + fill: ({ datum }) => (datum.y === 0 ? "red" : "blue"), + fontFamily: "arial" + } ]} text={["multi array", "with", "functions"]} backgroundStyle={[{ stroke: "blue", fill: "none" }]} diff --git a/stories/victory-line.stories.js b/stories/victory-line.stories.js index 8ce079368..ff29400c3 100644 --- a/stories/victory-line.stories.js +++ b/stories/victory-line.stories.js @@ -81,7 +81,12 @@ export const Theme = () => { export const Interpolation = () => { const makeInterpolationChart = (interpolation) => ( - + ); @@ -106,7 +111,12 @@ export const Interpolation = () => { export const PolarInterpolation = () => { const makeInterpolationChart = (interpolation) => ( - + ); @@ -219,7 +229,10 @@ export const PlottingFunctions = () => { Math.sin(Math.PI * d.x)} /> - Math.sin(Math.PI * d.x)} y0={(d) => Math.sin(Math.PI * d.x) - 0.5} /> + Math.sin(Math.PI * d.x)} + y0={(d) => Math.sin(Math.PI * d.x) - 0.5} + />
    ); @@ -229,10 +242,16 @@ export const Labels = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - + { return (
    - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> datum.x.getFullYear()}> @@ -396,10 +421,16 @@ export const LogScale = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> diff --git a/stories/victory-pie.stories.js b/stories/victory-pie.stories.js index 8bb9181f2..9320058d9 100644 --- a/stories/victory-pie.stories.js +++ b/stories/victory-pie.stories.js @@ -229,7 +229,10 @@ export const PadAngle = () => { export const Labels = () => { return (
    - + `#${index}`} /> { labelPlacement="perpendicular" labelComponent={} /> - } /> + } + /> { export const LabelRadius = () => { return (
    - + datum.y} @@ -391,7 +401,15 @@ export const Styles = () => { ]} innerRadius={100} labelRadius={110} - colorScale={["#D85F49", "#F66D3B", "#D92E1D", "#D73C4C", "#FFAF59", "#E28300", "#F6A57F"]} + colorScale={[ + "#D85F49", + "#F66D3B", + "#D92E1D", + "#D73C4C", + "#FFAF59", + "#E28300", + "#F6A57F" + ]} />
    ); @@ -410,7 +428,12 @@ export const StartAndEndAngles = () => { /> datum.endAngle} />} + dataComponent={ + datum.endAngle} + /> + } labels={() => null} cornerRadius={5} radius={({ datum }) => datum.radius} @@ -427,7 +450,9 @@ export const StartAndEndAngles = () => { dataComponent={ Helpers.radiansToDegrees(slice.endAngle) - 90} + sliceEndAngle={({ slice }) => + Helpers.radiansToDegrees(slice.endAngle) - 90 + } /> } labels={() => null} @@ -554,7 +579,10 @@ export const DisableInlineStyles = () => { return (
    - } /> + } + />
    ); }; diff --git a/stories/victory-polar-axis.stories.js b/stories/victory-polar-axis.stories.js index 9cbab5cf6..c8787e540 100644 --- a/stories/victory-polar-axis.stories.js +++ b/stories/victory-polar-axis.stories.js @@ -125,8 +125,16 @@ export const Domain = () => { return (
    - - + + { return (
    - + - - + +
    ); @@ -214,8 +232,17 @@ export const StartAndEndAngle = () => { - - + +
    ); }; @@ -296,14 +323,22 @@ export const Style = () => { export const Scale = () => { return (
    - + - + { return (
    - datum.x} /> + datum.x} + /> datum.x}> @@ -76,7 +79,10 @@ export const Theme = () => { - datum.x} /> + datum.x} + /> datum.x}> @@ -95,10 +101,20 @@ export const Symbols = () => { return SYMBOLS.map((symbol) => (
    - symbol} /> + symbol} + /> - symbol} /> + symbol} + />
    )); @@ -157,10 +173,18 @@ export const BubbleCharts = () => {
    - + - + { /> - + @@ -266,10 +294,16 @@ export const Labels = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - + { return (
    - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> - datum.x.getFullYear()} /> + datum.x.getFullYear()} + /> datum.x.getFullYear()}> @@ -436,10 +476,16 @@ export const LogScale = () => { return (
    - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> - `x: ${datum.x}`} /> + `x: ${datum.x}`} + /> @@ -500,7 +546,11 @@ export const Polar = () => { export const Domain = () => { return (
    - + diff --git a/stories/victory-tooltip.stories.js b/stories/victory-tooltip.stories.js index fc9eb97f4..e046ec958 100644 --- a/stories/victory-tooltip.stories.js +++ b/stories/victory-tooltip.stories.js @@ -53,9 +53,19 @@ export default { export const DefaultRendering = () => { return (
    - } /> - } /> - } /> + } + /> + } + /> + } + />
    ); }; @@ -65,47 +75,71 @@ export const CenterOffset = () => {
    } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> + } /> + } /> + } /> { labelComponent={ (datum.y < 0 ? -10 : 10), y: -10 }} + centerOffset={{ + x: ({ datum }) => (datum.y < 0 ? -10 : 10), + y: -10 + }} text={`function\noffset`} /> } @@ -152,7 +189,9 @@ export const PointerOrientation = () => { (datum.y > 0 ? "bottom" : "top")} - text={({ datum }) => (datum.y > 0 ? `orientation\nbottom` : `orientation\ntop`)} + text={({ datum }) => + datum.y > 0 ? `orientation\nbottom` : `orientation\ntop` + } /> } /> @@ -167,7 +206,9 @@ export const PointerOrientation = () => { x: ({ datum }) => (datum.y > 0 ? -20 : 20) }} pointerOrientation={({ datum }) => (datum.y > 0 ? "bottom" : "top")} - text={({ datum }) => (datum.y > 0 ? `orientation\nbottom` : `orientation\ntop`)} + text={({ datum }) => + datum.y > 0 ? `orientation\nbottom` : `orientation\ntop` + } /> } /> @@ -177,7 +218,9 @@ export const PointerOrientation = () => { (index < 3 ? "bottom" : "top")} - text={({ index }) => (index < 3 ? `orientation\nbottom` : `orientation\ntop`)} + text={({ index }) => + index < 3 ? `orientation\nbottom` : `orientation\ntop` + } /> } /> @@ -190,7 +233,9 @@ export const PointerOrientation = () => { x: ({ datum }) => (datum.y > 0 ? 55 : -55) }} pointerOrientation={({ datum }) => (datum.y > 0 ? "left" : "right")} - text={({ datum }) => (datum.y > 0 ? `orientation\nleft` : `orientation\nright`)} + text={({ datum }) => + datum.y > 0 ? `orientation\nleft` : `orientation\nright` + } /> } /> @@ -201,7 +246,9 @@ export const PointerOrientation = () => { (datum.y > 0 ? "left" : "right")} - text={({ datum }) => (datum.y > 0 ? `orientation\nleft` : `orientation\nright`)} + text={({ datum }) => + datum.y > 0 ? `orientation\nleft` : `orientation\nright` + } /> } /> @@ -212,9 +259,13 @@ export const PointerOrientation = () => { (index === 2 || index === 3 ? "right" : "left")} + pointerOrientation={({ index }) => + index === 2 || index === 3 ? "right" : "left" + } text={({ index }) => - index === 2 || index === 3 ? `orientation\nleft` : `orientation\nright` + index === 2 || index === 3 + ? `orientation\nleft` + : `orientation\nright` } /> } @@ -297,16 +348,22 @@ export const FlyoutHeight = () => {
    } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> {
    } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> { labelComponent={ (index === 0 || index === 4 ? 20 : null) }} + centerOffset={{ + x: ({ index }) => (index === 0 || index === 4 ? 20 : null) + }} pointerWidth={({ text }) => (text === "skinny" ? 0 : 20)} text={({ index }) => (index > 2 ? "skinny" : "wide ")} /> @@ -534,7 +599,9 @@ export const PointerLength = () => { labelComponent={ (index === 0 || index === 4 ? 20 : null) }} + centerOffset={{ + x: ({ index }) => (index === 0 || index === 4 ? 20 : null) + }} pointerLength={({ text }) => (text === "short" ? 1 : 30)} text={({ index }) => (index > 2 ? "short" : "long ")} /> @@ -549,16 +616,22 @@ export const CornerRadius = () => {
    } + labelComponent={ + + } /> } + labelComponent={ + + } /> } + labelComponent={ + + } /> { } @@ -616,7 +693,12 @@ export const FlyoutStyle = () => { } @@ -665,7 +747,9 @@ export const FlyoutPadding = () => { labelComponent={ (datum.y > 0 ? { top: 20, left: 15, right: 5 } : 2)} + flyoutPadding={({ datum }) => + datum.y > 0 ? { top: 20, left: 15, right: 5 } : 2 + } text={`flyoutPadding\nfunction`} /> } diff --git a/test/client/spec/mock-components.js b/test/client/spec/mock-components.js index 1e89ee06c..48cf45ddb 100644 --- a/test/client/spec/mock-components.js +++ b/test/client/spec/mock-components.js @@ -102,11 +102,22 @@ class MockVictoryComponent extends React.Component { }); const labelComponents = map(this.dataKeys, (_key, index) => { - const labelProps = this.getComponentProps(labelComponent, "labels", index); - return get(labelProps, "text") ? React.cloneElement(labelComponent, labelProps) : undefined; + const labelProps = this.getComponentProps( + labelComponent, + "labels", + index + ); + return get(labelProps, "text") + ? React.cloneElement(labelComponent, labelProps) + : undefined; }); - return React.cloneElement(groupComponent, {}, ...dataComponents, ...labelComponents); + return React.cloneElement( + groupComponent, + {}, + ...dataComponents, + ...labelComponents + ); } } diff --git a/test/client/spec/svg-test-helper-pie.js b/test/client/spec/svg-test-helper-pie.js index 7e3f57753..2851acd0e 100644 --- a/test/client/spec/svg-test-helper-pie.js +++ b/test/client/spec/svg-test-helper-pie.js @@ -50,9 +50,10 @@ const SvgTestHelper = { const firstSweepFlag = commands[1].args[4]; const secondSweepFlag = commands[3].args[4]; - expect(firstSweepFlag, "The 2 arcs are drawn in opposite directions").to.not.eql( - secondSweepFlag - ); + expect( + firstSweepFlag, + "The 2 arcs are drawn in opposite directions" + ).to.not.eql(secondSweepFlag); const startOfOuterArc = { x: commands[0].args[0], @@ -120,7 +121,9 @@ const SvgTestHelper = { */ parseSvgPathCommands: (str) => { // Match on all valid SVG path commands - const matches = str.match(/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g); + const matches = str.match( + /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g + ); return matches.map((match) => { return { @@ -210,7 +213,8 @@ const SvgTestHelper = { const cartesianY1 = coord1.y * -1; const cartesianY2 = coord2.y * -1; - const radians = Math.atan2(cartesianY1, coord1.x) - Math.atan2(cartesianY2, coord2.x); + const radians = + Math.atan2(cartesianY1, coord1.x) - Math.atan2(cartesianY2, coord2.x); const theta = radians * (180 / Math.PI); return theta < 0 ? 360 + theta : theta; diff --git a/test/client/spec/svg-test-helper.js b/test/client/spec/svg-test-helper.js index f68262778..53af3afb0 100644 --- a/test/client/spec/svg-test-helper.js +++ b/test/client/spec/svg-test-helper.js @@ -5,10 +5,25 @@ import { assign, without, min, max, property } from "lodash"; const RECTANGULAR_SEQUENCE = ["M", "A", "L", "A", "L", "A", "L", "A", "z"]; const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"]; -const FLYOUT_SEQUENCE = ["M", "L", "L", "L", "A", "L", "A", "L", "A", "L", "A", "z"]; +const FLYOUT_SEQUENCE = [ + "M", + "L", + "L", + "L", + "A", + "L", + "A", + "L", + "A", + "L", + "A", + "z" +]; const parseSvgPathCommands = (commandStr) => { - const matches = commandStr.match(/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g); + const matches = commandStr.match( + /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g + ); return matches.map((match) => { const name = match.charAt(0); @@ -42,12 +57,15 @@ const exhibitsShapeSequence = (wrapper, shapeSequence) => { const calculateD3Path = (props, pathType, index) => { // eslint-disable-line max-statements const { width, height, padding, scale, interpolation, data, domain } = props; - const scaleType = scale ? `scale${scale[0].toUpperCase() + scale.slice(1)}` : "scaleLinear"; + const scaleType = scale + ? `scale${scale[0].toUpperCase() + scale.slice(1)}` + : "scaleLinear"; const curveType = typeof interpolation === "string" ? `curve${interpolation[0].toUpperCase() + interpolation.slice(1)}` : undefined; - const curveFunction = typeof interpolation === "function" ? interpolation : d3Shape[curveType]; + const curveFunction = + typeof interpolation === "function" ? interpolation : d3Shape[curveType]; const dataDomain = data.reduce( (prev, datum) => { @@ -179,7 +197,9 @@ const expectations = { */ expectIsFlyout(wrapper) { const commands = getPathCommandsFromWrapper(wrapper); - expect(exhibitsShapeSequence(wrapper, FLYOUT_SEQUENCE, commands)).to.equal(true); + expect(exhibitsShapeSequence(wrapper, FLYOUT_SEQUENCE, commands)).to.equal( + true + ); } }; diff --git a/test/client/spec/victory-area/victory-area.spec.js b/test/client/spec/victory-area/victory-area.spec.js index 924e6e316..02498ea5f 100644 --- a/test/client/spec/victory-area/victory-area.spec.js +++ b/test/client/spec/victory-area/victory-area.spec.js @@ -60,7 +60,9 @@ describe("components/victory-area", () => { { x: 4, y: 1, y0: 0 } ] }; - const stringWrapper = mount(); + const stringWrapper = mount( + + ); const stringArea = stringWrapper.find(Area); const stringPath = stringArea.find("path").prop("d"); SvgTestHelper.expectCorrectD3Path( @@ -69,7 +71,9 @@ describe("components/victory-area", () => { "area" ); - const functionWrapper = mount(); + const functionWrapper = mount( + + ); const functionArea = functionWrapper.find(Area); const functionPath = functionArea.find("path").prop("d"); SvgTestHelper.expectCorrectD3Path( @@ -138,7 +142,13 @@ describe("components/victory-area", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -212,14 +222,19 @@ describe("components/victory-area", () => { `data point 1's x value is ${data[0].x}`} tabIndex={4} /> + `data point 1's x value is ${data[0].x}`} + tabIndex={4} + /> } /> ); expect(wrapper.find("path")).to.have.length(1); wrapper.find("path").forEach((p, i) => { - expect(p.prop("aria-label")).to.equal(`data point 1's x value is ${ariaTestData[i].x}`); + expect(p.prop("aria-label")).to.equal( + `data point 1's x value is ${ariaTestData[i].x}` + ); expect(p.prop("tabIndex")).to.equal(4); }); }); diff --git a/test/client/spec/victory-axis/victory-axis.spec.js b/test/client/spec/victory-axis/victory-axis.spec.js index f260df56b..b3bea4eea 100644 --- a/test/client/spec/victory-axis/victory-axis.spec.js +++ b/test/client/spec/victory-axis/victory-axis.spec.js @@ -80,13 +80,17 @@ describe("components/victory-axis", () => { }); it("renders ticks as lines", () => { - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); const ticks = wrapper.find('[type="axis"]'); ticks.forEach(SvgTestHelper.expectIsALine); }); it("renders a line", () => { - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); const line = wrapper.find('[type="axis"]'); SvgTestHelper.expectIsALine(line); }); @@ -94,7 +98,10 @@ describe("components/victory-axis", () => { it("renders labels with auto-generated ids if id is not provided", () => { const wrapper = shallow( - } /> + } + /> ); const labels = wrapper.find("VictoryLabel"); expect(labels.length).to.equal(3); @@ -110,7 +117,9 @@ describe("components/victory-axis", () => { tickLabelComponent={ `generated-id-${props.text[props.index].toLowerCase()}`} + id={(props) => + `generated-id-${props.text[props.index].toLowerCase()}` + } /> } /> @@ -125,7 +134,9 @@ describe("components/victory-axis", () => { describe("dependentAxis prop", () => { it("renders a horizontal axis by default", () => { const props = { padding: 50, width: 300 }; - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); const line = wrapper.find('[type="axis"]'); expect(SvgTestHelper.isHorizontalAxis(line, props)).to.equal(true); }); @@ -133,7 +144,11 @@ describe("components/victory-axis", () => { it("renders a vertical axis if specified", () => { const props = { padding: 50, height: 300 }; const wrapper = mount( - } /> + } + /> ); const line = wrapper.find('[type="axis"]'); expect(SvgTestHelper.isVerticalAxis(line, props)).to.equal(true); @@ -157,7 +172,13 @@ describe("components/victory-axis", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("ticks", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "ticks", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to the axis line", () => { @@ -189,7 +210,10 @@ describe("components/victory-axis", () => { describe("label overlap", () => { describe("with empty label widths", () => { before(() => { - sinon.stub(TextSize, "approximateTextSize", () => ({ width: 0, height: 0 })); + sinon.stub(TextSize, "approximateTextSize", () => ({ + width: 0, + height: 0 + })); }); after(() => { TextSize.approximateTextSize.restore(); @@ -213,7 +237,10 @@ describe("components/victory-axis", () => { }); describe("with not empty label widths", () => { beforeEach(() => { - sinon.stub(TextSize, "approximateTextSize", () => ({ width: 30, height: 30 })); + sinon.stub(TextSize, "approximateTextSize", () => ({ + width: 30, + height: 30 + })); }); afterEach(() => { @@ -261,7 +288,9 @@ describe("components/victory-axis", () => { }} /> ); - const labelTexts = wrapper.find("VictoryLabel").map((tick) => tick.props("text").text); + const labelTexts = wrapper + .find("VictoryLabel") + .map((tick) => tick.props("text").text); expect(labelTexts.filter((text) => text === "1")).to.be.not.empty; expect(labelTexts.filter((text) => text === "2")).to.be.empty; expect(labelTexts.filter((text) => text === "3")).to.be.not.empty; @@ -280,7 +309,9 @@ describe("components/victory-axis", () => { }} /> ); - const labelTexts = wrapper.find("VictoryLabel").map((tick) => tick.props("text").text); + const labelTexts = wrapper + .find("VictoryLabel") + .map((tick) => tick.props("text").text); expect(labelTexts.filter((text) => text === "1")).to.be.not.empty; expect(labelTexts.filter((text) => text === "2")).to.be.empty; expect(labelTexts.filter((text) => text === "3")).to.be.not.empty; diff --git a/test/client/spec/victory-bar/geometry-helper-methods.spec.js b/test/client/spec/victory-bar/geometry-helper-methods.spec.js index cf7e9fea4..7e6650cb0 100644 --- a/test/client/spec/victory-bar/geometry-helper-methods.spec.js +++ b/test/client/spec/victory-bar/geometry-helper-methods.spec.js @@ -1,4 +1,7 @@ -import { circle, point } from "packages/victory-bar/src/geometry-helper-methods"; +import { + circle, + point +} from "packages/victory-bar/src/geometry-helper-methods"; const epsilon = 0.01; // float imprecision diff --git a/test/client/spec/victory-bar/victory-bar.spec.js b/test/client/spec/victory-bar/victory-bar.spec.js index 8f5c62e5e..8bba4b2fa 100644 --- a/test/client/spec/victory-bar/victory-bar.spec.js +++ b/test/client/spec/victory-bar/victory-bar.spec.js @@ -61,7 +61,9 @@ describe("components/victory-bar", () => { const data = range(5) .map((i) => ({ x: i, y: i })) .reverse(); - const wrapper = shallow(); + const wrapper = shallow( + + ); const xValues = wrapper.find(Bar).map((bar) => bar.prop("datum")._x); expect(xValues).to.eql([4, 3, 2, 1, 0]); }); @@ -75,7 +77,9 @@ describe("components/victory-bar", () => { it("renders bars for deeply-nested data", () => { const data = range(40).map((i) => ({ a: { b: [{ x: i, y: i }] } })); - const wrapper = shallow(); + const wrapper = shallow( + + ); const bars = wrapper.find(Bar); expect(bars.length).to.equal(40); }); @@ -132,7 +136,13 @@ describe("components/victory-bar", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -217,7 +227,10 @@ describe("components/victory-bar", () => { `x: ${datum.x}`} tabIndex={({ index }) => index + 1} /> + `x: ${datum.x}`} + tabIndex={({ index }) => index + 1} + /> } /> ); diff --git a/test/client/spec/victory-box-plot/victory-box-plot.spec.js b/test/client/spec/victory-box-plot/victory-box-plot.spec.js index 9792112cf..3cd7ce0d3 100644 --- a/test/client/spec/victory-box-plot/victory-box-plot.spec.js +++ b/test/client/spec/victory-box-plot/victory-box-plot.spec.js @@ -53,7 +53,9 @@ describe("components/victory-box-plot", () => { { x: 2, y: null }, { x: 2, y: null } ]; - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); expect(wrapper.find('[data-test="testGroup"]').length).to.equal(1); }); @@ -62,7 +64,9 @@ describe("components/victory-box-plot", () => { { x: 1, y: [1, 2, 3, 5, 8] }, { x: 1, y: [null, 2, 5, 9, 14] } ]; - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); expect(wrapper.find('[data-test="testGroup"]').length).to.equal(1); }); @@ -75,7 +79,9 @@ describe("components/victory-box-plot", () => { { x: 5, min: 2, median: 8, max: 15, q1: null, q3: 12 }, { x: 5, min: 2, median: 10, max: 20, q1: 8, q3: null } ]; - const wrapper = mount(} />); + const wrapper = mount( + } /> + ); expect(wrapper.find('[data-test="testGroup"]').length).to.equal(1); }); @@ -111,10 +117,18 @@ describe("components/victory-box-plot", () => { /> ); - const whiskersWithAriaLabel = wrapper.find("line").filterWhere((l) => l.prop("aria-label")); - expect(whiskersWithAriaLabel.first().html().includes("1 max is 18")).to.equal(true); - expect(whiskersWithAriaLabel.last().html().includes("3 max is 12")).to.equal(true); - expect(whiskersWithAriaLabel.at(3).html().includes("2 max is 25")).to.equal(false); + const whiskersWithAriaLabel = wrapper + .find("line") + .filterWhere((l) => l.prop("aria-label")); + expect( + whiskersWithAriaLabel.first().html().includes("1 max is 18") + ).to.equal(true); + expect( + whiskersWithAriaLabel.last().html().includes("3 max is 12") + ).to.equal(true); + expect( + whiskersWithAriaLabel.at(3).html().includes("2 max is 25") + ).to.equal(false); // 2 whiskers for each max value for "T" shape expect(whiskersWithAriaLabel).to.have.length(6); }); @@ -131,11 +145,21 @@ describe("components/victory-box-plot", () => { } /> ); - const q3Elements = wrapper.find("rect").filterWhere((l) => l.prop("aria-label")); - expect(q3Elements.first().html().includes("1 q3 value is 15")).to.equal(true); - expect(q3Elements.at(1).html().includes("2 q3 value is 15")).to.equal(true); - expect(q3Elements.at(1).html().includes("2 q3 value is 8")).to.equal(false); - expect(q3Elements.last().html().includes("3 q3 value is 10")).to.equal(true); + const q3Elements = wrapper + .find("rect") + .filterWhere((l) => l.prop("aria-label")); + expect(q3Elements.first().html().includes("1 q3 value is 15")).to.equal( + true + ); + expect(q3Elements.at(1).html().includes("2 q3 value is 15")).to.equal( + true + ); + expect(q3Elements.at(1).html().includes("2 q3 value is 8")).to.equal( + false + ); + expect(q3Elements.last().html().includes("3 q3 value is 10")).to.equal( + true + ); // 2 whiskers for each max value for "T" shape expect(q3Elements).to.have.length(3); }); @@ -146,17 +170,29 @@ describe("components/victory-box-plot", () => { data={dataset} medianComponent={ `${datum.x} median value is ${datum._median}`} + ariaLabel={({ datum }) => + `${datum.x} median value is ${datum._median}` + } tabIndex={({ index }) => index + 1.3} /> } /> ); - const medianLine = wrapper.find("line").filterWhere((l) => l.prop("aria-label")); - expect(medianLine.first().html().includes("1 median value is 8")).to.equal(true); - expect(medianLine.at(1).html().includes("2 median value is 10")).to.equal(true); - expect(medianLine.at(1).html().includes("2 median value is 8")).to.equal(false); - expect(medianLine.last().html().includes("3 median value is 6")).to.equal(true); + const medianLine = wrapper + .find("line") + .filterWhere((l) => l.prop("aria-label")); + expect( + medianLine.first().html().includes("1 median value is 8") + ).to.equal(true); + expect(medianLine.at(1).html().includes("2 median value is 10")).to.equal( + true + ); + expect(medianLine.at(1).html().includes("2 median value is 8")).to.equal( + false + ); + expect(medianLine.last().html().includes("3 median value is 6")).to.equal( + true + ); // 2 whiskers for each max value for "T" shape expect(medianLine).to.have.length(3); }); diff --git a/test/client/spec/victory-brush-container/brush-helpers.spec.js b/test/client/spec/victory-brush-container/brush-helpers.spec.js index b4529de07..bc8f9d95e 100644 --- a/test/client/spec/victory-brush-container/brush-helpers.spec.js +++ b/test/client/spec/victory-brush-container/brush-helpers.spec.js @@ -19,14 +19,24 @@ describe("containers/brush-helpers", () => { it("returns true when within bounds using dates", () => { const point = { x: new Date("1/2/2017"), y: 1 }; - const bounds = { x1: new Date("1/1/2017"), x2: new Date("2/1/2017"), y1: 0, y2: 2 }; + const bounds = { + x1: new Date("1/1/2017"), + x2: new Date("2/1/2017"), + y1: 0, + y2: 2 + }; const isWithinBoundsResults = BrushHelpers.withinBounds(point, bounds); expect(isWithinBoundsResults).to.eql(true); }); it("returns false when not within bounds using dates", () => { const point = { x: new Date("3/2/2017"), y: 1 }; - const bounds = { x1: new Date("1/1/2017"), x2: new Date("2/1/2017"), y1: 0, y2: 2 }; + const bounds = { + x1: new Date("1/1/2017"), + x2: new Date("2/1/2017"), + y1: 0, + y2: 2 + }; const isWithinBoundsResults = BrushHelpers.withinBounds(point, bounds); expect(isWithinBoundsResults).to.eql(false); }); @@ -47,9 +57,19 @@ describe("containers/brush-helpers", () => { y1: 0, y2: 2 }; - const box = { x1: new Date("1/1/2017 PST"), x2: new Date("1/10/2017 PST"), y1: 1, y2: 2 }; + const box = { + x1: new Date("1/1/2017 PST"), + x2: new Date("1/10/2017 PST"), + y1: 1, + y2: 2 + }; const constrainBoxResult = BrushHelpers.constrainBox(box, fullDomainBox); - expect(constrainBoxResult).to.eql({ x1: 1483344000000, y1: 1, x2: 1484121600000, y2: 2 }); + expect(constrainBoxResult).to.eql({ + x1: 1483344000000, + y1: 1, + x2: 1484121600000, + y2: 2 + }); }); }); }); diff --git a/test/client/spec/victory-candlestick/helper-methods.spec.js b/test/client/spec/victory-candlestick/helper-methods.spec.js index 065bfda55..2cc254a66 100644 --- a/test/client/spec/victory-candlestick/helper-methods.spec.js +++ b/test/client/spec/victory-candlestick/helper-methods.spec.js @@ -1,6 +1,9 @@ /* eslint no-unused-expressions: 0 */ /* eslint max-nested-callbacks: 0 */ -import { getData, getDomain } from "packages/victory-candlestick/src/helper-methods"; +import { + getData, + getDomain +} from "packages/victory-candlestick/src/helper-methods"; import { range } from "lodash"; import { fromJS } from "immutable"; @@ -45,7 +48,14 @@ const getDataTest = { it("returns a domain array for the x axis", () => { const domainXResult = getDomain( - { data: dataSet, x: "x", open: "open", close: "close", high: "high", low: "low" }, + { + data: dataSet, + x: "x", + open: "open", + close: "close", + high: "high", + low: "low" + }, "x" ); expect(domainXResult).to.eql([5, 10]); @@ -53,7 +63,13 @@ const getDataTest = { it("returns a domain array for the y axis", () => { const domainYResult = getDomain( - { data: dataSet, open: "open", close: "close", high: "high", low: "low" }, + { + data: dataSet, + open: "open", + close: "close", + high: "high", + low: "low" + }, "y" ); expect(domainYResult).to.eql([5, 30]); diff --git a/test/client/spec/victory-candlestick/victory-candlestick.spec.js b/test/client/spec/victory-candlestick/victory-candlestick.spec.js index 9c9bc302c..f4e238030 100644 --- a/test/client/spec/victory-candlestick/victory-candlestick.spec.js +++ b/test/client/spec/victory-candlestick/victory-candlestick.spec.js @@ -6,7 +6,10 @@ import React from "react"; import { shallow, mount } from "enzyme"; import { range, omit } from "lodash"; -import { VictoryCandlestick, Candle } from "packages/victory-candlestick/src/index"; +import { + VictoryCandlestick, + Candle +} from "packages/victory-candlestick/src/index"; import { VictoryLabel } from "packages/victory-core"; class MyCandle extends React.Component { @@ -43,15 +46,29 @@ describe("components/victory-candlestick", () => { describe("rendering data", () => { it("renders injected points for {x, y} shaped data (default)", () => { - const data = range(10).map((i) => ({ x: i, open: i, close: i, high: i, low: i })); - const wrapper = shallow(} />); + const data = range(10).map((i) => ({ + x: i, + open: i, + close: i, + high: i, + low: i + })); + const wrapper = shallow( + } /> + ); const points = wrapper.find(MyCandle); expect(points.length).to.equal(10); }); it("renders points for {x, y} shaped data (default)", () => { - const data = range(10).map((i) => ({ x: i, open: i, close: i, high: i, low: i })); + const data = range(10).map((i) => ({ + x: i, + open: i, + close: i, + high: i, + low: i + })); const wrapper = shallow(); const points = wrapper.find(Candle); expect(points.length).to.equal(10); @@ -80,7 +97,14 @@ describe("components/victory-candlestick", () => { it("renders points for array-shaped data", () => { const data = range(20).map((i) => [i, i, i, i, i]); const wrapper = shallow( - + ); const points = wrapper.find(Candle); expect(points.length).to.equal(20); @@ -107,7 +131,14 @@ describe("components/victory-candlestick", () => { it("renders data values with null accessor", () => { const data = range(30); const wrapper = shallow( - + ); const points = wrapper.find(Candle); expect(points.length).to.equal(30); @@ -211,7 +242,9 @@ describe("components/victory-candlestick", () => { data={data} dataComponent={ `open ${datum.open}, close ${datum.close}`} + ariaLabel={({ datum }) => + `open ${datum.open}, close ${datum.close}` + } tabIndex={({ index }) => index + 5} /> } @@ -221,7 +254,9 @@ describe("components/victory-candlestick", () => { expect(wrapper.find("rect")).to.have.length(3); expect(wrapper.find("line")).to.have.length(6); wrapper.find("rect").forEach((p, i) => { - expect(p.prop("aria-label")).to.equal(`open ${data[i].open}, close ${data[i].close}`); + expect(p.prop("aria-label")).to.equal( + `open ${data[i].open}, close ${data[i].close}` + ); expect(p.prop("tabIndex")).to.equal(i + 5); }); wrapper.find("line").forEach((p, i) => { diff --git a/test/client/spec/victory-chart/helper-methods.spec.js b/test/client/spec/victory-chart/helper-methods.spec.js index 92ae24524..8ed2202a4 100644 --- a/test/client/spec/victory-chart/helper-methods.spec.js +++ b/test/client/spec/victory-chart/helper-methods.spec.js @@ -29,7 +29,10 @@ describe("victory-chart/helpers-methods", () => { const children = []; const result = getChildComponents({ children }, defaultAxes); expect(result).to.have.length(2); - expect(result).to.deep.include.members([defaultAxes.independent, defaultAxes.dependent]); + expect(result).to.deep.include.members([ + defaultAxes.independent, + defaultAxes.dependent + ]); }); it("adds default axes when none of the children are axis components", () => { @@ -37,7 +40,10 @@ describe("victory-chart/helpers-methods", () => { const children = [line]; const result = getChildComponents({ children }, defaultAxes); expect(result).to.have.length(3); - expect(result).to.deep.include.members([defaultAxes.independent, defaultAxes.dependent]); + expect(result).to.deep.include.members([ + defaultAxes.independent, + defaultAxes.dependent + ]); }); it("does not add default axes if axis any axis components exist in children", () => { diff --git a/test/client/spec/victory-chart/victory-chart.spec.js b/test/client/spec/victory-chart/victory-chart.spec.js index fb95af7f4..6a9132274 100644 --- a/test/client/spec/victory-chart/victory-chart.spec.js +++ b/test/client/spec/victory-chart/victory-chart.spec.js @@ -74,7 +74,12 @@ describe("components/victory-chart", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "scale", + "width", + "height", + "style" + ); }); }); }); diff --git a/test/client/spec/victory-core/victory-accessible-group/victory-accessible-group.spec.js b/test/client/spec/victory-core/victory-accessible-group/victory-accessible-group.spec.js index bf567ce29..ad8405dd5 100644 --- a/test/client/spec/victory-core/victory-accessible-group/victory-accessible-group.spec.js +++ b/test/client/spec/victory-core/victory-accessible-group/victory-accessible-group.spec.js @@ -9,13 +9,17 @@ import VictoryAccessibleGroup from "packages/victory-core/src/victory-accessible describe("components/victory-accessible-group", () => { it("renders an g with an aria-label", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); expect(wrapper.find("g")).to.have.length(1); expect(wrapper.find("g").prop("aria-label")).to.equal("test-aria-label"); }); it("renders an g with a tabIndex and className", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); expect(wrapper.find("g").prop("tabIndex")).to.equal(5); expect(wrapper.find("g").prop("className")).to.equal("accessibility"); }); @@ -28,7 +32,9 @@ describe("components/victory-accessible-group", () => { aria-describedby="describes group" /> ); - expect(wrapper.find("g").prop("aria-describedby")).to.equal("describes group"); + expect(wrapper.find("g").prop("aria-describedby")).to.equal( + "describes group" + ); expect(wrapper.find("desc").text()).to.equal("test description"); expect(wrapper.find("desc").props().id).to.equal("describes group"); }); @@ -40,10 +46,14 @@ describe("components/victory-accessible-group", () => { desc="applies to both aria-describeby and descId" /> ); - expect(wrapper.find("desc").text()).to.equal("applies to both aria-describeby and descId"); + expect(wrapper.find("desc").text()).to.equal( + "applies to both aria-describeby and descId" + ); expect(wrapper.find("g").prop("aria-describedby")).to.equal( "applies-to-both-aria-describeby-and-descId" ); - expect(wrapper.find("desc").props().id).to.equal("applies-to-both-aria-describeby-and-descId"); + expect(wrapper.find("desc").props().id).to.equal( + "applies-to-both-aria-describeby-and-descId" + ); }); }); diff --git a/test/client/spec/victory-core/victory-container/victory-container.spec.js b/test/client/spec/victory-core/victory-container/victory-container.spec.js index 2e42d3ca4..deddbb110 100644 --- a/test/client/spec/victory-core/victory-container/victory-container.spec.js +++ b/test/client/spec/victory-core/victory-container/victory-container.spec.js @@ -35,13 +35,17 @@ describe("components/victory-container", () => { }); it("renders an svg with an aria-describedby attribute", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const describedElement = wrapper.find(`[aria-describedby~="testid"]`).at(0); expect(describedElement.type()).to.equal("svg"); }); it("renders an svg with an aria-labelledby attribute", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const describedElement = wrapper.find(`[aria-labelledby~="testid"]`).at(0); expect(describedElement.type()).to.equal("svg"); }); @@ -57,7 +61,9 @@ describe("components/victory-container", () => { it("attaches an event to the container", () => { const clickHandler = sinon.spy(); - const wrapper = mount(); + const wrapper = mount( + + ); const svg = wrapper.find("svg").at(0); svg.simulate("click"); expect(clickHandler).called; diff --git a/test/client/spec/victory-core/victory-label/victory-label.spec.js b/test/client/spec/victory-core/victory-label/victory-label.spec.js index 552206c21..fd03e5086 100644 --- a/test/client/spec/victory-core/victory-label/victory-label.spec.js +++ b/test/client/spec/victory-core/victory-label/victory-label.spec.js @@ -14,7 +14,9 @@ describe("components/victory-label", () => { }); it("sets dx and dy for text element", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(Text); expect(output.prop("dx")).to.eql(30); // dy = props.dy + (capHeight(0.71) / 2 + (0.5 - length(1) / 2) * lineHeight(1)) * fontSize(14); @@ -22,32 +24,42 @@ describe("components/victory-label", () => { }); it("sets x and y for text element", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(Text); expect(output.prop("x")).to.eql("100%"); expect(output.prop("y")).to.eql(34.97); }); it("has a transform property that rotates the text to match the labelAngle prop", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(Text); expect(output.prop("transform")).to.contain("rotate(46"); }); it("accepts the angle prop as a function", () => { - const wrapper = shallow( 46} text={"such text, wow"} />); + const wrapper = shallow( + 46} text={"such text, wow"} /> + ); const output = wrapper.find(Text); expect(output.prop("transform")).to.contain("rotate(46"); }); it("strips px from fontSize", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(TSpan); expect(output.prop("style")).to.contain({ fontSize: 10 }); }); it("uses a default fontSize when an invalid fontSize is given", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(TSpan); expect(output.prop("style")).to.contain({ fontSize: 14 }); }); @@ -65,7 +77,9 @@ describe("components/victory-label", () => { }); it("renders title and desc if provided ", () => { - const wrapper = mount(); + const wrapper = mount( + + ); const wrapper2 = mount(); @@ -99,14 +113,18 @@ describe("components/victory-label", () => { describe("event handling", () => { it("attaches an to the parent object", () => { const clickHandler = sinon.spy(); - const wrapper = mount(); + const wrapper = mount( + + ); wrapper.find(Text).simulate("click"); expect(clickHandler.called).to.equal(true); }); }); it("renders TSpan elements inline when `inline` prop is passed", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(TSpan); output.forEach((tspan) => { @@ -121,7 +139,10 @@ describe("components/victory-label", () => { const lineHeight = [1, 2, 3]; const expectedDy = [0, 21, 35]; const wrapper = shallow( - + ); const output = wrapper.find(TSpan); @@ -137,7 +158,10 @@ describe("components/victory-label", () => { it("defaults lineHeight to 1 if an empty array is provided for lineHeight", () => { const expectedDy = [0, 14, 14, 14]; const wrapper = shallow( - + ); const output = wrapper.find(TSpan); @@ -150,7 +174,8 @@ describe("components/victory-label", () => { const defaultStyles = { fill: "#252525", fontSize: 14, - fontFamily: "'Gill Sans', 'Gill Sans MT', 'Ser­avek', 'Trebuchet MS', sans-serif", + fontFamily: + "'Gill Sans', 'Gill Sans MT', 'Ser­avek', 'Trebuchet MS', sans-serif", stroke: "transparent" }; @@ -165,7 +190,9 @@ describe("components/victory-label", () => { }); it("passes id if provided as a string", () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); const output = wrapper.find(Text); output.forEach((text) => { @@ -184,7 +211,10 @@ describe("components/victory-label", () => { it("runs function if id provided as a function", () => { const wrapper = shallow( - `created-in-function-${Math.random()}`} /> + `created-in-function-${Math.random()}`} + /> ); const output = wrapper.find(Text); diff --git a/test/client/spec/victory-core/victory-primitives/path-helper.spec.js b/test/client/spec/victory-core/victory-primitives/path-helper.spec.js index 8624cd778..54677d649 100644 --- a/test/client/spec/victory-core/victory-primitives/path-helper.spec.js +++ b/test/client/spec/victory-core/victory-primitives/path-helper.spec.js @@ -25,7 +25,9 @@ describe("path-helpers", () => { const pathResult = PathHelpers.diamond(0, 0, 1); const baseSize = 0.87 * size; const length = Math.sqrt(2 * (baseSize * baseSize)); - expect(pathResult).to.contain(`M ${Math.round(x)}, ${Math.round(y + length)}`); + expect(pathResult).to.contain( + `M ${Math.round(x)}, ${Math.round(y + length)}` + ); }); }); diff --git a/test/client/spec/victory-core/victory-primitives/point.spec.js b/test/client/spec/victory-core/victory-primitives/point.spec.js index 45d3f55a9..0bb3d421d 100644 --- a/test/client/spec/victory-core/victory-primitives/point.spec.js +++ b/test/client/spec/victory-core/victory-primitives/point.spec.js @@ -36,7 +36,9 @@ describe("victory-primitives/point", () => { "star", "cross" ].forEach((symbol) => { - const stub = sandbox.stub(pathHelpers, symbol).returns(`${symbol} symbol`); + const stub = sandbox + .stub(pathHelpers, symbol) + .returns(`${symbol} symbol`); const props = assign({}, baseProps, { symbol }); const wrapper = shallow(); const directions = wrapper.find(Path).prop("d"); diff --git a/test/client/spec/victory-core/victory-primitives/slice.spec.js b/test/client/spec/victory-core/victory-primitives/slice.spec.js index 225d726d4..62a556706 100644 --- a/test/client/spec/victory-core/victory-primitives/slice.spec.js +++ b/test/client/spec/victory-core/victory-primitives/slice.spec.js @@ -9,12 +9,16 @@ describe("victory-primitives/slice", () => { const EXPECTED_D_ATTR = "M1,1"; const slice = { x: 1, y: 1 }; const pathFunction = (sli) => { - expect(sli, "The path function is called with `props.slice`").to.eql(slice); + expect(sli, "The path function is called with `props.slice`").to.eql( + slice + ); return EXPECTED_D_ATTR; }; - const wrapper = shallow(); + const wrapper = shallow( + + ); expect(wrapper.html()).to.eql( `` // eslint-disable-line max-len diff --git a/test/client/spec/victory-core/victory-transition/victory-transition.spec.js b/test/client/spec/victory-core/victory-transition/victory-transition.spec.js index d9acb32f1..d8f1376f0 100644 --- a/test/client/spec/victory-core/victory-transition/victory-transition.spec.js +++ b/test/client/spec/victory-core/victory-transition/victory-transition.spec.js @@ -19,7 +19,10 @@ TestComponent.propTypes = { describe("components/victory-transition", () => { it("renders a child component", () => { const wrapper = mount( - + ); diff --git a/test/client/spec/victory-core/victory-util/add-events.spec.js b/test/client/spec/victory-core/victory-util/add-events.spec.js index 23c21ccd2..082126ca9 100644 --- a/test/client/spec/victory-core/victory-util/add-events.spec.js +++ b/test/client/spec/victory-core/victory-util/add-events.spec.js @@ -4,12 +4,21 @@ import React from "react"; import { get } from "lodash"; import { mount } from "enzyme"; import { addEvents } from "packages/victory-core/src/index"; -import { MockVictoryComponent, MockLabel, MockDataComponent } from "../../mock-components"; +import { + MockVictoryComponent, + MockLabel, + MockDataComponent +} from "../../mock-components"; describe("victory-util/add-events", () => { const EventedMockVictoryComponent = addEvents(MockVictoryComponent); - const expectEventsTriggered = (getComponentsToTest, testFn, expectations, wrapper) => { + const expectEventsTriggered = ( + getComponentsToTest, + testFn, + expectations, + wrapper + ) => { expect(getComponentsToTest(wrapper).map(testFn)).to.eql(expectations); }; @@ -52,11 +61,26 @@ describe("victory-util/add-events", () => { return get(dataComponent.props(), "style.fill") === "tomato"; }; - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [false, false], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [false, false], + wrapper + ); getDataComponents(wrapper).at(0).simulate("click"); - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [true, false], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [true, false], + wrapper + ); getDataComponents(wrapper).at(1).simulate("click"); - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [true, true], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [true, true], + wrapper + ); }); it("should set up events on data components scoped with an event key", () => { @@ -91,11 +115,26 @@ describe("victory-util/add-events", () => { return get(dataComponent.props(), "style.fill") === "tomato"; }; - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [false, false], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [false, false], + wrapper + ); getDataComponents(wrapper).at(0).simulate("click"); - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [false, false], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [false, false], + wrapper + ); getDataComponents(wrapper).at(1).simulate("click"); - expectEventsTriggered(getDataComponents, dataComponentIsAltered, [false, true], wrapper); + expectEventsTriggered( + getDataComponents, + dataComponentIsAltered, + [false, true], + wrapper + ); }); it("should set up events on data components to target labels", () => { @@ -130,11 +169,26 @@ describe("victory-util/add-events", () => { return get(labelComponent.props(), "text") === "altered"; }; - expectEventsTriggered(getLabelComponents, labelComponentIsAltered, [false, false], wrapper); + expectEventsTriggered( + getLabelComponents, + labelComponentIsAltered, + [false, false], + wrapper + ); getDataComponents(wrapper).at(0).simulate("click"); - expectEventsTriggered(getLabelComponents, labelComponentIsAltered, [true, false], wrapper); + expectEventsTriggered( + getLabelComponents, + labelComponentIsAltered, + [true, false], + wrapper + ); getDataComponents(wrapper).at(1).simulate("click"); - expectEventsTriggered(getLabelComponents, labelComponentIsAltered, [true, true], wrapper); + expectEventsTriggered( + getLabelComponents, + labelComponentIsAltered, + [true, true], + wrapper + ); }); describe("when adding animations to the component", () => { @@ -162,7 +216,9 @@ describe("victory-util/add-events", () => { const victoryTransitionWrapper = wrapper.find("VictoryTransition"); - expect(victoryTransitionWrapper.prop("animationWhitelist")).to.deep.equal(["allTheThings"]); + expect( + victoryTransitionWrapper.prop("animationWhitelist") + ).to.deep.equal(["allTheThings"]); }); }); }); diff --git a/test/client/spec/victory-core/victory-util/axis.spec.js b/test/client/spec/victory-core/victory-util/axis.spec.js index 649704e71..dba4aa318 100644 --- a/test/client/spec/victory-core/victory-util/axis.spec.js +++ b/test/client/spec/victory-core/victory-util/axis.spec.js @@ -89,8 +89,12 @@ describe("helpers/axis", () => { it("returns the independent axis when called with 'x'", () => { const childComponents = [dependentAxis, independentAxis, bar]; const componentResult = Axis.getAxisComponent(childComponents, "x"); - expect(dependentAxis.type.getAxis).calledWith(dependentAxis.props).and.returned("y"); - expect(independentAxis.type.getAxis).calledWith(independentAxis.props).and.returned("x"); + expect(dependentAxis.type.getAxis) + .calledWith(dependentAxis.props) + .and.returned("y"); + expect(independentAxis.type.getAxis) + .calledWith(independentAxis.props) + .and.returned("x"); expect(componentResult).to.eql(independentAxis); }); }); diff --git a/test/client/spec/victory-core/victory-util/collection.spec.js b/test/client/spec/victory-core/victory-util/collection.spec.js index d14e23d16..5bc7561dd 100644 --- a/test/client/spec/victory-core/victory-util/collection.spec.js +++ b/test/client/spec/victory-core/victory-util/collection.spec.js @@ -15,7 +15,9 @@ describe("victory-util/collection", () => { it("returns false for collections of non-strings", () => { expect(Collection.containsStrings([0, 1])).to.equal(false); - expect(Collection.containsStrings([undefined, null, NaN])).to.equal(false); + expect(Collection.containsStrings([undefined, null, NaN])).to.equal( + false + ); expect(Collection.containsStrings([{}, { a: "foo" }])).to.equal(false); }); @@ -37,14 +39,22 @@ describe("victory-util/collection", () => { it("returns false for collections of non-strings", () => { expect(Collection.containsOnlyStrings([0, 1])).to.equal(false); - expect(Collection.containsOnlyStrings([undefined, null, NaN])).to.equal(false); - expect(Collection.containsOnlyStrings([{}, { a: "foo" }])).to.equal(false); + expect(Collection.containsOnlyStrings([undefined, null, NaN])).to.equal( + false + ); + expect(Collection.containsOnlyStrings([{}, { a: "foo" }])).to.equal( + false + ); }); it("returns false for collections with some strings", () => { expect(Collection.containsOnlyStrings(["hello", 0])).to.equal(false); - expect(Collection.containsOnlyStrings(["hello", ["not me"]])).to.equal(false); - expect(Collection.containsOnlyStrings([0, "hello", {}, null])).to.equal(false); + expect(Collection.containsOnlyStrings(["hello", ["not me"]])).to.equal( + false + ); + expect(Collection.containsOnlyStrings([0, "hello", {}, null])).to.equal( + false + ); }); it("returns true for collections with only strings", () => { @@ -93,7 +103,16 @@ describe("victory-util/collection", () => { }); it("filters out undefineds", () => { - const testArray = [undefined, 0, undefined, {}, false, null, NaN, undefined]; + const testArray = [ + undefined, + 0, + undefined, + {}, + false, + null, + NaN, + undefined + ]; const expectedArray = [0, {}, false, null, NaN]; expect(Collection.removeUndefined(testArray)).to.eql(expectedArray); }); @@ -118,7 +137,11 @@ describe("victory-util/collection", () => { describe("getMinValue", () => { it("returns a date if array contains dates", () => { - const array = [new Date(2016, 3, 6), new Date(2017, 5, 3), new Date(2015, 11, 4)]; + const array = [ + new Date(2016, 3, 6), + new Date(2017, 5, 3), + new Date(2015, 11, 4) + ]; expect(Collection.getMinValue(array)).to.eql(new Date(2015, 11, 4)); }); diff --git a/test/client/spec/victory-core/victory-util/domain.spec.js b/test/client/spec/victory-core/victory-util/domain.spec.js index 54cfb97dc..46a50ad72 100644 --- a/test/client/spec/victory-core/victory-util/domain.spec.js +++ b/test/client/spec/victory-core/victory-util/domain.spec.js @@ -71,7 +71,8 @@ describe("victory-util/domain", () => { const props = { ...baseProps, domainPadding }; const paddedDomain = Domain.formatDomain(domain, props, "x"); const adjustedDomain = domain[1] + pad; - const adjustedPercent = adjustedDomain / (baseProps.width - baseProps.padding); + const adjustedPercent = + adjustedDomain / (baseProps.width - baseProps.padding); const totalPadding = adjustedPercent * pad; expect(paddedDomain).to.eql([0, domain[1] + totalPadding]); }); diff --git a/test/client/spec/victory-core/victory-util/helpers.spec.js b/test/client/spec/victory-core/victory-util/helpers.spec.js index 28cb2db1a..968da177d 100644 --- a/test/client/spec/victory-core/victory-util/helpers.spec.js +++ b/test/client/spec/victory-core/victory-util/helpers.spec.js @@ -47,7 +47,9 @@ describe("victory-util/helpers", () => { ...props, data: 42 }; - expect(Helpers.modifyProps(props, fallbackProps, role)).to.eql(modifiedProps); + expect(Helpers.modifyProps(props, fallbackProps, role)).to.eql( + modifiedProps + ); }); it("uses fallbackProps", () => { const props = { x: 2, y: 3 }; @@ -76,7 +78,10 @@ describe("victory-util/helpers", () => { color: (datum) => (datum.y > 0 ? "red" : "blue"), size: 5 }; - expect(Helpers.evaluateStyle(style, data)).to.deep.equal({ color: "red", size: 5 }); + expect(Helpers.evaluateStyle(style, data)).to.deep.equal({ + color: "red", + size: 5 + }); }); it("returns no styles if disableInlineStyles is true", () => { const style = { @@ -116,16 +121,28 @@ describe("victory-util/helpers", () => { it("merges styles", () => { const style = { data: { fill: "red" }, labels: { fontSize: 12 } }; const styles = Helpers.getStyles(style, defaultStyles); - expect(styles.parent).to.deep.equal({ border: "black", width: "100%", height: "100%" }); + expect(styles.parent).to.deep.equal({ + border: "black", + width: "100%", + height: "100%" + }); expect(styles.data).to.deep.equal({ fill: "red", stroke: "black" }); - expect(styles.labels).to.deep.equal({ fontSize: 12, fontFamily: "Helvetica" }); + expect(styles.labels).to.deep.equal({ + fontSize: 12, + fontFamily: "Helvetica" + }); }); }); describe("getPadding", () => { it("sets padding from a single number", () => { const props = { padding: 40 }; - expect(Helpers.getPadding(props)).to.deep.equal({ top: 40, bottom: 40, left: 40, right: 40 }); + expect(Helpers.getPadding(props)).to.deep.equal({ + top: 40, + bottom: 40, + left: 40, + right: 40 + }); }); it("sets padding from a complete object", () => { const props = { @@ -137,7 +154,12 @@ describe("victory-util/helpers", () => { const props = { padding: { top: 40, bottom: 40 } }; - expect(Helpers.getPadding(props)).to.deep.equal({ top: 40, bottom: 40, left: 0, right: 0 }); + expect(Helpers.getPadding(props)).to.deep.equal({ + top: 40, + bottom: 40, + left: 0, + right: 0 + }); }); }); diff --git a/test/client/spec/victory-core/victory-util/label-helpers.spec.js b/test/client/spec/victory-core/victory-util/label-helpers.spec.js index 807e97af8..b467c5a21 100644 --- a/test/client/spec/victory-core/victory-util/label-helpers.spec.js +++ b/test/client/spec/victory-core/victory-util/label-helpers.spec.js @@ -50,10 +50,17 @@ describe("victory-util/label-helpers", () => { y: d3Scale.scaleLinear() }; data.forEach((datum, index) => { - const props = assign({}, basicProps, { scale: polarScale, polar: true }); + const props = assign({}, basicProps, { + scale: polarScale, + polar: true + }); const labelProps = LabelHelpers.getProps(props, index); - expect(labelProps.x).to.equal(datum.y * Math.cos(datum.x * Math.PI * 2)); - expect(labelProps.y).to.equal(-datum.y * Math.sin(datum.x * Math.PI * 2)); + expect(labelProps.x).to.equal( + datum.y * Math.cos(datum.x * Math.PI * 2) + ); + expect(labelProps.y).to.equal( + -datum.y * Math.sin(datum.x * Math.PI * 2) + ); }); }); }); @@ -64,24 +71,56 @@ describe("victory-util/label-helpers", () => { expect(angle).to.equal(0); }); it("returns angles corresponding to perpendicular labelPlacement", () => { - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 15)).to.equal(75); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 45)).to.equal(45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 90)).to.equal(0); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 135)).to.equal(-45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 180)).to.equal(90); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 225)).to.equal(45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 270)).to.equal(0); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 315)).to.equal(-45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 15) + ).to.equal(75); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 45) + ).to.equal(45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 90) + ).to.equal(0); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 135) + ).to.equal(-45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 180) + ).to.equal(90); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 225) + ).to.equal(45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 270) + ).to.equal(0); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "perpendicular" }, 315) + ).to.equal(-45); }); it("returns angles corresponding to parallel labelPlacement", () => { - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 15)).to.equal(-15); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 45)).to.equal(-45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 90)).to.equal(-90); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 135)).to.equal(45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 180)).to.equal(0); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 225)).to.equal(-45); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 270)).to.equal(-90); - expect(LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 315)).to.equal(45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 15) + ).to.equal(-15); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 45) + ).to.equal(-45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 90) + ).to.equal(-90); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 135) + ).to.equal(45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 180) + ).to.equal(0); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 225) + ).to.equal(-45); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 270) + ).to.equal(-90); + expect( + LabelHelpers.getPolarAngle({ labelPlacement: "parallel" }, 315) + ).to.equal(45); }); }); }); diff --git a/test/client/spec/victory-core/victory-util/prop-types.spec.js b/test/client/spec/victory-core/victory-util/prop-types.spec.js index a7796ad27..eac1a88ac 100644 --- a/test/client/spec/victory-core/victory-util/prop-types.spec.js +++ b/test/client/spec/victory-core/victory-util/prop-types.spec.js @@ -46,14 +46,18 @@ describe("victory-util/prop-types", () => { it("Should warn about deprecation and validate OK", () => { validate("value"); - shouldWarn('"pName" property of "ComponentName" has been deprecated Read more at link'); + shouldWarn( + '"pName" property of "ComponentName" has been deprecated Read more at link' + ); shouldNotError(); }); it(`Should warn about deprecation and throw validation error when property value is not OK`, () => { validate({}); - shouldWarn('"pName" property of "ComponentName" has been deprecated Read more at link'); + shouldWarn( + '"pName" property of "ComponentName" has been deprecated Read more at link' + ); shouldError( "Warning: Failed pName type: Invalid pName `pName` of type `object` supplied to " + "`ComponentName`, expected `string`." @@ -64,11 +68,10 @@ describe("victory-util/prop-types", () => { describe("allOfType", () => { const validate = function (prop) { - return CustomPropTypes.allOfType([CustomPropTypes.nonNegative, CustomPropTypes.integer])( - { testProp: prop }, - "testProp", - "TestComponent" - ); + return CustomPropTypes.allOfType([ + CustomPropTypes.nonNegative, + CustomPropTypes.integer + ])({ testProp: prop }, "testProp", "TestComponent"); }; it("returns an error if the first validator is false", () => { @@ -82,7 +85,9 @@ describe("victory-util/prop-types", () => { it("returns an error if the second validator is false", () => { const result = validate(1.3); expect(result).to.be.an.instanceOf(Error); - expect(result.message).contain("`testProp` in `TestComponent` must be an integer."); + expect(result.message).contain( + "`testProp` in `TestComponent` must be an integer." + ); }); it("does not return an error if both validators are true", () => { @@ -93,7 +98,11 @@ describe("victory-util/prop-types", () => { describe("nonNegative", () => { const validate = function (prop) { - return CustomPropTypes.nonNegative({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.nonNegative( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non numeric values", () => { @@ -125,19 +134,27 @@ describe("victory-util/prop-types", () => { describe("integer", () => { const validate = function (prop) { - return CustomPropTypes.integer({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.integer( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non numeric values", () => { const result = validate("a"); expect(result).to.be.an.instanceOf(Error); - expect(result.message).contain("`testProp` in `TestComponent` must be an integer."); + expect(result.message).contain( + "`testProp` in `TestComponent` must be an integer." + ); }); it("returns an error for non-integer numeric values", () => { const result = validate(2.4); expect(result).to.be.an.instanceOf(Error); - expect(result.message).to.contain("`testProp` in `TestComponent` must be an integer."); + expect(result.message).to.contain( + "`testProp` in `TestComponent` must be an integer." + ); }); it("does not return an error for integers", () => { @@ -152,7 +169,11 @@ describe("victory-util/prop-types", () => { describe("greaterThanZero", () => { const validate = function (prop) { - return CustomPropTypes.greaterThanZero({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.greaterThanZero( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non numeric values", () => { @@ -191,7 +212,11 @@ describe("victory-util/prop-types", () => { describe("domain", () => { const validate = function (prop) { - return CustomPropTypes.domain({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.domain( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non array values", () => { @@ -236,13 +261,19 @@ describe("victory-util/prop-types", () => { describe("scale", () => { const validate = function (prop) { - return CustomPropTypes.scale({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.scale( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non function values", () => { const result = validate("a"); expect(result).to.be.an.instanceOf(Error); - expect(result.message).contain("`testProp` in `TestComponent` must be a d3 scale."); + expect(result.message).contain( + "`testProp` in `TestComponent` must be a d3 scale." + ); }); it("returns an error when the function does not have a domain, range, and copy methods", () => { @@ -251,7 +282,9 @@ describe("victory-util/prop-types", () => { }; const result = validate(testFunc); expect(result).to.be.an.instanceOf(Error); - expect(result.message).contain("`testProp` in `TestComponent` must be a d3 scale."); + expect(result.message).contain( + "`testProp` in `TestComponent` must be a d3 scale." + ); }); it.skip("does not return an error when the function is a d3 scale", () => { @@ -263,13 +296,19 @@ describe("victory-util/prop-types", () => { describe("homogeneousArray", () => { const validate = function (prop) { - return CustomPropTypes.homogeneousArray({ testProp: prop }, "testProp", "TestComponent"); + return CustomPropTypes.homogeneousArray( + { testProp: prop }, + "testProp", + "TestComponent" + ); }; it("returns an error for non array values", () => { const result = validate("a"); expect(result).to.be.an.instanceOf(Error); - expect(result.message).contain("`testProp` in `TestComponent` must be an array."); + expect(result.message).contain( + "`testProp` in `TestComponent` must be an array." + ); }); it("returns an error when the array has elements of different types", () => { @@ -300,7 +339,11 @@ describe("victory-util/prop-types", () => { describe("matchDataLength", () => { const validate = function (prop, dataProp) { const props = { testProp: prop, data: dataProp }; - return CustomPropTypes.matchDataLength(props, "testProp", "TestComponent"); + return CustomPropTypes.matchDataLength( + props, + "testProp", + "TestComponent" + ); }; it("does not return an error when prop is undefined", () => { @@ -314,7 +357,10 @@ describe("victory-util/prop-types", () => { it("returns an error when prop doesn't have same length as data", () => { expect(validate([{}], [1, 2])) .to.be.an.instanceOf(Error) - .and.to.have.property("message", "Length of data and testProp arrays must match."); + .and.to.have.property( + "message", + "Length of data and testProp arrays must match." + ); }); }); }); diff --git a/test/client/spec/victory-core/victory-util/scale.spec.js b/test/client/spec/victory-core/victory-util/scale.spec.js index 824051b86..06295936f 100644 --- a/test/client/spec/victory-core/victory-util/scale.spec.js +++ b/test/client/spec/victory-core/victory-util/scale.spec.js @@ -92,7 +92,11 @@ describe("victory-util/scale", () => { }); it("returns 'time' when no scale is set, and data contains dates", () => { - const props = { x: "x", y: "y", data: [{ x: new Date("2016-01-13"), y: 1 }] }; + const props = { + x: "x", + y: "y", + data: [{ x: new Date("2016-01-13"), y: 1 }] + }; const scaleType = Scale.getScaleType(props, "x"); expect(scaleType).to.equal("time"); }); diff --git a/test/client/spec/victory-core/victory-util/style.spec.js b/test/client/spec/victory-core/victory-util/style.spec.js index 173bb95d9..5d6080a16 100644 --- a/test/client/spec/victory-core/victory-util/style.spec.js +++ b/test/client/spec/victory-core/victory-util/style.spec.js @@ -15,12 +15,14 @@ describe("toTransformString", () => { }); it("returns a string with two transform instructions when two objects are given", () => { - expect(Style.toTransformString({ rotate: [45, 0, 1] }, { skewY: [65] })).to.equal( - "rotate(45,0,1) skewY(65)" - ); + expect( + Style.toTransformString({ rotate: [45, 0, 1] }, { skewY: [65] }) + ).to.equal("rotate(45,0,1) skewY(65)"); }); it("returns at least the subsequent transforms if the first is undefined", () => { - expect(Style.toTransformString(undefined, { skewY: [65] })).to.equal("skewY(65)"); + expect(Style.toTransformString(undefined, { skewY: [65] })).to.equal( + "skewY(65)" + ); }); }); diff --git a/test/client/spec/victory-core/victory-util/textsize.spec.js b/test/client/spec/victory-core/victory-util/textsize.spec.js index 7cf7be225..848659ba9 100644 --- a/test/client/spec/victory-core/victory-util/textsize.spec.js +++ b/test/client/spec/victory-core/victory-util/textsize.spec.js @@ -22,23 +22,32 @@ describe("victory-util/textsize", () => { }); it("return correct width with signed angle", () => { expect( - TextSize.approximateTextSize(testString, { angle: -45, fontSize: 14 }).width.toFixed(2) + TextSize.approximateTextSize(testString, { + angle: -45, + fontSize: 14 + }).width.toFixed(2) ).to.be.eql("31.71"); }); it("return correct width with pixel fontsize", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: "14px" }).width.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: "14px" + }).width.toFixed(2) ).to.be.eql("28.74"); }); it("return appropriate width with defined fontSize", () => { - expect(TextSize.approximateTextSize(testString, { fontSize: 12 }).width.toFixed(2)).to.be.eql( - "24.64" - ); + expect( + TextSize.approximateTextSize(testString, { + fontSize: 12 + }).width.toFixed(2) + ).to.be.eql("24.64"); }); it("consider font", () => { - expect(TextSize.approximateTextSize(testString, { fontSize: 16 }).width.toFixed(2)).to.be.eql( - "32.85" - ); + expect( + TextSize.approximateTextSize(testString, { + fontSize: 16 + }).width.toFixed(2) + ).to.be.eql("32.85"); }); it("consider letterSpacing", () => { expect( @@ -50,12 +59,18 @@ describe("victory-util/textsize", () => { }); it("consider angle", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 12, angle: 30 }).width.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 12, + angle: 30 + }).width.toFixed(2) ).to.be.eql("28.24"); }); it("not consider lineHeight without angle", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 12, lineHeight: 2 }).width.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 12, + lineHeight: 2 + }).width.toFixed(2) ).to.eql("24.64"); }); it("consider lineHeight with angle", () => { @@ -69,13 +84,17 @@ describe("victory-util/textsize", () => { }); it("return width of widest string in text", () => { expect( - TextSize.approximateTextSize("ABC\nDEFGH\nIJK", { fontSize: 12 }).width.toFixed(2) + TextSize.approximateTextSize("ABC\nDEFGH\nIJK", { + fontSize: 12 + }).width.toFixed(2) ).to.eql("41.94"); }); it("returns width of widest string in array if array has an empty string", () => { expect( - TextSize.approximateTextSize(["06-14-20", ""], { fontSize: 12 }).width.toFixed(2) + TextSize.approximateTextSize(["06-14-20", ""], { + fontSize: 12 + }).width.toFixed(2) ).to.eql("47.93"); }); }); @@ -86,27 +105,39 @@ describe("victory-util/textsize", () => { }); it("return correct height with signed angle", () => { expect( - TextSize.approximateTextSize(testString, { angle: -45, fontSize: 14 }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + angle: -45, + fontSize: 14 + }).height.toFixed(2) ).to.be.eql("33.29"); }); it("return correct height with pixel fontsize", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: "14px" }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: "14px" + }).height.toFixed(2) ).to.be.eql("16.90"); }); it("return appropriate height with expected precision", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 12 }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 12 + }).height.toFixed(2) ).to.be.eql("14.49"); }); it("consider font", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 16 }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 16 + }).height.toFixed(2) ).to.be.eql("19.32"); }); it("consider angle", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 12, angle: 30 }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 12, + angle: 30 + }).height.toFixed(2) ).to.be.eql("25.48"); }); it("not consider letterSpacing without angle", () => { @@ -128,12 +159,17 @@ describe("victory-util/textsize", () => { }); it("consider lineHeight", () => { expect( - TextSize.approximateTextSize(testString, { fontSize: 12, lineHeight: 2 }).height.toFixed(2) + TextSize.approximateTextSize(testString, { + fontSize: 12, + lineHeight: 2 + }).height.toFixed(2) ).to.be.eql("28.98"); }); it("consider multiLines text", () => { expect( - TextSize.approximateTextSize(`ABC\n${"DBCDEFG"}\n123`, { fontSize: 12 }).height.toFixed(2) + TextSize.approximateTextSize(`ABC\n${"DBCDEFG"}\n123`, { + fontSize: 12 + }).height.toFixed(2) ).to.be.eql("43.47"); }); }); diff --git a/test/client/spec/victory-core/victory-util/transitions.spec.js b/test/client/spec/victory-core/victory-util/transitions.spec.js index f6c8e5b1a..0aeab8978 100644 --- a/test/client/spec/victory-core/victory-util/transitions.spec.js +++ b/test/client/spec/victory-core/victory-util/transitions.spec.js @@ -88,7 +88,11 @@ describe("getTransitionPropsFactory", () => { nodesShouldLoad: true, nodesDoneLoad: true }; - const result = Transitions.getTransitionPropsFactory({}, exitingState, callback); + const result = Transitions.getTransitionPropsFactory( + {}, + exitingState, + callback + ); const child = makeChild([ { x: 1, y: 1 }, { x: 2, y: 3 } @@ -101,7 +105,9 @@ describe("getTransitionPropsFactory", () => { { x: 1, y: 1 }, { x: 2, y: 0 } ]); - expect(calledResult.animate.duration).to.equal(child.type.defaultTransitions.onExit.duration); + expect(calledResult.animate.duration).to.equal( + child.type.defaultTransitions.onExit.duration + ); }); it("returns a function that describes data entering", () => { @@ -113,7 +119,11 @@ describe("getTransitionPropsFactory", () => { nodesShouldLoad: true, nodesDoneLoad: true }; - const result = Transitions.getTransitionPropsFactory({}, enteringState, callback); + const result = Transitions.getTransitionPropsFactory( + {}, + enteringState, + callback + ); const child = makeChild([ { x: 1, y: 1 }, { x: 2, y: 3 } diff --git a/test/client/spec/victory-errorbars/victory-errorbars.spec.js b/test/client/spec/victory-errorbars/victory-errorbars.spec.js index 7385bec03..76c9b0bfa 100644 --- a/test/client/spec/victory-errorbars/victory-errorbars.spec.js +++ b/test/client/spec/victory-errorbars/victory-errorbars.spec.js @@ -58,692 +58,918 @@ describe("components/victory-errorbar", () => { testLabel: "with js data" }; - [renderDataTest, immutableRenderDataTest].forEach(({ createData, testLabel }) => { - describe(`symmetric error, rendering data ${testLabel}`, () => { - it("renders injected errors for {x, y}", () => { - const data = createData(range(10).map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 }))); - const wrapper = shallow(} />); - - const errors = wrapper.find(MyErrorBar); - expect(errors.length).to.equal(10); - }); - - it("renders errors for {x, y}", () => { - const data = createData(range(10).map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 }))); - const wrapper = shallow(); - const errors = wrapper.find(ErrorBar); - expect(errors.length).to.equal(10); - }); - - it("sorts data by sortKey prop", () => { - const data = createData( - range(5) - .map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) - .reverse() - ); - const wrapper = shallow(); - const xValues = wrapper.find(ErrorBar).map((errorBar) => errorBar.prop("datum")._x); - expect(xValues).to.eql([0, 1, 2, 3, 4]); - }); - - it("reversed sorted data with the sortOrder prop", () => { - const data = createData( - range(5) - .map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) - .reverse() - ); - const wrapper = shallow(); - const xValues = wrapper.find(ErrorBar).map((errorBar) => errorBar.prop("datum")._x); - expect(xValues).to.eql([4, 3, 2, 1, 0]); - }); - - it("renders errors with error bars, check total svg lines", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const wrapper = mount( - - ); - expect(wrapper.find(Line)).to.have.length(24); - }); - - it("should check right border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount( - - ); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x + data[i].errorX); - const xScaleMax = xScale.range()[1]; - const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; - // right border - const rightBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-right") !== -1); - expect(rightBorder.props().x1).to.equal(positiveErrorX); - expect(rightBorder.props().x2).to.equal(positiveErrorX); - expect(rightBorder.props().y1).to.equal(yScale(data[i].y) - borderWidth); - expect(rightBorder.props().y2).to.equal(yScale(data[i].y) + borderWidth); + [renderDataTest, immutableRenderDataTest].forEach( + ({ createData, testLabel }) => { + describe(`symmetric error, rendering data ${testLabel}`, () => { + it("renders injected errors for {x, y}", () => { + const data = createData( + range(10).map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) + ); + const wrapper = shallow( + } /> + ); + + const errors = wrapper.find(MyErrorBar); + expect(errors.length).to.equal(10); }); - }); - it("should check left border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount( - - ); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x - data[i].errorX); - const xScaleMin = xScale.range()[0]; - const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; - - // left border - const leftBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-left") !== -1); - expect(leftBorder.props().x1).to.equal(negativeErrorX); - expect(leftBorder.props().x2).to.equal(negativeErrorX); - expect(leftBorder.props().y1).to.equal(yScale(data[i].y) - borderWidth); - expect(leftBorder.props().y2).to.equal(yScale(data[i].y) + borderWidth); + it("renders errors for {x, y}", () => { + const data = createData( + range(10).map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) + ); + const wrapper = shallow(); + const errors = wrapper.find(ErrorBar); + expect(errors.length).to.equal(10); }); - }); - it("should check bottom border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount( - - ); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y + data[i].errorY); - const yScaleMin = yScale.range()[1]; - const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; - - // bottom border - const bottomBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-bottom") !== -1); - expect(bottomBorder.props().x1).to.equal(xScale(data[i].x) - borderWidth); - expect(bottomBorder.props().x2).to.equal(xScale(data[i].x) + borderWidth); - expect(bottomBorder.props().y1).to.equal(negativeErrorY); - expect(bottomBorder.props().y2).to.equal(negativeErrorY); + it("sorts data by sortKey prop", () => { + const data = createData( + range(5) + .map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) + .reverse() + ); + const wrapper = shallow(); + const xValues = wrapper + .find(ErrorBar) + .map((errorBar) => errorBar.prop("datum")._x); + expect(xValues).to.eql([0, 1, 2, 3, 4]); }); - }); - it("should check top border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount( - - ); + it("reversed sorted data with the sortOrder prop", () => { + const data = createData( + range(5) + .map((i) => ({ x: i, y: i, errorX: 0.1, errorY: 0.2 })) + .reverse() + ); + const wrapper = shallow( + + ); + const xValues = wrapper + .find(ErrorBar) + .map((errorBar) => errorBar.prop("datum")._x); + expect(xValues).to.eql([4, 3, 2, 1, 0]); + }); - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y - data[i].errorY); - const yScaleMax = yScale.range()[0]; - const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; - - // top border - const topBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-top") !== -1); - expect(topBorder.props().x1).to.equal(xScale(data[i].x) - borderWidth); - expect(topBorder.props().x2).to.equal(xScale(data[i].x) + borderWidth); - expect(topBorder.props().y1).to.equal(positiveErrorY); - expect(topBorder.props().y2).to.equal(positiveErrorY); + it("renders errors with error bars, check total svg lines", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const wrapper = mount( + + ); + expect(wrapper.find(Line)).to.have.length(24); }); - }); - it("should check top cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y - data[i].errorY); - const yScaleMax = yScale.range()[0]; - const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; - - const topCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-top") !== -1); - expect(topCross.props().x1).to.equal(xScale(data[i].x)); - expect(topCross.props().x2).to.equal(xScale(data[i].x)); - expect(topCross.props().y1).to.equal(yScale(data[i].y)); - expect(topCross.props().y2).to.equal(positiveErrorY); + it("should check right border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x + data[i].errorX); + const xScaleMax = xScale.range()[1]; + const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; + // right border + const rightBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-right") !== -1 + ); + expect(rightBorder.props().x1).to.equal(positiveErrorX); + expect(rightBorder.props().x2).to.equal(positiveErrorX); + expect(rightBorder.props().y1).to.equal( + yScale(data[i].y) - borderWidth + ); + expect(rightBorder.props().y2).to.equal( + yScale(data[i].y) + borderWidth + ); + }); }); - }); - it("should check bottom cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y + data[i].errorY); - const yScaleMin = yScale.range()[1]; - const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; - - const bottomCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-bottom") !== -1); - expect(bottomCross.props().x1).to.equal(xScale(data[i].x)); - expect(bottomCross.props().x2).to.equal(xScale(data[i].x)); - expect(bottomCross.props().y1).to.equal(yScale(data[i].y)); - expect(bottomCross.props().y2).to.equal(negativeErrorY); + it("should check left border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x - data[i].errorX); + const xScaleMin = xScale.range()[0]; + const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; + + // left border + const leftBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-left") !== -1 + ); + expect(leftBorder.props().x1).to.equal(negativeErrorX); + expect(leftBorder.props().x2).to.equal(negativeErrorX); + expect(leftBorder.props().y1).to.equal( + yScale(data[i].y) - borderWidth + ); + expect(leftBorder.props().y2).to.equal( + yScale(data[i].y) + borderWidth + ); + }); }); - }); - it("should check left cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x - data[i].errorX); - const xScaleMin = xScale.range()[0]; - const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; - - const leftCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-left") !== -1); - expect(leftCross.props().x1).to.equal(xScale(data[i].x)); - expect(leftCross.props().x2).to.equal(negativeErrorX); - expect(leftCross.props().y1).to.equal(yScale(data[i].y)); - expect(leftCross.props().y2).to.equal(yScale(data[i].y)); + it("should check bottom border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y + data[i].errorY); + const yScaleMin = yScale.range()[1]; + const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; + + // bottom border + const bottomBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-bottom") !== -1 + ); + expect(bottomBorder.props().x1).to.equal( + xScale(data[i].x) - borderWidth + ); + expect(bottomBorder.props().x2).to.equal( + xScale(data[i].x) + borderWidth + ); + expect(bottomBorder.props().y1).to.equal(negativeErrorY); + expect(bottomBorder.props().y2).to.equal(negativeErrorY); + }); }); - }); - it("should check right cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, - { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, - { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.1, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.2, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].errorX + data[i].x); - const xScaleMax = xScale.range()[1]; - const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; - - const rightCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-right") !== -1); - expect(rightCross.props().x1).to.equal(xScale(data[i].x)); - expect(rightCross.props().x2).to.equal(positiveErrorX); - expect(rightCross.props().y1).to.equal(yScale(data[i].y)); - expect(rightCross.props().y2).to.equal(yScale(data[i].y)); + it("should check top border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y - data[i].errorY); + const yScaleMax = yScale.range()[0]; + const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; + + // top border + const topBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-top") !== -1 + ); + expect(topBorder.props().x1).to.equal( + xScale(data[i].x) - borderWidth + ); + expect(topBorder.props().x2).to.equal( + xScale(data[i].x) + borderWidth + ); + expect(topBorder.props().y1).to.equal(positiveErrorY); + expect(topBorder.props().y2).to.equal(positiveErrorY); + }); }); - }); - }); - describe(`asymmetric error, rendering data ${testLabel}`, () => { - it("renders injected errors for {x, y}", () => { - const data = createData( - range(10).map((i) => ({ x: i, y: i, errorX: [0.1, 0.2], errorY: [0.2, 0.5] })) - ); - const wrapper = shallow(} />); + it("should check top cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y - data[i].errorY); + const yScaleMax = yScale.range()[0]; + const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; + + const topCross = node + .find(Line) + .findWhere((n) => n.key() && n.key().indexOf("cross-top") !== -1); + expect(topCross.props().x1).to.equal(xScale(data[i].x)); + expect(topCross.props().x2).to.equal(xScale(data[i].x)); + expect(topCross.props().y1).to.equal(yScale(data[i].y)); + expect(topCross.props().y2).to.equal(positiveErrorY); + }); + }); - const errors = wrapper.find(MyErrorBar); - expect(errors.length).to.equal(10); - }); + it("should check bottom cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y + data[i].errorY); + const yScaleMin = yScale.range()[1]; + const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; + + const bottomCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-bottom") !== -1 + ); + expect(bottomCross.props().x1).to.equal(xScale(data[i].x)); + expect(bottomCross.props().x2).to.equal(xScale(data[i].x)); + expect(bottomCross.props().y1).to.equal(yScale(data[i].y)); + expect(bottomCross.props().y2).to.equal(negativeErrorY); + }); + }); - it("renders errors for {x, y}", () => { - const data = createData( - range(10).map((i) => ({ x: i, y: i, errorX: [0.1, 0.2], errorY: [0.2, 1] })) - ); - const wrapper = shallow(); - const errors = wrapper.find(ErrorBar); - expect(errors.length).to.equal(10); - }); + it("should check left cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x - data[i].errorX); + const xScaleMin = xScale.range()[0]; + const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; + + const leftCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-left") !== -1 + ); + expect(leftCross.props().x1).to.equal(xScale(data[i].x)); + expect(leftCross.props().x2).to.equal(negativeErrorX); + expect(leftCross.props().y1).to.equal(yScale(data[i].y)); + expect(leftCross.props().y2).to.equal(yScale(data[i].y)); + }); + }); - it("renders errors with error bars, check total svg lines", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const wrapper = mount( - - ); - expect(wrapper.find(Line)).to.have.length(24); + it("should check right cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: 0.1, errorY: 0.2 }, + { x: 2, y: 3, errorX: 0.1, errorY: 0.2 }, + { x: 5, y: 5, errorX: 0.1, errorY: 0.2 } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.1, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.2, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].errorX + data[i].x); + const xScaleMax = xScale.range()[1]; + const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; + + const rightCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-right") !== -1 + ); + expect(rightCross.props().x1).to.equal(xScale(data[i].x)); + expect(rightCross.props().x2).to.equal(positiveErrorX); + expect(rightCross.props().y1).to.equal(yScale(data[i].y)); + expect(rightCross.props().y2).to.equal(yScale(data[i].y)); + }); + }); }); - it("should check right border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount( - - ); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x + data[i].errorX[0]); - const xScaleMax = xScale.range()[1]; - const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; - - // right border - const rightBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-right") !== -1); - expect(rightBorder.props().x1).to.equal(positiveErrorX); - expect(rightBorder.props().x2).to.equal(positiveErrorX); - expect(rightBorder.props().y1).to.equal(yScale(data[i].y) - borderWidth); - expect(rightBorder.props().y2).to.equal(yScale(data[i].y) + borderWidth); + describe(`asymmetric error, rendering data ${testLabel}`, () => { + it("renders injected errors for {x, y}", () => { + const data = createData( + range(10).map((i) => ({ + x: i, + y: i, + errorX: [0.1, 0.2], + errorY: [0.2, 0.5] + })) + ); + const wrapper = shallow( + } /> + ); + + const errors = wrapper.find(MyErrorBar); + expect(errors.length).to.equal(10); }); - }); - it("should check left border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount( - - ); + it("renders errors for {x, y}", () => { + const data = createData( + range(10).map((i) => ({ + x: i, + y: i, + errorX: [0.1, 0.2], + errorY: [0.2, 1] + })) + ); + const wrapper = shallow(); + const errors = wrapper.find(ErrorBar); + expect(errors.length).to.equal(10); + }); - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x - data[i].errorX[1]); - const xScaleMin = xScale.range()[0]; - const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; - - // left border - const leftBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-left") !== -1); - expect(leftBorder.props().x1).to.equal(negativeErrorX); - expect(leftBorder.props().x2).to.equal(negativeErrorX); - expect(leftBorder.props().y1).to.equal(yScale(data[i].y) - borderWidth); - expect(leftBorder.props().y2).to.equal(yScale(data[i].y) + borderWidth); + it("renders errors with error bars, check total svg lines", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const wrapper = mount( + + ); + expect(wrapper.find(Line)).to.have.length(24); }); - }); - it("should check bottom border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount( - - ); + it("should check right border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x + data[i].errorX[0]); + const xScaleMax = xScale.range()[1]; + const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; + + // right border + const rightBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-right") !== -1 + ); + expect(rightBorder.props().x1).to.equal(positiveErrorX); + expect(rightBorder.props().x2).to.equal(positiveErrorX); + expect(rightBorder.props().y1).to.equal( + yScale(data[i].y) - borderWidth + ); + expect(rightBorder.props().y2).to.equal( + yScale(data[i].y) + borderWidth + ); + }); + }); - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y + data[i].errorY[0]); - const yScaleMin = yScale.range()[1]; - const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; - - // bottom border - const bottomBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-bottom") !== -1); - expect(bottomBorder.props().x1).to.equal(xScale(data[i].x) - borderWidth); - expect(bottomBorder.props().x2).to.equal(xScale(data[i].x) + borderWidth); - expect(bottomBorder.props().y1).to.equal(negativeErrorY); - expect(bottomBorder.props().y2).to.equal(negativeErrorY); + it("should check left border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x - data[i].errorX[1]); + const xScaleMin = xScale.range()[0]; + const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; + + // left border + const leftBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-left") !== -1 + ); + expect(leftBorder.props().x1).to.equal(negativeErrorX); + expect(leftBorder.props().x2).to.equal(negativeErrorX); + expect(leftBorder.props().y1).to.equal( + yScale(data[i].y) - borderWidth + ); + expect(leftBorder.props().y2).to.equal( + yScale(data[i].y) + borderWidth + ); + }); }); - }); - it("should check top border of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const borderWidth = 10; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount( - - ); + it("should check bottom border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y + data[i].errorY[0]); + const yScaleMin = yScale.range()[1]; + const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; + + // bottom border + const bottomBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-bottom") !== -1 + ); + expect(bottomBorder.props().x1).to.equal( + xScale(data[i].x) - borderWidth + ); + expect(bottomBorder.props().x2).to.equal( + xScale(data[i].x) + borderWidth + ); + expect(bottomBorder.props().y1).to.equal(negativeErrorY); + expect(bottomBorder.props().y2).to.equal(negativeErrorY); + }); + }); - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y - data[i].errorY[1]); - const yScaleMax = yScale.range()[0]; - const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; - - const topBorder = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("border-top") !== -1); - expect(topBorder.props().x1).to.equal(xScale(data[i].x) - borderWidth); - expect(topBorder.props().x2).to.equal(xScale(data[i].x) + borderWidth); - expect(topBorder.props().y1).to.equal(positiveErrorY); - expect(topBorder.props().y2).to.equal(positiveErrorY); + it("should check top border of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const borderWidth = 10; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y - data[i].errorY[1]); + const yScaleMax = yScale.range()[0]; + const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; + + const topBorder = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("border-top") !== -1 + ); + expect(topBorder.props().x1).to.equal( + xScale(data[i].x) - borderWidth + ); + expect(topBorder.props().x2).to.equal( + xScale(data[i].x) + borderWidth + ); + expect(topBorder.props().y1).to.equal(positiveErrorY); + expect(topBorder.props().y2).to.equal(positiveErrorY); + }); }); - }); - it("should check top cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y - data[i].errorY[1]); - const yScaleMax = yScale.range()[0]; - const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; - - const topCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-top") !== -1); - expect(topCross.props().x1).to.equal(xScale(data[i].x)); - expect(topCross.props().x2).to.equal(xScale(data[i].x)); - expect(topCross.props().y1).to.equal(yScale(data[i].y)); - expect(topCross.props().y2).to.equal(positiveErrorY); + it("should check top cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y - data[i].errorY[1]); + const yScaleMax = yScale.range()[0]; + const positiveErrorY = errorY >= yScaleMax ? yScaleMax : errorY; + + const topCross = node + .find(Line) + .findWhere((n) => n.key() && n.key().indexOf("cross-top") !== -1); + expect(topCross.props().x1).to.equal(xScale(data[i].x)); + expect(topCross.props().x2).to.equal(xScale(data[i].x)); + expect(topCross.props().y1).to.equal(yScale(data[i].y)); + expect(topCross.props().y2).to.equal(positiveErrorY); + }); }); - }); - it("should check bottom cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorY = yScale(data[i].y + data[i].errorY[0]); - const yScaleMin = yScale.range()[1]; - const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; - - const bottomCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-bottom") !== -1); - expect(bottomCross.props().x1).to.equal(xScale(data[i].x)); - expect(bottomCross.props().x2).to.equal(xScale(data[i].x)); - expect(bottomCross.props().y1).to.equal(yScale(data[i].y)); - expect(bottomCross.props().y2).to.equal(negativeErrorY); + it("should check bottom cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorY = yScale(data[i].y + data[i].errorY[0]); + const yScaleMin = yScale.range()[1]; + const negativeErrorY = errorY <= yScaleMin ? yScaleMin : errorY; + + const bottomCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-bottom") !== -1 + ); + expect(bottomCross.props().x1).to.equal(xScale(data[i].x)); + expect(bottomCross.props().x2).to.equal(xScale(data[i].x)); + expect(bottomCross.props().y1).to.equal(yScale(data[i].y)); + expect(bottomCross.props().y2).to.equal(negativeErrorY); + }); }); - }); - it("should check left cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x - data[i].errorX[1]); - const xScaleMin = xScale.range()[0]; - const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; - - const leftCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-left") !== -1); - expect(leftCross.props().x1).to.equal(xScale(data[i].x)); - expect(leftCross.props().x2).to.equal(negativeErrorX); - expect(leftCross.props().y1).to.equal(yScale(data[i].y)); - expect(leftCross.props().y2).to.equal(yScale(data[i].y)); + it("should check left cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x - data[i].errorX[1]); + const xScaleMin = xScale.range()[0]; + const negativeErrorX = errorX <= xScaleMin ? xScaleMin : errorX; + + const leftCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-left") !== -1 + ); + expect(leftCross.props().x1).to.equal(xScale(data[i].x)); + expect(leftCross.props().x2).to.equal(negativeErrorX); + expect(leftCross.props().y1).to.equal(yScale(data[i].y)); + expect(leftCross.props().y2).to.equal(yScale(data[i].y)); + }); }); - }); - it("should check right cross line of error bars positions", () => { - const svgDimensions = { width: 350, height: 200, padding: 75 }; - const data = [ - { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, - { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, - { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } - ]; - const wrapper = mount(); - - const xScale = d3Scale - .scaleLinear() - .domain([-0.3, 5.1]) - .range([svgDimensions.padding, svgDimensions.width - svgDimensions.padding]); - - const yScale = d3Scale - .scaleLinear() - .domain([-0.5, 5.2]) - .range([svgDimensions.height - svgDimensions.padding, svgDimensions.padding]); - - const Data = wrapper.find(ErrorBar); - Data.forEach((node, i) => { - const errorX = xScale(data[i].x + data[i].errorX[0]); - const xScaleMax = xScale.range()[1]; - const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; - - const rightCross = node - .find(Line) - .findWhere((n) => n.key() && n.key().indexOf("cross-right") !== -1); - expect(rightCross.props().x1).to.equal(xScale(data[i].x)); - expect(rightCross.props().x2).to.equal(positiveErrorX); - expect(rightCross.props().y1).to.equal(yScale(data[i].y)); - expect(rightCross.props().y2).to.equal(yScale(data[i].y)); + it("should check right cross line of error bars positions", () => { + const svgDimensions = { width: 350, height: 200, padding: 75 }; + const data = [ + { x: 0, y: 0, errorX: [0.1, 0.3], errorY: [0.2, 0.5] }, + { x: 2, y: 3, errorX: [0.1, 0.2], errorY: [0.2, 0.3] }, + { x: 5, y: 5, errorX: [0.1, 0.6], errorY: [0.2, 0.1] } + ]; + const wrapper = mount( + + ); + + const xScale = d3Scale + .scaleLinear() + .domain([-0.3, 5.1]) + .range([ + svgDimensions.padding, + svgDimensions.width - svgDimensions.padding + ]); + + const yScale = d3Scale + .scaleLinear() + .domain([-0.5, 5.2]) + .range([ + svgDimensions.height - svgDimensions.padding, + svgDimensions.padding + ]); + + const Data = wrapper.find(ErrorBar); + Data.forEach((node, i) => { + const errorX = xScale(data[i].x + data[i].errorX[0]); + const xScaleMax = xScale.range()[1]; + const positiveErrorX = errorX >= xScaleMax ? xScaleMax : errorX; + + const rightCross = node + .find(Line) + .findWhere( + (n) => n.key() && n.key().indexOf("cross-right") !== -1 + ); + expect(rightCross.props().x1).to.equal(xScale(data[i].x)); + expect(rightCross.props().x2).to.equal(positiveErrorX); + expect(rightCross.props().y1).to.equal(yScale(data[i].y)); + expect(rightCross.props().y2).to.equal(yScale(data[i].y)); + }); }); }); - }); - }); + } + ); describe("event handling", () => { it("attaches an event to the parent svg", () => { @@ -762,7 +988,13 @@ describe("components/victory-errorbar", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data, click border lines", () => { @@ -841,7 +1073,9 @@ describe("components/victory-errorbar", () => { .find("g") .slice(1) .forEach((g, i) => { - expect(g.prop("aria-label")).to.equal(`error bar chart, x ${data[i].x}`); + expect(g.prop("aria-label")).to.equal( + `error bar chart, x ${data[i].x}` + ); expect(g.prop("tabIndex")).to.equal(i + 2); }); }); diff --git a/test/client/spec/victory-histogram/victory-histogram.spec.js b/test/client/spec/victory-histogram/victory-histogram.spec.js index e1e2d756c..47526ec54 100644 --- a/test/client/spec/victory-histogram/victory-histogram.spec.js +++ b/test/client/spec/victory-histogram/victory-histogram.spec.js @@ -63,9 +63,13 @@ describe("components/victory-histogram", () => { it("renders 2 bars of equal height", () => { const data = [{ x: 2 }, { x: 3 }]; - const wrapper = mount(); + const wrapper = mount( + + ); const bars = wrapper.find("Bar"); - const heights = bars.map(SvgTestHelper.getBarHeight).map((n) => parseInt(n)); + const heights = bars + .map(SvgTestHelper.getBarHeight) + .map((n) => parseInt(n)); expect(bars.length).to.equal(2); expect(heights[0]).to.equal(heights[1]); @@ -74,7 +78,9 @@ describe("components/victory-histogram", () => { it("renders bars values with null accessor", () => { const data = range(30); - const wrapper = shallow(); + const wrapper = shallow( + + ); const bars = wrapper.find("Bar"); expect(bars.length).to.be.greaterThan(0); }); @@ -111,7 +117,13 @@ describe("components/victory-histogram", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -166,7 +178,9 @@ describe("components/victory-histogram", () => { node.childAt(0).simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(typeof clickHandler.args[index][1].text === "function").to.eql(true); + expect(typeof clickHandler.args[index][1].text === "function").to.eql( + true + ); expect(`${clickHandler.args[index][2]}`).to.eql(`${index}`); }); }); diff --git a/test/client/spec/victory-legend/victory-legend.spec.js b/test/client/spec/victory-legend/victory-legend.spec.js index 40cb3ba58..69d02754c 100644 --- a/test/client/spec/victory-legend/victory-legend.spec.js +++ b/test/client/spec/victory-legend/victory-legend.spec.js @@ -33,7 +33,9 @@ describe("components/victory-legend", () => { }); it("has expected horizontal symbol position", () => { - const wrappedLegend = shallow(); + const wrappedLegend = shallow( + + ); const output = wrappedLegend.find("Point"); expect(output.at(0).prop("x")).to.equal(14); @@ -43,7 +45,9 @@ describe("components/victory-legend", () => { }); it("has expected vertical symbol position", () => { - const wrappedLegend = shallow(); + const wrappedLegend = shallow( + + ); const output = wrappedLegend.find("Point"); expect(output.at(0).prop("x")).to.equal(14); @@ -53,7 +57,9 @@ describe("components/victory-legend", () => { }); it("has expected horizontal legend labels position", () => { - const wrappedLegend = render(); + const wrappedLegend = render( + + ); const output = wrappedLegend.find("text"); expect(output.eq(0).prop("x")).to.equal("30.8"); @@ -63,7 +69,9 @@ describe("components/victory-legend", () => { }); it("has expected vertical legend labels position", () => { - const wrappedLegend = render(); + const wrappedLegend = render( + + ); const output = wrappedLegend.find("text"); expect(output.eq(0).prop("x")).to.equal("30.8"); @@ -192,12 +200,18 @@ describe("components/victory-legend", () => { // columns are the same distance apart expect(outputPoints.get(0).props.x - outputPoints.get(3).props.x) .to.equal(outputPoints.get(1).props.x - outputPoints.get(4).props.x) - .and.to.equal(outputPoints.get(2).props.x - outputPoints.get(5).props.x); + .and.to.equal( + outputPoints.get(2).props.x - outputPoints.get(5).props.x + ); }); it("displays items in rows", () => { wrapper = shallow( - + ); const outputLabels = wrapper.find("VictoryLabel"); const outputPoints = wrapper.find("Point"); @@ -213,7 +227,9 @@ describe("components/victory-legend", () => { // rows are the same distance apart expect(outputPoints.get(0).props.y - outputPoints.get(3).props.y) .to.equal(outputPoints.get(1).props.y - outputPoints.get(4).props.y) - .and.to.equal(outputPoints.get(2).props.y - outputPoints.get(5).props.y); + .and.to.equal( + outputPoints.get(2).props.y - outputPoints.get(5).props.y + ); }); }); }); diff --git a/test/client/spec/victory-line/victory-line.spec.js b/test/client/spec/victory-line/victory-line.spec.js index 33bbc8581..6ba451d02 100644 --- a/test/client/spec/victory-line/victory-line.spec.js +++ b/test/client/spec/victory-line/victory-line.spec.js @@ -45,7 +45,9 @@ describe("components/victory-line", () => { { x: 6, y: 4 }, { x: 7, y: 6 } ]; - const wrapper = shallow(} />); + const wrapper = shallow( + } /> + ); const lines = wrapper.find(MyLineSegment); expect(lines.length).to.equal(1); @@ -96,7 +98,9 @@ describe("components/victory-line", () => { { x: 2, y: 2 } ] }; - const stringWrapper = mount(); + const stringWrapper = mount( + + ); const stringLine = stringWrapper.find(Curve); const stringPath = stringLine.find("path").prop("d"); SvgTestHelper.expectCorrectD3Path( @@ -105,7 +109,9 @@ describe("components/victory-line", () => { "line" ); - const functionWrapper = mount(); + const functionWrapper = mount( + + ); const functionLine = functionWrapper.find(Curve); const functionPath = functionLine.find("path").prop("d"); SvgTestHelper.expectCorrectD3Path( @@ -137,15 +143,22 @@ describe("components/victory-line", () => { }); it("renders deeply nested data", () => { - const data = [{ a: { b: [{ x: 1, y: 2 }] } }, { a: { b: [{ x: 3, y: 4 }] } }]; - const wrapper = shallow(); + const data = [ + { a: { b: [{ x: 1, y: 2 }] } }, + { a: { b: [{ x: 3, y: 4 }] } } + ]; + const wrapper = shallow( + + ); const lines = wrapper.find(Curve); expect(lines.length).to.equal(1); }); it("renders data ordered by x-value, by default", () => { const data = [{ t: 0 /*x: 10, y: 1*/ }, { t: 1 /*x: 9, y: 1*/ }]; - const wrapper = shallow( 10 - t} y={() => 1} />); + const wrapper = shallow( + 10 - t} y={() => 1} /> + ); const lines = wrapper.find(Curve); expect(lines.props().data[0].t).to.equal(1); @@ -155,7 +168,12 @@ describe("components/victory-line", () => { it("renders data ordered by value of sortKey, if given", () => { const data = [{ t: 0 /*x: 10, y: 1*/ }, { t: 1 /*x: 9, y: 1*/ }]; const wrapper = shallow( - 10 - t} y={() => 1} /> + 10 - t} + y={() => 1} + /> ); const lines = wrapper.find(Curve); @@ -201,7 +219,13 @@ describe("components/victory-line", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -287,7 +311,9 @@ describe("components/victory-line", () => { data={ariaTestData} dataComponent={ `data point ${data[2].x + 1}'s x value is ${data[2].x}`} + ariaLabel={({ data }) => + `data point ${data[2].x + 1}'s x value is ${data[2].x}` + } tabIndex={3} /> } diff --git a/test/client/spec/victory-pie/victory-pie.spec.js b/test/client/spec/victory-pie/victory-pie.spec.js index 501ec7788..ef33c1473 100644 --- a/test/client/spec/victory-pie/victory-pie.spec.js +++ b/test/client/spec/victory-pie/victory-pie.spec.js @@ -67,7 +67,9 @@ describe("components/victory-pie", () => { describe("rendering data", () => { it("renders dataComponents for {x, y} shaped data (default)", () => { const data = range(5).map((i) => ({ x: i, y: i })); - const wrapper = shallow(} />); + const wrapper = shallow( + } /> + ); const slices = wrapper.find(PizzaSlice); expect(slices.length).to.equal(5); }); @@ -88,7 +90,9 @@ describe("components/victory-pie", () => { it("renders points for deeply-nested data", () => { const data = range(7).map((i) => ({ a: { b: [{ x: i, y: i }] } })); - const wrapper = shallow(); + const wrapper = shallow( + + ); const slices = wrapper.find(Slice); expect(slices.length).to.equal(7); }); @@ -127,7 +131,9 @@ describe("components/victory-pie", () => { it("renders data values sorted by sortKey prop and sortOrder", () => { const data = range(9).map((i) => ({ x: i, y: i })); - const wrapper = shallow(); + const wrapper = shallow( + + ); const xValues = wrapper.find(Slice).map((slice) => { return slice.prop("datum")._x; }); @@ -153,7 +159,8 @@ describe("components/victory-pie", () => { const firstSlice = wrapper.find(Slice).first(); const coordinates = SvgTestHelper.getSliceArcStart(firstSlice); - const renderedAngle = SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(coordinates); + const renderedAngle = + SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(coordinates); // There is a small degree of inprecision due to how D3 renders the paths expect(renderedAngle).to.be.closeTo(angle, 0.0001); @@ -174,7 +181,9 @@ describe("components/victory-pie", () => { const slices = wrapper.find(Slice); slices.forEach((slice) => { - expect(SvgTestHelper.getInnerRadiusOfCircularOrAnnularSlice(slice)).to.eql(70); + expect( + SvgTestHelper.getInnerRadiusOfCircularOrAnnularSlice(slice) + ).to.eql(70); }); }); }); @@ -189,8 +198,12 @@ describe("components/victory-pie", () => { const arcStart = SvgTestHelper.getSliceArcStart(firstSlice); const arcEnd = SvgTestHelper.getSliceArcEnd(lastSlice); - expect(SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(arcStart)).to.eql(270); - expect(SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(arcEnd)).to.eql(90); + expect( + SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(arcStart) + ).to.eql(270); + expect( + SvgTestHelper.getSvgCoordinatesAngleFromCartesianYAxis(arcEnd) + ).to.eql(90); }); }); @@ -217,7 +230,9 @@ describe("components/victory-pie", () => { it("renders each slice with the next color in the array, reiterating through colors as necessary", () => { const data = range(5); const colorScale = ["#fffff", "#eeeee", "#ddddd"]; - const wrapper = shallow(); + const wrapper = shallow( + + ); const slices = wrapper.find(Slice); expect(slices.length).to.equal(5); @@ -245,7 +260,9 @@ describe("components/victory-pie", () => { VALID_VICTORY_COLOR_SCALE_NAMES.map((colorScaleName) => { const colorScale = Style.getColorScale(colorScaleName); const data = range(colorScale.length + 1); - const wrapper = shallow(); + const wrapper = shallow( + + ); wrapper.find(Slice).map((slice, i) => { const expectedColor = colorScale[i % colorScale.length]; @@ -263,7 +280,9 @@ describe("components/victory-pie", () => { const grayscale = Style.getColorScale("grayscale"); const data = range(grayscale.length); - const wrapper = shallow(); + const wrapper = shallow( + + ); const slices = wrapper.find(Slice); slices.map((slice, i) => { @@ -293,7 +312,12 @@ describe("components/victory-pie", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("slices", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "slices", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -356,7 +380,10 @@ describe("components/victory-pie", () => { `${datum.x}`} tabIndex={({ index }) => index + 5} /> + `${datum.x}`} + tabIndex={({ index }) => index + 5} + /> } /> ); diff --git a/test/client/spec/victory-scatter/helper-methods.spec.js b/test/client/spec/victory-scatter/helper-methods.spec.js index 0a9d10845..6ed64c6fb 100644 --- a/test/client/spec/victory-scatter/helper-methods.spec.js +++ b/test/client/spec/victory-scatter/helper-methods.spec.js @@ -1,6 +1,10 @@ /* eslint no-unused-expressions: 0 */ /* global sinon */ -import { getSize, getBubbleSize, getSymbol } from "packages/victory-scatter/src/helper-methods"; +import { + getSize, + getBubbleSize, + getSymbol +} from "packages/victory-scatter/src/helper-methods"; describe("victory-scatter/helper-methods", () => { describe("getSize", () => { diff --git a/test/client/spec/victory-scatter/victory-scatter.spec.js b/test/client/spec/victory-scatter/victory-scatter.spec.js index f67bd9a69..c6b192960 100644 --- a/test/client/spec/victory-scatter/victory-scatter.spec.js +++ b/test/client/spec/victory-scatter/victory-scatter.spec.js @@ -47,7 +47,9 @@ describe("components/victory-scatter", () => { describe("rendering data", () => { it("renders injected points for {x, y} shaped data (default)", () => { const data = range(10).map((i) => ({ x: i, y: i })); - const wrapper = shallow(} />); + const wrapper = shallow( + } /> + ); const points = wrapper.find(MyPoint); expect(points.length).to.equal(10); @@ -65,7 +67,9 @@ describe("components/victory-scatter", () => { .map((i) => ({ x: i, y: i })) .reverse(); const wrapper = shallow(); - const xValues = wrapper.find(Point).map((point) => point.prop("datum")._x); + const xValues = wrapper + .find(Point) + .map((point) => point.prop("datum")._x); expect(xValues).to.eql([0, 1, 2, 3, 4]); }); @@ -73,8 +77,12 @@ describe("components/victory-scatter", () => { const data = range(5) .map((i) => ({ x: i, y: i })) .reverse(); - const wrapper = shallow(); - const xValues = wrapper.find(Point).map((point) => point.prop("datum")._x); + const wrapper = shallow( + + ); + const xValues = wrapper + .find(Point) + .map((point) => point.prop("datum")._x); expect(xValues).to.eql([4, 3, 2, 1, 0]); }); @@ -87,7 +95,9 @@ describe("components/victory-scatter", () => { it("renders points for deeply-nested data", () => { const data = range(40).map((i) => ({ a: { b: [{ x: i, y: i }] } })); - const wrapper = shallow(); + const wrapper = shallow( + + ); const points = wrapper.find(Point); expect(points.length).to.equal(40); }); @@ -116,7 +126,11 @@ describe("components/victory-scatter", () => { const points = wrapper.find(Point); const svgCoordinates = points.map(SvgTestHelper.getSvgPointCoordinates); const coordinates = svgCoordinates.map((coord) => { - return SvgTestHelper.convertSvgCoordinatesToCartesian(coord, svgDimensions, domain); + return SvgTestHelper.convertSvgCoordinatesToCartesian( + coord, + svgDimensions, + domain + ); }); expect(coordinates).to.eql([ @@ -154,7 +168,13 @@ describe("components/victory-scatter", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -230,7 +250,9 @@ describe("components/victory-scatter", () => { data={data} dataComponent={ `scatter point x: ${datum.x}, y:${datum.y}`} + ariaLabel={({ datum }) => + `scatter point x: ${datum.x}, y:${datum.y}` + } tabIndex={({ index }) => index + 10} /> } @@ -238,7 +260,9 @@ describe("components/victory-scatter", () => { ); expect(wrapper.find("path")).to.have.length(5); wrapper.find("path").forEach((p, i) => { - expect(p.prop("aria-label")).to.equal(`scatter point x: ${data[i].x}, y:${data[i].y}`); + expect(p.prop("aria-label")).to.equal( + `scatter point x: ${data[i].x}, y:${data[i].y}` + ); expect(p.prop("tabIndex")).to.equal(i + 10); }); }); diff --git a/test/client/spec/victory-selection-container/selection-helpers.spec.js b/test/client/spec/victory-selection-container/selection-helpers.spec.js index e58ba163a..2ceae7e98 100644 --- a/test/client/spec/victory-selection-container/selection-helpers.spec.js +++ b/test/client/spec/victory-selection-container/selection-helpers.spec.js @@ -51,7 +51,11 @@ describe("helpers/selection", () => { ]; const props = { scale, x1: 0, y1: 0, x2: 0.5, y2: 0.5 }; const bounds = { x: [0, 1], y: [10, 15] }; - const filteredData = SelectionHelpers.filterDatasets(props, datasets, bounds); + const filteredData = SelectionHelpers.filterDatasets( + props, + datasets, + bounds + ); expect(filteredData).to.equal(null); }); @@ -64,7 +68,11 @@ describe("helpers/selection", () => { const datasets = [{ childName, data }]; const bounds = { x: [0, 1], y: [0, 10] }; const props = { scale, x1: 0, y1: 0, x2: 0.5, y2: 0.5 }; - const filteredData = SelectionHelpers.filterDatasets(props, datasets, bounds); + const filteredData = SelectionHelpers.filterDatasets( + props, + datasets, + bounds + ); const expected = { eventKey: [0], data: [data[0]] }; expect(filteredData).to.eql([assign({ childName }, expected)]); }); diff --git a/test/client/spec/victory-shared-events/victory-shared-events.spec.js b/test/client/spec/victory-shared-events/victory-shared-events.spec.js index 02d2c6e0e..80098e1a2 100644 --- a/test/client/spec/victory-shared-events/victory-shared-events.spec.js +++ b/test/client/spec/victory-shared-events/victory-shared-events.spec.js @@ -20,17 +20,25 @@ describe("components/victory-shared-events", () => { }; const expectOnDataComponents = (expectationMatrix, testFn, component) => { - forEach(expectationMatrix, (dataComponentExpectations, parentComponentName) => { - const dataComponentTests = findComponentByName(parentComponentName, component) - .find(MockDataComponent) - .map(testFn); + forEach( + expectationMatrix, + (dataComponentExpectations, parentComponentName) => { + const dataComponentTests = findComponentByName( + parentComponentName, + component + ) + .find(MockDataComponent) + .map(testFn); - expect(dataComponentTests).to.eql(dataComponentExpectations); - }); + expect(dataComponentTests).to.eql(dataComponentExpectations); + } + ); }; const findDataComponent = (parentName, index, component) => { - return findComponentByName(parentName, component).find(MockDataComponent).at(index); + return findComponentByName(parentName, component) + .find(MockDataComponent) + .at(index); }; it("should trigger shared events exclusively on selected children", () => { diff --git a/test/client/spec/victory-tooltip/victory-tooltip.spec.js b/test/client/spec/victory-tooltip/victory-tooltip.spec.js index 3df143b37..c0be45e1f 100644 --- a/test/client/spec/victory-tooltip/victory-tooltip.spec.js +++ b/test/client/spec/victory-tooltip/victory-tooltip.spec.js @@ -47,7 +47,9 @@ describe("components/victory-tooltip", () => { describe("event handling", () => { it("attaches an to the flyout object", () => { const clickHandler = sinon.spy(); - const wrapper = mount(); + const wrapper = mount( + + ); wrapper.find("path").simulate("click"); expect(clickHandler.called).to.equal(true); }); diff --git a/test/client/spec/victory-voronoi/victory-voronoi.spec.js b/test/client/spec/victory-voronoi/victory-voronoi.spec.js index 6e3433333..d57f29281 100644 --- a/test/client/spec/victory-voronoi/victory-voronoi.spec.js +++ b/test/client/spec/victory-voronoi/victory-voronoi.spec.js @@ -55,7 +55,9 @@ describe("components/victory-voronoi", () => { .reverse(); const wrapper = shallow(); - const xValues = wrapper.find(Voronoi).map((voronoi) => voronoi.prop("datum")._x); + const xValues = wrapper + .find(Voronoi) + .map((voronoi) => voronoi.prop("datum")._x); expect(xValues).to.eql([0, 1, 2, 3, 4]); }); @@ -63,9 +65,13 @@ describe("components/victory-voronoi", () => { const data = range(5) .map((i) => ({ x: i, y: i })) .reverse(); - const wrapper = shallow(); + const wrapper = shallow( + + ); - const xValues = wrapper.find(Voronoi).map((voronoi) => voronoi.prop("datum")._x); + const xValues = wrapper + .find(Voronoi) + .map((voronoi) => voronoi.prop("datum")._x); expect(xValues).to.eql([4, 3, 2, 1, 0]); }); @@ -97,7 +103,13 @@ describe("components/victory-voronoi", () => { svg.simulate("click"); expect(clickHandler).called; // the first argument is the standard evt object - expect(clickHandler.args[0][1]).to.include.keys("data", "scale", "width", "height", "style"); + expect(clickHandler.args[0][1]).to.include.keys( + "data", + "scale", + "width", + "height", + "style" + ); }); it("attaches an event to data", () => { @@ -166,7 +178,10 @@ describe("components/victory-voronoi", () => { `${datum.x}`} tabIndex={({ index }) => index + 6} /> + `${datum.x}`} + tabIndex={({ index }) => index + 6} + /> } /> );