diff --git a/src/app/pages/home/home-page.component.ts b/src/app/pages/home/home-page.component.ts index e4321bd..d276d7e 100644 --- a/src/app/pages/home/home-page.component.ts +++ b/src/app/pages/home/home-page.component.ts @@ -40,6 +40,7 @@ export class HomePageComponent implements OnInit, OnDestroy { private nodes: Node[]; private links: Link[]; public simulation: d3.Simulation | undefined; + private zoomBehavior: d3.ZoomBehavior; private discoveryContainerWidth: number; private discoveryContainerHeight: number; @@ -265,11 +266,11 @@ export class HomePageComponent implements OnInit, OnDestroy { const svg = d3.select(this.discoveryTargetRef.nativeElement); - const _zoom = d3.zoom().on('zoom', () => { + this.zoomBehavior = d3.zoom().on('zoom', () => { const transform = d3.event.transform; svg.select('g').attr('transform', 'translate(' + transform.x + ',' + transform.y + ') scale(' + transform.k + ')'); }); - svg.call(_zoom); + svg.call(this.zoomBehavior); const __this = this; this.simulation = d3 @@ -385,6 +386,31 @@ export class HomePageComponent implements OnInit, OnDestroy { } } + zoomToFit(paddingPercent, transitionDuration) { + const root = d3.select(this.discoveryTargetRef.nativeElement); + const bounds = root.node().getBBox(); + const parent = root.node().parentElement; + + const fullWidth = parent.clientWidth; + const fullHeight = parent.clientHeight; + + const width = bounds.width; + const height = bounds.height; + + const midX = bounds.x + width / 2; + const midY = bounds.y + height / 2; + + if (width === 0 || height === 0) { return; } // nothing to fit + + const scale = (paddingPercent || 0.75) / Math.max(width / fullWidth, height / fullHeight); + const translate = [fullWidth / 2 - scale * midX, fullHeight / 2 - scale * midY]; + + root + .transition() + .duration(transitionDuration || 0) // milliseconds + .call(this.zoomBehavior.transform, d3.zoomIdentity.translate(translate[0], translate[1]).scale(scale)); + } + onTargetClick(node: Node) { console.log(node); this.displaySidebar = true; @@ -454,6 +480,7 @@ export class HomePageComponent implements OnInit, OnDestroy { console.log('DiscoveryStop', stopDate); this.discoveryConfigService.setStarted(false); this.simulationRestart(true); + this.zoomToFit(0.95, 500); // this.simulation.stop(); }