2022-06-23 11:28:31 +02:00
|
|
|
import { Controller } from '@hotwired/stimulus';
|
2022-04-15 13:05:46 +02:00
|
|
|
import { toggle, delegate } from '@utils';
|
|
|
|
|
2022-06-23 11:28:31 +02:00
|
|
|
export class ChartkickController extends Controller {
|
|
|
|
async connect() {
|
2022-07-01 10:07:39 +02:00
|
|
|
const Highcharts = await import('highcharts');
|
|
|
|
const Chartkick = await import('chartkick');
|
|
|
|
|
2022-06-23 11:28:31 +02:00
|
|
|
Chartkick.use(Highcharts);
|
|
|
|
const reflow = (nextChartId?: string) =>
|
|
|
|
nextChartId && Chartkick.charts[nextChartId]?.getChartObject()?.reflow();
|
|
|
|
|
|
|
|
delegate('click', '[data-toggle-chart]', (event) =>
|
|
|
|
toggleChart(event as MouseEvent, reflow)
|
|
|
|
);
|
|
|
|
}
|
2022-04-15 13:05:46 +02:00
|
|
|
}
|
|
|
|
|
2022-06-23 11:28:31 +02:00
|
|
|
function toggleChart(
|
|
|
|
event: MouseEvent,
|
|
|
|
reflow: (nextChartId?: string) => void
|
|
|
|
) {
|
2022-04-15 13:05:46 +02:00
|
|
|
const nextSelectorItem = event.target as HTMLButtonElement,
|
|
|
|
chartClass = nextSelectorItem.dataset.toggleChart,
|
|
|
|
nextChart = chartClass
|
|
|
|
? document.querySelector<HTMLDivElement>(chartClass)
|
|
|
|
: undefined,
|
|
|
|
nextChartId = nextChart?.children[0]?.id,
|
|
|
|
currentSelectorItem = nextSelectorItem.parentElement?.querySelector(
|
|
|
|
'.segmented-control-item-active'
|
|
|
|
),
|
|
|
|
currentChart =
|
|
|
|
nextSelectorItem.parentElement?.parentElement?.querySelector<HTMLDivElement>(
|
|
|
|
'.chart:not(.hidden)'
|
|
|
|
);
|
|
|
|
|
|
|
|
// Change the current selector and the next selector states
|
|
|
|
currentSelectorItem?.classList.toggle('segmented-control-item-active');
|
|
|
|
nextSelectorItem.classList.toggle('segmented-control-item-active');
|
|
|
|
|
|
|
|
// Hide the currently shown chart and show the new one
|
|
|
|
currentChart && toggle(currentChart);
|
|
|
|
nextChart && toggle(nextChart);
|
|
|
|
|
|
|
|
// Reflow needed, see https://github.com/highcharts/highcharts/issues/1979
|
2022-06-23 11:28:31 +02:00
|
|
|
reflow(nextChartId);
|
2022-04-15 13:05:46 +02:00
|
|
|
}
|