Skip to content

Commit

Permalink
Merge pull request #59 from ScottLogic/add-debounce-to-chart-resize
Browse files Browse the repository at this point in the history
SFD-78: Add debounce to chart resize
  • Loading branch information
sdun-scottlogic authored Jun 10, 2024
2 parents 0119ad4 + 8bf00f4 commit 2296b29
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions src/app/carbon-estimation/carbon-estimation.component.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
import {
ChangeDetectorRef,
Component,
ElementRef,
HostListener,
OnInit,
ViewChild,
effect,
input,
} from '@angular/core';
import { ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild, effect, input } from '@angular/core';
import { CarbonEstimation, ChartOptions } from '../types/carbon-estimator';
import { NumberObject, sumValues } from '../utils/number-object';
import { ApexAxisChartSeries, ChartComponent, NgApexchartsModule } from 'ng-apexcharts';
Expand All @@ -22,6 +13,7 @@ import {
tooltipFormatter,
} from './carbon-estimation.constants';
import { ExpansionPanelComponent } from '../expansion-panel/expansion-panel.component';
import { Subscription, debounceTime, fromEvent } from 'rxjs';

type ApexChartDataItem = { x: string; y: number; meta: { svg: string; parent: string } };

Expand All @@ -38,7 +30,7 @@ type ApexChartSeries = {
templateUrl: './carbon-estimation.component.html',
styleUrls: ['./carbon-estimation.component.css'],
})
export class CarbonEstimationComponent implements OnInit {
export class CarbonEstimationComponent implements OnInit, OnDestroy {
public carbonEstimation = input.required<CarbonEstimation>();
public extraHeight = input<string>();

Expand All @@ -49,6 +41,8 @@ export class CarbonEstimationComponent implements OnInit {
private tooltipFormatter = tooltipFormatter;
private estimatorBaseHeight = sumValues(estimatorHeights);

private resizeSubscription!: Subscription;

@ViewChild('chart') chart: ChartComponent | undefined;
@ViewChild('detailsPanel', { static: true, read: ElementRef }) detailsPanel!: ElementRef;

Expand All @@ -64,14 +58,21 @@ export class CarbonEstimationComponent implements OnInit {
if (chartHeight > 0) {
this.chartOptions.chart.height = chartHeight;
}

this.resizeSubscription = fromEvent(window, 'resize')
.pipe(debounceTime(500))
.subscribe(() => this.onResize(window.innerHeight, window.innerWidth));
}

public ngOnDestroy(): void {
this.resizeSubscription.unsubscribe();
}

public onExpanded(): void {
this.changeDetectorRef.detectChanges();
this.onResize(window.innerHeight, window.innerWidth);
}

@HostListener('window:resize', ['$event.target.innerHeight', '$event.target.innerWidth'])
onResize(innerHeight: number, innerWidth: number): void {
const chartHeight = this.getChartHeight(innerHeight, innerWidth);
if (chartHeight > 0) {
Expand Down

0 comments on commit 2296b29

Please sign in to comment.