The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Convert the legacy chart legend components to TypeScript function components (#78258)
Andrei Chernykh166175677e11
diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsxindex 6cc11248ba8..d58e4996cc2 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx@@ -17,6 +17,7 @@ import type { HoveredObject } from "metabase/visualizations/types";import styles from "./ChartWithLegend.module.css";import { LegendHorizontal } from "./LegendHorizontal";import { LegendVertical } from "./LegendVertical";+import type { LegendHover, LegendTitle } from "./types";const GRID_ASPECT_RATIO = 4 / 3;const PADDING = 14;@@ -25,11 +26,19 @@ const DEFAULT_GRID_SIZE = 100;export const HIDE_HORIZONTAL_LEGEND_THRESHOLD = 180;export const HIDE_SECONDARY_INFO_THRESHOLD = 260;-type LegendTitle = string | string[];+type GridSize = {+ width: number;+ height: number;+};-type LegendHover = {- index: number;- element?: HTMLElement | null;+type ChartLayout = {+ type: "horizontal" | "vertical" | "small";+ LegendComponent: typeof LegendHorizontal | typeof LegendVertical | undefined;+ processedLegendTitles: LegendTitle[];+ chartWidth: number | undefined;+ chartHeight: number | undefined;+ flexChart: boolean;+ hasDimensions: boolean;};type ChartWithLegendProps = {@@ -42,10 +51,7 @@ type ChartWithLegendProps = {className?: string;chartClassName?: string;style?: CSSProperties;- gridSize?: {- width: number;- height: number;- };+ gridSize?: GridSize;aspectRatio?: number;height: number;width: number;@@ -92,75 +98,17 @@ const ChartWithLegendInner = ({}}, [height, width]);- const layout = useMemo(() => {- // padding- const adjustedWidth = stableWidth - PADDING * 2;- const adjustedHeight = stableHeight - PADDING;-- const calculatedGridSize = gridSize || {- width: adjustedWidth / DEFAULT_GRID_SIZE,- height: adjustedHeight / DEFAULT_GRID_SIZE,- };-- let chartWidth;- let chartHeight;- let flexChart = false;- let type: "horizontal" | "vertical" | "small";- let LegendComponent;- let processedLegendTitles = legendTitles;-- const isHorizontal =- calculatedGridSize.width > calculatedGridSize.height / GRID_ASPECT_RATIO;-- if (isHorizontal && adjustedWidth > HIDE_HORIZONTAL_LEGEND_THRESHOLD) {- type = "horizontal";- LegendComponent = LegendVertical;-- if (adjustedWidth < HIDE_SECONDARY_INFO_THRESHOLD) {- processedLegendTitles = legendTitles.map((title) =>- Array.isArray(title) ? title.slice(0, 1) : title,- );- }- const desiredWidth = adjustedHeight * aspectRatio;- if (desiredWidth > adjustedWidth * (2 / 3)) {- flexChart = true;- } else {- chartWidth = desiredWidth;- }- chartHeight = adjustedHeight;- } else if (- !isHorizontal &&- calculatedGridSize.height > 3 &&- calculatedGridSize.width > 2- ) {- type = "vertical";- LegendComponent = LegendHorizontal;- processedLegendTitles = legendTitles.map((title) =>- Array.isArray(title) ? title.join(" ") : title,- );- const desiredHeight = adjustedWidth * (1 / aspectRatio);- if (desiredHeight > adjustedHeight * (3 / 4)) {- flexChart = true;- } else {- chartHeight = desiredHeight;- }- chartWidth = adjustedWidth;- } else {- type = "small";- }-- const hasDimensions = adjustedWidth > 0 && adjustedHeight > 0;-- return {- type,- LegendComponent,- processedLegendTitles,- chartWidth,- chartHeight,- flexChart,- hasDimensions,- };- }, [stableWidth, stableHeight, gridSize, aspectRatio, legendTitles]);+ const layout = useMemo(+ () =>+ getChartLayout({+ width: stableWidth,+ height: stableHeight,+ gridSize,+ aspectRatio,+ legendTitles,+ }),+ [stableWidth, stableHeight, gridSize, aspectRatio, legendTitles],+ );const legend =showLegend && layout.type !== "small" && layout.LegendComponent ? (@@ -169,7 +117,6 @@ const ChartWithLegendInner = ({titles={layout.processedLegendTitles}hiddenIndices={legendHiddenIndices}colors={legendColors}- dotSize={isDashboard || isMetricsViewer ? "8px" : "12px"}hovered={hovered}onHoverChange={onHoverChange}onToggleSeriesVisibility={onToggleSeriesVisibility}@@ -239,3 +186,82 @@ export const ChartWithLegend = ExplicitSize<ChartWithLegendProps>({wrapped: true,refreshMode: "debounce",})(ChartWithLegendRefWrapper);++export function getChartLayout({+ width,+ height,+ gridSize,+ aspectRatio,+ legendTitles,+}: {+ width: number;+ height: number;+ gridSize: GridSize | undefined;+ aspectRatio: number;+ legendTitles: LegendTitle[];+}): ChartLayout {+ const adjustedWidth = width - PADDING * 2;+ const adjustedHeight = height - PADDING;+ const hasDimensions = adjustedWidth > 0 && adjustedHeight > 0;++ const calculatedGridSize = gridSize || {+ width: adjustedWidth / DEFAULT_GRID_SIZE,+ height: adjustedHeight / DEFAULT_GRID_SIZE,+ };++ const isHorizontal =+ calculatedGridSize.width > calculatedGridSize.height / GRID_ASPECT_RATIO;++ if (isHorizontal && adjustedWidth > HIDE_HORIZONTAL_LEGEND_THRESHOLD) {+ const processedLegendTitles =+ adjustedWidth < HIDE_SECONDARY_INFO_THRESHOLD+ ? legendTitles.map((title) =>+ Array.isArray(title) ? title.slice(0, 1) : title,+ )+ : legendTitles;+ const desiredWidth = adjustedHeight * aspectRatio;+ const flexChart = desiredWidth > adjustedWidth * (2 / 3);++ return {+ type: "horizontal",+ LegendComponent: LegendVertical,+ processedLegendTitles,+ chartWidth: flexChart ? undefined : desiredWidth,+ chartHeight: adjustedHeight,+ flexChart,+ hasDimensions,+ };+ }++ if (+ !isHorizontal &&+ calculatedGridSize.height > 3 &&+ calculatedGridSize.width > 2+ ) {+ const processedLegendTitles = legendTitles.map((title) =>+ Array.isArray(title) ? title.join(" ") : title,+ );+ const desiredHeight = adjustedWidth * (1 / aspectRatio);+ const flexChart = desiredHeight > adjustedHeight * (3 / 4);++ return {+ type: "vertical",+ LegendComponent: LegendHorizontal,+ processedLegendTitles,+ chartWidth: adjustedWidth,+ chartHeight: flexChart ? undefined : desiredHeight,+ flexChart,+ hasDimensions,+ };+ }++ return {+ type: "small",+ LegendComponent: undefined,+ processedLegendTitles: legendTitles,+ chartWidth: undefined,+ chartHeight: undefined,+ flexChart: false,+ hasDimensions,+ };+}diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsxindex 9a69254d966..a3d639cb4b5 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx@@ -7,14 +7,11 @@ import {ChartWithLegend,HIDE_HORIZONTAL_LEGEND_THRESHOLD,HIDE_SECONDARY_INFO_THRESHOLD,+ getChartLayout,} from "./ChartWithLegend";--type LegendTitle = string | string[];--type LegendHover = {- index: number;- element?: HTMLElement | null;-};+import { LegendHorizontal } from "./LegendHorizontal";+import { LegendVertical } from "./LegendVertical";+import type { LegendHover, LegendTitle } from "./types";interface SetupProps {children?: ReactNode;@@ -106,3 +103,91 @@ describe("ChartWithLegend", () => {expect(screen.getByTestId("chart-legend")).toHaveTextContent("Bar 90%");});});++describe("getChartLayout", () => {+ const defaultInput: Parameters<typeof getChartLayout>[0] = {+ width: 800,+ height: 400,+ gridSize: undefined,+ aspectRatio: 1,+ legendTitles: ["Series 1", "Series 2"],+ };++ it("should lay out a wide chart horizontally with a fixed chart size", () => {+ const layout = getChartLayout(defaultInput);++ expect(layout).toMatchObject({+ type: "horizontal",+ LegendComponent: LegendVertical,+ chartWidth: 386,+ chartHeight: 386,+ flexChart: false,+ hasDimensions: true,+ });+ expect(layout.processedLegendTitles).toEqual(["Series 1", "Series 2"]);+ });++ it("should hide secondary title info and flex the chart when the area is narrow", () => {+ const layout = getChartLayout({+ ...defaultInput,+ width: 250,+ height: 200,+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "horizontal",+ flexChart: true,+ chartWidth: undefined,+ chartHeight: 186,+ });+ expect(layout.processedLegendTitles).toEqual([["Series 1"], "Series 2"]);+ });++ it("should lay out vertically with joined titles when the grid is tall", () => {+ const layout = getChartLayout({+ ...defaultInput,+ height: 600,+ gridSize: { width: 3, height: 8 },+ aspectRatio: 2,+ legendTitles: [["Series 1", "50%"], "Series 2"],+ });++ expect(layout).toMatchObject({+ type: "vertical",+ LegendComponent: LegendHorizontal,+ chartWidth: 772,+ chartHeight: 386,+ flexChart: false,+ });+ expect(layout.processedLegendTitles).toEqual(["Series 1 50%", "Series 2"]);+ });++ it("should use the small layout when the grid has too few columns", () => {+ const layout = getChartLayout({+ ...defaultInput,+ gridSize: { width: 2, height: 8 },+ });++ expect(layout).toMatchObject({+ type: "small",+ LegendComponent: undefined,+ chartWidth: undefined,+ chartHeight: undefined,+ flexChart: false,+ });+ });++ it("should use the small layout when a horizontal chart is below the legend width threshold", () => {+ const layout = getChartLayout({ ...defaultInput, width: 200, height: 100 });++ expect(layout.type).toBe("small");+ expect(layout.LegendComponent).toBeUndefined();+ });++ it("should report missing dimensions when the chart is not measured yet", () => {+ const layout = getChartLayout({ ...defaultInput, width: 0, height: 0 });++ expect(layout).toMatchObject({ type: "small", hasDimensions: false });+ });+});diff --git a/frontend/src/metabase/visualizations/components/LegendHorizontal.jsx b/frontend/src/metabase/visualizations/components/LegendHorizontal.jsxdeleted file mode 100644index 42fe186b344..00000000000--- a/frontend/src/metabase/visualizations/components/LegendHorizontal.jsx+++ /dev/null@@ -1,82 +0,0 @@-/* eslint-disable react/prop-types */-import cx from "classnames";-import { Component } from "react";--import LegendS from "./Legend.module.css";-import { LegendItem } from "./LegendItem";--export class LegendHorizontal extends Component {- constructor(props) {- super(props);-- /** @type {Record<number, LegendItem | null>} */- this.legendItemRefs = {};- }-- render() {- const {- className,- titles,- colors,- dotSize,- hiddenIndices = [],- hovered,- onHoverChange,- onToggleSeriesVisibility,- } = this.props;- return (- <ol className={cx(className, LegendS.Legend, LegendS.horizontal)}>- {titles.map((title, index) => {- const isMuted =- hovered && hovered.index != null && index !== hovered.index;- const isVisible = !hiddenIndices.includes(index);-- const handleMouseEnter = () => {- onHoverChange?.({- index,- element: this.legendItemRefs[index]?.getRootElement(),- });- };-- const handleMouseLeave = () => {- onHoverChange?.(null);- };-- return (- <li- key={index}- data-testid={`legend-item-${title}`}- {...(hovered && { "aria-current": !isMuted })}- >- <LegendItem- ref={(legendItem) => {- this.legendItemRefs[index] = legendItem;- }}- title={title}- color={colors[index % colors.length]}- dotSize={dotSize}- isMuted={isMuted}- isVisible={isVisible}- showTooltip={false}- onMouseEnter={() => {- if (isVisible) {- handleMouseEnter();- }- }}- onMouseLeave={handleMouseLeave}- onToggleSeriesVisibility={(event) => {- if (isVisible) {- handleMouseLeave();- } else {- handleMouseEnter();- }- onToggleSeriesVisibility(event, index);- }}- />- </li>- );- })}- </ol>- );- }-}diff --git a/frontend/src/metabase/visualizations/components/LegendHorizontal.tsx b/frontend/src/metabase/visualizations/components/LegendHorizontal.tsxnew file mode 100644index 00000000000..2f31e3a9eff--- /dev/null+++ b/frontend/src/metabase/visualizations/components/LegendHorizontal.tsx@@ -0,0 +1,71 @@+import cx from "classnames";+import { useRef } from "react";++import LegendS from "./Legend.module.css";+import { LegendItem } from "./LegendItem";+import type { LegendProps } from "./types";++export function LegendHorizontal({+ className,+ titles,+ colors,+ hiddenIndices = [],+ hovered,+ onHoverChange,+ onToggleSeriesVisibility,+}: LegendProps) {+ const legendItemRefs = useRef<Record<number, HTMLSpanElement | null>>({});++ return (+ <ol className={cx(className, LegendS.Legend, LegendS.horizontal)}>+ {titles.map((title, index) => {+ const isMuted = hovered?.index != null && index !== hovered.index;+ const isVisible = !hiddenIndices.includes(index);++ const handleMouseEnter = () => {+ onHoverChange?.({+ index,+ element: legendItemRefs.current[index] ?? undefined,+ });+ };++ const handleMouseLeave = () => {+ onHoverChange?.(null);+ };++ return (+ <li+ key={index}+ data-testid={`legend-item-${title}`}+ aria-current={hovered ? !isMuted : undefined}+ >+ <LegendItem+ ref={(legendItem) => {+ legendItemRefs.current[index] = legendItem;+ }}+ title={title}+ color={colors[index % colors.length]}+ isMuted={isMuted}+ isVisible={isVisible}+ showTooltip={false}+ onMouseEnter={() => {+ if (isVisible) {+ handleMouseEnter();+ }+ }}+ onMouseLeave={handleMouseLeave}+ onToggleSeriesVisibility={(event) => {+ if (isVisible) {+ handleMouseLeave();+ } else {+ handleMouseEnter();+ }+ onToggleSeriesVisibility?.(event, index);+ }}+ />+ </li>+ );+ })}+ </ol>+ );+}diff --git a/frontend/src/metabase/visualizations/components/LegendItem.jsx b/frontend/src/metabase/visualizations/components/LegendItem.jsxdeleted file mode 100644index 5528df7d87d..00000000000--- a/frontend/src/metabase/visualizations/components/LegendItem.jsx+++ /dev/null@@ -1,134 +0,0 @@-/* eslint-disable react/prop-types */-import cx from "classnames";-import PropTypes from "prop-types";-import { Component, createRef } from "react";--import CS from "metabase/css/core/index.css";-import DashboardS from "metabase/css/dashboard.module.css";-import { Box, Ellipsified, Icon, Tooltip } from "metabase/ui";--import LegendS from "./Legend.module.css";-import { LegendItemDot } from "./legend/LegendItemDot";--const propTypes = {- icon: PropTypes.object,-};--export class LegendItem extends Component {- constructor(props, context) {- super(props, context);- this.state = {};-- /** @type {React.RefObject<HTMLSpanElement>} */- this.rootRef = createRef();- }-- static defaultProps = {- showDot: true,- showTitle: true,- isVisible: true,- isMuted: false,- showTooltip: true,- showDotTooltip: true,- };-- getRootElement() {- return this.rootRef.current;- }-- render() {- const {- title,- color,- icon,- dotSize,- showDot,- showTitle,- isVisible,- isMuted,- showTooltip,- showDotTooltip,- onMouseEnter,- onMouseLeave,- className,- description,- onClick,- infoClassName,- onToggleSeriesVisibility,- } = this.props;-- return (- <span- ref={this.rootRef}- data-testid="legend-item"- className={cx(- className,- LegendS.LegendItem,- { [LegendS.LegendItemMuted]: isMuted },- CS.noDecoration,- DashboardS.fullscreenNormalText,- DashboardS.DashboardChartLegend,- CS.flex,- CS.alignCenter,- {- [CS.mr1]: showTitle,- [CS.cursorPointer]: onClick,- },- )}- style={{- overflowX: "hidden",- flex: "0 1 auto",- paddingLeft: showDot ? "4px" : "0",- }}- onMouseEnter={onMouseEnter}- onMouseLeave={onMouseLeave}- onClick={onClick}- >- {icon && (- <Box pr="xs">- <Icon {...icon} />- </Box>- )}- {showDot && (- <Tooltip- label={title}- disabled={!showTooltip || !showDotTooltip}- arrowPosition="center"- >- <LegendItemDot- color={color}- dotSize={dotSize}- isVisible={isVisible}- onClick={onToggleSeriesVisibility}- />- </Tooltip>- )}- {showTitle && (- <div- className={cx(CS.flex, CS.alignCenter, CS.overflowHidden)}- style={showDot && { marginLeft: "4px" }}- >- <Ellipsified showTooltip={showTooltip}>{title}</Ellipsified>- {description && (- <div- className={cx(- CS.hoverChild,- CS.ml1,- CS.flex,- CS.alignCenter,- CS.textMedium,- )}- >- <Tooltip label={description} maxWidth="22em">- <Icon className={infoClassName} name="info" />- </Tooltip>- </div>- )}- </div>- )}- </span>- );- }-}--LegendItem.propTypes = propTypes;diff --git a/frontend/src/metabase/visualizations/components/LegendItem.tsx b/frontend/src/metabase/visualizations/components/LegendItem.tsxnew file mode 100644index 00000000000..11f2b487a85--- /dev/null+++ b/frontend/src/metabase/visualizations/components/LegendItem.tsx@@ -0,0 +1,75 @@+import cx from "classnames";+import { type MouseEvent, type MouseEventHandler, forwardRef } from "react";++import CS from "metabase/css/core/index.css";+import DashboardS from "metabase/css/dashboard.module.css";+import { Ellipsified, Tooltip } from "metabase/ui";++import LegendS from "./Legend.module.css";+import { LegendItemDot } from "./legend/LegendItemDot";+import type { LegendTitle } from "./types";++interface LegendItemProps {+ title: LegendTitle;+ color: string;+ isMuted?: boolean;+ isVisible?: boolean;+ showTooltip?: boolean;+ onMouseEnter?: MouseEventHandler<HTMLSpanElement>;+ onMouseLeave?: MouseEventHandler<HTMLSpanElement>;+ onToggleSeriesVisibility?: (event: MouseEvent) => void;+}++export const LegendItem = forwardRef<HTMLSpanElement, LegendItemProps>(+ function LegendItem(+ {+ title,+ color,+ isMuted = false,+ isVisible = true,+ showTooltip = true,+ onMouseEnter,+ onMouseLeave,+ onToggleSeriesVisibility,+ },+ ref,+ ) {+ return (+ <span+ ref={ref}+ data-testid="legend-item"+ className={cx(+ LegendS.LegendItem,+ { [LegendS.LegendItemMuted]: isMuted },+ CS.noDecoration,+ DashboardS.fullscreenNormalText,+ DashboardS.DashboardChartLegend,+ CS.flex,+ CS.alignCenter,+ CS.mr1,+ )}+ style={{+ overflowX: "hidden",+ flex: "0 1 auto",+ paddingLeft: "4px",+ }}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ >+ <Tooltip label={title} disabled={!showTooltip} arrowPosition="center">+ <LegendItemDot+ color={color}+ isVisible={isVisible}+ onClick={onToggleSeriesVisibility}+ />+ </Tooltip>+ <div+ className={cx(CS.flex, CS.alignCenter, CS.overflowHidden)}+ style={{ marginLeft: "4px" }}+ >+ <Ellipsified showTooltip={showTooltip}>{title}</Ellipsified>+ </div>+ </span>+ );+ },+);diff --git a/frontend/src/metabase/visualizations/components/LegendVertical.jsx b/frontend/src/metabase/visualizations/components/LegendVertical.jsxdeleted file mode 100644index db382ff272c..00000000000--- a/frontend/src/metabase/visualizations/components/LegendVertical.jsx+++ /dev/null@@ -1,188 +0,0 @@-/* eslint-disable react/prop-types */-import cx from "classnames";-import { Component, createRef } from "react";-import { t } from "ttag";--import CS from "metabase/css/core/index.css";-import DashboardS from "metabase/css/dashboard.module.css";-import { Popover } from "metabase/ui";--import LegendS from "./Legend.module.css";-import { LegendItem } from "./LegendItem";--export class LegendVertical extends Component {- static propTypes = {};- static defaultProps = {};-- state = {- overflowCount: 0,- size: null,- };-- constructor(props) {- super(props);- this.listContainerRef = createRef();-- /** @type {Record<number, HTMLLIElement | null>} */- this.itemRefs = {};-- /** @type {Record<number, LegendItem | null>} */- this.legendItemRefs = {};- }-- componentDidUpdate(prevProps, prevState) {- // Get the bounding rectangle of the chart widget to determine if- // legend items will overflow the widget area- const size = this.listContainerRef.current?.getBoundingClientRect();-- // check the height, width may flucatuate depending on the browser causing an infinite loop- // check overflowCount, because after setting overflowCount the height changes and it causing an infinite loop too- if (- this.state.size &&- size.height !== this.state.size.height &&- prevState.overflowCount === this.state.overflowCount- ) {- this.setState({ overflowCount: 0, size });- } else if (this.state.overflowCount === 0) {- let overflowCount = 0;- for (let i = 0; i < this.props.titles.length; i++) {- const itemSize = this.itemRefs[i]?.getBoundingClientRect();- if (size.top > itemSize.top || size.bottom < itemSize.bottom) {- overflowCount++;- }- }- if (this.state.overflowCount !== overflowCount) {- this.setState({ overflowCount, size });- }- }- }-- render() {- const {- className,- titles,- colors,- hovered,- dotSize,- hiddenIndices = [],- onHoverChange,- onToggleSeriesVisibility,- } = this.props;- const { overflowCount } = this.state;- let items, extraItems, extraColors;- if (overflowCount > 0) {- items = titles.slice(0, -overflowCount - 1);- extraItems = titles.slice(-overflowCount - 1);- extraColors = colors- .slice(-overflowCount - 1)- .concat(colors.slice(0, -overflowCount - 1));- } else {- items = titles;- }- return (- <ol- className={cx(className, LegendS.Legend, LegendS.vertical)}- ref={this.listContainerRef}- >- {items.map((title, index) => {- const isMuted =- hovered && hovered.index != null && index !== hovered.index;- const legendItemTitle = Array.isArray(title) ? title[0] : title;- const isVisible = !hiddenIndices.includes(index);-- const handleMouseEnter = () => {- onHoverChange?.({- index,- element: this.legendItemRefs[index]?.getRootElement(),- });- };-- const handleMouseLeave = () => {- onHoverChange?.();- };-- return (- <li- key={index}- ref={(element) => {- this.itemRefs[index] = element;- }}- className={cx(CS.flex, CS.flexNoShrink)}- onMouseEnter={(e) => {- if (isVisible) {- handleMouseEnter();- }- }}- onMouseLeave={handleMouseLeave}- data-testid={`legend-item-${legendItemTitle}`}- {...(hovered && { "aria-current": !isMuted })}- >- <LegendItem- ref={(legendItem) => {- this.legendItemRefs[index] = legendItem;- }}- title={legendItemTitle}- color={colors[index % colors.length]}- dotSize={dotSize}- isMuted={isMuted}- isVisible={isVisible}- showTooltip={false}- onToggleSeriesVisibility={(event) => {- if (isVisible) {- handleMouseLeave();- } else {- handleMouseEnter();- }- onToggleSeriesVisibility(event, index);- }}- />- {Array.isArray(title) && (- <span- className={cx(- LegendS.LegendItem,- DashboardS.DashboardChartLegend,- CS.flex,- CS.alignCenter,- CS.flexAlignRight,- CS.pl1,- { [LegendS.LegendItemMuted]: isMuted },- )}- >- {title[1]}- </span>- )}- </li>- );- })}- {overflowCount > 0 ? (- <Popover>- <Popover.Target>- <li className={cx(CS.flex, CS.flexNoShrink, CS.cursorPointer)}>- <LegendItem- title={overflowCount + 1 + " " + t`more`}- color="gray"- dotSize={dotSize}- showTooltip={false}- />- </li>- </Popover.Target>- <Popover.Dropdown>- <LegendVertical- className={CS.p2}- titles={extraItems}- dotSize={dotSize}- colors={extraColors}- hiddenIndices={hiddenIndices- .filter((i) => i >= items.length - 1)- .map((i) => i - items.length)}- onToggleSeriesVisibility={(event, sliceIndex) =>- onToggleSeriesVisibility(event, sliceIndex + items.length)- }- />- </Popover.Dropdown>- </Popover>- ) : null}- </ol>- );- }-}diff --git a/frontend/src/metabase/visualizations/components/LegendVertical.tsx b/frontend/src/metabase/visualizations/components/LegendVertical.tsxnew file mode 100644index 00000000000..8092a52c582--- /dev/null+++ b/frontend/src/metabase/visualizations/components/LegendVertical.tsx@@ -0,0 +1,175 @@+import cx from "classnames";+import { useLayoutEffect, useRef, useState } from "react";+import { t } from "ttag";++import CS from "metabase/css/core/index.css";+import DashboardS from "metabase/css/dashboard.module.css";+import { Popover } from "metabase/ui";++import LegendS from "./Legend.module.css";+import { LegendItem } from "./LegendItem";+import type { LegendProps } from "./types";++export function LegendVertical({+ className,+ titles,+ colors,+ hiddenIndices = [],+ hovered,+ onHoverChange,+ onToggleSeriesVisibility,+}: LegendProps) {+ const [overflowCount, setOverflowCount] = useState(0);+ const [size, setSize] = useState<DOMRect | null>(null);+ const listContainerRef = useRef<HTMLOListElement>(null);+ const itemRefs = useRef<Record<number, HTMLLIElement | null>>({});+ const legendItemRefs = useRef<Record<number, HTMLSpanElement | null>>({});+ const prevOverflowCountRef = useRef(overflowCount);++ // Measures whether legend items overflow the widget area. Runs after every+ // render because the container can resize without any prop or state change.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ useLayoutEffect(() => {+ const prevOverflowCount = prevOverflowCountRef.current;+ prevOverflowCountRef.current = overflowCount;++ const containerRect = listContainerRef.current?.getBoundingClientRect();+ if (!containerRect) {+ return;+ }++ // check the height, width may fluctuate depending on the browser causing an infinite loop+ // check overflowCount, because after setting overflowCount the height changes and it causing an infinite loop too+ if (+ size &&+ containerRect.height !== size.height &&+ prevOverflowCount === overflowCount+ ) {+ setOverflowCount(0);+ setSize(containerRect);+ } else if (overflowCount === 0) {+ let currentOverflowCount = 0;+ for (let i = 0; i < titles.length; i++) {+ const itemRect = itemRefs.current[i]?.getBoundingClientRect();+ if (+ itemRect &&+ (containerRect.top > itemRect.top ||+ containerRect.bottom < itemRect.bottom)+ ) {+ currentOverflowCount++;+ }+ }+ if (currentOverflowCount !== overflowCount) {+ setOverflowCount(currentOverflowCount);+ setSize(containerRect);+ }+ }+ });++ const hasOverflow = overflowCount > 0;+ const items = hasOverflow ? titles.slice(0, -overflowCount - 1) : titles;++ return (+ <ol+ className={cx(className, LegendS.Legend, LegendS.vertical)}+ ref={listContainerRef}+ >+ {items.map((title, index) => {+ const isMuted = hovered?.index != null && index !== hovered.index;+ const legendItemTitle = Array.isArray(title) ? title[0] : title;+ const isVisible = !hiddenIndices.includes(index);++ const handleMouseEnter = () => {+ onHoverChange?.({+ index,+ element: legendItemRefs.current[index] ?? undefined,+ });+ };++ const handleMouseLeave = () => {+ onHoverChange?.();+ };++ return (+ <li+ key={index}+ ref={(element) => {+ itemRefs.current[index] = element;+ }}+ className={cx(CS.flex, CS.flexNoShrink)}+ onMouseEnter={() => {+ if (isVisible) {+ handleMouseEnter();+ }+ }}+ onMouseLeave={handleMouseLeave}+ data-testid={`legend-item-${legendItemTitle}`}+ aria-current={hovered ? !isMuted : undefined}+ >+ <LegendItem+ ref={(legendItem) => {+ legendItemRefs.current[index] = legendItem;+ }}+ title={legendItemTitle}+ color={colors[index % colors.length]}+ isMuted={isMuted}+ isVisible={isVisible}+ showTooltip={false}+ onToggleSeriesVisibility={(event) => {+ if (isVisible) {+ handleMouseLeave();+ } else {+ handleMouseEnter();+ }+ onToggleSeriesVisibility?.(event, index);+ }}+ />+ {Array.isArray(title) && (+ <span+ className={cx(+ LegendS.LegendItem,+ DashboardS.DashboardChartLegend,+ CS.flex,+ CS.alignCenter,+ CS.flexAlignRight,+ CS.pl1,+ { [LegendS.LegendItemMuted]: isMuted },+ )}+ >+ {title[1]}+ </span>+ )}+ </li>+ );+ })}+ {hasOverflow ? (+ <Popover>+ <Popover.Target>+ <li className={cx(CS.flex, CS.flexNoShrink, CS.cursorPointer)}>+ <LegendItem+ title={overflowCount + 1 + " " + t`more`}+ color="gray"+ showTooltip={false}+ />+ </li>+ </Popover.Target>+ <Popover.Dropdown>+ <LegendVertical+ className={CS.p2}+ titles={titles.slice(-overflowCount - 1)}+ colors={colors+ .slice(-overflowCount - 1)+ .concat(colors.slice(0, -overflowCount - 1))}+ hiddenIndices={hiddenIndices+ .filter((i) => i >= items.length - 1)+ .map((i) => i - items.length)}+ onToggleSeriesVisibility={(event, sliceIndex) =>+ onToggleSeriesVisibility?.(event, sliceIndex + items.length)+ }+ />+ </Popover.Dropdown>+ </Popover>+ ) : null}+ </ol>+ );+}diff --git a/frontend/src/metabase/visualizations/components/LegendVertical.unit.spec.js b/frontend/src/metabase/visualizations/components/LegendVertical.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/visualizations/components/LegendVertical.unit.spec.jsrename to frontend/src/metabase/visualizations/components/LegendVertical.unit.spec.tsxdiff --git a/frontend/src/metabase/visualizations/components/types.ts b/frontend/src/metabase/visualizations/components/types.tsnew file mode 100644index 00000000000..937afcc5d11--- /dev/null+++ b/frontend/src/metabase/visualizations/components/types.ts@@ -0,0 +1,20 @@+import type { MouseEvent } from "react";++import type { HoveredObject } from "metabase/visualizations/types";++export type LegendTitle = string | string[];++export type LegendHover = {+ index: number;+ element?: HTMLElement;+};++export interface LegendProps {+ className?: string;+ titles: LegendTitle[];+ colors: string[];+ hiddenIndices?: number[];+ hovered?: HoveredObject | null;+ onHoverChange?: (hover?: LegendHover | null) => void;+ onToggleSeriesVisibility?: (event: MouseEvent, index: number) => void;+}