Add clickForMoreInfo to statistics graph card (#19178)

* add clickForMoreInfo

* only show more info on graphs when mouse is used

* disable clickForMoreInfo already in more-info popup

* check if not isExternalStatistic

* Apply suggestions from code review

Co-authored-by: Bram Kragten <mail@bramkragten.nl>

---------

Co-authored-by: Bram Kragten <mail@bramkragten.nl>
pull/19993/head
Michael 2024-03-05 15:13:51 +01:00 committed by GitHub
parent b03f483e4f
commit bf028915ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 0 deletions

View File

@ -16,6 +16,7 @@ import { customElement, property, state, query } from "lit/decorators";
import memoizeOne from "memoize-one";
import { getGraphColorByIndex } from "../../common/color/colors";
import { isComponentLoaded } from "../../common/config/is_component_loaded";
import { fireEvent } from "../../common/dom/fire_event";
import {
formatNumber,
numberFormatToLocale,
@ -25,6 +26,7 @@ import {
getDisplayUnit,
getStatisticLabel,
getStatisticMetadata,
isExternalStatistic,
Statistics,
statisticsHaveType,
StatisticsMetaData,
@ -79,6 +81,8 @@ export class StatisticsChart extends LitElement {
@property({ type: Boolean }) public isLoadingData = false;
@property({ type: Boolean }) public clickForMoreInfo = true;
@property() public period?: string;
@state() private _chartData: ChartData = { datasets: [] };
@ -273,6 +277,33 @@ export class StatisticsChart extends LitElement {
},
// @ts-expect-error
locale: numberFormatToLocale(this.hass.locale),
onClick: (e: any) => {
if (
!this.clickForMoreInfo ||
!(e.native instanceof MouseEvent) ||
(e.native instanceof PointerEvent && e.native.pointerType !== "mouse")
) {
return;
}
const chart = e.chart;
const points = chart.getElementsAtEventForMode(
e,
"nearest",
{ intersect: true },
true
);
if (points.length) {
const firstPoint = points[0];
const statisticId = this._statisticIds[firstPoint.datasetIndex];
if (!isExternalStatistic(statisticId)) {
fireEvent(this, "hass-more-info", { entityId: statisticId });
chart.canvas.dispatchEvent(new Event("mouseout")); // to hide tooltip
}
}
},
};
}

View File

@ -93,6 +93,7 @@ export class MoreInfoHistory extends LitElement {
.names=${this._statNames}
hideLegend
.showNames=${false}
.clickForMoreInfo=${false}
></statistics-chart>`
: html`<state-history-charts
up-to-now