diff --git a/README.md b/README.md
index c0dfac2..cc81ba3 100644
--- a/README.md
+++ b/README.md
@@ -13,6 +13,7 @@ Contents:
- [Types](#types)
- [Data](#data)
- [Large and live data](#large-and-live-data)
+ - [Several plots](#several-plots)
- [Props](#props)
- [Events](#events)
- [Methods](#methods)
@@ -73,8 +74,10 @@ 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). |
| `PlotTheme` | `'system' \| 'light' \| 'dark'` | The value of the [`theme`](#props) prop. |
+| `PlotGroup` | `string \| symbol` | A group of plots, i.e. the value of the [`xAxisAlign`](#props), [`xAxisSync`](#props), [`yAxisAlign`](#props), and [`yAxisSync`](#props) props. A symbol is unique, so that unrelated parts of a page can't end up in the same group by using the same string. |
+| `PlotRanges` | `{ x: [number, number]; y: [number, number]; zoomed: { x: boolean; y: boolean } }` | The payload of the [`rangesUpdated`](#events) event, i.e. the current ranges of the axes (in actual units, even along a logarithmic axis) and whether each axis is zoomed (rather than autoranged). To restore them later, give `{ x: zoomed.x ? x : null, y: zoomed.y ? y : null }` to [`setRanges()`](#methods), so that an autoranged axis stays autoranged. |
+| `PlotRangesToSet` | `{ x?: [number, number] \| null; y?: [number, number] \| null }` | The ranges to give to [`setRanges()`](#methods), i.e. the range (in actual units, even along a logarithmic axis) into which to zoom an axis, `null` to reset the zoom of an axis, or nothing to leave an axis as it is. |
| `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. |
| `PlotCsvExportProgressEvent` | `{ type: 'progress'; percent: number }` | An export to CSV has made some progress: `percent` goes from 0 to 100 (an integer). |
@@ -138,6 +141,76 @@ data.value = {
Also set the [`live`](#props) prop while the data is live, so that the last point of each visible trace gets marked, making its latest value easy to spot (even where a trace overlaps itself, e.g. in a phase plot).
+### Several plots
+
+Plots can be shown together (e.g., stacked or side by side) and made to work as one, using a [`PlotGroup`](#types), i.e. a string or a symbol, which all the plots of a group share:
+- **Aligned axes:** the plots of an [`xAxisAlign`](#props) group get the same left and right margins, so that their plotting areas line up when they are stacked, while those of a [`yAxisAlign`](#props) group get the same top and bottom margins, so that their plotting areas line up when they are side by side.
+- **Synchronised axes:** the plots of an [`xAxisSync`](#props) (or [`yAxisSync`](#props)) group share the range and the scale (i.e. linear or logarithmic) of their X (or Y) axis. Zooming, panning, or resetting the zoom of one of them, or making its axis logarithmic (or not), does the same to the others, be it done by the user or using [`setRanges()`](#methods). Until one of them gets zoomed or panned, their axes fit the data of all of them. With a synchronised X axis, hovering one of them also shows the hover guide and tooltip of the others, at the same X value.
+
+Aligning and synchronising are independent of each other: plots can be aligned without being synchronised (e.g., when they show different X values), and synchronised without being aligned (e.g., when they are not shown next to each other). A plot can also be in different groups for its X and Y axes, and the groups of X axes are separate from those of Y axes, so the same group can be used for both.
+
+For example, to stack a plot of the membrane potential of a cell and a plot of its membrane current, both against time, with their plotting areas lined up and, unless the user unchecks a checkbox, zooming or panning the time axis of one plot doing the same to the other:
+
+```vue
+
+ Linked time axes
+
+
+
+
+
+
+
+
+
+```
+
+Here, the plotting areas line up even though the Y axis of the current plot needs more room for its tick labels (e.g., `-2000` rather than `-80`). Both plots show the same 10 seconds, and hovering one of them also shows the values of the other at the same time.
+
+A symbol is unique, so that unrelated parts of a page can't end up in the same group by using the same string. A plot joins or leaves a group whenever its props change (e.g., to let the user choose whether some plots are synchronised), and leaves its groups when it is unmounted. A plot that joins a group with a synchronised axis takes on the range and scale of that axis.
+
+To keep track of the ranges of the axes of a plot (e.g., to restore them later), handle its [`rangesUpdated`](#events) event.
+
### Props
| Prop | Type | Default | Description |
@@ -145,7 +218,10 @@ Also set the [`live`](#props) prop while the data is live, so that the last poin
| `data` | [`PlotData`](#types) | (required) | The data to plot. |
| `showLegend` | `boolean` | `true` | Whether to show the legend. The legend takes at most 40% of the width of the plot (with long trace names truncated, and shown in full when hovered or in the context menu of their legend item), and is hidden if the plot is too narrow for it to be useful. |
| `theme` | [`PlotTheme`](#types) | `'system'` | Whether to use light or dark mode, or whatever the system uses. |
-| `margins` | [`PlotMargins`](#types) | | Margins shared with other plots, so that their plotting areas line up (see [`marginsUpdated`](#events)). |
+| `xAxisAlign` | [`PlotGroup`](#types) | | The group of plots whose X axes are to line up with this plot's, i.e. whose plotting areas are to have the same left and right edges (e.g., when they are stacked). |
+| `xAxisSync` | [`PlotGroup`](#types) | | The group of plots whose X axis is to be synchronised with this plot's, i.e. which share the range and the scale of their X axis, so that zooming, panning, or resetting the zoom of one of them does the same to the others, as does making its X axis logarithmic (or not). Their X axes always show the same range, which, until one of them gets zoomed or panned, fits the data of all of them. Hovering one of them also shows the hover guide and tooltip of the others at the same X value (next to their guide line, at the same relative height as the mouse pointer or finger), so that the values of all of them can be read at once. For a trace whose X values are not sorted (e.g., a phase plot), the others show the point that is closest to where the mouse pointer would be, i.e. at their guide line and at that relative height, if any is close enough to it. |
+| `yAxisAlign` | [`PlotGroup`](#types) | | The group of plots whose Y axes are to line up with this plot's, i.e. whose plotting areas are to have the same top and bottom edges (e.g., when they are side by side). |
+| `yAxisSync` | [`PlotGroup`](#types) | | The group of plots whose Y axis is to be synchronised with this plot's, i.e. which share the range and the scale of their Y axis, so that zooming, panning, or resetting the zoom of one of them does the same to the others, as does making its Y axis logarithmic (or not). Their Y axes always show the same range, which, until one of them gets zoomed or panned, fits the data of all of them. |
| `appendTo` | `HTMLElement \| string` | `body` | Where to append our overlays (context menu, hover tooltip, etc.). |
| `customContextMenu` | `boolean` | `false` | Whether to emit a [`contextMenu`](#events) event rather than show our own context menu. To have no context menu at all, set it and don't handle the `contextMenu` event. |
| `levelOfDetail` | `boolean` | `true` | Whether to only go through the points that are needed for a trace to look the same when drawing it (see [Large and live data](#large-and-live-data)). Hovering a trace whose X values are sorted always does. Only meant to be disabled to see how much it helps. |
@@ -157,9 +233,9 @@ 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. |
| `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. |
+| `rangesUpdated` | [`PlotRanges`](#types) | The range of an axis has changed, or whether it is zoomed has. It is emitted at most once per frame, including while the plot is being zoomed, panned, or animated, and while its data gets updated. |
| `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. The custom menu should call the `command` of the chosen item while handling the click (or tap, or key press) that chose it, and it shouldn't move the keyboard focus afterwards (calling [`contextMenuHidden()`](#methods) instead), since some commands (e.g., to edit the range of an axis) give the keyboard focus to an editor that closes when it loses it, and iOS only shows its virtual keyboard for such an editor while handling a user interaction. If it calls that `command` while handling a key press (e.g., Enter or Space), it should also prevent that key's default action (using `preventDefault()`), since the key would otherwise also be typed into such an editor, replacing its selected value. |
### Methods
@@ -168,8 +244,8 @@ Available through a template ref:
| Method | Description |
|---|---|
-| `resetMargins()` | Emit [`marginsUpdated`](#events) again, e.g. after the shared margins have been reset. |
| `contextMenuHidden()` | Tell the plot that a custom context menu (see [`contextMenu`](#events)) has been hidden, so that it can get the keyboard focus back (unless something else, e.g. an editor opened by the chosen item, has it). |
+| `setRanges(ranges, options?)` | Zoom the axes into the given ranges and/or reset their zoom (see [`PlotRangesToSet`](#types)), as if the user had done it (so, a synchronised axis gets updated in all the plots of its group), animating the change if `options.animate` is set (`false` by default). A range that can't be plotted (e.g., with a non-positive end along a logarithmic axis, or with two ends that are the same) is ignored. |
| `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. |
@@ -186,6 +262,8 @@ Like with [Plotly](https://plotly.com/javascript/):
Hovering shows the value of each visible trace at the X value under the mouse pointer. For a trace that is not a function of X (e.g., a phase plot), it shows the point closest to the mouse pointer instead.
+With synchronised axes (see [Several plots](#several-plots)), zooming, panning, resetting the zoom, editing the range of an axis, and making an axis logarithmic (or not) apply to all the plots of the group of that axis, be it done with the mouse, by touch, with the keyboard, or from the context menu.
+
The context menu can zoom in and out, reset the zoom, edit the range of an axis, make an axis logarithmic, copy the plot to the clipboard, export it as JPEG, PNG, SVG, or WebP, and export its data to CSV. When requested from a legend item, it can also show only that trace (or all the traces again), or show or hide it if it is the only trace.
Copied and exported images always use the light colours (white background, dark text), whatever the current theme, since they are typically used in light documents.
diff --git a/demo/App.vue b/demo/App.vue
index ed384d6..cef9fbd 100644
--- a/demo/App.vue
+++ b/demo/App.vue
@@ -9,10 +9,13 @@
:live="liveRunning"
:showLegend="showLegend"
:customContextMenu="customContextMenu"
- :margins="sharedMargins ? margins : undefined"
+ :xAxisAlign="alignedXAxes ? ALIGN_GROUP : undefined"
+ :xAxisSync="linkedXAxes ? SYNC_GROUP : undefined"
+ :yAxisAlign="alignedYAxes ? ALIGN_GROUP : undefined"
+ :yAxisSync="linkedYAxes ? SYNC_GROUP : undefined"
@contextMenu="(event) => onContextMenu(event, index)"
@csvExport="onCsvExport"
- @marginsUpdated="(newMargins) => onMarginsUpdated(newMargins, index)"
+ @rangesUpdated="(ranges) => onRangesUpdated(ranges, index)"
/>
@@ -113,8 +116,20 @@
-
- Shared margins
+
+ Aligned X axes
+
+
+
+ Linked X axes
+
+
+
+ Aligned Y axes
+
+
+
+ Linked Y axes
Theme
@@ -167,8 +182,8 @@ import OpenCORPlot, {
type PlotContextMenuEvent,
type PlotCsvExportEvent,
type PlotData,
- type PlotMargins,
type PlotMemoryUsage,
+ type PlotRanges,
type PlotTheme
} from '../index';
import {
@@ -199,7 +214,10 @@ const levelOfDetail = vue.ref(true);
const showLegend = vue.ref(true);
const customContextMenu = vue.ref(false);
const layout = vue.ref<'grid' | 'stacked'>('grid'); // Whether our instances are in a grid or stacked (in one column).
-const sharedMargins = vue.ref(true); // Whether our instances share their margins (see onMarginsUpdated()).
+const alignedXAxes = vue.ref(true); // Whether the X axes of our instances line up (see ALIGN_GROUP).
+const linkedXAxes = vue.ref(true); // Whether the X axes of our instances are synchronised (see SYNC_GROUP).
+const alignedYAxes = vue.ref(true); // Whether the Y axes of our instances line up (see ALIGN_GROUP).
+const linkedYAxes = vue.ref(false); // Whether the Y axes of our instances are synchronised (see SYNC_GROUP).
const live = vue.ref(false);
const nbOfPointsPerSecond = vue.ref(1000);
const xRange = vue.ref<'fixed' | 'growing'>('fixed');
@@ -498,32 +516,17 @@ const gridStyle = vue.computed(() => {
};
});
-// Shared margins, i.e. the biggest natural margins of our instances, which we give to all of them (if they are to share
-// their margins), so that their plotting areas are aligned (e.g., when they are stacked).
-// Note: an instance always emits its natural margins (i.e. the margins that it needs), whether or not it is given some
-// shared margins (see updateMarginsAsync() in PlotWidget.vue).
-
-const naturalMargins: (PlotMargins | undefined)[] = []; // Natural margins of our instances.
-const margins = vue.shallowRef(); // Shared margins of our instances.
+// The alignment group of our instances (if their X and/or Y axes are to line up), so that their plotting areas have the
+// same left and right edges (e.g., when they are stacked) and/or the same top and bottom edges (e.g., when they are
+// side by side).
+// Note: we use a symbol rather than a string, so that no other part of the page could end up in our group.
-const onMarginsUpdated = (newMargins: PlotMargins, index: number): void => {
- // Keep track of the natural margins of the given instance and update our shared margins, if needed (i.e. only if they
- // have changed, so that our instances don't get relaid out for nothing).
+const ALIGN_GROUP = Symbol('demo');
- naturalMargins[index] = newMargins;
+// The synchronisation group of our instances (if their X and/or Y axes are to be synchronised), so that zooming,
+// panning, or resetting the zoom of an axis of one of them does the same to the others.
- let left = 0;
- let right = 0;
-
- for (const instanceMargins of naturalMargins.slice(0, datasets.value.length)) {
- left = Math.max(left, instanceMargins?.left ?? 0);
- right = Math.max(right, instanceMargins?.right ?? 0);
- }
-
- if (margins.value?.left !== left || margins.value?.right !== right) {
- margins.value = { left, right };
- }
-};
+const SYNC_GROUP = Symbol('demo');
// 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
@@ -536,8 +539,25 @@ const plottedPoints = vue.ref('');
const drawnPoints = vue.ref('');
const lodMemoryStatus = vue.ref(''); // Memory used by the levels of detail of our instances.
const logMemoryStatus = vue.ref(''); // Memory used by the logarithm of the values of our instances.
+const xRangeStatus = vue.ref(''); // X range of our first instance.
+const yRangeStatus = vue.ref(''); // Y range of our first instance.
+let firstInstanceRanges: PlotRanges | undefined; // Latest ranges of our first instance (see onRangesUpdated()).
let fpsFrameId = 0;
+const formatRange = (range: [number, number], zoomed: boolean): string => {
+ // Return the given range, with its ends rounded to 4 significant digits, and whether it is zoomed.
+
+ return `${Number(range[0].toPrecision(4))} to ${Number(range[1].toPrecision(4))}${zoomed ? ' (zoomed)' : ''}`;
+};
+
+const onRangesUpdated = (ranges: PlotRanges, index: number): void => {
+ // Keep track of the ranges of our first instance, which we show in our status (see updateDrawingStatus()).
+
+ if (index === 0) {
+ firstInstanceRanges = ranges;
+ }
+};
+
const updateDrawingStatus = (): void => {
let nbOfPoints = 0;
let nbOfDrawnPoints = 0;
@@ -563,6 +583,8 @@ const updateDrawingStatus = (): void => {
plottedPoints.value = formatNumber(nbOfPoints);
lodMemoryStatus.value = formatBytes(memoryUsage.levelOfDetail);
logMemoryStatus.value = formatBytes(memoryUsage.logValues);
+ xRangeStatus.value = firstInstanceRanges ? formatRange(firstInstanceRanges.x, firstInstanceRanges.zoomed.x) : '';
+ yRangeStatus.value = firstInstanceRanges ? formatRange(firstInstanceRanges.y, firstInstanceRanges.zoomed.y) : '';
drawnPoints.value = `${formatNumber(nbOfDrawnPoints)}${nbOfPoints ? ` (${percentage(nbOfDrawnPoints / nbOfPoints)})` : ''}`;
};
@@ -1081,6 +1103,8 @@ const statusRows = vue.computed(() => [
{ term: 'LOD memory', value: lodMemoryStatus.value },
{ term: 'Log memory', value: logMemoryStatus.value },
{ term: 'Live', value: liveStatus.value },
+ { term: 'X axis', value: xRangeStatus.value },
+ { term: 'Y axis', value: yRangeStatus.value },
...benchmarkRows.value,
{ term: 'CSV export', value: csvExportStatus.value }
]);
diff --git a/demo/data.ts b/demo/data.ts
index db79f81..6291695 100644
--- a/demo/data.ts
+++ b/demo/data.ts
@@ -159,7 +159,7 @@ export const plotData = (kind: DataKind, nbOfTraces: number, nbOfPoints: number,
// Return the data of the given instance of our plot, which is different for each instance (since its curves have a
// different phase and its noise a different seed). Also, the Y values of our instances have different scales (i.e. 1,
// 10, 100, and 1,000, over and over), so that their Y tick labels have different widths and therefore their plots
- // have different natural margins (see our shared margins in App.vue).
+ // have different natural margins (see ALIGN_GROUP in App.vue).
// Note: our traces share their X values, if possible, to save memory.
const x = kind === 'unsorted' || kind === 'unsortedNoisy' ? undefined : xValues(kind, nbOfPoints);
diff --git a/index.ts b/index.ts
index 82ac990..3dc35c7 100644
--- a/index.ts
+++ b/index.ts
@@ -1,6 +1,7 @@
// Our plotting component, which is our plot widget (see PlotWidget.vue), as well as the types that are needed to use it
// (e.g., to provide it with some data or to handle its events).
+export type { PlotGroup } from './src/common/common';
export type { IconName } from './src/common/icons';
export type {
ContextMenuAction,
@@ -17,9 +18,10 @@ export type {
PlotCsvExportStartedEvent,
PlotData,
PlotImageExportEvent,
- PlotMargins,
PlotMemoryUsage,
PlotPointCounts,
+ PlotRanges,
+ PlotRangesToSet,
PlotTrace
} from './src/widgets/PlotWidget.vue';
export { default, default as OpenCORPlot } from './src/widgets/PlotWidget.vue';
diff --git a/package.json b/package.json
index 590adcc..9206471 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
],
"type": "module",
"types": "dist/index.d.ts",
- "version": "0.20261127.0",
+ "version": "0.20261201.0",
"exports": {
".": {
"types": "./dist/index.d.ts",
diff --git a/src/common/alignUtils.test.ts b/src/common/alignUtils.test.ts
new file mode 100644
index 0000000..243fdd0
--- /dev/null
+++ b/src/common/alignUtils.test.ts
@@ -0,0 +1,263 @@
+import { afterEach, describe, expect, it } from 'bun:test';
+
+import { type AlignAxis, type Margins, MarginsAligner, sameMargins } from './alignUtils';
+import type { PlotGroup } from './common';
+
+// Note: our groups are shared by all our tests (since they are module-level), so each test uses its own groups and all
+// our aligners leave their group once a test is done.
+
+const aligners: MarginsAligner[] = [];
+
+afterEach(() => {
+ for (const aligner of aligners) {
+ aligner.setGroup(undefined);
+ }
+
+ aligners.length = 0;
+});
+
+interface TestAligner {
+ aligner: MarginsAligner;
+ nbOfCalls: () => number;
+}
+
+const testAligner = (group?: PlotGroup, naturalMargins?: Margins, axis: AlignAxis = 'x'): TestAligner => {
+ // Return an aligner that counts how many times its shared margins have changed, after having given it the given
+ // natural margins, if any, and having had it join the given group, if any.
+
+ let nbOfCalls = 0;
+ const aligner = new MarginsAligner(axis, () => {
+ ++nbOfCalls;
+ });
+
+ aligners.push(aligner);
+
+ if (naturalMargins) {
+ aligner.setNaturalMargins(naturalMargins);
+ }
+
+ aligner.setGroup(group);
+
+ return { aligner, nbOfCalls: () => nbOfCalls };
+};
+
+// sameMargins().
+
+describe('sameMargins()', () => {
+ it('returns whether some margins are the same', () => {
+ expect(sameMargins({ start: 1, end: 2 }, { start: 1, end: 2 })).toBe(true);
+ expect(sameMargins({ start: 1, end: 2 }, { start: 3, end: 2 })).toBe(false);
+ expect(sameMargins({ start: 1, end: 2 }, { start: 1, end: 3 })).toBe(false);
+ });
+
+ it('returns that no margins are only the same as no margins', () => {
+ expect(sameMargins(undefined, undefined)).toBe(true);
+ expect(sameMargins({ start: 1, end: 2 }, undefined)).toBe(false);
+ expect(sameMargins(undefined, { start: 1, end: 2 })).toBe(false);
+ });
+});
+
+// MarginsAligner.
+
+describe('MarginsAligner', () => {
+ it('has no shared margins if it is not in a group', () => {
+ const plot = testAligner(undefined, { start: 10, end: 20 });
+
+ expect(plot.aligner.sharedMargins()).toBeUndefined();
+ expect(plot.nbOfCalls()).toBe(0);
+ });
+
+ it('has no shared margins if no plot in its group knows its natural margins', () => {
+ const group = Symbol('group');
+ const plot1 = testAligner(group);
+ const plot2 = testAligner(group);
+
+ expect(plot1.aligner.sharedMargins()).toBeUndefined();
+ expect(plot2.aligner.sharedMargins()).toBeUndefined();
+ expect(plot1.nbOfCalls()).toBe(0);
+ expect(plot2.nbOfCalls()).toBe(0);
+ });
+
+ it('shares its natural margins if it is alone in its group', () => {
+ const plot = testAligner(Symbol('group'));
+
+ plot.aligner.setNaturalMargins({ start: 10, end: 20 });
+
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot.nbOfCalls()).toBe(1);
+ });
+
+ it('shares the biggest natural margins of the plots in its group', () => {
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 30, end: 20 });
+ const plot2 = testAligner(group, { start: 10, end: 40 });
+ const plot3 = testAligner(group);
+
+ for (const plot of [plot1, plot2, plot3]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ }
+
+ expect(plot1.nbOfCalls()).toBe(2);
+ expect(plot2.nbOfCalls()).toBe(1);
+ expect(plot3.nbOfCalls()).toBe(1);
+ });
+
+ it('only lets its plot know when its shared margins change', () => {
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 30, end: 40 });
+ const plot2 = testAligner(group, { start: 10, end: 20 });
+
+ // The natural margins of our second plot change, but they are still smaller than those of our first plot.
+
+ plot2.aligner.setNaturalMargins({ start: 20, end: 30 });
+
+ expect(plot1.nbOfCalls()).toBe(1);
+ expect(plot2.nbOfCalls()).toBe(1);
+
+ // The natural margins of our second plot don't change.
+
+ plot2.aligner.setNaturalMargins({ start: 20, end: 30 });
+
+ expect(plot1.nbOfCalls()).toBe(1);
+ expect(plot2.nbOfCalls()).toBe(1);
+
+ // The natural margins of our second plot become the biggest ones.
+
+ plot2.aligner.setNaturalMargins({ start: 50, end: 30 });
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 50, end: 40 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 50, end: 40 });
+ expect(plot1.nbOfCalls()).toBe(2);
+ expect(plot2.nbOfCalls()).toBe(2);
+ });
+
+ it('keeps a copy of the natural margins it is given', () => {
+ const naturalMargins = { start: 10, end: 20 };
+ const plot = testAligner(Symbol('group'), naturalMargins);
+
+ naturalMargins.start = 100;
+
+ plot.aligner.setNaturalMargins(naturalMargins);
+
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 100, end: 20 });
+ expect(plot.nbOfCalls()).toBe(2);
+ });
+
+ it('shrinks the shared margins of a group when a plot leaves it', () => {
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 10, end: 20 });
+ const plot2 = testAligner(group, { start: 30, end: 40 });
+
+ plot2.aligner.setGroup(undefined);
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot2.aligner.sharedMargins()).toBeUndefined();
+ expect(plot1.nbOfCalls()).toBe(3);
+ expect(plot2.nbOfCalls()).toBe(2);
+ });
+
+ it('does nothing if it is to join the group it is already in', () => {
+ const group = Symbol('group');
+ const plot = testAligner(group, { start: 10, end: 20 });
+
+ plot.aligner.setGroup(group);
+
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot.nbOfCalls()).toBe(1);
+ });
+
+ it('can move from one group to another', () => {
+ const group1 = Symbol('group1');
+ const group2 = Symbol('group2');
+ const plot1 = testAligner(group1, { start: 10, end: 20 });
+ const plot2 = testAligner(group2, { start: 30, end: 40 });
+ const plot3 = testAligner(group1, { start: 50, end: 60 });
+
+ plot3.aligner.setGroup(group2);
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 50, end: 60 });
+ expect(plot3.aligner.sharedMargins()).toEqual({ start: 50, end: 60 });
+ });
+
+ it('shares its natural margins with a group it joins later', () => {
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 10, end: 20 });
+ const plot2 = testAligner(undefined, { start: 30, end: 40 });
+
+ plot2.aligner.setGroup(group);
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ });
+
+ it('puts plots with the same string in the same group', () => {
+ const plot1 = testAligner('alignUtils.test', { start: 10, end: 20 });
+ const plot2 = testAligner('alignUtils.test', { start: 30, end: 40 });
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ });
+
+ it('puts plots with different symbols with the same description in different groups', () => {
+ const plot1 = testAligner(Symbol('group'), { start: 10, end: 20 });
+ const plot2 = testAligner(Symbol('group'), { start: 30, end: 40 });
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ });
+
+ it('keeps the groups of different axes separate', () => {
+ const plot1 = testAligner('alignUtils.test.axes', { start: 10, end: 20 }, 'x');
+ const plot2 = testAligner('alignUtils.test.axes', { start: 30, end: 40 }, 'y');
+ const plot3 = testAligner('alignUtils.test.axes', { start: 0, end: 35 }, 'y');
+
+ expect(plot1.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ expect(plot3.aligner.sharedMargins()).toEqual({ start: 30, end: 40 });
+ });
+
+ it('forgets about a group once it is empty', () => {
+ // Our first plot leaves our group, which becomes empty, so our second plot only gets its own margins when joining a
+ // group with the same name.
+
+ const plot1 = testAligner('alignUtils.test.empty', { start: 30, end: 40 });
+
+ plot1.aligner.setGroup(undefined);
+
+ const plot2 = testAligner('alignUtils.test.empty', { start: 10, end: 20 });
+
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 10, end: 20 });
+ });
+
+ it('keeps the plots of a group in agreement if a plot joins it while they are told about their margins', () => {
+ // Our first plot makes a third plot join our group as soon as it gets told about the shared margins that our second
+ // plot gives it. Our third plot has the biggest natural margins, which all our plots should end up with, including
+ // our second plot, which only gets told about its new shared margins after our first plot.
+
+ const group = Symbol('group');
+ let joinGroup = false;
+ let plot3: TestAligner | undefined;
+ const plot1Aligner = new MarginsAligner('x', () => {
+ if (joinGroup) {
+ joinGroup = false;
+
+ plot3 = testAligner(group, { start: 50, end: 60 });
+ }
+ });
+
+ aligners.push(plot1Aligner);
+
+ plot1Aligner.setNaturalMargins({ start: 10, end: 20 });
+ plot1Aligner.setGroup(group);
+
+ joinGroup = true;
+
+ const plot2 = testAligner(group, { start: 30, end: 40 });
+
+ expect(plot3).toBeDefined();
+ expect(plot1Aligner.sharedMargins()).toEqual({ start: 50, end: 60 });
+ expect(plot2.aligner.sharedMargins()).toEqual({ start: 50, end: 60 });
+ expect(plot3?.aligner.sharedMargins()).toEqual({ start: 50, end: 60 });
+ });
+});
diff --git a/src/common/alignUtils.ts b/src/common/alignUtils.ts
new file mode 100644
index 0000000..70bb6b1
--- /dev/null
+++ b/src/common/alignUtils.ts
@@ -0,0 +1,170 @@
+// Some utilities to align plots, i.e. to have plots that are in the same group share their margins along an axis, so
+// that their plotting areas line up along that axis (see the xAxisAlign and yAxisAlign props of PlotWidget.vue).
+
+import type { PlotGroup } from './common';
+
+/**
+ * An axis along which plots can be aligned, i.e. along which their plotting areas can line up (e.g., when they are
+ * stacked for the X axis, or side by side for the Y axis).
+ */
+
+export type AlignAxis = 'x' | 'y';
+
+/**
+ * The margins (in pixels) of a plot along an axis, i.e. on either side of its plotting area: its left and right margins
+ * along the X axis (i.e. the space taken by its Y axis and its legend), or its top and bottom margins along the Y axis
+ * (i.e. the space taken by its X axis).
+ */
+
+export interface Margins {
+ /** The margin before the plotting area, i.e. its left margin along the X axis, or its top margin along the Y axis. */
+ start: number;
+ /** The margin after the plotting area, i.e. its right margin along the X axis, or its bottom one along the Y axis. */
+ end: number;
+}
+
+export const sameMargins = (firstMargins: Margins | undefined, secondMargins: Margins | undefined): boolean => {
+ // Return whether the given margins are the same, with no margins only being the same as no margins.
+
+ if (firstMargins === undefined || secondMargins === undefined) {
+ return firstMargins === secondMargins;
+ }
+
+ return firstMargins.start === secondMargins.start && firstMargins.end === secondMargins.end;
+};
+
+// Our groups for each axis, i.e. the aligners (i.e. plots) that are in each of them.
+// Note #1: the groups of our X axes are separate from those of our Y axes, so that the same group can be used for both.
+// Note #2: a group gets removed once it is empty, so that we don't keep track of groups that are not used anymore.
+
+const groups: Record>> = {
+ x: new Map>(),
+ y: new Map>()
+};
+
+export class MarginsAligner {
+ // The aligner of a plot along an axis, which keeps track of its natural margins along that axis (i.e. the margins
+ // that it needs) and gives it some shared margins (i.e. the biggest natural margins of all the plots in its group, if
+ // any), calling the given callback whenever its shared margins change.
+ // Note: the natural margins of a plot must not depend on its shared margins, or the plots in a group could keep
+ // adjusting to each other's margins (see updateMarginsAsync() in PlotWidget.vue).
+
+ private group: PlotGroup | undefined;
+ private natural: Margins | undefined;
+ private shared: Margins | undefined;
+
+ constructor(
+ private readonly axis: AlignAxis,
+ private readonly onSharedMarginsChanged: () => void
+ ) {}
+
+ sharedMargins(): Readonly | undefined {
+ // Return our shared margins, if we are in a group and at least one of its plots knows its natural margins.
+
+ return this.shared;
+ }
+
+ setGroup(group: PlotGroup | undefined): void {
+ // Leave our current group, if any, and join the given one, if any.
+
+ if (group === this.group) {
+ return;
+ }
+
+ const oldGroup = this.group;
+
+ this.group = group;
+
+ if (oldGroup !== undefined) {
+ const oldMembers = groups[this.axis].get(oldGroup) as Set;
+
+ oldMembers.delete(this);
+
+ if (oldMembers.size === 0) {
+ groups[this.axis].delete(oldGroup);
+ } else {
+ MarginsAligner.updateMembers(oldMembers);
+ }
+ }
+
+ if (group === undefined) {
+ if (this.setShared(undefined)) {
+ this.onSharedMarginsChanged();
+ }
+
+ return;
+ }
+
+ let members = groups[this.axis].get(group);
+
+ if (!members) {
+ members = new Set();
+
+ groups[this.axis].set(group, members);
+ }
+
+ members.add(this);
+
+ MarginsAligner.updateMembers(members);
+ }
+
+ setNaturalMargins(margins: Margins): void {
+ // Keep track of our natural margins and, if they have changed and we are in a group, update the shared margins of
+ // our group.
+
+ if (sameMargins(margins, this.natural)) {
+ return;
+ }
+
+ this.natural = { ...margins };
+
+ if (this.group !== undefined) {
+ MarginsAligner.updateMembers(groups[this.axis].get(this.group) as Set);
+ }
+ }
+
+ private setShared(margins: Margins | undefined): boolean {
+ // Set our shared margins and return whether they have changed (in which case our plot must be told about them).
+
+ if (sameMargins(margins, this.shared)) {
+ return false;
+ }
+
+ this.shared = margins;
+
+ return true;
+ }
+
+ private static updateMembers(members: Set): void {
+ // Give the biggest natural margins of the given members to all of them, ignoring the members that don't know their
+ // natural margins yet (e.g., a plot that hasn't been laid out yet), and then tell the members which shared margins
+ // have changed about them.
+ // Note: we first give all our members their new shared margins and only then tell them about them, in case one of
+ // them was to straight away join or leave a group, or change its natural margins. Indeed, this would update
+ // the shared margins of the members of its group, which we would otherwise, for the members that we have yet
+ // to tell, override with our (now outdated) shared margins.
+
+ let margins: Margins | undefined;
+
+ for (const member of members) {
+ if (member.natural) {
+ margins = {
+ start: Math.max(margins?.start ?? 0, member.natural.start),
+ end: Math.max(margins?.end ?? 0, member.natural.end)
+ };
+ }
+ }
+
+ const changedMembers: MarginsAligner[] = [];
+
+ for (const member of members) {
+ if (member.setShared(margins)) {
+ changedMembers.push(member);
+ }
+ }
+
+ for (const member of changedMembers) {
+ member.onSharedMarginsChanged();
+ }
+ }
+}
diff --git a/src/common/common.ts b/src/common/common.ts
index 037de56..3f6afd2 100644
--- a/src/common/common.ts
+++ b/src/common/common.ts
@@ -1,3 +1,13 @@
+// A group of plots, i.e. a string or a symbol, which plots use to align or synchronise their axes (see the xAxisAlign,
+// xAxisSync, yAxisAlign, and yAxisSync props of PlotWidget.vue).
+
+/**
+ * A group of plots (see the `xAxisAlign`, `xAxisSync`, `yAxisAlign`, and `yAxisSync` props), i.e. a string or a symbol.
+ * A symbol is unique, so that unrelated parts of a page can't end up in the same group by using the same string.
+ */
+
+export type PlotGroup = string | symbol;
+
// A method to format an error into a string.
export const formatError = (error: unknown): string => {
diff --git a/src/common/syncUtils.test.ts b/src/common/syncUtils.test.ts
new file mode 100644
index 0000000..cfe9171
--- /dev/null
+++ b/src/common/syncUtils.test.ts
@@ -0,0 +1,467 @@
+import { afterEach, describe, expect, it } from 'bun:test';
+
+import type { PlotGroup } from './common';
+import type { Range } from './rangeUtils';
+import {
+ AxisSyncer,
+ type AxisSyncerHandlers,
+ type SyncAxis,
+ type SyncAxisState,
+ type SyncHover,
+ sameRange
+} from './syncUtils';
+
+// Note: our groups are shared by all our tests (since they are module-level), so each test uses its own groups and all
+// our syncers leave their group once a test is done.
+
+const syncers: AxisSyncer[] = [];
+
+afterEach(() => {
+ for (const syncer of syncers) {
+ syncer.setGroup(undefined, { zoomRange: undefined, log: false });
+ }
+
+ syncers.length = 0;
+});
+
+interface TestSyncer {
+ syncer: AxisSyncer;
+ zooms: [Range | undefined, number][];
+ logs: SyncAxisState[];
+ hovers: (SyncHover | undefined)[];
+ nbOfNaturalRangeChanges: () => number;
+}
+
+const LINEAR: SyncAxisState = { zoomRange: undefined, log: false };
+
+const testSyncer = (
+ group?: PlotGroup,
+ state: SyncAxisState = LINEAR,
+ axis: SyncAxis = 'x',
+ onNaturalRangeChanged?: () => void
+): TestSyncer => {
+ // Return a syncer that keeps track of what it gets told about the other plots in its group, after having had it join
+ // the given group, if any, with the given state.
+
+ const zooms: [Range | undefined, number][] = [];
+ const logs: SyncAxisState[] = [];
+ const hovers: (SyncHover | undefined)[] = [];
+ let nbOfNaturalRangeChanges = 0;
+ const handlers: AxisSyncerHandlers = {
+ onZoom: (zoomRange: Range | undefined, duration: number) => {
+ zooms.push([zoomRange, duration]);
+ },
+ onLog: (state: SyncAxisState) => {
+ logs.push(state);
+ },
+ onNaturalRangeChanged: () => {
+ ++nbOfNaturalRangeChanges;
+
+ onNaturalRangeChanged?.();
+ },
+ onHover: (hover: SyncHover | undefined) => {
+ hovers.push(hover);
+ }
+ };
+ const syncer = new AxisSyncer(axis, handlers);
+
+ syncers.push(syncer);
+
+ syncer.setGroup(group, state);
+
+ return { syncer, zooms, logs, hovers, nbOfNaturalRangeChanges: () => nbOfNaturalRangeChanges };
+};
+
+// sameRange().
+
+describe('sameRange()', () => {
+ it('returns whether some ranges are the same', () => {
+ expect(sameRange([1, 2], [1, 2])).toBe(true);
+ expect(sameRange([1, 2], [3, 2])).toBe(false);
+ expect(sameRange([1, 2], [1, 3])).toBe(false);
+ });
+
+ it('returns that no range is only the same as no range', () => {
+ expect(sameRange(undefined, undefined)).toBe(true);
+ expect(sameRange([1, 2], undefined)).toBe(false);
+ expect(sameRange(undefined, [1, 2])).toBe(false);
+ });
+});
+
+// AxisSyncer.
+
+describe('AxisSyncer', () => {
+ it('does nothing but return its natural range if it is not in a group', () => {
+ const plot = testSyncer();
+
+ expect(plot.syncer.isInGroup()).toBe(false);
+
+ plot.syncer.setZoom([1, 2], 100);
+ plot.syncer.setLog({ zoomRange: undefined, log: true });
+
+ expect(plot.syncer.naturalRange([3, 4])).toEqual([3, 4]);
+ expect(plot.syncer.naturalRange(undefined)).toBeUndefined();
+ });
+
+ it('gives its state to a new group and gets the state of an existing group', () => {
+ const group = Symbol('group');
+ const plot1 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot1);
+
+ expect(plot1.setGroup(group, { zoomRange: [1, 2], log: true })).toBeUndefined();
+ expect(plot1.isInGroup()).toBe(true);
+
+ const plot2 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot2);
+
+ expect(plot2.setGroup(group, LINEAR)).toEqual({ zoomRange: [1, 2], log: true });
+ });
+
+ it('gives a copy of the state of its group', () => {
+ const group = Symbol('group');
+ const state: SyncAxisState = { zoomRange: [1, 2], log: false };
+
+ testSyncer(group, state);
+
+ (state.zoomRange as Range)[0] = 100;
+
+ const plot2 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot2);
+
+ const groupState = plot2.setGroup(group, LINEAR) as SyncAxisState;
+
+ expect(groupState).toEqual({ zoomRange: [1, 2], log: false });
+
+ (groupState.zoomRange as Range)[0] = 100;
+
+ const plot3 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot3);
+
+ expect(plot3.setGroup(group, LINEAR)).toEqual({ zoomRange: [1, 2], log: false });
+ });
+
+ it('does nothing if it is to join the group it is already in', () => {
+ const group = Symbol('group');
+ const plot = testSyncer(group, { zoomRange: [1, 2], log: false });
+
+ expect(plot.syncer.setGroup(group, LINEAR)).toBeUndefined();
+ expect(plot.syncer.isInGroup()).toBe(true);
+ });
+
+ it('tells the other plots in its group about a zoom', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+ const plot3 = testSyncer(group);
+
+ plot1.syncer.setZoom([1, 2], 250);
+
+ expect(plot1.zooms).toEqual([]);
+ expect(plot2.zooms).toEqual([[[1, 2], 250]]);
+ expect(plot3.zooms).toEqual([[[1, 2], 250]]);
+
+ plot2.syncer.setZoom(undefined, 0);
+
+ expect(plot1.zooms).toEqual([[undefined, 0]]);
+ expect(plot2.zooms).toEqual([[[1, 2], 250]]);
+ expect(plot3.zooms).toEqual([
+ [[1, 2], 250],
+ [undefined, 0]
+ ]);
+ });
+
+ it('gives the latest zoom of its group to a plot that joins it', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+
+ plot1.syncer.setZoom([1, 2], 250);
+
+ const plot2 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot2);
+
+ expect(plot2.setGroup(group, LINEAR)).toEqual({ zoomRange: [1, 2], log: false });
+ });
+
+ it('tells the other plots in its group about a change of scale', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ plot1.syncer.setLog({ zoomRange: [0, 1], log: true });
+
+ expect(plot1.logs).toEqual([]);
+ expect(plot2.logs).toEqual([{ zoomRange: [0, 1], log: true }]);
+
+ const plot3 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot3);
+
+ expect(plot3.setGroup(group, LINEAR)).toEqual({ zoomRange: [0, 1], log: true });
+ });
+
+ it('gives the union of the natural ranges of the plots in its group', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ expect(plot1.syncer.naturalRange([0, 10])).toEqual([0, 10]);
+ expect(plot2.syncer.naturalRange([5, 20])).toEqual([0, 20]);
+ expect(plot1.syncer.naturalRange([-5, 10])).toEqual([-5, 20]);
+ });
+
+ it('only tells the other plots in its group when the natural range of its group changes', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ plot1.syncer.naturalRange([0, 10]);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(0);
+ expect(plot2.nbOfNaturalRangeChanges()).toBe(1);
+
+ // Our second plot has a natural range that is within that of our group, so it doesn't change it.
+
+ plot2.syncer.naturalRange([2, 8]);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(0);
+ expect(plot2.nbOfNaturalRangeChanges()).toBe(1);
+
+ // Our first plot gives the same natural range again.
+
+ plot1.syncer.naturalRange([0, 10]);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(0);
+ expect(plot2.nbOfNaturalRangeChanges()).toBe(1);
+
+ // Our second plot widens the natural range of our group.
+
+ plot2.syncer.naturalRange([2, 30]);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(1);
+ expect(plot2.nbOfNaturalRangeChanges()).toBe(1);
+ });
+
+ it('ignores the plots that have nothing to autorange to', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ expect(plot1.syncer.naturalRange(undefined)).toBeUndefined();
+ expect(plot2.syncer.naturalRange([5, 20])).toEqual([5, 20]);
+ expect(plot1.syncer.naturalRange(undefined)).toEqual([5, 20]);
+ });
+
+ it('forgets the natural ranges of the plots in its group when the scale changes', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ plot1.syncer.naturalRange([1, 10]);
+ plot2.syncer.naturalRange([1, 1000]);
+ plot1.syncer.setLog({ zoomRange: undefined, log: true });
+
+ // Only our first plot has given its natural range in the new scale.
+
+ expect(plot1.syncer.naturalRange([0, 1])).toEqual([0, 1]);
+ expect(plot2.syncer.naturalRange([0, 3])).toEqual([0, 3]);
+ });
+
+ it('forgets its natural range when joining a group', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer();
+
+ plot1.syncer.naturalRange([0, 10]);
+ plot2.syncer.naturalRange([0, 1000]);
+ plot2.syncer.setGroup(group, LINEAR);
+
+ expect(plot1.syncer.naturalRange([0, 10])).toEqual([0, 10]);
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(0);
+ });
+
+ it('updates the natural range of a group when a plot leaves it', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ plot1.syncer.naturalRange([0, 10]);
+ plot2.syncer.naturalRange([0, 20]);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(1);
+
+ plot2.syncer.setGroup(undefined, LINEAR);
+
+ expect(plot2.syncer.isInGroup()).toBe(false);
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(2);
+ expect(plot1.syncer.naturalRange([0, 10])).toEqual([0, 10]);
+ expect(plot2.syncer.naturalRange([0, 20])).toEqual([0, 20]);
+
+ // Our first plot leaves our group too, but has nobody to tell.
+
+ plot1.syncer.setGroup(undefined, LINEAR);
+
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(2);
+ });
+
+ it('can move from one group to another', () => {
+ const group1 = Symbol('group1');
+ const group2 = Symbol('group2');
+ const plot1 = testSyncer(group1, { zoomRange: [1, 2], log: false });
+ const plot2 = testSyncer(group2, { zoomRange: [3, 4], log: true });
+ const plot3 = testSyncer(group1);
+
+ expect(plot3.syncer.setGroup(group2, LINEAR)).toEqual({ zoomRange: [3, 4], log: true });
+
+ plot3.syncer.setZoom([5, 6], 0);
+
+ expect(plot1.zooms).toEqual([]);
+ expect(plot2.zooms).toEqual([[[5, 6], 0]]);
+ });
+
+ it('puts plots with the same string in the same group', () => {
+ const plot1 = testSyncer('syncUtils.test');
+ const plot2 = testSyncer('syncUtils.test');
+
+ plot1.syncer.setZoom([1, 2], 0);
+
+ expect(plot2.zooms).toEqual([[[1, 2], 0]]);
+ });
+
+ it('puts plots with different symbols with the same description in different groups', () => {
+ const plot1 = testSyncer(Symbol('group'));
+ const plot2 = testSyncer(Symbol('group'));
+
+ plot1.syncer.setZoom([1, 2], 0);
+
+ expect(plot2.zooms).toEqual([]);
+ });
+
+ it('keeps the groups of different axes separate', () => {
+ const plot1 = testSyncer('syncUtils.test.axes', LINEAR, 'x');
+ const plot2 = testSyncer('syncUtils.test.axes', LINEAR, 'y');
+
+ plot1.syncer.setZoom([1, 2], 0);
+
+ expect(plot2.zooms).toEqual([]);
+ });
+
+ it('forgets about a group once it is empty', () => {
+ // Our first plot leaves our group, which becomes empty, so our second plot creates a new group (with its own state)
+ // when joining a group with the same name.
+
+ const plot1 = testSyncer('syncUtils.test.empty', { zoomRange: [1, 2], log: true });
+
+ plot1.syncer.setGroup(undefined, LINEAR);
+
+ const plot2 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot2);
+
+ expect(plot2.setGroup('syncUtils.test.empty', LINEAR)).toBeUndefined();
+ });
+
+ it('tells the other plots in its group where it is hovered', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+ const plot3 = testSyncer(group);
+
+ plot1.syncer.setHover({ x: 5, yFraction: 0.25 });
+ plot1.syncer.setHover(undefined);
+
+ expect(plot1.hovers).toEqual([]);
+ expect(plot2.hovers).toEqual([{ x: 5, yFraction: 0.25 }, undefined]);
+ expect(plot3.hovers).toEqual([{ x: 5, yFraction: 0.25 }, undefined]);
+ });
+
+ it('gives a copy of where a plot is hovered', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+ const hover: SyncHover = { x: 5, yFraction: 0.25 };
+
+ plot1.syncer.setHover(hover);
+
+ hover.x = 100;
+
+ expect(plot2.hovers).toEqual([{ x: 5, yFraction: 0.25 }]);
+ });
+
+ it('only lets the plot that is hovered stop the hover of its group', () => {
+ // The mouse pointer goes from our first plot to our second one, which starts being hovered before our first plot
+ // stops being hovered, so our third plot should still show the hover of our second plot.
+
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+ const plot3 = testSyncer(group);
+
+ plot1.syncer.setHover({ x: 5, yFraction: 0.25 });
+ plot2.syncer.setHover({ x: 6, yFraction: 0.5 });
+ plot1.syncer.setHover(undefined);
+
+ expect(plot3.hovers).toEqual([
+ { x: 5, yFraction: 0.25 },
+ { x: 6, yFraction: 0.5 }
+ ]);
+
+ // A plot that isn't hovered and doesn't stop being hovered doesn't tell anybody anything.
+
+ plot3.syncer.setHover(undefined);
+
+ expect(plot1.hovers).toEqual([{ x: 6, yFraction: 0.5 }]);
+ });
+
+ it('stops the hover of its group when the plot that is hovered leaves it', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = testSyncer(group);
+
+ plot1.syncer.setHover({ x: 5, yFraction: 0.25 });
+ plot1.syncer.setGroup(undefined, LINEAR);
+
+ expect(plot2.hovers).toEqual([{ x: 5, yFraction: 0.25 }, undefined]);
+
+ // A plot that is not in a group has nobody to tell.
+
+ plot1.syncer.setHover({ x: 5, yFraction: 0.25 });
+
+ expect(plot2.hovers).toEqual([{ x: 5, yFraction: 0.25 }, undefined]);
+ });
+
+ it('copes with a plot that does not want to know where the other plots are hovered', () => {
+ const group = Symbol('group');
+ const plot1 = testSyncer(group);
+ const plot2 = new AxisSyncer('x', { onZoom: () => {}, onLog: () => {}, onNaturalRangeChanged: () => {} });
+
+ syncers.push(plot2);
+ plot2.setGroup(group, LINEAR);
+
+ expect(() => {
+ plot1.syncer.setHover({ x: 5, yFraction: 0.25 });
+ }).not.toThrow();
+ });
+
+ it('keeps the natural range of a group right if a plot gives its own while being told about it', () => {
+ // Our second plot gives a wider natural range as soon as it gets told that the natural range of our group has
+ // changed, which our first plot should end up with.
+
+ const group = Symbol('group');
+ let plot2: TestSyncer | undefined;
+ const plot1 = testSyncer(group);
+
+ plot2 = testSyncer(group, LINEAR, 'x', () => {
+ plot2?.syncer.naturalRange([0, 100]);
+ });
+
+ plot1.syncer.naturalRange([0, 10]);
+
+ expect(plot1.syncer.naturalRange([0, 10])).toEqual([0, 100]);
+ expect(plot1.nbOfNaturalRangeChanges()).toBe(1);
+ });
+});
diff --git a/src/common/syncUtils.ts b/src/common/syncUtils.ts
new file mode 100644
index 0000000..6e7e8cc
--- /dev/null
+++ b/src/common/syncUtils.ts
@@ -0,0 +1,272 @@
+// Some utilities to synchronise the axes of plots, i.e. to have plots that are in the same group share the range and
+// the scale (i.e. linear or logarithmic) of an axis, so that zooming, panning, or resetting the zoom of one of them
+// does the same to the others (see the xAxisSync and yAxisSync props of PlotWidget.vue).
+// Note: ranges are shared as they are plotted, i.e. as the decimal logarithm of their values along a logarithmic axis
+// (see plotValue() in PlotWidget.vue), which is fine since the plots in a group always share their scale.
+
+import type { PlotGroup } from './common';
+import type { Range } from './rangeUtils';
+
+/** An axis that can be synchronised. */
+
+export type SyncAxis = 'x' | 'y';
+
+/** The state of an axis that the plots in a group share. */
+
+export interface SyncAxisState {
+ /** The range into which the axis is zoomed, if any, or `undefined` if the axis is autoranged. */
+ zoomRange: Range | undefined;
+ /** Whether the axis is logarithmic. */
+ log: boolean;
+}
+
+/**
+ * Where a plot of a group is hovered, so that the other plots in the group can show their hover guide and tooltip there
+ * too.
+ */
+
+export interface SyncHover {
+ /** The X value at which the plot shows its hover guide (as it is plotted, see the note at the top of this file). */
+ x: number;
+ /** How far down the plotting area the mouse pointer (or finger) is, from 0 at its top to 1 at its bottom. */
+ yFraction: number;
+}
+
+/** What a plot gets told about the other plots in its group. */
+
+export interface AxisSyncerHandlers {
+ /** Another plot zoomed into the given range (or reset its zoom, if `undefined`), animating over the given time. */
+ onZoom: (zoomRange: Range | undefined, duration: number) => void;
+ /** Another plot changed the scale of the axis, which is now in the given state. */
+ onLog: (state: SyncAxisState) => void;
+ /** The natural range of the group (see AxisSyncer.naturalRange()) changed because of another plot. */
+ onNaturalRangeChanged: () => void;
+ /** Another plot is hovered at the given place (or is not hovered anymore, if `undefined`). */
+ onHover?: (hover: SyncHover | undefined) => void;
+}
+
+export const sameRange = (firstRange: Range | undefined, secondRange: Range | undefined): boolean => {
+ // Return whether the given ranges are the same, with no range only being the same as no range.
+
+ if (firstRange === undefined || secondRange === undefined) {
+ return firstRange === secondRange;
+ }
+
+ return firstRange[0] === secondRange[0] && firstRange[1] === secondRange[1];
+};
+
+const copiedRange = (range: Range | undefined): Range | undefined => {
+ return range && [range[0], range[1]];
+};
+
+const copiedState = (state: SyncAxisState): SyncAxisState => {
+ return { zoomRange: copiedRange(state.zoomRange), log: state.log };
+};
+
+interface Group {
+ members: Set;
+ state: SyncAxisState;
+ naturalRange: Range | undefined;
+ hoveredMember: AxisSyncer | undefined;
+}
+
+// Our groups for each axis, i.e. the syncers (i.e. plots) that are in each of them, the state of their axis, their
+// natural range, and which of them is hovered, if any.
+// Note #1: the groups of our X axes are separate from those of our Y axes, so that the same group can be used for both
+// without the X axis of a plot being synchronised with the Y axis of another.
+// Note #2: a group gets removed once it is empty, so that we don't keep track of groups that are not used anymore.
+
+const groups: Record> = {
+ x: new Map(),
+ y: new Map()
+};
+
+export class AxisSyncer {
+ // The syncer of an axis of a plot, which shares the state of that axis with the other plots in its group, if any, and
+ // tells it (using the given handlers) when another plot in its group changes that state. It also keeps track of the
+ // natural range of its plot (i.e. the range that it would autorange its axis to on its own) and gives it the natural
+ // range of its group, i.e. the union of the natural ranges of the plots in its group, so that they all autorange
+ // their axis to the same range. Finally, it tells the other plots in its group where its plot is hovered, if
+ // anywhere.
+ // Note: a plot doesn't get told about its own changes, so that it doesn't apply them twice.
+
+ private groupKey: PlotGroup | undefined;
+ private natural: Range | undefined;
+
+ constructor(
+ private readonly axis: SyncAxis,
+ private readonly handlers: AxisSyncerHandlers
+ ) {}
+
+ private group(): Group | undefined {
+ return this.groupKey === undefined ? undefined : groups[this.axis].get(this.groupKey);
+ }
+
+ private otherMembers(group: Group): AxisSyncer[] {
+ return [...group.members].filter((member: AxisSyncer) => member !== this);
+ }
+
+ isInGroup(): boolean {
+ return this.groupKey !== undefined;
+ }
+
+ setGroup(groupKey: PlotGroup | undefined, state: SyncAxisState): SyncAxisState | undefined {
+ // Leave our current group, if any, and join the given one, if any. If it already has some plots, then return its
+ // state, which our plot must adopt. Otherwise, our group gets the given state (i.e. that of our plot).
+ // Note: we forget our natural range when joining a group, since it may be in the wrong scale for our group (e.g.,
+ // if our axis is linear while the axis of our group is logarithmic), so that our plot gives it again once it
+ // has adopted the state of our group (see naturalRange()).
+
+ if (groupKey === this.groupKey) {
+ return undefined;
+ }
+
+ const oldGroup = this.group();
+
+ if (oldGroup) {
+ this.setHover(undefined);
+
+ oldGroup.members.delete(this);
+
+ if (oldGroup.members.size === 0) {
+ groups[this.axis].delete(this.groupKey as PlotGroup);
+ } else {
+ AxisSyncer.updateNaturalRange(oldGroup, []);
+ }
+ }
+
+ this.groupKey = groupKey;
+
+ if (groupKey === undefined) {
+ return undefined;
+ }
+
+ this.natural = undefined;
+
+ const group = groups[this.axis].get(groupKey);
+
+ if (!group) {
+ groups[this.axis].set(groupKey, {
+ members: new Set([this]),
+ state: copiedState(state),
+ naturalRange: undefined,
+ hoveredMember: undefined
+ });
+
+ return undefined;
+ }
+
+ group.members.add(this);
+
+ return copiedState(group.state);
+ }
+
+ setHover(hover: SyncHover | undefined): void {
+ // Our plot is hovered at the given place (or is not hovered anymore, if undefined), so tell the other plots in our
+ // group, if any, so that they can show their hover guide and tooltip there too (or hide them).
+ // Note: only the plot that is hovered can stop the hover of our group, so that a plot that stops being hovered
+ // after another one has started being hovered (e.g., when the mouse pointer goes from one plot to another)
+ // doesn't stop the hover of that other plot.
+
+ const group = this.group();
+
+ if (!group || (!hover && group.hoveredMember !== this)) {
+ return;
+ }
+
+ group.hoveredMember = hover ? this : undefined;
+
+ for (const member of this.otherMembers(group)) {
+ member.handlers.onHover?.(hover && { x: hover.x, yFraction: hover.yFraction });
+ }
+ }
+
+ setZoom(zoomRange: Range | undefined, duration: number): void {
+ // Our plot zoomed into the given range (or reset its zoom, if undefined), so tell the other plots in our group, if
+ // any, so that they do the same.
+
+ const group = this.group();
+
+ if (!group) {
+ return;
+ }
+
+ group.state.zoomRange = copiedRange(zoomRange);
+
+ for (const member of this.otherMembers(group)) {
+ member.handlers.onZoom(copiedRange(zoomRange), duration);
+ }
+ }
+
+ setLog(state: SyncAxisState): void {
+ // Our plot changed the scale of its axis, which is now in the given state, so tell the other plots in our group, if
+ // any, so that they do the same.
+ // Note: the natural ranges of the plots in our group are in the wrong scale now, so we forget them, and the plots
+ // give them again once they have changed their scale (see naturalRange()).
+
+ const group = this.group();
+
+ if (!group) {
+ return;
+ }
+
+ group.state = copiedState(state);
+ group.naturalRange = undefined;
+
+ for (const member of group.members) {
+ member.natural = undefined;
+ }
+
+ for (const member of this.otherMembers(group)) {
+ member.handlers.onLog(copiedState(state));
+ }
+ }
+
+ naturalRange(naturalRange: Range | undefined): Range | undefined {
+ // Keep track of the given natural range of our plot (undefined if it has nothing to autorange to, e.g., if it has
+ // no data) and return the natural range of our group, if any, i.e. the union of the natural ranges of the plots in
+ // our group, or the given natural range otherwise. If the natural range of our group has changed, then tell the
+ // other plots in our group, so that they can autorange their axis to it.
+
+ this.natural = copiedRange(naturalRange);
+
+ const group = this.group();
+
+ if (!group) {
+ return copiedRange(naturalRange);
+ }
+
+ AxisSyncer.updateNaturalRange(group, [this]);
+
+ return copiedRange(group.naturalRange);
+ }
+
+ private static updateNaturalRange(group: Group, ignoredMembers: AxisSyncer[]): void {
+ // Update the natural range of the given group and, if it has changed, tell its members about it, except for the
+ // given ones.
+ // Note: we first update the natural range of our group and only then tell its members about it, in case one of them
+ // was to straight away change our group (e.g., by giving its own natural range).
+
+ let naturalRange: Range | undefined;
+
+ for (const member of group.members) {
+ if (member.natural) {
+ naturalRange = naturalRange
+ ? [Math.min(naturalRange[0], member.natural[0]), Math.max(naturalRange[1], member.natural[1])]
+ : [member.natural[0], member.natural[1]];
+ }
+ }
+
+ if (sameRange(naturalRange, group.naturalRange)) {
+ return;
+ }
+
+ group.naturalRange = naturalRange;
+
+ for (const member of [...group.members]) {
+ if (!ignoredMembers.includes(member)) {
+ member.handlers.onNaturalRangeChanged();
+ }
+ }
+ }
+}
diff --git a/src/common/touchUtils.ts b/src/common/touchUtils.ts
index 9fa691f..ddbe1be 100644
--- a/src/common/touchUtils.ts
+++ b/src/common/touchUtils.ts
@@ -21,8 +21,8 @@ export const axisEndSize = (axisLength: number, minSize: number): number => {
export const pinchShift = (length: number, startCenter: number, center: number, factor: number): number => {
// Return the largest distance by which a pinch moves something along an axis of the given length, i.e. once the given
- // start center of that pinch has moved to the given center and everything around it has been scaled by the inverse
- // of the given factor (see pinchedRange()).
+ // start center of that pinch has moved to the given center and everything around it has been scaled by the inverse of
+ // the given factor (see pinchedRange()).
// Note: that distance varies linearly along our axis, so it is largest at one of its ends.
const shift = (position: number): number => Math.abs(center + (position - startCenter) / factor - position);
diff --git a/src/widgets/PlotWidget.vue b/src/widgets/PlotWidget.vue
index c00981f..394a988 100644
--- a/src/widgets/PlotWidget.vue
+++ b/src/widgets/PlotWidget.vue
@@ -181,12 +181,15 @@ import * as vue from 'vue';
import 'uplot/dist/uPlot.min.css';
+import { MarginsAligner } from '../common/alignUtils';
import { createChunkedPath, MAX_PATH_POINTS } from '../common/chunkedPathUtils';
import * as common from '../common/common';
+import type { PlotGroup } from '../common/common';
import * as levelOfDetailUtils from '../common/levelOfDetailUtils';
import * as pathLevelOfDetailUtils from '../common/pathLevelOfDetailUtils';
import { isValidRange, pinchedRange, type Range, scaledRange } from '../common/rangeUtils';
import { SimplifiedPath, TraceSmoothness } from '../common/simplifiedPathUtils';
+import { AxisSyncer, type SyncAxisState, type SyncHover, sameRange } from '../common/syncUtils';
import { roundDTick, ticksBetween } from '../common/ticksUtils';
import {
type LogValues,
@@ -268,18 +271,6 @@ export interface PlotData {
traces: PlotTrace[];
}
-/**
- * The left and right margins of a plot, i.e. the space taken by its Y axis and legend. To line up several plots, pass
- * the largest left and right margins that their `marginsUpdated` events gave to the `margins` prop of each of them.
- */
-
-export interface PlotMargins {
- /** The left margin (in pixels), i.e. the space taken by the Y axis and its title. */
- left: number;
- /** The right margin (in pixels), i.e. the space taken by the legend. */
- right: number;
-}
-
/** The payload of the `csvExport` event when an export to CSV has started. */
export interface PlotCsvExportStartedEvent {
@@ -323,6 +314,34 @@ export interface PlotImageExportEvent {
success: boolean;
}
+/**
+ * The payload of the `rangesUpdated` event, i.e. the current ranges of the axes (in actual units, even along a
+ * logarithmic axis) and whether each axis is zoomed (rather than autoranged). To restore them later, give
+ * `{ x: zoomed.x ? x : null, y: zoomed.y ? y : null }` to the `setRanges()` method, so that an autoranged axis stays
+ * autoranged.
+ */
+
+export interface PlotRanges {
+ /** The range of the X axis. */
+ x: [number, number];
+ /** The range of the Y axis. */
+ y: [number, number];
+ /** Whether each axis is zoomed, i.e. whether it has been zoomed or panned rather than autoranged. */
+ zoomed: { x: boolean; y: boolean };
+}
+
+/**
+ * The ranges to give to the `setRanges()` method, i.e. the range (in actual units, even along a logarithmic axis) into
+ * which to zoom an axis, `null` to reset the zoom of an axis, or nothing to leave an axis as it is.
+ */
+
+export interface PlotRangesToSet {
+ /** The range into which to zoom the X axis, or `null` to reset its zoom. */
+ x?: [number, number] | null;
+ /** The range into which to zoom the Y axis, or `null` to reset its zoom. */
+ y?: [number, number] | null;
+}
+
/** The value of the `theme` prop, i.e. whether to use light or dark mode, or whatever the system uses. */
export type PlotTheme = 'system' | 'light' | 'dark';
@@ -387,8 +406,38 @@ const props = withDefaults(
defineProps<{
/** The data to plot (see `PlotData`). */
data: PlotData;
- /** Margins shared with other plots, so that their plotting areas line up (see the `marginsUpdated` event). */
- margins?: PlotMargins;
+ /**
+ * The group of plots (a string or a symbol) whose X axes are to line up with ours, i.e. whose plotting areas are to
+ * have the same left and right edges as ours (e.g., when they are stacked). A symbol is unique, so that unrelated
+ * parts of a page can't end up in the same group by using the same string.
+ */
+ xAxisAlign?: PlotGroup;
+ /**
+ * The group of plots (a string or a symbol) whose X axis is to be synchronised with ours, i.e. which share the
+ * range and the scale of their X axis, so that zooming, panning, or resetting the zoom of one of them does the same
+ * to the others, as does making its X axis logarithmic (or not). Their X axes always show the same range, which,
+ * until one of them gets zoomed or panned, fits the data of all of them. Hovering one of them also shows the hover
+ * guide and tooltip of the others at the same X value, so that the values of all of them can be read at once. For a
+ * trace whose X values are not sorted (e.g., a phase plot), the others show the point that is closest to where the
+ * mouse pointer would be (i.e. at their guide line and at the same relative height as the mouse pointer), if any is
+ * close enough to it. A symbol is unique, so that unrelated parts of a page can't end up in the same group by using
+ * the same string.
+ */
+ xAxisSync?: PlotGroup;
+ /**
+ * The group of plots (a string or a symbol) whose Y axes are to line up with ours, i.e. whose plotting areas are to
+ * have the same top and bottom edges as ours (e.g., when they are side by side). A symbol is unique, so that
+ * unrelated parts of a page can't end up in the same group by using the same string.
+ */
+ yAxisAlign?: PlotGroup;
+ /**
+ * The group of plots (a string or a symbol) whose Y axis is to be synchronised with ours, i.e. which share the
+ * range and the scale of their Y axis, so that zooming, panning, or resetting the zoom of one of them does the same
+ * to the others, as does making its Y axis logarithmic (or not). Their Y axes always show the same range, which,
+ * until one of them gets zoomed or panned, fits the data of all of them. A symbol is unique, so that unrelated
+ * parts of a page can't end up in the same group by using the same string.
+ */
+ yAxisSync?: PlotGroup;
/**
* Whether to show the legend (`true` by default). The legend takes at most 40% of the width of the plot (with long
* trace names truncated, and shown in full when hovered or in the context menu of their legend item), and is hidden
@@ -442,10 +491,10 @@ const emit = defineEmits<{
*/
imageExport: [event: PlotImageExportEvent];
/**
- * 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 the `margins` prop of each of them.
+ * The range of an axis has changed, or whether it is zoomed has (see `PlotRanges`). It is emitted at most once per
+ * frame, including while the plot is being zoomed, panned, or animated, and while its data gets updated.
*/
- marginsUpdated: [newMargins: PlotMargins];
+ rangesUpdated: [ranges: PlotRanges];
}>();
// Some constants (in CSS pixels, where relevant).
@@ -534,15 +583,6 @@ const relayoutPlot = (): void => {
}
};
-const resetMargins = (): void => {
- // Forget the margins that we last emitted, so that we emit our current margins (e.g., when the shared margins we are
- // given have been reset).
-
- trackedMargins = undefined;
-
- updateMarginsAsync();
-};
-
const contextMenuHidden = (): void => {
// Our custom context menu has been hidden (see PlotContextMenuEvent), so do as if it was our context menu.
@@ -615,6 +655,42 @@ const memoryUsage = (): PlotMemoryUsage => {
return res;
};
+const setRanges = (ranges: PlotRangesToSet, options: { animate?: boolean } = {}): void => {
+ // Zoom our axes into the given ranges (which are in actual units) and/or reset their zoom (see PlotRangesToSet), as
+ // if the user had done it, so that the plots with which an axis is synchronised, if any, do the same with it.
+ // Note: a range is ignored if it can't be plotted (e.g., if it has a non-positive end along a logarithmic axis, or if
+ // its two ends are the same), while its two ends can be given in any order.
+
+ const duration = options.animate ? ZOOM_ANIMATION_DURATION : 0;
+ const newZoomRanges: Partial> = {};
+ const resetAxisKeys: AxisKey[] = [];
+
+ for (const axisKey of ['x', 'y'] as AxisKey[]) {
+ const range = ranges[axisKey];
+
+ if (range === null) {
+ resetAxisKeys.push(axisKey);
+ } else if (range) {
+ const plotRange: Range = [
+ plotValue(axisKey, Math.min(range[0], range[1])),
+ plotValue(axisKey, Math.max(range[0], range[1]))
+ ];
+
+ if (isValidRange(plotRange)) {
+ newZoomRanges[axisKey] = plotRange;
+ }
+ }
+ }
+
+ if (Object.keys(newZoomRanges).length) {
+ zoomTo(newZoomRanges, duration);
+ }
+
+ if (resetAxisKeys.length) {
+ resetZoom(resetAxisKeys, duration);
+ }
+};
+
// Note: we give the type of our methods explicitly, so that their JSDoc comments make it into our type declarations.
/** The methods of the plot, which are available through a template ref. */
@@ -635,15 +711,20 @@ interface PlotMethods {
* It is not reactive, i.e. it is meant to be polled. Mainly meant for testing and benchmarking.
*/
pointCounts: () => PlotPointCounts;
- /** Emit the `marginsUpdated` event again (e.g., after the shared margins have been reset). */
- resetMargins: () => void;
+ /**
+ * Zoom the axes into the given ranges (in actual units, even along a logarithmic axis) and/or reset their zoom (see
+ * `PlotRangesToSet`), as if the user had done it (so, a synchronised axis gets updated in all the plots of its
+ * group), animating the change if `options.animate` is set (`false` by default). A range that can't be plotted (e.g.,
+ * with a non-positive end along a logarithmic axis, or with two ends that are the same) is ignored.
+ */
+ setRanges: (ranges: PlotRangesToSet, options?: { animate?: boolean }) => void;
}
defineExpose({
contextMenuHidden,
memoryUsage,
pointCounts,
- resetMargins
+ setRanges
});
const mainDivRef = vue.shallowRef(null);
@@ -661,7 +742,27 @@ let isUnmounted = false;
let stopTrackingContainerSize: (() => void) | undefined;
let stopTrackingLegendSize: (() => void) | undefined;
let marginsUpdatePending = false;
-let trackedMargins: PlotMargins | undefined;
+
+// Our margins aligners, which share our margins along each axis with the other plots in the alignment group of that
+// axis, if any, and let us know when our shared margins change, so that we can update our layout (see
+// updateMarginsAsync()). Along our X axis, our margins are our left and right margins (i.e. the space taken by our Y
+// axis and our legend), while along our Y axis, they are our top and bottom margins (i.e. the space taken by our X
+// axis).
+// Note: we relayout our plot on the next tick, so that we use our new shared margins once Vue has applied any other
+// changes (e.g., to our data).
+
+const onSharedMarginsChanged = (): void => {
+ if (!isUnmounted) {
+ void vue.nextTick().then(() => {
+ relayoutPlot();
+ });
+ }
+};
+
+const marginsAligners: Record = {
+ x: new MarginsAligner('x', onSharedMarginsChanged),
+ y: new MarginsAligner('y', onSharedMarginsChanged)
+};
// Whether our axes are logarithmic, which can be changed using our context menu (see contextMenuItems and Logarithmic
// axes below).
@@ -1240,8 +1341,8 @@ const onLegendPointerDown = (event: PointerEvent, index: number): void => {
};
const onLegendPressMove = (event: PointerEvent): void => {
- // Keep track of how far our pointer has moved, in case it can't become a long press anymore or, if it already has,
- // in case it has moved far enough for its long press to be cancelled (e.g., to back out of showing our context menu),
+ // Keep track of how far our pointer has moved, in case it can't become a long press anymore or, if it already has, in
+ // case it has moved far enough for its long press to be cancelled (e.g., to back out of showing our context menu),
// since, unlike on our plotting area and axes, a drag doesn't mean anything else on a legend item.
// Note: the click that may follow the release of our pointer still gets swallowed (see onLongPress()), so that it
// doesn't toggle the visibility of a trace (or do anything else).
@@ -2535,11 +2636,11 @@ let zoomTitles: string | undefined;
// simulation is running). They get reset when the user resets the zoom (using our context menu or by
// double-clicking on our plotting area, on a corner, or on the middle of an axis, in which case only the zoom
// along that axis gets reset) or when our axis titles change (i.e. when we are plotting something else, see
-// updatePlot()).
+// updatePlot()), unless that axis is synchronised with other plots (see axisSyncers).
-const naturalRange = (u: uPlot, axisKey: AxisKey): Range => {
- // Return the natural range of the given axis, i.e. the given range for the axis, if any, or the autorange of our data
- // otherwise.
+const ownNaturalRange = (u: uPlot, axisKey: AxisKey): Range | undefined => {
+ // Return our own natural range for the given axis, i.e. the given range for the axis, if any, or the autorange of our
+ // data otherwise, or undefined if we have nothing to autorange to (e.g., if we have no data).
// If a range was given for the axis and it can be plotted (i.e. it is finite and, for a logarithmic axis, positive,
// see plotValue()), then we use it.
@@ -2574,8 +2675,8 @@ const naturalRange = (u: uPlot, axisKey: AxisKey): Range => {
if (!finiteRange) {
// No (finite) data, so if some of our traces are hidden (e.g., the user hid all of them using our legend), then we
- // keep our last autorange (so that the user sees the same view when showing some traces again). Otherwise, we use
- // Plotly's default range.
+ // keep our last autorange (so that the user sees the same view when showing some traces again). Otherwise, we have
+ // nothing to autorange to.
const lastAutoRange = lastAutoRanges[axisKey];
@@ -2583,7 +2684,7 @@ const naturalRange = (u: uPlot, axisKey: AxisKey): Range => {
return [...lastAutoRange];
}
- return axisKey === 'x' ? [...DEFAULT_X_RANGE] : [...DEFAULT_Y_RANGE];
+ return undefined;
}
const [min, max] = finiteRange;
@@ -2599,6 +2700,23 @@ const naturalRange = (u: uPlot, axisKey: AxisKey): Range => {
return [...res];
};
+const naturalRange = (u: uPlot, axisKey: AxisKey): Range => {
+ // Return the natural range of the given axis, i.e. our own natural range or, if the axis is synchronised with other
+ // plots, the union of their natural ranges and ours (see axisSyncers), so that we all autorange the axis to the same
+ // range. If there is nothing to autorange to (e.g., if there is no data), then we use Plotly's default range.
+ // Note: a plot that has nothing to autorange to doesn't use (nor give to other plots) Plotly's default range, so that
+ // it doesn't widen the range of the plots that have something to autorange to.
+
+ const ownRange = ownNaturalRange(u, axisKey);
+ const range = axisSyncers[axisKey].naturalRange(ownRange);
+
+ if (range) {
+ return range;
+ }
+
+ return axisKey === 'x' ? [...DEFAULT_X_RANGE] : [...DEFAULT_Y_RANGE];
+};
+
const scaleRange = (axisKey: AxisKey): uPlot.Range.Function => {
return (u: uPlot): Range => {
// If the axis is being animated, then we use its animated range (e.g., if our data gets updated while we are
@@ -2854,7 +2972,7 @@ const finishRangeAnimation = (): void => {
const zoomTo = (ranges: Partial>, duration: number = 0): void => {
// Zoom into the given ranges, animating our zoom over the given duration, but only if they are all valid (see
- // isValidRange()).
+ // isValidRange()), and have the plots with which our axes are synchronised, if any, do the same with them.
for (const range of Object.values(ranges)) {
if (!isValidRange(range)) {
@@ -2870,6 +2988,10 @@ const zoomTo = (ranges: Partial>, duration: number = 0):
finishRangeAnimation();
setScales(ranges);
}
+
+ for (const [axisKey, range] of Object.entries(ranges) as [AxisKey, Range][]) {
+ axisSyncers[axisKey].setZoom(range, duration);
+ }
};
const zoomBy = (
@@ -2914,9 +3036,10 @@ const zoomOut = (): void => {
zoomBy(1 / ZOOM_FACTOR, ['x', 'y'], contextMenuCenterFractions, ZOOM_ANIMATION_DURATION);
};
-const resetZoom = (axisKeys: AxisKey[] = ['x', 'y']): void => {
- // Like Plotly, reset the zoom of the given axes, i.e. go back to the given ranges, if any, or autorange the axes, and
- // animate our reset.
+const resetZoom = (axisKeys: AxisKey[] = ['x', 'y'], duration: number = ZOOM_ANIMATION_DURATION): void => {
+ // Like Plotly, reset the zoom of the given axes, i.e. go back to the given ranges, if any, or autorange the axes,
+ // animating our reset over the given duration, and have the plots with which our axes are synchronised, if any, do
+ // the same with them.
const ranges: Partial> = {};
@@ -2926,40 +3049,288 @@ const resetZoom = (axisKeys: AxisKey[] = ['x', 'y']): void => {
ranges[axisKey] = null;
}
- animateScales(ranges, ZOOM_ANIMATION_DURATION);
+ animateScales(ranges, duration);
+
+ for (const axisKey of axisKeys) {
+ axisSyncers[axisKey].setZoom(undefined, duration);
+ }
+};
+
+// Our current ranges, which we emit (see the rangesUpdated event) whenever they change. We check whether they have
+// changed whenever our plot gets drawn, which it does whenever our scales get set (see Note #2 of setScales()) or our
+// data gets updated (in which case our axes may get autoranged).
+// Note #1: we emit our ranges at most once per frame. The first time they change in a frame, we emit them in a
+// microtask (so that they are emitted in the frame in which they changed, rather than one frame late), while
+// any further change in that frame gets emitted in the next frame.
+// Note #2: we only emit our ranges if they (or whether our axes are zoomed) have changed since we last emitted them.
+
+let rangesUpdatePending = false;
+let rangesFrameId: number | undefined;
+let lastRanges: PlotRanges | undefined;
+let lastRangesFrameTime: number | undefined;
+
+const currentRanges = (): PlotRanges | undefined => {
+ // Return our current ranges, in actual units, if we have a plot.
+
+ const xRange = currentRange('x');
+ const yRange = currentRange('y');
+
+ if (!xRange || !yRange) {
+ return undefined;
+ }
+
+ return {
+ x: [actualValue('x', xRange[0]), actualValue('x', xRange[1])],
+ y: [actualValue('y', yRange[0]), actualValue('y', yRange[1])],
+ zoomed: { x: zoomRanges.x !== undefined, y: zoomRanges.y !== undefined }
+ };
+};
+
+const sameRanges = (firstRanges: PlotRanges, secondRanges: PlotRanges | undefined): boolean => {
+ return (
+ 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] &&
+ firstRanges.zoomed.x === secondRanges.zoomed.x &&
+ firstRanges.zoomed.y === secondRanges.zoomed.y
+ );
+};
+
+const emitRanges = (): void => {
+ // Emit our current ranges, if they have changed since we last emitted them.
+
+ rangesUpdatePending = false;
+ rangesFrameId = undefined;
+
+ if (isUnmounted) {
+ return;
+ }
+
+ const ranges = currentRanges();
+
+ if (!ranges || sameRanges(ranges, lastRanges)) {
+ return;
+ }
+
+ lastRanges = ranges;
+ lastRangesFrameTime = frameTime();
+
+ emit('rangesUpdated', ranges);
+};
+
+const updateRangesAsync = (): void => {
+ // Emit our current ranges in a microtask or, if we have already emitted them in the current frame, in the next frame,
+ // coalescing multiple requests into a single one.
+
+ if (rangesUpdatePending) {
+ return;
+ }
+
+ rangesUpdatePending = true;
+
+ queueMicrotask(() => {
+ if (frameTime() === lastRangesFrameTime) {
+ rangesFrameId = common.requestFrame(emitRanges);
+ } else {
+ emitRanges();
+ }
+ });
};
// Logarithmic axis toggling (see contextMenuItems).
const toggleLogAxis = (axisKey: AxisKey): void => {
// Toggle whether the given axis is logarithmic, keeping its zoom range, if any and if possible (i.e. unless it has a
- // non-positive end and the axis becomes logarithmic, in which case the axis gets autoranged), and replot our data
- // (see plotData()).
+ // non-positive end and the axis becomes logarithmic, in which case the axis gets autoranged), and have the plots with
+ // which the axis is synchronised, if any, do the same with it.
// Note: the ranges of a logarithmic axis are the decimal logarithm of its actual ranges (see plotValue()), hence we
- // convert its zoom range and forget its last autorange.
+ // convert its zoom range.
finishRangeAnimation();
+ const log = !logAxes.value[axisKey];
const zoomRange = zoomRanges[axisKey];
const actualZoomRange: Range | undefined = zoomRange && [
actualValue(axisKey, zoomRange[0]),
actualValue(axisKey, zoomRange[1])
];
+ let newZoomRange: Range | undefined;
- logAxes.value = { ...logAxes.value, [axisKey]: !logAxes.value[axisKey] };
+ if (actualZoomRange) {
+ const toPlotValue = (value: number): number => (log ? Math.log10(value) : value);
+
+ newZoomRange = [toPlotValue(actualZoomRange[0]), toPlotValue(actualZoomRange[1])];
+
+ if (!Number.isFinite(newZoomRange[0]) || !Number.isFinite(newZoomRange[1]) || newZoomRange[0] >= newZoomRange[1]) {
+ newZoomRange = undefined;
+ }
+ }
+
+ axisSyncers[axisKey].setLog({ zoomRange: newZoomRange, log });
+
+ setLogAxis(axisKey, log, newZoomRange);
+};
+
+const setLogAxis = (axisKey: AxisKey, log: boolean, zoomRange: Range | undefined): void => {
+ // Make the given axis logarithmic (or not) with the given zoom range, if any (which is in the new scale of the axis),
+ // and replot our data (see plotData()).
+ // Note: we forget the last autorange of the axis since it is in the old scale of the axis.
+
+ finishRangeAnimation();
+
+ logAxes.value = { ...logAxes.value, [axisKey]: log };
+
+ if (zoomRange) {
+ zoomRanges[axisKey] = zoomRange;
+ } else {
+ delete zoomRanges[axisKey];
+ }
- delete zoomRanges[axisKey];
delete lastAutoRanges[axisKey];
- if (actualZoomRange) {
- const newZoomRange: Range = [plotValue(axisKey, actualZoomRange[0]), plotValue(axisKey, actualZoomRange[1])];
+ updatePlot();
+};
+
+// Axis synchronisation, i.e. the plots in the synchronisation group of an axis, if any, share the range and the scale
+// of that axis (see AxisSyncer), so whenever one of them zooms, pans, resets the zoom of that axis, or toggles whether
+// it is logarithmic, the others do the same, and while that axis is not zoomed, they all autorange it to the union of
+// their natural ranges (see naturalRange()). The plots in our X axis synchronisation group also share where they are
+// hovered (see Note #2 of the hover functionality section).
+// Note #1: a change that comes from another plot doesn't get shared again (i.e. we don't use zoomTo(), resetZoom(), nor
+// toggleLogAxis() to apply it), so that it doesn't echo back and forth.
+// Note #2: the natural range of a group may change because of another plot (e.g., its data got updated), in which case
+// we autorange our axis again (or update the target of its animation), if needed. We do so in a microtask
+// since we may be told about it while the other plot is being drawn, but still before the browser gets to
+// paint us, so that we don't lag behind it.
+
+const naturalRangeUpdatesPending: Record = { x: false, y: false };
+
+const applyGroupZoom = (axisKey: AxisKey, zoomRange: Range | undefined, duration: number): void => {
+ // Zoom the given axis into the given range (or reset its zoom, if undefined), animating it over the given duration.
+
+ if (zoomRange) {
+ zoomRanges = { ...zoomRanges, [axisKey]: zoomRange };
+ } else {
+ delete zoomRanges[axisKey];
+ }
+
+ animateScales({ [axisKey]: zoomRange ?? null }, duration);
+};
+
+const updateNaturalRangeAsync = (axisKey: AxisKey): void => {
+ // Autorange the given axis again (or update the target of its animation), if it is not zoomed and if the natural
+ // range of its group has changed, coalescing multiple requests into a single microtask.
+
+ if (naturalRangeUpdatesPending[axisKey]) {
+ return;
+ }
+
+ naturalRangeUpdatesPending[axisKey] = true;
+
+ queueMicrotask(() => {
+ naturalRangeUpdatesPending[axisKey] = false;
+
+ const u = plot;
+
+ if (!u || isUnmounted) {
+ return;
+ }
+
+ // If we are animating our axis to its natural range, then update the target of our animation.
+
+ if (rangeAnimation?.final[axisKey] === null) {
+ rangeAnimation.to[axisKey] = naturalRange(u, axisKey);
+
+ return;
+ }
+
+ // Autorange our axis again if it is not zoomed (nor animated) and if its natural range has changed.
+
+ if (zoomRanges[axisKey] || animatedRanges[axisKey]) {
+ return;
+ }
+
+ const range = currentRange(axisKey);
+ const newRange = naturalRange(u, axisKey);
+
+ if (!range || range[0] !== newRange[0] || range[1] !== newRange[1]) {
+ setScales({ [axisKey]: null });
+ }
+ });
+};
+
+const onGroupHover = (hover: SyncHover | undefined): void => {
+ // Another plot of our X axis synchronisation group is hovered at the given place (or is not hovered anymore), so show
+ // our hover guide and tooltip there too (or hide them, see updateHover()).
+ // Note: we update our hover straight away rather than in the next frame (see queueHoverUpdate()), so that our hover
+ // tooltip doesn't lag behind that of the hovered plot.
+
+ groupHover = hover;
+
+ if (!isUnmounted) {
+ updateHover();
+ }
+};
- if (Number.isFinite(newZoomRange[0]) && Number.isFinite(newZoomRange[1]) && newZoomRange[0] < newZoomRange[1]) {
- zoomRanges[axisKey] = newZoomRange;
+const axisSyncer = (axisKey: AxisKey): AxisSyncer => {
+ // Return a syncer for the given axis, which applies the changes that come from the other plots in its group.
+
+ return new AxisSyncer(axisKey, {
+ onZoom: (zoomRange: Range | undefined, duration: number) => {
+ if (!isUnmounted) {
+ applyGroupZoom(axisKey, zoomRange, duration);
+ }
+ },
+ onLog: (state: SyncAxisState) => {
+ if (!isUnmounted) {
+ setLogAxis(axisKey, state.log, state.zoomRange);
+ }
+ },
+ onNaturalRangeChanged: () => {
+ if (!isUnmounted) {
+ updateNaturalRangeAsync(axisKey);
+ }
+ },
+ onHover: axisKey === 'x' ? onGroupHover : undefined
+ });
+};
+
+const axisSyncers: Record = {
+ x: axisSyncer('x'),
+ y: axisSyncer('y')
+};
+
+const joinAxisSyncGroup = (axisKey: AxisKey, group: PlotGroup | undefined): void => {
+ // Leave the current synchronisation group of the given axis, if any, and join the given one, if any, adopting the
+ // state of its axis if it already has some plots (or giving it ours otherwise).
+
+ const groupState = axisSyncers[axisKey].setGroup(group, {
+ zoomRange: zoomRanges[axisKey],
+ log: logAxes.value[axisKey]
+ });
+
+ // Forget where another plot of our previous X axis synchronisation group was hovered, if anywhere.
+
+ if (axisKey === 'x' && groupHover) {
+ groupHover = undefined;
+
+ updateHover();
+ }
+
+ if (groupState) {
+ if (groupState.log !== logAxes.value[axisKey]) {
+ setLogAxis(axisKey, groupState.log, groupState.zoomRange);
+ } else {
+ applyGroupZoom(axisKey, groupState.zoomRange, 0);
}
}
- updatePlot();
+ // Our natural range may have changed (e.g., it is now the union of the natural ranges of the plots in our new group,
+ // or our own natural range if we are not in a group anymore).
+
+ updateNaturalRangeAsync(axisKey);
};
// Pointer interaction (i.e. using a mouse, a pen, or a finger), like with Plotly:
@@ -4327,11 +4698,20 @@ const cancelDrag = (): void => {
};
const restoreRanges = (ranges: Partial>): void => {
- // Restore the given ranges, i.e. those that we had when a drag (or a pinch, see startPinch()) started.
+ // Restore the given ranges, i.e. those that we had when a drag (or a pinch, see startPinch()) started, and have the
+ // plots with which our axes are synchronised, if any, do the same with those that have changed.
+
+ const changedAxisKeys = (['x', 'y'] as AxisKey[]).filter(
+ (axisKey: AxisKey) => !sameRange(zoomRanges[axisKey], ranges[axisKey])
+ );
zoomRanges = { ...ranges };
setScales({ x: zoomRanges.x ?? null, y: zoomRanges.y ?? null });
+
+ for (const axisKey of changedAxisKeys) {
+ axisSyncers[axisKey].setZoom(zoomRanges[axisKey], 0);
+ }
};
const isNearStart = (x: number, y: number, startX: number, startY: number): boolean => {
@@ -4419,8 +4799,8 @@ const onLongPress = (pointerId: number, clientX: number, clientY: number): void
top: clientY - (mainDivRect?.top ?? 0)
};
- // Swallow the click and ignore the context menu that may follow the release of our finger (or pen), whether or not
- // it then shows our context menu (e.g., not if it has been dragged or backed out of), since the browser may still
+ // Swallow the click and ignore the context menu that may follow the release of our finger (or pen), whether or not it
+ // then shows our context menu (e.g., not if it has been dragged or backed out of), since the browser may still
// emulate a right-click once a pointer that was held has been released (e.g., with a pen on Windows). So, keep track
// of when our finger (or pen) gets released (see Note #4 above).
// Note: we can't use swallowClick to ignore that context menu since it gets reset by the click that may follow the
@@ -5100,8 +5480,8 @@ const yAxisTitleSize = (): number => {
};
const yAxisSize = (): number => {
- // Size our Y axis (without its title) based on the width of its widest tick label or, if we are given some shared
- // margins, based on the shared left margin (but never less than what we need).
+ // Size our Y axis (without its title) based on the width of its widest tick label or, if we have some shared margins
+ // along our X axis (see marginsAligners), based on our shared left margin (but never less than what we need).
// Note: uPlot computes our tick labels (see axisValues()) before the size of our axis, so our Y tick labels are up to
// date.
@@ -5113,22 +5493,25 @@ const yAxisSize = (): number => {
naturalYAxisSize = Math.ceil(maxWidth + Y_AXIS_EXTRA_SIZE);
- return props.margins ? Math.max(naturalYAxisSize, props.margins.left - yAxisTitleSize()) : naturalYAxisSize;
+ const sharedMargins = marginsAligners.x.sharedMargins();
+
+ return sharedMargins ? Math.max(naturalYAxisSize, sharedMargins.start - yAxisTitleSize()) : naturalYAxisSize;
};
// Right margin, which we use to make sure that our legend and last X tick label are not cut off.
const legendRightMargin = (): number => {
// Return the right margin needed by our legend (if any), with a margin on both sides of it (see legendLeft).
- // Note: this is our natural right margin, i.e. the right margin that we share with our sibling panels (see
- // updateMarginsAsync()).
+ // Note: this is our natural right margin, i.e. the right margin that we share with the other plots in our X axis
+ // alignment group, if any (see updateMarginsAsync()).
return legendWidth ? Math.ceil(LEGEND_LEFT_MARGIN + legendWidth + LEGEND_RIGHT_MARGIN) : 0;
};
const rightMargin = (): number => {
- // Our right margin must leave room for our legend (or, if we are given some shared margins, for the shared right
- // margin) and for half our last X tick label (since it is centred on its tick), with a margin on its right side.
+ // Our right margin must leave room for our legend (or, if we have some shared margins along our X axis, for our
+ // shared right margin) and for half our last X tick label (since it is centred on its tick), with a margin on its
+ // right side.
// Note #1: our legend is to the right of our plotting area and no taller than it while our last X tick label is below
// our plotting area, so they can't overlap and our right margin only needs to fit the wider of the two. In
// practice, our last X tick label only matters when we don't have a legend (e.g., in the standard view or if
@@ -5139,40 +5522,58 @@ const rightMargin = (): number => {
// date.
const lastXValue = tickValues.x[tickValues.x.length - 1];
- const legendSize = props.margins ? Math.max(legendRightMargin(), props.margins.right) : legendRightMargin();
+ const sharedMargins = marginsAligners.x.sharedMargins();
+ const legendSize = sharedMargins ? Math.max(legendRightMargin(), sharedMargins.end) : legendRightMargin();
const lastXTickLabelSize = lastXValue ? 0.5 * textWidth(lastXValue, tickFont()) + LEGEND_RIGHT_MARGIN : 0;
return Math.ceil(Math.max(legendSize, lastXTickLabelSize));
};
+// Top and bottom margins, i.e. the space above our plotting area (none) and below it (taken by our X axis), which we
+// share with the other plots in our Y axis alignment group, if any (see marginsAligners), so that our plotting areas
+// line up when side by side.
+
+const naturalBottomMargin = (): number => {
+ // Return the size of our X axis, including its title, if any (see the X axis in createPlot()).
+
+ return props.data.xAxisTitle ? X_AXIS_SIZE_WITH_TITLE + X_AXIS_TITLE_SIZE : X_AXIS_SIZE_WITHOUT_TITLE;
+};
+
+const topPadding = (): number => {
+ // Return the space that we need above our plotting area for it to line up with that of the other plots in our Y axis
+ // alignment group, if any.
+
+ return marginsAligners.y.sharedMargins()?.start ?? 0;
+};
+
+const bottomPadding = (): number => {
+ // Return the space that we need below our X axis for our plotting area to line up with that of the other plots in our
+ // Y axis alignment group, if any.
+
+ const sharedMargins = marginsAligners.y.sharedMargins();
+
+ return sharedMargins ? Math.max(0, sharedMargins.end - naturalBottomMargin()) : 0;
+};
+
// Update our margins asynchronously, i.e. after our plot has been laid out and we know how much space it needs for its
-// axes and legend. This allows us to share our margins with other instances of PlotWidget, so that they can align their
-// plots with ours.
-// Note #1: we emit our natural margins (i.e. the margins that we need) whenever they change, and get given some shared
-// margins (i.e. the biggest natural margins of all our sibling panels), which we then use (see yAxisSize() and
-// rightMargin()).
-// Note #2: our natural margins must not depend on our shared margins, or our sibling panels could keep adjusting to
+// axes and legend. This allows us to share our margins with the other plots in our alignment groups, if any, so that
+// our plotting areas line up.
+// Note #1: we give our natural margins (i.e. the margins that we need) to our margins aligners whenever they change,
+// and get some shared margins (i.e. the biggest natural margins of all the plots in our groups) from them,
+// which we then use (see marginsAligners, yAxisSize(), rightMargin(), topPadding(), and bottomPadding()).
+// Note #2: our natural margins must not depend on our shared margins, or the plots in our group could keep adjusting to
// each other's margins. Our natural left margin depends on our Y tick labels, i.e. on the height of our
// plotting area, which doesn't depend on our shared margins. However, our last X tick label depends on our X
// ticks, i.e. on the width of our plotting area, which does depend on our shared margins. So, our natural
-// right margin only accounts for our legend (see legendRightMargin()) and each panel makes room for its own
-// last X tick label (see rightMargin()). The (unlikely) cost is that a panel which last X tick label needs
-// more room than our shared right margin has a narrower plotting area than its sibling panels.
-
-const sameMargins = (firstMargins: PlotMargins | undefined, secondMargins: PlotMargins | undefined): boolean => {
- return (
- firstMargins !== undefined &&
- secondMargins !== undefined &&
- firstMargins.left === secondMargins.left &&
- firstMargins.right === secondMargins.right
- );
-};
+// right margin only accounts for our legend (see legendRightMargin()) and each plot makes room for its own
+// last X tick label (see rightMargin()). The (unlikely) cost is that a plot which last X tick label needs more
+// room than our shared right margin has a narrower plotting area than the other plots in our group.
const updateMarginsAsync = (): void => {
// Coalesce multiple margin update requests into a single microtask.
- // Note: we use a microtask rather than an animation frame, so that our sibling panels (and ourselves) get relaid out
- // using our new shared margins before the browser gets to paint us (e.g., while being resized). Otherwise, our
- // sibling panels would be misaligned for one frame, i.e. they would flicker.
+ // Note: we use a microtask rather than an animation frame, so that the plots in our group (including ourselves) get
+ // relaid out using our new shared margins before the browser gets to paint us (e.g., while being resized).
+ // Otherwise, they would be misaligned for one frame, i.e. they would flicker.
if (marginsUpdatePending) {
return;
@@ -5189,19 +5590,17 @@ const updateMarginsAsync = (): void => {
return;
}
- // Emit our natural margins if they have changed.
+ // Give our natural margins to our margins aligners, which only do something if they have changed.
// Note: our natural right margin only accounts for our legend (see legendRightMargin()).
- const newMargins = {
- left: naturalYAxisSize + yAxisTitleSize(),
- right: legendRightMargin()
- };
-
- if (!sameMargins(newMargins, trackedMargins)) {
- trackedMargins = newMargins;
-
- emit('marginsUpdated', newMargins);
- }
+ marginsAligners.x.setNaturalMargins({
+ start: naturalYAxisSize + yAxisTitleSize(),
+ end: legendRightMargin()
+ });
+ marginsAligners.y.setNaturalMargins({
+ start: 0,
+ end: naturalBottomMargin()
+ });
});
};
@@ -6201,8 +6600,14 @@ const setPlotSize = (u: uPlot, width: number, height: number): void => {
// Hover functionality, i.e. a tooltip that lists the value of each of our visible traces at the X value that is under
// the mouse pointer (like Plotly's 'x unified' hover mode), with a vertical guide line at that X value and the
// corresponding points of our traces highlighted.
-// Note: a trace which X values are not sorted (e.g., a phase plot) doesn't have one value per X value, so we use its
-// point that is closest to the mouse pointer instead (like Plotly's 'closest' hover mode).
+// Note #1: a trace which X values are not sorted (e.g., a phase plot) doesn't have one value per X value, so we use its
+// point that is closest to the mouse pointer instead (like Plotly's 'closest' hover mode).
+// Note #2: if our X axis is synchronised with other plots (see axisSyncers), then we show our hover guide and tooltip
+// at the X value at which another plot of our group is hovered, if any (and we are not hovered ourselves), so
+// that the values of all of our plots can be read at once. We then do as if the mouse pointer was at that X
+// value and at the same relative height as the mouse pointer (or finger) in the hovered plot, i.e. our tooltip
+// is next to our guide line at that height. So, for a trace which X values are not sorted (see Note #1), we
+// use its point that is closest to that position, if any is close enough to it.
interface HoverPoint {
seriesIndex: number;
@@ -6219,6 +6624,9 @@ interface HoverRow {
}
interface Hover {
+ local: boolean; // Whether we are hovered ourselves, rather than another plot of our X axis synchronisation group.
+ xValue: number; // The X value of our guide line (as it is plotted).
+ yFraction: number; // The relative height of the mouse pointer (or finger) in the hovered plot.
clientX: number;
clientY: number;
aboveFinger: boolean;
@@ -6232,6 +6640,7 @@ interface Hover {
const hover = vue.shallowRef(null);
let hoverRafId: number | undefined;
+let groupHover: SyncHover | undefined; // Where another plot of our X axis synchronisation group is hovered, if any.
const formatHoverValue = (value: number): string => {
// Like Plotly, format a value in our hover tooltip using the value itself as the tick spacing and adding four digits
@@ -6379,39 +6788,56 @@ const hoveredIndex = (
};
const updateHover = (): void => {
- // Make sure that we have a plot, that the mouse pointer is over our plotting area, and that we are not dragging
- // (unless we are scrubbing, see the scrubbing section above).
+ // Make sure that we have a plot and that we are not dragging (unless we are scrubbing, see the scrubbing section
+ // above).
const u = plot;
const rect = plotRect.value;
const mainDiv = mainDivRef.value;
- const left = u?.cursor.left;
- const top = u?.cursor.top;
const area = u ? pathArea(u) : undefined;
- if (
- !u ||
- !rect ||
- !mainDiv ||
- !area ||
- (drag && !drag.scrubbing) ||
- left == null ||
- top == null ||
- left < 0 ||
- top < 0
- ) {
+ if (!u || !rect || !mainDiv || !area || (drag && !drag.scrubbing)) {
hover.value = null;
return;
}
- // Determine the point of each of our visible traces that gets hovered, if any, and the X value of the one that is the
- // closest to the mouse pointer (horizontally), which is the X value that we show in our hover tooltip.
+ // Determine where we are hovered, i.e. where the mouse pointer is, if it is over our plotting area, or where another
+ // plot of our X axis synchronisation group is hovered, if anywhere (see Note #2 of the hover functionality section
+ // above), and hide our hover tooltip if we are not hovered.
// Note: we use our plotting area in CSS pixels (since the position of the mouse pointer is in CSS pixels).
const cssArea: PathArea = { ...area, ...rect, pxRatio: 1 };
const xFactor = cssArea.width / (cssArea.xMax - cssArea.xMin);
const yFactor = cssArea.height / (cssArea.yMax - cssArea.yMin);
+ const cursorLeft = u.cursor.left;
+ const cursorTop = u.cursor.top;
+ let local = false;
+ let left: number | undefined;
+ let top: number | undefined;
+
+ if (cursorLeft != null && cursorTop != null && cursorLeft >= 0 && cursorTop >= 0) {
+ local = true;
+ left = cursorLeft;
+ top = cursorTop;
+ } else if (groupHover) {
+ const groupLeft = (groupHover.x - cssArea.xMin) * xFactor;
+
+ if (groupLeft >= 0 && groupLeft <= cssArea.width) {
+ left = groupLeft;
+ top = groupHover.yFraction * cssArea.height;
+ }
+ }
+
+ if (left === undefined || top === undefined) {
+ hover.value = null;
+
+ return;
+ }
+
+ // Determine the point of each of our visible traces that gets hovered, if any, and the X value of the one that is the
+ // closest to where we are hovered (horizontally), which is the X value that we show in our hover tooltip.
+
const hoveredIndices = new Map();
let xValue = Number.NaN;
let xDistance = Number.POSITIVE_INFINITY;
@@ -6481,23 +6907,28 @@ const updateHover = (): void => {
});
}
- // Show our hover tooltip at the mouse pointer (in CSS pixels) and our guide line at our X value.
+ // Show our hover tooltip at the mouse pointer (in CSS pixels) or, if another plot of our X axis synchronisation group
+ // is hovered, next to our guide line, and our guide line at our X value.
// Note: like our grid and zero lines (see linesPath()), our guide line is snapped to whole device pixels and is a
// whole number of device pixels wide (see lineWidth()), so that it is crisp whatever our pixel ratio.
const mainDivRect = mainDiv.getBoundingClientRect();
const pxRatio = uPlot.pxRatio;
const guideWidth = lineWidth(pxRatio);
+ const guideX = (Math.round((xValue - cssArea.xMin) * xFactor * pxRatio) + 0.5 * (guideWidth % 2)) / pxRatio;
if (!hover.value) {
updateOverlayThemeStyle();
}
hover.value = {
- clientX: mainDivRect.left + rect.left + left,
+ local,
+ xValue,
+ yFraction: top / cssArea.height,
+ clientX: mainDivRect.left + rect.left + (local ? left : guideX),
clientY: mainDivRect.top + rect.top + top,
- aboveFinger: isDirectPointer(lastPointerType),
- guideX: (Math.round((xValue - cssArea.xMin) * xFactor * pxRatio) + 0.5 * (guideWidth % 2)) / pxRatio,
+ aboveFinger: local && isDirectPointer(lastPointerType),
+ guideX,
guideWidth: guideWidth / pxRatio,
points,
x: formatHoverValue(actualValue('x', xValue)),
@@ -6789,7 +7220,7 @@ const createPlot = (width: number, height: number): void => {
mode: 2,
width,
height,
- padding: [0, rightMargin, 0, 0],
+ padding: [topPadding, rightMargin, bottomPadding, 0],
legend: {
show: false
},
@@ -6863,12 +7294,14 @@ const createPlot = (width: number, height: number): void => {
updatePlotRect(u);
updateLivePoints(u);
updateMarginsAsync();
+ updateRangesAsync();
- // Update our hover tooltip if we have one or if the mouse pointer is over our plotting area, since our plot
- // may have changed (e.g., our data got updated or we zoomed in/out), i.e. our tooltip may have to change,
- // disappear, or appear (e.g., when a live trace reaches the mouse pointer).
+ // Update our hover tooltip if we have one, if the mouse pointer is over our plotting area, or if another
+ // plot of our X axis synchronisation group is hovered, since our plot may have changed (e.g., our data got
+ // updated or we zoomed in/out), i.e. our tooltip may have to change, disappear, or appear (e.g., when a
+ // live trace reaches the mouse pointer or the X value at which another plot of our group is hovered).
- if (hover.value || (u.cursor.left ?? -1) >= 0) {
+ if (hover.value || groupHover || (u.cursor.left ?? -1) >= 0) {
queueHoverUpdate();
}
}
@@ -6965,8 +7398,13 @@ const updatePlot = (): void => {
const titles = `${props.data.xAxisTitle ?? ''}::${props.data.yAxisTitle ?? ''}`;
if (titles !== zoomTitles) {
+ // Note: we keep the zoom range of an axis that is synchronised with other plots, since it is theirs too (see
+ // axisSyncers).
+
zoomTitles = titles;
- zoomRanges = {};
+ zoomRanges = Object.fromEntries(
+ Object.entries(zoomRanges).filter(([axisKey]) => axisSyncers[axisKey as AxisKey].isInGroup())
+ );
delete lastAutoRanges.x;
delete lastAutoRanges.y;
@@ -7081,6 +7519,17 @@ vue.onBeforeUnmount(() => {
isUnmounted = true;
+ // Leave our alignment groups, if any, so that the other plots in them stop making room for our margins.
+
+ marginsAligners.x.setGroup(undefined);
+ marginsAligners.y.setGroup(undefined);
+
+ // Leave our axis synchronisation groups, if any, so that the other plots in them stop autoranging their axes to fit
+ // our data.
+
+ axisSyncers.x.setGroup(undefined, { zoomRange: zoomRanges.x, log: logAxes.value.x });
+ axisSyncers.y.setGroup(undefined, { zoomRange: zoomRanges.y, log: logAxes.value.y });
+
// Stop tracking whether the system uses light mode.
prefersColorScheme?.removeEventListener('change', onPrefersColorSchemeChange);
@@ -7104,6 +7553,12 @@ vue.onBeforeUnmount(() => {
hoverRafId = undefined;
}
+ if (rangesFrameId !== undefined) {
+ common.cancelFrame(rangesFrameId);
+
+ rangesFrameId = undefined;
+ }
+
stopDrag();
stopLegendPress();
stopTrackingLongPressRelease();
@@ -7139,28 +7594,51 @@ vue.watch(
{ immediate: true }
);
-// Update the layout of our plot when our shared margins change.
+// Join the alignment group of our axes, if any, and leave their previous one, if any, when it changes.
+// Note: our margins aligners let us know if our shared margins change as a result, in which case we relayout our plot
+// (see marginsAligners).
vue.watch(
- () => props.margins,
- (newMargins: PlotMargins | undefined, oldMargins: PlotMargins | undefined) => {
- // Nothing to do if our margins haven't actually changed (e.g., if we were given a new object with the same values).
+ () => props.xAxisAlign,
+ (xAxisAlign: PlotGroup | undefined) => {
+ marginsAligners.x.setGroup(xAxisAlign);
+ },
+ { immediate: true }
+);
- if (sameMargins(newMargins, oldMargins)) {
- return;
- }
+vue.watch(
+ () => props.yAxisAlign,
+ (yAxisAlign: PlotGroup | undefined) => {
+ marginsAligners.y.setGroup(yAxisAlign);
+ },
+ { immediate: true }
+);
- void vue.nextTick().then(() => {
- relayoutPlot();
+// Tell the other plots of our X axis synchronisation group, if any, where we are hovered, if anywhere, so that they can
+// show their hover guide and tooltip there too (see Note #2 of the hover functionality section).
+// Note: we only tell them where we are hovered ourselves, not where we show the hover of another plot of our group.
+
+vue.watch(hover, (newHover: Hover | null) => {
+ axisSyncers.x.setHover(newHover?.local ? { x: newHover.xValue, yFraction: newHover.yFraction } : undefined);
+});
- // If we are not given shared margins anymore, then emit our margins again (since they may be needed to compute
- // new shared margins).
+// Join the synchronisation group of our axes, if any, and leave their previous one, if any, when it changes (see
+// axisSyncers).
- if (!props.margins) {
- resetMargins();
- }
- });
- }
+vue.watch(
+ () => props.xAxisSync,
+ (xAxisSync: PlotGroup | undefined) => {
+ joinAxisSyncGroup('x', xAxisSync);
+ },
+ { immediate: true }
+);
+
+vue.watch(
+ () => props.yAxisSync,
+ (yAxisSync: PlotGroup | undefined) => {
+ joinAxisSyncGroup('y', yAxisSync);
+ },
+ { immediate: true }
);
// Redraw our plot when we are to use our level of detail or not.