Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] added closest area and line strategies for tooltip tracking #170

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions demo/examples/tooltip-tracking-strategies.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<html>
<head>
<title>Yagr</title>
<script src="../../dist/yagr.iife.js"></script>
<script src="../helpers.js"></script>
<link rel="stylesheet" href="../../dist/index.css" />
<style>
.container {
margin-bottom: 26px;
height: 400px;
}
#root {
display: grid;
grid-gap: 12px;
grid-template-columns: 1fr 1fr;
}
</style>
</head>
<body>
<h1>Tooltip tracking strategies</h1>
<div id="root">
<div id="chart1" class="container"></div>
<div id="chart2" class="container"></div>
<div id="chart3" class="container"></div>
<div id="chart4" class="container"></div>
</div>

<script>
const negate = (x) => -x;

new Yagr(chart1, {
title: {
text: 'sticky',
},
timeline: [1, 2, 3, 4],
series: [
{data: [1, 2, 3, 2], color: 'green'},
{data: [2, 1, 1, 3], color: 'red'},
{data: [4, 3, 0.3, 4], color: 'blue'},
{data: [3, 2, 5, 1], color: 'orange'},
],
axes: {
r: {side: 'right'},
y: {},
},
scales: {
r: {},
y: {
max: 0,
transform: negate,
},
},
tooltip: {
tracking: 'sticky',
},
});

new Yagr(chart2, {
title: {
text: 'line-closest',
},
timeline: [1, 2, 3, 4],
series: [
{data: [1, 2, 3, 2], color: 'green'},
{data: [2, 1, 1, 3], color: 'red'},
{data: [4, 3, 0.3, 4], color: 'blue'},
{data: [3, 2, 5, 1], color: 'orange'},
],
axes: {
r: {side: 'right'},
y: {},
},
scales: {
r: {},
y: {
max: 0,
transform: negate,
},
},
tooltip: {
tracking: 'line-closest',
},
});

new Yagr(chart3, {
title: {
text: 'area',
},
chart: {
series: {type: 'area'},
},
scales: {
y: {stacking: true},
},
timeline: [1, 2, 3, 4],
series: [
{data: [4, 3, 0.3, 4], color: 'blue', stackGroup: 0},

{data: [2, 1, 1, 3], color: 'red', transform: negate, name: 'transformed 2', stackGroup: 1},
{data: [1, 2, 3, 2], color: 'green', transform: negate, name: 'transformed 1', stackGroup: 1},

{data: [1, 2, 2, 1], color: 'orange', stackGroup: 0},
],
tooltip: {
tracking: 'area',
sum: false,
},
});

new Yagr(chart4, {
title: {
text: 'area-closest',
},
chart: {
series: {type: 'area'},
},
scales: {
y: {stacking: true},
},
timeline: [1, 2, 3, 4],
series: [
{data: [4, 3, 0.3, 4], color: 'blue', stackGroup: 0},

{data: [2, 1, 1, 3], color: 'red', transform: negate, name: 'transformed 2', stackGroup: 1},
{data: [1, 2, 3, 2], color: 'green', transform: negate, name: 'transformed 1', stackGroup: 1},

{data: [1, 2, 2, 1], color: 'orange', stackGroup: 0},
],
tooltip: {
tracking: 'area-closest',
sum: false,
},
});
</script>
</body>
</html>
69 changes: 54 additions & 15 deletions src/YagrCore/plugins/tooltip/tooltip.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable complexity, no-nested-ternary */

import uPlot, {Series} from 'uplot';
import uPlot, {Series, TypedArray} from 'uplot';

import {CursorOptions} from '../cursor/cursor';
import placementFn from './placement';
Expand All @@ -10,7 +10,7 @@ import {DataSeries, ProcessingInterpolation, YagrPlugin} from '../../types';

import {TOOLTIP_Y_OFFSET, TOOLTIP_X_OFFSET, TOOLTIP_DEFAULT_MAX_LINES, DEFAULT_Y_SCALE} from '../../defaults';

import {findInRange, findDataIdx, findSticky, px, isNil} from '../../utils/common';
import {findDataIdx, findSticky, px, isNil, findInRange} from '../../utils/common';
import {
TooltipOptions,
TooltipRow,
Expand All @@ -25,7 +25,7 @@ import {
} from './types';

import {renderTooltip} from './render';
import {getOptionValue} from './utils';
import {findClosestLines, getOptionValue} from './utils';

// eslint-disable-next-line complexity
const findValue = (
Expand Down Expand Up @@ -397,19 +397,58 @@ class YagrTooltip {
section.rows.push(rowData);
}

if (getOptionValue(opts.highlight, scale) && section.rows.length) {
const tracking = getOptionValue<TrackingOptions>(opts.tracking, scale);
if (getOptionValue(opts.highlight, scale) && section.rows.length && !state.pinned) {
let activeIndex: number | null = 0;
if (tracking === 'area') {
activeIndex = findInRange(
section,
cursorValue,
getOptionValue<boolean | undefined>(opts.stickToRanges, scale),
);
} else if (tracking === 'sticky') {
activeIndex = findSticky(section, cursorValue);
} else if (typeof tracking === 'function') {
activeIndex = tracking(section, cursorValue);
const tracking = getOptionValue<TrackingOptions>(opts.tracking, scale);
const areaSeries = this.yagr.series.filter(
(_, si) => si === 0 || serieIndicies.includes(si),
) as TypedArray[];

switch (tracking) {
case 'area':
activeIndex = findInRange(
section,
cursorValue,
getOptionValue<boolean | undefined>(opts.stickToRanges, scale),
);
break;
case 'sticky':
activeIndex = findSticky(section, cursorValue);
break;
case 'area-closest': {
const lines = findClosestLines({
x: u.posToVal(left, 'x'),
y: u.posToVal(top, scale),
series: areaSeries,
});

if (u.posToVal(top, scale) >= 0) {
activeIndex = lines.higher.index ?? lines.lower.index;
} else {
activeIndex = lines.lower.index ?? lines.higher.index;
}

break;
}
case 'line-closest': {
const lines = findClosestLines({
x: u.posToVal(left, 'x'),
y: u.posToVal(top, scale),
series: areaSeries,
});

if (lines.higher.distance < lines.lower.distance) {
activeIndex = lines.higher.index;
} else {
activeIndex = lines.lower.index;
}

break;
}
default:
if (typeof tracking === 'function') {
activeIndex = tracking(section, cursorValue);
}
}

if (activeIndex !== null) {
Expand Down
4 changes: 4 additions & 0 deletions src/YagrCore/plugins/tooltip/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import Yagr from '../../index';
export type TrackingOptions =
/** Tracks serie only if mouse hovered on series' area */
| 'area'
/** Tracks mouse to closest area */
| 'area-closest'
/** Tracks mouse to closest line */
| 'line-closest'
/** Tracks mouse to closest line near closest timeline */
| 'sticky'
/** Custom tracking function */
| ((s: TooltipSection, y: number) => number | null);
Expand Down
64 changes: 64 additions & 0 deletions src/YagrCore/plugins/tooltip/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {AlignedData} from 'uplot';

export function getOptionValue<T>(option: T | {[key in string]: T}, scale: string): T {
return (typeof option === 'object' ? (option as {[key in string]: T})[scale] : option) as T;
}
Expand All @@ -8,3 +10,65 @@ export function escapeHTML(html: string) {
elem.innerText = html;
return elem.innerHTML;
}

type FindClosestAreaOptions = {
/** cursor X */
x: number;
/** cursor Y */
y: number;
series: AlignedData;
};

export const findClosestLines = ({x, y, series}: FindClosestAreaOptions) => {
Copy link
Collaborator

@zefirka zefirka Oct 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add unit tests for this util, mostly to ensure valid calculation of closest area/line between two X coordinates?

const [timeline, ...areas] = series as number[][];

let i1 = 0,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you can find i1 and i2 with using uplot.cursor.idx or something. I think traversing whole timeline on each setCursor generally is a bad idea, because tooltip.tracking is function which can be called very frequently.

i2 = 0;

// finding current timeline
timeline.forEach((t, i) => {
if (i1 || i2) {
return;
}
if (t === x) {
i1 = i2 = i;
return;
}
if (t > x) {
i1 = i - 1;
i2 = i;
}
});

let minLower = Number.MAX_VALUE,
minHigher = Number.MAX_VALUE;
let iLower: number | null = null,
iHigher: number | null = null;

const x1 = timeline[i1];
const x2 = timeline[i2];

areas
Copy link
Collaborator

@zefirka zefirka Oct 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's try to reduce number of possible iterations. I understand that in most cases it doesn't do any issues, but I'd like to keep calculations as fast as possible.

I mean let's do it in single loop

.map((a) => [a[i1], a[i2]])
.forEach(([y1, y2], i) => {
// finding intersection between line and vertical X = x
const k = (y2 - y1) / (x2 - x1);
const b = y1 - k * x1;
const yInter = k * x + b;

const distance = Math.abs(y - yInter);

if (yInter < y && distance <= minLower) {
minLower = distance;
iLower = i;
} else if (yInter >= y && distance <= minHigher) {
minHigher = distance;
iHigher = i;
}
});

return {
lower: {index: iLower, distance: minLower},
higher: {index: iHigher, distance: minHigher},
};
};
Loading