Skip to content
Closed
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
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ The component is the default export of `@opencor/plot`, and is also exported as
| `PlotData` | `{ traces, xAxisTitle?, yAxisTitle?, xAxisRange?, yAxisRange? }` | The data to plot (see [Data](#data)). |
| `PlotTrace` | `{ name, x, y, xValue, yValue, color, traceId?, legendRank?, runLabel? }` | A trace to plot (see [Data](#data)). |
| `PlotMargins` | `{ left: number; right: number }` | The left and right margins (in pixels) of a plot, i.e. the space taken by its Y axis and legend (see the [`margins`](#props) prop and the [`marginsUpdated`](#events) event). |
| `PlotRanges` | `{ x: [number, number]; y: [number, number] }` | The current ranges of the axes of a plot (even if an axis is logarithmic, see the [`rangesUpdated`](#events) event and the [`setRanges()`](#methods) method). |
| `PlotTheme` | `'system' \| 'light' \| 'dark'` | The value of the [`theme`](#props) prop. |
| `PlotCsvExportEvent` | `PlotCsvExportStartedEvent \| PlotCsvExportProgressEvent \| PlotCsvExportFinishedEvent` | The payload of the [`csvExport`](#events) event. Use its `type` to tell which one it is. |
| `PlotCsvExportStartedEvent` | `{ type: 'started' }` | An export to CSV has started. |
Expand All @@ -96,7 +97,7 @@ The component is the default export of `@opencor/plot`, and is also exported as
|---|---|---|
| `traces` | [`PlotTrace`](#types)`[]` | The traces to plot. |
| `xAxisTitle`, `yAxisTitle` | `string` | The axis titles. |
| `xAxisRange`, `yAxisRange` | `[number, number]` | The range of an axis when the zoom is reset. By default, it fits the data. |
| `xAxisRange`, `yAxisRange` | `[number, number]` | The range of an axis when the zoom is reset. By default, it fits the data. The current ranges can be followed using the [`rangesUpdated`](#events) event and set using the [`setRanges()`](#methods) method. |

[`PlotTrace`](#types):

Expand All @@ -114,6 +115,7 @@ Notes:
- Titles and trace names can contain a little HTML (`b`, `br`, `code`, `em`, `i`, `strong`, `sub`, and `sup`). Anything else is removed.
- A trace can be a function of X (e.g., against time) or not (e.g., a phase plot). A point with a non-finite X or Y value (e.g., `NaN`) is a gap in its trace.
- A trace with fewer than 20 points is also drawn with markers.
- The zoom is kept when the data is updated, unless the axis titles change (i.e. something else is being plotted).

### Large and live data

Expand Down Expand Up @@ -157,6 +159,7 @@ To draw traces without our level of detail, use `:levelOfDetail="false"`. Our pa
| Event | Payload | Description |
|---|---|---|
| `marginsUpdated` | [`PlotMargins`](#types) | The margins that the plot needs have changed. To line up several plots, pass the largest left and right margins of all of them to each plot's [`margins`](#props) prop. |
| `rangesUpdated` | [`PlotRanges`](#types) | The current ranges of the axes have changed (e.g., after zooming, panning, or resetting the zoom, or after the data has been updated while an axis is autoranged). To link the X axes of several plots, pass the `x` range of one of them to the [`setRanges()`](#methods) method of the others. |
| `csvExport` | [`PlotCsvExportEvent`](#types) | An export to CSV has `'started'`, made `'progress'` (with a `percent`), or `'finished'` (with whether it was a `success`), so that its progress can be shown. |
| `imageExport` | [`PlotImageExportEvent`](#types) | The plot has been copied to the clipboard or exported to an image (or has failed to be), so that the user can be told about it. |
| `contextMenu` | [`PlotContextMenuEvent`](#types) | Only with [`customContextMenu`](#props): the context menu was requested at `clientX`/`clientY`, with the `items` that our context menu would have shown. If `usingKeyboard` is true, the custom menu should take the keyboard focus. |
Expand All @@ -168,6 +171,7 @@ Available through a template ref:
| Method | Description |
|---|---|
| `resetMargins()` | Emit [`marginsUpdated`](#events) again, e.g. after the shared margins have been reset. |
| `setRanges(ranges)` | Zoom into the given [`PlotRanges`](#types) (e.g., `{ x: [0, 10] }`), leaving the axes without a range as they are. Like a zoom by the user, they are kept when the data is updated. They are ignored if any of them is not valid (e.g., if its minimum is not smaller than its maximum or, for a logarithmic axis, if it is not positive). |
| `contextMenuHidden()` | Tell the plot that a custom context menu (see [`contextMenu`](#events)) has been hidden, so that it can get the keyboard focus back. |
| `pointCounts()` | The number of points of the visible traces (`nbOfPoints`), and how many of them were last drawn (`nbOfDrawnPoints`), as a [`PlotPointCounts`](#types). Meant for testing and benchmarking. |
| `memoryUsage()` | The memory (in bytes) used by the component itself, not counting the data, as a [`PlotMemoryUsage`](#types): by its levels of detail (`levelOfDetail`) and by the logarithm of its values along logarithmic axes (`logValues`). Meant for testing and benchmarking. |
Expand Down
35 changes: 35 additions & 0 deletions demo/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
@contextMenu="(event) => onContextMenu(event, index)"
@csvExport="onCsvExport"
@marginsUpdated="(newMargins) => onMarginsUpdated(newMargins, index)"
@rangesUpdated="(newRanges) => onRangesUpdated(newRanges, index)"
/>
</div>
</main>
Expand Down Expand Up @@ -116,6 +117,10 @@
<input v-model="sharedMargins" type="checkbox" />
Shared margins
</label>
<label class="demo-check">
<input v-model="sharedXRange" type="checkbox" />
Shared X range
</label>
<label class="demo-field">
<span>Theme</span>
<select v-model="theme">
Expand Down Expand Up @@ -168,6 +173,7 @@ import OpenCORPlot, {
type PlotData,
type PlotMargins,
type PlotMemoryUsage,
type PlotRanges,
type PlotTheme
} from '../index';
import {
Expand Down Expand Up @@ -199,6 +205,7 @@ const showLegend = vue.ref<boolean>(true);
const customContextMenu = vue.ref<boolean>(false);
const layout = vue.ref<'grid' | 'stacked'>('grid'); // Whether our instances are in a grid or stacked (in one column).
const sharedMargins = vue.ref<boolean>(true); // Whether our instances share their margins (see onMarginsUpdated()).
const sharedXRange = vue.ref<boolean>(false); // Whether our instances share their X range (see onRangesUpdated()).
const live = vue.ref<boolean>(false);
const nbOfPointsPerSecond = vue.ref<number>(1000);
const xRange = vue.ref<'fixed' | 'growing'>('fixed');
Expand Down Expand Up @@ -524,6 +531,34 @@ const onMarginsUpdated = (newMargins: PlotMargins, index: number): void => {
}
};

// Shared X range, i.e. the X range of the instance that was last zoomed, panned, or reset, which we give to all the
// other instances (if they are to share their X range), so that they show the same part of their data (e.g., when they
// are stacked).
// Note: an instance emits its current ranges whenever they change, including when it is given some ranges (see
// updateRangesAsync() in PlotWidget.vue), so we ignore the X range that we last shared, or our instances would
// keep giving it to each other.

let lastSharedXRange: [number, number] | undefined; // Shared X range of our instances.

const onRangesUpdated = (newRanges: PlotRanges, index: number): void => {
// Give the X range of the given instance to all the other instances, if needed (i.e. only if it is a new X range).

if (
!sharedXRange.value ||
(lastSharedXRange && newRanges.x[0] === lastSharedXRange[0] && newRanges.x[1] === lastSharedXRange[1])
) {
return;
}

lastSharedXRange = newRanges.x;

plotRefs.slice(0, datasets.value.length).forEach((plot: PlotInstance | null, plotIndex: number) => {
if (plotIndex !== index) {
plot?.setRanges({ x: newRanges.x });
}
});
};

// Our frame rate, and the number of points that our instances actually draw compared to their number of points (i.e.
// without level of detail), which we update twice a second (rather than reactively, which would be costly with many
// instances).
Expand Down
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type {
PlotMargins,
PlotMemoryUsage,
PlotPointCounts,
PlotRanges,
PlotTrace
} from './src/widgets/PlotWidget.vue';
export { default, default as OpenCORPlot } from './src/widgets/PlotWidget.vue';
137 changes: 124 additions & 13 deletions src/widgets/PlotWidget.vue
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,20 @@ export interface PlotMargins {
right: number;
}

/**
* The current ranges of the axes of a plot, i.e. what the user sees after zooming, panning, or resetting the zoom. It is
* the payload of the `rangesUpdated` event, which is emitted whenever they change, and what the `setRanges()` method
* takes. To link the X axes of several plots, pass the X range that the `rangesUpdated` event of one of them gave to
* the `setRanges()` method of the others.
*/

export interface PlotRanges {
/** The current range of the X axis, i.e. its minimum and maximum values (even if the axis is logarithmic). */
x: [number, number];
/** The current range of the Y axis, i.e. its minimum and maximum values (even if the axis is logarithmic). */
y: [number, number];
}

/** The payload of the `csvExport` event when an export to CSV has started. */

export interface PlotCsvExportStartedEvent {
Expand Down Expand Up @@ -411,6 +425,11 @@ const emit = defineEmits<{
* all of them to the `margins` prop of each of them.
*/
marginsUpdated: [newMargins: PlotMargins];
/**
* The current ranges of the axes have changed (e.g., after zooming, panning, or resetting the zoom, or after the data
* has been updated while an axis is autoranged), so that they can be shown or shared with other plots.
*/
rangesUpdated: [newRanges: PlotRanges];
}>();

// Some constants (in CSS pixels, where relevant).
Expand Down Expand Up @@ -508,6 +527,26 @@ const resetMargins = (): void => {
updateMarginsAsync();
};

const setRanges = (ranges: Partial<PlotRanges>): void => {
// Zoom into the given (actual) ranges, which we first convert to the ranges that we plot (see plotValue()).
// Note: we may be given some ranges before we got to plot some new data (see updatePlot()), in which case we must
// first forget our zoom if we are plotting something else, or we would forget the given ranges instead.

resetZoomIfNeeded();

const plotRanges: Partial<Record<AxisKey, Range>> = {};

for (const axisKey of ['x', 'y'] as AxisKey[]) {
const range = ranges[axisKey];

if (range) {
plotRanges[axisKey] = [plotValue(axisKey, range[0]), plotValue(axisKey, range[1])];
}
}

zoomTo(plotRanges);
};

const contextMenuHidden = (): void => {
// Our custom context menu has been hidden (see PlotContextMenuEvent), so do as if it was our context menu.

Expand Down Expand Up @@ -602,13 +641,21 @@ interface PlotMethods {
pointCounts: () => PlotPointCounts;
/** Emit the `marginsUpdated` event again (e.g., after the shared margins have been reset). */
resetMargins: () => void;
/**
* Zoom into the given ranges (e.g., those that the `rangesUpdated` event of another plot gave), leaving the axes
* without a range as they are. The ranges are kept when the data gets updated, like when the user zooms, and they are
* ignored if any of them is not valid (e.g., if its minimum is not smaller than its maximum or, for a logarithmic
* axis, if it is not positive).
*/
setRanges: (ranges: Partial<PlotRanges>) => void;
}

defineExpose<PlotMethods>({
contextMenuHidden,
memoryUsage,
pointCounts,
resetMargins
resetMargins,
setRanges
});

const mainDivRef = vue.shallowRef<HTMLElement | null>(null);
Expand All @@ -627,6 +674,8 @@ let stopTrackingContainerSize: (() => void) | undefined;
let stopTrackingLegendSize: (() => void) | undefined;
let marginsUpdatePending = false;
let trackedMargins: PlotMargins | undefined;
let rangesUpdatePending = false;
let trackedRanges: PlotRanges | undefined;

// Whether our axes are logarithmic, which can be changed using our context menu (see contextMenuItems and Logarithmic
// axes below).
Expand Down Expand Up @@ -2411,6 +2460,58 @@ const setScales = (ranges: Partial<Record<AxisKey, Range | null>>): void => {
});
};

// Update our ranges asynchronously, i.e. once our scales have been set (e.g., several times while zooming, or once per
// frame while animating a zoom), so that we emit our current ranges (see PlotRanges) at most once per change.
// Note: like for our margins (see updateMarginsAsync()), we use a microtask, so that other plots that share our X range
// get updated before the browser gets to paint us.

const sameRanges = (firstRanges: PlotRanges | undefined, secondRanges: PlotRanges | undefined): boolean => {
return (
firstRanges !== undefined &&
secondRanges !== undefined &&
firstRanges.x[0] === secondRanges.x[0] &&
firstRanges.x[1] === secondRanges.x[1] &&
firstRanges.y[0] === secondRanges.y[0] &&
firstRanges.y[1] === secondRanges.y[1]
);
};

const updateRangesAsync = (): void => {
// Coalesce multiple range update requests into a single microtask.

if (rangesUpdatePending) {
return;
}

rangesUpdatePending = true;

queueMicrotask(() => {
rangesUpdatePending = false;

// Make sure that we have a plot and that it has ranges.

const xRange = currentRange('x');
const yRange = currentRange('y');

if (!plot || isUnmounted || !xRange || !yRange) {
return;
}

// Emit our current (actual) ranges if they have changed.

const newRanges: PlotRanges = {
x: [actualValue('x', xRange[0]), actualValue('x', xRange[1])],
y: [actualValue('y', yRange[0]), actualValue('y', yRange[1])]
};

if (!sameRanges(newRanges, trackedRanges)) {
trackedRanges = newRanges;

emit('rangesUpdated', newRanges);
}
});
};

// Zoom animations, i.e. our ranges smoothly go from their current values to their new values (or their natural values
// if they get reset) rather than jump to them.
// Note #1: while animating, our range function uses our animated ranges (see scaleRange()), so that an update of our
Expand Down Expand Up @@ -6089,6 +6190,7 @@ const createPlot = (width: number, height: number): void => {
}
],
setCursor: [queueHoverUpdate],
setScale: [updateRangesAsync],
drawAxes: [drawZeroLines, drawTickLabels],
setSize: [
(u: uPlot) => {
Expand Down Expand Up @@ -6146,6 +6248,25 @@ const createPlot = (width: number, height: number): void => {
});
};

const resetZoomIfNeeded = (): string => {
// Reset our zoom and forget our last autoranges (see naturalRange()) if we are plotting something else, i.e. if our
// axis titles have changed, and return our axis titles.

const res = `${props.data.xAxisTitle ?? ''}::${props.data.yAxisTitle ?? ''}`;

if (res !== zoomTitles) {
zoomTitles = res;
zoomRanges = {};

delete lastAutoRanges.x;
delete lastAutoRanges.y;

stopRangeAnimation();
}

return res;
};

const updatePlot = (): void => {
// Make sure that we haven't been unmounted (e.g., if this was scheduled using vue.nextTick() just before we got
// unmounted) and that we can be shown (e.g., we can't if we are in a hidden file tab, in which case we will be
Expand All @@ -6172,19 +6293,9 @@ const updatePlot = (): void => {

isPlotOutdated = false;

// Reset our zoom and forget our last autoranges (see naturalRange()) if we are plotting something else.
// Reset our zoom if we are plotting something else.

const titles = `${props.data.xAxisTitle ?? ''}::${props.data.yAxisTitle ?? ''}`;

if (titles !== zoomTitles) {
zoomTitles = titles;
zoomRanges = {};

delete lastAutoRanges.x;
delete lastAutoRanges.y;

stopRangeAnimation();
}
const titles = resetZoomIfNeeded();

// Create or update our plot.
// Note: we only (re)create our plot if needed since it is much cheaper to update its data.
Expand Down