chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
63.9k stars 11.88k forks source link

Add fit method to LegendElement interface #11796

Closed MichelHMachado closed 1 month ago

MichelHMachado commented 1 month ago

Purpose This pull request aims to add the fit method to the LegendElement interface in Chart.js. The primary purpose of this change is to enable the usage of chart.legend.fit within custom plugins, ensuring TypeScript correctly recognizes and supports this method.

Background While working on a custom plugin that adds a margin below the legend, I encountered a TypeScript error indicating that the fit method was not recognized. The fit method is, however, present on the legend object at runtime. To address this discrepancy and improve TypeScript support, I propose adding the fit method to the LegendElement interface.

Changes Added the fit method to the LegendElement interface in Chart.js type definitions. Example Usage Here's an example of how this change can be utilized in a custom plugin:

const legendMargin: Plugin = { id: 'legendMargin', afterInit(chart, args, plugins) { const originalFit = chart?.legend?.fit; const margin = plugins.margin || 0; if (chart.legend) { chart.legend.fit = function fit() { if (originalFit) { originalFit.call(this); } return (this.height += margin); }; } }, };