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(sdk): Fix the empty container detection in SDK question layouts (#70389)
Timofey Kachalov8056c1835a0d
diff --git a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsxindex 34a9e93525b..456ecc88c0c 100644--- a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx@@ -1,11 +1,22 @@const { H } = cy;+import {+ MetabaseProvider,+ StaticQuestion,+ type StaticQuestionProps,+} from "@metabase/embedding-sdk-react";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";import { createQuestion, modal, popover } from "e2e/support/helpers";import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";-import { mountStaticQuestion } from "e2e/support/helpers/embedding-sdk-component-testing";+import {+ DEFAULT_SDK_AUTH_PROVIDER_CONFIG,+ mountSdk,+ mountStaticQuestion,+} from "e2e/support/helpers/embedding-sdk-component-testing";import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";+import { ThemeProvider } from "metabase/ui";const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;@@ -43,6 +54,76 @@ describe("scenarios > embedding-sdk > static-question", () => {});});+ it("should not render the top bar when it has no visible children, and restore it when children appear", () => {+ cy.intercept("GET", "/api/card/*").as("getCard");+ cy.intercept("POST", "/api/card/*/query").as("cardQuery");+ cy.intercept("GET", "/api/user/current").as("getUser");++ cy.get<number>("@questionId").then((questionId) => {+ const consoleErrorSpy = cy.spy(console, "error").as("consoleError");++ const renderQuestion = (props: Partial<StaticQuestionProps>) => (+ <ThemeProvider>+ <MetabaseProvider authConfig={DEFAULT_SDK_AUTH_PROVIDER_CONFIG}>+ <StaticQuestion questionId={questionId} {...props} />+ </MetabaseProvider>+ </ThemeProvider>+ );++ mountSdk(+ renderQuestion({ title: false, withChartTypeSelector: false }),+ ).then(({ rerender }) => {+ cy.wait("@getUser");+ cy.wait("@getCard");++ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ cy.findByTestId("static-question-top-bar").should("not.exist");+ });++ rerender(renderQuestion({ title: true, withChartTypeSelector: false }));++ getSdkRoot().within(() => {+ cy.findByTestId("static-question-top-bar")+ .should("exist")+ .and("be.visible");+ });++ rerender(+ renderQuestion({ title: false, withChartTypeSelector: false }),+ );++ getSdkRoot().within(() => {+ cy.findByTestId("static-question-top-bar").should("not.exist");+ });++ rerender(renderQuestion({ title: false, withDownloads: true }));++ getSdkRoot().within(() => {+ cy.findByTestId("static-question-top-bar")+ .should("exist")+ .and("be.visible");+ });++ rerender(renderQuestion({ title: false, withDownloads: false }));++ getSdkRoot().within(() => {+ cy.findByTestId("static-question-top-bar").should("not.exist");+ });++ cy.then(() => {+ const refWarningCalls = consoleErrorSpy+ .getCalls()+ .filter((call: sinon.SinonSpyCall) =>+ String(call.args[0]).includes("cannot be given refs"),+ );++ expect(refWarningCalls).to.have.length(0);+ });+ });+ });+ });+it("should show question title", () => {mountStaticQuestion({ title: true });diff --git a/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.tsx b/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.tsxnew file mode 100644index 00000000000..e916450b276--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.tsx@@ -0,0 +1,94 @@+import {+ type ComponentPropsWithoutRef,+ type ElementType,+ type PropsWithChildren,+ createElement,+ useCallback,+ useRef,+ useState,+} from "react";++type RenderIfHasContentProps<C extends ElementType> = PropsWithChildren<+ { component: C } & Omit<ComponentPropsWithoutRef<C>, "component" | "children">+>;++/**+ * Renders children inside the given `component` when they have visible content.+ * When children are empty, renders a hidden sentinel `<div>` to keep observing+ * for content changes, while removing the styled wrapper from the DOM entirely.+ *+ * This is useful with CSS `:has()` selectors that rely on the wrapper's class+ * being absent when content is empty (e.g., grid layout adjustments).+ */+export function RenderIfHasContent<C extends ElementType>({+ component: Component,+ children,+ ...props+}: RenderIfHasContentProps<C>) {+ const [shouldRender, setShouldRender] = useState(true);+ const observerRef = useRef<MutationObserver | null>(null);++ const refCallback = useCallback((node: HTMLElement | null) => {+ observerRef.current?.disconnect();+ observerRef.current = null;++ if (!node) {+ return;+ }++ const update = () => setShouldRender(hasVisibleContent(node));+ update();++ const observer = new MutationObserver(update);+ observer.observe(node, {+ childList: true,+ subtree: true,+ characterData: true,+ });+ observerRef.current = observer;+ }, []);++ if (!shouldRender) {+ return (+ <div ref={refCallback} hidden>+ {children}+ </div>+ );+ }++ return createElement(Component, { ...props, ref: refCallback }, children);+}++/**+ * Elements that are visually meaningful even without text content.+ */+const REPLACED_ELEMENTS = new Set([+ "IMG",+ "SVG",+ "INPUT",+ "TEXTAREA",+ "SELECT",+]);++function hasVisibleContent(element: HTMLElement): boolean {+ if (REPLACED_ELEMENTS.has(element.tagName.toUpperCase())) {+ return true;+ }++ const children = Array.from(element.children);++ // Leaf node: check for direct text content+ if (children.length === 0) {+ return !!element.textContent?.trim();+ }++ return children.some((child) => {+ const el = child as HTMLElement;++ if (el.hidden || el.style?.display === "none") {+ return false;+ }++ return hasVisibleContent(el);+ });+}diff --git a/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.unit.spec.tsxnew file mode 100644index 00000000000..3acb656dbec--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent.unit.spec.tsx@@ -0,0 +1,175 @@+import { useState } from "react";++import { act, render, screen } from "__support__/ui";++import { RenderIfHasContent } from "./RenderIfHasContent";++describe("RenderIfHasContent", () => {+ it("should render the component when children have text content", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <span>Hello</span>+ </RenderIfHasContent>,+ );++ expect(screen.getByTestId("wrapper")).toBeInTheDocument();+ expect(screen.getByTestId("wrapper").tagName).toBe("SECTION");+ expect(screen.getByText("Hello")).toBeVisible();+ });++ it("should not render the component when children are empty", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <div />+ </RenderIfHasContent>,+ );++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();+ });++ it("should not render the component when children only contain empty wrappers", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <div>+ <div>+ <span />+ </div>+ </div>+ </RenderIfHasContent>,+ );++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();+ });++ it("should render the component when children contain an SVG", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <button>+ <svg>+ <path d="M0 0" />+ </svg>+ </button>+ </RenderIfHasContent>,+ );++ expect(screen.getByTestId("wrapper")).toBeInTheDocument();+ });++ it("should skip hidden children when checking for content", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <div hidden>+ <span>Hidden text</span>+ </div>+ </RenderIfHasContent>,+ );++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();+ });++ it("should skip display:none children when checking for content", () => {+ render(+ <RenderIfHasContent component="section" data-testid="wrapper">+ <div style={{ display: "none" }}>+ <span>Hidden text</span>+ </div>+ </RenderIfHasContent>,+ );++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();+ });++ it("should pass props to the rendered component", () => {+ render(+ <RenderIfHasContent+ component="section"+ data-testid="wrapper"+ className="my-class"+ aria-label="test"+ >+ <span>Content</span>+ </RenderIfHasContent>,+ );++ const wrapper = screen.getByTestId("wrapper");+ expect(wrapper).toHaveClass("my-class");+ expect(wrapper).toHaveAttribute("aria-label", "test");+ });++ it("should show the component when content appears dynamically", async () => {+ const Toggle = () => {+ const [show, setShow] = useState(false);+ return (+ <>+ <button onClick={() => setShow(true)}>Show</button>+ <RenderIfHasContent component="section" data-testid="wrapper">+ {show && <span>Dynamic content</span>}+ </RenderIfHasContent>+ </>+ );+ };++ render(<Toggle />);++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();++ await act(async () => {+ screen.getByText("Show").click();+ });++ expect(await screen.findByTestId("wrapper")).toBeInTheDocument();+ expect(screen.getByText("Dynamic content")).toBeVisible();+ });++ it("should hide the component when content is removed dynamically", async () => {+ const Toggle = () => {+ const [show, setShow] = useState(true);+ return (+ <>+ <button onClick={() => setShow(false)}>Hide</button>+ <RenderIfHasContent component="section" data-testid="wrapper">+ {show && <span>Content</span>}+ </RenderIfHasContent>+ </>+ );+ };++ render(<Toggle />);++ expect(screen.getByTestId("wrapper")).toBeInTheDocument();+ expect(screen.getByText("Content")).toBeVisible();++ await act(async () => {+ screen.getByText("Hide").click();+ });++ expect(screen.queryByTestId("wrapper")).not.toBeInTheDocument();+ });++ it("should render nested RenderIfHasContent components when content is present", () => {+ render(+ <RenderIfHasContent component="section" data-testid="outer">+ <RenderIfHasContent component="div" data-testid="inner">+ <span>Nested content</span>+ </RenderIfHasContent>+ </RenderIfHasContent>,+ );++ expect(screen.getByTestId("outer")).toBeInTheDocument();+ expect(screen.getByTestId("inner")).toBeInTheDocument();+ expect(screen.getByText("Nested content")).toBeVisible();+ });++ it("should hide nested RenderIfHasContent components when content is empty", () => {+ render(+ <RenderIfHasContent component="section" data-testid="outer">+ <RenderIfHasContent component="div" data-testid="inner">+ <div />+ </RenderIfHasContent>+ </RenderIfHasContent>,+ );++ expect(screen.queryByTestId("outer")).not.toBeInTheDocument();+ expect(screen.queryByTestId("inner")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsxindex ce7db78d870..996c76a5094 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/ResultToolbar/ResultToolbar.tsx@@ -1,4 +1,4 @@-import type { HTMLAttributes, PropsWithChildren } from "react";+import { type HTMLAttributes, type PropsWithChildren, forwardRef } from "react";import { Group } from "metabase/ui";@@ -6,20 +6,25 @@ type Props = HTMLAttributes<HTMLDivElement> & {"data-testid"?: string;};-export const ResultToolbar = ({- children,- "data-testid": dataTestId,- ...divProps-}: PropsWithChildren<Props>) => (- <Group- p="sm"- style={{- borderRadius: "0.5rem",- backgroundColor: "var(--mb-color-bg-sdk-question-toolbar)",- }}- data-testid={dataTestId}- {...divProps}- >- {children}- </Group>-);+export const ResultToolbar = forwardRef<+ HTMLDivElement,+ PropsWithChildren<Props>+>(function ResultToolbar(+ { children, "data-testid": dataTestId, ...divProps },+ ref,+) {+ return (+ <Group+ ref={ref}+ p="sm"+ style={{+ borderRadius: "0.5rem",+ backgroundColor: "var(--mb-color-bg-sdk-question-toolbar)",+ }}+ data-testid={dataTestId}+ {...divProps}+ >+ {children}+ </Group>+ );+});diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsxindex 386bf561829..2314b085994 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx@@ -1,7 +1,7 @@import { useDisclosure } from "@mantine/hooks";import cx from "classnames";import type { ReactElement } from "react";-import { useEffect, useMemo, useRef } from "react";+import { useEffect, useMemo } from "react";import { t } from "ttag";import {@@ -13,7 +13,6 @@ import { QuestionVisualization } from "embedding-sdk-bundle/components/private/Simport { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion";import { QuestionAlertsButton } from "embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton";import { useCollectionData } from "embedding-sdk-bundle/hooks/private/use-collection-data";-import { useHideEmptyElement } from "embedding-sdk-bundle/hooks/private/use-hide-empty-element";import { useQuestionEditorSync } from "embedding-sdk-bundle/hooks/private/use-question-editor-sync";import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";import { shouldRunCardQuery } from "embedding-sdk-bundle/lib/sdk-question";@@ -36,6 +35,7 @@ import {FlexibleSizeComponent,type FlexibleSizeProps,} from "../FlexibleSizeComponent";+import { RenderIfHasContent } from "../RenderIfHasContent/RenderIfHasContent";import { SdkInternalNavigationBackButton } from "../SdkInternalNavigation/SdkInternalNavigationBackButton";import { BreakoutDropdown } from "../SdkQuestion/components/Breakout/BreakoutDropdown";import { ChartTypeDropdown } from "../SdkQuestion/components/ChartTypeDropdown";@@ -159,9 +159,6 @@ export const SdkQuestionDefaultView = ({{ skipCollectionFetching: !isSaveEnabled },);- const hideEmptyParentRef = useRef<HTMLDivElement>(null);- useHideEmptyElement("[data-hide-empty]", hideEmptyParentRef);-if (!isEditorOpen &&(isLocaleLoading || isQuestionLoading || isQueryResultLoading)@@ -191,33 +188,32 @@ export const SdkQuestionDefaultView = ({className={cx(InteractiveQuestionS.Container, className)}style={style}>- <Stack- ref={hideEmptyParentRef}+ <RenderIfHasContent+ component={Stack}className={InteractiveQuestionS.TopBar}gap="sm"p="md"- data-hide-empty>- <Group+ <RenderIfHasContent+ component={Group}justify="space-between"align="flex-end"data-testid="interactive-question-top-toolbar"- data-hide-empty>- <Group gap="xs" data-hide-empty>+ <RenderIfHasContent component={Group} gap="xs"><Stack align="flex-start"><SdkInternalNavigationBackButton /><DefaultViewTitle title={title} /></Stack>- </Group>+ </RenderIfHasContent>{showSaveButton && <SaveButton onClick={openSaveModal} />}- </Group>+ </RenderIfHasContent>{queryResults && (- <ResultToolbar+ <RenderIfHasContent+ component={ResultToolbar}data-testid="interactive-question-result-toolbar"- data-hide-empty>- <Group gap="xs" data-hide-empty>+ <RenderIfHasContent component={Group} gap="xs">{isEditorOpen ? (<PopoverBackButtononClick={toggleEditor}@@ -257,8 +253,8 @@ export const SdkQuestionDefaultView = ({)}</>)}- </Group>- <Group gap="sm" ml="auto" data-hide-empty>+ </RenderIfHasContent>+ <RenderIfHasContent component={Group} gap="sm" ml="auto">{!isEditorOpen && (<><DownloadWidgetDropdown />@@ -266,8 +262,8 @@ export const SdkQuestionDefaultView = ({</>)}<EditorButton isOpen={isEditorOpen} onClick={toggleEditor} />- </Group>- </ResultToolbar>+ </RenderIfHasContent>+ </RenderIfHasContent>)}{isGuestEmbed && (@@ -275,7 +271,7 @@ export const SdkQuestionDefaultView = ({<SdkQuestion.SqlParametersList /></Box>)}- </Stack>+ </RenderIfHasContent><BoxclassName={cx(InteractiveQuestionS.Main, "sdk-question-main")}diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsxindex 6780b4b6ec8..171f6261e69 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx@@ -1,7 +1,8 @@-import { type PropsWithChildren, useRef } from "react";+import type { PropsWithChildren } from "react";import { FlexibleSizeComponent } from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";+import { RenderIfHasContent } from "embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent";import {Breakout,BreakoutDropdown,@@ -28,7 +29,6 @@ import {type SdkQuestionProps,} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";import { QuestionAlertsButton } from "embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton";-import { useHideEmptyElement } from "embedding-sdk-bundle/hooks/private/use-hide-empty-element";import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";import { useSdkSelector } from "embedding-sdk-bundle/store";import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";@@ -125,9 +125,6 @@ const StaticQuestionInner = ();};- const hideEmptyParentRef = useRef<HTMLDivElement>(null);- useHideEmptyElement("[data-hide-empty]", hideEmptyParentRef);-return (<SdkQuestionquestionId={questionId ?? null}@@ -151,27 +148,30 @@ const StaticQuestionInner = (w="100%"h="100%"gap="xs"- ref={hideEmptyParentRef}>- <Stack+ <RenderIfHasContent+ component={Stack}className={InteractiveQuestionS.TopBar}gap="sm"p="md"- data-hide-emptydata-testid="static-question-top-bar">{title && <DefaultViewTitle title={title} />}- <ResultToolbar data-hide-empty data-testid="result-toolbar">++ <RenderIfHasContent+ component={ResultToolbar}+ data-testid="result-toolbar"+ >{withChartTypeSelector && <SdkQuestion.ChartTypeDropdown />}- {/* This container is always shown on the right */}- <Group gap="sm" ml="auto" data-hide-empty>++ <RenderIfHasContent component={Group} gap="sm" ml="auto"><SdkQuestion.DownloadWidgetDropdown /><QuestionAlertsButton />- </Group>- </ResultToolbar>+ </RenderIfHasContent>+ </RenderIfHasContent>{isGuestEmbed && <SdkQuestion.SqlParametersList />}- </Stack>+ </RenderIfHasContent><Box className={InteractiveQuestionS.Main} w="100%" h="100%"><Box className={InteractiveQuestionS.Content}>diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsxindex 3343ea57d7d..91fc75ece88 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx@@ -217,10 +217,9 @@ describe("StaticQuestion", () => {withAlerts: false,});- const topBar = screen.getByTestId("static-question-top-bar");-- expect(topBar).not.toBeVisible();- expect(topBar).toHaveStyle({ display: "none" });+ expect(+ screen.queryByTestId("static-question-top-bar"),+ ).not.toBeInTheDocument();});it("should show the TopBar when title is provided", async () => {@@ -330,7 +329,9 @@ describe("StaticQuestion", () => {expect(within(screen.getByRole("gridcell")).getByText("Test Row"),).toBeVisible();- expect(screen.getByRole("button", { name: "Alerts" })).toBeVisible();+ expect(+ await screen.findByRole("button", { name: "Alerts" }),+ ).toBeVisible();});it("should show the alert button for custom layouts when withAlerts is true", async () => {@@ -476,7 +477,9 @@ describe("StaticQuestion", () => {within(screen.getByRole("gridcell")).getByText("Test Row"),).toBeVisible();- await userEvent.click(screen.getByRole("button", { name: "Alerts" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Alerts" }),+ );// Verify the alert list modal appears, not the create modalconst withinModal = within(await findModal());@@ -507,7 +510,9 @@ describe("StaticQuestion", () => {expect(within(screen.getByRole("gridcell")).getByText("Test Row"),).toBeVisible();- await userEvent.click(screen.getByRole("button", { name: "Alerts" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Alerts" }),+ );const withinModal = within(await findModal());expect(diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.tsdeleted file mode 100644index 7e0a0846dfd..00000000000--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-hide-empty-element.ts+++ /dev/null@@ -1,83 +0,0 @@-import { useEffect } from "react";--/**- * The reason we need to use JavaScript to detect the emptiness of nested elements is that- * we can't easily determine if an element would be empty because each element has its own logic- * to decide whether it will render content or not. And we need to expose all those logics to the- * parent component which would make the code more complex and less maintainable.- */--/**- * A hook that hides elements matching the given selector if they are empty- * @param {string} selector - CSS selector targeting elements we want to hide if empty- * @param {React.RefObject<HTMLDivElement>} parentElementRef - The parent element ref within which to search for elements to hide- */-export function useHideEmptyElement(- selector: string,- parentElementRef: React.RefObject<HTMLDivElement>,-) {- /**- * This hook will traverse the DOM tree starting from the children and going up to the parent.- * This ensures MutationObserver captures changes in child elements before evaluating parent elements- * in case a parent component uses this hook as well.- */- useEffect(() => {- const parentElement = parentElementRef.current;- if (!parentElement) {- return;- }-- const updateVisibility = () => {- const elements: Element[] = [- parentElement as Element,- ...Array.from(parentElement.querySelectorAll(selector)),- ];-- // Bottom-up recursion- for (let index = elements.length - 1; index >= 0; index--) {- const element = elements[index];- const hasText = element.textContent?.trim().length > 0;- const hasMeaningfulChildren = Array.from(element.children).some(- (child) => {- return isElementVisible(child as HTMLElement);- },- );-- (element as HTMLElement).style.display =- !hasText && !hasMeaningfulChildren ? "none" : "";- }- };-- // Initial check- updateVisibility();-- // Set up MutationObserver to watch for DOM changes- const observer = new MutationObserver(() => {- updateVisibility();- });-- observer.observe(parentElement, {- childList: true,- subtree: true,- characterData: true,- });-- return () => {- observer.disconnect();- };- }, [selector, parentElementRef]);-}--function isElementVisible(element: HTMLElement): boolean {- if (element.style.display === "none") {- return false;- }-- if (element.children.length === 0) {- return true;- }-- return Array.from(element.children).some((child) =>- isElementVisible(child as HTMLElement),- );-}