Skip to content

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

Avoid updating url when navigating to query builder (#68982)

Romeo Van Snick40cbf2ffb544
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx
index 95ab83725ab..bd9b4edf4e5 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkAdHocQuestion/SdkAdHocQuestion.tsx
@@ -65,7 +65,9 @@ export const SdkAdHocQuestion = ({
const { options, deserializedCard } = useMemo(() => {
const { options, serializedCard } = parseHash(location.hash);
- const deserializedCard = serializedCard && deserializeCard(serializedCard);
+ const deserializedCard = serializedCard
+ ? deserializeCard(serializedCard)
+ : undefined;
return { options, deserializedCard };
}, [location.hash]);
diff --git a/frontend/src/metabase-lib/v1/Question.ts b/frontend/src/metabase-lib/v1/Question.ts
index 9adf9227423..4fe2a3a9cf3 100644
--- a/frontend/src/metabase-lib/v1/Question.ts
+++ b/frontend/src/metabase-lib/v1/Question.ts
@@ -4,7 +4,12 @@ import { assoc, assocIn, chain, dissoc, getIn } from "icepick";
import slugg from "slugg";
import _ from "underscore";
-import { utf8_to_b64url } from "metabase/lib/encoding";
+// eslint-disable-next-line no-restricted-imports
+import {
+ type SerializeCardOptions,
+ serializeCardForUrl,
+} from "metabase/lib/card";
+import { equals } from "metabase/lib/utils";
import { applyParameter } from "metabase/querying/parameters/utils/query";
import * as Lib from "metabase-lib";
import {
@@ -24,10 +29,9 @@ import NativeQuery, {
} from "metabase-lib/v1/queries/NativeQuery";
import { STRUCTURED_QUERY_TEMPLATE } from "metabase-lib/v1/queries/StructuredQuery";
import { isTransientId } from "metabase-lib/v1/queries/utils/card";
-import { sortObject } from "metabase-lib/v1/utils";
import type {
+ Card,
CardDisplayType,
- Card as CardObject,
CardType,
CollectionId,
DashCardId,
@@ -79,7 +83,7 @@ class Question {
* The plain object presentation of this question, equal to the format that Metabase REST API understands.
* It is called `card` for both historical reasons and to make a clear distinction to this class.
*/
- _card: CardObject;
+ _card: Card;
/**
* The Question wrapper requires a metadata object because the queries it contains (like {@link StructuredQuery})
@@ -135,7 +139,7 @@ class Question {
return this._card;
}
- setCard(card: CardObject): Question {
+ setCard(card: Card): Question {
const q = this.clone();
q._card = card;
return q;
@@ -677,19 +681,10 @@ class Question {
} else {
// If it's saved, then it's dirty when the current card doesn't match the last saved version.
// Omit `entity_id` and `dataset_query` as they have randomized idents
- const origCardSerialized =
- originalQuestion &&
- originalQuestion._serializeForUrl({
- includeEntityId: false,
- includeDatasetQuery: false,
- includeOriginalCardId: false,
- });
- const currentCardSerialized = this._serializeForUrl({
- includeEntityId: false,
- includeDatasetQuery: false,
- includeOriginalCardId: false,
- });
- if (currentCardSerialized !== origCardSerialized) {
+ const originalCard = originalQuestion?._getValueForComparison();
+ const currentCard = this._getValueForComparison();
+
+ if (!equals(originalCard, currentCard)) {
return true;
}
@@ -724,60 +719,44 @@ class Question {
);
}
+ serializeForUrl(opts: SerializeCardOptions = {}) {
+ const card = {
+ ...this.card(),
+ dataset_query: Lib.toJsQuery(this.query()),
+ };
+ return serializeCardForUrl(card, {
+ ...opts,
+ parameterValues: this._parameterValues,
+ });
+ }
+
// Internal methods
- _serializeForUrl({
- includeEntityId = true,
- includeDatasetQuery = true,
- includeOriginalCardId = true,
- includeDisplayIsLocked = false,
- creationType,
- }: {
- includeEntityId?: boolean;
- includeDatasetQuery?: boolean;
- includeOriginalCardId?: boolean;
- includeDisplayIsLocked?: boolean;
- creationType?: string;
- } = {}) {
- const card = this._card;
- const cardCopy = {
- name: card.name,
- description: card.description,
- collection_id: card.collection_id,
- dashboard_id: card.dashboard_id,
- ...(includeEntityId ? { entity_id: card.entity_id } : {}),
- ...(includeDatasetQuery
- ? { dataset_query: Lib.toJsQuery(this.query()) }
- : {}),
- display: card.display,
- ...(_.isEmpty(card.parameters)
- ? undefined
- : {
- parameters: card.parameters,
- }),
- type: card.type,
- ...(_.isEmpty(this._parameterValues)
- ? undefined
- : {
- parameterValues: this._parameterValues,
- }),
- // this is kinda wrong. these values aren't really part of the card, but this is a convenient place to put them
- visualization_settings: card.visualization_settings,
- ...(includeOriginalCardId
- ? {
- original_card_id: card.original_card_id,
- }
- : {}),
- ...(includeDisplayIsLocked
- ? {
- displayIsLocked: card.displayIsLocked,
- }
- : {}),
-
- ...(creationType ? { creationType } : {}),
- dashboardId: card.dashboardId,
- dashcardId: card.dashcardId,
+ _getValueForComparison() {
+ const value = {
+ ...this._card,
+ ...this._parameterValues,
};
- return utf8_to_b64url(JSON.stringify(sortObject(cardCopy)));
+
+ const keys = [
+ "collection_id",
+ "dashboard_id",
+ "dashboardId",
+ "dashcardId",
+ "description",
+ "display",
+ "name",
+ "parameters",
+ "parameterValues",
+ "type",
+ "visualization_settings",
+ ];
+
+ const res = {};
+ for (const key of keys) {
+ res[key] = value[key] ?? undefined;
+ }
+
+ return res;
}
_convertParametersToMbql({ isComposed }: { isComposed: boolean }): Question {
@@ -911,7 +890,7 @@ class Question {
? NATIVE_QUERY_TEMPLATE
: STRUCTURED_QUERY_TEMPLATE,
}: QuestionCreatorOpts = {}) {
- let card: CardObject = {
+ let card: Card = {
name,
collection_id: collectionId,
dashboard_id: dashboardId,
diff --git a/frontend/src/metabase-lib/v1/urls.ts b/frontend/src/metabase-lib/v1/urls.ts
index 3e8ee952a22..457e5bbd40a 100644
--- a/frontend/src/metabase-lib/v1/urls.ts
+++ b/frontend/src/metabase-lib/v1/urls.ts
@@ -19,12 +19,7 @@ type UrlBuilderOpts = {
export function getUrl(
question: Question,
- {
- originalQuestion,
- query,
- includeDisplayIsLocked,
- creationType,
- }: UrlBuilderOpts = {},
+ { originalQuestion, query, creationType }: UrlBuilderOpts = {},
) {
question = question.omitTransientCardIds();
@@ -33,8 +28,8 @@ export function getUrl(
(originalQuestion && question.isDirtyComparedTo(originalQuestion))
) {
return Urls.question(null, {
- hash: question._serializeForUrl({
- includeDisplayIsLocked,
+ hash: question.serializeForUrl({
+ includeDisplayIsLocked: true,
creationType,
}),
query,
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index bcbc7dee3a4..62ed71163be 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -89,6 +89,7 @@ export interface Card<Q extends DatasetQuery = DatasetQuery>
view_count?: number;
download_perms?: DownloadPermission;
+ displayIsLocked?: boolean;
}
export interface PublicCard {
diff --git a/frontend/src/metabase/dashboard/actions/tabs.ts b/frontend/src/metabase/dashboard/actions/tabs.ts
index d448bdc7b83..5fa28430bac 100644
--- a/frontend/src/metabase/dashboard/actions/tabs.ts
+++ b/frontend/src/metabase/dashboard/actions/tabs.ts
@@ -219,7 +219,11 @@ export function getPrevDashAndTabs({
filterRemovedTabs?: boolean;
}) {
const dashId = state.dashboardId;
- const prevDash = dashId ? state.dashboards[dashId] : null;
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore - possibly infinite type error
+ const prevDash: StoreDashboard | null = dashId
+ ? state.dashboards[dashId]
+ : null;
const prevTabs =
prevDash?.tabs?.filter((t) => !filterRemovedTabs || !t.isRemoved) ?? [];
diff --git a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/utils.ts b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/utils.ts
index 14370538244..918c23c3b6a 100644
--- a/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/utils.ts
+++ b/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/utils.ts
@@ -17,7 +17,7 @@ export const isNavigatingToCreateADashboardQuestion = (
const isDashboardQuestion =
deserializedCard && deserializedCard.dashboard_id !== null;
- return isDashboardQuestion;
+ return Boolean(isDashboardQuestion);
}
return false;
diff --git a/frontend/src/metabase/documents/documents.slice.ts b/frontend/src/metabase/documents/documents.slice.ts
index feb69639be1..4ccd59156ab 100644
--- a/frontend/src/metabase/documents/documents.slice.ts
+++ b/frontend/src/metabase/documents/documents.slice.ts
@@ -84,7 +84,8 @@ const documentsSlice = createSlice({
state.cardEmbeds = action.payload;
},
setCurrentDocument: (state, action: PayloadAction<Document | null>) => {
- // @ts-expect-error - possibly infinite type error
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore - possibly infinite type error
state.currentDocument = action.payload;
},
resetDocuments: () => {
diff --git a/frontend/src/metabase/lib/card.js b/frontend/src/metabase/lib/card.js
deleted file mode 100644
index 1a2deaf46eb..00000000000
--- a/frontend/src/metabase/lib/card.js
+++ /dev/null
@@ -1,45 +0,0 @@
-import { b64hash_to_utf8, utf8_to_b64url } from "metabase/lib/encoding";
-import { equals } from "metabase/lib/utils";
-
-export function createCard(name = null) {
- return {
- name: name,
- display: "table",
- visualization_settings: {},
- dataset_query: {},
- };
-}
-
-function getCleanCard(card) {
- return {
- name: card.name,
- collectionId: card.collectionId,
- description: card.description,
- dataset_query: card.dataset_query,
- display: card.display,
- displayIsLocked: card.displayIsLocked,
- parameters: card.parameters,
- dashboardId: card.dashboardId,
- dashcardId: card.dashcardId,
- visualization_settings: card.visualization_settings,
- original_card_id: card.original_card_id,
- type: card.type,
- };
-}
-
-export function isEqualCard(card1, card2) {
- if (card1 && card2) {
- return equals(getCleanCard(card1), getCleanCard(card2));
- } else {
- return false;
- }
-}
-
-// TODO Atte Keinänen 5/31/17 Deprecated, we should move tests to Questions.spec.js
-export function serializeCardForUrl(card) {
- return utf8_to_b64url(JSON.stringify(getCleanCard(card)));
-}
-
-export function deserializeCardFromUrl(serialized) {
- return JSON.parse(b64hash_to_utf8(serialized));
-}
diff --git a/frontend/src/metabase/lib/card.ts b/frontend/src/metabase/lib/card.ts
new file mode 100644
index 00000000000..2c6975f504d
--- /dev/null
+++ b/frontend/src/metabase/lib/card.ts
@@ -0,0 +1,83 @@
+import { b64hash_to_utf8, utf8_to_b64url } from "metabase/lib/encoding";
+import { stableStringify } from "metabase/lib/objects";
+import { equals } from "metabase/lib/utils";
+import type { Card, ParameterValuesMap, UnsavedCard } from "metabase-types/api";
+
+export type SerializeCardOptions = {
+ includeDatasetQuery?: boolean;
+ includeOriginalCardId?: boolean;
+ includeDisplayIsLocked?: boolean;
+ creationType?: string;
+ parameterValues?: ParameterValuesMap;
+};
+
+function getCleanCard(
+ card: Card | UnsavedCard,
+ {
+ includeDatasetQuery = true,
+ includeOriginalCardId = true,
+ includeDisplayIsLocked = false,
+ creationType,
+ parameterValues,
+ }: SerializeCardOptions = {},
+) {
+ const value = { ...card, creationType, parameterValues };
+ const keysToInclude = [
+ "collection_id",
+ "dashboard_id",
+ "dashboardId",
+ "dashcardId",
+ "description",
+ "display",
+ "name",
+ "parameters",
+ "type",
+ "visualization_settings",
+ ];
+
+ if (includeDatasetQuery) {
+ keysToInclude.push("dataset_query");
+ }
+ if (includeOriginalCardId) {
+ keysToInclude.push("original_card_id");
+ }
+ if (includeDisplayIsLocked) {
+ keysToInclude.push("displayIsLocked");
+ }
+ if (creationType) {
+ keysToInclude.push("creationType");
+ }
+ if (parameterValues) {
+ keysToInclude.push("parameterValues");
+ }
+
+ type Key = keyof typeof value;
+
+ const res: { [key in Key]?: unknown } = {};
+ for (const key of keysToInclude) {
+ // coerce to undefined to omit
+ res[key as Key] = value[key as Key] ?? undefined;
+ }
+
+ return res;
+}
+
+export function isEqualCard(card1?: Card | null, card2?: Card | null) {
+ if (card1 && card2) {
+ return equals(getCleanCard(card1), getCleanCard(card2));
+ } else {
+ return false;
+ }
+}
+
+// TODO Atte Keinänen 5/31/17 Deprecated, we should move tests to Questions.spec.js
+export function serializeCardForUrl(
+ card: Card | UnsavedCard,
+ options: SerializeCardOptions = {},
+) {
+ return utf8_to_b64url(stableStringify(getCleanCard(card, options)));
+}
+
+export function deserializeCardFromUrl(serialized: string): Card {
+ return JSON.parse(b64hash_to_utf8(serialized));
+}
diff --git a/frontend/src/metabase/lib/urls/questions.ts b/frontend/src/metabase/lib/urls/questions.ts
index 61c2f0be46f..3496996aa23 100644
--- a/frontend/src/metabase/lib/urls/questions.ts
+++ b/frontend/src/metabase/lib/urls/questions.ts
@@ -5,7 +5,11 @@ import MetabaseSettings from "metabase/lib/settings";
import type { QuestionCreatorOpts } from "metabase-lib/v1/Question";
import Question from "metabase-lib/v1/Question";
import * as ML_Urls from "metabase-lib/v1/urls";
-import type { CardId, Card as SavedCard } from "metabase-types/api";
+import type {
+ CardId,
+ Card as SavedCard,
+ UnsavedCard,
+} from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
import { appendSlug, getEncodedUrlSearchParams } from "./utils";
@@ -17,7 +21,7 @@ type Card = Partial<SavedCard> & {
export type QuestionUrlBuilderParams = {
mode?: "view" | "notebook" | "query";
- hash?: Card | string;
+ hash?: SavedCard | UnsavedCard | string;
query?: Record<string, unknown> | string;
objectId?: number | string;
};
@@ -42,21 +46,11 @@ export function question(
objectId,
}: QuestionUrlBuilderParams = {},
) {
- if (hash && typeof hash === "object") {
- hash = serializeCardForUrl(hash);
- }
-
- if (query && typeof query === "object") {
- query = String(getEncodedUrlSearchParams(query));
- }
+ hash = encodeIfNeeded(hash, serializeCardForUrl);
+ hash = prefixIfNeeded(hash, "#");
- if (hash && hash.charAt(0) !== "#") {
- hash = "#" + hash;
- }
-
- if (query && query.charAt(0) !== "?") {
- query = "?" + query;
- }
+ query = encodeIfNeeded(query, getEncodedUrlSearchParams);
+ query = prefixIfNeeded(query, "?");
const isModel = card?.type === "model" || card?.model === "dataset";
const fallbackPath = isModel ? "model" : "question";
@@ -101,7 +95,24 @@ export function question(
return `${path}${query}${hash}`;
}
-export function serializedQuestion(card: Card, opts = {}) {
+function encodeIfNeeded<T extends object>(
+ value: T | string,
+ fn: (value: T) => string,
+) {
+ if (typeof value === "string") {
+ return value;
+ }
+ return fn(value);
+}
+
+function prefixIfNeeded(value: string, prefix: string) {
+ if (value === "" || value.startsWith(prefix)) {
+ return value;
+ }
+ return `${prefix}${value}`;
+}
+
+export function serializedQuestion(card: SavedCard | UnsavedCard, opts = {}) {
return question(null, { ...opts, hash: card });
}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index 5521c06df38..16cdb4b1c02 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -307,7 +307,7 @@ async function handleQBInit(
const deserializedCard = serializedCard
? deserializeCard(serializedCard)
- : null;
+ : undefined;
let { card, originalCard } = await resolveCards({
cardId,
diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsx
index 01679abdb1d..1accdc074dc 100644
--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx
+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx
@@ -238,7 +238,11 @@ export const setup = async ({
card,
dataset = createMockDataset(),
initialRoute = `/question${
- isSavedCard(card) ? `/${card.id}` : `#${serializeCardForUrl(card)}`
+ card == null
+ ? ""
+ : isSavedCard(card)
+ ? `/${card.id}`
+ : `#${serializeCardForUrl(card)}`
}`,
}: SetupOpts) => {
setupDatabasesEndpoints([TEST_DB]);
diff --git a/frontend/src/metabase/query_builder/utils/index.ts b/frontend/src/metabase/query_builder/utils/index.ts
index faf72501e07..89c8589ef48 100644
--- a/frontend/src/metabase/query_builder/utils/index.ts
+++ b/frontend/src/metabase/query_builder/utils/index.ts
@@ -50,7 +50,14 @@ export function getURLForCardState(
objectId?: string;
}
const options: Options = {
- hash: card && dirty ? serializeCardForUrl(card) : "",
+ hash:
+ card && dirty
+ ? serializeCardForUrl(card, {
+ includeOriginalCardId: true,
+ includeDatasetQuery: true,
+ includeDisplayIsLocked: true,
+ })
+ : "",
query,
};
const isAdHocQuestion = !card.id;
diff --git a/frontend/test/metabase-lib/lib/Question.unit.spec.js b/frontend/test/metabase-lib/lib/Question.unit.spec.js
index 57f627c0635..14ea9737f15 100644
--- a/frontend/test/metabase-lib/lib/Question.unit.spec.js
+++ b/frontend/test/metabase-lib/lib/Question.unit.spec.js
@@ -590,7 +590,7 @@ describe("Question", () => {
describe("URLs", () => {
const adhocUrl =
- "/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJsaWIvdHlwZSI6Im1icWwvcXVlcnkiLCJzdGFnZXMiOlt7ImxpYi90eXBlIjoibWJxbC5zdGFnZS9tYnFsIiwic291cmNlLXRhYmxlIjoyfV19LCJkaXNwbGF5IjoidGFibGUiLCJuYW1lIjoiUmF3IG9yZGVycyBkYXRhIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e319";
+ "/question#eyJkYXRhc2V0X3F1ZXJ5Ijp7ImRhdGFiYXNlIjoxLCJsaWIvdHlwZSI6Im1icWwvcXVlcnkiLCJzdGFnZXMiOlt7ImxpYi90eXBlIjoibWJxbC5zdGFnZS9tYnFsIiwic291cmNlLXRhYmxlIjoyfV19LCJkaXNwbGF5IjoidGFibGUiLCJuYW1lIjoiUmF3IG9yZGVycyBkYXRhIiwicGFyYW1ldGVyVmFsdWVzIjp7fSwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e319";
// Covered a lot in query_builder/actions.spec.js, just very basic cases here
// (currently getUrl has logic that is strongly tied to the logic query builder Redux actions)
@@ -982,10 +982,12 @@ describe("Question", () => {
const deserializedCard = {
...card,
parameters,
- id: undefined,
original_card_id: card.id,
+ parameterValues: {},
};
+ delete deserializedCard.id;
+
expect(parseUrl(url)).toEqual({
pathname: "/question",
query: {
diff --git a/frontend/test/metabase/lib/card.unit.spec.js b/frontend/test/metabase/lib/card.unit.spec.js
index 9bc256077a9..553687fed6a 100644
--- a/frontend/test/metabase/lib/card.unit.spec.js
+++ b/frontend/test/metabase/lib/card.unit.spec.js
@@ -1,8 +1,4 @@
-import {
- createCard,
- deserializeCardFromUrl,
- serializeCardForUrl,
-} from "metabase/lib/card";
+import { deserializeCardFromUrl, serializeCardForUrl } from "metabase/lib/card";
import {
b64_to_utf8,
b64url_to_utf8,
@@ -56,26 +52,6 @@ const getCard = ({
};
describe("lib/card", () => {
- describe("createCard", () => {
- it("should return a new card", () => {
- expect(createCard()).toEqual({
- name: null,
- display: "table",
- visualization_settings: {},
- dataset_query: {},
- });
- });
-
- it("should set the name if supplied", () => {
- expect(createCard("something")).toEqual({
- name: "something",
- display: "table",
- visualization_settings: {},
- dataset_query: {},
- });
- });
- });
-
describe("utf8_to_b64", () => {
it("should encode with non-URL-safe characters", () => {
expect(utf8_to_b64(" ?").indexOf("/")).toEqual(3);