Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guide/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ export const chart = new Chart('id', {
| `speed` | `number` | `0.1` | Factor of zoom speed applied per notch of a mouse wheel
| `modifierKey` | `'ctrl'`\|`'alt'`\|`'shift'`\|`'meta'` | `null` | Modifier key required for zooming via mouse wheel

The first wheel event zooms at once. The events that follow it before the next animation frame are applied together in that frame, around the position of the latest one, so a stream of events updates the chart, and calls `onZoom`, once per frame.

#### Drag options

| Name | Type | Default | Description
Expand Down
58 changes: 54 additions & 4 deletions src/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { directionEnabled, debounce, keyNotPressed, getModifierKey, keyPressed } from './utils'
import { zoom, zoomRect } from './core'
import { getRelativePosition, _isPointInArea } from 'chart.js/helpers'
import { getState, type HandlerFunctions, type HandlerName } from './state'
import { getRelativePosition, _isPointInArea, requestAnimFrame } from 'chart.js/helpers'
import { getState, type HandlerFunctions, type HandlerName, type State, type WheelZoom } from './state'
import type { Chart, ChartArea } from 'chart.js'
import type { ModeOption, ZoomOptions, ZoomPluginOptions } from './options'
import type { Point } from './types'
Expand Down Expand Up @@ -268,11 +268,59 @@ function wheelDistance(event: WheelEvent, pageHeight: number): number {
}
}

// A zoom by `a` leaves `2 - a` of the range, so two zooms in a row leave the
// product of what each leaves.
const combineZoom = (a: number, b: number) => 2 - (2 - a) * (2 - b)

function cancelWheelFrame(state: State) {
if (state.wheelFrame !== undefined) {
cancelAnimationFrame(state.wheelFrame)
}
state.wheelFrame = state.wheelZoom = undefined
}

// Zooms, and requests a frame in which to zoom by what the wheel events until
// then add up to. As long as there is something to do in that frame, the next
// one is requested as well, so that a steady stream of events gives one chart
// update per frame.
function zoomByWheel(chart: Chart, state: State, amount: WheelZoom) {
zoom(chart, amount, 'zoom', 'wheel')
// Where there is no window, the helper calls back at once and returns
// nothing, so every event zooms right away.
state.wheelFrame = requestAnimFrame(() => {
const pending = state.wheelZoom
state.wheelFrame = state.wheelZoom = undefined
if (pending) {
zoomByWheel(chart, state, pending)
}
})
}

/**
* A touchpad sends wheel events faster than a large chart can update. Updating
* for each of them makes the events queue up behind the updates, and the chart
* falls further and further behind the gesture.
*
* The first event zooms right away. The ones that follow before the next frame
* are added up and applied together in that frame.
*/
function queueWheelZoom(chart: Chart, state: State, amount: WheelZoom) {
if (state.wheelFrame === undefined) {
zoomByWheel(chart, state, amount)
return
}
const pending = state.wheelZoom
state.wheelZoom = pending
? { x: combineZoom(pending.x, amount.x), y: combineZoom(pending.y, amount.y), focalPoint: amount.focalPoint }
: amount
}

export function wheel(chart: Chart, event: WheelEvent & { target?: HTMLCanvasElement }) {
const state = getState(chart)
const {
handlers: { onZoomComplete },
options: { zoom: zoomOptions = {} },
} = getState(chart)
} = state

if (!wheelPreconditions(chart, event, zoomOptions)) {
return
Expand All @@ -292,7 +340,7 @@ export function wheel(chart: Chart, event: WheelEvent & { target?: HTMLCanvasEle
},
}

zoom(chart, amount, 'zoom', 'wheel')
queueWheelZoom(chart, state, amount)

onZoomComplete?.(event)
}
Expand All @@ -319,6 +367,7 @@ export function addListeners(chart: Chart, options: ZoomPluginOptions) {
addHandler(chart, canvas, 'wheel', wheel)
addDebouncedHandler(chart, 'onZoomComplete', onZoomComplete, 250)
} else {
cancelWheelFrame(getState(chart))
removeHandler(chart, 'wheel')
}
if (dragOptions?.enabled) {
Expand All @@ -333,6 +382,7 @@ export function addListeners(chart: Chart, options: ZoomPluginOptions) {
}

export function removeListeners(chart: Chart) {
cancelWheelFrame(getState(chart))
removeHandler(chart, 'mousedown')
removeHandler(chart, 'mousemove')
removeHandler(chart, 'mouseup')
Expand Down
5 changes: 5 additions & 0 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export type Handlers = Partial<Record<HandlerName, Handler>>

export type HandlerTarget = Partial<Record<HandlerName, HTMLCanvasElement | Document>>

export type WheelZoom = { x: number; y: number; focalPoint: Point }

export interface State {
originalScaleLimits: OriginalScaleLimits
updatedScaleLimits: UpdatedScaleLimits
Expand All @@ -37,6 +39,9 @@ export interface State {
scale?: number | null
delta?: Point | null
panScales?: string[]
/** The frame in which the wheel events that came after the last zoom are applied. */
wheelFrame?: number
wheelZoom?: WheelZoom
}

const chartStates = new WeakMap<Chart, State>()
Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/zoom/category-x.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { clearCanvas } from 'chart.js/helpers'
import { triggerWheelEvent } from '../../utils.js'
import { wheelInOwnFrame } from '../../utils.js'

const labels = []
const data = []
Expand Down Expand Up @@ -49,14 +49,14 @@ export default {
},
},
options: {
run(chart) {
async run(chart) {
const steps = 16
const n = Math.sqrt(steps)
const side = 512 / n
for (let i = 0; i < steps; i++) {
const col = i % n
const row = Math.floor(i / n)
triggerWheelEvent(chart, {
await wheelInOwnFrame(chart, {
x: 255,
y: 255,
deltaY: -100,
Expand Down
6 changes: 3 additions & 3 deletions test/fixtures/zoom/zoom-reset.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { clearCanvas } from 'chart.js/helpers'
import { triggerWheelEvent } from '../../utils.js'
import { wheelInOwnFrame } from '../../utils.js'

const labels = []
const data = []
Expand Down Expand Up @@ -49,15 +49,15 @@ export default {
},
},
options: {
run(chart) {
async run(chart) {
const steps = 4
const n = Math.sqrt(steps)
const side = 512 / n
for (let i = 0; i < steps; i++) {
const col = i % n
const row = Math.floor(i / n)
if (i > 0 && i < steps - 1) {
triggerWheelEvent(chart, {
await wheelInOwnFrame(chart, {
x: 255,
y: 255,
deltaY: -100,
Expand Down
124 changes: 116 additions & 8 deletions test/specs/zoom.wheel.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { acquireChart, triggerMouseEvent } from 'chartjs-test-utils'
import { triggerWheelEvent } from '../utils.js'
import { nextFrame, triggerWheelEvent, wheelInOwnFrame } from '../utils.js'

describe('zoom with wheel', function () {
const data = {
Expand Down Expand Up @@ -258,7 +258,7 @@ describe('zoom with wheel', function () {
})

describe('with logarithmic scale', function () {
it('should zoom correctly when mouse in center of chart', function () {
it('should zoom correctly when mouse in center of chart', async function () {
const config = {
type: 'line',
data: {
Expand Down Expand Up @@ -299,18 +299,18 @@ describe('zoom with wheel', function () {
expect(scaleY.min).toBe(1)
expect(scaleY.max).toBe(10000)

triggerWheelEvent(chart, zoomIn)
await wheelInOwnFrame(chart, zoomIn)

expect(scaleY.min).toBeCloseTo(1.6, 1)
expect(scaleY.max).toBeCloseTo(6310, -1)

triggerWheelEvent(chart, zoomIn)
await wheelInOwnFrame(chart, zoomIn)

expect(scaleY.min).toBeCloseTo(2.4, 1)
expect(scaleY.max).toBeCloseTo(4170, -1)

triggerWheelEvent(chart, zoomOut)
triggerWheelEvent(chart, zoomOut)
await wheelInOwnFrame(chart, zoomOut)
await wheelInOwnFrame(chart, zoomOut)

expect(scaleY.min).toBe(1)
expect(scaleY.max).toBe(10000)
Expand All @@ -320,12 +320,12 @@ describe('zoom with wheel', function () {
expect(scaleY.min).toBe(1)
expect(scaleY.max).toBe(10000)

triggerWheelEvent(chart, zoomOut)
await wheelInOwnFrame(chart, zoomOut)

expect(scaleY.min).toBeCloseTo(0.6, 1)
expect(scaleY.max).toBeCloseTo(16700, -2)

triggerWheelEvent(chart, zoomIn)
await wheelInOwnFrame(chart, zoomIn)

expect(scaleY.min).toBeCloseTo(1)
expect(scaleY.max).toBeCloseTo(10000)
Expand Down Expand Up @@ -531,4 +531,112 @@ describe('zoom with wheel', function () {
expect(chart.scales.x.min).toBe(1)
})
})

describe('events that arrive faster than frames', function () {
function createChart(onZoom) {
return acquireChart({
type: 'scatter',
data: {
datasets: [
{
data: [
{ x: 0, y: 0 },
{ x: 100, y: 100 },
],
},
],
},
options: {
scales: { x: { min: 0, max: 100 }, y: { min: 0, max: 100 } },
plugins: { zoom: { zoom: { wheel: { enabled: true }, mode: 'x', onZoom } } },
},
})
}

function wheelAtCenter(chart, deltaY) {
const { left, right, top, bottom } = chart.scales.x
triggerWheelEvent(chart, { x: (left + right) / 2, y: (top + bottom) / 2 - 20, deltaY })
}

it('should zoom for the first event at once', function () {
const onZoom = vi.fn()
const chart = createChart(onZoom)

wheelAtCenter(chart, -100)

expect(chart.scales.x.max - chart.scales.x.min).toBeCloseTo(90, 10)
expect(onZoom).toHaveBeenCalledTimes(1)
})

it('should apply the events of one frame together in the next frame', async function () {
const onZoom = vi.fn()
const chart = createChart(onZoom)

for (let i = 0; i < 4; i++) {
wheelAtCenter(chart, -100)
}

// Only the first one has zoomed.
expect(chart.scales.x.max - chart.scales.x.min).toBeCloseTo(90, 10)
expect(onZoom).toHaveBeenCalledTimes(1)

await nextFrame()

// Four steps that each leave 90% of the range.
expect(chart.scales.x.max - chart.scales.x.min).toBeCloseTo(100 * 0.9 ** 4, 10)
expect(onZoom).toHaveBeenCalledTimes(2)
})

it('should end up where zooming for each event would', async function () {
const steps = [-100, -6, 12, -100, 3]
const reference = createChart()
for (const deltaY of steps) {
wheelAtCenter(reference, deltaY)
await nextFrame()
}

const chart = createChart()
for (const deltaY of steps) {
wheelAtCenter(chart, deltaY)
}
await nextFrame()

expect(chart.scales.x.min).toBeCloseTo(reference.scales.x.min, 8)
expect(chart.scales.x.max).toBeCloseTo(reference.scales.x.max, 8)
})

it('should zoom at once again after a frame without events', async function () {
const chart = createChart()
wheelAtCenter(chart, -100)
await nextFrame()

wheelAtCenter(chart, -100)

expect(chart.scales.x.max - chart.scales.x.min).toBeCloseTo(81, 10)
})

it('should drop what is waiting when the wheel is turned off', async function () {
const chart = createChart()
wheelAtCenter(chart, -100)
wheelAtCenter(chart, -100)

chart.options.plugins.zoom.zoom.wheel.enabled = false
chart.update()
await nextFrame()

expect(chart.scales.x.max - chart.scales.x.min).toBeCloseTo(90, 10)
})

it('should drop what is waiting when the chart is destroyed', async function () {
const onZoom = vi.fn()
const chart = createChart(onZoom)
wheelAtCenter(chart, -100)
wheelAtCenter(chart, -100)

chart.destroy()
await nextFrame()

expect(onZoom).toHaveBeenCalledTimes(1)
})
})
})
9 changes: 9 additions & 0 deletions test/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,12 @@ export function simulatePinch(chart, { pos, scale = 2, steps = 5, angle = 0 } =
dispatchPointer(node, 'pointerup', 1, end[0].x, end[0].y)
dispatchPointer(node, 'pointerup', 2, end[1].x, end[1].y)
}

export const nextFrame = () => new Promise((resolve) => requestAnimationFrame(() => resolve()))

// Wheel events that follow each other within a frame are applied together, so
// a test that looks at the chart after each event gives each its own frame.
export async function wheelInOwnFrame(chart, init) {
triggerWheelEvent(chart, init)
await nextFrame()
}