Skip to content

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

Convert metabase-lib/v1 parameter-values utils to TypeScript (#79555)

Andrei Chernykh893c614bed0c
diff --git a/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts b/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
index 4b3cb017073..36637d2ca29 100644
--- a/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/controlled-parameters.ts
@@ -75,7 +75,11 @@ export function buildParametersPayload(
applied: ParameterValuesMap,
parameterDefinitions: UiParameter[],
lastUsedParameterValues?: ParameterValuesMap,
-) {
+): {
+ parameters: ParameterValues;
+ defaultParameters: ParameterValues;
+ lastUsedParameters?: ParameterValues;
+} {
return {
parameters: getParameterValuesBySlug(parameterDefinitions, applied),
defaultParameters: getParameterValuesBySlug(
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.js b/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.ts
similarity index 67%
rename from frontend/src/metabase-lib/v1/parameters/utils/parameter-values.js
rename to frontend/src/metabase-lib/v1/parameters/utils/parameter-values.ts
index c982870ad53..b4fed4dcee3 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.js
+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.ts
@@ -1,5 +1,14 @@
import _ from "underscore";
+import type { ParameterWithTemplateTagTarget } from "metabase-lib/v1/parameters/types";
+import type {
+ NormalizedParameter,
+ NormalizedQueryParameter,
+ Parameter,
+ ParameterValueOrArray,
+ ParameterValuesMap,
+} from "metabase-types/api";
+
import {
getQueryType,
getSourceConfig,
@@ -19,6 +28,11 @@ export function getParameterValue({
values = {},
defaultRequired = false,
lastUsedParameterValue = null,
+}: {
+ parameter: Parameter;
+ values?: ParameterValuesMap | null;
+ defaultRequired?: boolean;
+ lastUsedParameterValue?: ParameterValueOrArray | null;
}) {
const value = values?.[parameter.id];
const useDefault = defaultRequired && parameter.required;
@@ -29,17 +43,17 @@ export function getParameterValue({
}
/**
- * @import { UiParameter } from "metabase-lib/v1/parameters/types";
- *
* In some cases, we need to use default parameter value in place of an absent one.
* Please use this function when dealing with the required parameters.
- *
- * @returns {UiParameter[]}
*/
-export function getValuePopulatedParameters({
+export function getValuePopulatedParameters<P extends Parameter>({
parameters,
values = {},
defaultRequired = false,
+}: {
+ parameters: P[];
+ values?: ParameterValuesMap | null;
+ defaultRequired?: boolean;
}) {
return parameters.map((parameter) => ({
...parameter,
@@ -51,9 +65,9 @@ export function getValuePopulatedParameters({
}));
}
-export function getDefaultValuePopulatedParameters(
- parameters,
- parameterValues,
+export function getDefaultValuePopulatedParameters<P extends Parameter>(
+ parameters: P[],
+ parameterValues?: ParameterValuesMap | null,
) {
return parameters.map((parameter) => {
const value = parameterValues?.[parameter.id];
@@ -66,19 +80,14 @@ export function getDefaultValuePopulatedParameters(
// Needed because parameter values might be arrays
// in which case order of elements isn't guaranteed
-export function areParameterValuesIdentical(a, b) {
+export function areParameterValuesIdentical(a: unknown, b: unknown): boolean {
return _.isEqual(
Array.isArray(a) ? a.slice().sort() : a,
Array.isArray(b) ? b.slice().sort() : b,
);
}
-/**
- * @import { NormalizedParameter } from "metabase-types/api";
- *
- * @returns {NormalizedParameter}
- */
-export function normalizeParameter(parameter) {
+export function normalizeParameter(parameter: Parameter): NormalizedParameter {
return {
id: parameter.id,
name: parameter.name,
@@ -92,7 +101,9 @@ export function normalizeParameter(parameter) {
};
}
-export function normalizeParameters(parameters) {
+export function normalizeParameters(
+ parameters: Parameter[],
+): NormalizedQueryParameter[] {
return parameters
.filter((parameter) => _.has(parameter, "value"))
.map(({ id, type, value, target, options }) => ({
@@ -107,7 +118,7 @@ export function normalizeParameters(parameters) {
// This distinguishes between empty value (deliberately unset), which is null,
// and no value, which is undefined. Needed in API requests.
// TODO reconcile with hasNoValueToShow
-export function isParameterValueEmpty(value) {
+export function isParameterValueEmpty(value: unknown): boolean {
return (
value === PULSE_PARAM_EMPTY ||
(Array.isArray(value) && value.length === 0) ||
@@ -118,7 +129,7 @@ export function isParameterValueEmpty(value) {
// This is a UI-bound function used to render filter widget.
// Should treat undefined and null equally.
// TODO reconcile with isParameterValueEmpty
-export function parameterHasNoDisplayValue(value) {
+export function parameterHasNoDisplayValue(value: unknown): boolean {
return (
(!value && value !== 0) ||
value === "" ||
@@ -126,28 +137,37 @@ export function parameterHasNoDisplayValue(value) {
);
}
-export function normalizeParameterValue(type, value) {
- const fieldType = getParameterType(type);
+export function normalizeParameterValue(
+ type: string,
+ value: ParameterValueOrArray | null | undefined,
+) {
if (value === PULSE_PARAM_USE_DEFAULT) {
return PULSE_PARAM_USE_DEFAULT;
- } else if (isParameterValueEmpty(value)) {
+ }
+
+ if (value === PULSE_PARAM_EMPTY || isParameterValueEmpty(value)) {
return PULSE_PARAM_EMPTY;
- } else if (["string", "number"].includes(fieldType)) {
- return [].concat(value);
- } else {
- return value;
}
-}
-export function getParameterValuesBySlug(parameters, parameterValuesById) {
- parameters = parameters ?? [];
- parameterValuesById = parameterValuesById ?? {};
+ const fieldType = getParameterType(type);
+ if (["string", "number"].includes(fieldType)) {
+ return Array.isArray(value) ? [...value] : [value];
+ }
+
+ return value;
+}
+export function getParameterValuesBySlug(
+ parameters?: Parameter[] | null,
+ parameterValuesById?: ParameterValuesMap | null,
+): Record<string, ParameterValueOrArray | null> {
return Object.fromEntries(
- parameters.map((parameter) => [
- parameter.slug,
- parameter.value ?? parameterValuesById[parameter.id] ?? null,
- ]),
+ (parameters ?? []).map(
+ (parameter): [string, ParameterValueOrArray | null] => [
+ parameter.slug,
+ parameter.value ?? parameterValuesById?.[parameter.id] ?? null,
+ ],
+ ),
);
}
@@ -167,10 +187,12 @@ export function getParameterValuesBySlug(parameters, parameterValuesById) {
* mapping is changed instead of relying on the `undefined` value and the
* implicit behavior of this function.
*/
-export function getIsMultiSelect(parameter) {
+export function getIsMultiSelect(
+ parameter: ParameterWithTemplateTagTarget,
+): boolean {
return parameter.isMultiSelect ?? !parameter.hasVariableTemplateTagTarget;
}
-export function hasValue(value) {
+export function hasValue(value: unknown): boolean {
return Array.isArray(value) ? value.length > 0 : value != null;
}
diff --git a/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.js b/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.ts
similarity index 81%
rename from frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.js
rename to frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.ts
index 87e9875d4ad..8a9f8672c97 100644
--- a/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.js
+++ b/frontend/src/metabase-lib/v1/parameters/utils/parameter-values.unit.spec.ts
@@ -7,71 +7,28 @@ import {
import { createMockParameter } from "metabase-types/api/mocks";
describe("parameters/utils/parameter-values", () => {
- let field1;
- let field2;
- let field3;
- let field4;
- let parameter1;
- let parameter2;
- let parameter3;
- let parameterValues;
-
- beforeEach(() => {
- field1 = {
- id: 1,
- table_id: 1,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
- };
- field2 = {
- id: 2,
- table_id: 1,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
- };
- field3 = {
- id: 3,
- table_id: 1,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
- };
- field4 = {
- id: 4,
- table_id: 1,
- isNumeric: () => false,
- isDate: () => false,
- isBoolean: () => false,
- };
-
- parameter1 = {
- id: 111,
- slug: "foo",
- fields: [field1, field4],
- };
- parameter2 = {
- id: 222,
- slug: "bar",
- default: "parameter2 default value",
- fields: [field2],
- };
- parameter3 = {
- id: 333,
- slug: "baz",
- default: "parameter3 default value",
- fields: [field3],
- };
-
- // typically generated using getParameterValuesByIdFromQueryParams(parameters, queryParams)
- parameterValues = {
- [parameter1.id]: "parameter1 parameterValue",
- [parameter2.id]: "parameter2 parameterValue",
- [parameter3.id]: "parameter3 default value",
- };
+ const parameter1 = createMockParameter({
+ id: "111",
+ slug: "foo",
+ });
+ const parameter2 = createMockParameter({
+ id: "222",
+ slug: "bar",
+ default: "parameter2 default value",
+ });
+ const parameter3 = createMockParameter({
+ id: "333",
+ slug: "baz",
+ default: "parameter3 default value",
});
+ // typically generated using getParameterValuesByIdFromQueryParams(parameters, queryParams)
+ const parameterValues = {
+ [parameter1.id]: "parameter1 parameterValue",
+ [parameter2.id]: "parameter2 parameterValue",
+ [parameter3.id]: "parameter3 default value",
+ };
+
describe("getValuePopulatedParameters", () => {
it("should return an array of parameter objects with the `value` property set if it exists in the given `parameterValues` id, value map, and null if it doesn't exist", () => {
expect(
@@ -167,18 +124,18 @@ describe("parameters/utils/parameter-values", () => {
});
it("should not remove any properties with nil values from the map", () => {
- const defaultedParameter = {
- id: 999,
+ const defaultedParameter = createMockParameter({
+ id: "999",
slug: "abc",
default: 123,
- };
+ });
- const defaultedParameterWithValue = {
- id: 888,
+ const defaultedParameterWithValue = createMockParameter({
+ id: "888",
slug: "def",
default: 456,
value: 789,
- };
+ });
const parameters = [defaultedParameter, defaultedParameterWithValue];
@@ -200,10 +157,9 @@ describe("parameters/utils/parameter-values", () => {
describe("getParameterValue", () => {
const parameter = createMockParameter({
- id: 333,
+ id: "333",
slug: "baz",
default: "parameter default value",
- fields: [field1],
required: true,
});
diff --git a/frontend/src/metabase-types/api/dataset.ts b/frontend/src/metabase-types/api/dataset.ts
index b09c2239edc..da20e93aae6 100644
--- a/frontend/src/metabase-types/api/dataset.ts
+++ b/frontend/src/metabase-types/api/dataset.ts
@@ -15,7 +15,7 @@ import type {
FieldVisibilityType,
} from "./field";
import type { Insight } from "./insight";
-import type { ParameterOptions } from "./parameters";
+import type { NormalizedQueryParameter, ParameterOptions } from "./parameters";
import type { DownloadPermission } from "./permissions";
import type { DatasetQuery, DatetimeUnit, DimensionReference } from "./query";
import type { TableId } from "./table";
@@ -121,7 +121,7 @@ export interface DatasetData {
}
export type JsonQuery = DatasetQuery & {
- parameters?: Parameter[];
+ parameters?: NormalizedQueryParameter[];
"cache-strategy"?: CacheStrategy & {
/** An ISO 8601 date */
"invalidated-at"?: string;
diff --git a/frontend/src/metabase-types/api/parameters.ts b/frontend/src/metabase-types/api/parameters.ts
index e301cfc6c64..ff91790c269 100644
--- a/frontend/src/metabase-types/api/parameters.ts
+++ b/frontend/src/metabase-types/api/parameters.ts
@@ -152,6 +152,16 @@ export type NormalizedParameter = {
values_source_config?: ValuesSourceConfig;
};
+// The parameter payload attached to query execution requests. `value` is
+// undefined when the parameter should fall back to its default.
+export type NormalizedQueryParameter = {
+ id: ParameterId;
+ type: string;
+ value?: ParameterValueOrArray | null;
+ target?: ParameterTarget;
+ options?: ParameterOptions;
+};
+
export type GetParameterValuesRequest = {
parameter: NormalizedParameter;
field_ids: number[];
diff --git a/frontend/src/metabase-types/api/query.ts b/frontend/src/metabase-types/api/query.ts
index f77d479ee39..3856708caca 100644
--- a/frontend/src/metabase-types/api/query.ts
+++ b/frontend/src/metabase-types/api/query.ts
@@ -6,7 +6,7 @@ import type { TemplateTag, TemplateTags, TemporalUnit } from "./dataset";
import type { FieldId } from "./field";
import type { MeasureId } from "./measure";
import type { MetricId } from "./metric";
-import type { Parameter } from "./parameters";
+import type { NormalizedQueryParameter } from "./parameters";
import type { SegmentId } from "./segment";
import type { TableId } from "./table";
@@ -22,7 +22,7 @@ export interface StructuredDatasetQuery {
// Database is null when missing data permissions to the database
database: DatabaseId | null;
- parameters?: Parameter[];
+ parameters?: NormalizedQueryParameter[];
}
export interface NativeDatasetQuery {
@@ -31,7 +31,7 @@ export interface NativeDatasetQuery {
// Database is null when missing data permissions to the database
database: DatabaseId | null;
- parameters?: Parameter[];
+ parameters?: NormalizedQueryParameter[];
}
export type DatasetQuery = OpaqueDatasetQuery | LegacyDatasetQuery;
diff --git a/frontend/src/metabase/dashboard/actions/data-fetching.ts b/frontend/src/metabase/dashboard/actions/data-fetching.ts
index 0ced3199e2c..7dca4c6f152 100644
--- a/frontend/src/metabase/dashboard/actions/data-fetching.ts
+++ b/frontend/src/metabase/dashboard/actions/data-fetching.ts
@@ -47,7 +47,6 @@ import {
isVirtualDashCard,
} from "metabase/utils/dashboard";
import { uuid } from "metabase/utils/uuid";
-import type { UiParameter } from "metabase-lib/v1/parameters/types";
import { getParameterValuesBySlug } from "metabase-lib/v1/parameters/utils/parameter-values";
import type {
Card,
@@ -58,6 +57,7 @@ import type {
DashboardId,
Dataset,
JsonQuery,
+ ParameterId,
ParameterValuesMap,
QuestionDashboardCard,
} from "metabase-types/api";
@@ -663,7 +663,7 @@ function getDatasetQueryParams(datasetQuery?: JsonQuery) {
.sort(sortById);
}
-function sortById(a: UiParameter, b: UiParameter) {
+function sortById(a: { id: ParameterId }, b: { id: ParameterId }) {
return a.id.localeCompare(b.id);
}
diff --git a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
index c523ba37ad1..d192562e6b2 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
@@ -856,7 +856,7 @@ describe("DashCard", () => {
jest
.spyOn(dashboardSelectors, "getDashCardInlineValuePopulatedParameters")
- .mockReturnValue([parameter]);
+ .mockReturnValue([{ ...parameter, value: null }]);
setup({
dashboard,
@@ -915,7 +915,7 @@ describe("DashCard", () => {
jest
.spyOn(dashboardSelectors, "getDashCardInlineValuePopulatedParameters")
- .mockReturnValue([parameter]);
+ .mockReturnValue([{ ...parameter, value: null }]);
setup({
dashboard,
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
index 33fe2bb4987..639351f4cff 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.tsx
@@ -13,6 +13,7 @@ import type { State } from "metabase/redux/store";
import { Button, Card, Flex, Icon, Tooltip } from "metabase/ui";
import { conjunct } from "metabase/utils/formatting";
import { formatFrame } from "metabase/utils/time-dayjs";
+import { isNotNull } from "metabase/utils/types";
import {
formatDateTimeWithUnit,
formatTimeWithUnit,
@@ -188,7 +189,7 @@ function buildRecipientText(pulse: DashboardSubscription): string {
)}`;
}
-function buildFilterText(
+export function buildFilterText(
pulse: DashboardSubscription,
parameters: UiParameter[],
): string {
@@ -207,8 +208,8 @@ function buildFilterText(
? firstParameter.value
: [firstParameter.value];
const formattedValues = values
- .map((val: string) => formatDateValue(firstParameter, val))
- .filter(Boolean);
+ .map((val) => formatDateValue(firstParameter, val))
+ .filter(isNotNull);
if (formattedValues.length > 0) {
formattedValue = conjunct(formattedValues, t`and`);
} else {
@@ -221,7 +222,7 @@ function buildFilterText(
formattedValue =
values.length > 1
? t`${values.length} selections`
- : conjunct(values, t`and`);
+ : conjunct(values.filter(isNotNull), t`and`);
}
const firstFilterText = `${firstParameter.name}: ${formattedValue}`;
diff --git a/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx
new file mode 100644
index 00000000000..3d47f3d69f8
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardSubscriptionsSidebar/PulsesListSidebar.unit.spec.tsx
@@ -0,0 +1,95 @@
+import { createMockUiParameter } from "metabase-lib/v1/parameters/mock";
+import type { ParameterValueOrArray } from "metabase-types/api";
+import {
+ createMockDashboardSubscription,
+ createMockParameter,
+} from "metabase-types/api/mocks";
+
+import { buildFilterText } from "./PulsesListSidebar";
+
+jest.mock("metabase/parameters/utils/date-formatting", () => ({
+ formatDateValue: jest.fn((_parameter, value) =>
+ value === "2024-01-15" ? "January 15, 2024" : null,
+ ),
+}));
+
+describe("buildFilterText", () => {
+ const stateParameter = createMockUiParameter({
+ id: "1",
+ name: "State",
+ slug: "state",
+ type: "string/=",
+ });
+
+ const buildPulse = (value: ParameterValueOrArray) =>
+ createMockDashboardSubscription({
+ parameters: [createMockParameter({ id: "1", value })],
+ });
+
+ it("returns an empty string when no parameters have values", () => {
+ expect(
+ buildFilterText(createMockDashboardSubscription(), [stateParameter]),
+ ).toBe("");
+ });
+
+ it("renders a single value", () => {
+ expect(buildFilterText(buildPulse("CA"), [stateParameter])).toBe(
+ "State: CA",
+ );
+ });
+
+ it("renders a single-element array value", () => {
+ expect(buildFilterText(buildPulse(["CA"]), [stateParameter])).toBe(
+ "State: CA",
+ );
+ });
+
+ it("renders a numeric value", () => {
+ expect(buildFilterText(buildPulse(42), [stateParameter])).toBe("State: 42");
+ });
+
+ it("summarizes multi-value selections", () => {
+ expect(buildFilterText(buildPulse(["CA", "NY"]), [stateParameter])).toBe(
+ "State: 2 selections",
+ );
+ });
+
+ it("drops nullish array entries instead of rendering them", () => {
+ expect(buildFilterText(buildPulse([null]), [stateParameter])).toBe(
+ "State: ",
+ );
+ });
+
+ it("mentions the number of additional filters", () => {
+ const cityParameter = createMockUiParameter({
+ id: "2",
+ name: "City",
+ slug: "city",
+ type: "string/=",
+ });
+ const pulse = createMockDashboardSubscription({
+ parameters: [
+ createMockParameter({ id: "1", value: "CA" }),
+ createMockParameter({ id: "2", value: "SF" }),
+ ],
+ });
+ expect(buildFilterText(pulse, [stateParameter, cityParameter])).toBe(
+ "State: CA and 1 more filter",
+ );
+ });
+
+ it("formats date parameter values", () => {
+ const dateParameter = createMockUiParameter({
+ id: "3",
+ name: "Created At",
+ slug: "created_at",
+ type: "date/single",
+ });
+ const pulse = createMockDashboardSubscription({
+ parameters: [createMockParameter({ id: "3", value: "2024-01-15" })],
+ });
+ expect(buildFilterText(pulse, [dateParameter])).toBe(
+ "Created At: January 15, 2024",
+ );
+ });
+});
diff --git a/frontend/src/metabase/embedding/types.ts b/frontend/src/metabase/embedding/types.ts
index 1c94221f2e2..6fc28347e96 100644
--- a/frontend/src/metabase/embedding/types.ts
+++ b/frontend/src/metabase/embedding/types.ts
@@ -27,7 +27,7 @@ export type EmbedResourceParameter = {
export type EmbeddingParametersValues = Record<
string,
- number | string | string[] | null | undefined
+ ParameterValueOrArray | null | undefined
>;
/**
diff --git a/frontend/src/metabase/parameters/utils/date-formatting.ts b/frontend/src/metabase/parameters/utils/date-formatting.ts
index 5e64aae7567..bc41df860b7 100644
--- a/frontend/src/metabase/parameters/utils/date-formatting.ts
+++ b/frontend/src/metabase/parameters/utils/date-formatting.ts
@@ -1,10 +1,14 @@
import { getDateFilterDisplayName } from "metabase/querying/filters/utils/dates";
import { deserializeDateParameterValue } from "metabase/querying/parameters/utils/parsing";
-import type { DateFormattingSettings, Parameter } from "metabase-types/api";
+import type {
+ DateFormattingSettings,
+ Parameter,
+ ParameterValueOrArray,
+} from "metabase-types/api";
export function formatDateValue(
parameter: Parameter,
- value: string,
+ value: ParameterValueOrArray | null | undefined,
formattingSettings?: DateFormattingSettings,
): string | null {
const filter = deserializeDateParameterValue(value);
diff --git a/frontend/src/metabase/query_builder/components/view/PreviewQueryModal/PreviewQueryModal.tsx b/frontend/src/metabase/query_builder/components/view/PreviewQueryModal/PreviewQueryModal.tsx
index 67f95f1d112..47f7ca0b2f3 100644
--- a/frontend/src/metabase/query_builder/components/view/PreviewQueryModal/PreviewQueryModal.tsx
+++ b/frontend/src/metabase/query_builder/components/view/PreviewQueryModal/PreviewQueryModal.tsx
@@ -8,7 +8,6 @@ import { NativeQueryPreview } from "metabase/querying/notebook/components/Native
import { useSelector } from "metabase/redux";
import { Modal } from "metabase/ui";
import { checkNotNull } from "metabase/utils/types";
-import type { UiParameter } from "metabase-lib/v1/parameters/types";
export const PreviewQueryModal = ({
onClose = () => undefined,
@@ -16,7 +15,7 @@ export const PreviewQueryModal = ({
onClose?: () => void;
}) => {
const question = checkNotNull(useSelector(getQuestion));
- const parameters: UiParameter[] = useSelector(getNextRunParameters);
+ const parameters = useSelector(getNextRunParameters);
return (
<Modal opened onClose={onClose} title={t`Query preview`}>
diff --git a/frontend/src/metabase/querying/notebook/components/NativeQueryPreview/NativeQueryPreview.tsx b/frontend/src/metabase/querying/notebook/components/NativeQueryPreview/NativeQueryPreview.tsx
index 87542878094..664121e7d53 100644
--- a/frontend/src/metabase/querying/notebook/components/NativeQueryPreview/NativeQueryPreview.tsx
+++ b/frontend/src/metabase/querying/notebook/components/NativeQueryPreview/NativeQueryPreview.tsx
@@ -11,8 +11,10 @@ import { getLearnUrl } from "metabase/selectors/settings";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
import { Box, Flex, Icon, Loader, Stack } from "metabase/ui";
import * as Lib from "metabase-lib";
-import type { UiParameter } from "metabase-lib/v1/parameters/types";
-import type { NativeDatasetResponse } from "metabase-types/api";
+import type {
+ NativeDatasetResponse,
+ NormalizedQueryParameter,
+} from "metabase-types/api";
import { language } from "../../../components/CodeMirrorEditor/language";
@@ -23,7 +25,7 @@ export function NativeQueryPreview({
parameters = [],
}: {
query: Lib.Query;
- parameters?: UiParameter[];
+ parameters?: NormalizedQueryParameter[];
}) {
const { data, error, isFetching } = useGetNativeDatasetQuery({
...Lib.toJsQuery(query),
diff --git a/frontend/src/metabase/utils/formatting/strings.ts b/frontend/src/metabase/utils/formatting/strings.ts
index b817cbef79c..e1872ec7f28 100644
--- a/frontend/src/metabase/utils/formatting/strings.ts
+++ b/frontend/src/metabase/utils/formatting/strings.ts
@@ -34,12 +34,15 @@ export function humanize(str: string, lowFirstLetter?: boolean) {
return inflection.humanize(str, lowFirstLetter);
}
-export function conjunct(list: string[], conjunction: string) {
+export function conjunct(
+ list: (string | number | boolean)[],
+ conjunction: string,
+) {
return (
list.slice(0, -1).join(`, `) +
(list.length > 2 ? `,` : ``) +
(list.length > 1 ? ` ${conjunction} ` : ``) +
- (list[list.length - 1] || ``)
+ (list[list.length - 1] ?? ``)
);
}
diff --git a/frontend/src/metabase/utils/formatting/strings.unit.spec.ts b/frontend/src/metabase/utils/formatting/strings.unit.spec.ts
index 5be6b182a97..67533c478c4 100644
--- a/frontend/src/metabase/utils/formatting/strings.unit.spec.ts
+++ b/frontend/src/metabase/utils/formatting/strings.unit.spec.ts
@@ -1,50 +1,74 @@
-import { capitalize, slugify } from "./strings";
-
-describe("formatting", () => {
- describe("strings", () => {
- describe("capitalize", () => {
- it("capitalizes a single word", () => {
- expect(capitalize("hello")).toBe("Hello");
- });
-
- it("capitalizes only the first char of a string", () => {
- expect(capitalize("hello world")).toBe("Hello world");
- });
-
- it("converts a string to lowercase by default", () => {
- expect(capitalize("heLLo")).toBe("Hello");
- });
-
- it("doesn't lowercase the string if option provided", () => {
- expect(capitalize("hellO WoRlD", { lowercase: false })).toBe(
- "HellO WoRlD",
- );
- });
-
- it("doesn't break on an empty string", () => {
- expect(capitalize("")).toBe("");
- expect(capitalize("", { lowercase: false })).toBe("");
- });
- });
-
- describe("slugify", () => {
- it("should slugify Chinese", () => {
- expect(slugify("類型")).toEqual("%E9%A1%9E%E5%9E%8B");
- });
-
- it("should slugify multiple words", () => {
- expect(slugify("Test Parameter")).toEqual("test_parameter");
- });
-
- it("should slugify Russian", () => {
- expect(slugify("русский язык")).toEqual(
- "%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9_%D1%8F%D0%B7%D1%8B%D0%BA",
- );
- });
-
- it("should slugify diacritics", () => {
- expect(slugify("än umlaut")).toEqual("%C3%A4n_umlaut");
- });
- });
+import { capitalize, conjunct, slugify } from "./strings";
+
+describe("capitalize", () => {
+ it("capitalizes a single word", () => {
+ expect(capitalize("hello")).toBe("Hello");
+ });
+
+ it("capitalizes only the first char of a string", () => {
+ expect(capitalize("hello world")).toBe("Hello world");
+ });
+
+ it("converts a string to lowercase by default", () => {
+ expect(capitalize("heLLo")).toBe("Hello");
+ });
+
+ it("doesn't lowercase the string if option provided", () => {
+ expect(capitalize("hellO WoRlD", { lowercase: false })).toBe("HellO WoRlD");
+ });
+
+ it("doesn't break on an empty string", () => {
+ expect(capitalize("")).toBe("");
+ expect(capitalize("", { lowercase: false })).toBe("");
+ });
+});
+
+describe("conjunct", () => {
+ it("returns a single item as-is", () => {
+ expect(conjunct(["a"], "and")).toBe("a");
+ });
+
+ it("joins two items with the conjunction", () => {
+ expect(conjunct(["a", "b"], "and")).toBe("a and b");
+ });
+
+ it("joins three or more items with commas and an Oxford comma", () => {
+ expect(conjunct(["a", "b", "c"], "and")).toBe("a, b, and c");
+ expect(conjunct(["a", "b", "c", "d"], "or")).toBe("a, b, c, or d");
+ });
+
+ it("returns an empty string for an empty list", () => {
+ expect(conjunct([], "and")).toBe("");
+ });
+
+ it("coerces non-string values to strings", () => {
+ expect(conjunct([1, 2], "and")).toBe("1 and 2");
+ expect(conjunct([true, 0.5], "or")).toBe("true or 0.5");
+ });
+
+ it("doesn't drop falsy values (metabase#79555)", () => {
+ expect(conjunct([0], "and")).toBe("0");
+ expect(conjunct(["a", 0], "and")).toBe("a and 0");
+ expect(conjunct([false, 0], "or")).toBe("false or 0");
+ });
+});
+
+describe("slugify", () => {
+ it("should slugify Chinese", () => {
+ expect(slugify("類型")).toEqual("%E9%A1%9E%E5%9E%8B");
+ });
+
+ it("should slugify multiple words", () => {
+ expect(slugify("Test Parameter")).toEqual("test_parameter");
+ });
+
+ it("should slugify Russian", () => {
+ expect(slugify("русский язык")).toEqual(
+ "%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9_%D1%8F%D0%B7%D1%8B%D0%BA",
+ );
+ });
+
+ it("should slugify diacritics", () => {
+ expect(slugify("än umlaut")).toEqual("%C3%A4n_umlaut");
});
});
diff --git a/frontend/src/metabase/visualizations/lib/map.ts b/frontend/src/metabase/visualizations/lib/map.ts
index a2b162dffc9..a2e2c37672f 100644
--- a/frontend/src/metabase/visualizations/lib/map.ts
+++ b/frontend/src/metabase/visualizations/lib/map.ts
@@ -1,7 +1,11 @@
import { isEmbedPreview as getIsEmbedPreview } from "metabase/embedding/config";
import { isJWT } from "metabase/utils/jwt";
import { isUuid } from "metabase/utils/uuid";
-import type { DashboardId, JsonQuery, Parameter } from "metabase-types/api";
+import type {
+ DashboardId,
+ JsonQuery,
+ NormalizedQueryParameter,
+} from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
interface TileCoordinate {
@@ -20,7 +24,7 @@ interface TileUrlParams {
datasetQuery?: JsonQuery;
uuid?: string;
token?: EntityToken;
- parameters?: Parameter[];
+ parameters?: NormalizedQueryParameter[];
/**
* Indicates whether the tile URL is being generated for a preview embed context.
* You probably don't need to set this manually; it defaults to `isEmbedPreview()`