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
Fix pie chart flickering when toggling legend / Convert ChartWithLegend to ts (#67240)
Anderson48b6a9d28993
diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.jsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.jsxdeleted file mode 100644index 87d72fd7beb..00000000000--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.jsx+++ /dev/null@@ -1,166 +0,0 @@-/* eslint-disable react/prop-types */-import cx from "classnames";-import { Component, forwardRef } from "react";--import ExplicitSize from "metabase/common/components/ExplicitSize";-import DashboardS from "metabase/css/dashboard.module.css";--import styles from "./ChartWithLegend.module.css";-import LegendHorizontal from "./LegendHorizontal";-import LegendVertical from "./LegendVertical";--const GRID_ASPECT_RATIO = 4 / 3;-const PADDING = 14;--const DEFAULT_GRID_SIZE = 100;-export const HIDE_HORIZONTAL_LEGEND_THRESHOLD = 180;-export const HIDE_SECONDARY_INFO_THRESHOLD = 260;--class ChartWithLegend extends Component {- static defaultProps = {- aspectRatio: 1,- style: {},- showLegend: true,- };-- render() {- let {- children,- legendTitles,- legendHiddenIndices,- legendColors,- hovered,- onHoverChange,- className,- style,- gridSize,- aspectRatio,- height,- width,- showLegend,- isDashboard,- isDocument,- onToggleSeriesVisibility,- } = this.props;-- // padding- width -= PADDING * 2;- height -= PADDING;-- if (!gridSize) {- gridSize = {- width: width / DEFAULT_GRID_SIZE,- height: height / DEFAULT_GRID_SIZE,- };- }-- let chartWidth;- let chartHeight;- let flexChart = false;- let type;- let LegendComponent;- const isHorizontal = gridSize.width > gridSize.height / GRID_ASPECT_RATIO;- if (!showLegend) {- type = "small";- } else if (isHorizontal && width > HIDE_HORIZONTAL_LEGEND_THRESHOLD) {- type = "horizontal";- LegendComponent = LegendVertical;-- if (width < HIDE_SECONDARY_INFO_THRESHOLD) {- legendTitles = legendTitles.map((title) =>- Array.isArray(title) ? title.slice(0, 1) : title,- );- }- const desiredWidth = height * aspectRatio;- if (desiredWidth > width * (2 / 3)) {- flexChart = true;- } else {- chartWidth = desiredWidth;- }- chartHeight = height;- } else if (!isHorizontal && gridSize.height > 3 && gridSize.width > 2) {- type = "vertical";- LegendComponent = LegendHorizontal;- legendTitles = legendTitles.map((title) =>- Array.isArray(title) ? title.join(" ") : title,- );- const desiredHeight = width * (1 / aspectRatio);- if (desiredHeight > height * (3 / 4)) {- flexChart = true;- } else {- chartHeight = desiredHeight;- }- chartWidth = width;- } else {- type = "small";- }-- const hasDimensions = width > 0 && height > 0;-- const legend = LegendComponent ? (- <LegendComponent- className={styles.Legend}- titles={legendTitles}- hiddenIndices={legendHiddenIndices}- colors={legendColors}- dotSize={isDashboard ? "8px" : "12px"}- hovered={hovered}- onHoverChange={onHoverChange}- onToggleSeriesVisibility={onToggleSeriesVisibility}- />- ) : null;-- return (- <div- className={cx(- className,- DashboardS.fullscreenNormalText,- styles.ChartWithLegend,- styles[type],- flexChart && styles.flexChart,- )}- style={{- ...style,- paddingBottom: PADDING,- paddingLeft: PADDING,- paddingRight: PADDING,- }}- ref={this.props.forwardedRef}- >- {legend && (- <div className={cx(styles.LegendWrapper)} data-testid="chart-legend">- {legend}- </div>- )}- <div- className={cx(styles.Chart)}- style={{ width: chartWidth, height: chartHeight }}- >- {hasDimensions ? children : null}- </div>- {/* spacer div to balance legend */}- {legend && (- <div- className={cx(styles.LegendSpacer)}- // don't center the chart on dashboards- style={isDashboard || isDocument ? { flexBasis: 0 } : {}}- data-testid="chart-legend-spacer"- >- {legend}- </div>- )}- </div>- );- }-}--const ChartWithLegendRefWrapper = forwardRef(- function _ChartWithLegendRefWrapper(props, ref) {- return <ChartWithLegend {...props} forwardedRef={ref} />;- },-);--export default ExplicitSize({- wrapped: true,- refreshMode: "debounceLeading",-})(ChartWithLegendRefWrapper);diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css b/frontend/src/metabase/visualizations/components/ChartWithLegend.module.cssindex 01ddbd3b1a9..6495b426b02 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.module.css@@ -1,8 +1,8 @@.ChartWithLegend {display: flex;- justify-content: flex-end;- width: 100%;height: 100%;+ justify-content: center;+ width: 100%;}.ChartWithLegend .Legend {diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsxnew file mode 100644index 00000000000..b7738579c8c--- /dev/null+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.tsx@@ -0,0 +1,235 @@+import cx from "classnames";+import {+ type CSSProperties,+ type MouseEvent,+ type ReactNode,+ type Ref,+ forwardRef,+ useEffect,+ useMemo,+ useState,+} from "react";++import ExplicitSize from "metabase/common/components/ExplicitSize";+import DashboardS from "metabase/css/dashboard.module.css";+import type { HoveredObject } from "metabase/visualizations/types";++import styles from "./ChartWithLegend.module.css";+import LegendHorizontal from "./LegendHorizontal";+import LegendVertical from "./LegendVertical";++const GRID_ASPECT_RATIO = 4 / 3;+const PADDING = 14;++const DEFAULT_GRID_SIZE = 100;+export const HIDE_HORIZONTAL_LEGEND_THRESHOLD = 180;+export const HIDE_SECONDARY_INFO_THRESHOLD = 260;++type LegendTitle = string | string[];++type LegendHover = {+ index: number;+ element?: HTMLElement | null;+};++type ChartWithLegendProps = {+ children?: ReactNode;+ legendTitles: LegendTitle[];+ legendHiddenIndices?: number[];+ legendColors: string[];+ hovered?: HoveredObject | null;+ onHoverChange?: (hover?: LegendHover | null) => void;+ className?: string;+ chartClassName?: string;+ style?: CSSProperties;+ gridSize?: {+ width: number;+ height: number;+ };+ aspectRatio?: number;+ height: number;+ width: number;+ showLegend?: boolean;+ isDashboard?: boolean;+ isDocument?: boolean;+ onToggleSeriesVisibility?: (event: MouseEvent, index: number) => void;+ forwardedRef?: Ref<HTMLDivElement>;+};++const ChartWithLegendInner = ({+ children,+ legendTitles,+ legendHiddenIndices,+ legendColors,+ hovered,+ onHoverChange,+ className,+ chartClassName,+ style = {},+ gridSize,+ aspectRatio = 1,+ height,+ width,+ showLegend = true,+ isDashboard,+ isDocument,+ onToggleSeriesVisibility = () => {},+ forwardedRef,+}: ChartWithLegendProps) => {+ const [stableWidth, setStableWidth] = useState(width);+ const [stableHeight, setStableHeight] = useState(height);++ useEffect(() => {+ // Use last valid dimensions to prevent flickering+ if (width > 0) {+ setStableWidth(width);+ }++ if (height > 0) {+ setStableHeight(height);+ }+ }, [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 legend =+ showLegend && layout.type !== "small" && layout.LegendComponent ? (+ <layout.LegendComponent+ className={styles.Legend}+ titles={layout.processedLegendTitles}+ hiddenIndices={legendHiddenIndices}+ colors={legendColors}+ dotSize={isDashboard ? "8px" : "12px"}+ hovered={hovered}+ onHoverChange={onHoverChange}+ onToggleSeriesVisibility={onToggleSeriesVisibility}+ />+ ) : null;++ return (+ <div+ className={cx(+ className,+ DashboardS.fullscreenNormalText,+ styles.ChartWithLegend,+ styles[layout.type],+ layout.flexChart && styles.flexChart,+ )}+ style={{+ ...style,+ paddingBottom: PADDING,+ paddingLeft: PADDING,+ paddingRight: PADDING,+ }}+ ref={forwardedRef}+ >+ {legend && (+ <div className={cx(styles.LegendWrapper)} data-testid="chart-legend">+ {legend}+ </div>+ )}+ <div+ className={cx(styles.Chart, chartClassName)}+ style={{+ width: layout.chartWidth,+ height: layout.chartHeight,+ }}+ >+ {layout.hasDimensions && children}+ </div>+ {/* spacer div to balance legend */}+ {legend && (+ <div+ className={cx(styles.LegendSpacer)}+ // don't center the chart on dashboards+ style={isDashboard || isDocument ? { flexBasis: 0 } : {}}+ data-testid="chart-legend-spacer"+ >+ {legend}+ </div>+ )}+ </div>+ );+};++const ChartWithLegendRefWrapper = forwardRef(+ function _ChartWithLegendRefWrapper(+ props: ChartWithLegendProps,+ ref: Ref<HTMLDivElement>,+ ) {+ return <ChartWithLegendInner {...props} forwardedRef={ref} />;+ },+);++export const ChartWithLegend = ExplicitSize<ChartWithLegendProps>({+ wrapped: true,+ refreshMode: "debounce",+})(ChartWithLegendRefWrapper);diff --git a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.jsx b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsxsimilarity index 70%rename from frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.jsxrename to frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsxindex d37426402d3..9a69254d966 100644--- a/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.jsx+++ b/frontend/src/metabase/visualizations/components/ChartWithLegend.unit.spec.tsx@@ -1,11 +1,44 @@+import type { CSSProperties, MouseEvent, ReactNode } from "react";+import { render, screen } from "__support__/ui";+import type { HoveredObject } from "metabase/visualizations/types";-import ChartWithLegend, {+import {+ ChartWithLegend,HIDE_HORIZONTAL_LEGEND_THRESHOLD,HIDE_SECONDARY_INFO_THRESHOLD,} from "./ChartWithLegend";-const defaultProps = {+type LegendTitle = string | string[];++type LegendHover = {+ index: number;+ element?: HTMLElement | null;+};++interface SetupProps {+ children?: ReactNode;+ legendTitles: LegendTitle[];+ legendHiddenIndices?: number[];+ legendColors: string[];+ hovered?: HoveredObject | null;+ onHoverChange?: (hover?: LegendHover | null) => void;+ className?: string;+ style?: CSSProperties;+ gridSize?: {+ width: number;+ height: number;+ };+ aspectRatio?: number;+ height: number;+ width: number;+ showLegend?: boolean;+ isDashboard?: boolean;+ isDocument?: boolean;+ onToggleSeriesVisibility?: (event: MouseEvent, index: number) => void;+}++const defaultProps: SetupProps = {legendTitles: [["Series 1", "50%"],["Series 2", "50%"],@@ -18,7 +51,7 @@ const defaultProps = {children: <div>Chart stub</div>,};-const setup = (props = {}) => {+const setup = (props: Partial<SetupProps> = {}) => {render(<ChartWithLegend {...defaultProps} {...props} />);};diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.jsxindex b09e4d6cc7d..83aaad8da4d 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx@@ -28,7 +28,7 @@ import {} from "metabase/visualizations/shared/utils/sizes";import { isMetric, isString } from "metabase-lib/v1/types/utils/isa";-import ChartWithLegend from "./ChartWithLegend";+import { ChartWithLegend } from "./ChartWithLegend";import LeafletChoropleth from "./LeafletChoropleth";import LegacyChoropleth from "./LegacyChoropleth";diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.module.css b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.module.cssnew file mode 100644index 00000000000..f024134ced7--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.module.css@@ -0,0 +1,8 @@+.PieChartContainer {+ div > svg {+ /* Make sure the svg is centralized to avoid overflow and flickering when container is resized */+ left: 50% !important;+ position: absolute;+ translate: -50% 0;+ }+}diff --git a/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsxindex ed212a1c7a5..8a0ca11045c 100644--- a/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/PieChart/PieChart.tsx@@ -4,7 +4,7 @@ import { useSet } from "react-use";import { isNotNull } from "metabase/lib/types";import { extractRemappings } from "metabase/visualizations";-import ChartWithLegend from "metabase/visualizations/components/ChartWithLegend";+import { ChartWithLegend } from "metabase/visualizations/components/ChartWithLegend";import { ResponsiveEChartsRenderer } from "metabase/visualizations/components/EChartsRenderer";import { getPieChartFormatters } from "metabase/visualizations/echarts/pie/format";import { getPieChartModel } from "metabase/visualizations/echarts/pie/model";@@ -19,6 +19,7 @@ import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-brimport type { VisualizationProps } from "metabase/visualizations/types";import { useTooltipMouseLeave } from "metabase/visualizations/visualizations/CartesianChart/use-tooltip-mouse-leave";+import S from "./PieChart.module.css";import { PIE_CHART_DEFINITION } from "./chart-definition";import { useChartEvents } from "./use-chart-events";@@ -183,6 +184,7 @@ export function PieChart(props: VisualizationProps) {showLegend={showLegend}onHoverChange={onHoverChange}className={props.className}+ chartClassName={S.PieChartContainer}gridSize={props.gridSize}hovered={props.hovered}isDashboard={isDashboard}