Compare commits

..

4 Commits

Author SHA1 Message Date
glitch4347 328b6f7b1f rename 9 months ago
glitch4347 e901f51c16 import line-pod from .. 9 months ago
glitch4347 fbc412fee4 poty vue folder 9 months ago
glitch4347 5bea7eebd4 extract to vue folder 9 months ago
  1. 2
      .gitignore
  2. 11
      README.md
  3. 4
      build/webpack.base.conf.js
  4. 42
      examples/area.html
  5. 0
      examples/demo.html
  6. 0
      examples/demo_live.html
  7. 0
      examples/demo_vertical.html
  8. 19
      examples/markers.html
  9. 12
      examples/markers_select.html
  10. 33
      examples/right_click.html
  11. 9
      examples/segments.html
  12. 46
      examples/segments_select.html
  13. 37
      examples/zoom_out.html
  14. 11
      package.json
  15. 3
      react/ChartwerkLinePod.tsx
  16. 26
      react/build/webpack.base.conf.js
  17. 8
      react/build/webpack.dev.conf.js
  18. 6
      react/build/webpack.prod.conf.js
  19. 23
      react/package.json
  20. 23
      react/tsconfig.json
  21. 1322
      react/yarn.lock
  22. 144
      src/components/markers.ts
  23. 48
      src/components/segments.ts
  24. 184
      src/index.ts
  25. 4
      src/models/line_series.ts
  26. 12
      src/models/marker.ts
  27. 9
      src/models/segment.ts
  28. 28
      src/types.ts
  29. 3
      tsconfig.json
  30. 33
      vue/VueChartwerkLinePod.ts
  31. 10
      yarn.lock

2
.gitignore vendored

@ -2,7 +2,7 @@ node_modules
dist dist
# yarn # yarn
.yarn .yarn/*
!.yarn/patches !.yarn/patches
!.yarn/plugins !.yarn/plugins
!.yarn/releases !.yarn/releases

11
README.md

@ -19,11 +19,12 @@
``` ```
#### Other examples #### Other examples
* [Basic](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/basic.html) [Static Chart](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/demo.html)
* [Live](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/live.html)
* [Vertical](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/vertical.html) [Live Chart](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/demo_live.html)
* [Segments](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/segments.html)
* [Markers](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/markers.html) [Vertical Chart](https://code.corpglory.net/chartwerk/line-pod/src/branch/main/examples/demo_vertical.html)
### Development ### Development

4
build/webpack.base.conf.js

@ -12,8 +12,8 @@ module.exports = {
plugins: [ plugins: [
new CopyPlugin({ new CopyPlugin({
patterns: [ patterns: [
{ from: "../react/dist/index.js", to: "react/index.js" }, { from: "../react", to: "react" },
{ from: "../react/dist/index.d.ts", to: "react/index.d.ts" }, { from: "../vue", to: "vue" },
], ],
}) })
], ],

42
examples/area.html

@ -1,42 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="../dist/index.dev.js" type="text/javascript"></script>
</head>
<body>
<div id="chart" style="width: 50%; height: 500px;"></div>
<script type="text/javascript">
let options = {
renderLegend: false, usePanning: false,
axis: {
x: { format: 'numeric', range: [0, 100] },
y: { invert: true, range: [0, 100] },
y1: { isActive: true, format: 'numeric', range: [0, 1000] },
},
zoomEvents: {
mouse: { zoom: { isActive: false, orientation: 'horizontal' } },
scroll: { zoom: { isActive: false, orientation: 'horizontal' } }
},
}
const data1 = [[0,0], [35, 40], [65, 60], [100, 100]];
const data2 = [[0,0], [35, 50], [65, 65], [80, 100]];
const data3 = [[0,0], [35, 20], [65, 50], [100, 80]];
const data4 = [[0,900], [35, 800], [65, 700], [100, 600]];
var pod = new LinePod(
document.getElementById('chart'),
[
{ target: 'test1', datapoints: data1, color: 'green', renderArea: 'Above' },
{ target: 'test2', datapoints: data2, color: 'blue', renderArea: 'Below' },
{ target: 'test3', datapoints: data3, color: 'orange', renderArea: 'Below', yOrientation: 'right' },
{ target: 'test4', datapoints: data4, color: 'purple', renderArea: 'Above', yOrientation: 'right' },
],
options
);
pod.render();
</script>
</body>
</html>

0
examples/basic.html → examples/demo.html

0
examples/live.html → examples/demo_live.html

0
examples/vertical.html → examples/demo_vertical.html

19
examples/markers.html

@ -13,18 +13,9 @@
const startTime = 1701790172908; const startTime = 1701790172908;
const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8] const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8]
.map((el, idx) => [startTime + idx * 1000, el]); .map((el, idx) => [startTime + idx * 1000, el]);
const markersData1 = [3, 6, 9].map(el => ({ // TODO: make this one-dimensinal data when implemented
x: startTime + el * 1000, const markersData1 = [3, 6, 9].map(el => [startTime + el * 1000]);
color: 'red', const markersData2 = [4, 11].map(el => [startTime + el * 1000]);
alwaysDisplay: false,
html: new Date(startTime).toISOString(),
}));
const markersData2 = [4, 11].map(el => ({
x: startTime + el * 1000,
color: 'blue',
alwaysDisplay: true,
html: new Date(startTime).toISOString(),
}));
let options = { let options = {
renderLegend: false, renderLegend: false,
axis: { axis: {
@ -40,8 +31,8 @@
options, options,
{ {
series: [ series: [
{ data: markersData1 }, { data: markersData1, color: 'red' },
{ data: markersData2 }, { data: markersData2, color: 'blue' },
] ]
} }
); );

12
examples/markers_select.html

@ -13,11 +13,11 @@
const startTime = 1701790172908; const startTime = 1701790172908;
const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8] const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8]
.map((el, idx) => [startTime + idx * 1000, el]); .map((el, idx) => [startTime + idx * 1000, el]);
const markersData = [3, 6, 9].map(el => ({ // TODO: make this one-dimensinal data when implemented
x: startTime + el * 1000, const markersData = [3, 6, 9].map(el => [
payload: el, startTime + el * 1000,
color: 'red', { el }
})); ]);
let options = { let options = {
renderLegend: false, renderLegend: false,
axis: { axis: {
@ -33,7 +33,7 @@
options, options,
{ {
series: [ series: [
{ data: markersData }, { data: markersData, color: 'red' },
], ],
events: { events: {
onMouseMove: (el) => { console.log(el); }, onMouseMove: (el) => { console.log(el); },

33
examples/right_click.html

@ -1,33 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="../dist/index.dev.js" type="text/javascript"></script>
</head>
<body>
<div id="chart" style="width: 50%; height: 500px;"></div>
<script type="text/javascript">
const startTime = 1590590148;
const data = Array.from(
{ length: 20 },
(el, idx) => [startTime + idx * 10000, Math.floor(Math.random() * 30)]
);
let options = {
renderLegend: false, usePanning: false,
axis: { y: { range: [0, 50] } },
zoomEvents: { mouse: {
zoom: { isActive: false },
pan: { isActive: false },
} },
eventsCallbacks: { contextMenu: (position) => console.log('contextMenu', position) }
}
var pod = new LinePod(
document.getElementById('chart'),
[{ datapoints: data }],
options
);
pod.render();
</script>
</body>
</html>

9
examples/segments.html

@ -13,7 +13,7 @@
const startTime = 1701790172908; const startTime = 1701790172908;
const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8] const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8]
.map((el, idx) => [startTime + idx * 1000, el]); .map((el, idx) => [startTime + idx * 1000, el]);
const segmentsData = [3, 6, 9].map(el => [startTime + el * 1000, startTime + (el + 1) * 1100]); const segmentsData = [3, 6, 9].map(el => [startTime + el * 1000, startTime + (el + 1) * 1000]);
let options = { let options = {
renderLegend: false, renderLegend: false,
axis: { axis: {
@ -27,12 +27,9 @@
{ datapoints: timeSerieData, color: 'black' }, { datapoints: timeSerieData, color: 'black' },
], ],
options, options,
undefined, [],
[ [
{ { data: segmentsData, color:'#FFE545' }
data: segmentsData,
color:'#FFE545'
}
] ]
); );
pod.render(); pod.render();

46
examples/segments_select.html

@ -1,46 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="../dist/index.dev.js" type="text/javascript"></script>
</head>
<body>
<div id="chart" style="width: 100%; height: 500px;"></div>
<script type="text/javascript">
const startTime = 1701790172908;
const timeSerieData = [5, 6, 3, 7, 5, 6, 8, 4, 5, 6, 4, 3, 5, 7, 8]
.map((el, idx) => [startTime + idx * 1000, el]);
const segmentsData = [3, 6, 9].map(el => [startTime + el * 1000, startTime + (el + 1) * 1100]);
let options = {
renderLegend: false,
axis: {
y: { range: [0, 10] },
x: { format: 'time' }
},
}
var pod = new LinePod(
document.getElementById('chart'),
[
{ datapoints: timeSerieData, color: 'black' },
],
options,
undefined,
[
{
data: segmentsData,
color:'#FFE545',
select: true,
opacity: 0.4,
opacitySelect: 0.8,
onSelect: console.log,
onUnselect: console.log
}
]
);
pod.render();
</script>
</body>
</html>

37
examples/zoom_out.html

@ -1,37 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="../dist/index.dev.js" type="text/javascript"></script>
</head>
<body>
<div id="chart" style="width: 50%; height: 500px;"></div>
<script type="text/javascript">
const startTime = 1590590148;
const data = Array.from(
{ length: 20 },
(el, idx) => [startTime + idx * 10000, Math.floor(Math.random() * 30)]
);
let options = {
renderLegend: false, usePanning: false,
axis: { y: { range: [0, 50] } },
zoomEvents: { mouse: {
zoom: { isActive: true, orientation: "horizontal" },
pan: { isActive: false },
}},
events: {
zoomOut: function(centers, ranges) {
console.log('zoomOut', centers, ranges);
}
}
}
var pod = new LinePod(
document.getElementById('chart'),
[{ datapoints: data }],
options
);
pod.render();
</script>
</body>
</html>

11
package.json

@ -1,13 +1,13 @@
{ {
"name": "@chartwerk/line-pod", "name": "@chartwerk/line-pod",
"version": "0.7.8", "version": "0.6.16",
"description": "Chartwerk line chart", "description": "Chartwerk line chart",
"main": "dist/index.js", "main": "dist/index.js",
"files": [ "files": [
"/dist" "/dist"
], ],
"scripts": { "scripts": {
"build": "rm -rf dist && cd react && yarn build && cd .. && webpack --config build/webpack.prod.conf.js && webpack --config build/webpack.dev.conf.js", "build": "webpack --config build/webpack.prod.conf.js && webpack --config build/webpack.dev.conf.js",
"dev": "webpack --watch --config build/webpack.dev.conf.js", "dev": "webpack --watch --config build/webpack.dev.conf.js",
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"update-core": "yarn up @chartwerk/core && yarn up @chartwerk/core@latest" "update-core": "yarn up @chartwerk/core && yarn up @chartwerk/core@latest"
@ -19,7 +19,7 @@
"author": "CorpGlory", "author": "CorpGlory",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"@chartwerk/core": "^0.6.26" "@chartwerk/core": "^0.6.21"
}, },
"devDependencies": { "devDependencies": {
"copy-webpack-plugin": "^11.0.0", "copy-webpack-plugin": "^11.0.0",
@ -30,8 +30,5 @@
"webpack": "^5.87.0", "webpack": "^5.87.0",
"webpack-cli": "^5.1.4" "webpack-cli": "^5.1.4"
}, },
"packageManager": "yarn@3.2.1", "packageManager": "yarn@3.2.1"
"workspaces": [
"react/*"
]
} }

3
react/src/index.tsx → react/ChartwerkLinePod.tsx

@ -2,7 +2,7 @@ import { LineTimeSerie, LineOptions, LinePod } from '@chartwerk/line-pod';
import { MarkersConf } from '@chartwerk/line-pod/dist/models/marker'; import { MarkersConf } from '@chartwerk/line-pod/dist/models/marker';
import { SegmentSerie } from '@chartwerk/line-pod/dist/models/segment'; import { SegmentSerie } from '@chartwerk/line-pod/dist/models/segment';
import React, { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import _ from 'lodash'; import _ from 'lodash';
@ -66,6 +66,7 @@ export function ChartwerkLinePod(props: ChartwerkLinePodProps) {
} }
}, 1); }, 1);
return ( return (
<div id={props.id} className={props.className} ref={chartRef}></div> <div id={props.id} className={props.className} ref={chartRef}></div>
); );

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

@ -1,26 +0,0 @@
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/line-pod', 'react'
]
};

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

@ -1,8 +0,0 @@
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

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

23
react/package.json

@ -1,23 +0,0 @@
{
"name": "line-pod-react",
"version": "0.0.1",
"description": "React wrapper around line-pod",
"main": "dist/index.js",
"repository": "http://code.corpglory.net/chartwerk/line-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/line-pod": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"ts-loader": "^9.5.1",
"typescript": "^5.4.3",
"webpack": "^5.87.0"
}
}

23
react/tsconfig.json

@ -1,23 +0,0 @@
{
"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

144
src/components/markers.ts

@ -1,92 +1,33 @@
import { MarkerElem, MarkersConf, MarkerSerie } from '../models/marker'; import { MarkersConf, MarkerSerie } from "../models/marker";
import { LineTimeSerie, LineOptions } from '../types'; import { PodState } from "@chartwerk/core";
import { LineTimeSerie, LineOptions } from "../types";
import { Margin, PodState } from '@chartwerk/core'; import d3 from "d3";
import d3 from 'd3';
export class Markers { export class Markers {
private _layerContainer = null; // TODO: more semantic name
private _chartHeight = 0; private _d3Holder = null;
constructor(
private _chartContainer: d3.Selection<HTMLElement, unknown, null, undefined>,
private _markerConf: MarkersConf,
private _state: PodState<LineTimeSerie, LineOptions>,
private _margin: Margin,
) { }
clear() {
if(this._layerContainer !== null) {
this._layerContainer.remove();
}
this._chartContainer.selectAll('.marker-content').remove();
}
render(metricContainer: d3.Selection<SVGGElement, unknown, null, undefined>, chartHeight: number) { constructor(private _markerConf: MarkersConf, private _state: PodState<LineTimeSerie, LineOptions>) {
this._chartHeight = chartHeight;
this._layerContainer = metricContainer
.append('g')
.attr('class', 'markers-layer');
for(const serie of this._markerConf.series) {
this.renderSerie(serie);
}
}
private _getLinePosition(marker: MarkerElem): number {
return this._state.xScale(marker.x);
} }
private _renderCircle(marker: MarkerElem) { render(metricContainer: d3.Selection<SVGGElement, unknown, null, undefined>) {
const linePosition = this._getLinePosition(marker); if(this._d3Holder !== null) {
this._d3Holder.remove();
let circle = this._layerContainer.append('circle')
.attr('class', 'gap-circle')
.attr('stroke', marker.color)
.attr('stroke-width', '2px')
.attr('r', 4)
.attr('cx', linePosition)
.attr('cy', 5)
circle
.attr('pointer-events', 'all')
.style('cursor', 'pointer')
.on('mousemove', () => {
const onMouseMove = this._markerConf.events?.onMouseMove;
if(onMouseMove) {
onMouseMove(marker);
return
}
if(marker.alwaysDisplay) {
return;
}
this._chartContainer
.selectAll(`.marker-content-${marker.x}`)
.style('visibility', 'visible')
.style('z-index', 9999);
})
.on('mouseout', () => {
const onMouseOut = this._markerConf.events?.onMouseOut;
if(onMouseOut) {
onMouseOut()
return
} }
if(marker.alwaysDisplay) { this._d3Holder = metricContainer.append('g').attr('class', 'markers-layer');
return; for (const ms of this._markerConf.series) {
this.renderSerie(ms);
} }
this._chartContainer
.selectAll(`.marker-content-${marker.x}`)
.style('visibility', 'hidden')
.style('z-index', 1);
});
} }
private _renderLine(marker: MarkerElem) { protected renderSerie(serie: MarkerSerie) {
const linePosition = this._getLinePosition(marker); serie.data.forEach((d) => {
let linePosition = this._state.xScale(d[0]) as number;
this._layerContainer.append('line') this._d3Holder.append('line')
.attr('class', 'gap-line') .attr('class', 'gap-line')
.attr('stroke', marker.color) .attr('stroke', serie.color)
.attr('stroke-width', '1px') .attr('stroke-width', '1px')
.attr('stroke-opacity', '0.3') .attr('stroke-opacity', '0.3')
.attr('stroke-dasharray', '4') .attr('stroke-dasharray', '4')
@ -96,44 +37,23 @@ export class Markers {
// @ts-ignore // TODO: remove ignore but boxParams are protected // @ts-ignore // TODO: remove ignore but boxParams are protected
.attr('y2', this._state.boxParams.height) .attr('y2', this._state.boxParams.height)
.attr('pointer-events', 'none'); .attr('pointer-events', 'none');
} let circle = this._d3Holder.append('circle')
.attr('class', 'gap-circle')
private _renderTooltip(marker: MarkerElem) { .attr('stroke', serie.color)
if(marker.html === undefined) { .attr('stroke-width', '2px')
return; .attr('r', 4)
} .attr('cx', linePosition)
.attr('cy', 5)
const linePosition = this._getLinePosition(marker);
const div = this._chartContainer
.append('div')
.attr('class', `marker-content marker-content-${marker.x}`)
// @ts-ignore // TODO: remove ignore but boxParams are protected
.style('top', `${this._state.boxParams.height - this._chartHeight}px`)
.style('visibility', marker.alwaysDisplay ? 'visible' : 'hidden')
.style('position', 'absolute')
.style('border', '1px solid black')
.style('background-color', 'rgb(33, 37, 41)')
.style('color', 'rgb(255, 255, 255)')
.style('line-height', '1.55')
.style('font-size', '0.875rem')
.style('border-radius', '0.5rem')
.style('padding', 'calc(0.3125rem) 0.625rem')
.style('position', 'absolute')
.style('white-space', 'nowrap')
.style('pointer-events', 'none')
.style('z-index', 1)
.html(marker.html);
// align tooltip: center (we need it to be rendered first) if(this._markerConf !== undefined) {
div.style('left', `${linePosition + this._margin.left - div.node().getBoundingClientRect().width / 2}px`) circle
.attr('pointer-events', 'all')
.style('cursor', 'pointer')
.on('mousemove', () => this._markerConf.events.onMouseMove(d))
.on('mouseout', () => this._markerConf.events.onMouseOut())
} }
protected renderSerie(serie: MarkerSerie) {
serie.data.forEach((marker: MarkerElem) => {
this._renderLine(marker);
this._renderCircle(marker);
this._renderTooltip(marker);
}); });
} }
} }

48
src/components/segments.ts

@ -1,44 +1,34 @@
import { SegmentSerie, SegmentElement } from "../models/segment"; import { SegmentSerie } from "../models/segment";
import { PodState } from "@chartwerk/core"; import { PodState } from "@chartwerk/core";
import { LineTimeSerie, LineOptions } from "../types"; import { LineTimeSerie, LineOptions } from "../types";
import * as d3 from "d3"; import d3 from "d3";
const OPACITY = 0.3;
const OPACITY_SELECT = 0.3;
export class Segments { export class Segments {
// TODO: more semantic name // TODO: more semantic name
private _d3Holder = null; private _d3Holder = null;
private _metricCon = null;
constructor( constructor(private _series: SegmentSerie[], private _state: PodState<LineTimeSerie, LineOptions>) {
private _series: SegmentSerie[],
private _state: PodState<LineTimeSerie, LineOptions>
) {
} }
render(metricContainer: d3.Selection<SVGGElement, unknown, null, undefined>, chartContainer: d3.Selection<SVGGElement, unknown, null, undefined>) { render(metricContainer: d3.Selection<SVGGElement, unknown, null, undefined>) {
if(this._d3Holder !== null) { if(this._d3Holder !== null) {
this._d3Holder.remove(); this._d3Holder.remove();
} }
this._d3Holder = metricContainer.append('g').attr('class', 'markers-layer'); this._d3Holder = metricContainer.append('g').attr('class', 'markers-layer');
for (const s of this._series) { for (const s of this._series) {
this.renderSerie(chartContainer, s); this.renderSerie(s);
} }
} }
protected renderSerie(chartContainer: d3.Selection<SVGGElement, unknown, null, undefined>, serie: SegmentSerie) { protected renderSerie(serie: SegmentSerie) {
// TODO: it's hack with core, need to find a better way
const overlay = chartContainer.select('.overlay');
serie.data.forEach((d) => { serie.data.forEach((d) => {
// @ts-ignore // @ts-ignore
const startPositionX = this._state.xScale(d[0]) as number; const startPositionX = this._state.xScale(d[0]) as number;
// @ts-ignore // @ts-ignore
const endPositionX = this._state.xScale(d[1]) as number; const endPositionX = this._state.xScale(d[1]) as number;
const width = endPositionX - startPositionX // Math.max(endPositionX - startPositionX, MIMIMUM_SEGMENT_WIDTH); const width = endPositionX - startPositionX // Math.max(endPositionX - startPositionX, MIMIMUM_SEGMENT_WIDTH);
const opacity = serie.opacity || OPACITY;
const opacitySelect = serie.opacitySelect || OPACITY_SELECT;
this._d3Holder.append('rect') this._d3Holder.append('rect')
.attr('class', 'segment') .attr('class', 'segment')
.attr('x', startPositionX) .attr('x', startPositionX)
@ -46,28 +36,10 @@ export class Segments {
.attr('width', width) .attr('width', width)
// @ts-ignore // TODO: remove ignore but boxParams are protected // @ts-ignore // TODO: remove ignore but boxParams are protected
.attr('height', this._state.boxParams.height) .attr('height', this._state.boxParams.height)
.attr('opacity', opacity) .attr('opacity', 0.3)
.style('fill', serie.color) .style('fill', serie.color)
.on('mouseover', function() { .style('pointer-events', 'none');
if(serie.select === true) {
d3.select(this).attr('opacity', opacitySelect);
if(serie.onSelect) {
serie.onSelect(d);
}
}
})
.on('mouseout', function(e) {
if(serie.select === true) {
d3.select(this).attr('opacity', opacity);
if(serie.onUnselect) {
serie.onUnselect(d);
}
}
})
.on('mousemove', function(e) {
var event = new MouseEvent('mousemove', d3.event);
overlay.node().dispatchEvent(event)
})
}); });
} }
} }

184
src/index.ts

@ -1,5 +1,5 @@
import { ChartwerkPod, VueChartwerkPodMixin, TimeFormat, CrosshairOrientation, BrushOrientation, yAxisOrientation } from '@chartwerk/core'; import { ChartwerkPod, TimeFormat, CrosshairOrientation, BrushOrientation, yAxisOrientation } from '@chartwerk/core';
import { LineTimeSerie, LineOptions, MouseObj, AreaType } from './types'; import { LineTimeSerie, LineOptions, MouseObj } from './types';
import { Markers } from './components/markers'; import { Markers } from './components/markers';
import { Segments } from './components/segments'; import { Segments } from './components/segments';
@ -14,9 +14,14 @@ const METRIC_CIRCLE_RADIUS = 1.5;
const CROSSHAIR_CIRCLE_RADIUS = 3; const CROSSHAIR_CIRCLE_RADIUS = 3;
const CROSSHAIR_BACKGROUND_RAIDUS = 9; const CROSSHAIR_BACKGROUND_RAIDUS = 9;
const CROSSHAIR_BACKGROUND_OPACITY = 0.3; const CROSSHAIR_BACKGROUND_OPACITY = 0.3;
type Generator = d3.Line<[number, number]> | d3.Area<[number, number]>;
class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> { class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> {
lineGenerator = null;
areaGenerator = null;
lineGeneratorY1 = null;
areaGeneratorY1 = null;
private _markersLayer: Markers = null; private _markersLayer: Markers = null;
private _segmentsLayer: Segments = null; private _segmentsLayer: Segments = null;
@ -35,70 +40,55 @@ class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> {
this.clearAllMetrics(); this.clearAllMetrics();
this.updateCrosshair(); this.updateCrosshair();
this.updateEvents(); this.initLineGenerator();
this.initAreaGenerator();
if(!this.series.isSeriesAvailable) { if(!this.series.isSeriesAvailable) {
this.renderNoDataPointsMessage(); this.renderNoDataPointsMessage();
return; return;
} }
for(const serie of this.series.visibleSeries) { for(const serie of this.series.visibleSeries) {
const generator = this.getRenderGenerator(serie.renderArea, serie.yOrientation); this._renderMetric(serie);
this._renderMetric(serie, generator);
} }
if(!_.isEmpty(this._markersConf)) { if(this._markersConf !== undefined) {
this._markersLayer = new Markers(this.d3Node, this._markersConf, this.state, this.margin); this._markersLayer = new Markers(this._markersConf, this.state);
this._markersLayer.render(this.metricContainer, this.height); this._markersLayer.render(this.metricContainer);
} }
if(!_.isEmpty(this._segmentSeries)) {
this._segmentsLayer = new Segments(this._segmentSeries, this.state); this._segmentsLayer = new Segments(this._segmentSeries, this.state);
this._segmentsLayer.render(this.metricContainer, this.chartContainer); this._segmentsLayer.render(this.metricContainer);
}
} }
clearAllMetrics(): void { clearAllMetrics(): void {
// TODO: temporary hack before it will be implemented in core. // TODO: temporary hack before it will be implemented in core.
this.chartContainer.selectAll('.metric-el').remove(); this.chartContainer.selectAll('.metric-el').remove();
this._markersLayer?.clear();
} }
protected updateEvents(): void { initLineGenerator(): void {
// overlay - core component that is used to handle mouse events this.lineGenerator = d3.line()
if(!this.overlay) { .x(d => this.state.xScale(d[0]))
return; .y(d => this.state.yScale(d[1]));
} this.lineGeneratorY1 = d3.line()
if(this.options._options.events?.contextMenu === undefined) { .x(d => this.state.xScale(d[0]))
return; .y(d => this.state.y1Scale(d[1]));
}
this.overlay.on('contextmenu', this.onContextMenu.bind(this));
} }
getRenderGenerator(renderArea: AreaType, yOrientation: yAxisOrientation): Generator { initAreaGenerator(): void {
const yScale = yOrientation === yAxisOrientation.LEFT ? this.state.yScale : this.state.y1Scale; this.areaGenerator = d3.area()
const yValueRange = yOrientation === yAxisOrientation.LEFT ? this.state.yValueRange : this.state.y1ValueRange;
const yAxisOptions = yOrientation === yAxisOrientation.LEFT ? this.options.axis.y : this.options.axis.y1;
const topChartBorder = !yAxisOptions.invert ? yScale(yValueRange[1]) : yScale(yValueRange[0]);
const bottomChartBorder = !yAxisOptions.invert ? yScale(yValueRange[0]) : yScale(yValueRange[1]);
switch(renderArea) {
case AreaType.NONE:
// return line generator
return d3.line()
.x(d => this.state.xScale(d[0])) .x(d => this.state.xScale(d[0]))
.y(d => yScale(d[1])); .y1(d => this.state.yScale(d[1]))
case AreaType.ABOVE: .y0(d => this.height);
return d3.area() this.areaGeneratorY1 = d3.area()
.x(d => this.state.xScale(d[0])) .x(d => this.state.xScale(d[0]))
.y0(topChartBorder) .y1(d => this.state.y1Scale(d[1]))
.y1(d => yScale(d[1])); .y0(d => this.height);
case AreaType.BELOW:
return d3.area()
.x(d => this.state.xScale(d[0]))
.y0(d => yScale(d[1]))
.y1(bottomChartBorder);
default:
throw new Error(`Unknown type of renderArea: ${renderArea}`);
} }
getRenderGenerator(renderArea: boolean, yOrientation: yAxisOrientation): any {
if(renderArea) {
return yOrientation === yAxisOrientation.LEFT ? this.areaGenerator : this.areaGeneratorY1;
}
return yOrientation === yAxisOrientation.LEFT ? this.lineGenerator : this.areaGeneratorY1;
} }
_renderDots(serie: LineTimeSerie): void { _renderDots(serie: LineTimeSerie): void {
@ -111,12 +101,12 @@ class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> {
.attr('r', METRIC_CIRCLE_RADIUS) .attr('r', METRIC_CIRCLE_RADIUS)
.style('pointer-events', 'none') .style('pointer-events', 'none')
.attr('cx', d => this.state.xScale(d[0])) .attr('cx', d => this.state.xScale(d[0]))
.attr('cy', d => this.state.getYScaleByOrientation(serie.yOrientation)(d[1])); .attr('cy', d => this.state.yScale(d[1]));
} }
_renderLines(serie: LineTimeSerie, generator: Generator): void { _renderLines(serie: LineTimeSerie): void {
const fillColor = serie.renderArea !== AreaType.NONE ? serie.color : 'none'; const fillColor = serie.renderArea ? serie.color : 'none';
const fillOpacity = serie.renderArea !== AreaType.NONE ? 0.5 : 'none'; const fillOpacity = serie.renderArea ? 0.5 : 'none';
this.metricContainer this.metricContainer
.append('path') .append('path')
@ -129,12 +119,12 @@ class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> {
.attr('stroke-opacity', 0.7) .attr('stroke-opacity', 0.7)
.attr('pointer-events', 'none') .attr('pointer-events', 'none')
.style('stroke-dasharray', serie.dashArray) .style('stroke-dasharray', serie.dashArray)
.attr('d', generator); .attr('d', this.getRenderGenerator(serie.renderArea, serie.yOrientation));
} }
_renderMetric(serie: LineTimeSerie, generator: Generator): void { _renderMetric(serie: LineTimeSerie): void {
if(serie.renderLines === true) { if(serie.renderLines === true) {
this._renderLines(serie, generator); this._renderLines(serie);
} }
if(serie.renderDots === true) { if(serie.renderDots === true) {
@ -453,94 +443,8 @@ class LinePod extends ChartwerkPod<LineTimeSerie, LineOptions> {
x: xAxisMiddleValue, x: xAxisMiddleValue,
y: yAxisMiddleValue y: yAxisMiddleValue
} }
this.options.callbackZoomOut(centers);
// TODO: refactor core not to take _options explicitly
if(
this.options._options.events !== undefined &&
this.options._options.events.zoomOut !== undefined
) {
this.options._options.events.zoomOut(
centers,
[this.state.xValueRange, this.state.yValueRange]
);
}
}
protected onContextMenu(): void {
d3.event.preventDefault(); // do not open browser's context menu.
const eventX = d3.mouse(this.chartContainer.node())[0];
const eventY = d3.mouse(this.chartContainer.node())[1];
this.options._options.events.contextMenu({
x: this.state.xScale.invert(eventX),
y: this.state.yScale.invert(eventY),
});
}
// override parent updateData method to provide markers and segments
protected updateLineData(
series?: LineTimeSerie[],
options?: LineOptions,
markersConf?: MarkersConf,
segments?: SegmentSerie[],
shouldRerender = true
): void {
this.updateMarkers(markersConf);
this.updateSegments(segments);
this.updateData(series, options, shouldRerender);
}
}
// TODO: it should be moved to VUE folder
// it is used with Vue.component, e.g.: Vue.component('chartwerk-line-pod', VueChartwerkLinePod)
export const VueChartwerkLinePod = {
// alternative to `template: '<div class="chartwerk-line-pod" :id="id" />'`
props: {
markersConf: {
type: Object,
required: false,
default: function() { return {}; }
},
segments: {
type: Array,
required: false,
default: function() { return []; }
},
},
watch: {
markersConf() {
this.renderChart();
},
segments() {
this.renderChart();
},
},
render(createElement) {
return createElement(
'div',
{
class: { 'chartwerk-line-pod': true },
attrs: { id: this.id }
}
);
},
mixins: [VueChartwerkPodMixin],
methods: {
render() {
if(this.pod === undefined) {
this.pod = new LinePod(document.getElementById(this.id), this.series, this.options, this.markersConf, this.segments);
this.pod.render();
} else {
this.pod.updateLineData(this.series, this.options, this.markersConf, this.segments);
} }
},
renderSharedCrosshair(values) {
this.pod.renderSharedCrosshair(values);
},
hideSharedCrosshair() {
this.pod.hideSharedCrosshair();
} }
}
};
export { LineTimeSerie, LineOptions, TimeFormat, LinePod, AreaType, MarkersConf, SegmentSerie }; export { LineTimeSerie, LineOptions, TimeFormat, LinePod };

4
src/models/line_series.ts

@ -1,5 +1,5 @@
import { CoreSeries, yAxisOrientation } from '@chartwerk/core'; import { CoreSeries, yAxisOrientation } from '@chartwerk/core';
import { LineTimeSerie, AreaType } from '../types'; import { LineTimeSerie } from '../types';
import * as _ from 'lodash'; import * as _ from 'lodash';
@ -10,7 +10,7 @@ const LINE_SERIE_DEFAULTS = {
renderLines: true, renderLines: true,
dashArray: '0', dashArray: '0',
class: '', class: '',
renderArea: AreaType.NONE, renderArea: false,
yOrientation: yAxisOrientation.LEFT, yOrientation: yAxisOrientation.LEFT,
}; };

12
src/models/marker.ts

@ -1,13 +1,9 @@
export type MarkerElem = { export type MarkerElem = [number, any?];
x: number;
color: string;
html?: string;
alwaysDisplay?: boolean;
payload?: any;
}
export type MarkerSerie = { export type MarkerSerie = {
data: MarkerElem[]; color: string;
// TODO: make one-dimensional array with only x
data: MarkerElem[] // [x, payload] payload is any data for tooltip
} }
export type MarkersConf = { export type MarkersConf = {

9
src/models/segment.ts

@ -1,11 +1,4 @@
export type SegmentElement = [number, number, any?];
export type SegmentSerie = { export type SegmentSerie = {
color: string; color: string;
data: SegmentElement[] // [from, to, payload?] payload is any data for tooltip, data: [number, number, any?][] // [from, to, payload?] payload is any data for tooltip
select?: boolean,
opacity?: number,
opacitySelect?: number,
onSelect?: (SegmentElement) => void
onUnselect?: (SegmentElement) => void
} }

28
src/types.ts

@ -1,34 +1,16 @@
import { Serie, Options } from '@chartwerk/core'; import { Serie, Options } from '@chartwerk/core';
import { AxisRange } from '@chartwerk/core/dist/types';
type LineTimeSerieParams = { type LineTimeSerieParams = {
maxLength: number; maxLength: number,
renderDots: boolean; renderDots: boolean,
renderLines: boolean; // TODO: refactor same as scatter-pod renderLines: boolean, // TODO: refactor same as scatter-pod
dashArray: string; // dasharray attr, only for lines dashArray: string; // dasharray attr, only for lines
class: string; // option to add custom class to each serie element class: string; // option to add custom class to each serie element
renderArea: AreaType; // default is none renderArea: boolean; // TODO: move to render type
}
export enum AreaType {
NONE = 'None',
ABOVE = 'Above',
BELOW = 'Below',
} }
export type LineTimeSerie = Serie & Partial<LineTimeSerieParams>; export type LineTimeSerie = Serie & Partial<LineTimeSerieParams>;
export type LineOptions = Options & { export type LineOptions = Options;
events? : {
zoomOut?: (centers: {
x: number;
y: number;
}, range: AxisRange[]) => void;
contextMenu?: (position: {
x: number;
y: number;
}) => void;
}
}
export type MouseObj = { export type MouseObj = {
x: number, x: number,

3
tsconfig.json

@ -19,5 +19,6 @@
"noUnusedLocals": false, "noUnusedLocals": false,
"baseUrl": "./src", "baseUrl": "./src",
}, },
"include": ["src/**/*"] "include": ["src/**/*"],
"exclude": ["*.tsx"]
} }

33
vue/VueChartwerkLinePod.ts

@ -0,0 +1,33 @@
import { LinePod } from '..';
import { VueChartwerkPodMixin } from '@chartwerk/core';
// it is used with Vue.component, e.g.: Vue.component('chartwerk-line-pod', VueChartwerkLinePod)
export const ChartwerkLinePod = {
// alternative to `template: '<div class="chartwerk-line-pod" :id="id" />'`
render(createElement) {
return createElement(
'div',
{
class: { 'chartwerk-line-pod': true },
attrs: { id: this.id }
}
);
},
mixins: [VueChartwerkPodMixin],
methods: {
render() {
if(this.pod === undefined) {
this.pod = new LinePod(document.getElementById(this.id), this.series, this.options);
this.pod.render();
} else {
this.pod.updateData(this.series, this.options);
}
},
renderSharedCrosshair(values) {
this.pod.renderSharedCrosshair(values);
},
hideSharedCrosshair() {
this.pod.hideSharedCrosshair();
}
}
};

10
yarn.lock

@ -5,13 +5,13 @@ __metadata:
version: 6 version: 6
cacheKey: 8 cacheKey: 8
"@chartwerk/core@npm:^0.6.26": "@chartwerk/core@npm:^0.6.21":
version: 0.6.26 version: 0.6.21
resolution: "@chartwerk/core@npm:0.6.26" resolution: "@chartwerk/core@npm:0.6.21"
dependencies: dependencies:
d3: ^5.16.0 d3: ^5.16.0
lodash: ^4.17.21 lodash: ^4.17.21
checksum: d77ef83701dc13cf2b7fb36dc96448060b6301928bcc0730a7150930f83c51f295e176bcda4e1b8cb8f56d15fef5696edfe6f4e1033adbb5ef5d3487a02c3390 checksum: c536eca30241e775d4d4cfed4d54fd64c2f0299e792056166c90e50e11d9b698b1736b9c0dbf6ec6ea30fecd676f0012c774ff91a1d184eaee00c71b5d9e3925
languageName: node languageName: node
linkType: hard linkType: hard
@ -19,7 +19,7 @@ __metadata:
version: 0.0.0-use.local version: 0.0.0-use.local
resolution: "@chartwerk/line-pod@workspace:." resolution: "@chartwerk/line-pod@workspace:."
dependencies: dependencies:
"@chartwerk/core": ^0.6.26 "@chartwerk/core": ^0.6.21
copy-webpack-plugin: ^11.0.0 copy-webpack-plugin: ^11.0.0
css-loader: ^6.8.1 css-loader: ^6.8.1
style-loader: ^3.3.3 style-loader: ^3.3.3

Loading…
Cancel
Save