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
GDGT-1755: Migrate AdHocQuestionLoader, Breadcrumbs, QuestionLoader, QuestionResultLoader, SavedQuestionLoader to TS (#70106)
Stas Gavrylovd813be6b09b5
diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsxindex 2fd074cf508..8efbe864211 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/components/EditSandboxingModal/EditSandboxingModal.tsx@@ -25,7 +25,6 @@ import type {} from "metabase-enterprise/sandboxes/types";import { getRawDataQuestionForTable } from "metabase-enterprise/sandboxes/utils";import * as Lib from "metabase-lib";-import type Question from "metabase-lib/v1/Question";import type {GroupTableAccessPolicy,Table,@@ -426,7 +425,7 @@ const TargetName = ({ policy, policyTable, target }: TargetNameProps) => {}includeSensitiveFields>- {({ question }: { question: Question }) => {+ {({ question }) => {if (!question) {return null;}diff --git a/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx b/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsxindex c8d4e5e3407..d9fe83c4e1f 100644--- a/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx+++ b/enterprise/frontend/src/metabase-enterprise/sandboxes/utils.tsx@@ -7,6 +7,7 @@ import type {StructuredUserAttributes,Table,Tenant,+ UnsavedCard,} from "metabase-types/api";import type {@@ -33,12 +34,14 @@ export const getPolicyKeyFromParams = ({export const getPolicyKey = (policy: GroupTableAccessPolicy) =>`${policy.group_id}:${policy.table_id}`;-export const getRawDataQuestionForTable = (table: Table) => ({+export const getRawDataQuestionForTable = (table: Table): UnsavedCard => ({+ display: "table",dataset_query: {type: "query",database: table?.db_id,query: { "source-table": table?.id },},+ visualization_settings: {},});export const renderUserAttributesForSelect: SelectProps["renderOption"] = ({diff --git a/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx b/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsxindex 3b3560e2920..f736e8a18f0 100644--- a/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx+++ b/frontend/src/metabase/collections/components/PinnedQuestionCard/PinnedQuestionLoader.tsx@@ -26,14 +26,6 @@ export interface PinnedQuestionChildrenProps {errorIcon?: IconName;}-export interface QuestionResultLoaderProps {- loading: boolean;- error?: any;- result?: any;- results?: any;- rawSeries?: RawSeries;-}-const PinnedQuestionLoader = ({id,children,@@ -68,13 +60,7 @@ const PinnedQuestionLoader = ({return (<QuestionResultLoader question={question} collectionPreview>- {({- loading,- error,- result,- results,- rawSeries,- }: QuestionResultLoaderProps) =>+ {({ loading, error, result, results, rawSeries }) =>children({question,loading: loading || results == null,@@ -87,7 +73,7 @@ const PinnedQuestionLoader = ({);};-const getRawSeries = (rawSeries?: any[]) => {+const getRawSeries = (rawSeries: RawSeries | null | undefined) => {return rawSeries?.map((series) => ({...series,card: {diff --git a/frontend/src/metabase/common/components/AdHocQuestionLoader.jsx b/frontend/src/metabase/common/components/AdHocQuestionLoader.jsxdeleted file mode 100644index 43558efdf83..00000000000--- a/frontend/src/metabase/common/components/AdHocQuestionLoader.jsx+++ /dev/null@@ -1,142 +0,0 @@-/* eslint-disable react/prop-types */-import { Component } from "react";--import { deserializeCardFromUrl } from "metabase/lib/card";-import { connect } from "metabase/lib/redux";-import { loadMetadataForCard } from "metabase/questions/actions";-import { getMetadata } from "metabase/selectors/metadata";-import Question from "metabase-lib/v1/Question";--// type annotations--/*- * AdHocQuestionLoader- *- * Load a transient quetsion via its encoded URL and return it to the calling- * component- *- * @example- *- * Render prop style- * import AdHocQuestionLoader from 'metabase/containers/AdHocQuestionLoader'- *- * // assuming- * class ExampleAdHocQuestionFeature extends React.Component {- * render () {- * return (- * <AdHocQuestionLoader questionId={this.props.params.questionId}>- * { ({ question, loading, error }) => {- *- * }}- * </SavedQuestion>- * )- * }- * }- *- * @example- *- * The raw un-connected component is also exported so we can unit test it- * without the redux store.- */-export class AdHocQuestionLoaderView extends Component {- state = {- // this will store the loaded question- question: null,- // keep a reference to the card as well to help with re-creating question- // objects if the underlying metadata changes- card: null,- loading: false,- error: null,- };-- UNSAFE_componentWillMount() {- // load the specified question when the component mounts- this._loadQuestion(this.props.questionHash);- }-- UNSAFE_componentWillReceiveProps(nextProps) {- // if the questionHash changes (this will most likely be the result of a- // url change) then we need to load this new question- if (nextProps.questionHash !== this.props.questionHash) {- this._loadQuestion(nextProps.questionHash);- }-- // if the metadata changes for some reason we need to make sure we- // update the question with that metadata- if (nextProps.metadata !== this.props.metadata && this.state.card) {- this.setState({- question: new Question(this.state.card, nextProps.metadata),- });- }- }-- /*- * Load an AdHoc question and any required metadata- *- * 1. Decode the question via the URL- * 2. Load any required metadata into the redux store- * 3. Create a new Question object to return to metabase-lib methods can- * be used- * 4. Set the component state to the new Question- */- async _loadQuestion(questionHash) {- if (!questionHash) {- this.setState({- loading: false,- error: null,- question: null,- card: null,- });- return;- }- try {- this.setState({ loading: true, error: null });- // get the card definition from the URL, the "card"- const card = deserializeCardFromUrl(questionHash);- // pass the decoded card to load any necessary metadata- // (tables, source db, segments, etc) into- // the redux store, the resulting metadata will be available as metadata on the- // component props once it's available- await this.props.loadMetadataForCard(card, {- includeSensitiveFields: this.props.includeSensitiveFields,- });-- // instantiate a new question object using the metadata and saved question- // so we can use metabase-lib methods to retrieve information and modify- // the question- const question = new Question(card, this.props.metadata);-- // finally, set state to store the Question object so it can be passed- // to the component using the loader, keep a reference to the card- // as well- this.setState({ loading: false, question, card });- } catch (error) {- this.setState({ loading: false, error });- }- }-- render() {- const { children } = this.props;- const { question, loading, error } = this.state;- // call the child function with our loaded question- return children && children({ question, loading, error });- }-}--// redux stuff-function mapStateToProps(state, ownProps) {- return {- metadata: getMetadata(state, {- includeSensitiveFields: ownProps.includeSensitiveFields,- }),- };-}--const mapDispatchToProps = {- loadMetadataForCard,-};--export const AdHocQuestionLoader = connect(- mapStateToProps,- mapDispatchToProps,-)(AdHocQuestionLoaderView);diff --git a/frontend/src/metabase/common/components/AdHocQuestionLoader.tsx b/frontend/src/metabase/common/components/AdHocQuestionLoader.tsxnew file mode 100644index 00000000000..49926707af0--- /dev/null+++ b/frontend/src/metabase/common/components/AdHocQuestionLoader.tsx@@ -0,0 +1,186 @@+import type { ReactNode } from "react";+import { useCallback, useEffect, useRef, useState } from "react";++import { deserializeCardFromUrl } from "metabase/lib/card";+import { useDispatch, useSelector } from "metabase/lib/redux";+import { loadMetadataForCard } from "metabase/questions/actions";+import { getMetadata } from "metabase/selectors/metadata";+import Question from "metabase-lib/v1/Question";+import type Metadata from "metabase-lib/v1/metadata/Metadata";+import type { UnsavedCard } from "metabase-types/api";++type ChildrenProps = {+ question: Question | null;+ loading: boolean;+ error: unknown;+};++type AdHocQuestionLoaderViewProps = {+ questionHash: string | null;+ metadata?: Metadata;+ loadMetadataForCard: (+ card: UnsavedCard,+ options?: { includeSensitiveFields?: boolean },+ ) => Promise<void>;+ includeSensitiveFields?: boolean;+ children: (state: ChildrenProps) => ReactNode;+};++type AdHocQuestionLoaderProps = {+ questionHash: string | null;+ includeSensitiveFields?: boolean;+ children: (state: ChildrenProps) => ReactNode;+};++/**+ * AdHocQuestionLoader+ *+ * Load a transient question via its encoded URL and return it to the calling+ * component+ *+ * @example+ *+ * Render prop style+ * import { AdHocQuestionLoader } from 'metabase/common/components/AdHocQuestionLoader'+ *+ * function ExampleAdHocQuestionFeature({ params }) {+ * return (+ * <AdHocQuestionLoader questionHash={params.questionHash}>+ * {({ question, loading, error }) => {+ * // render content+ * }}+ * </AdHocQuestionLoader>+ * );+ * }+ *+ * The raw component (AdHocQuestionLoaderView) is also exported so we can unit+ * test it without the redux store.+ */+export function AdHocQuestionLoaderView({+ questionHash,+ metadata,+ loadMetadataForCard: loadMetadata,+ includeSensitiveFields,+ children,+}: AdHocQuestionLoaderViewProps) {+ const [question, setQuestion] = useState<Question | null>(null);+ // keep a reference to the card as well to help with re-creating question+ // objects if the underlying metadata changes+ const [card, setCard] = useState<UnsavedCard | null>(null);+ const [loading, setLoading] = useState(Boolean(questionHash));+ const [error, setError] = useState<unknown>(null);++ const metadataRef = useRef<Metadata | undefined>(metadata);+ metadataRef.current = metadata;++ useEffect(() => {+ let cancelled = false;++ /*+ * Load an AdHoc question and any required metadata+ *+ * 1. Decode the question via the URL+ * 2. Load any required metadata into the redux store+ * 3. Create a new Question object to return to metabase-lib methods can+ * be used+ * 4. Set the component state to the new Question+ */+ async function loadQuestion() {+ if (!questionHash) {+ setLoading(false);+ setError(null);+ setQuestion(null);+ setCard(null);+ return;+ }++ try {+ setLoading(true);+ setError(null);++ // get the card definition from the URL, the "card"+ const deserializedCard = deserializeCardFromUrl(questionHash);++ // pass the decoded card to load any necessary metadata+ // (tables, source db, segments, etc) into+ // the redux store, the resulting metadata will be available as metadata on the+ // component props once it's available+ await loadMetadata(deserializedCard, { includeSensitiveFields });++ if (cancelled) {+ return;+ }++ // instantiate a new question object using the metadata and saved question+ // so we can use metabase-lib methods to retrieve information and modify+ // the question+ const newQuestion = new Question(deserializedCard, metadataRef.current);++ // finally, set state to store the Question object so it can be passed+ // to the component using the loader, keep a reference to the card+ // as well+ setQuestion(newQuestion);+ setCard(deserializedCard);+ } catch (err) {+ if (!cancelled) {+ setError(err);+ setQuestion(null);+ setCard(null);+ }+ } finally {+ if (!cancelled) {+ setLoading(false);+ }+ }+ }++ loadQuestion();++ return () => {+ cancelled = true;+ };+ }, [questionHash, includeSensitiveFields, loadMetadata]);++ // if the metadata changes for some reason we need to make sure we+ // update the question with that metadata+ useEffect(() => {+ if (metadata && card) {+ setQuestion(new Question(card, metadata));+ }+ }, [metadata, card]);++ // call the child function with our loaded question+ return children({ question, loading, error });+}++export function AdHocQuestionLoader({+ questionHash,+ includeSensitiveFields,+ children,+}: AdHocQuestionLoaderProps) {+ const dispatch = useDispatch();+ const metadata = useSelector((state) =>+ getMetadata(state, { includeSensitiveFields }),+ );++ const loadMetadata = useCallback(+ async (+ card: UnsavedCard,+ options?: { includeSensitiveFields?: boolean },+ ) => {+ await dispatch(loadMetadataForCard(card, options));+ },+ [dispatch],+ );++ return (+ <AdHocQuestionLoaderView+ questionHash={questionHash}+ metadata={metadata}+ loadMetadataForCard={loadMetadata}+ includeSensitiveFields={includeSensitiveFields}+ >+ {children}+ </AdHocQuestionLoaderView>+ );+}diff --git a/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.js b/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.jsdeleted file mode 100644index 800ad01a3ac..00000000000--- a/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.js+++ /dev/null@@ -1,90 +0,0 @@-import { render } from "__support__/ui";-import { delay } from "__support__/utils";-import * as Lib from "metabase-lib";-import {- DEFAULT_TEST_QUERY,- SAMPLE_METADATA,- SAMPLE_PROVIDER,-} from "metabase-lib/test-helpers";-import Question from "metabase-lib/v1/Question";-import * as ML_Urls from "metabase-lib/v1/urls";--import { AdHocQuestionLoaderView } from "./AdHocQuestionLoader";--describe("AdHocQuestionLoader", () => {- let loadQuestionSpy, loadMetadataSpy, mockChild;-- beforeEach(() => {- // reset mocks between tests so we have fresh spies, etc- jest.resetAllMocks();- mockChild = jest.fn().mockReturnValue(<div />);- loadMetadataSpy = jest.fn();- loadQuestionSpy = jest.spyOn(- AdHocQuestionLoaderView.prototype,- "_loadQuestion",- );- });-- it("should load a question given a questionHash", async () => {- const q = Question.create({ metadata: SAMPLE_METADATA }).setQuery(- Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),- );- const questionHash = ML_Urls.getUrl(q).match(/(#.*)/)[1];-- render(- <AdHocQuestionLoaderView- questionHash={questionHash}- loadMetadataForCard={loadMetadataSpy}- >- {mockChild}- </AdHocQuestionLoaderView>,- );- expect(mockChild.mock.calls[0][0].loading).toEqual(true);- expect(mockChild.mock.calls[0][0].error).toEqual(null);-- // stuff happens asynchronously- await delay(0);-- const calls = mockChild.mock.calls;- const { question, loading, error } = calls[calls.length - 1][0];- expect(- Lib.areLegacyQueriesEqual(question.datasetQuery(), q.datasetQuery()),- ).toBe(true);- expect(loading).toEqual(false);- expect(error).toEqual(null);- });-- it("should load a new question if the question hash changes", () => {- // create some junk strings, real question hashes are more ludicrous but this- // is easier to verify- const originalQuestionHash = "#abc123";- const newQuestionHash = "#def456";-- const { rerender } = render(- <AdHocQuestionLoaderView- questionHash={originalQuestionHash}- loadMetadataForCard={loadMetadataSpy}- >- {mockChild}- </AdHocQuestionLoaderView>,- );-- expect(loadQuestionSpy).toHaveBeenCalledWith(originalQuestionHash);-- // update the question hash, a new location.hash in the url would most- // likely do this- rerender(- <AdHocQuestionLoaderView- questionHash={newQuestionHash}- loadMetadataForCard={loadMetadataSpy}- >- {mockChild}- </AdHocQuestionLoaderView>,- );-- // question loading should begin with the new ID- expect(loadQuestionSpy).toHaveBeenCalledWith(newQuestionHash);-- expect(mockChild).toHaveBeenCalled();- });-});diff --git a/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.tsx b/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.tsxnew file mode 100644index 00000000000..c6fcf6eb27b--- /dev/null+++ b/frontend/src/metabase/common/components/AdHocQuestionLoader.unit.spec.tsx@@ -0,0 +1,144 @@+import { render } from "__support__/ui";+import { delay } from "__support__/utils";+import * as Card from "metabase/lib/card";+import * as Lib from "metabase-lib";+import {+ DEFAULT_TEST_QUERY,+ SAMPLE_METADATA,+ SAMPLE_PROVIDER,+} from "metabase-lib/test-helpers";+import Question from "metabase-lib/v1/Question";+import * as ML_Urls from "metabase-lib/v1/urls";++import { AdHocQuestionLoaderView } from "./AdHocQuestionLoader";++const getQuestionHash = (questionUrl: string) => {+ const url = new URL(questionUrl, "http://example.com");+ return url.hash;+};++describe("AdHocQuestionLoader", () => {+ let loadMetadataSpy: jest.Mock;+ let mockChild: jest.Mock;++ beforeEach(() => {+ jest.resetAllMocks();+ mockChild = jest.fn().mockReturnValue(<div />);+ loadMetadataSpy = jest.fn();+ });++ it("should load a question given a questionHash", async () => {+ const q = Question.create({ metadata: SAMPLE_METADATA }).setQuery(+ Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),+ );+ const questionHash = getQuestionHash(ML_Urls.getUrl(q));++ render(+ <AdHocQuestionLoaderView+ questionHash={questionHash}+ loadMetadataForCard={loadMetadataSpy}+ >+ {mockChild}+ </AdHocQuestionLoaderView>,+ );+ expect(mockChild.mock.calls[0][0].loading).toEqual(true);+ expect(mockChild.mock.calls[0][0].error).toEqual(null);++ await delay(0);++ const calls = mockChild.mock.calls;+ const { question, loading, error } = calls[calls.length - 1][0];+ expect(+ Lib.areLegacyQueriesEqual(question.datasetQuery(), q.datasetQuery()),+ ).toBe(true);+ expect(loading).toEqual(false);+ expect(error).toEqual(null);+ });++ it("should call loadMetadataForCard when question hash changes", async () => {+ const q = Question.create({ metadata: SAMPLE_METADATA }).setQuery(+ Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),+ );+ const questionHash = getQuestionHash(ML_Urls.getUrl(q));++ // Create a different valid question with a different limit+ const q2 = Question.create({ metadata: SAMPLE_METADATA })+ .setQuery(Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY))+ .updateSettings({ "table.pivot": true });+ const newQuestionHash = getQuestionHash(ML_Urls.getUrl(q2));++ const deserializeCardSpy = jest.spyOn(Card, "deserializeCardFromUrl");++ const { rerender } = render(+ <AdHocQuestionLoaderView+ questionHash={questionHash}+ loadMetadataForCard={loadMetadataSpy}+ >+ {mockChild}+ </AdHocQuestionLoaderView>,+ );++ // Initial load+ await delay(0);+ expect(loadMetadataSpy).toHaveBeenCalledTimes(1);+ expect(deserializeCardSpy).toHaveBeenCalledWith(questionHash);++ // Rerender with different hash+ rerender(+ <AdHocQuestionLoaderView+ questionHash={newQuestionHash}+ loadMetadataForCard={loadMetadataSpy}+ >+ {mockChild}+ </AdHocQuestionLoaderView>,+ );++ await delay(0);++ // Should have called loadMetadataForCard again with the new card+ expect(loadMetadataSpy).toHaveBeenCalledTimes(2);+ expect(deserializeCardSpy).toHaveBeenCalledWith(newQuestionHash);+ });++ it("should show loading state while question is being loaded", async () => {+ const q = Question.create({ metadata: SAMPLE_METADATA }).setQuery(+ Lib.createTestQuery(SAMPLE_PROVIDER, DEFAULT_TEST_QUERY),+ );+ const questionHash = getQuestionHash(ML_Urls.getUrl(q));++ // Make loadMetadataForCard hang so we can observe loading state+ let resolveLoad: () => void;+ loadMetadataSpy.mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ resolveLoad = resolve;+ }),+ );++ render(+ <AdHocQuestionLoaderView+ questionHash={questionHash}+ loadMetadataForCard={loadMetadataSpy}+ >+ {mockChild}+ </AdHocQuestionLoaderView>,+ );++ // Initially loading+ expect(mockChild.mock.calls[0][0].loading).toEqual(true);++ await delay(0);++ // Still loading because promise hasn't resolved+ let lastCall = mockChild.mock.calls[mockChild.mock.calls.length - 1][0];+ expect(lastCall.loading).toEqual(true);++ // Resolve the load+ resolveLoad!();+ await delay(0);++ // Now loading should be false+ lastCall = mockChild.mock.calls[mockChild.mock.calls.length - 1][0];+ expect(lastCall.loading).toEqual(false);+ });+});diff --git a/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.jsx b/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.jsxdeleted file mode 100644index d214170faf5..00000000000--- a/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.jsx+++ /dev/null@@ -1,84 +0,0 @@-import cx from "classnames";-import PropTypes from "prop-types";-import { Component } from "react";-import { Link } from "react-router";--import { Ellipsified } from "metabase/common/components/Ellipsified";-import { Icon } from "metabase/ui";--import S from "./Breadcrumbs.module.css";--export class Breadcrumbs extends Component {- static propTypes = {- className: PropTypes.string,- // each "crumb" is an array, the first index being the string title, the- // second index being a string URL or action function- crumbs: PropTypes.array,- inSidebar: PropTypes.bool,- placeholder: PropTypes.string,- size: PropTypes.oneOf(["medium", "large"]),- };- static defaultProps = {- crumbs: [],- inSidebar: false,- placeholder: null,- size: "medium",- };-- render() {- const { className, crumbs, inSidebar, placeholder, size } = this.props;-- const breadcrumbClass = inSidebar ? S.sidebarBreadcrumb : S.breadcrumb;- const breadcrumbsClass = inSidebar ? S.sidebarBreadcrumbs : S.breadcrumbs;-- return (- <section- data-testid="breadcrumbs"- className={cx(className, breadcrumbsClass)}- >- {crumbs.length <= 1 && placeholder ? (- <span className={cx(breadcrumbClass, S.breadcrumbPage)}>- {placeholder}- </span>- ) : (- crumbs- .map((breadcrumb) =>- Array.isArray(breadcrumb) ? breadcrumb : [breadcrumb],- )- .map((breadcrumb, index) => (- <Ellipsified- key={index}- tooltip={breadcrumb[0]}- tooltipProps={{ w: "auto" }}- className={cx(- breadcrumbClass,- breadcrumb.length > 1 ? S.breadcrumbPath : S.breadcrumbPage,- { [S.fontLarge]: size === "large" },- )}- >- {breadcrumb.length > 1 && typeof breadcrumb[1] === "string" ? (- <Link to={breadcrumb[1]}>{breadcrumb[0]}</Link>- ) : (- <span onClick={breadcrumb[1]}>{breadcrumb[0]}</span>- )}- </Ellipsified>- ))- .map((breadcrumb, index, breadcrumbs) =>- index < breadcrumbs.length - 1- ? [- breadcrumb,- <Icon- key={`${index}-separator`}- name="chevronright"- className={S.breadcrumbDivider}- width={12}- height={12}- />,- ]- : breadcrumb,- )- )}- </section>- );- }-}diff --git a/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.tsx b/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.tsxnew file mode 100644index 00000000000..12d69aa22d6--- /dev/null+++ b/frontend/src/metabase/common/components/Breadcrumbs/Breadcrumbs.tsx@@ -0,0 +1,115 @@+import cx from "classnames";+import type { MouseEventHandler, ReactNode } from "react";+import { Link } from "react-router";++import { Ellipsified } from "metabase/common/components/Ellipsified";+import { Icon } from "metabase/ui";++import S from "./Breadcrumbs.module.css";++// A crumb can be:+// - [title] - just a string title (current page)+// - [title, url] - title with a URL link+// - [title, onClick] - title with an onClick handler+// - Or just a string `title` which gets normalized to [title]+type CrumbTuple =+ | [title: ReactNode]+ | [+ title: ReactNode,+ urlOrAction: string | MouseEventHandler<HTMLSpanElement>,+ ];++export type Crumb = ReactNode | CrumbTuple;++type BreadcrumbsProps = {+ className?: string;+ crumbs?: Crumb[];+ inSidebar?: boolean;+ placeholder?: string;+ size?: "medium" | "large";+};++export function Breadcrumbs({+ className,+ crumbs = [],+ inSidebar = false,+ placeholder,+ size = "medium",+}: BreadcrumbsProps) {+ const breadcrumbClass = inSidebar ? S.sidebarBreadcrumb : S.breadcrumb;+ const breadcrumbsClass = inSidebar ? S.sidebarBreadcrumbs : S.breadcrumbs;++ return (+ <section+ data-testid="breadcrumbs"+ className={cx(className, breadcrumbsClass)}+ >+ {crumbs.length <= 1 && placeholder ? (+ <span className={cx(breadcrumbClass, S.breadcrumbPage)}>+ {placeholder}+ </span>+ ) : (+ crumbs+ .map(+ (breadcrumb): CrumbTuple =>+ isCrumbTuple(breadcrumb) ? breadcrumb : [breadcrumb],+ )+ .map((breadcrumb, index) => {+ const linkTarget = isLinkCrumb(breadcrumb)+ ? breadcrumb[1]+ : undefined;+ const onClick = isActionCrumb(breadcrumb)+ ? breadcrumb[1]+ : undefined;++ return (+ <Ellipsified+ key={index}+ tooltip={breadcrumb[0]}+ tooltipProps={{ w: "auto" }}+ className={cx(+ breadcrumbClass,+ breadcrumb.length > 1 ? S.breadcrumbPath : S.breadcrumbPage,+ { [S.fontLarge]: size === "large" },+ )}+ >+ {linkTarget ? (+ <Link to={linkTarget}>{breadcrumb[0]}</Link>+ ) : (+ <span onClick={onClick}>{breadcrumb[0]}</span>+ )}+ </Ellipsified>+ );+ })+ .map((breadcrumb, index, breadcrumbs) =>+ index < breadcrumbs.length - 1+ ? [+ breadcrumb,+ <Icon+ key={`${index}-separator`}+ name="chevronright"+ className={S.breadcrumbDivider}+ width={12}+ height={12}+ />,+ ]+ : breadcrumb,+ )+ )}+ </section>+ );+}++function isCrumbTuple(crumb: Crumb): crumb is CrumbTuple {+ return Array.isArray(crumb);+}++function isLinkCrumb(crumb: CrumbTuple): crumb is [ReactNode, string] {+ return crumb.length > 1 && typeof crumb[1] === "string";+}++function isActionCrumb(+ crumb: CrumbTuple,+): crumb is [ReactNode, MouseEventHandler<HTMLSpanElement>] {+ return crumb.length > 1 && typeof crumb[1] === "function";+}diff --git a/frontend/src/metabase/common/components/Breadcrumbs/index.tsx b/frontend/src/metabase/common/components/Breadcrumbs/index.tsxindex e283cad5903..cf0814396b7 100644--- a/frontend/src/metabase/common/components/Breadcrumbs/index.tsx+++ b/frontend/src/metabase/common/components/Breadcrumbs/index.tsx@@ -1 +1,2 @@export { Breadcrumbs } from "./Breadcrumbs";+export type { Crumb } from "./Breadcrumbs";diff --git a/frontend/src/metabase/common/components/QuestionLoader.jsx b/frontend/src/metabase/common/components/QuestionLoader.tsxsimilarity index 79%rename from frontend/src/metabase/common/components/QuestionLoader.jsxrename to frontend/src/metabase/common/components/QuestionLoader.tsxindex 1ad936e147f..4a496a5c11d 100644--- a/frontend/src/metabase/common/components/QuestionLoader.jsx+++ b/frontend/src/metabase/common/components/QuestionLoader.tsx@@ -1,9 +1,25 @@-/* eslint-disable react/prop-types */+import type { ReactNode } from "react";import { AdHocQuestionLoader } from "metabase/common/components/AdHocQuestionLoader";import { SavedQuestionLoader } from "metabase/common/components/SavedQuestionLoader";import renderPropToHOC from "metabase/hoc/RenderPropToHOC";import { serializeCardForUrl } from "metabase/lib/card";+import type Question from "metabase-lib/v1/Question";+import type { CardId, UnsavedCard } from "metabase-types/api";++export type QuestionLoaderChildrenProps = {+ question: Question | null;+ loading: boolean;+ error: unknown;+};++type QuestionLoaderProps = {+ questionObject?: UnsavedCard | null;+ questionId?: CardId | null;+ questionHash?: string | null;+ includeSensitiveFields?: boolean;+ children: (state: QuestionLoaderChildrenProps) => ReactNode;+};/** QuestionLoader@@ -40,7 +56,7 @@ export const QuestionLoader = ({questionHash,includeSensitiveFields = false,children,-}) =>+}: QuestionLoaderProps) =>questionObject != null ? (<AdHocQuestionLoaderquestionHash={serializeCardForUrl(questionObject)}diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.jsx b/frontend/src/metabase/common/components/QuestionResultLoader.jsxdeleted file mode 100644index 8dc38baaaae..00000000000--- a/frontend/src/metabase/common/components/QuestionResultLoader.jsx+++ /dev/null@@ -1,141 +0,0 @@-/* eslint-disable react/prop-types */-import PropTypes from "prop-types";-import { Component } from "react";--import { defer } from "metabase/lib/promise";-import { runQuestionQuery } from "metabase/services";--const propTypes = {- question: PropTypes.object,- children: PropTypes.func,- onLoad: PropTypes.func,- keepPreviousWhileLoading: PropTypes.bool,-};--/*- * Question result loader- *- * Handle running, canceling, and reloading Question results- *- * @example- * <QuestionResultLoader question={question}>- * { ({ result, cancel, reload }) =>- * <div>- * { result && (<Visualization ... />) }- *- * <a onClick={() => reload()}>Reload this please</a>- * <a onClick={() => cancel()}>Changed my mind</a>- * </div>- * }- * </QuestionResultLoader>- *- */-export class QuestionResultLoader extends Component {- state = {- results: null,- loading: false,- error: null,- };-- UNSAFE_componentWillMount = () => {- this._reload();- };-- UNSAFE_componentWillReceiveProps(nextProps) {- const { question, onLoad, keepPreviousWhileLoading } = nextProps;- // if the question is different, we need to do a fresh load- if (question && !question.isEqual(this.props.question)) {- this._loadResult(question, onLoad, keepPreviousWhileLoading);- }- }-- async _loadResult(question, onLoad, keepPreviousWhileLoading) {- const { collectionPreview } = this.props;-- // we need to have a question for anything to happen- if (question) {- try {- // set up a defer for cancelation- this._cancelDeferred = defer();-- // begin the request, set cancel in state so the query can be canceled- this.setState((prev) => ({- loading: true,- results: keepPreviousWhileLoading ? prev.results : null,- error: null,- }));-- const results = await runQuestionQuery(question, {- cancelDeferred: this._cancelDeferred,- collectionPreview,- });-- // setState with our result, remove our cancel since we've finished- this.setState({ loading: false, results });-- // handle onLoad prop- if (onLoad) {- setTimeout(() => onLoad && onLoad(results));- }- } catch (error) {- this.setState({ loading: false, error });- }- } else {- // if there's not a question we can't do anything so go back to our initial- // state- this.setState({ loading: false, results: null, error: null });- }- }-- /*- * a function to pass to the child to allow the component to call- * load again- */- _reload = () => {- const { question, onLoad, keepPreviousWhileLoading } = this.props;- this._loadResult(question, onLoad, keepPreviousWhileLoading);- };-- /*- * a function to pass to the child to allow the component to interrupt- * the query- */- _cancel = () => {- // we only want to do things if cancel has been set- if (this.state.loading) {- // set loading false- this.setState({ loading: false });- // call our _cancelDeferred to cancel the query- if (this._cancelDeferred) {- this._cancelDeferred();- }- }- };-- render() {- const { question, children } = this.props;- const { results, loading, error } = this.state;- return (- children &&- children({- results,- result: results && results[0],- // convenience for <Visualization /> component. Only support single series for now- rawSeries:- question && results- ? [{ card: question.card(), data: results[0].data }]- : null,- loading,- error,- cancel: this._cancel,- reload: this._reload,- })- );- }-}--QuestionResultLoader.defaultProps = {- keepPreviousWhileLoading: false,-};--QuestionResultLoader.propTypes = propTypes;diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.tsx b/frontend/src/metabase/common/components/QuestionResultLoader.tsxnew file mode 100644index 00000000000..8e518cc39cb--- /dev/null+++ b/frontend/src/metabase/common/components/QuestionResultLoader.tsx@@ -0,0 +1,144 @@+import type { ReactNode } from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import { useEffectOnce } from "react-use";++import type { Deferred } from "metabase/lib/promise";+import { defer } from "metabase/lib/promise";+import { runQuestionQuery } from "metabase/services";+import type Question from "metabase-lib/v1/Question";+import type { Dataset, RawSeries } from "metabase-types/api";++export type QuestionResultLoaderChildrenProps = {+ results: Dataset[] | null;+ result: Dataset | null;+ rawSeries: RawSeries | null;+ loading: boolean;+ error: unknown;+ cancel: () => void;+ reload: () => void;+};++type QuestionResultLoaderProps = {+ question: Question | null | undefined;+ onLoad?: (results: Dataset[]) => void;+ keepPreviousWhileLoading?: boolean;+ collectionPreview?: boolean;+ children: (state: QuestionResultLoaderChildrenProps) => ReactNode;+};++/*+ * Question result loader+ *+ * Handle running, canceling, and reloading Question results+ *+ * @example+ * <QuestionResultLoader question={question}>+ * { ({ result, cancel, reload }) =>+ * <div>+ * { result && (<Visualization ... />) }+ *+ * <a onClick={() => reload()}>Reload this please</a>+ * <a onClick={() => cancel()}>Changed my mind</a>+ * </div>+ * }+ * </QuestionResultLoader>+ *+ */+export function QuestionResultLoader({+ question,+ onLoad,+ keepPreviousWhileLoading = false,+ collectionPreview,+ children,+}: QuestionResultLoaderProps) {+ const [results, setResults] = useState<Dataset[] | null>(null);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState<unknown>(null);++ const cancelDeferredRef = useRef<Deferred | null>(null);+ const questionRef = useRef<Question | null | undefined>(question);++ const loadResult = useCallback(+ async (+ questionToLoad: Question | null | undefined,+ onLoadCallback?: (results: Dataset[]) => void,+ keepPrevious?: boolean,+ ) => {+ if (!questionToLoad) {+ setLoading(false);+ setResults(null);+ setError(null);+ return;+ }++ try {+ cancelDeferredRef.current = defer();++ setLoading(true);+ setResults((prev) => (keepPrevious ? prev : null));+ setError(null);++ const queryResults = await runQuestionQuery(questionToLoad, {+ cancelDeferred: cancelDeferredRef.current,+ collectionPreview,+ });++ setLoading(false);+ setResults(queryResults);++ if (onLoadCallback) {+ setTimeout(() => onLoadCallback(queryResults));+ }+ } catch (err) {+ setLoading(false);+ setError(err);+ }+ },+ [collectionPreview],+ );++ // A function to pass to the child to allow the component to call `loadResult` again+ const reload = useCallback(() => {+ loadResult(questionRef.current, onLoad, keepPreviousWhileLoading);+ }, [loadResult, onLoad, keepPreviousWhileLoading]);++ // A function to pass to the child to allow the component to interrupt the query+ const cancel = useCallback(() => {+ if (loading) {+ setLoading(false);+ cancelDeferredRef.current?.resolve();+ }+ }, [loading]);++ // Initial load on mount+ useEffectOnce(() => {+ loadResult(question, onLoad, keepPreviousWhileLoading);+ });++ // Reload when question changes+ useEffect(() => {+ const prevQuestion = questionRef.current;+ questionRef.current = question;++ if (question && prevQuestion && !question.isEqual(prevQuestion)) {+ loadResult(question, onLoad, keepPreviousWhileLoading);+ }+ }, [question, onLoad, keepPreviousWhileLoading, loadResult]);++ const result = results?.[0] ?? null;+ // convenience for <Visualization /> component. Only support single series for now+ const rawSeries: RawSeries | null =+ question && results+ ? [{ card: question.card(), data: results[0].data }]+ : null;++ return children({+ results,+ result,+ rawSeries,+ loading,+ error,+ cancel,+ reload,+ });+}diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.js b/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.jsdeleted file mode 100644index af5e92a4f48..00000000000--- a/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.js+++ /dev/null@@ -1,25 +0,0 @@-import { setupCardQueryEndpoints } from "__support__/server-mocks";-import { render } from "__support__/ui";-import Question from "metabase-lib/v1/Question";-import { createMockDataset } from "metabase-types/api/mocks";--import { QuestionResultLoader } from "./QuestionResultLoader";--describe("QuestionResultLoader", () => {- it("should load a result given a question", () => {- const question = new Question({- id: 1,- });- setupCardQueryEndpoints(question.card(), createMockDataset());-- const loadSpy = jest.spyOn(QuestionResultLoader.prototype, "_loadResult");-- render(- <QuestionResultLoader question={question}>- {() => <div />}- </QuestionResultLoader>,- );-- expect(loadSpy).toHaveBeenCalledWith(question, undefined, false);- });-});diff --git a/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.tsx b/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.tsxnew file mode 100644index 00000000000..b7f748d2fa5--- /dev/null+++ b/frontend/src/metabase/common/components/QuestionResultLoader.unit.spec.tsx@@ -0,0 +1,46 @@+import { setupCardQueryEndpoints } from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import Question from "metabase-lib/v1/Question";+import { createMockCard, createMockDataset } from "metabase-types/api/mocks";++import type { QuestionResultLoaderChildrenProps } from "./QuestionResultLoader";+import { QuestionResultLoader } from "./QuestionResultLoader";++describe("QuestionResultLoader", () => {+ it("should load a result given a question", async () => {+ const card = createMockCard({ id: 1 });+ const question = new Question(card);+ const dataset = createMockDataset();+ setupCardQueryEndpoints(question.card(), dataset);++ const childrenFn = jest.fn(+ ({ loading, result }: QuestionResultLoaderChildrenProps) => (+ <div data-testid="content">+ {loading ? "loading" : result ? "loaded" : "no result"}+ </div>+ ),+ );++ renderWithProviders(+ <QuestionResultLoader question={question}>+ {childrenFn}+ </QuestionResultLoader>,+ );++ // Initial render should show loading+ expect(screen.getByTestId("content")).toHaveTextContent("loading");++ // Wait for the result to load+ await waitFor(() => {+ expect(screen.getByTestId("content")).toHaveTextContent("loaded");+ });++ // Verify children was called with correct state+ expect(childrenFn).toHaveBeenCalledWith(+ expect.objectContaining({+ loading: false,+ result: expect.objectContaining({ data: dataset.data }),+ }),+ );+ });+});diff --git a/frontend/src/metabase/common/components/SavedQuestionLoader.jsx b/frontend/src/metabase/common/components/SavedQuestionLoader.jsxdeleted file mode 100644index 6a96db84b79..00000000000--- a/frontend/src/metabase/common/components/SavedQuestionLoader.jsx+++ /dev/null@@ -1,81 +0,0 @@-/* eslint-disable react/prop-types */-import { useMemo } from "react";-import { useAsync } from "react-use";-import _ from "underscore";--import { Questions } from "metabase/entities/questions";-import { useDispatch, useSelector } from "metabase/lib/redux";-import { loadMetadataForCard } from "metabase/questions/actions";-import { getMetadata } from "metabase/selectors/metadata";-import Question from "metabase-lib/v1/Question";--// type annotations--/*- * SavedQuestionLaoder- *- * Load a saved quetsion and return it to the calling component- *- * @example- *- * Render prop style- * import SavedQuestionLoader from 'metabase/containers/SavedQuestionLoader'- *- * // assuming- * class ExampleSavedQuestionFeature extends React.Component {- * render () {- * return (- * <SavedQuestionLoader questionId={this.props.params.questionId}>- * { ({ question, loading, error }) => {- *- * }}- * </SavedQuestion>- * )- * }- * }- *- * @example- */-const SavedQuestionLoaderInner = ({- children,- question: loadedQuestion,- error,- loading,-}) => {- const metadata = useSelector(getMetadata);- const dispatch = useDispatch();-- const cardMetadataState = useAsync(async () => {- if (loadedQuestion?.id() == null) {- return;- }-- await dispatch(loadMetadataForCard(loadedQuestion.card()));- }, [loadedQuestion?.id()]);-- const question = useMemo(() => {- const hasCardMetadataLoaded =- !cardMetadataState.loading && cardMetadataState.error == null;-- if (!loadedQuestion || !hasCardMetadataLoaded) {- return null;- }-- return new Question(loadedQuestion.card(), metadata);- }, [cardMetadataState, loadedQuestion, metadata]);-- return (- children?.({- question,- loading: loading || cardMetadataState.loading,- error: error ?? cardMetadataState.error,- }) ?? null- );-};--export const SavedQuestionLoader = _.compose(- Questions.load({- id: (_state, props) => props.questionId,- loadingAndErrorWrapper: false,- }),-)(SavedQuestionLoaderInner);diff --git a/frontend/src/metabase/common/components/SavedQuestionLoader.tsx b/frontend/src/metabase/common/components/SavedQuestionLoader.tsxnew file mode 100644index 00000000000..4f62718ceb3--- /dev/null+++ b/frontend/src/metabase/common/components/SavedQuestionLoader.tsx@@ -0,0 +1,70 @@+import type { ReactNode } from "react";+import { useEffect, useMemo } from "react";++import { skipToken, useGetCardQuery } from "metabase/api";+import { useDispatch, useSelector } from "metabase/lib/redux";+import { loadMetadataForCard } from "metabase/questions/actions";+import { getMetadata } from "metabase/selectors/metadata";+import Question from "metabase-lib/v1/Question";+import type { CardId } from "metabase-types/api";++import type { QuestionLoaderChildrenProps } from "./QuestionLoader";++type SavedQuestionLoaderProps = {+ questionId: CardId | null | undefined;+ children: (state: QuestionLoaderChildrenProps) => ReactNode;+};++/*+ * SavedQuestionLoader+ *+ * Load a saved question and return it to the calling component+ *+ * @example+ *+ * Render prop style+ * import { SavedQuestionLoader } from 'metabase/common/components/SavedQuestionLoader'+ *+ * function ExampleSavedQuestionFeature({ questionId }) {+ * return (+ * <SavedQuestionLoader questionId={questionId}>+ * {({ question, loading, error }) => {+ * // render content+ * }}+ * </SavedQuestionLoader>+ * );+ * }+ */+export function SavedQuestionLoader({+ questionId,+ children,+}: SavedQuestionLoaderProps) {+ const metadata = useSelector(getMetadata);+ const dispatch = useDispatch();++ const {+ data: card,+ isLoading: isCardLoading,+ isFetching,+ error: cardError,+ } = useGetCardQuery(questionId != null ? { id: questionId } : skipToken);++ // Load metadata for the card when it's available+ useEffect(() => {+ if (card) {+ dispatch(loadMetadataForCard(card));+ }+ }, [card, dispatch]);++ const question = useMemo(() => {+ if (!card || isFetching) {+ return null;+ }+ return new Question(card, metadata);+ }, [card, isFetching, metadata]);++ const loading = isCardLoading || isFetching;+ const error = cardError;++ return children({ question, loading, error });+}diff --git a/frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.js b/frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.tsxsimilarity index 79%rename from frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.jsrename to frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.tsxindex 5aad7b79636..2857696a7b0 100644--- a/frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.js+++ b/frontend/src/metabase/common/components/SavedQuestionLoader.unit.spec.tsx@@ -6,11 +6,13 @@ import {setupUnauthorizedSchemaEndpoints,} from "__support__/server-mocks";import { renderWithProviders, screen } from "__support__/ui";+import type { QuestionLoaderChildrenProps } from "metabase/common/components/QuestionLoader";import Question from "metabase-lib/v1/Question";+import type { Card, CardId } from "metabase-types/api";import {createMockCard,createMockCardQueryMetadata,- createMockColumn,+ createMockField,} from "metabase-types/api/mocks";import { createSampleDatabase } from "metabase-types/api/mocks/presets";@@ -18,7 +20,11 @@ import { SavedQuestionLoader } from "./SavedQuestionLoader";const databaseMock = createSampleDatabase();-const childrenRenderFn = ({ loading, question, error }) => {+function childrenRenderFn({+ loading,+ question,+ error,+}: QuestionLoaderChildrenProps) {if (error) {return <div>error</div>;}@@ -27,16 +33,22 @@ const childrenRenderFn = ({ loading, question, error }) => {return <div>loading</div>;}- return <div>{question.displayName()}</div>;+ return <div>{question?.displayName()}</div>;+}++type SetupQuestionOptions = {+ id: CardId;+ name: string;+ hasAccess: boolean;};-const setupQuestion = ({ id, name, hasAccess }) => {+function setupQuestion({ id, name, hasAccess }: SetupQuestionOptions): Card {const card = createMockCard({id,name,- result_metadata: [createMockColumn()],+ result_metadata: [createMockField()],});- const q = new Question(card, null);+ const q = new Question(card);if (hasAccess) {setupCardEndpoints(q.card());@@ -51,9 +63,14 @@ const setupQuestion = ({ id, name, hasAccess }) => {}return card;+}++type SetupOptions = {+ questionId: CardId;+ hasAccess: boolean;};-const setup = ({ questionId, hasAccess }) => {+function setup({ questionId, hasAccess }: SetupOptions) {if (hasAccess) {setupDatabaseEndpoints(databaseMock);} else {@@ -73,7 +90,7 @@ const setup = ({ questionId, hasAccess }) => {);return { rerender, card };-};+}describe("SavedQuestionLoader", () => {beforeEach(() => {diff --git a/frontend/src/metabase/lib/collections.ts b/frontend/src/metabase/lib/collections.tsindex df4b797897a..edb399c4e86 100644--- a/frontend/src/metabase/lib/collections.ts+++ b/frontend/src/metabase/lib/collections.ts@@ -1,29 +1,36 @@import { t } from "ttag";+import type { Crumb } from "metabase/common/components/Breadcrumbs";import { isNotNull } from "metabase/lib/types";import type { Collection, CollectionId } from "metabase-types/api";export const getCrumbs = (- collection: Collection,+ collection: Collection | undefined,collectionsById: Partial<Record<CollectionId, Collection>>,callback: (id: CollectionId) => void,-) => {- if (collection && collection.path) {+): Crumb[] => {+ if (collection?.path) {return [...collection.path.map((id) => collectionsById[id]).filter(isNotNull)- .map((collection) => [collection.name, () => callback(collection.id)]),+ .map(+ (collection): Crumb => [+ collection.name,+ () => callback(collection.id),+ ],+ ),[collection.name],];- } else {- const rootCollection = collectionsById.root;+ }- return [- ...(rootCollection- ? [[rootCollection.name, () => callback(rootCollection.id)]]- : []),- [t`Unknown`],- ];+ const rootCollection = collectionsById.root;+ if (!rootCollection) {+ return [[t`Unknown`]];}++ return [+ [rootCollection.name, () => callback(rootCollection.id)],+ [t`Unknown`],+ ];};diff --git a/frontend/src/metabase/lib/collections.unit.spec.ts b/frontend/src/metabase/lib/collections.unit.spec.tsindex 3d13ca489da..aa819d42a28 100644--- a/frontend/src/metabase/lib/collections.unit.spec.ts+++ b/frontend/src/metabase/lib/collections.unit.spec.ts@@ -1,7 +1,20 @@+import type { Crumb } from "metabase/common/components/Breadcrumbs";import { createMockCollection } from "metabase-types/api/mocks";import { getCrumbs } from "./collections";+const getCrumbAction = (crumb: Crumb) => {+ if (+ !Array.isArray(crumb) ||+ crumb.length < 2 ||+ typeof crumb[1] !== "function"+ ) {+ throw new Error("Expected crumb callback action");+ }++ return crumb[1];+};+const collectionsById = {root: createMockCollection({ id: "root", name: "Our analytics", path: [] }),1: createMockCollection({ id: 1, name: "parent", path: ["root"] }),@@ -23,12 +36,14 @@ describe("getCrumbs", () => {const callbackMock = jest.fn();const crumbs = getCrumbs(collectionsById[2], collectionsById, callbackMock);- const [_rootName, rootCallback] = crumbs[0];- (rootCallback as any)();+ const rootCallback = getCrumbAction(crumbs[0]);+ // Workaround to simulate actual event object passed by React, impossible to construct.+ rootCallback(undefined as never);expect(callbackMock).toHaveBeenCalledWith("root");- const [_parentName, parentCallback] = crumbs[1];- (parentCallback as any)();+ const parentCallback = getCrumbAction(crumbs[1]);+ // Workaround to simulate actual event object passed by React, impossible to construct.+ parentCallback(undefined as never);expect(callbackMock).toHaveBeenCalledWith(1);});});