import { Component, effect, ElementRef, input, OnDestroy, viewChild } from '@angular/core'; import type * as Plotly from 'plotly.js'; import { headroom } from './plot-headroom'; import plotly from './plotly-bundle'; export type Figure = { data: Partial[]; layout?: Partial }; export const PALETTE = [ '#A8C243', '#42C29C', '#C24269', '#9C42C2', '#4269C2', '#C29C42', '#7A7A7A', ]; const LAYOUT: Partial = { font: { family: 'Roboto, Arial, sans-serif', size: 14, color: '#17324d' }, colorway: PALETTE, margin: { t: 24, r: 16, b: 48, l: 56 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', legend: { orientation: 'h', x: 0, xanchor: 'left', y: 1.02, yanchor: 'bottom' }, hoverlabel: { font: { family: 'Roboto, Arial, sans-serif', size: 13 } }, }; const axisDefaults = (): Partial => ({ automargin: true, title: { standoff: 12 }, ticklabelstandoff: 4, }); function layoutOf( layout: Partial = {}, data: Partial[] = [], ): Partial { const axes = Object.fromEntries( Object.entries(layout) .filter(([k]) => /^[xy]axis\d*$/.test(k)) .map(([k, v]) => { const axis = (v ?? {}) as Partial; const title = typeof axis.title === 'string' ? { text: axis.title } : axis.title; const base = axisDefaults(); return [k, { ...base, ...axis, title: { ...base.title, ...title } }]; }), ); const composed: Partial = { ...LAYOUT, xaxis: axisDefaults(), yaxis: axisDefaults(), ...layout, ...axes, legend: { ...LAYOUT.legend, ...layout.legend }, margin: { ...LAYOUT.margin, ...layout.margin }, }; return { ...composed, ...headroom(data, composed) }; } function withRoom(data: Partial[]): Plotly.Data[] { return data.map((d) => (d.type === 'pie' ? { automargin: true, ...d } : d)) as Plotly.Data[]; } const CONFIG: Partial = { responsive: true, displaylogo: false, modeBarButtonsToRemove: ['lasso2d', 'select2d'], }; @Component({ selector: 'app-plot', template: '
', styles: ':host { display: block; } .plot { width: 100%; }', }) export class Plot implements OnDestroy { readonly figure = input.required
(); readonly height = input(320); private readonly host = viewChild.required>('host'); constructor() { effect(() => { const { data, layout } = this.figure(); void plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout, data), CONFIG); }); } ngOnDestroy(): void { plotly.purge(this.host().nativeElement); } }