Skip to content

Commit

Permalink
refactor: customisable chart tooltips (#598)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexbarnsley authored Oct 4, 2023
1 parent 8d05795 commit 42c88b5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
46 changes: 31 additions & 15 deletions resources/assets/js/chart.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Chart.register(...registerables);
* @param {Number} yPadding
* @param {Number} xPadding
* @param {Boolean} showCrosshair
* @param {CallableFunction} tooltipHandler
* @param {CallableFunction} xTicksCallback
* @return {Object}
*/
const CustomChart = (
Expand All @@ -35,7 +37,9 @@ const CustomChart = (
currency,
yPadding = 15,
xPadding = 10,
showCrosshair = false
showCrosshair = false,
tooltipHandler = null,
xTicksCallback = null
) => {
const themeMode = () => {
if (theme.mode === "auto") {
Expand Down Expand Up @@ -246,7 +250,28 @@ const CustomChart = (
datasets: this.loadData(),
};

let tooltipOptions = {
enabled: tooltips,
external: this.tooltip,
displayColors: false,
callbacks: {
title: (items) => {},
label: (context) => this.getCurrencyValue(context.raw),
labelTextColor: (context) =>
getFontConfig("tooltip", themeMode()).fontColor,
},
backgroundColor: getFontConfig("tooltip", themeMode())
.backgroundColor,
};
if (tooltipHandler) {
tooltipOptions = {
enabled: false,
external: tooltipHandler,
};
}

const options = {
currency,
spanGaps: true,
normalized: true,
responsive: true,
Expand All @@ -259,20 +284,7 @@ const CustomChart = (
},
plugins: {
legend: { display: false },
tooltip: {
enabled: tooltips,
external: this.tooltip,
displayColors: false,
callbacks: {
title: (items) => {},
label: (context) =>
this.getCurrencyValue(context.raw),
labelTextColor: (context) =>
getFontConfig("tooltip", themeMode()).fontColor,
},
backgroundColor: getFontConfig("tooltip", themeMode())
.backgroundColor,
},
tooltip: tooltipOptions,
},
hover: {
mode: "nearest",
Expand Down Expand Up @@ -303,6 +315,10 @@ const CustomChart = (
},
};

if (xTicksCallback) {
options.scales.xAxes.ticks.callback = xTicksCallback;
}

this.chart = new Chart(this.getCanvasContext(), { data, options });
},
};
Expand Down
6 changes: 5 additions & 1 deletion resources/views/chart.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
'yPadding' => 15,
'xPadding' => 10,
'showCrosshair' => false,
'tooltipHandler' => null,
'ticksCallback' => null,
])

<div
Expand All @@ -26,7 +28,9 @@
'{{ $currency }}',
{{ $yPadding }},
{{ $xPadding }},
{{ $showCrosshair ? 'true' : 'false' }}
{{ $showCrosshair ? 'true' : 'false' }},
{{ $tooltipHandler ? $tooltipHandler : 'null' }},
{{ $ticksCallback ? $ticksCallback : 'null' }}
)"
wire:key="{{ $id.time() }}"
{{ $attributes->only('class') }}
Expand Down

0 comments on commit 42c88b5

Please sign in to comment.