Skip to content

Commit

Permalink
Add chart method for getting initial scale bounds (#585)
Browse files Browse the repository at this point in the history
* Add chart method for getting initial scale bounds

* Add types for initial scale bounds function

* Always return a {min, max} object, even if the scale is not found

Co-authored-by: Jukka Kurkela <[email protected]>

* Add `isZoomedOrPanned` API

* Add documentation for using the imperative API

* Fix type and documentation tests

Co-authored-by: Jonathan Frere <[email protected]>
Co-authored-by: Jukka Kurkela <[email protected]>
  • Loading branch information
3 people authored Sep 22, 2021
1 parent cf1966d commit 4e3a12d
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 4 deletions.
46 changes: 45 additions & 1 deletion docs/guide/developers.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,49 @@
# Developers

## Imperative Zoom/Pan API

Alongside user-driven interactions, it is also possible to imperatively interact with the chart, either to manually zoom into a selected region, or to get information about the current zoom status.

### `chart.pan(delta, scales?, mode = 'none'): void`

Pans the current chart by the specified amount in one or more axes. The value of `delta` can be a number, in which case all axes are panned by the same amount, or it can be an `{x, y}` object to pan different amounts in the horizontal and vertical directions. The value of `scales` is a list of scale objects that should be panned - by default, all scales of the chart will be panned. The value of `mode` should be one of the Chart.js [animation modes](https://www.chartjs.org/docs/latest/configuration/animations.html#default-transitions).

### `chart.zoom(zoomLevel, mode = 'none'): void`

Zooms the current chart by the specified amount in one more axes. The value of `zoomLevel` can be a number, in which case all axes are zoomed by the same amount, or it can be an `{x, y}` object to zoom different amounts in the horizontal and vertical directions. The value of `mode` should be one of the Chart.js [animation modes](https://www.chartjs.org/docs/latest/configuration/animations.html#default-transitions).

### `chart.zoomScale(scaleId, newRange, mode = 'none'): void`

Zooms the specified scale to the range given by `newRange`. This is an object in the form `{min, max}` and represents the new bounds of that scale. The value of `mode` should be one of the Chart.js [animation modes](https://www.chartjs.org/docs/latest/configuration/animations.html#default-transitions).

### `chart.resetZoom(mode = 'none'): void`

Resets the current chart bounds to the defaults that were used before any zooming or panning occurred. The value of `mode` should be one of the Chart.js [animation modes](https://www.chartjs.org/docs/latest/configuration/animations.html#default-transitions).

### `chart.getZoomLevel(): number`

Returns the current zoom level. If this is the same as the chart's initial scales, the value returned will be `1.0`. Otherwise, the value will be less than one if the chart has been zoomed out, and more than one if it has been zoomed in. If different axes have been zoomed by different amounts, the returned value will be the zoom level of the most zoomed out axis if any have been zoomed out, otherwise it will be the zoom level of the most zoomed-in axis.

If the chart has been panned but not zoomed, this method will still return `1.0`.

### `chart.getInitialScaleBounds(): Record<string, {min: number, max: number}>`

Returns the initial scale bounds of each scale before any zooming or panning took place. This is returned in the format of an object, e.g.

```json
{
x: {min: 0, max: 100},
y1: {min: 50, max: 80},
y2: {min: 0.1, max: 0.8}
}
```

### `chart.isZoomedOrPanned(): boolean`

Returns whether the chart has been zoomed or panned - i.e. whether the initial scale of any axis is different to the one used currently.

## Custom Scales

You can extend chartjs-plugin-zoom with support for [custom scales](https://www.chartjs.org/docs/latest/developers/axes.html) by using the zoom plugin's `zoomFunctions` and `panFunctions` members. These objects are indexed by scale types (scales' `id` members) and give optional handlers for zoom and pan functionality.

```js
Expand All @@ -23,7 +67,7 @@ The zoom and pan functions take the following arguments:
| `scale` | `Scale` | Zoom, Pan | The custom scale instance (usually derived from `Chart.Scale`)
| `zoom` | `number` | Zoom | The zoom fraction; 1.0 is unzoomed, 0.5 means zoomed in to 50% of the original area, etc.
| `center` | `{x, y}` | Zoom | Pixel coordinates of the center of the zoom operation. `{x: 0, y: 0}` is the upper left corner of the chart's canvas.
| `pan` | `number` | Pan | Pixel amount to pan by
| `delta` | `number` | Pan | Pixel amount to pan by
| `limits` | [Limits](./options#limits) | Zoom, Pan | Zoom and pan limits (from chart options)

For examples, see chartjs-plugin-zoom's [default zoomFunctions and panFunctions handling for standard Chart.js axes](https://github.com/chartjs/chartjs-plugin-zoom/blob/v1.0.1/src/scale.types.js#L128).
27 changes: 27 additions & 0 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,30 @@ export function pan(chart, delta, enabledScales, transition = 'none') {
call(onPan, [{chart}]);
}

export function getInitialScaleBounds(chart) {
const state = getState(chart);
const scaleBounds = {};
for (const scaleId of Object.keys(chart.scales)) {
const {min, max} = state.originalScaleLimits[scaleId] || {min: {}, max: {}};
scaleBounds[scaleId] = {min: min.scale, max: max.scale};
}

return scaleBounds;
}

export function isZoomedOrPanned(chart) {
const scaleBounds = getInitialScaleBounds(chart);
for (const scaleId of Object.keys(chart.scales)) {
const {min: originalMin, max: originalMax} = scaleBounds[scaleId];

if (chart.scales[scaleId].min !== originalMin) {
return true;
}

if (chart.scales[scaleId].max !== originalMax) {
return true;
}
}

return false;
}
4 changes: 3 additions & 1 deletion src/plugin.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Hammer from 'hammerjs';
import {addListeners, computeDragRect, removeListeners} from './handlers';
import {startHammer, stopHammer} from './hammer';
import {pan, zoom, resetZoom, zoomScale, getZoomLevel} from './core';
import {pan, zoom, resetZoom, zoomScale, getZoomLevel, getInitialScaleBounds, isZoomedOrPanned} from './core';
import {panFunctions, zoomFunctions} from './scale.types';
import {getState, removeState} from './state';
import {version} from '../package.json';
Expand Down Expand Up @@ -52,6 +52,8 @@ export default {
chart.zoomScale = (id, range, transition) => zoomScale(chart, id, range, transition);
chart.resetZoom = (transition) => resetZoom(chart, transition);
chart.getZoomLevel = () => getZoomLevel(chart);
chart.getInitialScaleBounds = () => getInitialScaleBounds(chart);
chart.isZoomedOrPanned = () => isZoomedOrPanned(chart);
},

beforeEvent(chart) {
Expand Down
93 changes: 93 additions & 0 deletions test/specs/api.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ describe('api', function() {
expect(typeof chart.zoom).toBe('function');
expect(typeof chart.zoomScale).toBe('function');
expect(typeof chart.resetZoom).toBe('function');
expect(typeof chart.getZoomLevel).toBe('function');
expect(typeof chart.getInitialScaleBounds).toBe('function');
});

describe('zoom and resetZoom', function() {
Expand Down Expand Up @@ -89,4 +91,95 @@ describe('api', function() {
expect(chart.scales.y.max).toBe(100);
});
});

describe('getInitialScaleBounds', function() {
it('should provide the correct initial scale bounds regardless of the zoom level', function() {
const chart = window.acquireChart({
type: 'scatter',
options: {
scales: {
x: {
min: 0,
max: 100
},
y: {
min: 0,
max: 100
}
}
}
});

chart.zoom(1);
expect(chart.getInitialScaleBounds().x.min).toBe(0);
expect(chart.getInitialScaleBounds().x.max).toBe(100);
expect(chart.getInitialScaleBounds().y.min).toBe(0);
expect(chart.getInitialScaleBounds().y.max).toBe(100);

chart.zoom({x: 1.5, y: 1.25});
expect(chart.getInitialScaleBounds().x.min).toBe(0);
expect(chart.getInitialScaleBounds().x.max).toBe(100);
expect(chart.getInitialScaleBounds().y.min).toBe(0);
expect(chart.getInitialScaleBounds().y.max).toBe(100);
});
});

describe('isZoomedOrPanned', function() {
it('should return whether or not the page is currently zoomed', function() {
const chart = window.acquireChart({
type: 'scatter',
options: {
scales: {
x: {
min: 0,
max: 100
},
y: {
min: 0,
max: 100
}
}
}
});

chart.zoom(1);
expect(chart.isZoomedOrPanned()).toBe(false);

chart.zoom({x: 1.5, y: 1.25});
expect(chart.isZoomedOrPanned()).toBe(true);

chart.zoom({x: 0.25, y: 0.5});
expect(chart.isZoomedOrPanned()).toBe(true);

chart.resetZoom();
expect(chart.isZoomedOrPanned()).toBe(false);
});

it('should return whether or not the page is currently panned', function() {
const chart = window.acquireChart({
type: 'scatter',
options: {
scales: {
x: {
min: 0,
max: 100
},
y: {
min: 0,
max: 100
}
}
}
});

chart.pan({x: 0, y: 0});
expect(chart.isZoomedOrPanned()).toBe(false);

chart.pan({x: 10});
expect(chart.isZoomedOrPanned()).toBe(true);

chart.resetZoom();
expect(chart.isZoomedOrPanned()).toBe(false);
});
});
});
6 changes: 5 additions & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ declare module 'chart.js' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Chart<TType extends keyof ChartTypeRegistry = keyof ChartTypeRegistry, TData = DistributiveArray<ChartTypeRegistry[TType]['defaultDataPoint']>, TLabel = unknown> {
pan(pan: PanAmount, scales?: Scale[], mode?: UpdateMode): void;
zoom(zoom: ZoomAmount, useTransition?: boolean, mode?: UpdateMode): void;
zoom(zoom: ZoomAmount, mode?: UpdateMode): void;
zoomScale(id: string, range: ScaleRange, mode?: UpdateMode): void;
resetZoom(mode?: UpdateMode): void;
getZoomLevel(): number;
getInitialScaleBounds(): Record<string, {min: number, max: number}>;
isZoomedOrPanned(): boolean;
}
}

Expand All @@ -48,3 +50,5 @@ export function zoom(chart: Chart, amount: ZoomAmount, mode?: UpdateMode): void;
export function zoomScale(chart: Chart, scaleId: string, range: ScaleRange, mode?: UpdateMode): void;
export function resetZoom(chart: Chart, mode?: UpdateMode): void;
export function getZoomLevel(chart: Chart): number;
export function getInitialScaleBounds(chart: Chart): Record<string, {min: number, max: number}>;
export function isZoomedOrPanned(chart: Chart): boolean;
2 changes: 1 addition & 1 deletion types/tests/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const chart = new Chart('id', {

chart.resetZoom();
chart.zoom(1.1);
chart.zoom({ x: 1, y: 1.1, focalPoint: { x: 10, y: 10 } }, true);
chart.zoom({ x: 1, y: 1.1, focalPoint: { x: 10, y: 10 } }, 'zoom');

chart.pan(10);
chart.pan({ x: 10, y: 20 }, [chart.scales.x]);
Expand Down

0 comments on commit 4e3a12d

Please sign in to comment.