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
UXW-4658 Fix viz settings dropdown broken styles (#76845)
Denis Berezindc91702b6bf4
diff --git a/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.tsx b/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.tsxindex c30de7f2988..e55ca42acb8 100644--- a/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import _ from "underscore";import CS from "metabase/css/core/index.css";@@ -9,6 +9,7 @@ import { PopoverWithRef } from "metabase/ui/components/overlays/Popover/PopoverWimport type { Widget } from "../types";import ChartSettingsWidget from "./ChartSettingsWidget";+import { WidgetPopoverPortalContext } from "./settings/WidgetPopoverPortalContext";interface ChartSettingsWidgetPopoverProps {anchor: HTMLElement;@@ -22,7 +23,26 @@ export const ChartSettingsWidgetPopover = ({widgets,}: ChartSettingsWidgetPopoverProps) => {const sections = useRef<(string | undefined)[]>([]);- const contentRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLDivElement | null>(null);+ const [dropdownTarget, setDropdownTarget] = useState<HTMLDivElement | null>(+ null,+ );+ const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(+ null,+ );++ const setContentRef = useCallback((node: HTMLDivElement | null) => {+ contentRef.current = node;+ setScrollContainer(node);+ }, []);++ const portalValue = useMemo(+ () =>+ dropdownTarget && scrollContainer+ ? { dropdownTarget, scrollContainer }+ : null,+ [dropdownTarget, scrollContainer],+ );useEffect(() => {sections.current = _.chain(widgets).pluck("section").unique().value();@@ -56,40 +76,54 @@ export const ChartSettingsWidgetPopover = ({flip: { fallbackStrategy: "initialPlacement" },size: { padding: 5 },}}+ styles={{ dropdown: { overflow: "visible" } }}{...(isEmbeddingSdk() && {withinPortal: false,floatingStrategy: "fixed",})}>- <Box- pt={hasMultipleSections ? 0 : undefined}- ref={contentRef}- mah="40rem"- miw="336px"- className={CS.overflowYAuto}- >- {hasMultipleSections && (- <Tabs- px="md"- pt="xs"- value={currentSection}- onChange={(section) => setCurrentSection(String(section))}+ <Box ref={setDropdownTarget}>+ <WidgetPopoverPortalContext.Provider value={portalValue}>+ <Box+ pt={hasMultipleSections ? 0 : undefined}+ ref={setContentRef}+ data-testid="chart-settings-widget-popover-content"+ mah="40rem"+ miw="336px"+ className={CS.overflowYAuto}>- <Tabs.List grow>- {sections.current.map((sectionName) => (- <Tabs.Tab key={sectionName} value={String(sectionName)} p="md">- {sectionName}- </Tabs.Tab>+ {hasMultipleSections && (+ <Tabs+ px="md"+ pt="xs"+ value={currentSection}+ onChange={(section) => setCurrentSection(String(section))}+ >+ <Tabs.List grow>+ {sections.current.map((sectionName) => (+ <Tabs.Tab+ key={sectionName}+ value={String(sectionName)}+ p="md"+ >+ {sectionName}+ </Tabs.Tab>+ ))}+ </Tabs.List>+ </Tabs>+ )}+ <Space py="sm"></Space>+ {widgets+ .filter((widget) => widget.section === currentSection)+ ?.map((widget) => (+ <ChartSettingsWidget+ key={widget.id}+ {...widget}+ hidden={false}+ />))}- </Tabs.List>- </Tabs>- )}- <Space py="sm"></Space>- {widgets- .filter((widget) => widget.section === currentSection)- ?.map((widget) => (- <ChartSettingsWidget key={widget.id} {...widget} hidden={false} />- ))}+ </Box>+ </WidgetPopoverPortalContext.Provider></Box></PopoverWithRef>);diff --git a/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.unit.spec.tsxindex e7dd7ccadc5..7c77f179734 100644--- a/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettingsWidgetPopover.unit.spec.tsx@@ -1,11 +1,19 @@import userEvent from "@testing-library/user-event";import { type ComponentProps, useState } from "react";-import { renderWithProviders, screen } from "__support__/ui";+import {+ fireEvent,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";import { ChartSettingsWidgetPopover } from "metabase/visualizations/components/ChartSettingsWidgetPopover";import type { Widget } from "../types";+import { ChartSettingSelect } from "./settings/ChartSettingSelect";+type PopoverProps = ComponentProps<typeof ChartSettingsWidgetPopover>;const DEFAULT_PROPS: Pick<PopoverProps, "handleEndShowWidget"> = {@@ -94,3 +102,77 @@ it("should change tabs when clicked", async () => {expect(await screen.findByText("Bar")).toBeInTheDocument();});++describe("Select widgets", () => {+ const onChange = jest.fn();++ const SELECT_WIDGET: Widget = {+ id: "column_settings",+ section: "Formatting",+ widget: () => (+ <ChartSettingSelect+ options={[+ { name: "Option 1", value: "value1" },+ { name: "Option 2", value: "value2" },+ ]}+ value="value1"+ onChange={onChange}+ />+ ),+ props: {},+ };++ beforeEach(() => {+ onChange.mockClear();+ });++ it("should render the dropdown outside of the popover's scroll container", async () => {+ setup({ widgets: [SELECT_WIDGET] });++ await userEvent.click(await screen.findByTestId("chart-setting-select"));++ const scrollContainer = screen.getByTestId(+ "chart-settings-widget-popover-content",+ );+ const option = await screen.findByText("Option 2");++ expect(scrollContainer).not.toContainElement(option);+ });++ it("should keep the popover open when an option is selected", async () => {+ setup({ widgets: [SELECT_WIDGET] });++ await userEvent.click(await screen.findByTestId("chart-setting-select"));+ await userEvent.click(await screen.findByText("Option 2"));++ expect(onChange).toHaveBeenCalledWith("value2");+ // The popover content (and its select) remains mounted.+ expect(+ within(+ screen.getByTestId("chart-settings-widget-popover-content"),+ ).getByTestId("chart-setting-select"),+ ).toBeInTheDocument();+ });++ it("should close the dropdown when the popover scrolls", async () => {+ // The dropdown floats past the popover, so it must not linger detached when+ // the popover scrolls.++ setup({ widgets: [SELECT_WIDGET] });++ await userEvent.click(await screen.findByTestId("chart-setting-select"));+ expect(await screen.findByText("Option 2")).toBeInTheDocument();++ fireEvent.scroll(+ screen.getByTestId("chart-settings-widget-popover-content"),+ );++ await waitFor(() =>+ expect(screen.queryByText("Option 2")).not.toBeInTheDocument(),+ );+ // The popover itself stays open.+ expect(+ screen.getByTestId("chart-settings-widget-popover-content"),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx b/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsxindex d1fa5ca5540..069cf5e8dfb 100644--- a/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx+++ b/frontend/src/metabase/visualizations/components/settings/ChartSettingSelect.tsx@@ -1,5 +1,5 @@import cx from "classnames";-import type { ReactNode } from "react";+import { type ReactNode, useContext, useEffect, useState } from "react";import CS from "metabase/css/core/index.css";import { Select, type SelectProps, Stack } from "metabase/ui";@@ -9,6 +9,7 @@ import {} from "metabase/visualizations/lib/settings/widgets";import S from "./ChartSettingSelect.module.css";+import { WidgetPopoverPortalContext } from "./WidgetPopoverPortalContext";export type ChartSettingSelectValue = string | number | boolean | null;@@ -67,6 +68,28 @@ export const ChartSettingSelect = ({variant,w,}: ChartSettingSelectProps) => {+ const popoverPortal = useContext(WidgetPopoverPortalContext);+ const comboboxProps: SelectProps["comboboxProps"] = popoverPortal+ ? {+ keepMounted: false,+ withinPortal: true,+ portalProps: { target: popoverPortal.dropdownTarget },+ }+ : { withinPortal: false, floatingStrategy: "absolute" };++ const [dropdownOpened, setDropdownOpened] = useState(+ Boolean(defaultDropdownOpened),+ );+ const scrollContainer = popoverPortal?.scrollContainer;+ useEffect(() => {+ if (!scrollContainer || !dropdownOpened) {+ return;+ }+ const close = () => setDropdownOpened(false);+ scrollContainer.addEventListener("scroll", close, { passive: true });+ return () => scrollContainer.removeEventListener("scroll", close);+ }, [scrollContainer, dropdownOpened]);+const disabled =options.length === 0 ||(options.length === 1 && options[0].value === value);@@ -114,10 +137,7 @@ export const ChartSettingSelect = ({}}placeholder={options.length === 0 ? placeholderNoOptions : placeholder}searchable={!!searchProp}- comboboxProps={{- withinPortal: false,- floatingStrategy: "absolute",- }}+ comboboxProps={comboboxProps}leftSection={resolvedLeftSection}leftSectionWidth={icon != null ? iconWidth : undefined}rightSection={rightSection}@@ -129,7 +149,12 @@ export const ChartSettingSelect = ({? { "--chart-setting-select-input-padding-right": inputPaddingRight }: undefined}- defaultDropdownOpened={defaultDropdownOpened}+ defaultDropdownOpened={popoverPortal ? undefined : defaultDropdownOpened}+ dropdownOpened={popoverPortal ? dropdownOpened : undefined}+ onDropdownOpen={popoverPortal ? () => setDropdownOpened(true) : undefined}+ onDropdownClose={+ popoverPortal ? () => setDropdownOpened(false) : undefined+ }pl={pl}pr={pr}variant={variant}diff --git a/frontend/src/metabase/visualizations/components/settings/WidgetPopoverPortalContext.tsx b/frontend/src/metabase/visualizations/components/settings/WidgetPopoverPortalContext.tsxnew file mode 100644index 00000000000..5d0c2de201e--- /dev/null+++ b/frontend/src/metabase/visualizations/components/settings/WidgetPopoverPortalContext.tsx@@ -0,0 +1,9 @@+import { createContext } from "react";++export type WidgetPopoverPortal = {+ dropdownTarget: HTMLElement;+ scrollContainer: HTMLElement;+};++export const WidgetPopoverPortalContext =+ createContext<WidgetPopoverPortal | null>(null);