Skip to content

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

Migrate LogoIcon from JSX class component to TS functional component (#75121)

Andrei Chernykhf74bbbe90149
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.jsx b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.jsx
deleted file mode 100644
index c88691e7e9c..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.jsx
+++ /dev/null
@@ -1,174 +0,0 @@
-/* eslint-disable react/prop-types */
-import cx from "classnames";
-import PropTypes from "prop-types";
-import { Component } from "react";
-
-import CS from "metabase/css/core/index.css";
-import { connect } from "metabase/redux";
-import { parseDataUri } from "metabase/utils/data-url";
-import {
- getIsDefaultMetabaseLogo,
- getLogoUrl,
-} from "metabase-enterprise/settings/selectors";
-
-const mapStateToProps = (state) => ({
- url: getLogoUrl(state),
- isDefaultMetabaseLogo: getIsDefaultMetabaseLogo(state),
-});
-
-class LogoIcon extends Component {
- state = {
- svg: null,
- };
-
- static defaultProps = {
- height: 32,
- };
-
- static propTypes = {
- size: PropTypes.number,
- width: PropTypes.number,
- height: PropTypes.number,
- dark: PropTypes.bool,
- className: PropTypes.string,
- style: PropTypes.object,
- };
-
- componentDidMount() {
- if (this.props.url) {
- this.loadImage(this.props.url);
- }
- }
-
- UNSAFE_componentWillReceiveProps(newProps) {
- if (newProps.url && newProps.url !== this.props.url) {
- this.loadImage(newProps.url);
- }
- }
-
- componentWillUnmount() {
- if (this.abortController) {
- this.abortController.abort();
- this.abortController = null;
- }
- }
-
- async loadImage(url) {
- if (this.abortController) {
- this.abortController.abort();
- }
-
- this._container.replaceChildren();
-
- const parsed = parseDataUri(url);
- if (parsed) {
- if (parsed.mimeType === "image/svg+xml") {
- this._container.innerHTML = parsed.data;
- const svg = this._container.getElementsByTagName("svg")[0];
- if (svg) {
- svg.setAttribute("fill", "currentcolor");
- this.updateSize(svg);
- } else {
- this.loadImageFallback(url);
- }
- } else {
- this.loadImageFallback(url);
- }
- } else {
- this.abortController = new AbortController();
- try {
- const response = await fetch(url, {
- signal: this.abortController.signal,
- });
-
- if (!response.ok) {
- this.loadImageFallback(url);
- return;
- }
-
- const text = await response.text();
- const parser = new DOMParser();
- const doc = parser.parseFromString(text, "image/svg+xml");
- const svg = doc.getElementsByTagName("svg")[0];
-
- if (svg) {
- svg.setAttribute("fill", "currentcolor");
- this.updateSize(svg);
-
- this._container.replaceChildren();
- this._container.appendChild(svg);
- } else {
- this.loadImageFallback(url);
- }
- } catch (error) {
- if (error.name !== "AbortError") {
- this.loadImageFallback(url);
- }
- }
- }
- }
-
- loadImageFallback(url) {
- this._container.replaceChildren();
-
- const img = document.createElement("img");
- img.src = url;
- this.updateSize(img);
-
- this._container.appendChild(img);
- }
-
- updateSize(element) {
- const width = this.props.width || this.props.size;
- const height = this.props.height || this.props.size;
- if (width) {
- element.setAttribute("width", width);
- } else {
- element.removeAttribute("width");
- }
- if (height) {
- element.setAttribute("height", height);
- } else {
- element.removeAttribute("height");
- }
- element.style.maxWidth = "100%";
- element.style.maxHeight = "32px";
- element.style.minHeight = "100%";
- element.style.height = "auto";
- }
-
- render() {
- const {
- dark,
- style = {},
- height,
- className,
- isDefaultMetabaseLogo,
- } = this.props;
-
- return (
- <span
- ref={(c) => (this._container = c)}
- className={cx(
- "Icon",
- CS.textCentered,
- // If using the Metabase logo, use the non-whitelabeled Metabase brand color.
- {
- [isDefaultMetabaseLogo ? CS.textMetabaseBrand : CS.textBrand]:
- !dark,
- },
- { [CS.textWhite]: dark },
- className,
- )}
- style={{
- ...style,
- height: style.height || height || "32px",
- }}
- data-testid="main-logo"
- />
- );
- }
-}
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default connect(mapStateToProps)(LogoIcon);
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.tsx b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.tsx
new file mode 100644
index 00000000000..f90db96263b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.tsx
@@ -0,0 +1,147 @@
+import cx from "classnames";
+import { type CSSProperties, useEffect, useRef } from "react";
+
+import CS from "metabase/css/core/index.css";
+import { useSelector } from "metabase/redux";
+import { parseDataUri } from "metabase/utils/data-url";
+import {
+ getIsDefaultMetabaseLogo,
+ getLogoUrl,
+} from "metabase-enterprise/settings/selectors";
+
+const DEFAULT_HEIGHT = 32;
+
+type LogoIconProps = {
+ width?: number;
+ height?: number;
+ size?: number;
+ dark?: boolean;
+ className?: string;
+ style?: CSSProperties;
+};
+
+export function LogoIcon({
+ dark,
+ className,
+ style = {},
+ width,
+ height = DEFAULT_HEIGHT,
+ size,
+}: LogoIconProps) {
+ const url = useSelector(getLogoUrl);
+ const isDefaultMetabaseLogo = useSelector(getIsDefaultMetabaseLogo);
+ const containerRef = useRef<HTMLSpanElement>(null);
+
+ // Keep the latest sizing available to the load effect without making it a
+ // dependency, so the image only reloads when the URL changes.
+ const sizingRef = useRef({ width, height, size });
+ sizingRef.current = { width, height, size };
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container || !url) {
+ return;
+ }
+
+ const controller = new AbortController();
+
+ const applySize = (element: SVGSVGElement | HTMLImageElement) => {
+ const { width, height, size } = sizingRef.current;
+ const resolvedWidth = width || size;
+ const resolvedHeight = height || size;
+ if (resolvedWidth) {
+ element.setAttribute("width", String(resolvedWidth));
+ } else {
+ element.removeAttribute("width");
+ }
+ if (resolvedHeight) {
+ element.setAttribute("height", String(resolvedHeight));
+ } else {
+ element.removeAttribute("height");
+ }
+ element.style.maxWidth = "100%";
+ element.style.maxHeight = "32px";
+ element.style.minHeight = "100%";
+ element.style.height = "auto";
+ };
+
+ const renderImgFallback = () => {
+ container.replaceChildren();
+ const img = document.createElement("img");
+ img.src = url;
+ applySize(img);
+ container.appendChild(img);
+ };
+
+ const loadImage = async () => {
+ container.replaceChildren();
+
+ const parsed = parseDataUri(url);
+ if (parsed) {
+ if (parsed.mimeType === "image/svg+xml") {
+ container.innerHTML = parsed.data;
+ const svg = container.getElementsByTagName("svg")[0];
+ if (svg) {
+ svg.setAttribute("fill", "currentcolor");
+ applySize(svg);
+ } else {
+ renderImgFallback();
+ }
+ } else {
+ renderImgFallback();
+ }
+ return;
+ }
+
+ try {
+ const response = await fetch(url, { signal: controller.signal });
+ if (!response.ok) {
+ renderImgFallback();
+ return;
+ }
+
+ const text = await response.text();
+ const doc = new DOMParser().parseFromString(text, "image/svg+xml");
+ const svg = doc.getElementsByTagName("svg")[0];
+
+ if (svg) {
+ svg.setAttribute("fill", "currentcolor");
+ applySize(svg);
+ container.replaceChildren();
+ container.appendChild(svg);
+ } else {
+ renderImgFallback();
+ }
+ } catch (error) {
+ if ((error as Error).name !== "AbortError") {
+ renderImgFallback();
+ }
+ }
+ };
+
+ loadImage();
+
+ return () => controller.abort();
+ }, [url]);
+
+ return (
+ <span
+ ref={containerRef}
+ className={cx(
+ "Icon",
+ CS.textCentered,
+ // If using the Metabase logo, use the non-whitelabeled Metabase brand color.
+ {
+ [isDefaultMetabaseLogo ? CS.textMetabaseBrand : CS.textBrand]: !dark,
+ },
+ { [CS.textWhite]: dark },
+ className,
+ )}
+ style={{
+ ...style,
+ height: style.height || height || "32px",
+ }}
+ data-testid="main-logo"
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.unit.spec.tsx
index d1468b695bd..5b6ba818373 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/components/LogoIcon.unit.spec.tsx
@@ -5,7 +5,17 @@ import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { createMockSettings } from "metabase-types/api/mocks";
-import LogoIcon from "./LogoIcon";
+jest.mock("metabase/css/core/index.css", () => ({
+ textCentered: "textCentered",
+ textBrand: "textBrand",
+ textMetabaseBrand: "textMetabaseBrand",
+ textWhite: "textWhite",
+}));
+
+import { LogoIcon } from "./LogoIcon";
+
+const NOOP_SVG_DATA_URI =
+ 'data:image/svg+xml,<svg data-testid="noop-svg"><circle r="1"/></svg>';
const setup = (props = {}, settingsOverrides = {}) => {
const storeInitialState = createMockState({
@@ -112,4 +122,103 @@ describe("LogoIcon", () => {
expect(container.querySelector("img")).toBeInTheDocument();
});
});
+
+ it("should fall back to img element for non-SVG data URIs", async () => {
+ const pngDataUri =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
+
+ setup({}, { "application-logo-url": pngDataUri });
+
+ await waitFor(() => {
+ const container = screen.getByTestId("main-logo");
+ expect(container.querySelector("img")).toBeInTheDocument();
+ });
+
+ const img = screen.getByTestId("main-logo").querySelector("img");
+ expect(img).toHaveAttribute("src", pngDataUri);
+ });
+
+ it("should fall back to img when data URI declares SVG but contains no svg tag", async () => {
+ const badSvgDataUri = "data:image/svg+xml,<div>not-svg</div>";
+
+ setup({}, { "application-logo-url": badSvgDataUri });
+
+ await waitFor(() => {
+ const container = screen.getByTestId("main-logo");
+ expect(container.querySelector("img")).toBeInTheDocument();
+ });
+ });
+
+ it("should apply width and height props to the rendered SVG", async () => {
+ const svgData = '<svg data-testid="sized-svg"><circle r="10"/></svg>';
+ const dataUri = `data:image/svg+xml,${svgData}`;
+
+ setup({ width: 64, height: 48 }, { "application-logo-url": dataUri });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("sized-svg")).toBeInTheDocument();
+ });
+
+ const svg = screen.getByTestId("sized-svg");
+ expect(svg).toHaveAttribute("width", "64");
+ expect(svg).toHaveAttribute("height", "48");
+ });
+
+ it("should apply textMetabaseBrand when not dark and the logo is the default", () => {
+ fetchMock.get("http://localhost//app/assets/img/logo.svg", 404);
+ setup({}, { "application-logo-url": "app/assets/img/logo.svg" });
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveClass("textMetabaseBrand");
+ expect(container).not.toHaveClass("textBrand");
+ expect(container).not.toHaveClass("textWhite");
+ });
+
+ it("should apply textBrand when not dark and the logo is whitelabeled", () => {
+ setup({}, { "application-logo-url": NOOP_SVG_DATA_URI });
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveClass("textBrand");
+ expect(container).not.toHaveClass("textMetabaseBrand");
+ expect(container).not.toHaveClass("textWhite");
+ });
+
+ it("should apply textWhite when dark is true", () => {
+ setup({ dark: true }, { "application-logo-url": NOOP_SVG_DATA_URI });
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveClass("textWhite");
+ expect(container).not.toHaveClass("textMetabaseBrand");
+ expect(container).not.toHaveClass("textBrand");
+ });
+
+ it("should merge a custom className", () => {
+ setup(
+ { className: "my-custom-class" },
+ { "application-logo-url": NOOP_SVG_DATA_URI },
+ );
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveClass("my-custom-class");
+ });
+
+ it("should apply custom style and the height prop", () => {
+ setup(
+ { height: 48, style: { color: "rgb(1, 2, 3)" } },
+ { "application-logo-url": NOOP_SVG_DATA_URI },
+ );
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveStyle({ color: "rgb(1, 2, 3)", height: "48px" });
+ });
+
+ it("should let style.height override the height prop", () => {
+ setup(
+ { height: 48, style: { height: "16px" } },
+ { "application-logo-url": NOOP_SVG_DATA_URI },
+ );
+
+ const container = screen.getByTestId("main-logo");
+ expect(container).toHaveStyle({ height: "16px" });
+ });
});
diff --git a/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts b/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
index 346ac78463c..e64b6307176 100644
--- a/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/whitelabel/index.ts
@@ -23,7 +23,7 @@ import {
import type { SettingKey } from "metabase-types/api";
import { LandingPageUrlField } from "./components/LandingPageUrlField";
-import LogoIcon from "./components/LogoIcon";
+import { LogoIcon } from "./components/LogoIcon";
import { WhiteLabelBrandingSettingsPage } from "./components/WhiteLabelBrandingSettingsPage";
import { WhiteLabelConcealSettingsPage } from "./components/WhiteLabelConcealSettingsPage";
import { updateColors } from "./lib/whitelabel";