User/niusoff/horizontal markers (#336)

* added HorizontalMarkers which are passed in via chart data options or swimlane options, which draw a horizontal line at a static y position

* added logic for including markers coming from swimlanes in shared y axis state

* null checks for chartOptions.swimlaneOptions
This commit is contained in:
niusoff 2021-10-06 15:06:58 -07:00 коммит произвёл GitHub
Родитель abf0eb9461
Коммит ecfa35a55e
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
6 изменённых файлов: 355 добавлений и 3 удалений

Просмотреть файл

@ -0,0 +1,231 @@
<!DOCTYPE html>
<html>
<head>
<title>Horizontal markers</title>
<!-- boilerplate headers are injected with head.js, grab them from the live example header, or include a link to head.js -->
<script src="../../boilerplate/head.js"></script>
</head>
<body style="font-family: 'Segoe UI', sans-serif;">
<div id="chart1" style="width: 100%; height: 600px;"></div>
<div>
<label>Show series labels</label>
<input type="checkbox" id="showLabels" />
</div>
<div>
<h2>Lane selections:</h2>
<span>group 0: </span>
<select id='group0Select'>
<option selected>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<br/>
<span>group 1: </span>
<select id='group1Select'>
<option>1</option>
<option selected>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<br/>
<span>group 2: </span>
<select id='group2Select'>
<option>1</option>
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
</select>
<br/>
<span>group 3: </span>
<select id='group3Select'>
<option>1</option>
<option>2</option>
<option>3</option>
<option selected>4</option>
<option>5</option>
</select>
<br/>
<span>group 4: </span>
<select id='group4Select'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option selected>5</option>
</select>
</div>
<script>
window.onload = function() {
// create fake data in the shape our charts expect
let numberOfBuckets = 120;
var data = [];
var from = new Date(Math.floor((new Date()).valueOf() / (1000*60 * 60)) * (1000*60 * 60));
var to;
for(var i = 0; i < 3; i++){
var lines = {};
data.push({[`Factory${i}`]: lines});
var values = {};
lines[``] = values;
for(var k = 0; k < numberOfBuckets; k++){
if (i % 2 === 0) {
// if(!(k%2 && k%3)){ // if check is to create some sparseness in the data
var to = new Date(from.valueOf() + 1000*60*k);
var val = Math.random() + (j !== 4 ? 2 : 0);
var val2 = Math.random();
var val3 = Math.random();
var val4 = Math.random();
values[to.toISOString()] = {avg: val, x: val2, y: val3, r: val4};
// }
} else {
var val1 = Math.random();
if (val1 < .5) {
val1 = 1;
}
var val2 = (1 - val1) / 2;
var val3 = (1 - val1) / 2;
var to = new Date(from.valueOf() + 1000*60*k);
if(Math.random() < .2)
values[to.toISOString()] = {state1: val1, state2: val2, state3: val3};
else
values[to.toISOString()] = null;
}
}
}
var random1Through10 = function () {
return Math.ceil(Math.random() * 10);
}
var lines = {};
var events = {};
data.push({[`Factory3`]: events});
data.push({[`Factory 4`]: lines})
for(var j = 0; j < 1; j++){
var values = {};
lines[`Station${j}`] = values;
events[`Station${j}`] = {};
for(var k = 0; k < numberOfBuckets; k++){
var val1 = Math.random();
var val2 = 1- val1;
var val3 = 0;
if (j === 1) {
val1 = 0;
val2 = 1;
val3 = 0;
}
if (j === 2) {
val1 = 0;
val2 = 0;
val3 = 1;
}
let previousTo = to;
var toLocal = new Date(from.valueOf() + 1000*60*k);
values[toLocal.toISOString()] = {state1: val1, state2: val2, state3: val3};
if (Math.random() > .8) {
let goodOrBad = Math.random() > .5;
let goodAndBad = Math.random() > .8;
let localEvent = {};
events[`Station${j}`][toLocal.toISOString()] = localEvent;
localEvent[goodOrBad ? 'goodEvent' : 'badEvent'] = (goodOrBad ? random1Through10() : random1Through10());
if (goodAndBad) {
localEvent[goodOrBad ? 'badEvent' : 'goodEvent'] = (!goodOrBad ? random1Through10() : random1Through10());
}
if (Math.random() > .7) {
localEvent['neutral Event'] = 'neutral message';
}
}
to = toLocal;
}
}
let searchSpan = {
from: from.toISOString(),
to: new Date(to.valueOf() + 45 * 1000).toISOString(),
bucketSize: '1m'
}
// render the data in a chart
var tsiClient = new TsiClient();
var lineChart = new tsiClient.ux.LineChart(document.getElementById('chart1'));
let valueMapping = {
state1: {
color: '#F2C80F'
},
state2: {
color: '#FD625E'
},
state3: {
color:'#3599B8'
}
}
let eventValueMapping = {
badEvent: {
color: 'red'
},
goodEvent: {
color: 'blue'
}
}
eventValueMapping['neutral Event'] = { color: 'purple' };
var onElementClick = function (aggKey, splitBy, ts, measures) {
console.log(aggKey, splitBy, ts, measures);
}
var horizontalMarkers = [
{color: 'blue', value: 0.1},
{color: 'grey', value: 0.25},
{color: 'grey', value: 0.6},
{color: 'grey', value: 0.750},
{color: 'red', value: 0.9},
]
var chartDataOptions = [{dataType: 'numeric', searchSpan: searchSpan, swimLane: 1},
{dataType: 'numeric', searchSpan: searchSpan, swimLane: 2},
{dataType: 'categorical', valueMapping: valueMapping, height: 50, searchSpan: searchSpan, onElementClick: onElementClick, swimLane: 3},
{dataType: 'events', valueMapping: eventValueMapping, height: 30, eventElementType: 'teardrop', onElementClick: onElementClick, swimLane: 4},
{dataType: 'numeric', searchSpan: searchSpan, onElementClick: onElementClick, swimLane: 5, horizontalMarkers: horizontalMarkers}];
var swimLaneOptions = {
1: {yAxisType: 'shared', horizontalMarkers: [{color: '#000', value: 2.5}, {color: '#AAA', value: 2.8}]},
2: {yAxisType: 'overlap'},
3: {yAxisType: 'overlap'}
}
var chartOptions = {theme: 'light', tooltip: 'true', swimLaneOptions: swimLaneOptions, labelSeriesWithMarker: false};
var renderLinechart = function () {
lineChart.render(data, chartOptions, chartDataOptions);
}
renderLinechart();
function changeSwimLaneAndRender (aggGroup, newSwimLane) {
chartDataOptions[aggGroup].swimLane = newSwimLane;
renderLinechart();
}
function changeShowSeriesLabelsAndRender (shouldChange) {
console.log(shouldChange);
chartOptions.labelSeriesWithMarker = !chartOptions.labelSeriesWithMarker;
renderLinechart();
}
document.getElementById(`group0Select`).onchange = function(evt) { changeSwimLaneAndRender(0, Number(evt.target.value))};
document.getElementById(`group1Select`).onchange = function(evt) { changeSwimLaneAndRender(1, Number(evt.target.value))};
document.getElementById(`group2Select`).onchange = function(evt) { changeSwimLaneAndRender(2, Number(evt.target.value))};
document.getElementById(`group3Select`).onchange = function(evt) { changeSwimLaneAndRender(3, Number(evt.target.value))};
document.getElementById(`group4Select`).onchange = function(evt) { changeSwimLaneAndRender(4, Number(evt.target.value))};
document.getElementById('showLabels').onclick = function(evt) { changeShowSeriesLabelsAndRender(evt.target.checked)}
};
</script>
</body>
</html>

Просмотреть файл

@ -269,6 +269,15 @@
}
}
}
.tsi-horizontalMarkerLine {
stroke-dasharray: 2,2;
}
.tsi-horizontalMarkerText {
font-style: italic;
text-anchor: end;
}
&.tsi-dark{
$grays: grays('dark');

Просмотреть файл

@ -15,6 +15,7 @@ import EventsPlot from '../EventsPlot';
import { AxisState } from '../../Models/AxisState';
import Marker from '../Marker';
import { swimlaneLabelConstants} from '../../Constants/Constants'
import { HorizontalMarker } from '../../Utils/Interfaces';
class LineChart extends TemporalXAxisComponent {
private targetElement: any;
@ -605,7 +606,7 @@ class LineChart extends TemporalXAxisComponent {
marker.render(millis, this.chartOptions, this.chartComponentData, {
chartMargins: this.chartMargins,
x: this.x,
marginLeft: this.getMarkerMarginLeft(),
marginLeft: this.getMarkerMarginLeft() + (isSeriesLabels ? this.getAdditionalOffsetFromHorizontalMargin() : 0),
colorMap: this.colorMap,
yMap: this.yMap,
onChange: onChange,
@ -1267,7 +1268,12 @@ class LineChart extends TemporalXAxisComponent {
this.aggregateExpressionOptions.forEach((aEO) => {
aEO.swimLane = 0;
});
this.chartOptions.swimLaneOptions = {0: {yAxisType: this.chartOptions.yAxisState}};
// consolidate horizontal markers
const horizontalMarkers = [];
Object.values(this.chartOptions.swimLaneOptions).forEach((lane) => {
horizontalMarkers.push(...lane.horizontalMarkers);
});
this.chartOptions.swimLaneOptions = {0: {yAxisType: this.chartOptions.yAxisState, horizontalMarkers: horizontalMarkers}};
} else {
let minimumPresentSwimLane = this.aggregateExpressionOptions.reduce((currMin, aEO) => {
return Math.max(aEO.swimLane, currMin);
@ -1287,6 +1293,102 @@ class LineChart extends TemporalXAxisComponent {
this.chartOptions.swimLaneOptions = this.originalSwimLaneOptions;
}
private getHorizontalMarkersWithYScales () {
let visibleCDOs = this.aggregateExpressionOptions.filter((cDO) => this.chartComponentData.displayState[cDO.aggKey]["visible"]);
const markerList = [];
const pushMarker = (cDO, marker, markerList) => {
if (this.chartOptions.yAxisState === YAxisStates.Overlap) {
return;
}
const domain = this.chartOptions.yAxisState === YAxisStates.Stacked ?
this.swimlaneYExtents[cDO.swimLane] :
this.swimlaneYExtents[0];
// filter out markers not in the y range of that lane and in lanes that have overlap axis
if (domain &&
this.chartOptions.swimLaneOptions?.[cDO.swimLane]?.yAxisType !== YAxisStates.Overlap &&
marker.value >= domain[0] &&
marker.value <= domain[1]) {
markerList.push({yScale: this.yMap[cDO.aggKey], ...marker});
}
}
visibleCDOs.forEach((cDO) => {
cDO.horizontalMarkers.forEach((horizontalMarkerParams: HorizontalMarker) => {
pushMarker(cDO, horizontalMarkerParams, markerList);
});
});
// find a visible CDO for a swimlane
const findFirstVisibleCDO = (swimlaneNumber) => {
return visibleCDOs.find((cDO) => {
return (cDO.swimLane === swimlaneNumber);
});
}
if (this.chartOptions.yAxisState !== YAxisStates.Overlap && this.chartOptions.swimLaneOptions) {
Object.keys(this.chartOptions.swimLaneOptions).forEach((swimlaneNumber) => {
const swimlaneOptions = this.chartOptions.swimLaneOptions[swimlaneNumber];
swimlaneOptions.horizontalMarkers?.forEach((horizontalMarkerParams: HorizontalMarker) => {
const firstVisibleCDO = findFirstVisibleCDO(Number(swimlaneNumber));
if (firstVisibleCDO) {
pushMarker(firstVisibleCDO, horizontalMarkerParams, markerList);
}
});
});
}
return markerList;
}
// having horizontal markers present should add additional right hand margin to allow space for series labels
private getAdditionalOffsetFromHorizontalMargin () {
return this.getHorizontalMarkersWithYScales().length ? 16 : 0;
}
private drawHorizontalMarkers () {
const markerList = this.getHorizontalMarkersWithYScales();
const self = this;
const markerContainers = this.svgSelection.select('.svgGroup').selectAll('.tsi-horizontalMarker')
.data(markerList);
markerContainers
.enter()
.append('g')
.merge(markerContainers)
.attr('class', 'tsi-horizontalMarker')
.attr("transform", (marker) => {
return "translate(" + 0 + "," + marker.yScale(marker.value) + ")";
})
.each(function (marker) {
const valueText = d3.select(this)
.selectAll('.tsi-horizontalMarkerText')
.data([marker.value]);
valueText
.enter()
.append('text')
.merge(valueText)
.attr('class', 'tsi-horizontalMarkerText')
.attr('x', self.chartWidth)
.attr('y', -4)
.text((value) => value);
valueText.exit().remove();
const valueLine = d3.select(this)
.selectAll('.tsi-horizontalMarkerLine')
.data([marker]);
valueLine
.enter()
.append('line')
.merge(valueLine)
.attr('class', 'tsi-horizontalMarkerLine')
.attr('stroke', marker => marker.color)
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', self.chartWidth)
.attr('y2', 0);
valueLine.exit().remove();
});
markerContainers.exit().remove();
}
private createSwimlaneLabels(offsetsAndHeights, visibleCDOs){
// swimLaneLabels object contains data needed to render each lane label
@ -1892,6 +1994,7 @@ class LineChart extends TemporalXAxisComponent {
}
this.renderAllMarkers();
this.drawHorizontalMarkers();
this.voronoiDiagram = this.voronoi(this.getFilteredAndSticky(this.chartComponentData.allValues));
}

Просмотреть файл

@ -1,5 +1,6 @@
import { InterpolationFunctions, DataTypes, EventElementTypes } from "../Constants/Enums";
import Utils from "../Utils";
import { HorizontalMarker } from '../Utils/Interfaces'
const DEFAULT_HEIGHT = 40;
// Represents an expression that is suitable for use as the expression options parameter in a chart component
@ -35,6 +36,7 @@ class ChartDataOptions {
public image: string;
public isRawData: boolean;
public isVariableAliasShownOnTooltip: boolean;
public horizontalMarkers: Array<HorizontalMarker>;
constructor (optionsObject: Object){
this.searchSpan = Utils.getValueOrDefault(optionsObject, 'searchSpan');
@ -67,6 +69,7 @@ class ChartDataOptions {
this.startAt = Utils.getValueOrDefault(optionsObject, 'startAt', null);
this.isRawData = Utils.getValueOrDefault(optionsObject, 'isRawData', false);
this.isVariableAliasShownOnTooltip = Utils.getValueOrDefault(optionsObject, 'isVariableAliasShownOnTooltip', true);
this.horizontalMarkers = Utils.getValueOrDefault(optionsObject, 'horizontalMarkers', []);
}
}
export {ChartDataOptions}

Просмотреть файл

@ -3,13 +3,15 @@ import Utils from '../Utils';
import { Strings } from './Strings';
import { DefaultHierarchyNavigationOptions } from '../Constants/Constants';
import { InterpolationFunctions, YAxisStates } from '../Constants/Enums';
import { HorizontalMarker } from '../Utils/Interfaces';
// Interfaces
interface swimLaneOption {
yAxisType: YAxisStates,
label?: string,
onClick?: (lane: number) => any,
collapseEvents?: string
collapseEvents?: string,
horizontalMarkers?: Array<HorizontalMarker>
}
class ChartOptions {

Просмотреть файл

@ -0,0 +1,4 @@
export interface HorizontalMarker {
color: string,
value: number
}