Compare commits

...

50 Commits

Author SHA1 Message Date
rozetko 1fba260d5a 0.6.9 2 weeks ago
rozetko 07812328ec Merge pull request 'init React component (TODO: use workspaces properly)' (#2) from init-react-component into main 2 weeks ago
rozetko 37ff7588dd init React component (TODO: use workspaces properly) 2 weeks ago
rozetko 6e9da1a6c9 Merge pull request 'Update dependencies' (#1) from upd-deps into main 2 years ago
rozetko 0f4c6349af upd d3-delaunay 2 years ago
rozetko b248076e45 do not push anything except `dist/` to npm 2 years ago
rozetko bd25966ac7 0.6.8 2 years ago
rozetko c9b6b7ada2 upd deps 2 years ago
vargburz 907f4c6146 0.6.7 2 years ago
Alexander Velikiy 57bf8dddae Merge branch 'core-test' into 'main' 2 years ago
vargburz 6125ef38f1 use new core with fixed overlay 2 years ago
Alexander Velikiy e217ebc042 Merge branch 'click-on-metric' into 'main' 2 years ago
vargburz b3ecd93ea0 add click for path too 2 years ago
vargburz bb934ac50a metric options: callback on click 2 years ago
vargburz 65ad8b9de4 defaults deep 3 years ago
vargburz ec1379c6f2 use new core 3 years ago
vargburz 31d4eefc5f use latest core 3 years ago
vargburz 73462724d3 0.6.2 3 years ago
vargburz e954673ebb use 0.6.6 core 3 years ago
vargburz ec89395bd3 0.6.1 3 years ago
Alexander Velikiy f49b3d404d Merge branch 'new-mouse-move-callback-format' into 'main' 3 years ago
vargburz 6f3a686769 remove log 3 years ago
vargburz c93bde1ad3 update delaunay data with serie target && update mouse move callback type 3 years ago
rozetko 2ab116febe todo 3 years ago
rozetko 97297afee5 0.6.0 3 years ago
rozetko a89e2cf8d6 Merge branch 'new-core-models' into 'main' 3 years ago
rozetko f109d33364 upd core 3 years ago
rozetko 2ea990aaeb fix demo axes labels 3 years ago
rozetko 09f08acb5e fix points not rendering 3 years ago
vargburz 5634e9e615 circles not working 3 years ago
rozetko 9f7d2cd182 yarn migrate to 2 3 years ago
rozetko b46a9bbe2d 0.5.1 3 years ago
rozetko 8cbcabac08 change chartwerk core dep to latest 3 years ago
rozetko 296ea7acc0 Merge branch '0.5.0-beta' into 'main' 3 years ago
rozetko c4cea54518 0.5.0 3 years ago
rozetko 8504573451 upd core 3 years ago
rozetko 261a0d02e9 0.5.0-beta3 3 years ago
rozetko 1ecba37236 external core, d3 and lodash 3 years ago
rozetko c1b81f0b28 move demo into examples/ 3 years ago
rozetko c88c0cf72d 0.4.1 3 years ago
rozetko f0b4cf4d33 upd core 3 years ago
rozetko f6472222b2 rm package lock && rm dist 3 years ago
vargburz 6b19371613 use core 0.4.0 3 years ago
Alexander Velikiy 31725f8cff Merge branch 'use-color-formatter' into 'main' 3 years ago
vargburz e5fbdac44b upd version 3 years ago
vargburz 908263513e use color formatter 3 years ago
Alexander Velikiy ba5641640b Merge branch 'core-from-gitlab' into 'main' 3 years ago
vargburz 872e2357a7 use gitlab core 3 years ago
Alexey Velikiy 63475dcc2c add yarn lock 3 years ago
Alexander Velikiy 22ef565587 Merge branch 'target-master' into 'main' 3 years ago
  1. 9
      .gitignore
  2. 786
      .yarn/releases/yarn-3.2.1.cjs
  3. 3
      .yarnrc.yml
  4. 14
      build/webpack.base.conf.js
  5. 2
      build/webpack.dev.conf.js
  6. 3
      build/webpack.prod.conf.js
  7. 15
      dist/delaunay.d.ts
  8. 88
      dist/index.d.ts
  9. 9
      dist/index.js
  10. 26
      dist/types.d.ts
  11. 43
      examples/demo.html
  12. 4662
      package-lock.json
  13. 39
      package.json
  14. 26
      react/build/webpack.base.conf.js
  15. 8
      react/build/webpack.dev.conf.js
  16. 6
      react/build/webpack.prod.conf.js
  17. 23
      react/package.json
  18. 62
      react/src/index.tsx
  19. 23
      react/tsconfig.json
  20. 1322
      react/yarn.lock
  21. 253
      src/index.ts
  22. 34
      src/models/delaunay.ts
  23. 26
      src/models/scatter_series.ts
  24. 43
      src/types.ts
  25. 3
      tsconfig.json
  26. 2155
      yarn.lock

9
.gitignore vendored

@ -1 +1,10 @@
node_modules
dist
# yarn
.yarn
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions

786
.yarn/releases/yarn-3.2.1.cjs vendored

File diff suppressed because one or more lines are too long

3
.yarnrc.yml

@ -0,0 +1,3 @@
nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-3.2.1.cjs

14
build/webpack.base.conf.js

@ -1,4 +1,5 @@
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
function resolve(dir) {
@ -8,7 +9,14 @@ function resolve(dir) {
module.exports = {
context: resolve('src'),
entry: './index.ts',
plugins: [],
plugins: [
new CopyPlugin({
patterns: [
{ from: '../react/dist/index.js', to: 'react/index.js' },
{ from: '../react/dist/index.d.ts', to: 'react/index.d.ts' },
],
})
],
module: {
rules: [
{
@ -25,6 +33,10 @@ module.exports = {
},
resolve: {
extensions: ['.ts', '.js'],
// this is necessary for resolution of external libs like d3 in dev mode
// when core is linked: webpack will take d3 from this node_modules but not from
// internal so you get one version of d3
modules: [path.resolve(__dirname, '../node_modules'), 'node_modules']
},
output: {
filename: 'index.js',

2
build/webpack.dev.conf.js

@ -2,7 +2,7 @@ const baseWebpackConfig = require('./webpack.base.conf');
var conf = baseWebpackConfig;
conf.devtool = 'inline-source-map';
conf.watch = true;
conf.mode = 'development';
conf.output.filename = 'index.dev.js';
module.exports = conf;

3
build/webpack.prod.conf.js

@ -2,5 +2,8 @@ const baseWebpackConfig = require('./webpack.base.conf');
var conf = baseWebpackConfig;
conf.mode = 'production';
conf.externals = [
'@chartwerk/core', 'd3', 'lodash'
];
module.exports = baseWebpackConfig;

15
dist/delaunay.d.ts vendored

@ -1,15 +0,0 @@
import { ScatterData } from './types';
import * as d3 from 'd3';
export declare class DelaunayDiagram {
protected series: ScatterData[];
private _delaunayData;
private _delaunayDiagram;
constructor(series: ScatterData[], xScale: d3.ScaleLinear<number, number>, yScale: (string: any) => d3.ScaleLinear<number, number>);
get data(): number[][] | undefined;
setDelaunayDiagram(xScale: d3.ScaleLinear<number, number>, yScale: (string: any) => d3.ScaleLinear<number, number>): void;
findPointIndex(eventX: number, eventY: number): number | undefined;
getDataRowByIndex(index: number): number[] | undefined;
private getDatapointsForDelaunay;
private concatSeriesDatapoints;
private getSerieIdxByTarget;
}

88
dist/index.d.ts vendored

@ -1,88 +0,0 @@
import { ChartwerkPod, TickOrientation, TimeFormat, yAxisOrientation } from '@chartwerk/core';
import { ScatterData, ScatterOptions, PointType, LineType } from './types';
import { DelaunayDiagram } from './delaunay';
import * as d3 from 'd3';
export declare class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOptions> {
_metricsContainer: any;
_delaunayDiagram: DelaunayDiagram;
constructor(el: HTMLElement, _series?: ScatterData[], _options?: ScatterOptions);
renderMetrics(): void;
renderMetricContainer(): void;
protected updateCrosshair(): void;
appendCrosshairPoints(): void;
protected appendCrosshairPoint(serieIdx: number): void;
protected renderLines(): void;
renderLine(datapoints: number[][], lineType: LineType, color: string, orientation: yAxisOrientation): void;
protected renderPoints(): void;
onPanningEnd(): void;
unhighlight(): void;
highlight(pointIdx: number): void;
protected getCrosshairCircleBackgroundSize(serieIdx: number): number;
renderSharedCrosshair(values: {
x?: number;
y?: number;
}): void;
moveCrosshairLine(xPosition: number, yPosition: number): void;
findAndHighlightDatapoints(eventX: number, eventY: number): {
values: any[];
pointIdx: number;
} | null;
protected getYScale(orientation: yAxisOrientation): d3.ScaleLinear<number, number>;
hideSharedCrosshair(): void;
onMouseMove(): void;
onMouseOver(): void;
onMouseOut(): void;
}
export declare const VueChartwerkScatterPodObject: {
render(createElement: any): any;
mixins: {
props: {
id: {
type: StringConstructor;
required: boolean;
};
series: {
type: ArrayConstructor;
required: boolean;
default: () => any[];
};
options: {
type: ObjectConstructor;
required: boolean;
default: () => {};
};
};
watch: {
id(): void;
series(): void;
options(): void;
};
mounted(): void;
destroyed(): void;
methods: {
render(): void;
renderSharedCrosshair(values: {
x?: number;
y?: number;
}): void;
hideSharedCrosshair(): void;
onPanningRescale(event: any): void;
renderChart(): void;
appendEvents(): void;
zoomIn(range: any): void;
zoomOut(centers: any): void;
mouseMove(evt: any): void;
mouseOut(): void;
onLegendClick(idx: any): void;
panningEnd(range: any): void;
panning(range: any): void;
contextMenu(evt: any): void;
sharedCrosshairMove(event: any): void;
renderEnd(): void;
};
}[];
methods: {
render(): void;
};
};
export { ScatterData, ScatterOptions, TickOrientation, TimeFormat, PointType, LineType };

9
dist/index.js vendored

File diff suppressed because one or more lines are too long

26
dist/types.d.ts vendored

@ -1,26 +0,0 @@
import { TimeSerie, Options } from '@chartwerk/core';
declare type ScatterDataParams = {
pointType: PointType;
lineType: LineType;
pointSize: number;
colorFormatter?: ColorFormatter;
};
declare type ScatterOptionsParams = {
voronoiRadius: number;
circleView: boolean;
renderGrid: boolean;
};
export declare type ScatterData = TimeSerie & Partial<ScatterDataParams>;
export declare type ScatterOptions = Options & Partial<ScatterOptionsParams>;
export declare enum PointType {
NONE = "none",
CIRCLE = "circle",
RECTANGLE = "rectangle"
}
export declare enum LineType {
NONE = "none",
SOLID = "solid",
DASHED = "dashed"
}
export declare type ColorFormatter = (datapoint: number[]) => string;
export {};

43
demo.html → examples/demo.html

@ -4,28 +4,31 @@
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="./dist/index.js" type="text/javascript"></script>
<script src="../dist/index.dev.js" type="text/javascript"></script>
</head>
<body>
<div id="chart" style="width: 500px; height: 500px;"></div>
<script type="text/javascript">
var pod = new ChartwerkScatterPod(
document.getElementById('chart'),
[
{
target: 'test1',
datapoints: [
const datapoints1 = [
[100, -50, 0],
[200, 150, 0],
[100, 160, 1],
[150, 170, 1],
[150, 180, 0],
[150, 250, 1]
],
];
var pod = new ChartwerkScatterPod(
document.getElementById('chart'),
[
{
target: 'test1',
datapoints: datapoints1,
color: 'red',
lineType: 'dashed',
pointType: 'circle'
pointType: 'circle',
colorFormatter: (values, idx) => datapoints1[idx][2] === 0 ? 'blue' : 'green',
clickCallback: (metricData, pointData) => { console.log('click', metricData, pointData) }
},
{
target: 'test2',
@ -37,18 +40,19 @@
color: 'purple',
pointType: 'rectangle',
pointSize: 5,
yOrientation: 'right',
}
],
{
axis: {
x: {
format: 'numeric',
range: [-100, 300]
range: [-100, 300],
label: 'x'
},
y: {
invert: true,
range: [-100, 250]
range: [-100, 250],
label: 'y'
},
y1: {
isActive: true,
@ -57,8 +61,8 @@
},
zoomEvents: {
mouse: {
pan: { isActive: false, orientation: 'both', keyEvent: 'main' },
zoom: { isActive: true, keyEvent: 'shift' },
pan: { isActive: true, orientation: 'both', keyEvent: 'main' },
zoom: { isActive: false, keyEvent: 'shift' },
},
scroll: {
pan: { isActive: false },
@ -69,18 +73,19 @@
orientation: 'both',
color: 'gray'
},
labelFormat: {
yAxis: 'y',
xAxis: 'x'
},
eventsCallbacks: {
zoomOut: () => { pod.render() }
},
margin: { top: 30, right: 30, bottom: 40, left: 30 },
circleView: true,
}
);
pod.render();
</script>
</body>
</html>
<style>
.overlay {
fill: black;
}
</style>

4662
package-lock.json generated

File diff suppressed because it is too large Load Diff

39
package.json

@ -1,30 +1,35 @@
{
"name": "@chartwerk/scatter-pod",
"version": "0.2.4",
"version": "0.6.9",
"description": "Chartwerk scatter pod",
"main": "dist/index.js",
"files": [
"/dist"
],
"scripts": {
"build": "webpack --config build/webpack.prod.conf.js",
"dev": "webpack --config build/webpack.dev.conf.js",
"test": "echo \"Error: no test specified\" && exit 1"
"build": "rm -rf dist && cd react && yarn build && cd .. && webpack --config build/webpack.prod.conf.js && webpack --config build/webpack.dev.conf.js",
"dev": "webpack --watch --config build/webpack.dev.conf.js",
"test": "echo \"Error: no test specified\" && exit 1",
"update-core": "yarn up @chartwerk/core && yarn up @chartwerk/core@latest"
},
"repository": {},
"author": "CorpGlory",
"license": "Apache-2.0",
"dependencies": {
"@chartwerk/core": "github:chartwerk/core#532eddbc8ad938091b1d9ec1693cec5eddfdbfc2"
"@chartwerk/core": "latest"
},
"devDependencies": {
"@types/d3": "^5.7.2",
"@types/lodash": "^4.14.149",
"css-loader": "^3.4.2",
"d3": "^5.15.0",
"d3-delaunay": "^6.0.2",
"lodash": "^4.17.15",
"style-loader": "^1.1.3",
"ts-loader": "^6.2.1",
"typescript": "^3.8.3",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
}
"copy-webpack-plugin": "^11.0.0",
"css-loader": "^6.8.1",
"d3-delaunay": "^6.0.4",
"style-loader": "^3.3.3",
"ts-loader": "^9.4.3",
"typescript": "^5.1.3",
"webpack": "^5.87.0",
"webpack-cli": "^5.1.4"
},
"packageManager": "yarn@3.2.1",
"workspaces": [
"react/*"
]
}

26
react/build/webpack.base.conf.js

@ -0,0 +1,26 @@
const path = require('path');
module.exports = {
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'index.js',
path: path.resolve(__dirname, '../dist'),
libraryTarget: 'umd',
umdNamedDefine: true,
},
externals: [
'@chartwerk/scatter-pod', 'react'
]
};

8
react/build/webpack.dev.conf.js

@ -0,0 +1,8 @@
const baseWebpackConfig = require('./webpack.base.conf');
var conf = baseWebpackConfig;
conf.devtool = 'inline-source-map';
conf.mode = 'development';
conf.output.filename = 'index.dev.js';
module.exports = conf;

6
react/build/webpack.prod.conf.js

@ -0,0 +1,6 @@
const baseWebpackConfig = require('./webpack.base.conf');
var conf = baseWebpackConfig;
conf.mode = 'production';
module.exports = baseWebpackConfig;

23
react/package.json

@ -0,0 +1,23 @@
{
"name": "scatter-pod-react",
"version": "0.0.1",
"description": "React wrapper around scatter-pod",
"main": "dist/index.js",
"repository": "http://code.corpglory.net/chartwerk/scatter-pod.git",
"author": "CorpGlory Inc.",
"license": "ISC",
"scripts": {
"build": "webpack --config build/webpack.prod.conf.js",
"dev": "webpack --config build/webpack.dev.conf.js"
},
"dependencies": {
"@chartwerk/scatter-pod": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"ts-loader": "^9.5.1",
"typescript": "^5.4.3",
"webpack": "^5.87.0"
}
}

62
react/src/index.tsx

@ -0,0 +1,62 @@
import { ScatterData, ScatterOptions, ChartwerkScatterPod } from '@chartwerk/scatter-pod';
import React, { useEffect, useRef, useState } from 'react';
import _ from 'lodash';
export type ChartwerkScatterPodReactProps = {
id?: string;
series: ScatterData[];
options?: ScatterOptions;
className?: string;
}
export function ChartwerkScatterPodReact(props: ChartwerkScatterPodReactProps) {
const [pod, setPod] = useState<ChartwerkScatterPod | null>(null);
const [hack, setHack] = useState<number | null>(null);
const chartRef = useRef(null);
const chart = chartRef.current;
useEffect(() => {
// this function will be called on component unmount
return () => {
if(pod === null) { return; }
// @ts-ignore
pod.removeEventListeners();
}
}, []);
useEffect(() => {
if(chart === null) { return; }
if(pod === null) {
const newPod = new ChartwerkScatterPod(
// @ts-ignore
chart,
props.series,
props.options,
);
setPod(newPod);
newPod.render();
} else {
// TODO: actually it's wrong logic with updates
// because it creates new pod anyway
pod.updateData(props.series, props.options);
}
}, [chart, props.id, props.options]);
// TODO: it's a hack to render the ScatterPod right after the div appears in DOM
setTimeout(() => {
if(hack === null) {
setHack(1);
}
}, 1);
return (
<div id={props.id} className={props.className} ref={chartRef}></div>
);
}
export default ChartwerkScatterPodReact;

23
react/tsconfig.json

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "es5",
"rootDir": "./src",
"module": "esnext",
"moduleResolution": "node",
"declaration": true,
"declarationDir": "dist",
"allowSyntheticDefaultImports": true,
"inlineSourceMap": false,
"sourceMap": true,
"noEmitOnError": false,
"emitDecoratorMetadata": false,
"experimentalDecorators": true,
"noImplicitReturns": true,
"noImplicitThis": false,
"noImplicitUseStrict": false,
"noImplicitAny": false,
"noUnusedLocals": false,
"baseUrl": "./src",
"jsx": "react"
}
}

1322
react/yarn.lock

File diff suppressed because it is too large Load Diff

253
src/index.ts

@ -1,74 +1,65 @@
import { ChartwerkPod, VueChartwerkPodMixin, TickOrientation, TimeFormat, yAxisOrientation, CrosshairOrientation, PanOrientation } from '@chartwerk/core';
import { ScatterData, ScatterOptions, PointType, LineType, ColorFormatter } from './types';
import { ChartwerkPod, VueChartwerkPodMixin, TimeFormat, yAxisOrientation, CrosshairOrientation } from '@chartwerk/core';
import { ScatterData, ScatterOptions, PointType, LineType, HighlightedData, MouseMoveEvent, DelaunayDataRow } from './types';
import { DelaunayDiagram } from './delaunay';
import { DelaunayDiagram } from './models/delaunay';
import { ScatterSeries } from './models/scatter_series';
import * as d3 from 'd3';
import * as _ from 'lodash';
// TODO: use pod state with defaults
const DEFAULT_POINT_SIZE = 4;
const POINT_HIGHLIGHT_DIAMETER = 4;
const CROSSHAIR_BACKGROUND_OPACITY = 0.3;
const DEFAULT_POINT_TYPE = PointType.CIRCLE;
const DEFAULT_LINE_TYPE = LineType.NONE;
const DEFAULT_LINE_DASHED_AMOUNT = 4;
export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOptions> {
_metricsContainer: any;
metricContainer: any;
_delaunayDiagram: DelaunayDiagram;
series: ScatterSeries;
constructor(el: HTMLElement, _series: ScatterData[] = [], _options: ScatterOptions = {}) {
super(d3, el, _series, _options);
super(el, _series, _options);
this.series = new ScatterSeries(_series);
}
renderMetrics(): void {
if(this.series.length === 0) {
if(!this.series.isSeriesAvailable) {
this.renderNoDataPointsMessage();
return;
}
this.updateCrosshair();
this.renderMetricContainer();
this._delaunayDiagram = new DelaunayDiagram(this.series, this.xScale, this.getYScale.bind(this));
this._delaunayDiagram = new DelaunayDiagram(this.series, this.state.xScale, this.getYScale.bind(this));
this.renderLines();
this.renderPoints();
}
renderMetricContainer(): void {
// container for clip path
const clipContatiner = this.chartContainer
.append('g')
.attr('clip-path', `url(#${this.rectClipId})`)
.attr('class', 'metrics-container');
// container for panning
this._metricsContainer = clipContatiner
.append('g')
.attr('class', ' metrics-rect');
clearAllMetrics(): void {
// TODO: temporary hack before it will be implemented in core.
this.chartContainer.selectAll('.metric-el').remove();
}
protected updateCrosshair(): void {
this.crosshair.selectAll('circle').remove();
// TODO: Crosshair class, which can be used as Pod
this.appendCrosshairPoints();
}
appendCrosshairPoints(): void {
this.series.forEach((serie: ScatterData, serieIdx: number) => {
this.appendCrosshairPoint(serieIdx);
this.series.visibleSeries.forEach((serie: ScatterData) => {
this.appendCrosshairPoint(serie.idx, serie.pointType, serie.pointSize);
});
}
protected appendCrosshairPoint(serieIdx: number): void {
protected appendCrosshairPoint(serieIdx: number, pointType: PointType, size: number): void {
// TODO: add Crosshair type options
const pointType = this.series[serieIdx].pointType || DEFAULT_POINT_TYPE;
switch(pointType) {
case PointType.NONE:
return;
case PointType.CIRCLE:
this.crosshair.append('circle')
.attr('class', `crosshair-point crosshair-point-${serieIdx} crosshair-background`)
.attr('r', this.getCrosshairCircleBackgroundSize(serieIdx))
.attr('r', this.getCrosshairCircleBackgroundSize(size, pointType))
.attr('clip-path', `url(#${this.rectClipId})`)
.style('opacity', CROSSHAIR_BACKGROUND_OPACITY)
.style('pointer-events', 'none')
@ -77,8 +68,8 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
case PointType.RECTANGLE:
this.crosshair.append('rect')
.attr('class', `crosshair-point crosshair-point-${serieIdx} crosshair-background`)
.attr('width', this.getCrosshairCircleBackgroundSize(serieIdx))
.attr('height', this.getCrosshairCircleBackgroundSize(serieIdx))
.attr('width', this.getCrosshairCircleBackgroundSize(size, pointType))
.attr('height', this.getCrosshairCircleBackgroundSize(size, pointType))
.attr('clip-path', `url(#${this.rectClipId})`)
.style('opacity', CROSSHAIR_BACKGROUND_OPACITY)
.style('pointer-events', 'none')
@ -90,82 +81,97 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
}
protected renderLines(): void {
this.series.forEach((serie, serieIdx) => {
if(serie.visible === false) {
return;
}
const lineType = serie.lineType || DEFAULT_LINE_TYPE;
this.renderLine(serie.datapoints, lineType, this.getSerieColor(serieIdx), serie.yOrientation);
this.series.visibleSeries.forEach(serie => {
this.renderLine(serie);
});
}
renderLine(datapoints: number[][], lineType: LineType, color: string, orientation: yAxisOrientation): void {
if(lineType === LineType.NONE) {
renderLine(serie: ScatterData): void {
if(serie.lineType === LineType.NONE) {
return;
}
let strokeDasharray;
// TODO: move to option
if(lineType === LineType.DASHED) {
if(serie.lineType === LineType.DASHED) {
strokeDasharray = DEFAULT_LINE_DASHED_AMOUNT;
}
const lineGenerator = this.d3.line()
.x((d: [number, number]) => this.xScale(d[1]))
.y((d: [number, number]) => this.getYScale(orientation)(d[0]));
const lineGenerator = d3.line()
.x((d: [number, number]) => this.state.xScale(d[0]))
.y((d: [number, number]) => this.getYScale(serie.yOrientation)(d[1]));
this._metricsContainer
this.metricContainer
.append('path')
.datum(datapoints)
.datum(serie.datapoints)
.attr('class', 'metric-path')
.attr('d', lineGenerator)
.attr('fill', 'none')
.style('pointer-events', 'none')
.attr('stroke', color)
.attr('stroke', serie.color)
.attr('stroke-width', 1)
.attr('stroke-opacity', 0.7)
.attr('stroke-dasharray', strokeDasharray)
.attr('d', lineGenerator);
.style('pointer-events', serie.clickCallback ? 'auto' : 'none')
.style('cursor', serie.clickCallback ? 'pointer' : 'crosshair')
.on('click', () => { serie.clickCallback({ target: serie.target, class: serie.class, alias: serie.alias }) });
}
protected renderPoints(): void {
if(!this._delaunayDiagram.data) {
return;
}
this._metricsContainer.selectAll(null)
this.metricContainer.selectAll(null)
.data(this._delaunayDiagram.data)
.enter()
.append('circle')
.filter((d: number[]) => this.series[_.last(d)].pointType !== PointType.RECTANGLE)
.filter((d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointType !== PointType.RECTANGLE)
.attr('class', (d, i: number) => `metric-element metric-circle point-${i}`)
.attr('r', (d: number[]) => this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE)
.style('fill', (d: number[]) => this.getSerieColor(_.last(d)))
.style('pointer-events', 'none')
.attr('cx', (d: any[]) => this.xScale(d[1]))
.attr('cy', (d: any[]) => this.getYScale(this.series[_.last(d)].yOrientation)(d[0]));
.attr('r', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointSize)
.attr('cx', (d: DelaunayDataRow) => this.state.xScale(d[0]))
.attr('cy', (d: DelaunayDataRow) => this.getYScale(this.series.getSerieByTarget(d[4])?.yOrientation)(d[1]))
.style('fill', (d: DelaunayDataRow, i: number) => this.getSeriesColorFromDataRow(d, i))
.style('pointer-events', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.clickCallback ? 'auto' : 'none')
.style('cursor', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.clickCallback ? 'pointer' : 'crosshair')
.on('click', (d: DelaunayDataRow) => {
d3.event.stopPropagation();
const serie = this.series.getSerieByTarget(d[4]);
const serieData = { target: serie?.target, class: serie?.class, alias: serie?.alias };
serie?.clickCallback(serieData, d);
});
this._metricsContainer.selectAll(null)
this.metricContainer.selectAll(null)
.data(this._delaunayDiagram.data)
.enter()
.append('rect')
.filter((d: number[]) => this.series[_.last(d)].pointType === PointType.RECTANGLE)
.filter((d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointType === PointType.RECTANGLE)
.attr('class', (d, i: number) => `metric-element metric-circle point-${i}`)
.attr('r', (d: number[]) => this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE)
.style('fill', (d: number[]) => this.getSerieColor(_.last(d)))
.style('pointer-events', 'none')
.attr('x', (d: number[]) => this.xScale(d[1]) - (this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE) / 2)
.attr('y', (d: number[]) => this.getYScale(this.series[_.last(d)].yOrientation)(d[0]) - (this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE) / 2)
.attr('width', (d: number[]) => this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE)
.attr('height', (d: number[]) => this.series[_.last(d)].pointSize || DEFAULT_POINT_SIZE);
.attr('r', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointSize)
.attr('x', (d: DelaunayDataRow) => this.state.xScale(d[0]) - this.series.getSerieByTarget(d[4])?.pointSize / 2)
.attr('y', (d: DelaunayDataRow) => this.getYScale(this.series.getSerieByTarget(d[4])?.yOrientation)(d[1]) - this.series.getSerieByTarget(d[4])?.pointSize / 2)
.attr('width', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointSize)
.attr('height', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.pointSize)
.style('fill', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.color)
.style('pointer-events', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.clickCallback ? 'auto' : 'none')
.style('cursor', (d: DelaunayDataRow) => this.series.getSerieByTarget(d[4])?.clickCallback ? 'pointer' : 'crosshair')
.on('click', (d: DelaunayDataRow) => {
d3.event.stopPropagation();
const serie = this.series.getSerieByTarget(d[4]);
const serieData = { target: serie?.target, class: serie?.class, alias: serie?.alias };
serie?.clickCallback(serieData, d);
});
}
getSeriesColorFromDataRow(values: DelaunayDataRow, rowIdx: number): string {
const serie = this.series.getSerieByTarget(values[4]);
if(serie?.colorFormatter) {
return serie.colorFormatter(values, rowIdx);
}
return serie.color;
}
onPanningEnd(): void {
this.isPanning = false;
this.onMouseOut();
this._delaunayDiagram.setDelaunayDiagram(this.xScale, this.getYScale.bind(this));
if(this.options.eventsCallbacks !== undefined && this.options.eventsCallbacks.panningEnd !== undefined) {
this.options.eventsCallbacks.panningEnd([this.state.xValueRange, this.state.yValueRange, this.state.y1ValueRange]);
} else {
console.log('on panning end, but there is no callback');
}
this._delaunayDiagram.setDelaunayDiagram(this.state.xScale, this.getYScale.bind(this));
this.options.callbackPanningEnd([this.state.xValueRange, this.state.yValueRange, this.state.y1ValueRange]);
}
unhighlight(): void {
@ -175,47 +181,37 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
highlight(pointIdx: number): void {
this.unhighlight();
const datapoint = this._delaunayDiagram.getDataRowByIndex(pointIdx);
if(datapoint === undefined || datapoint === null) {
const row = this._delaunayDiagram.getDataRowByIndex(pointIdx);
if(row === undefined || row === null) {
return;
}
const serieIdx = _.last(datapoint);
const serieOrientation = this.series[serieIdx].yOrientation;
const size = this.getCrosshairCircleBackgroundSize(serieIdx);
const colorFormatter = this.series[serieIdx].colorFormatter;
this.crosshair.selectAll(`.crosshair-point-${serieIdx}`)
.attr('cx', this.xScale(datapoint[1]))
.attr('cy', this.getYScale(serieOrientation)(datapoint[0]))
.attr('x', this.xScale(datapoint[1]) - size / 2)
.attr('y', this.getYScale(serieOrientation)(datapoint[0]) - size / 2)
.attr('fill', colorFormatter !== undefined ? colorFormatter(datapoint) : this.series[serieIdx].color)
const serie = this.series.getSerieByTarget(row[4]);
const size = this.getCrosshairCircleBackgroundSize(serie.pointSize, serie.pointType);
this.crosshair.selectAll(`.crosshair-point-${serie.idx}`)
.attr('cx', this.state.xScale(row[0]))
.attr('cy', this.getYScale(serie.yOrientation)(row[1]))
.attr('x', this.state.xScale(row[0]) - size / 2)
.attr('y', this.getYScale(serie.yOrientation)(row[1]) - size / 2)
.attr('fill', this.getSeriesColorFromDataRow(row, pointIdx))
.style('display', null);
}
protected getCrosshairCircleBackgroundSize(serieIdx: number): number {
const seriePointSize = this.series[serieIdx].pointSize || DEFAULT_POINT_SIZE;
const pointType = this.series[serieIdx].pointType || DEFAULT_POINT_TYPE;
protected getCrosshairCircleBackgroundSize(pointSize: number, pointType: PointType): number {
let highlightDiameter = POINT_HIGHLIGHT_DIAMETER;
if(pointType === PointType.RECTANGLE) {
highlightDiameter = highlightDiameter * 2;
}
return seriePointSize + highlightDiameter;
return pointSize + highlightDiameter;
}
public renderSharedCrosshair(values: { x?: number, y?: number }): void {
this.onMouseOver(); // TODO: refactor to use it once
const eventX = this.xScale(values.x);
const eventY = this.yScale(values.y);
const eventX = this.state.xScale(values.x);
const eventY = this.state.yScale(values.y);
this.moveCrosshairLine(eventX, eventY);
const datapoints = this.findAndHighlightDatapoints(values.x, values.y);
if(this.options.eventsCallbacks === undefined || this.options.eventsCallbacks.sharedCrosshairMove === undefined) {
console.log('Shared crosshair move, but there is no callback');
return;
}
this.options.eventsCallbacks.sharedCrosshairMove({
this.options.callbackSharedCrosshairMove({
datapoints,
eventX, eventY
});
@ -246,8 +242,12 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
}
}
findAndHighlightDatapoints(eventX: number, eventY: number): { values: any[], pointIdx: number } | null {
if(this.series === undefined || this.series.length === 0) {
findAndHighlightDatapoints(eventX: number, eventY: number): {
xValue: number, yValue: number, customValue: number,
pointIdx: number, totalPointIdx: number,
serieInfo: { target: string, alias?: string, class?: string, idx?: number }
} | null {
if(!this.series.isSeriesAvailable) {
return null;
}
@ -257,22 +257,29 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
return null;
}
this.highlight(pointIndex);
const row = this._delaunayDiagram.data[pointIndex];
const serie = this.series.getSerieByTarget(row[4]);
return {
values: this._delaunayDiagram.data[pointIndex],
pointIdx: pointIndex,
xValue: row[0],
yValue: row[1],
customValue: row[2],
pointIdx: row[3],
serieInfo: {
target: serie.target,
alias: serie.alias,
class: serie.class,
idx: serie.idx,
},
totalPointIdx: pointIndex,
};
}
protected getYScale(orientation: yAxisOrientation): d3.ScaleLinear<number, number> {
if(orientation === undefined || orientation === yAxisOrientation.BOTH) {
return this.yScale;
}
switch(orientation) {
case yAxisOrientation.LEFT:
return this.yScale;
return this.state.yScale;
case yAxisOrientation.RIGHT:
return this.y1Scale;
return this.state.y1Scale;
default:
throw new Error(`Unknown type of y axis orientation: ${orientation}`)
}
@ -283,12 +290,11 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
}
onMouseMove(): void {
const mousePosition = this.d3.mouse(this.chartContainer.node());
const mousePosition = d3.mouse(this.chartContainer.node());
const eventX = mousePosition[0];
const eventY = mousePosition[1];
// TODO: seems isOutOfChart is deprecated (check clippath correctness)
if(this.isOutOfChart() === true || this.isPanning === true || this.isBrushing === true) {
if(this.isPanning === true || this.isBrushing === true) {
this.crosshair.style('display', 'none');
return;
} else {
@ -299,24 +305,25 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
// TOOD: it should be two different methods
const highlighted = this.findAndHighlightDatapoints(eventX, eventY);
if(this.options.eventsCallbacks === undefined || this.options.eventsCallbacks.mouseMove === undefined) {
console.log('Mouse move, but there is no callback');
return;
}
// TODO: group fields
this.options.eventsCallbacks.mouseMove({
x: this.d3.event.clientX,
y: this.d3.event.clientY,
xval: this.xScale.invert(eventX),
yval: this.xScale.invert(eventY),
this.options.callbackMouseMove({
bbox: {
clientX: d3.event.clientX,
clientY: d3.event.clientY,
x: eventX,
y: eventY,
chartWidth: this.width,
chartHeight: this.height,
},
data: {
xval: this.state.xScale.invert(eventX),
yval: this.state.xScale.invert(eventY),
highlighted,
chartX: eventX,
chartWidth: this.width
}
});
}
onMouseOver(): void {
if(this.isOutOfChart() === true || this.isPanning === true || this.isBrushing === true) {
if(this.isPanning === true || this.isBrushing === true) {
this.crosshair.style('display', 'none');
return;
}
@ -324,9 +331,7 @@ export class ChartwerkScatterPod extends ChartwerkPod<ScatterData, ScatterOption
}
onMouseOut(): void {
if(this.options.eventsCallbacks !== undefined && this.options.eventsCallbacks.mouseOut !== undefined) {
this.options.eventsCallbacks.mouseOut();
}
this.options.callbackMouseOut();
this.crosshair.style('display', 'none');
}
}
@ -356,4 +361,4 @@ export const VueChartwerkScatterPodObject = {
}
};
export { ScatterData, ScatterOptions, TickOrientation, TimeFormat, PointType, LineType };
export { ScatterData, ScatterOptions, TimeFormat, PointType, LineType, HighlightedData, MouseMoveEvent };

34
src/delaunay.ts → src/models/delaunay.ts

@ -1,24 +1,24 @@
import { ScatterData, PointType } from './types';
import { ScatterData, PointType, DelaunayDataRow } from '../types';
import { ScatterSeries } from './scatter_series';
import { Delaunay } from 'd3-delaunay';
import * as _ from 'lodash';
import * as d3 from 'd3'; // only types
export class DelaunayDiagram {
private _delaunayData: number[][]; // [ 0:y, 1:x, ..., last:serieIdx ][]
private _delaunayData: DelaunayDataRow[];
private _delaunayDiagram: any;
constructor(
protected series: ScatterData[],
protected series: ScatterSeries,
xScale: d3.ScaleLinear<number, number>, yScale: (string) => d3.ScaleLinear<number, number>, // TODO: bad, but idk how to do it better
) {
this._delaunayData = this.getDatapointsForDelaunay();
this.setDelaunayDiagram(xScale, yScale);
}
public get data(): number[][] | undefined {
public get data(): DelaunayDataRow[] | undefined {
if(!this._delaunayData || this._delaunayData.length === 0) {
return undefined;
}
@ -33,8 +33,8 @@ export class DelaunayDiagram {
console.time('delaunay-init');
this._delaunayDiagram = Delaunay.from(
this._delaunayData,
(d: number[]) => xScale(d[1]),
(d: number[]) => yScale(this.series[_.last(d)].yOrientation)(d[0]),
(d: DelaunayDataRow) => xScale(d[0]),
(d: DelaunayDataRow) => yScale(this.series.getSerieByTarget(d[4])?.yOrientation)(d[1]),
);
console.timeEnd('delaunay-init');
}
@ -51,39 +51,29 @@ export class DelaunayDiagram {
return pointIndex;
}
public getDataRowByIndex(index: number): number[] | undefined {
public getDataRowByIndex(index: number): DelaunayDataRow | undefined {
if(!this.data) {
return undefined;
}
return this.data[index];
}
private getDatapointsForDelaunay(): number[][] | undefined {
private getDatapointsForDelaunay(): DelaunayDataRow[] | undefined {
// here we union all datapoints with point render type(circle or rectangle)
// it means that circles and rectangles will be highlighted(not lines)
// TODO: set Defaults (if pointType === undefined, Circle type will be used futher)
const seriesForPointType = this.series.filter((serie: ScatterData) => serie.pointType !== PointType.NONE);
const seriesForPointType = this.series.visibleSeries.filter((serie: ScatterData) => serie.pointType !== PointType.NONE);
if(seriesForPointType.length === 0) {
return undefined; // to avoid ts error
}
return this.concatSeriesDatapoints(seriesForPointType);
}
private concatSeriesDatapoints(series: ScatterData[]): number[][] {
// return type row: [ 0:y, 1:x, 2?:custom value, last:serieIdx ]
private concatSeriesDatapoints(series: ScatterData[]): DelaunayDataRow[] {
const datapointsList = _.map(series, serie => {
const serieIdx = this.getSerieIdxByTarget(serie.target);
const datapointsWithOptions = _.map(serie.datapoints, row => _.concat(row, serieIdx));
const datapointsWithOptions = _.map(serie.datapoints, (row, rowIdx) => [row[0], row[1], row[2] || null, rowIdx, serie.target]);
return datapointsWithOptions;
});
return _.union(...datapointsList);
}
private getSerieIdxByTarget(target: string): number {
const idx = _.findIndex(this.series, serie => serie.target === target);
if(idx === -1) {
throw new Error(`Can't find serie with target: ${target}`);
}
return idx;
}
}

26
src/models/scatter_series.ts

@ -0,0 +1,26 @@
import { CoreSeries } from '@chartwerk/core';
import { ScatterData, PointType, LineType, ScatterDataParams } from '../types';
import * as _ from 'lodash';
const DEFAULT_POINT_SIZE = 4;
const SCATTER_DATA_DEFAULTS: ScatterDataParams = {
pointType: PointType.CIRCLE,
lineType: LineType.NONE,
pointSize: DEFAULT_POINT_SIZE,
colorFormatter: undefined,
clickCallback: undefined,
};
export class ScatterSeries extends CoreSeries<ScatterData> {
constructor(series: ScatterData[]) {
super(series, _.cloneDeep(SCATTER_DATA_DEFAULTS));
}
// move to parent
public getSerieByTarget(target: string): ScatterData | undefined {
return _.find(this.visibleSeries, serie => serie.target === target);
}
}

43
src/types.ts

@ -1,18 +1,18 @@
import { TimeSerie, Options } from '@chartwerk/core';
import { Serie, Options } from '@chartwerk/core';
type ScatterDataParams = {
export type ScatterDataParams = {
pointType: PointType;
lineType: LineType;
pointSize: number;
colorFormatter?: ColorFormatter
colorFormatter?: ColorFormatter;
clickCallback?: ( metricData: { target: Target, class: string, alias: string }, pointData?: DelaunayDataRow) => void;
}
type ScatterOptionsParams = {
// TODO: this options is not used anywhere, let's remove it
voronoiRadius: number;
circleView: boolean;
renderGrid: boolean;
}
export type ScatterData = TimeSerie & Partial<ScatterDataParams>;
export type ScatterData = Serie & Partial<ScatterDataParams>;
export type ScatterOptions = Options & Partial<ScatterOptionsParams>;
export enum PointType {
@ -27,4 +27,33 @@ export enum LineType {
DASHED = 'dashed'
}
export type ColorFormatter = (datapoint: number[]) => string;
export type ColorFormatter = (datapointsRow: any[], pointIdx) => string;
export type MouseMoveEvent = {
bbox: {
clientX: number,
clientY: number,
x: number,
y: number,
chartWidth: number,
chartHeight: number,
},
data: {
xval: number,
yval: number,
highlighted?: HighlightedData,
}
}
export type HighlightedData = {
xValue: number, yValue: number, customValue: number,
pointIdx: number, totalPointIdx: number,
serieInfo: { target: string, alias?: string, class?: string, idx?: number }
}
type Value = number;
type PointIdx = number;
type Target = string;
// type row: [ 0:x, 1:y, 2:(custom value | null), 3:pointIdx, 4:serie.target ]
export type DelaunayDataRow = [Value, Value, Value | null, PointIdx, Target];

3
tsconfig.json

@ -18,5 +18,6 @@
"noImplicitAny": false,
"noUnusedLocals": false,
"baseUrl": "./src"
}
},
"include": ["src/**/*"]
}

2155
yarn.lock

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save