Skip to content

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

convert dashboard redux related files to typescript (#69797)

Uladzimir Havenchykcc1361936a65
diff --git a/frontend/src/metabase/dashboard/components/ClickMappings.jsx b/frontend/src/metabase/dashboard/components/ClickMappings.jsx
deleted file mode 100644
index ae2fdcade93..00000000000
--- a/frontend/src/metabase/dashboard/components/ClickMappings.jsx
+++ /dev/null
@@ -1,382 +0,0 @@
-/* eslint-disable react/prop-types */
-import cx from "classnames";
-import { assocIn, dissocIn, getIn } from "icepick";
-import { Component } from "react";
-import { t } from "ttag";
-import _ from "underscore";
-
-import { Select } from "metabase/common/components/Select";
-import CS from "metabase/css/core/index.css";
-import { getDashcardData, getParameters } from "metabase/dashboard/selectors";
-import { isPivotGroupColumn } from "metabase/lib/data_grid";
-import { connect } from "metabase/lib/redux";
-import MetabaseSettings from "metabase/lib/settings";
-import { loadMetadataForCard } from "metabase/questions/actions";
-import { getMetadata } from "metabase/selectors/metadata";
-import { GTAPApi } from "metabase/services";
-import { Flex, Icon } from "metabase/ui";
-import * as Lib from "metabase-lib";
-import Question from "metabase-lib/v1/Question";
-import {
- getTargetsForDashboard,
- getTargetsForQuestion,
-} from "metabase-lib/v1/parameters/utils/click-behavior";
-
-import S from "./ClickMappings.module.css";
-
-class ClickMappings extends Component {
- render() {
- const { setTargets, unsetTargets, question } = this.props;
- const sourceOptions = {
- ...this.props.sourceOptions,
- userAttribute: this.props.userAttributes,
- };
-
- const unsetTargetsWithSourceOptions = _.chain(unsetTargets)
- .map((target) => ({
- target,
- sourceOptions: _.chain(sourceOptions)
- .mapObject((sources, sourceType) =>
- sources
- .filter((source) => {
- const sourceFilter = target.sourceFilters[sourceType];
-
- return sourceFilter(source, question);
- })
- .map(getSourceOption[sourceType]),
- )
- .pairs()
- .filter(([, sources]) => sources.length > 0)
- .object()
- .value(),
- }))
- .filter(({ sourceOptions }) => Object.keys(sourceOptions).length > 0)
- .value();
-
- if (unsetTargetsWithSourceOptions.length === 0 && setTargets.length === 0) {
- return (
- <p
- className={cx(CS.textCentered, CS.textMedium)}
- >{t`No available targets`}</p>
- );
- }
- return (
- <div data-testid="click-mappings">
- <div>
- {setTargets.map((target) => {
- return (
- <TargetWithSource
- key={target.id}
- targetName={this.getTargetName()}
- target={target}
- {...this.props}
- />
- );
- })}
- </div>
- {unsetTargetsWithSourceOptions.length > 0 && (
- <div>
- <p className={cx(CS.mb2, CS.textMedium)}>
- {this.getTargetsHeading(setTargets)}
- </p>
- <div data-testid="unset-click-mappings">
- {unsetTargetsWithSourceOptions.map(
- ({ target, sourceOptions }) => (
- <TargetWithoutSource
- key={target.id}
- target={target}
- {...this.props}
- sourceOptions={sourceOptions}
- />
- ),
- )}
- </div>
- </div>
- )}
- </div>
- );
- }
-
- getTargetName() {
- const objectType = clickTargetObjectType(this.props.object);
- return { dashboard: t`filter`, native: t`variable`, gui: t`column` }[
- objectType
- ];
- }
-
- getTargetsHeading(setTargets) {
- const objectType = clickTargetObjectType(this.props.object);
- if (objectType === "dashboard") {
- return setTargets.length > 0
- ? t`Other available filters`
- : t`Available filters`;
- }
- if (objectType === "native") {
- return setTargets.length > 0
- ? t`Other available variables`
- : t`Available variables`;
- }
- if (objectType === "gui") {
- return setTargets.length > 0
- ? t`Other available columns`
- : t`Available columns`;
- }
- return "Unknown";
- }
-}
-
-export const ClickMappingsConnected = _.compose(
- loadQuestionMetadata((state, props) =>
- props.isDashboard ? null : props.object,
- ),
- withUserAttributes,
- connect((state, props) => {
- const { object, isDashboard, dashcard, clickBehavior } = props;
- let parameters = getParameters(state, props);
- const metadata = getMetadata(state);
- const dashcardData = getDashcardData(state, dashcard.id);
- const question = new Question(dashcard.card, metadata);
-
- if (props.excludeParametersSources) {
- // Remove parameters as possible sources.
- // We still include any that were already in use prior to this code change.
- const parametersUsedAsSources = Object.values(
- clickBehavior.parameterMapping || {},
- )
- .filter((mapping) => getIn(mapping, ["source", "type"]) === "parameter")
- .map((mapping) => mapping.source.id);
- parameters = parameters.filter((p) => {
- return parametersUsedAsSources.includes(p.id);
- });
- }
-
- const [setTargets, unsetTargets] = _.partition(
- isDashboard
- ? getTargetsForDashboard(object, dashcard)
- : getTargetsForQuestion(object),
- ({ id }) =>
- getIn(clickBehavior, ["parameterMapping", id, "source"]) != null,
- );
-
- const availableColumns =
- Object.values(dashcardData).flatMap((dataset) => dataset.data.cols) ?? [];
-
- const sourceOptions = {
- column: availableColumns.filter(isMappableColumn),
- parameter: parameters,
- };
- return { setTargets, unsetTargets, sourceOptions, question };
- }),
-)(ClickMappings);
-
-const getKeyForSource = (o) => (o.type == null ? null : `${o.type}-${o.id}`);
-const getSourceOption = {
- column: (c) => ({ type: "column", id: c.name, name: c.display_name }),
- parameter: (p) => ({ type: "parameter", id: p.id, name: p.name }),
- userAttribute: (name) => ({ type: "userAttribute", name, id: name }),
-};
-
-function TargetWithoutSource({
- target,
- sourceOptions,
- clickBehavior,
- updateSettings,
-}) {
- const { id, name, type } = target;
-
- return (
- <Select
- key={id}
- triggerElement={
- <Flex
- className={S.TargetTrigger}
- p="sm"
- mb="sm"
- fw="bold"
- w="100%"
- data-testid="click-target-column"
- >
- {name}
- </Flex>
- }
- value={null}
- sections={Object.entries(sourceOptions).map(([sourceType, items]) => ({
- name: {
- parameter: t`Dashboard filters`,
- column: t`Columns`,
- userAttribute: t`User attributes`,
- }[sourceType],
- items,
- }))}
- optionValueFn={getKeyForSource}
- optionNameFn={(o) => (o.type == null ? t`None` : o.name)}
- onChange={({ target: { value } }) => {
- updateSettings(
- assocIn(clickBehavior, ["parameterMapping", id], {
- source: Object.values(sourceOptions)
- .flat()
- .find((o) => getKeyForSource(o) === value),
- target: target.target,
- id,
- type,
- }),
- );
- }}
- />
- );
-}
-
-function TargetWithSource({
- target,
- targetName,
- clickBehavior,
- updateSettings,
-}) {
- const { name, id } = target;
- const source =
- getIn(clickBehavior, ["parameterMapping", id, "source"]) || null;
- return (
- <div className={CS.mb2}>
- <div
- className={cx(
- CS.bordered,
- CS.rounded,
- CS.p2,
- CS.textMedium,
- CS.flex,
- CS.alignCenter,
- )}
- // eslint-disable-next-line metabase/no-color-literals
- style={{ borderColor: "#E2E4E8" }}
- >
- <svg
- width="12"
- height="38"
- viewBox="0 0 12 38"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- style={{ marginLeft: 8, marginRight: 8 }}
- >
- <g opacity="0.6">
- <path
- d="M9 32C9 33.6569 7.65685 35 6 35C4.34315 35 3 33.6569 3 32C3 30.3431 4.34315 29 6 29C7.65685 29 9 30.3431 9 32Z"
- // eslint-disable-next-line metabase/no-color-literals
- fill="#509EE3"
- />
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M12 6C12 8.973 9.83771 11.441 7 11.917V26.083C9.83771 26.559 12 29.027 12 32C12 35.3137 9.31371 38 6 38C2.68629 38 0 35.3137 0 32C0 29.027 2.16229 26.559 5 26.083V11.917C2.16229 11.441 0 8.973 0 6C0 2.68629 2.68629 0 6 0C9.31371 0 12 2.68629 12 6ZM6 10C8.20914 10 10 8.20914 10 6C10 3.79086 8.20914 2 6 2C3.79086 2 2 3.79086 2 6C2 8.20914 3.79086 10 6 10ZM6 36C8.20914 36 10 34.2091 10 32C10 29.7909 8.20914 28 6 28C3.79086 28 2 29.7909 2 32C2 34.2091 3.79086 36 6 36Z"
- // eslint-disable-next-line metabase/no-color-literals
- fill="#509EE3"
- />
- </g>
- </svg>
- <div>
- <div>
- <span className={cx(CS.textBold, CS.textDark)}>{source.name}</span>{" "}
- {
- {
- column: t`column`,
- parameter: t`filter`,
- userAttribute: t`user attribute`,
- }[source.type]
- }
- </div>
- <div style={{ marginTop: 9 }}>
- <span className={cx(CS.textBrand, CS.textBold)}>{name}</span>{" "}
- {targetName}
- </div>
- </div>
- <div
- className={cx(CS.cursorPointer, CS.mlAuto)}
- onClick={() =>
- updateSettings(dissocIn(clickBehavior, ["parameterMapping", id]))
- }
- >
- <Icon name="close" size={12} />
- </div>
- </div>
- </div>
- );
-}
-
-/**
- * TODO: Extract this to a more general HOC. It can probably also take care of withTableMetadataLoaded.
- *
- * @deprecated HOCs are deprecated
- */
-function loadQuestionMetadata(getQuestion) {
- return (ComposedComponent) => {
- class MetadataLoader extends Component {
- componentDidMount() {
- if (this.props.question) {
- this.fetch();
- }
- }
-
- componentDidUpdate({ question: prevQuestion }) {
- const { question } = this.props;
- if (question != null && question.id !== (prevQuestion || {}).id) {
- this.fetch();
- }
- }
-
- fetch() {
- const { question, loadMetadataForCard } = this.props;
- if (question) {
- loadMetadataForCard(question.card());
- }
- }
-
- render() {
- const { question, metadata, ...rest } = this.props;
- return <ComposedComponent {...rest} />;
- }
- }
-
- return connect(
- (state, props) => ({
- question: getQuestion && getQuestion(state, props),
- }),
- { loadMetadataForCard },
- )(MetadataLoader);
- };
-}
-
-export function withUserAttributes(ComposedComponent) {
- return class WithUserAttributes extends Component {
- state = { userAttributes: [] };
-
- async componentDidMount() {
- if (MetabaseSettings.sandboxingEnabled()) {
- this.setState({ userAttributes: await GTAPApi.attributes() });
- }
- }
-
- render() {
- return (
- <ComposedComponent
- {...this.props}
- userAttributes={this.state.userAttributes}
- />
- );
- }
- };
-}
-
-export function isMappableColumn(column) {
- // Pivot tables have a column in the result set that shouldn't be displayed.
- return !isPivotGroupColumn(column);
-}
-
-export function clickTargetObjectType(object) {
- if (!(object instanceof Question)) {
- return "dashboard";
- }
-
- const query = object.query();
- const { isNative } = Lib.queryDisplayInfo(query);
-
- return isNative ? "native" : "gui";
-}
diff --git a/frontend/src/metabase/dashboard/components/ClickMappings.tsx b/frontend/src/metabase/dashboard/components/ClickMappings.tsx
new file mode 100644
index 00000000000..feb07fe9d75
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/ClickMappings.tsx
@@ -0,0 +1,548 @@
+import cx from "classnames";
+import { assocIn, dissocIn, getIn } from "icepick";
+import type { ComponentType } from "react";
+import { useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { Select } from "metabase/common/components/Select";
+import CS from "metabase/css/core/index.css";
+import { getDashcardData, getParameters } from "metabase/dashboard/selectors";
+import { isQuestionDashCard } from "metabase/dashboard/utils";
+import { isPivotGroupColumn } from "metabase/lib/data_grid";
+import { connect } from "metabase/lib/redux";
+import MetabaseSettings from "metabase/lib/settings";
+import { loadMetadataForCard } from "metabase/questions/actions";
+import { getMetadata } from "metabase/selectors/metadata";
+import { GTAPApi } from "metabase/services";
+import { Flex, Icon } from "metabase/ui";
+import * as Lib from "metabase-lib";
+import Question from "metabase-lib/v1/Question";
+import type Metadata from "metabase-lib/v1/metadata/Metadata";
+import {
+ getTargetsForDashboard,
+ getTargetsForQuestion,
+} from "metabase-lib/v1/parameters/utils/click-behavior";
+import type {
+ ClickBehavior,
+ ClickBehaviorParameterMapping,
+ ClickBehaviorTarget,
+ Dashboard,
+ DashboardCard,
+ DatasetColumn,
+ Parameter,
+} from "metabase-types/api";
+import type { State } from "metabase-types/store";
+
+import S from "./ClickMappings.module.css";
+
+type SourceType = "column" | "parameter" | "userAttribute";
+
+type SourceOption = {
+ type?: SourceType;
+ id?: string;
+ name?: string;
+};
+
+type SourceOptionsByType = Partial<Record<SourceType, SourceOption[]>>;
+
+type TargetItem = {
+ id: string;
+ name: string | null | undefined;
+ target: ClickBehaviorTarget;
+ sourceFilters: {
+ column: (source: DatasetColumn, question: Question) => boolean;
+ parameter: (source: Parameter, question: Question) => boolean;
+ userAttribute: (source: string, question: Question) => boolean;
+ };
+ type?: ClickBehaviorTarget["type"];
+};
+
+type ClickMappingsOwnProps = {
+ object: Dashboard | Question | undefined;
+ dashcard: DashboardCard;
+ isDashboard?: boolean;
+ clickBehavior: ClickBehavior;
+ updateSettings: (settings: Partial<ClickBehavior>) => void;
+ excludeParametersSources?: boolean;
+};
+
+type ClickMappingsStateProps = {
+ setTargets: TargetItem[];
+ unsetTargets: TargetItem[];
+ sourceOptions: {
+ column: DatasetColumn[];
+ parameter: Parameter[];
+ };
+ question: Question;
+};
+
+type ClickMappingsHocProps = {
+ userAttributes: string[];
+};
+
+type ClickMappingsProps = ClickMappingsOwnProps &
+ ClickMappingsStateProps &
+ ClickMappingsHocProps;
+
+function getTargetName(object: Dashboard | Question | undefined) {
+ const objectType = clickTargetObjectType(object);
+ return { dashboard: t`filter`, native: t`variable`, gui: t`column` }[
+ objectType
+ ];
+}
+
+function getTargetsHeading(
+ object: Dashboard | Question | undefined,
+ setTargets: TargetItem[],
+) {
+ const objectType = clickTargetObjectType(object);
+ if (objectType === "dashboard") {
+ return setTargets.length > 0
+ ? t`Other available filters`
+ : t`Available filters`;
+ }
+ if (objectType === "native") {
+ return setTargets.length > 0
+ ? t`Other available variables`
+ : t`Available variables`;
+ }
+ if (objectType === "gui") {
+ return setTargets.length > 0
+ ? t`Other available columns`
+ : t`Available columns`;
+ }
+ return "Unknown";
+}
+
+function ClickMappings(props: ClickMappingsProps) {
+ const { setTargets, unsetTargets, question } = props;
+
+ const sourceOptions: {
+ column: DatasetColumn[];
+ parameter: Parameter[];
+ userAttribute: string[];
+ } = useMemo(
+ () => ({
+ ...props.sourceOptions,
+ userAttribute: props.userAttributes,
+ }),
+ [props.sourceOptions, props.userAttributes],
+ );
+
+ const unsetTargetsWithSourceOptions = useMemo(
+ () =>
+ unsetTargets
+ .map((target: TargetItem) => {
+ const targetSourceOptions: SourceOptionsByType = {};
+
+ const columnOptions = sourceOptions.column
+ .filter((column) => target.sourceFilters.column(column, question))
+ .map(getSourceOption.column);
+ if (columnOptions.length > 0) {
+ targetSourceOptions.column = columnOptions;
+ }
+
+ const parameterOptions = sourceOptions.parameter
+ .filter((parameter) =>
+ target.sourceFilters.parameter(parameter, question),
+ )
+ .map(getSourceOption.parameter);
+ if (parameterOptions.length > 0) {
+ targetSourceOptions.parameter = parameterOptions;
+ }
+
+ const userAttributeOptions = sourceOptions.userAttribute
+ .filter((name) =>
+ target.sourceFilters.userAttribute(name, question),
+ )
+ .map(getSourceOption.userAttribute);
+ if (userAttributeOptions.length > 0) {
+ targetSourceOptions.userAttribute = userAttributeOptions;
+ }
+
+ return {
+ target,
+ sourceOptions: targetSourceOptions,
+ };
+ })
+ .filter(
+ ({ sourceOptions }: { sourceOptions: SourceOptionsByType }) =>
+ Object.keys(sourceOptions).length > 0,
+ ),
+ [question, sourceOptions, unsetTargets],
+ );
+
+ if (unsetTargetsWithSourceOptions.length === 0 && setTargets.length === 0) {
+ return (
+ <p
+ className={cx(CS.textCentered, CS.textMedium)}
+ >{t`No available targets`}</p>
+ );
+ }
+
+ return (
+ <div data-testid="click-mappings">
+ <div>
+ {setTargets.map((target) => (
+ <TargetWithSource
+ key={target.id}
+ targetName={getTargetName(props.object)}
+ target={target}
+ clickBehavior={props.clickBehavior}
+ updateSettings={props.updateSettings}
+ />
+ ))}
+ </div>
+ {unsetTargetsWithSourceOptions.length > 0 && (
+ <div>
+ <p className={cx(CS.mb2, CS.textMedium)}>
+ {getTargetsHeading(props.object, setTargets)}
+ </p>
+ <div data-testid="unset-click-mappings">
+ {unsetTargetsWithSourceOptions.map(
+ ({
+ target,
+ sourceOptions,
+ }: {
+ target: TargetItem;
+ sourceOptions: SourceOptionsByType;
+ }) => (
+ <TargetWithoutSource
+ key={target.id}
+ target={target}
+ clickBehavior={props.clickBehavior}
+ updateSettings={props.updateSettings}
+ sourceOptions={sourceOptions}
+ />
+ ),
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export const ClickMappingsConnected = _.compose(
+ loadQuestionMetadata((_state: State, props: ClickMappingsOwnProps) =>
+ props.object instanceof Question && !props.isDashboard
+ ? props.object
+ : null,
+ ),
+ withUserAttributes,
+ connect(
+ (state: State, props: ClickMappingsOwnProps & ClickMappingsHocProps) => {
+ const { object, isDashboard, dashcard, clickBehavior } = props;
+ let parameters = getParameters(state);
+ const metadata = getMetadata(state);
+ const dashcardData = getDashcardData(state, dashcard.id);
+ const question = new Question(dashcard.card, metadata);
+
+ if (props.excludeParametersSources) {
+ const parameterMapping: ClickBehaviorParameterMapping =
+ clickBehavior.type === "crossfilter" ||
+ (clickBehavior.type === "link" &&
+ (clickBehavior.linkType === "dashboard" ||
+ clickBehavior.linkType === "question"))
+ ? (clickBehavior.parameterMapping ?? {})
+ : {};
+
+ const parametersUsedAsSources = Object.values(parameterMapping)
+ .filter(
+ (mapping) => getIn(mapping, ["source", "type"]) === "parameter",
+ )
+ .map((mapping) => mapping.source.id);
+
+ parameters = parameters.filter((parameter) => {
+ return parametersUsedAsSources.includes(parameter.id);
+ });
+ }
+
+ const [setTargets, unsetTargets] = _.partition(
+ isDashboard &&
+ object &&
+ !(object instanceof Question) &&
+ isQuestionDashCard(dashcard)
+ ? getTargetsForDashboard(object, dashcard)
+ : object instanceof Question
+ ? getTargetsForQuestion(object)
+ : [],
+ ({ id }: { id: string }) =>
+ getIn(clickBehavior, ["parameterMapping", id, "source"]) != null,
+ );
+
+ const availableColumns: DatasetColumn[] = Object.values(
+ dashcardData ?? {},
+ ).flatMap((dataset) => {
+ if (!dataset || typeof dataset !== "object") {
+ return [];
+ }
+ const cols = getIn(dataset, ["data", "cols"]);
+ return Array.isArray(cols) ? cols : [];
+ });
+
+ const sourceOptions = {
+ column: availableColumns.filter(isMappableColumn),
+ parameter: parameters,
+ };
+
+ return { setTargets, unsetTargets, sourceOptions, question };
+ },
+ ),
+)(ClickMappings);
+
+const getKeyForSource = (option: SourceOption) =>
+ option.type == null ? null : `${option.type}-${option.id}`;
+
+const getSourceOption = {
+ column: (column: DatasetColumn): SourceOption => ({
+ type: "column",
+ id: column.name,
+ name: column.display_name,
+ }),
+ parameter: (parameter: Parameter): SourceOption => ({
+ type: "parameter",
+ id: parameter.id,
+ name: parameter.name,
+ }),
+ userAttribute: (name: string): SourceOption => ({
+ type: "userAttribute",
+ name: name,
+ id: name,
+ }),
+};
+
+function TargetWithoutSource({
+ target,
+ sourceOptions,
+ clickBehavior,
+ updateSettings,
+}: {
+ target: TargetItem;
+ sourceOptions: SourceOptionsByType;
+ clickBehavior: ClickBehavior;
+ updateSettings: (settings: Partial<ClickBehavior>) => void;
+}) {
+ const { id, name, type } = target;
+
+ return (
+ <Select
+ key={id}
+ triggerElement={
+ <Flex
+ className={S.TargetTrigger}
+ p="sm"
+ mb="sm"
+ fw="bold"
+ w="100%"
+ data-testid="click-target-column"
+ >
+ {name}
+ </Flex>
+ }
+ value={null}
+ sections={Object.entries(sourceOptions).map(([sourceType, items]) => ({
+ name: {
+ parameter: t`Dashboard filters`,
+ column: t`Columns`,
+ userAttribute: t`User attributes`,
+ }[sourceType],
+ items,
+ }))}
+ optionValueFn={getKeyForSource}
+ optionNameFn={(option: SourceOption) =>
+ option.type == null ? t`None` : option.name
+ }
+ onChange={({ target: { value } }: { target: { value: string } }) => {
+ updateSettings(
+ assocIn(clickBehavior, ["parameterMapping", id], {
+ source: Object.values(sourceOptions)
+ .flat()
+ .find((option) => getKeyForSource(option) === value),
+ target: target.target,
+ id,
+ type,
+ }),
+ );
+ }}
+ />
+ );
+}
+
+function TargetWithSource({
+ target,
+ targetName,
+ clickBehavior,
+ updateSettings,
+}: {
+ target: TargetItem;
+ targetName: string | undefined;
+ clickBehavior: ClickBehavior;
+ updateSettings: (settings: Partial<ClickBehavior>) => void;
+}) {
+ const { name, id } = target;
+ const source: { name?: string; type?: SourceType } =
+ getIn(clickBehavior, ["parameterMapping", id, "source"]) ?? {};
+
+ return (
+ <div className={CS.mb2}>
+ <div
+ className={cx(
+ CS.bordered,
+ CS.rounded,
+ CS.p2,
+ CS.textMedium,
+ CS.flex,
+ CS.alignCenter,
+ )}
+ // eslint-disable-next-line metabase/no-color-literals
+ style={{ borderColor: "#E2E4E8" }}
+ >
+ <svg
+ width="12"
+ height="38"
+ viewBox="0 0 12 38"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ style={{ marginLeft: 8, marginRight: 8 }}
+ >
+ <g opacity="0.6">
+ <path
+ d="M9 32C9 33.6569 7.65685 35 6 35C4.34315 35 3 33.6569 3 32C3 30.3431 4.34315 29 6 29C7.65685 29 9 30.3431 9 32Z"
+ // eslint-disable-next-line metabase/no-color-literals
+ fill="#509EE3"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M12 6C12 8.973 9.83771 11.441 7 11.917V26.083C9.83771 26.559 12 29.027 12 32C12 35.3137 9.31371 38 6 38C2.68629 38 0 35.3137 0 32C0 29.027 2.16229 26.559 5 26.083V11.917C2.16229 11.441 0 8.973 0 6C0 2.68629 2.68629 0 6 0C9.31371 0 12 2.68629 12 6ZM6 10C8.20914 10 10 8.20914 10 6C10 3.79086 8.20914 2 6 2C3.79086 2 2 3.79086 2 6C2 8.20914 3.79086 10 6 10ZM6 36C8.20914 36 10 34.2091 10 32C10 29.7909 8.20914 28 6 28C3.79086 28 2 29.7909 2 32C2 34.2091 3.79086 36 6 36Z"
+ // eslint-disable-next-line metabase/no-color-literals
+ fill="#509EE3"
+ />
+ </g>
+ </svg>
+ <div>
+ <div>
+ <span className={cx(CS.textBold, CS.textDark)}>{source.name}</span>{" "}
+ {source.type != null &&
+ {
+ column: t`column`,
+ parameter: t`filter`,
+ userAttribute: t`user attribute`,
+ }[source.type]}
+ </div>
+ <div style={{ marginTop: 9 }}>
+ <span className={cx(CS.textBrand, CS.textBold)}>{name}</span>{" "}
+ {targetName}
+ </div>
+ </div>
+ <div
+ className={cx(CS.cursorPointer, CS.mlAuto)}
+ onClick={() =>
+ updateSettings(dissocIn(clickBehavior, ["parameterMapping", id]))
+ }
+ >
+ <Icon name="close" size={12} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * TODO: Extract this to a more general HOC. It can probably also take care of withTableMetadataLoaded.
+ *
+ * @deprecated HOCs are deprecated
+ */
+function loadQuestionMetadata(
+ getQuestion: (
+ state: State,
+ props: ClickMappingsOwnProps,
+ ) => Question | null | undefined,
+) {
+ type ComposedProps = Record<string, unknown>;
+
+ return (ComposedComponent: ComponentType<ComposedProps>) => {
+ interface MetadataLoaderProps {
+ question?: Question | null;
+ metadata?: Metadata;
+ loadMetadataForCard: (
+ ...args: Parameters<typeof loadMetadataForCard>
+ ) => Promise<unknown>;
+ }
+
+ function MetadataLoader(props: MetadataLoaderProps) {
+ const { question, loadMetadataForCard, ...rest } = props;
+
+ useEffect(() => {
+ if (question instanceof Question) {
+ loadMetadataForCard(question.card());
+ }
+ }, [question, loadMetadataForCard]);
+
+ return <ComposedComponent {...rest} />;
+ }
+
+ return connect(
+ (state: State, props: ClickMappingsOwnProps) => ({
+ question: getQuestion && getQuestion(state, props),
+ }),
+ { loadMetadataForCard },
+ )(MetadataLoader);
+ };
+}
+
+export function withUserAttributes<TProps extends ClickMappingsHocProps>(
+ ComposedComponent: ComponentType<TProps>,
+) {
+ return function WithUserAttributes(
+ props: Omit<TProps, keyof ClickMappingsHocProps>,
+ ) {
+ const [userAttributes, setUserAttributes] = useState<string[]>([]);
+
+ useEffect(() => {
+ let isMounted = true;
+
+ const loadUserAttributes = async () => {
+ if (MetabaseSettings.sandboxingEnabled()) {
+ const attributes = await GTAPApi.attributes();
+ if (isMounted) {
+ setUserAttributes(attributes);
+ }
+ }
+ };
+
+ loadUserAttributes();
+
+ return () => {
+ isMounted = false;
+ };
+ }, []);
+
+ return (
+ <ComposedComponent
+ {...(props as TProps)}
+ userAttributes={userAttributes}
+ />
+ );
+ };
+}
+
+export function isMappableColumn(column: { name: string }) {
+ // Pivot tables have a column in the result set that shouldn't be displayed.
+ return !isPivotGroupColumn(column);
+}
+
+export function clickTargetObjectType(
+ object: Dashboard | Question | undefined,
+): "dashboard" | "native" | "gui" {
+ if (!(object instanceof Question)) {
+ return "dashboard";
+ }
+
+ const query = object.query();
+ const { isNative } = Lib.queryDisplayInfo(query);
+
+ return isNative ? "native" : "gui";
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardCopyModal.jsx b/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
similarity index 53%
rename from frontend/src/metabase/dashboard/components/DashboardCopyModal.jsx
rename to frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
index 8462c1aa48d..6633a0fd3ee 100644
--- a/frontend/src/metabase/dashboard/components/DashboardCopyModal.jsx
+++ b/frontend/src/metabase/dashboard/components/DashboardCopyModal.tsx
@@ -1,26 +1,32 @@
-/* eslint-disable react/prop-types */
import { dissoc } from "icepick";
import { useState } from "react";
-import { withRouter } from "react-router";
+import { type WithRouterProps, withRouter } from "react-router";
import { replace } from "react-router-redux";
import { t } from "ttag";
import _ from "underscore";
+import type { CopyDashboardFormProperties } from "metabase/dashboard/containers/CopyDashboardForm";
import { Collections } from "metabase/entities/collections";
import EntityCopyModal from "metabase/entities/containers/EntityCopyModal";
import { Dashboards } from "metabase/entities/dashboards";
import { connect } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
+import type { Dashboard } from "metabase-types/api";
+import type { State } from "metabase-types/store";
import { getDashboardComplete } from "../selectors";
-const mapStateToProps = (state, props) => {
- const dashboard = getDashboardComplete(state, props);
+type OwnProps = {
+ onClose: () => void;
+};
+
+const mapStateToProps = (state: State, props: OwnProps) => {
+ const dashboard = getDashboardComplete(state);
return {
dashboard,
initialCollectionId: Collections.selectors.getInitialCollectionId(state, {
...props,
- collectionId: dashboard && dashboard.collection_id,
+ collectionId: dashboard?.collection_id,
}),
};
};
@@ -30,14 +36,25 @@ const mapDispatchToProps = {
onReplaceLocation: replace,
};
-const getTitle = (dashboard, isShallowCopy) => {
+type StateProps = ReturnType<typeof mapStateToProps>;
+type DispatchProps = typeof mapDispatchToProps;
+
+type DashboardCopyModalProps = OwnProps &
+ StateProps &
+ DispatchProps &
+ WithRouterProps;
+
+const getTitle = (
+ dashboard: Dashboard | null,
+ isShallowCopy: boolean,
+): string => {
if (!dashboard?.name) {
return "";
- } else if (isShallowCopy) {
- return t`Duplicate "${dashboard.name}"`;
- } else {
- return t`Duplicate "${dashboard.name}" and its questions`;
}
+
+ return isShallowCopy
+ ? t`Duplicate "${dashboard.name}"`
+ : t`Duplicate "${dashboard.name}" and its questions`;
};
const DashboardCopyModal = ({
@@ -47,15 +64,19 @@ const DashboardCopyModal = ({
dashboard,
initialCollectionId,
params,
- ...props
-}) => {
+}: DashboardCopyModalProps) => {
const [isShallowCopy, setIsShallowCopy] = useState(true);
- const dashboardIdFromSlug = Urls.extractEntityId(params.slug);
+ const dashboardIdFromSlug = Urls.extractEntityId(params?.slug);
const title = getTitle(dashboard, isShallowCopy);
- const handleValuesChange = ({ is_shallow_copy }) => {
- setIsShallowCopy(is_shallow_copy);
+ const handleValuesChange = (values: CopyDashboardFormProperties) => {
+ if (
+ "is_shallow_copy" in values &&
+ typeof values.is_shallow_copy === "boolean"
+ ) {
+ setIsShallowCopy(values.is_shallow_copy);
+ }
};
return (
@@ -67,12 +88,13 @@ const DashboardCopyModal = ({
}}
title={title}
overwriteOnInitialValuesChange
- copy={async (object) =>
+ copy={async (object: Record<string, unknown>) =>
await copyDashboard({ id: dashboardIdFromSlug }, dissoc(object, "id"))
}
onClose={onClose}
- onSaved={(dashboard) => onReplaceLocation(Urls.dashboard(dashboard))}
- {...props}
+ onSaved={(savedDashboard: Dashboard) =>
+ onReplaceLocation(Urls.dashboard(savedDashboard))
+ }
onValuesChange={handleValuesChange}
/>
);
diff --git a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.jsx b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.jsx
deleted file mode 100644
index c2f9133cfda..00000000000
--- a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.jsx
+++ /dev/null
@@ -1,77 +0,0 @@
-/* eslint-disable react/prop-types */
-import PropTypes from "prop-types";
-import { Component } from "react";
-import { withRouter } from "react-router";
-import { push } from "react-router-redux";
-import { t } from "ttag";
-import _ from "underscore";
-
-import { ArchiveModal } from "metabase/common/components/ArchiveModal";
-import { setArchivedDashboard } from "metabase/dashboard/actions";
-import { Collections } from "metabase/entities/collections";
-import { Dashboards } from "metabase/entities/dashboards";
-import { connect } from "metabase/lib/redux";
-import * as Urls from "metabase/lib/urls";
-
-const mapDispatchToProps = (dispatch) => ({
- setDashboardArchived: () => dispatch(setArchivedDashboard(true)),
- push: (path) => dispatch(push(path)),
-});
-
-class ArchiveDashboardModal extends Component {
- static propTypes = {
- onClose: PropTypes.func,
- };
-
- constructor(props) {
- super(props);
- this.state = { loading: false };
- }
-
- archive = async () => {
- const dashboardId = Urls.extractEntityId(this.props.params.slug);
- this.setState({ loading: true });
- await this.props.setDashboardArchived(dashboardId);
- this.setState({ loading: false });
- };
-
- render() {
- const { dashboard } = this.props;
-
- const hasDashboardQuestions = dashboard.dashcards
- .filter((dc) => dc.card) // card might be null for virtual cards
- .some((dc) => _.isNumber(dc.card.dashboard_id));
-
- const message = hasDashboardQuestions
- ? t`This will trash the dashboard and the questions that are saved in it. Are you sure you want to do this?`
- : t`Are you sure you want to do this?`;
-
- return (
- <ArchiveModal
- title={
- dashboard.is_app_age
- ? t`Move this page to trash?`
- : t`Move this dashboard to trash?`
- }
- model="dashboard"
- modelId={dashboard?.id}
- message={message}
- onClose={this.props.onClose}
- isLoading={this.state.loading}
- onArchive={this.archive}
- />
- );
- }
-}
-
-export const ArchiveDashboardModalConnected = _.compose(
- connect(null, mapDispatchToProps),
- Dashboards.load({
- id: (state, props) => Urls.extractCollectionId(props.params.slug),
- }),
- Collections.load({
- id: (state, props) => props.dashboard && props.dashboard.collection_id,
- loadingAndErrorWrapper: false,
- }),
- withRouter,
-)(ArchiveDashboardModal);
diff --git a/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx
new file mode 100644
index 00000000000..b9de449a56a
--- /dev/null
+++ b/frontend/src/metabase/dashboard/containers/ArchiveDashboardModal.tsx
@@ -0,0 +1,71 @@
+import { useState } from "react";
+import { type WithRouterProps, withRouter } from "react-router";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { ArchiveModal } from "metabase/common/components/ArchiveModal";
+import { setArchivedDashboard } from "metabase/dashboard/actions";
+import { Collections } from "metabase/entities/collections";
+import { Dashboards } from "metabase/entities/dashboards";
+import { useDispatch } from "metabase/lib/redux";
+import * as Urls from "metabase/lib/urls";
+import type { Dashboard } from "metabase-types/api";
+
+type OwnProps = {
+ onClose: () => void;
+};
+
+type ArchiveDashboardModalProps = OwnProps &
+ WithRouterProps & {
+ dashboard: Dashboard;
+ };
+
+const ArchiveDashboardModal = ({
+ onClose,
+ dashboard,
+}: ArchiveDashboardModalProps) => {
+ const [loading, setLoading] = useState(false);
+ const dispatch = useDispatch();
+
+ const archive = async () => {
+ setLoading(true);
+ try {
+ await dispatch(setArchivedDashboard(true));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const hasDashboardQuestions = dashboard.dashcards
+ .filter((dc) => dc.card) // card might be null for virtual cards
+ .some((dc) => _.isNumber(dc.card.dashboard_id));
+
+ const message = hasDashboardQuestions
+ ? t`This will trash the dashboard and the questions that are saved in it. Are you sure you want to do this?`
+ : t`Are you sure you want to do this?`;
+
+ return (
+ <ArchiveModal
+ title={t`Move this dashboard to trash?`}
+ model="dashboard"
+ modelId={Number(dashboard.id)}
+ message={message}
+ onClose={onClose}
+ isLoading={loading}
+ onArchive={archive}
+ />
+ );
+};
+
+export const ArchiveDashboardModalConnected = _.compose(
+ Dashboards.load({
+ id: (_state: unknown, props: WithRouterProps) =>
+ Urls.extractCollectionId(props.params?.slug),
+ }),
+ Collections.load({
+ id: (_state: unknown, props: { dashboard?: Dashboard }) =>
+ props.dashboard?.collection_id,
+ loadingAndErrorWrapper: false,
+ }),
+ withRouter,
+)(ArchiveDashboardModal);
diff --git a/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.js b/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.js
deleted file mode 100644
index 098b4c0338b..00000000000
--- a/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.js
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useMemo } from "react";
-import _ from "underscore";
-
-import {
- getDashCardById,
- getDashboardComplete,
- getParameterValuesBySlugMap,
- getParameters,
-} from "metabase/dashboard/selectors";
-import { getLinkTargets } from "metabase/lib/click-behavior";
-import { useStore } from "metabase/lib/redux";
-import { getUserAttributes } from "metabase/selectors/user";
-
-function createGetExtraDataForClick(store, dashcardId) {
- return (clicked) => {
- const state = store.getState();
- const dashboard = getDashboardComplete(state);
- const dashcard = getDashCardById(state, dashcardId);
- const parameters = getParameters(state);
- const parameterValuesBySlug = getParameterValuesBySlugMap(state);
- const userAttributes = getUserAttributes(state);
-
- const entitiesByTypeAndId = _.chain(getLinkTargets(clicked.settings))
- .groupBy((target) => target.entity.name)
- .mapObject((targets) =>
- _.chain(targets)
- .map(({ entity, entityType, entityId }) =>
- entityType === "question"
- ? entity.selectors.getObject(state, { entityId })?.card()
- : entity.selectors.getObject(state, { entityId }),
- )
- .filter((object) => object != null)
- .indexBy((object) => object.id)
- .value(),
- )
- .value();
- return {
- ...entitiesByTypeAndId,
- parameters,
- parameterValuesBySlug,
- dashboard,
- dashcard,
- userAttributes,
- };
- };
-}
-
-/**
- * This hook gives access to data referenced in viz settings.
- */
-export const useClickBehaviorData = ({ dashcardId }) => {
- const store = useStore();
-
- const getExtraDataForClick = useMemo(
- () => createGetExtraDataForClick(store, dashcardId),
- [store, dashcardId],
- );
-
- return { getExtraDataForClick };
-};
diff --git a/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts b/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts
new file mode 100644
index 00000000000..96762859a06
--- /dev/null
+++ b/frontend/src/metabase/dashboard/hooks/use-click-behavior-data.ts
@@ -0,0 +1,119 @@
+import { useMemo } from "react";
+import _ from "underscore";
+
+import {
+ getDashCardById,
+ getDashboardComplete,
+ getParameterValuesBySlugMap,
+ getParameters,
+} from "metabase/dashboard/selectors";
+import { getLinkTargets } from "metabase/lib/click-behavior";
+import { useStore } from "metabase/lib/redux";
+import { getUserAttributes } from "metabase/selectors/user";
+import type { ClickObject } from "metabase/visualizations/types";
+import Question from "metabase-lib/v1/Question";
+import type { DashCardId } from "metabase-types/api";
+import type { State } from "metabase-types/store";
+
+type EntityObject = {
+ id: number | string;
+};
+
+type LinkedEntityTarget = {
+ entity: {
+ name: string;
+ selectors: {
+ getObject: (
+ state: State,
+ opts: { entityId: number | string | undefined },
+ ) => unknown;
+ };
+ };
+ entityType: "question" | "dashboard";
+ entityId: number | string | undefined;
+};
+
+function isEntityObject(value: unknown): value is EntityObject {
+ return _.isObject(value) && "id" in value;
+}
+
+function resolveLinkedObject(target: LinkedEntityTarget, state: State) {
+ const object = target.entity.selectors.getObject(state, {
+ entityId: target.entityId,
+ });
+
+ if (target.entityType === "question") {
+ if (object instanceof Question) {
+ const card = object.card();
+ return isEntityObject(card) ? card : null;
+ }
+ return null;
+ }
+
+ return isEntityObject(object) ? object : null;
+}
+
+function getEntitiesByTypeAndId(
+ state: State,
+ clicked: ClickObject | null,
+): Record<string, Record<string | number, EntityObject>> {
+ const targets: LinkedEntityTarget[] = getLinkTargets(clicked?.settings);
+
+ return targets.reduce<Record<string, Record<string | number, EntityObject>>>(
+ (acc, target) => {
+ const linkedObject = resolveLinkedObject(target, state);
+ if (!linkedObject) {
+ return acc;
+ }
+
+ const entityName = target.entity.name;
+ const bucket = acc[entityName] ?? {};
+ bucket[linkedObject.id] = linkedObject;
+ acc[entityName] = bucket;
+ return acc;
+ },
+ {},
+ );
+}
+
+function createGetExtraDataForClick(
+ store: ReturnType<typeof useStore>,
+ dashcardId: DashCardId,
+) {
+ return (clicked: ClickObject | null) => {
+ const state = store.getState();
+ const dashboard = getDashboardComplete(state);
+ const dashcard = getDashCardById(state, dashcardId);
+ const parameters = getParameters(state);
+ const parameterValuesBySlug = getParameterValuesBySlugMap(state);
+ const userAttributes = getUserAttributes(state);
+ const entitiesByTypeAndId = getEntitiesByTypeAndId(state, clicked);
+
+ return {
+ ...entitiesByTypeAndId,
+ parameters,
+ parameterValuesBySlug,
+ dashboard,
+ dashcard,
+ userAttributes,
+ };
+ };
+}
+
+/**
+ * This hook gives access to data referenced in viz settings.
+ */
+export const useClickBehaviorData = ({
+ dashcardId,
+}: {
+ dashcardId: DashCardId;
+}) => {
+ const store = useStore();
+
+ const getExtraDataForClick = useMemo(
+ () => createGetExtraDataForClick(store, dashcardId),
+ [store, dashcardId],
+ );
+
+ return { getExtraDataForClick };
+};
diff --git a/frontend/src/metabase/dashboard/reducers.unit.spec.js b/frontend/src/metabase/dashboard/reducers.unit.spec.ts
similarity index 88%
rename from frontend/src/metabase/dashboard/reducers.unit.spec.js
rename to frontend/src/metabase/dashboard/reducers.unit.spec.ts
index 27cc1988f71..e68e3cfebfb 100644
--- a/frontend/src/metabase/dashboard/reducers.unit.spec.js
+++ b/frontend/src/metabase/dashboard/reducers.unit.spec.ts
@@ -1,4 +1,5 @@
import { createMockDashboard } from "metabase-types/api/mocks";
+import { createMockStoreDashboard } from "metabase-types/store/mocks";
import {
ADD_DASHCARD_IDS_TO_LOADING_QUEUE,
@@ -16,10 +17,10 @@ import { dashboardReducers as reducer } from "./reducers";
const TEST_DASHBOARD = createMockDashboard();
describe("dashboard reducers", () => {
- let initState;
+ let initState: ReturnType<typeof reducer>;
beforeEach(() => {
- initState = reducer(undefined, {});
+ initState = reducer(undefined, { type: "__INIT__" });
});
it("should return the initial state", () => {
@@ -59,11 +60,11 @@ describe("dashboard reducers", () => {
expect(
reducer(undefined, {
type: SET_SIDEBAR,
- payload: { name: "foo", props: { abc: 123 } },
+ payload: { name: "sharing", props: { abc: 123 } },
}),
).toEqual({
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
+ sidebar: { name: "sharing", props: { abc: 123 } },
});
});
@@ -71,11 +72,11 @@ describe("dashboard reducers", () => {
expect(
reducer(undefined, {
type: SET_SIDEBAR,
- payload: { name: "foo" },
+ payload: { name: "sharing" },
}),
).toEqual({
...initState,
- sidebar: { name: "foo", props: {} },
+ sidebar: { name: "sharing", props: {} },
});
});
});
@@ -86,7 +87,7 @@ describe("dashboard reducers", () => {
reducer(
{
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
+ sidebar: { name: "sharing", props: { abc: 123 } },
},
{
type: CLOSE_SIDEBAR,
@@ -102,7 +103,7 @@ describe("dashboard reducers", () => {
reducer(
{
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
+ sidebar: { name: "sharing", props: { abc: 123 } },
},
{
type: INITIALIZE,
@@ -156,8 +157,8 @@ describe("dashboard reducers", () => {
it("should clear sidebar state when entering edit mode", () => {
const state = {
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
- };
+ sidebar: { name: "sharing", props: { abc: 123 } },
+ } satisfies ReturnType<typeof reducer>;
expect(
reducer(state, {
type: SET_EDITING_DASHBOARD,
@@ -173,8 +174,8 @@ describe("dashboard reducers", () => {
it("should clear sidebar state when leaving edit mode", () => {
const state = {
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
- };
+ sidebar: { name: "sharing", props: { abc: 123 } },
+ } satisfies ReturnType<typeof reducer>;
expect(
reducer(state, {
type: SET_EDITING_DASHBOARD,
@@ -190,7 +191,7 @@ describe("dashboard reducers", () => {
reducer(
{
...initState,
- sidebar: { name: "foo", props: { abc: 123 } },
+ sidebar: { name: "sharing", props: { abc: 123 } },
parameterValues: { 123: "abc", 456: "def" },
},
{
@@ -203,26 +204,11 @@ describe("dashboard reducers", () => {
});
describe("SET_DASHBOARD_ATTRIBUTES", () => {
- const emptyDashboard = {
- archived: false,
- dashcards: [],
- can_write: true,
- enable_embedding: false,
- show_in_getting_started: false,
- name: "Dashboard",
- creator_id: 1,
- updated_at: "2021-01-01T01:01:01.001",
+ const emptyDashboard = createMockStoreDashboard({
id: 1,
- "last-edit-info": {
- id: 1,
- email: "[email protected]",
- first_name: "Test",
- last_name: "Metabase",
- timestamp: "2021-01-01T01:01:01.001",
- },
+ dashcards: [],
parameters: [],
- created_at: "2021-01-01T01:01:01.001",
- };
+ });
it("should set attribute and isDirty", () => {
expect(
@@ -296,6 +282,9 @@ describe("dashboard reducers", () => {
...initState,
loadingDashCards: {
loadingIds: dashcardIds,
+ loadingStatus: "idle",
+ startTime: null,
+ endTime: null,
},
},
{
@@ -335,10 +324,11 @@ describe("dashboard reducers", () => {
loadingIds: [3],
loadingStatus: "running",
startTime: 100,
+ endTime: null,
},
},
{
- type: fetchCardDataAction.fulfilled,
+ type: fetchCardDataAction.fulfilled.type,
payload: {
dashcard_id: 3,
card_id: 1,
@@ -367,6 +357,7 @@ describe("dashboard reducers", () => {
loadingIds: [3],
loadingStatus: "running",
startTime: 100,
+ endTime: null,
},
},
{
diff --git a/frontend/src/metabase/dashboard/selectors.unit.spec.js b/frontend/src/metabase/dashboard/selectors.unit.spec.ts
similarity index 89%
rename from frontend/src/metabase/dashboard/selectors.unit.spec.js
rename to frontend/src/metabase/dashboard/selectors.unit.spec.ts
index c9ce6bc4021..02bf169d80e 100644
--- a/frontend/src/metabase/dashboard/selectors.unit.spec.js
+++ b/frontend/src/metabase/dashboard/selectors.unit.spec.ts
@@ -19,52 +19,62 @@ import {
createMockDashboardCard,
createMockField,
createMockHeadingDashboardCard,
+ createMockNativeDatasetQuery,
+ createMockParameter,
+ createMockStructuredDatasetQuery,
} from "metabase-types/api/mocks";
+import type { State } from "metabase-types/store";
import {
+ createMockDashboardState,
createMockSettingsState,
createMockState,
+ createMockStoreDashboard,
} from "metabase-types/store/mocks";
import { SIDEBAR_NAME } from "./constants";
const STATE = createMockState({
- dashboard: {
+ dashboard: createMockDashboardState({
dashboardId: 0,
dashboards: {
- 0: {
+ 0: createMockStoreDashboard({
+ id: 0,
dashcards: [0, 1, 2],
parameters: [],
- },
+ }),
},
dashcards: {
0: createMockDashboardCard({
card: createMockCard({
id: 0,
- dataset_query: {
- type: "native",
- query: {
+ dataset_query: createMockNativeDatasetQuery({
+ native: {
+ query: "",
"template-tags": {
foo: {
+ id: "foo",
type: "text",
+ name: "foo",
+ "display-name": "foo",
},
},
},
- },
+ }),
}),
parameter_mappings: [],
}),
1: createMockDashboardCard({
card: createMockCard({
id: 1,
- dataset_query: { type: "query", query: {} },
+ dataset_query: createMockStructuredDatasetQuery({ query: {} }),
}),
parameter_mappings: [],
}),
2: createMockHeadingDashboardCard(),
},
editingDashboard: createMockDashboard({ id: 0 }),
- sidebar: {},
- },
+ sidebar: { props: {} },
+ }),
entities: createMockEntitiesState({
fields: [createMockField({ id: 1 }), createMockField({ id: 2 })],
}),
@@ -234,7 +244,7 @@ describe("dashboard/selectors", () => {
0: {
...STATE.dashboard.dashboards[0],
dashcards: [1],
- parameters: [{ id: parameterId }],
+ parameters: [createMockParameter({ id: parameterId })],
},
},
dashcards: {
@@ -267,13 +277,14 @@ describe("dashboard/selectors", () => {
expect(getShowAddQuestionSidebar(STATE)).toBe(false);
});
- it("should returnftrue when the sidebar is set to the add question sidebar", () => {
+ it("should return true when the sidebar is set to the add question sidebar", () => {
const state = {
...STATE,
dashboard: {
...STATE.dashboard,
sidebar: {
name: SIDEBAR_NAME.addQuestion,
+ props: {},
},
},
};
@@ -294,6 +305,7 @@ describe("dashboard/selectors", () => {
...STATE.dashboard,
sidebar: {
name: SIDEBAR_NAME.sharing,
+ props: {},
},
},
};
@@ -335,6 +347,7 @@ describe("dashboard/selectors", () => {
...STATE.dashboard,
sidebar: {
name: SIDEBAR_NAME.editParameter,
+ props: {},
},
},
};
@@ -389,12 +402,15 @@ describe("dashboard/selectors", () => {
const multiCardState = chain(STATE)
.assocIn(["dashboard", "dashboards", 0, "dashcards"], [0, 1, 2])
.assocIn(["dashboard", "dashcards", 2], {
- card: { id: 2, dataset_query: { type: "query", query: {} } },
+ card: createMockCard({
+ id: 2,
+ dataset_query: createMockStructuredDatasetQuery({ query: {} }),
+ }),
parameter_mappings: [],
})
.value();
- const setup = (positions) => {
+ const setup = (positions: Array<{ row: number; col: number }>) => {
const newStateChain = chain(multiCardState);
positions.forEach((position, index) => {
@@ -407,24 +423,25 @@ describe("dashboard/selectors", () => {
};
it("should filter out removed dashcards", () => {
- const state = chain(multiCardState)
+ const state: State = chain(multiCardState)
.assocIn(["dashboard", "dashcards", 0, "isRemoved"], true)
.assocIn(["dashboard", "dashcards", 2, "isRemoved"], true)
.value();
- expect(getDashboardComplete(state).dashcards).toEqual([
+ const dashboardComplete = getDashboardComplete(state);
+ expect(dashboardComplete?.dashcards).toEqual([
multiCardState.dashboard.dashcards[1],
]);
});
it("should sort cards based on their positions top to bottom", () => {
- const state = setup([
+ const state: State = setup([
{ row: 2, col: 0 },
{ row: 1, col: 1 },
{ row: 0, col: 2 },
]);
- const cards = getDashboardComplete(state).dashcards;
+ const cards = getDashboardComplete(state)?.dashcards ?? [];
expect(cards[2].card.id).toBe(0);
expect(cards[1].card.id).toBe(1);
@@ -432,13 +449,13 @@ describe("dashboard/selectors", () => {
});
it("should sort cards based on their positions left to right when on the same row", () => {
- const state = setup([
+ const state: State = setup([
{ row: 0, col: 2 },
{ row: 0, col: 1 },
{ row: 0, col: 0 },
]);
- const cards = getDashboardComplete(state).dashcards;
+ const cards = getDashboardComplete(state)?.dashcards ?? [];
expect(cards[2].card.id).toBe(0);
expect(cards[1].card.id).toBe(1);