Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Keep Number and Trend card titles visible on small dashboard cards (#84567)

Anderson57aecc58d966
diff --git a/.loki/reference/chrome_laptop_App_Embed_DashCardMenuButton_States.png b/.loki/reference/chrome_laptop_App_Embed_DashCardMenuButton_States.png
index b4216478379..b3dd3a8c0cc 100644
Binary files a/.loki/reference/chrome_laptop_App_Embed_DashCardMenuButton_States.png and b/.loki/reference/chrome_laptop_App_Embed_DashCardMenuButton_States.png differ
diff --git a/.loki/reference/chrome_laptop_Viz_Components_ChartSkeleton_Scalar_Size_Tiers.png b/.loki/reference/chrome_laptop_Viz_Components_ChartSkeleton_Scalar_Size_Tiers.png
index 32012ea63e7..2483b67653c 100644
Binary files a/.loki/reference/chrome_laptop_Viz_Components_ChartSkeleton_Scalar_Size_Tiers.png and b/.loki/reference/chrome_laptop_Viz_Components_ChartSkeleton_Scalar_Size_Tiers.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Scalar_Compact_Sizes.png b/.loki/reference/chrome_laptop_viz_Scalar_Compact_Sizes.png
new file mode 100644
index 00000000000..65e4cefb6bc
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Scalar_Compact_Sizes.png differ
diff --git a/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons.png b/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons.png
index 36d643484f3..b8729391549 100644
Binary files a/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons.png and b/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons.png differ
diff --git a/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons_Tall.png b/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons_Tall.png
index 3e6b728d777..1b492fc58fc 100644
Binary files a/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons_Tall.png and b/.loki/reference/chrome_laptop_viz_SmartScalar_Dashcard_Multiple_Comparisons_Tall.png differ
diff --git a/.loki/reference/chrome_laptop_viz_SmartScalar_Default.png b/.loki/reference/chrome_laptop_viz_SmartScalar_Default.png
index adc4c0e2b8a..38fcbcdafe3 100644
Binary files a/.loki/reference/chrome_laptop_viz_SmartScalar_Default.png and b/.loki/reference/chrome_laptop_viz_SmartScalar_Default.png differ
diff --git a/e2e/test/scenarios/dashboard/dashcard-resizing.cy.spec.js b/e2e/test/scenarios/dashboard/dashcard-resizing.cy.spec.js
index 54cadb73d14..65be744c9ba 100644
--- a/e2e/test/scenarios/dashboard/dashcard-resizing.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashcard-resizing.cy.spec.js
@@ -750,11 +750,13 @@ describe("issue 31628", () => {
scalarContainer(card("scalar2x2")).then(($element) =>
H.assertIsNotEllipsified($element[0]),
);
- cy.log(
- "scalar 2x2: should show the title tooltip on hover because the smallest cards hide the inline title",
- );
+ cy.log("scalar 2x2: should keep the title visible without hovering");
+ card("scalar2x2")
+ .findByTestId("scalar-title")
+ .should("contain", SCALAR_QUESTION.name)
+ .and("be.visible");
scalarContainer(card("scalar2x2")).realHover();
- cy.findByRole("tooltip").findByText(SCALAR_QUESTION.name).should("exist");
+ cy.findByRole("tooltip").should("not.exist");
moveMouseAway();
cy.log(
@@ -771,13 +773,13 @@ describe("issue 31628", () => {
scalarContainer(card("smart2x2")).then(($element) =>
H.assertIsNotEllipsified($element[0]),
);
- cy.log(
- "smart scalar 2x2: should show the title tooltip on hover because the smallest cards hide the inline title",
- );
+ cy.log("smart scalar 2x2: should keep the title visible without hovering");
+ card("smart2x2")
+ .findByTestId("scalar-title")
+ .should("contain", SMART_SCALAR_QUESTION.name)
+ .and("be.visible");
scalarContainer(card("smart2x2")).realHover();
- cy.findByRole("tooltip")
- .findByText(SMART_SCALAR_QUESTION.name)
- .should("exist");
+ cy.findByRole("tooltip").should("not.exist");
moveMouseAway();
cy.log(
@@ -818,7 +820,7 @@ describe("issue 31628", () => {
moveMouseAway();
cy.log(`${key}: should show description tooltip on hover`);
- card(key).findByTestId("scalar-title").icon("info").realHover();
+ card(key).icon("info").realHover();
cy.findByRole("tooltip")
.findByText(SMART_SCALAR_QUESTION.description)
.should("exist");
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCard.module.css b/frontend/src/metabase/dashboard/components/DashCard/DashCard.module.css
index bdddc2ebec6..128dbb11af8 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCard.module.css
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCard.module.css
@@ -15,6 +15,8 @@
}
.DashCardRoot {
+ --scalar-description-opacity: 0;
+
background-color: var(--mb-color-bg-dashboard-card);
scroll-margin: 6px 0;
border-radius: 0.75rem;
@@ -22,6 +24,8 @@
transition: border-color 0.15s ease-in-out;
&:hover {
+ --scalar-description-opacity: 1;
+
border-color: var(--mb-color-border-neutral-strong);
}
@@ -63,11 +67,22 @@
&:hover {
color: var(--mb-color-text-primary);
- background: var(--mb-color-background_surface-primary-hover);
+ /* Equal gradient stops make a solid tint over the opaque surface below. */
+ background:
+ linear-gradient(
+ var(--mb-color-background_surface-primary-hover),
+ var(--mb-color-background_surface-primary-hover)
+ ),
+ var(--mb-color-background_surface-primary);
}
&:active {
- background: var(--mb-color-background_surface-primary-pressed);
+ background:
+ linear-gradient(
+ var(--mb-color-background_surface-primary-pressed),
+ var(--mb-color-background_surface-primary-pressed)
+ ),
+ var(--mb-color-background_surface-primary);
box-shadow: none;
transform: none;
}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarActionButtons.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarActionButtons.tsx
index 41c5f4c3565..b69ec428935 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarActionButtons.tsx
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarActionButtons.tsx
@@ -1,4 +1,4 @@
-import type { HTMLAttributes, PropsWithChildren } from "react";
+import type { PropsWithChildren } from "react";
import { Box } from "metabase/ui";
@@ -7,19 +7,17 @@ import type { ScalarSizeTier } from "./sizing";
export const ScalarActionButtons = ({
children,
tier,
- ...props
-}: PropsWithChildren<{ tier: ScalarSizeTier }> &
- HTMLAttributes<HTMLDivElement>) => {
+}: PropsWithChildren<{ tier: ScalarSizeTier }>) => {
if (!children) {
return null;
}
return (
<Box
pos="absolute"
+ style={{ zIndex: 1 }}
top={tier.menuOffset.top}
right={tier.menuOffset.right}
data-testid="scalar-action-buttons"
- {...props}
>
{children}
</Box>
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarCardShell.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarCardShell.tsx
index b41c4e7757f..98cd4a29b2b 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarCardShell.tsx
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarCardShell.tsx
@@ -1,7 +1,7 @@
-import { Children, type ReactNode, useState } from "react";
+import { Children, type ReactNode } from "react";
import { useTranslateContent } from "metabase/content-translation/hooks";
-import { Stack, Tooltip } from "metabase/ui";
+import { Center, Stack } from "metabase/ui";
import { getRootFontScale } from "metabase/visualizations/lib/scalar_utils";
import type {
VisualizationPassThroughProps,
@@ -13,12 +13,11 @@ import { ScalarTitle } from "./ScalarTitle";
import { ScalarWrapper } from "./ScalarValue";
import { type ScalarSizeTier, getScalarSizeTier } from "./sizing";
-const TITLE_TOOLTIP_OFFSET = 1;
-
type ScalarCardProps = VisualizationProps & VisualizationPassThroughProps;
interface UseScalarCardShellOptions {
hideTitle?: boolean;
+ shouldHideDescription?: (tier: ScalarSizeTier) => boolean;
}
export function useScalarCardShell(
@@ -37,24 +36,18 @@ export function useScalarCardShell(
isDashboard,
isEditing,
}: ScalarCardProps,
- { hideTitle = false }: UseScalarCardShellOptions = {},
+ { hideTitle = false, shouldHideDescription }: UseScalarCardShellOptions = {},
) {
- const [isInnerTooltipHovered, setIsInnerTooltipHovered] = useState(false);
- const innerTooltipHoverHandlers = {
- onMouseEnter: () => setIsInnerTooltipHovered(true),
- onMouseLeave: () => setIsInnerTooltipHovered(false),
- };
-
const tier = getScalarSizeTier(width, height);
const rootFontScale = getRootFontScale();
const availableWidth = Math.max(width - 2 * tier.xPadding * rootFontScale, 0);
const tc = useTranslateContent();
const title = showTitle && !hideTitle ? tc(settings["card.title"]) : null;
- const showsInlineTitle = Boolean(title) && tier.showsTitle;
- const showsTitleOnHover = Boolean(title) && !tier.showsTitle;
const description =
- isDashboard && isEditing ? null : settings["card.description"];
+ shouldHideDescription?.(tier) || (isDashboard && isEditing)
+ ? null
+ : settings["card.description"];
const canSelectTitle =
onChangeCardAndRun != null &&
@@ -64,11 +57,9 @@ export function useScalarCardShell(
nextCard: (visualizerRawSeries ?? rawSeries)[0].card,
});
- const showsTitleTooltip = showsTitleOnHover && !isInnerTooltipHovered;
-
- const titleElement = showsInlineTitle ? (
+ const titleElement = title ? (
<ScalarTitle
- description={description}
+ size={tier.size < 200 ? "sm" : "md"}
icon={headerIcon}
getHref={canSelectTitle ? getHref : undefined}
onSelectTitle={canSelectTitle ? handleSelectTitle : undefined}
@@ -81,54 +72,42 @@ export function useScalarCardShell(
tier,
rootFontScale,
availableWidth,
- title,
titleElement,
- showsTitleTooltip,
- innerTooltipHoverHandlers,
+ description: title ? description : null,
};
}
interface ScalarCardShellProps {
tier: ScalarSizeTier;
- title: ReactNode;
- showsTitleTooltip: boolean;
actionButtons: ReactNode;
- innerTooltipHoverHandlers: {
- onMouseEnter: () => void;
- onMouseLeave: () => void;
- };
children: ReactNode;
+ footer?: ReactNode;
}
export function ScalarCardShell({
tier,
- title,
- showsTitleTooltip,
actionButtons,
- innerTooltipHoverHandlers,
children,
+ footer,
}: ScalarCardShellProps) {
return (
- <Tooltip
- label={title}
- disabled={!showsTitleTooltip}
- position="top"
- offset={TITLE_TOOLTIP_OFFSET}
- >
- <ScalarWrapper xPadding={tier.xPadding}>
- <ScalarActionButtons tier={tier} {...innerTooltipHoverHandlers}>
- {actionButtons}
- </ScalarActionButtons>
- <Stack
- pos="relative"
- align="center"
- gap={tier.valueTitleGap}
- maw="100%"
- data-testid="scalar-content"
- >
- {children}
- </Stack>
- </ScalarWrapper>
- </Tooltip>
+ <ScalarWrapper xPadding={tier.xPadding}>
+ <ScalarActionButtons tier={tier}>{actionButtons}</ScalarActionButtons>
+ <Stack
+ pos="relative"
+ align="center"
+ gap={tier.valueTitleGap}
+ w="100%"
+ data-testid="scalar-content"
+ >
+ {children}
+ {/* Keep the footer out of flow so it cannot shift the centered content. */}
+ {footer && (
+ <Center pos="absolute" top="100%" mt={2} w="100%">
+ {footer}
+ </Center>
+ )}
+ </Stack>
+ </ScalarWrapper>
);
}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.module.css b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.module.css
new file mode 100644
index 00000000000..d0862912613
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.module.css
@@ -0,0 +1,25 @@
+.descriptionIcon {
+ display: flex;
+ flex: 0 0 auto;
+ color: var(--mb-color-text-disabled);
+ opacity: var(--scalar-description-opacity, 1);
+ transition: opacity 0.2s ease-in-out;
+
+ &:hover {
+ color: var(--mb-color-text-secondary);
+ }
+
+ &:focus-visible {
+ opacity: 1;
+ color: var(--mb-color-text-secondary);
+ outline: 2px solid var(--mb-color-core-brand);
+ outline-offset: 2px;
+ border-radius: 4px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .descriptionIcon {
+ transition: none;
+ }
+}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.tsx
new file mode 100644
index 00000000000..e29062c37af
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/ScalarDescription.tsx
@@ -0,0 +1,26 @@
+import { Markdown } from "metabase/common/components/Markdown";
+import { useTranslateContent } from "metabase/content-translation/hooks";
+import { Box, Icon, Tooltip } from "metabase/ui";
+
+import S from "./ScalarDescription.module.css";
+
+export const DESCRIPTION_ICON_SIZE = 16;
+
+export function ScalarDescription({ description }: { description: string }) {
+ const tc = useTranslateContent();
+
+ return (
+ <Tooltip
+ label={
+ <Markdown dark compact disallowHeading unstyleLinks lineClamp={8}>
+ {tc(description)}
+ </Markdown>
+ }
+ maw="22em"
+ >
+ <Box component="span" tabIndex={0} className={S.descriptionIcon}>
+ <Icon name="info" size={DESCRIPTION_ICON_SIZE} />
+ </Box>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/index.ts b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/index.ts
new file mode 100644
index 00000000000..e55f4f019ef
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarDescription/index.ts
@@ -0,0 +1 @@
+export * from "./ScalarDescription";
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/ScalarLabel.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/ScalarLabel.tsx
new file mode 100644
index 00000000000..f44eed6504d
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/ScalarLabel.tsx
@@ -0,0 +1,38 @@
+import type { ReactNode } from "react";
+
+import { Box, Flex, rem } from "metabase/ui";
+
+import { DESCRIPTION_ICON_SIZE, ScalarDescription } from "../ScalarDescription";
+
+const DESCRIPTION_ICON_GAP = 8;
+const DESCRIPTION_ICON_SPACE = DESCRIPTION_ICON_SIZE + DESCRIPTION_ICON_GAP;
+
+interface ScalarLabelProps {
+ children: ReactNode;
+ description?: string | null;
+}
+
+export function ScalarLabel({ children, description }: ScalarLabelProps) {
+ // Reserve equal icon space on both sides to keep the text centered and the icon inside the padding.
+ const maxWidth = description
+ ? `calc(100% - ${rem(2 * DESCRIPTION_ICON_SPACE)})`
+ : "100%";
+
+ return (
+ <Flex
+ pos="relative"
+ align="center"
+ justify="center"
+ gap="xxs"
+ miw={0}
+ maw={maxWidth}
+ >
+ {children}
+ {description && (
+ <Box pos="absolute" left={`calc(100% + ${rem(DESCRIPTION_ICON_GAP)})`}>
+ <ScalarDescription description={description} />
+ </Box>
+ )}
+ </Flex>
+ );
+}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/index.ts b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/index.ts
new file mode 100644
index 00000000000..271ed0dafd8
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarLabel/index.ts
@@ -0,0 +1 @@
+export { ScalarLabel } from "./ScalarLabel";
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarTitle.tsx b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarTitle.tsx
index a37091f8604..8d1b461a84f 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarTitle.tsx
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarTitle.tsx
@@ -1,33 +1,22 @@
-import cx from "classnames";
import { type ReactNode, useCallback, useState } from "react";
-import { Markdown } from "metabase/common/components/Markdown";
-import { useTranslateContent } from "metabase/content-translation/hooks";
-import CS from "metabase/css/core/index.css";
-import {
- Box,
- Ellipsified,
- Flex,
- Icon,
- type IconProps,
- Tooltip,
-} from "metabase/ui";
+import { Box, Ellipsified, Flex, Icon, type IconProps } from "metabase/ui";
import { LegendLabel } from "../legend/LegendLabel";
import S from "./ScalarValue.module.css";
interface ScalarTitleProps {
+ size?: "sm" | "md";
children: ReactNode;
- description?: string | null;
icon?: IconProps | null;
getHref?: () => string | undefined;
onSelectTitle?: () => void;
}
export const ScalarTitle = ({
+ size = "md",
children,
- description,
icon,
getHref,
onSelectTitle,
@@ -39,7 +28,6 @@ export const ScalarTitle = ({
}
}, [getHref]);
- const tc = useTranslateContent();
const title = <Ellipsified tooltip={children}>{children}</Ellipsified>;
return (
@@ -48,6 +36,7 @@ export const ScalarTitle = ({
justify="center"
gap="xxs"
maw="100%"
+ miw={0}
data-testid="scalar-title"
>
{icon && (
@@ -59,7 +48,7 @@ export const ScalarTitle = ({
tooltip={icon.tooltip}
/>
)}
- <Box fz="md" lh="md" fw={700} c="text-primary" ta="center" miw={0}>
+ <Box fz={size} lh={size} fw={700} c="text-primary" ta="center" miw={0}>
{onSelectTitle ? (
<LegendLabel
className={S.titleLink}
@@ -76,28 +65,6 @@ export const ScalarTitle = ({
title
)}
</Box>
- {description && (
- <Tooltip
- label={
- <Markdown dark compact disallowHeading unstyleLinks lineClamp={8}>
- {tc(description)}
- </Markdown>
- }
- maw="22em"
- >
- <Box
- component="span"
- tabIndex={0}
- className={cx(
- S.descriptionIcon,
- CS.hoverChild,
- CS.hoverChildSmooth,
- )}
- >
- <Icon name="info" />
- </Box>
- </Tooltip>
- )}
</Flex>
);
};
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.module.css b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.module.css
index d10493aadd7..44abd3069dd 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.module.css
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/ScalarValue.module.css
@@ -26,25 +26,3 @@
.titleIcon {
flex: 0 0 auto;
}
-
-.descriptionIcon {
- display: flex;
- flex: 0 0 auto;
- color: var(--mb-color-text-disabled);
-
- &&&& {
- visibility: visible;
- }
-
- &&&&:hover {
- color: var(--mb-color-text-secondary);
- }
-
- &&&&:focus-visible {
- opacity: 1;
- color: var(--mb-color-text-secondary);
- outline: 2px solid var(--mb-color-core-brand);
- outline-offset: 2px;
- border-radius: 4px;
- }
-}
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/sizing.ts b/frontend/src/metabase/visualizations/components/ScalarValue/sizing.ts
index 89c94e72f41..c26e92a3ee7 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/sizing.ts
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/sizing.ts
@@ -1,4 +1,5 @@
export interface ScalarSizeTier {
+ size: 100 | 150 | 200 | 300 | 400 | 500 | 600;
minWidth: number;
minHeight: number;
xPadding: number;
@@ -9,19 +10,19 @@ export interface ScalarSizeTier {
comparisonGap: number;
multiComparisonMinHeight: number | null;
menuOffset: { top: number; right: number };
- showsTitle: boolean;
skeleton: { valueWidth: number; valueHeight: number; titleWidth: number };
}
const SMALL_MENU_OFFSET = { top: 12, right: 16 };
const LARGE_MENU_OFFSET = { top: 22, right: 24 };
-// Largest tier first; a card gets the first tier it fits both dimensions of.
-// Values come from the "Charts visual improvements" Figma spec (node 314-478);
+// Largest tier first; both measured dimensions must fit.
+// Values come from the "Charts visual improvements" Figma specs (nodes 314-478 and 915-2038);
// skeleton pill sizes come from the loading states spec (node 431-1518) and
// the multiple-comparison heights from the Trend card spec (node 528-2394).
export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
{
+ size: 600,
minWidth: 600,
minHeight: 320,
xPadding: 48,
@@ -32,10 +33,10 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 12,
multiComparisonMinHeight: 320,
menuOffset: LARGE_MENU_OFFSET,
- showsTitle: true,
skeleton: { valueWidth: 200, valueHeight: 32, titleWidth: 256 },
},
{
+ size: 500,
minWidth: 500,
minHeight: 240,
xPadding: 40,
@@ -46,10 +47,10 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 12,
multiComparisonMinHeight: 288,
menuOffset: LARGE_MENU_OFFSET,
- showsTitle: true,
skeleton: { valueWidth: 160, valueHeight: 32, titleWidth: 256 },
},
{
+ size: 400,
minWidth: 400,
minHeight: 200,
xPadding: 32,
@@ -60,10 +61,10 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 8,
multiComparisonMinHeight: 264,
menuOffset: LARGE_MENU_OFFSET,
- showsTitle: true,
skeleton: { valueWidth: 96, valueHeight: 32, titleWidth: 128 },
},
{
+ size: 300,
minWidth: 320,
minHeight: 160,
xPadding: 24,
@@ -74,10 +75,10 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 8,
multiComparisonMinHeight: 256,
menuOffset: SMALL_MENU_OFFSET,
- showsTitle: true,
skeleton: { valueWidth: 72, valueHeight: 24, titleWidth: 128 },
},
{
+ size: 200,
minWidth: 160,
minHeight: 120,
xPadding: 24,
@@ -88,10 +89,24 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 6,
multiComparisonMinHeight: 240,
menuOffset: SMALL_MENU_OFFSET,
- showsTitle: true,
skeleton: { valueWidth: 72, valueHeight: 24, titleWidth: 128 },
},
{
+ size: 150,
+ minWidth: 120,
+ minHeight: 64,
+ xPadding: 8,
+ valueFontSize: 21,
+ valueTitleGap: 8,
+ symbolSize: 12,
+ symbolGap: 6,
+ comparisonGap: 6,
+ multiComparisonMinHeight: null,
+ menuOffset: SMALL_MENU_OFFSET,
+ skeleton: { valueWidth: 40, valueHeight: 21, titleWidth: 72 },
+ },
+ {
+ size: 100,
minWidth: 0,
minHeight: 0,
xPadding: 8,
@@ -102,7 +117,6 @@ export const SCALAR_SIZE_TIERS: readonly ScalarSizeTier[] = [
comparisonGap: 6,
multiComparisonMinHeight: null,
menuOffset: SMALL_MENU_OFFSET,
- showsTitle: false,
skeleton: { valueWidth: 40, valueHeight: 17, titleWidth: 128 },
},
];
diff --git a/frontend/src/metabase/visualizations/components/ScalarValue/sizing.unit.spec.ts b/frontend/src/metabase/visualizations/components/ScalarValue/sizing.unit.spec.ts
index af327bcf334..3869aee7f8d 100644
--- a/frontend/src/metabase/visualizations/components/ScalarValue/sizing.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/components/ScalarValue/sizing.unit.spec.ts
@@ -5,35 +5,40 @@ describe("getScalarSizeTier", () => {
expect(getScalarSizeTier(80, 80)).toBe(
SCALAR_SIZE_TIERS[SCALAR_SIZE_TIERS.length - 1],
);
- expect(getScalarSizeTier(0, 0).valueFontSize).toBe(17);
+ expect(getScalarSizeTier(0, 0).size).toBe(100);
});
it("requires both dimensions to fit before upgrading the tier", () => {
// wide but short card stays on the tier its height allows
- expect(getScalarSizeTier(800, 130).valueFontSize).toBe(32);
+ expect(getScalarSizeTier(800, 130).size).toBe(200);
// tall but narrow card stays on the tier its width allows
- expect(getScalarSizeTier(180, 800).valueFontSize).toBe(32);
+ expect(getScalarSizeTier(180, 800).size).toBe(200);
});
it("picks tiers by the spec thresholds", () => {
- expect(getScalarSizeTier(160, 120).valueFontSize).toBe(32);
- expect(getScalarSizeTier(320, 160).valueFontSize).toBe(40);
- expect(getScalarSizeTier(400, 200).valueFontSize).toBe(48);
- expect(getScalarSizeTier(500, 240).valueFontSize).toBe(56);
- expect(getScalarSizeTier(600, 320).valueFontSize).toBe(64);
+ expect(getScalarSizeTier(160, 120).size).toBe(200);
+ expect(getScalarSizeTier(320, 160).size).toBe(300);
+ expect(getScalarSizeTier(400, 200).size).toBe(400);
+ expect(getScalarSizeTier(500, 240).size).toBe(500);
+ expect(getScalarSizeTier(600, 320).size).toBe(600);
+ });
+
+ it("distinguishes short wide cards from the smallest cards", () => {
+ expect(getScalarSizeTier(119, 82).size).toBe(100);
+ expect(getScalarSizeTier(120, 63).size).toBe(100);
+ expect(getScalarSizeTier(120, 64).size).toBe(150);
+ expect(getScalarSizeTier(800, 82).size).toBe(150);
+ expect(getScalarSizeTier(160, 119).size).toBe(150);
+ expect(getScalarSizeTier(160, 120).size).toBe(200);
});
it("lists every comparison only from the spec min-height of each tier", () => {
expect(getScalarSizeTier(100, 400).multiComparisonMinHeight).toBeNull();
+ expect(getScalarSizeTier(126, 400).multiComparisonMinHeight).toBeNull();
expect(getScalarSizeTier(160, 120).multiComparisonMinHeight).toBe(240);
expect(getScalarSizeTier(320, 160).multiComparisonMinHeight).toBe(256);
expect(getScalarSizeTier(400, 200).multiComparisonMinHeight).toBe(264);
expect(getScalarSizeTier(500, 240).multiComparisonMinHeight).toBe(288);
expect(getScalarSizeTier(600, 320).multiComparisonMinHeight).toBe(320);
});
-
- it("hides the title only on the smallest tier", () => {
- expect(getScalarSizeTier(100, 100).showsTitle).toBe(false);
- expect(getScalarSizeTier(160, 120).showsTitle).toBe(true);
- });
});
diff --git a/frontend/src/metabase/visualizations/components/skeletons/ChartSkeleton/ChartSkeleton.stories.tsx b/frontend/src/metabase/visualizations/components/skeletons/ChartSkeleton/ChartSkeleton.stories.tsx
index db385a15edb..eec16fe4304 100644
--- a/frontend/src/metabase/visualizations/components/skeletons/ChartSkeleton/ChartSkeleton.stories.tsx
+++ b/frontend/src/metabase/visualizations/components/skeletons/ChartSkeleton/ChartSkeleton.stories.tsx
@@ -129,6 +129,7 @@ export const Scalar = {
const SCALAR_CARD_SIZES: [number, number][] = [
[82, 82],
+ [126, 82],
[256, 126],
[345, 170],
[433, 214],
diff --git a/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.tsx b/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.tsx
index 57c1f7ca22d..ab86bd10415 100644
--- a/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.tsx
+++ b/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.tsx
@@ -7,8 +7,7 @@ import SkeletonCaption from "metabase/visualizations/components/skeletons/Skelet
import S from "./ScalarSkeleton.module.css";
-// the title renders at fz "md" / lh "md", which is a 17px line
-const TITLE_LINE_HEIGHT = 17;
+const TITLE_LINE_HEIGHT = { sm: 14, md: 17 };
const PILL_RADIUS = 8;
const TITLE_PILL_HEIGHT = 8;
@@ -67,7 +66,12 @@ const ScalarSkeleton = ({
data-testid="scalar-skeleton"
>
{actionMenu && <Box className={S.actionMenu}>{actionMenu}</Box>}
- <Stack align="center" gap={tier.valueTitleGap}>
+ <Stack
+ align="center"
+ gap={tier.valueTitleGap}
+ maw="100%"
+ px={tier.xPadding}
+ >
<Flex align="center" justify="center" h={tier.valueFontSize}>
<Skeleton
radius={PILL_RADIUS}
@@ -78,15 +82,19 @@ const ScalarSkeleton = ({
{name ? (
<SkeletonCaption name={name} description={description} />
) : (
- tier.showsTitle && (
- <Flex align="center" justify="center" h={TITLE_LINE_HEIGHT}>
- <Skeleton
- radius={PILL_RADIUS}
- w={tier.skeleton.titleWidth}
- h={TITLE_PILL_HEIGHT}
- />
- </Flex>
- )
+ <Flex
+ align="center"
+ justify="center"
+ h={TITLE_LINE_HEIGHT[tier.size < 200 ? "sm" : "md"]}
+ maw="100%"
+ >
+ <Skeleton
+ radius={PILL_RADIUS}
+ w={tier.skeleton.titleWidth}
+ h={TITLE_PILL_HEIGHT}
+ maw="100%"
+ />
+ </Flex>
)}
</Stack>
</Flex>
diff --git a/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.unit.spec.tsx b/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.unit.spec.tsx
index b8b8d186fb8..405eec12051 100644
--- a/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/components/skeletons/ScalarSkeleton/ScalarSkeleton.unit.spec.tsx
@@ -3,13 +3,13 @@ import { render, screen } from "__support__/ui";
import ScalarSkeleton from "./ScalarSkeleton";
describe("ScalarSkeleton", () => {
- it("should show a value pill", () => {
+ it("should show value and title placeholders even before measuring the card (#84334)", () => {
render(<ScalarSkeleton />);
const skeleton = screen.getByTestId("scalar-skeleton");
expect(skeleton).toBeInTheDocument();
expect(skeleton.querySelectorAll(".mb-mantine-Skeleton-root")).toHaveLength(
- 1,
+ 2,
);
});
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx
index 87459d134f2..3cd756dc991 100644
--- a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.stories.tsx
@@ -11,6 +11,7 @@ import type { Series } from "metabase-types/api";
import {
createMockCard,
createMockSegmentFormatting,
+ createMockSingleSeries,
} from "metabase-types/api/mocks";
import { Scalar } from "./Scalar";
@@ -22,6 +23,54 @@ export default {
registerVisualization(Scalar);
+const COMPACT_CARD_SIZES = [
+ { width: 82, height: 82 },
+ { width: 106, height: 82 },
+ { width: 126, height: 82 },
+ { width: 170, height: 82 },
+ { width: 82, height: 126 },
+];
+
+export const CompactSizes = () => (
+ <VisualizationWrapper>
+ <SimpleGrid cols={5} spacing="lg" p="lg" w={1000}>
+ {[
+ { name: "Revenue", description: null },
+ { name: "Revenue", description: "Total revenue" },
+ { name: "Revenue from all orders", description: "Total revenue" },
+ ].flatMap(({ name, description }) =>
+ COMPACT_CARD_SIZES.map(({ width, height }) => (
+ <Box
+ key={`${name}-${description}-${width}-${height}`}
+ w={width}
+ h={height}
+ style={{
+ borderRadius: 12,
+ border: "1px solid var(--mb-color-border-neutral)",
+ }}
+ >
+ <Visualization
+ rawSeries={[
+ createMockSingleSeries(
+ { name, description, display: "scalar" },
+ {
+ data: {
+ cols: [NumberColumn({ name: "Count" })],
+ rows: [[1510621.68]],
+ },
+ },
+ ),
+ ]}
+ showTitle
+ width={width}
+ />
+ </Box>
+ )),
+ )}
+ </SimpleGrid>
+ </VisualizationWrapper>
+);
+
// Unjustified type cast. FIXME
const MOCK_SERIES = [
{
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
index acd71208075..89576013f58 100644
--- a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.tsx
@@ -7,6 +7,8 @@ import {
ScalarCardShell,
useScalarCardShell,
} from "metabase/visualizations/components/ScalarValue/ScalarCardShell";
+import { ScalarDescription } from "metabase/visualizations/components/ScalarValue/ScalarDescription";
+import { ScalarLabel } from "metabase/visualizations/components/ScalarValue/ScalarLabel";
import { ScalarValue } from "metabase/visualizations/components/ScalarValue/ScalarValue";
import { TransformedVisualization } from "metabase/visualizations/components/TransformedVisualization";
import {
@@ -63,14 +65,14 @@ function ScalarComponent(
const sublabel = settings["scalar.sublabel"];
const isMetricsViewer = label !== undefined;
- const {
- tier,
- availableWidth,
- title,
- titleElement,
- showsTitleTooltip,
- innerTooltipHoverHandlers,
- } = useScalarCardShell(props, { hideTitle: isMetricsViewer });
+ const { tier, availableWidth, titleElement, description } =
+ useScalarCardShell(props, {
+ hideTitle: isMetricsViewer,
+ });
+ const descriptionFooter =
+ tier.size === 100 && description ? (
+ <ScalarDescription description={description} />
+ ) : null;
if (rawSeries.length > 1) {
return (
@@ -131,18 +133,13 @@ function ScalarComponent(
}
};
- const hasValueTooltip =
- fullScalarValue !== displayValue || tooltipContent != null;
-
return (
<ScalarCardShell
tier={tier}
- title={title}
- showsTitleTooltip={showsTitleTooltip}
actionButtons={actionButtons}
- innerTooltipHoverHandlers={innerTooltipHoverHandlers}
+ footer={descriptionFooter}
>
- <Box maw="100%" {...(hasValueTooltip ? innerTooltipHoverHandlers : {})}>
+ <Box maw="100%">
<ScalarValueContainer
className={DashboardS.fullscreenNormalText}
tooltip={fullScalarValue}
@@ -178,7 +175,11 @@ function ScalarComponent(
</Tooltip>
</ScalarValueContainer>
</Box>
- {titleElement}
+ {titleElement && (
+ <ScalarLabel description={descriptionFooter ? null : description}>
+ {titleElement}
+ </ScalarLabel>
+ )}
</ScalarCardShell>
);
}
diff --git a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.unit.spec.tsx b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.unit.spec.tsx
index 7a07b6eec92..2959df73751 100644
--- a/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Scalar/Scalar.unit.spec.tsx
@@ -68,29 +68,29 @@ describe("Scalar", () => {
expect(screen.getByText("12.3k")).toBeInTheDocument();
});
- it("should show one tooltip at a time on the smallest cards", async () => {
- render(
- <Scalar
- {...mockedProps}
- showTitle
- series={series(12345.6)}
- rawSeries={series(12345.6)}
- settings={settings}
- visualizationIsClickable={() => false}
- width={80}
- />,
- );
-
- // hovering the compacted value shows the full value, not the title
- await userEvent.hover(screen.getByTestId("scalar-container"));
- expect(await screen.findByText("12,345.6")).toBeInTheDocument();
- expect(screen.queryByText("Scalar Title")).not.toBeInTheDocument();
- await userEvent.unhover(screen.getByTestId("scalar-container"));
-
- // hovering the rest of the card shows the title
- await userEvent.hover(screen.getByTestId("scalar-content"));
- expect(await screen.findByText("Scalar Title")).toBeInTheDocument();
- });
+ it.each([82, 126, 170, 214])(
+ "should keep the title visible on a short card of width %s (#84334)",
+ async (width) => {
+ render(
+ <Scalar
+ {...mockedProps}
+ showTitle
+ series={series(12345.6)}
+ rawSeries={series(12345.6)}
+ settings={settings}
+ visualizationIsClickable={() => false}
+ width={width}
+ height={82}
+ />,
+ );
+
+ expect(screen.getByTestId("scalar-title")).toHaveTextContent(
+ "Scalar Title",
+ );
+ await userEvent.hover(screen.getByTestId("scalar-content"));
+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
+ },
+ );
it("should navigate to the question when the title is clicked", async () => {
const onChangeCardAndRun = jest.fn();
@@ -193,44 +193,50 @@ describe("Scalar", () => {
expect(onChangeCardAndRun).not.toHaveBeenCalled();
});
- it("should show the description in a tooltip on the title info icon", async () => {
- render(
- <Scalar
- {...mockedProps}
- showTitle
- series={series(12345)}
- rawSeries={series(12345)}
- settings={{ ...settings, "card.description": "Scalar description" }}
- visualizationIsClickable={() => false}
- width={230}
- height={150}
- />,
- );
-
- await userEvent.hover(screen.getByLabelText("info icon"));
-
- expect(await screen.findByText("Scalar description")).toBeInTheDocument();
- });
-
- it("should open the description tooltip with keyboard navigation", async () => {
- render(
- <Scalar
- {...mockedProps}
- showTitle
- series={series(12345)}
- rawSeries={series(12345)}
- settings={{ ...settings, "card.description": "Scalar description" }}
- visualizationIsClickable={() => false}
- width={230}
- height={150}
- />,
- );
-
- // without a title link, the info icon is the first tabbable element
- await userEvent.tab();
-
- expect(await screen.findByText("Scalar description")).toBeInTheDocument();
- });
+ it.each([82, 126, 230])(
+ "should show the description on info icon hover at %i pixels wide",
+ async (width) => {
+ render(
+ <Scalar
+ {...mockedProps}
+ showTitle
+ series={series(12345)}
+ rawSeries={series(12345)}
+ settings={{ ...settings, "card.description": "Scalar description" }}
+ visualizationIsClickable={() => false}
+ width={width}
+ height={150}
+ />,
+ );
+
+ await userEvent.hover(screen.getByLabelText("info icon"));
+
+ expect(await screen.findByText("Scalar description")).toBeInTheDocument();
+ },
+ );
+
+ it.each([82, 126, 230])(
+ "should open the description tooltip with keyboard navigation at %i pixels wide",
+ async (width) => {
+ render(
+ <Scalar
+ {...mockedProps}
+ showTitle
+ series={series(12345)}
+ rawSeries={series(12345)}
+ settings={{ ...settings, "card.description": "Scalar description" }}
+ visualizationIsClickable={() => false}
+ width={width}
+ height={150}
+ />,
+ );
+
+ // without a title link, the info icon is the first tabbable element
+ await userEvent.tab();
+
+ expect(await screen.findByText("Scalar description")).toBeInTheDocument();
+ },
+ );
it("should not show the info icon while editing a dashboard", () => {
render(
diff --git a/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.stories.tsx b/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.stories.tsx
index e7d812a65dc..0b37855a53e 100644
--- a/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.stories.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.stories.tsx
@@ -28,10 +28,14 @@ const MOCK_SERIES = mockSeries({
rows: MOCK_ROWS,
insights: [{ unit: "month", col: "Count" }],
name: "Last invoice",
+ settings: { "card.description": "Total invoices" },
});
-// spec card sizes: size-200, size-300, and size-400 tiers
+// spec card sizes: size-100 through size-400 tiers
const CARD_SIZES = [
+ { width: 82, height: 82 },
+ { width: 126, height: 82 },
+ { width: 170, height: 82 },
{ width: 256, height: 126 },
{ width: 345, height: 170 },
{ width: 433, height: 214 },
@@ -39,7 +43,7 @@ const CARD_SIZES = [
export const Default: StoryFn = () => (
<VisualizationWrapper>
- <Flex gap="lg" align="flex-start" p="lg">
+ <Flex gap="lg" align="flex-start" wrap="wrap" p="lg">
{CARD_SIZES.map(({ width, height }) => (
<Box
key={`${width}x${height}`}
@@ -61,6 +65,7 @@ const MOCK_MULTI_COMPARISON_SERIES = mockSeries({
rows: MOCK_ROWS,
insights: [{ unit: "month", col: "Count" }],
name: "Last invoice",
+ settings: { "card.description": "Total invoices" },
comparisonTypes: [
{ id: "1", type: "previousPeriod" },
{ id: "2", type: "periodsAgo", value: 2 },
@@ -72,7 +77,7 @@ const MOCK_MULTI_COMPARISON_SERIES = mockSeries({
// comparisons live in the hover panel
export const DashcardMultipleComparisons: StoryFn = () => (
<VisualizationWrapper>
- <Flex gap="lg" align="flex-start" p="lg">
+ <Flex gap="lg" align="flex-start" wrap="wrap" p="lg">
{CARD_SIZES.map(({ width, height }) => (
<Box
key={`${width}x${height}`}
diff --git a/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.tsx b/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.tsx
index 8bef71f39d0..34ad528307d 100644
--- a/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/SmartScalar/SmartScalar.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef } from "react";
import DashboardS from "metabase/css/dashboard.module.css";
-import { Box, Stack, Text, rem } from "metabase/ui";
+import { Box, Stack, Text } from "metabase/ui";
import { assignLazily } from "metabase/utils/merge-lazily";
import {
ScalarCardShell,
@@ -20,9 +20,9 @@ import type {
import { ScalarValueContainer } from "../Scalar/ScalarValueContainer";
+import { TrendCardComparison } from "./TrendCardComparison";
import { TrendComparisonList } from "./TrendComparisonList";
import { TrendComparisonRow } from "./TrendComparisonRow";
-import { TrendComparisonStack } from "./TrendComparisonStack";
import { TrendSymbol } from "./TrendSymbol";
import { computeTrend, getComparisonDisplay } from "./compute";
import { SMART_SCALAR_CHART_DEFINITION } from "./definition";
@@ -46,15 +46,6 @@ function SmartScalarComponent(
} = props;
const scalarRef = useRef(null);
- const {
- tier,
- rootFontScale,
- availableWidth,
- title,
- titleElement,
- showsTitleTooltip,
- innerTooltipHoverHandlers,
- } = useScalarCardShell(props);
const { getColor } = useBrowserRenderingContext({ fontFamily });
const insights = rawSeries?.[0].data?.insights;
@@ -69,6 +60,12 @@ function SmartScalarComponent(
}
}, [error, onRenderError]);
+ const { tier, rootFontScale, availableWidth, titleElement, description } =
+ useScalarCardShell(props, {
+ shouldHideDescription: (tier) =>
+ tier.size === 150 && (trend?.comparisons.length ?? 0) > 1,
+ });
+
if (trend == null) {
return null;
}
@@ -93,7 +90,7 @@ function SmartScalarComponent(
}
};
- const isSmallestTier = !tier.showsTitle;
+ const isCompact = tier.size < 200;
const listsAllComparisons =
comparisons.length > 1 &&
tier.multiComparisonMinHeight != null &&
@@ -101,7 +98,7 @@ function SmartScalarComponent(
const primaryComparison = comparisons[0];
const symbolDirection =
- isSmallestTier || primaryComparison == null
+ isCompact || primaryComparison == null
? null
: getComparisonDisplay(primaryComparison, formatOptions).symbolDirection;
@@ -121,8 +118,6 @@ function SmartScalarComponent(
formatOptions,
);
- const hasValueTooltip = fullScalarValue !== displayValue;
-
const valueElement = (
<ScalarValueContainer
className={DashboardS.fullscreenNormalText}
@@ -204,44 +199,23 @@ function SmartScalarComponent(
}
return (
- <ScalarCardShell
- tier={tier}
- title={title}
- showsTitleTooltip={showsTitleTooltip}
- actionButtons={actionButtons}
- innerTooltipHoverHandlers={innerTooltipHoverHandlers}
- >
+ <ScalarCardShell tier={tier} actionButtons={actionButtons}>
<Box
pos="relative"
// measured pixels, not a design size — must not be rem-scaled
maw={`${valueMaxWidth}px`}
- {...(hasValueTooltip ? innerTooltipHoverHandlers : {})}
>
{valueElement}
{symbolElement}
</Box>
- {titleElement}
- {comparisons.length > 0 && (
- <Box
- pos="absolute"
- top={`calc(100% + ${rem(tier.comparisonGap)})`}
- left="50%"
- // measured pixels, not a design size — must not be rem-scaled
- w={`${availableWidth}px`}
- style={{ transform: "translateX(-50%)" }}
- {...innerTooltipHoverHandlers}
- >
- {listsAllComparisons ? (
- <TrendComparisonStack trend={trend} formatOptions={formatOptions} />
- ) : (
- <TrendComparisonRow
- trend={trend}
- formatOptions={formatOptions}
- percentOnly={isSmallestTier}
- />
- )}
- </Box>
- )}
+ <TrendCardComparison
+ tier={tier}
+ title={titleElement}
+ description={description}
+ trend={trend}
+ availableWidth={availableWidth}
+ listsAllComparisons={listsAllComparisons}
+ />
</ScalarCardShell>
);
}
diff --git a/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendCardComparison.tsx b/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendCardComparison.tsx
new file mode 100644
index 00000000000..df919abb83e
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendCardComparison.tsx
@@ -0,0 +1,90 @@
+import type { ReactNode } from "react";
+
+import { Box, Stack, rem } from "metabase/ui";
+import { ScalarLabel } from "metabase/visualizations/components/ScalarValue/ScalarLabel";
+import type { ScalarSizeTier } from "metabase/visualizations/components/ScalarValue/sizing";
+
+import { TrendComparisonRow } from "./TrendComparisonRow";
+import { TrendComparisonStack } from "./TrendComparisonStack";
+import type { Trend } from "./compute";
+
+interface TrendCardComparisonProps {
+ tier: ScalarSizeTier;
+ title: ReactNode;
+ description?: string | null;
+ trend: Trend;
+ availableWidth: number;
+ listsAllComparisons: boolean;
+}
+
+export function TrendCardComparison({
+ tier,
+ title,
+ description,
+ trend,
+ availableWidth,
+ listsAllComparisons,
+}: TrendCardComparisonProps) {
+ const titleWithDescription = title ? (
+ <ScalarLabel description={description}>{title}</ScalarLabel>
+ ) : null;
+
+ if (trend.comparisons.length === 0) {
+ return titleWithDescription;
+ }
+
+ if (tier.size === 100) {
+ return (
+ <Stack align="center" gap="xxs" w="100%">
+ {titleWithDescription}
+ <TrendComparisonRow
+ trend={trend}
+ formatOptions={trend.formatOptions}
+ percentOnly
+ showComparisonCount={false}
+ />
+ </Stack>
+ );
+ }
+
+ if (tier.size === 150) {
+ return (
+ <ScalarLabel description={description}>
+ {title}
+ <Box flex="0 0 auto">
+ <TrendComparisonRow
+ trend={trend}
+ formatOptions={trend.formatOptions}
+ percentOnly
+ />
+ </Box>
+ </ScalarLabel>
+ );
+ }
+
+ return (
+ <>
+ {titleWithDescription}
+ <Box
+ pos="absolute"
+ top={`calc(100% + ${rem(tier.comparisonGap)})`}
+ left="50%"
+ // Measured pixels must not be rem-scaled.
+ w={`${availableWidth}px`}
+ style={{ transform: "translateX(-50%)" }}
+ >
+ {listsAllComparisons ? (
+ <TrendComparisonStack
+ trend={trend}
+ formatOptions={trend.formatOptions}
+ />
+ ) : (
+ <TrendComparisonRow
+ trend={trend}
+ formatOptions={trend.formatOptions}
+ />
+ )}
+ </Box>
+ </>
+ );
+}
diff --git a/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendComparisonRow.tsx b/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendComparisonRow.tsx
index ee1516e506e..5bbff67b74d 100644
--- a/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendComparisonRow.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/SmartScalar/TrendComparisonRow.tsx
@@ -19,6 +19,7 @@ interface TrendComparisonRowProps {
trend: Trend;
formatOptions: ColumnSettings;
percentOnly?: boolean;
+ showComparisonCount?: boolean;
size?: TrendComparisonTextSize;
compactValue?: boolean;
}
@@ -27,6 +28,7 @@ export function TrendComparisonRow({
trend,
formatOptions,
percentOnly = false,
+ showComparisonCount = true,
size = "sm",
compactValue = true,
}: TrendComparisonRowProps) {
@@ -75,7 +77,7 @@ export function TrendComparisonRow({
compactValue={compactValue}
/>
</Box>
- {!percentOnly && extraComparisonsCount > 0 && (
+ {showComparisonCount && extraComparisonsCount > 0 && (
<Badge
px={6}
size="xs"
diff --git a/frontend/src/metabase/visualizations/visualizations/SmartScalar/tests/SmartScalar.unit.spec.tsx b/frontend/src/metabase/visualizations/visualizations/SmartScalar/tests/SmartScalar.unit.spec.tsx
index daed89f6222..07d5efe7afc 100644
--- a/frontend/src/metabase/visualizations/visualizations/SmartScalar/tests/SmartScalar.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/SmartScalar/tests/SmartScalar.unit.spec.tsx
@@ -4,6 +4,7 @@ import {
mockTextOverflow,
renderWithProviders,
screen,
+ waitFor,
within,
} from "__support__/ui";
import { NumberColumn } from "__support__/visualizations";
@@ -49,6 +50,35 @@ const setup = ({ series, width = 800, height }: SetupOpts) =>
/>,
);
+interface CompactTrendSetupOpts {
+ comparisonCount: number;
+}
+
+function setupCompactTrend({ comparisonCount }: CompactTrendSetupOpts) {
+ const comparisonTypes = [
+ { id: "1", type: "previousPeriod" as const },
+ { id: "2", type: "previousValue" as const },
+ { id: "3", type: "staticNumber" as const, value: 80, label: "Goal" },
+ ].slice(0, comparisonCount);
+ renderWithProviders(
+ <Visualization
+ rawSeries={series({
+ rows: [
+ ["2019-10-01T00:00:00", 100],
+ ["2019-11-01T00:00:00", 120],
+ ],
+ insights: createMockInsights([{ unit: "month", col: "Count" }]),
+ name: "Revenue",
+ comparisonTypes,
+ settings: { "card.description": "Monthly revenue" },
+ })}
+ width={170}
+ height={82}
+ showTitle
+ />,
+ );
+}
+
const getTrendSymbol = () => screen.getByTestId("trend-symbol");
describe("SmartScalar", () => {
@@ -532,36 +562,66 @@ describe("SmartScalar", () => {
expect(screen.queryByTestId("trend-symbol")).not.toBeInTheDocument();
});
- it("should show one tooltip at a time on the smallest cards", async () => {
- const rows = [
- ["2019-10-01T00:00:00", 50],
- ["2019-11-01T00:00:00", 100],
- ];
- const insights = createMockInsights([{ unit: "month", col: "Count" }]);
+ it.each([82, 126, 170, 214])(
+ "should keep the title visible alongside the compact comparison at width %s (#84334)",
+ async (width) => {
+ const rows = [
+ ["2019-10-01T00:00:00", 50],
+ ["2019-11-01T00:00:00", 100],
+ ];
+ const insights = createMockInsights([{ unit: "month", col: "Count" }]);
- // narrow width forces the smallest tier, where the title only shows on hover
- renderWithProviders(
- <Visualization
- rawSeries={series({ rows, insights, name: "Last invoice" })}
- width={100}
- showTitle
- />,
+ renderWithProviders(
+ <Visualization
+ rawSeries={series({ rows, insights, name: "Last invoice" })}
+ width={width}
+ height={82}
+ showTitle
+ />,
+ );
+
+ expect(screen.getByTestId("scalar-title")).toHaveTextContent(
+ "Last invoice",
+ );
+ expect(screen.getByText("+100%")).toBeVisible();
+ expect(screen.queryByTestId("trend-symbol")).not.toBeInTheDocument();
+ await userEvent.hover(screen.getByTestId("scalar-previous-value"));
+ const tooltip = await screen.findByRole("tooltip");
+ expect(
+ within(tooltip).getByText("vs. previous month"),
+ ).toBeInTheDocument();
+ expect(
+ within(tooltip).queryByText("Last invoice"),
+ ).not.toBeInTheDocument();
+ await userEvent.unhover(screen.getByTestId("scalar-previous-value"));
+ },
+ );
+
+ it("should show the description for a single compact comparison", async () => {
+ setupCompactTrend({ comparisonCount: 1 });
+ await userEvent.hover(screen.getByLabelText("info icon"));
+ await waitFor(() =>
+ expect(screen.getByText("Monthly revenue")).toBeVisible(),
);
-
- // hovering the comparison shows its tooltip, not the title
- await userEvent.hover(screen.getByTestId("scalar-previous-value"));
- const tooltip = await screen.findByRole("tooltip");
- expect(
- within(tooltip).getByText("vs. previous month"),
- ).toBeInTheDocument();
- expect(screen.queryByText("Last invoice")).not.toBeInTheDocument();
- await userEvent.unhover(screen.getByTestId("scalar-previous-value"));
-
- // hovering the rest of the card shows the title
- await userEvent.hover(screen.getByTestId("scalar-content"));
- expect(await screen.findByText("Last invoice")).toBeInTheDocument();
});
+ it.each([2, 3])(
+ "should show %s compact comparisons and hide the info icon",
+ async (count) => {
+ setupCompactTrend({ comparisonCount: count });
+ expect(screen.getByText("Revenue")).toBeVisible();
+ expect(screen.getByText("+20%")).toBeVisible();
+ expect(screen.queryByLabelText("info icon")).not.toBeInTheDocument();
+ expect(screen.getByText(`+${count - 1}`)).toBeVisible();
+ await userEvent.hover(screen.getByTestId("scalar-previous-value"));
+ const tooltip = await screen.findByRole("tooltip");
+ await waitFor(() =>
+ expect(within(tooltip).getByText("vs. previous month")).toBeVisible(),
+ );
+ expect(within(tooltip).getByText("vs. Oct")).toBeVisible();
+ },
+ );
+
it("should not show a hover panel for a single fully-displayed comparison", async () => {
const rows = [
["2019-10-01T00:00:00", 50],