Browse Source

fix(chart): update typings

pull/6264/head
KenTandrian 1 week ago
parent
commit
ccfa3b1503
  1. 38
      libs/common/src/lib/chart-helper.ts

38
libs/common/src/lib/chart-helper.ts

@ -1,5 +1,13 @@
import type { ElementRef } from '@angular/core'; import type { ElementRef } from '@angular/core';
import type { Chart, Plugin, TooltipOptions, TooltipPosition } from 'chart.js'; import type {
Chart,
ChartType,
ControllerDatasetOptions,
Plugin,
Point,
TooltipOptions,
TooltipPosition
} from 'chart.js';
import { format } from 'date-fns'; import { format } from 'date-fns';
import { import {
@ -28,7 +36,7 @@ export function formatGroupedDate({
return format(date, DATE_FORMAT); return format(date, DATE_FORMAT);
} }
export function getTooltipOptions({ export function getTooltipOptions<T extends ChartType>({
colorScheme, colorScheme,
currency = '', currency = '',
groupBy, groupBy,
@ -40,41 +48,39 @@ export function getTooltipOptions({
groupBy?: GroupBy; groupBy?: GroupBy;
locale?: string; locale?: string;
unit?: string; unit?: string;
}): Partial<TooltipOptions> { }): Partial<TooltipOptions<T>> {
return { return {
backgroundColor: getBackgroundColor(colorScheme), backgroundColor: getBackgroundColor(colorScheme),
bodyColor: `rgb(${getTextColor(colorScheme)})`, bodyColor: `rgb(${getTextColor(colorScheme)})`,
borderWidth: 1, borderWidth: 1,
borderColor: `rgba(${getTextColor(colorScheme)}, 0.1)`, borderColor: `rgba(${getTextColor(colorScheme)}, 0.1)`,
// @ts-ignore // @ts-expect-error: no need to set all attributes in callbacks.
callbacks: { callbacks: {
label: (context) => { label: (context) => {
let label = context.dataset.label ?? ''; let label = (context.dataset as ControllerDatasetOptions).label ?? '';
if (label) { if (label) {
label += ': '; label += ': ';
} }
// @ts-ignore
if (context.parsed.y !== null) { const yPoint = (context.parsed as Point).y;
if (yPoint !== null) {
if (currency) { if (currency) {
// @ts-ignore label += `${yPoint.toLocaleString(locale, {
label += `${context.parsed.y.toLocaleString(locale, {
maximumFractionDigits: 2, maximumFractionDigits: 2,
minimumFractionDigits: 2 minimumFractionDigits: 2
})} ${currency}`; })} ${currency}`;
} else if (unit) { } else if (unit) {
// @ts-ignore label += `${yPoint.toFixed(2)} ${unit}`;
label += `${context.parsed.y.toFixed(2)} ${unit}`;
} else { } else {
// @ts-ignore label += yPoint.toFixed(2);
label += context.parsed.y.toFixed(2);
} }
} }
return label; return label;
}, },
title: (contexts) => { title: (contexts) => {
if (groupBy) { const xPoint = (contexts[0].parsed as Point).x;
// @ts-ignore if (groupBy && xPoint !== null) {
return formatGroupedDate({ groupBy, date: contexts[0].parsed.x }); return formatGroupedDate({ groupBy, date: xPoint });
} }
return contexts[0].label; return contexts[0].label;

Loading…
Cancel
Save