Skip to content

Commit

Permalink
feat: chart bind autoFit in render
Browse files Browse the repository at this point in the history
  • Loading branch information
pepper-nice committed May 5, 2023
1 parent 1ba1fcd commit 3767316
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
34 changes: 34 additions & 0 deletions __tests__/unit/api/chart.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -619,4 +619,38 @@ describe('Chart', () => {
expect(chart.width()).toBeUndefined();
expect(chart.height()).toBeUndefined();
});

it('chart.options({ autoFit: true }) should bind autoFit.', async () => {
const div = document.createElement('div');
const chart = new Chart({
container: div,
});
chart.options({
autoFit: true,
theme: 'classic',
type: 'interval',
encode: {
x: 'genre',
y: 'sold',
},
data: [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
],
});

expect(chart['_hasBindAutoFit']).toBe(false);

await chart.render();
expect(chart['_hasBindAutoFit']).toBe(true);

chart.options({
autoFit: false,
});
await chart.render();
expect(chart['_hasBindAutoFit']).toBe(false);
});
});
18 changes: 14 additions & 4 deletions src/api/chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,17 +178,20 @@ export class Chart extends View<ChartOptions> {
private _options: G2ViewTree;
private _width: number;
private _height: number;
// Identifies whether bindAutoFit.
private _hasBindAutoFit = false;

constructor(options: ChartOptions) {
const { container, canvas, ...rest } = options || {};
super(rest, 'view');
this._container = normalizeContainer(container);
this._emitter = new EventEmitter();
this._context = { library, emitter: this._emitter, canvas };
this._bindAutoFit();
}

render(): Promise<Chart> {
this._bindAutoFit();

if (!this._context.canvas) {
// Init width and height.
const { renderer, plugins } = this.options();
Expand Down Expand Up @@ -339,15 +342,22 @@ export class Chart extends View<ChartOptions> {
private _bindAutoFit() {
const options = this.options();
const { autoFit } = options;

if (this._hasBindAutoFit) {
// If it was bind before, unbind it now.
if (!autoFit) this._unbindAutoFit();
return;
}

if (autoFit) {
this._hasBindAutoFit = true;
window.addEventListener('resize', this._onResize);
}
}

private _unbindAutoFit() {
const options = this.options();
const { autoFit } = options;
if (autoFit) {
if (this._hasBindAutoFit) {
this._hasBindAutoFit = false;
window.removeEventListener('resize', this._onResize);
}
}
Expand Down

0 comments on commit 3767316

Please sign in to comment.