Add resizeDelay option (#8509)

* Add resizeDelay option
* Extract helper
This commit is contained in:
Jukka Kurkela 2021-02-24 01:40:57 +02:00 committed by GitHub
parent 4207645a9a
commit ee74dd646a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 1 deletions

View File

@ -21,6 +21,7 @@ Namespace: `options`
| `maintainAspectRatio` | `boolean` | `true` | Maintain the original canvas aspect ratio `(width / height)` when resizing.
| `aspectRatio` | `number` | `2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.
| `onResize` | `function` | `null` | Called when a resize occurs. Gets passed two arguments: the chart instance and the new size.
| `resizeDelay` | `number` | `0` | Delay the resize update by give amount of milliseconds. This can ease the resize process by debouncing update of the elements.
## Important Note

View File

@ -11,6 +11,7 @@ import {each, callback as callCallback, uid, valueOrDefault, _elementsEqual} fro
import {clearCanvas, clipArea, unclipArea, _isPointInArea} from '../helpers/helpers.canvas';
// @ts-ignore
import {version} from '../../package.json';
import {debounce} from '../helpers/helpers.extras';
/**
* @typedef { import("../platform/platform.base").ChartEvent } ChartEvent
@ -122,6 +123,7 @@ class Chart {
this.attached = false;
this._animationsDisabled = undefined;
this.$context = undefined;
this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);
// Add the chart instance to the global namespace
instances[me.id] = me;
@ -242,7 +244,10 @@ class Chart {
callCallback(options.onResize, [newSize], me);
if (me.attached) {
me.update('resize');
if (me._doResize()) {
// The resize update is delayed, only draw without updating.
me.render();
}
}
}

View File

@ -40,6 +40,25 @@ export function throttled(fn, thisArg, updateFn) {
};
}
/**
* Debounces calling `fn` for `delay` ms
* @param {function} fn - Function to call. No arguments are passed.
* @param {number} delay - Delay in ms. 0 = immediate invocation.
* @returns {function}
*/
export function debounce(fn, delay) {
let timeout;
return function() {
if (delay) {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
} else {
fn();
}
return delay;
};
}
/**
* Converts 'start' to 'left', 'end' to 'right' and others to 'center'