Skip to content

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

Move template_tags and native parameters list into parameters (#79127)

Fraser364ec28c5687
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx
index 3d4eb47e131..131228654e1 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/QueryEditorAndResults.tsx
@@ -1,9 +1,7 @@
import { useState } from "react";
-import {
- QueryEditor,
- getInitialUiState,
-} from "metabase/querying/editor/components/QueryEditor";
+import { QueryEditorWithParameters } from "metabase/parameters/components/QueryEditorWithParameters";
+import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";
import { useQueryResults } from "metabase/querying/editor/hooks/use-query-results";
import { VisualizeButton } from "metabase/querying/notebook/components/Notebook";
import type * as Lib from "metabase-lib";
@@ -49,7 +47,7 @@ export function QueryEditorAndResults(props: QueryEditorAndResultsProps) {
return (
<>
- <QueryEditor
+ <QueryEditorWithParameters
query={currentQuestion.query()}
uiState={uiState}
onChangeQuery={onQueryChange}
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx
index 1416cdb54d3..50f3ba6168f 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/SqlParametersList/SqlParametersList.tsx
@@ -3,7 +3,7 @@ import { useLatest } from "react-use";
import { useSdkQuestionContext } from "embedding-sdk-bundle/components/private/SdkQuestion/context";
import { getMetadata } from "metabase/metadata-store";
-import { ResponsiveParametersList } from "metabase/querying/components/ResponsiveParametersList";
+import { ResponsiveParametersList } from "metabase/parameters/components/ResponsiveParametersList";
import { useSelector } from "metabase/redux";
import { Box } from "metabase/ui";
import * as Lib from "metabase-lib";
diff --git a/frontend/src/metabase/metrics/components/MetricQueryEditor/MetricQueryEditor.tsx b/frontend/src/metabase/metrics/components/MetricQueryEditor/MetricQueryEditor.tsx
index 43b7f090779..a931f241bef 100644
--- a/frontend/src/metabase/metrics/components/MetricQueryEditor/MetricQueryEditor.tsx
+++ b/frontend/src/metabase/metrics/components/MetricQueryEditor/MetricQueryEditor.tsx
@@ -1,6 +1,6 @@
import { useMemo } from "react";
-import { QueryEditor } from "metabase/querying/editor/components/QueryEditor";
+import { QueryEditorWithParameters } from "metabase/parameters/components/QueryEditorWithParameters";
import type { QueryEditorUiState } from "metabase/querying/editor/types";
import type * as Lib from "metabase-lib";
@@ -27,7 +27,7 @@ export function MetricQueryEditor({
);
return (
- <QueryEditor
+ <QueryEditorWithParameters
query={query}
uiState={uiState}
uiOptions={uiOptions}
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/ParametersList.tsx b/frontend/src/metabase/parameters/components/NativeQueryParametersList.tsx
similarity index 65%
rename from frontend/src/metabase/querying/components/NativeQueryEditor/slots/ParametersList.tsx
rename to frontend/src/metabase/parameters/components/NativeQueryParametersList.tsx
index 98794189036..8e874c0a5e2 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/ParametersList.tsx
+++ b/frontend/src/metabase/parameters/components/NativeQueryParametersList.tsx
@@ -1,13 +1,13 @@
-import { ResponsiveParametersList } from "metabase/querying/components/ResponsiveParametersList";
+import { useNativeQueryEditorContext } from "metabase/querying/components/NativeQueryEditor/context/NativeQueryEditorContext";
import type { ParameterId } from "metabase-types/api";
-import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+import { ResponsiveParametersList } from "./ResponsiveParametersList";
/**
- * The list of native query parameters (template tag values) shown in the top
- * bar. Renders nothing when the consumer did not provide `setParameterValue`.
+ * The list of native query parameters (template tag values). Renders nothing
+ * when the editor context has no `setParameterValue`.
*/
-export function ParametersList() {
+export function NativeQueryParametersList() {
const { question, query, setDatasetQuery, setParameterValue } =
useNativeQueryEditorContext();
diff --git a/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.tsx b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.tsx
new file mode 100644
index 00000000000..eb04db90f20
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.tsx
@@ -0,0 +1,24 @@
+import {
+ QueryEditor,
+ type QueryEditorProps,
+} from "metabase/querying/editor/components/QueryEditor/QueryEditor";
+
+import { NativeQueryParametersList } from "../NativeQueryParametersList";
+import { TemplateTagsSidebar } from "../TemplateTagsSidebar";
+
+export type QueryEditorWithParametersProps = Omit<
+ QueryEditorProps,
+ "parametersList" | "templateTagsSidebar"
+>;
+
+export function QueryEditorWithParameters(
+ props: QueryEditorWithParametersProps,
+) {
+ return (
+ <QueryEditor
+ {...props}
+ parametersList={<NativeQueryParametersList />}
+ templateTagsSidebar={TemplateTagsSidebar}
+ />
+ );
+}
diff --git a/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.unit.spec.tsx b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.unit.spec.tsx
new file mode 100644
index 00000000000..66523290c33
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/QueryEditorWithParameters.unit.spec.tsx
@@ -0,0 +1,73 @@
+import { render, screen } from "@testing-library/react";
+import { isValidElement } from "react";
+
+import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";
+import { QueryEditor } from "metabase/querying/editor/components/QueryEditor/QueryEditor";
+import { SAMPLE_METADATA } from "metabase-lib/test-helpers";
+import Question from "metabase-lib/v1/Question";
+import { createMockCard } from "metabase-types/api/mocks";
+
+import { NativeQueryParametersList } from "../NativeQueryParametersList";
+import { TemplateTagsSidebar } from "../TemplateTagsSidebar";
+
+import { QueryEditorWithParameters } from "./QueryEditorWithParameters";
+
+jest.mock(
+ "metabase/querying/editor/components/QueryEditor/QueryEditor",
+ () => ({
+ ...jest.requireActual(
+ "metabase/querying/editor/components/QueryEditor/QueryEditor",
+ ),
+ QueryEditor: jest.fn(() => <div data-testid="query-editor" />),
+ }),
+);
+
+function setup() {
+ const query = new Question(createMockCard(), SAMPLE_METADATA).query();
+ const onChangeQuery = jest.fn();
+ const onChangeUiState = jest.fn();
+
+ render(
+ <QueryEditorWithParameters
+ query={query}
+ uiState={getInitialUiState()}
+ height={300}
+ onChangeQuery={onChangeQuery}
+ onChangeUiState={onChangeUiState}
+ />,
+ );
+
+ const [props] = jest.mocked(QueryEditor).mock.calls[0];
+ return { props, query, onChangeQuery, onChangeUiState };
+}
+
+describe("QueryEditorWithParameters", () => {
+ beforeEach(() => {
+ jest.mocked(QueryEditor).mockClear();
+ });
+
+ it("should render NativeQueryParametersList in the parametersList slot", () => {
+ const { props } = setup();
+ const { parametersList } = props;
+
+ expect(screen.getByTestId("query-editor")).toBeInTheDocument();
+ expect(isValidElement(parametersList) && parametersList.type).toBe(
+ NativeQueryParametersList,
+ );
+ });
+
+ it("should pass TemplateTagsSidebar as the templateTagsSidebar", () => {
+ const { props } = setup();
+
+ expect(props.templateTagsSidebar).toBe(TemplateTagsSidebar);
+ });
+
+ it("should forward the remaining props to QueryEditor", () => {
+ const { props, query, onChangeQuery, onChangeUiState } = setup();
+
+ expect(props.query).toBe(query);
+ expect(props.height).toBe(300);
+ expect(props.onChangeQuery).toBe(onChangeQuery);
+ expect(props.onChangeUiState).toBe(onChangeUiState);
+ });
+});
diff --git a/frontend/src/metabase/parameters/components/QueryEditorWithParameters/index.ts b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/index.ts
new file mode 100644
index 00000000000..c4702e6ea27
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/index.ts
@@ -0,0 +1,5 @@
+export {
+ QueryEditorWithParameters,
+ loadQueryEditorWithParameters,
+} from "./lazy";
+export type { QueryEditorWithParametersProps } from "./QueryEditorWithParameters";
diff --git a/frontend/src/metabase/parameters/components/QueryEditorWithParameters/lazy.tsx b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/lazy.tsx
new file mode 100644
index 00000000000..a79bf3b1b97
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/QueryEditorWithParameters/lazy.tsx
@@ -0,0 +1,30 @@
+import { Suspense, lazy } from "react";
+
+import type { QueryEditorWithParametersProps } from "./QueryEditorWithParameters";
+
+// The chunk name matches the editor's own lazy import,
+// so rspack emits the parameter plugs in the editor's chunk instead of one of their own.
+const importQueryEditorWithParameters = () =>
+ import(
+ /* webpackChunkName: "query-editor" */
+ "./QueryEditorWithParameters"
+ );
+
+export const loadQueryEditorWithParameters = () =>
+ importQueryEditorWithParameters();
+
+const LazyQueryEditorWithParameters = lazy(() =>
+ importQueryEditorWithParameters().then(({ QueryEditorWithParameters }) => ({
+ default: QueryEditorWithParameters,
+ })),
+);
+
+export function QueryEditorWithParameters(
+ props: QueryEditorWithParametersProps,
+) {
+ return (
+ <Suspense fallback={null}>
+ <LazyQueryEditorWithParameters {...props} />
+ </Suspense>
+ );
+}
diff --git a/frontend/src/metabase/querying/components/ResponsiveParametersList.module.css b/frontend/src/metabase/parameters/components/ResponsiveParametersList.module.css
similarity index 100%
rename from frontend/src/metabase/querying/components/ResponsiveParametersList.module.css
rename to frontend/src/metabase/parameters/components/ResponsiveParametersList.module.css
diff --git a/frontend/src/metabase/querying/components/ResponsiveParametersList.tsx b/frontend/src/metabase/parameters/components/ResponsiveParametersList.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/ResponsiveParametersList.tsx
rename to frontend/src/metabase/parameters/components/ResponsiveParametersList.tsx
diff --git a/frontend/src/metabase/querying/components/ResponsiveParameterList.unit.spec.tsx b/frontend/src/metabase/parameters/components/ResponsiveParametersList.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/ResponsiveParameterList.unit.spec.tsx
rename to frontend/src/metabase/parameters/components/ResponsiveParametersList.unit.spec.tsx
diff --git a/frontend/src/metabase/querying/components/SyncedParametersList.tsx b/frontend/src/metabase/parameters/components/SyncedParametersList.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/SyncedParametersList.tsx
rename to frontend/src/metabase/parameters/components/SyncedParametersList.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/TagEditorHelp.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/TagEditorHelp.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/TagEditorHelp.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/TagEditorHelp.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/index.ts b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/index.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/index.ts
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/index.ts
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/common.unit.spec.ts b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/common.unit.spec.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/common.unit.spec.ts
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/common.unit.spec.ts
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/enterprise.unit.spec.ts b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/enterprise.unit.spec.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/enterprise.unit.spec.ts
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/enterprise.unit.spec.ts
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/premium.unit.spec.ts b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/premium.unit.spec.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/premium.unit.spec.ts
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/premium.unit.spec.ts
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/setup.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/setup.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorHelp/tests/setup.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorHelp/tests/setup.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParam.module.css b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.module.css
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParam.module.css
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.module.css
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParam.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParam.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParam.unit.spec.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParam.unit.spec.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParam.unit.spec.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/DefaultRequiredValueControl.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/DefaultRequiredValueControl.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/DefaultRequiredValueControl.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/DefaultRequiredValueControl.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FieldAliasInput.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FieldAliasInput.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FieldAliasInput.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FieldAliasInput.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FieldMappingSelect.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FieldMappingSelect.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FieldMappingSelect.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FieldMappingSelect.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FilterWidgetLabelInput.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FilterWidgetLabelInput.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FilterWidgetLabelInput.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FilterWidgetLabelInput.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FilterWidgetTypeSelect.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FilterWidgetTypeSelect.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/FilterWidgetTypeSelect.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/FilterWidgetTypeSelect.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/ParameterMultiSelectInput.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/ParameterMultiSelectInput.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/ParameterMultiSelectInput.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/ParameterMultiSelectInput.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TableMappingSelect.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TableMappingSelect.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TableMappingSelect.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TableMappingSelect.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TagEditorParam.module.css b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TagEditorParam.module.css
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TagEditorParam.module.css
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TagEditorParam.module.css
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TagEditorParam.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TagEditorParam.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/TagEditorParam.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/TagEditorParam.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/VariableTypeSelect.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/VariableTypeSelect.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/VariableTypeSelect.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/VariableTypeSelect.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/index.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/index.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorParamParts/index.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorParamParts/index.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorSidebar.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorSidebar.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorSidebar.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorSidebar.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/TagEditorSidebar.unit.spec.tsx b/frontend/src/metabase/parameters/components/TagEditor/TagEditorSidebar.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/TagEditorSidebar.unit.spec.tsx
rename to frontend/src/metabase/parameters/components/TagEditor/TagEditorSidebar.unit.spec.tsx
diff --git a/frontend/src/metabase/querying/components/template_tags/types.ts b/frontend/src/metabase/parameters/components/TagEditor/types.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/template_tags/types.ts
rename to frontend/src/metabase/parameters/components/TagEditor/types.ts
diff --git a/frontend/src/metabase/parameters/components/TemplateTagsSidebar.tsx b/frontend/src/metabase/parameters/components/TemplateTagsSidebar.tsx
new file mode 100644
index 00000000000..a2dd97b3aba
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/TemplateTagsSidebar.tsx
@@ -0,0 +1,82 @@
+import { useRef } from "react";
+
+import { useListDatabasesQuery } from "metabase/api";
+import type { TemplateTagsSidebarProps } from "metabase/querying/editor/types";
+import { checkNotNull } from "metabase/utils/types";
+import * as Lib from "metabase-lib";
+
+import { TagEditorSidebar } from "./TagEditor/TagEditorSidebar";
+
+const VISIBILITY_ALWAYS_ENABLED = () => "enabled" as const;
+
+export function TemplateTagsSidebar({
+ question,
+ query,
+ onClose,
+ setParameterValues,
+ parameterValues,
+ parametersAreUserVisible,
+ onChangeQuery,
+ canUseSampleDatabase,
+}: TemplateTagsSidebarProps) {
+ const { data: databases } = useListDatabasesQuery();
+ const sampleDatabaseId = databases?.data.find(
+ (database) => database.is_sample,
+ )?.id;
+
+ // Switching a variable's type calls setTemplateTag and setTemplateTagConfig within one event handler.
+ // React props don't update between those synchronous calls,
+ // so each change is composed on top of the latest query held in this ref.
+ const latestQueryRef = useRef(query);
+ latestQueryRef.current = query;
+
+ const nativeQuery = checkNotNull(question.legacyNativeQuery());
+
+ const commitQuery = (newQuery: Lib.Query) => {
+ latestQueryRef.current = newQuery;
+ onChangeQuery(newQuery);
+ };
+
+ return (
+ <TagEditorSidebar
+ question={question}
+ query={nativeQuery}
+ onClose={onClose}
+ sampleDatabaseId={
+ canUseSampleDatabase === false ? undefined : sampleDatabaseId
+ }
+ setTemplateTag={(tag) => {
+ const currentQuery = latestQueryRef.current;
+ const templateTags = Lib.templateTags(currentQuery);
+ commitQuery(
+ Lib.withTemplateTags(currentQuery, {
+ ...templateTags,
+ [tag.name]: tag,
+ }),
+ );
+ }}
+ setParameterValue={(tagId, value) => {
+ setParameterValues({
+ ...parameterValues,
+ [tagId]: value,
+ });
+ }}
+ setTemplateTagConfig={(tag, config) => {
+ const latestNativeQuery = checkNotNull(
+ question.setQuery(latestQueryRef.current).legacyNativeQuery(),
+ );
+ commitQuery(
+ latestNativeQuery
+ .setTemplateTagConfig(tag, config)
+ .question()
+ .query(),
+ );
+ }}
+ setDatasetQuery={(newQuery) => {
+ commitQuery(question.setDatasetQuery(newQuery).query());
+ }}
+ getEmbeddedParameterVisibility={VISIBILITY_ALWAYS_ENABLED}
+ parametersAreUserVisible={parametersAreUserVisible}
+ />
+ );
+}
diff --git a/frontend/src/metabase/parameters/components/TemplateTagsSidebar.unit.spec.tsx b/frontend/src/metabase/parameters/components/TemplateTagsSidebar.unit.spec.tsx
new file mode 100644
index 00000000000..51b4d6fe957
--- /dev/null
+++ b/frontend/src/metabase/parameters/components/TemplateTagsSidebar.unit.spec.tsx
@@ -0,0 +1,100 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupDatabasesEndpoints,
+ setupParameterValuesEndpoints,
+ setupSearchEndpoints,
+} from "__support__/server-mocks";
+import { createMockEntitiesState } from "__support__/store";
+import { renderWithProviders, screen } from "__support__/ui";
+import { getMetadata } from "metabase/metadata-store";
+import { createMockState } from "metabase/redux/store/mocks";
+import Question from "metabase-lib/v1/Question";
+import {
+ createMockCard,
+ createMockDatabase,
+ createMockNativeDatasetQuery,
+ createMockTemplateTag,
+} from "metabase-types/api/mocks";
+
+import { TemplateTagsSidebar } from "./TemplateTagsSidebar";
+
+const SAMPLE_DB_ID = 1;
+const WRITABLE_DB_ID = 2;
+
+interface SetupOpts {
+ canUseSampleDatabase?: boolean;
+}
+
+const setup = ({ canUseSampleDatabase }: SetupOpts = {}) => {
+ const sampleDatabase = createMockDatabase({
+ id: SAMPLE_DB_ID,
+ name: "Sample Database",
+ is_sample: true,
+ });
+ const writableDatabase = createMockDatabase({
+ id: WRITABLE_DB_ID,
+ name: "Writable Postgres",
+ engine: "postgres",
+ });
+ const nativeQuery = createMockNativeDatasetQuery({
+ database: WRITABLE_DB_ID,
+ native: {
+ query: "SELECT {{x}}",
+ "template-tags": {
+ x: createMockTemplateTag({
+ name: "x",
+ "display-name": "X",
+ type: "text",
+ }),
+ },
+ },
+ });
+ const card = createMockCard({ dataset_query: nativeQuery });
+ const state = createMockState({
+ entities: createMockEntitiesState({
+ databases: [sampleDatabase, writableDatabase],
+ }),
+ });
+ const metadata = getMetadata(state);
+ const question = new Question(card, metadata);
+
+ setupDatabasesEndpoints([sampleDatabase, writableDatabase]);
+ setupSearchEndpoints([]);
+ setupParameterValuesEndpoints({ values: [], has_more_values: false });
+
+ renderWithProviders(
+ <TemplateTagsSidebar
+ question={question}
+ query={question.query()}
+ onChangeQuery={jest.fn()}
+ onClose={jest.fn()}
+ parameterValues={{}}
+ setParameterValues={jest.fn()}
+ canUseSampleDatabase={canUseSampleDatabase}
+ />,
+ { storeInitialState: state },
+ );
+};
+
+describe("TemplateTagsSidebar", () => {
+ it("hides the 'Try it' examples when the sample database can't be used, e.g. in transforms (metabase#78037)", async () => {
+ setup({ canUseSampleDatabase: false });
+
+ await userEvent.click(screen.getByRole("tab", { name: "Help" }));
+
+ expect(
+ screen.queryByRole("button", { name: "Try it" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the 'Try it' examples when the sample database is available", async () => {
+ setup({});
+
+ await userEvent.click(screen.getByRole("tab", { name: "Help" }));
+
+ expect(
+ screen.getAllByRole("button", { name: "Try it" }).length,
+ ).toBeGreaterThan(0);
+ });
+});
diff --git a/frontend/src/metabase/querying/components/use-sync-url-parameters.ts b/frontend/src/metabase/parameters/components/use-sync-url-parameters.ts
similarity index 100%
rename from frontend/src/metabase/querying/components/use-sync-url-parameters.ts
rename to frontend/src/metabase/parameters/components/use-sync-url-parameters.ts
diff --git a/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx b/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx
index acd9ed982d1..b9fe7d2a2db 100644
--- a/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx
+++ b/frontend/src/metabase/public/components/EmbedFrame/EmbedFrame.tsx
@@ -19,9 +19,9 @@ import { EmbeddingFooter } from "metabase/embedding/components/EmbeddingFooter/E
import EmbedThemeS from "metabase/embedding/theme.module.css";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { ParametersList } from "metabase/parameters/components/ParametersList";
+import { SyncedParametersList } from "metabase/parameters/components/SyncedParametersList";
+import { useSyncUrlParameters } from "metabase/parameters/components/use-sync-url-parameters";
import { getVisibleParameters } from "metabase/parameters/utils/ui";
-import { SyncedParametersList } from "metabase/querying/components/SyncedParametersList";
-import { useSyncUrlParameters } from "metabase/querying/components/use-sync-url-parameters";
import { useSelector } from "metabase/redux";
import { getSetting } from "metabase/settings";
import { FullWidthContainer } from "metabase/styled-components/layout/FullWidthContainer";
diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx
index 7f4195b734a..d3611b23dd0 100644
--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx
+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx
@@ -23,12 +23,12 @@ import { getSemanticTypeIcon } from "metabase/common/utils/fields";
import CS from "metabase/css/core/index.css";
import { getMetadata } from "metabase/metadata-store";
import { HasResultsAlertPrompt } from "metabase/notifications/HasResultsAlertPrompt";
+import { TagEditorSidebar } from "metabase/parameters/components/TagEditor/TagEditorSidebar";
import { DataReference } from "metabase/querying/components/DataReference/DataReference";
import type { DataReferenceItem } from "metabase/querying/components/DataReference/types";
import { getInitialEditorHeight } from "metabase/querying/components/NativeQueryEditor/utils";
import { QueryVisualization } from "metabase/querying/components/QueryVisualization";
import { SnippetSidebar } from "metabase/querying/components/SnippetSidebar";
-import { TagEditorSidebar } from "metabase/querying/components/template_tags/TagEditorSidebar";
import { MODAL_TYPES } from "metabase/querying/constants";
import { connect, useDispatch } from "metabase/redux";
import { setUIControls } from "metabase/redux/query-builder";
diff --git a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx
index 96d41052d93..466f9fdba2b 100644
--- a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx
@@ -1,9 +1,9 @@
import { match } from "ts-pattern";
+import { TagEditorSidebar } from "metabase/parameters/components/TagEditor/TagEditorSidebar";
import { DataReference } from "metabase/querying/components/DataReference/DataReference";
import type { DataReferenceItem } from "metabase/querying/components/DataReference/types";
import { SnippetSidebar } from "metabase/querying/components/SnippetSidebar";
-import { TagEditorSidebar } from "metabase/querying/components/template_tags/TagEditorSidebar";
import { useDispatch, useSelector } from "metabase/redux";
import type Question from "metabase-lib/v1/Question";
import type {
diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx
index 9259a7c659d..2269b2da44e 100644
--- a/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx
@@ -4,8 +4,8 @@ import cx from "classnames";
import { DebouncedFrame } from "metabase/common/components/DebouncedFrame";
import CS from "metabase/css/core/index.css";
import { HasResultsAlertPrompt } from "metabase/notifications/HasResultsAlertPrompt";
+import { SyncedParametersList } from "metabase/parameters/components/SyncedParametersList";
import { QueryVisualization } from "metabase/querying/components/QueryVisualization";
-import { SyncedParametersList } from "metabase/querying/components/SyncedParametersList";
import type { QueryModalType } from "metabase/querying/constants";
import type { SelectionRange } from "metabase/querying/editor/types";
import { TimeseriesChrome } from "metabase/querying/filters/components/TimeseriesChrome";
diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
index 98c138fc257..c2f43fdf379 100644
--- a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx
@@ -1,4 +1,5 @@
import { useInlineSQLPrompt } from "metabase/metabot/components/MetabotInlineSQLPrompt";
+import { NativeQueryParametersList } from "metabase/parameters/components/NativeQueryParametersList";
import { NativeQueryEditor } from "metabase/querying/components/NativeQueryEditor";
import type { QueryModalType } from "metabase/querying/constants";
import type { SelectionRange } from "metabase/querying/editor/types";
@@ -107,8 +108,7 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {
isPromptInputOpen={inlineSQLPrompt?.isPromptOpen}
onTogglePromptInput={inlineSQLPrompt?.togglePrompt}
>
- <NativeQueryEditor.TopBar>
- <NativeQueryEditor.ParametersList />
+ <NativeQueryEditor.TopBar leftContent={<NativeQueryParametersList />}>
<NativeQueryEditor.Sidebar />
<NativeQueryEditor.VisibilityToggler />
</NativeQueryEditor.TopBar>
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx
index 08282ca6fa5..6a59fd41b92 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx
@@ -6,7 +6,6 @@ describe("NativeQueryEditor composition API", () => {
it("exposes the composable parts as static members", () => {
expect(NativeQueryEditor.TopBar).toBeDefined();
expect(NativeQueryEditor.Sidebar).toBeDefined();
- expect(NativeQueryEditor.ParametersList).toBeDefined();
expect(NativeQueryEditor.VisibilityToggler).toBeDefined();
expect(NativeQueryEditor.RunButton).toBeDefined();
});
@@ -14,7 +13,6 @@ describe("NativeQueryEditor composition API", () => {
it.each([
["TopBar", NativeQueryEditor.TopBar],
["Sidebar", NativeQueryEditor.Sidebar],
- ["ParametersList", NativeQueryEditor.ParametersList],
["VisibilityToggler", NativeQueryEditor.VisibilityToggler],
["RunButton", NativeQueryEditor.RunButton],
])("throws when %s is rendered outside the editor", (_name, Part) => {
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.tsx
index fba553c9ed2..3014ad23d0a 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -4,7 +4,6 @@ import {
type NativeQueryEditorCoreProps,
NativeQueryEditorRoot,
} from "./NativeQueryEditorRoot";
-import { ParametersList } from "./slots/ParametersList";
import { RunButton } from "./slots/RunButton";
import { Sidebar } from "./slots/Sidebar";
import { TopBar } from "./slots/TopBar";
@@ -21,7 +20,6 @@ type NativeQueryEditorProps = NativeQueryEditorCoreProps & {
*
* <NativeQueryEditor question={question} query={query} setDatasetQuery={...}>
* <NativeQueryEditor.TopBar>
- * <NativeQueryEditor.ParametersList />
* <NativeQueryEditor.Sidebar features={...} />
* <NativeQueryEditor.VisibilityToggler />
* </NativeQueryEditor.TopBar>
@@ -42,7 +40,6 @@ const NativeQueryEditorBase = forwardRef<
export const NativeQueryEditor = Object.assign(NativeQueryEditorBase, {
TopBar,
Sidebar,
- ParametersList,
VisibilityToggler,
RunButton,
});
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/__mocks__/NativeQueryEditor.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/__mocks__/NativeQueryEditor.tsx
index 04a206900d3..89b47dc6abc 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/__mocks__/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/__mocks__/NativeQueryEditor.tsx
@@ -1,8 +1,6 @@
import type { ChangeEvent } from "react";
-import CS from "metabase/css/core/index.css";
import { DataSourceSelectors } from "metabase/querying/components/NativeQueryEditor/DataSourceSelectors";
-import { SyncedParametersList } from "metabase/querying/components/SyncedParametersList";
import type { DatabaseId, TableId } from "metabase-types/api";
import type { NativeQueryEditorCoreProps } from "../NativeQueryEditorRoot";
@@ -16,7 +14,6 @@ type NativeQueryEditorProps = Pick<
| "question"
| "readOnly"
| "setDatasetQuery"
- | "setParameterValue"
>;
export const NativeQueryEditor = ({
@@ -27,7 +24,6 @@ export const NativeQueryEditor = ({
question,
readOnly,
setDatasetQuery,
- setParameterValue,
}: NativeQueryEditorProps) => {
const onChange = (evt: ChangeEvent<HTMLTextAreaElement>) => {
setDatasetQuery(query.setQueryText(evt.target.value));
@@ -62,12 +58,6 @@ export const NativeQueryEditor = ({
{query.queryText && (
<textarea value={query.queryText()} onChange={onChange} />
)}
- <SyncedParametersList
- className={CS.mt1}
- parameters={query.question().parameters()}
- setParameterValue={setParameterValue}
- commitImmediately
- />
</div>
);
};
@@ -78,6 +68,5 @@ export const NativeQueryEditor = ({
const Noop = () => null;
NativeQueryEditor.TopBar = Noop;
NativeQueryEditor.Sidebar = Noop;
-NativeQueryEditor.ParametersList = Noop;
NativeQueryEditor.VisibilityToggler = Noop;
NativeQueryEditor.RunButton = Noop;
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/TopBar.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/slots/TopBar.tsx
index 3ea898cd58a..4a80b063435 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/slots/TopBar.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/slots/TopBar.tsx
@@ -1,10 +1,4 @@
-import {
- Children,
- type PropsWithChildren,
- type ReactNode,
- forwardRef,
- isValidElement,
-} from "react";
+import { type PropsWithChildren, type ReactNode, forwardRef } from "react";
import { Flex } from "metabase/ui";
import type { DatabaseId, TableId } from "metabase-types/api";
@@ -12,79 +6,70 @@ import type { DatabaseId, TableId } from "metabase-types/api";
import { DataSourceSelectors } from "../DataSourceSelectors/DataSourceSelectors";
import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
-import { ParametersList } from "./ParametersList";
+type TopBarProps = PropsWithChildren<{
+ leftContent?: ReactNode;
+}>;
/**
- * The top bar of the native query editor. Renders the data source selector on
- * the left (from context) and lays out its children, keeping the parameters
- * list on the left and pushing the remaining actions (sidebar buttons,
- * visibility toggler, custom content) into the right-aligned cluster.
+ * The top bar of the native query editor. Renders the data source selector,
+ * then `leftContent`, and right-aligns its children.
*/
-export const TopBar = forwardRef<HTMLDivElement, PropsWithChildren>(
- function TopBar({ children }, ref) {
- const {
- question,
- query,
- canChangeDatabase,
- isNativeEditorOpen,
- readOnly,
- editorContext,
- setDatasetQuery,
- onSetDatabaseId,
- focusEditor,
- databaseIsDisabled,
- databaseDisabledTooltip,
- } = useNativeQueryEditorContext();
+export const TopBar = forwardRef<HTMLDivElement, TopBarProps>(function TopBar(
+ { leftContent, children },
+ ref,
+) {
+ const {
+ question,
+ query,
+ canChangeDatabase,
+ isNativeEditorOpen,
+ readOnly,
+ editorContext,
+ setDatasetQuery,
+ onSetDatabaseId,
+ focusEditor,
+ databaseIsDisabled,
+ databaseDisabledTooltip,
+ } = useNativeQueryEditorContext();
- if (!question) {
- return null;
- }
-
- const setTableId = (tableId: TableId) => {
- const table = query.metadata().table(tableId);
- if (table && table.name !== query.collection()) {
- setDatasetQuery(query.setCollectionName(table.name));
- }
- };
+ if (!question) {
+ return null;
+ }
- const setDatabaseId = (databaseId: DatabaseId) => {
- if (question.databaseId() !== databaseId) {
- setDatasetQuery(query.setDatabaseId(databaseId).setDefaultCollection());
- onSetDatabaseId?.(databaseId);
- focusEditor();
- }
- };
+ const setTableId = (tableId: TableId) => {
+ const table = query.metadata().table(tableId);
+ if (table && table.name !== query.collection()) {
+ setDatasetQuery(query.setCollectionName(table.name));
+ }
+ };
- const leftActions: ReactNode[] = [];
- const rightActions: ReactNode[] = [];
- Children.toArray(children).forEach((child) => {
- if (isValidElement(child) && child.type === ParametersList) {
- leftActions.push(child);
- } else {
- rightActions.push(child);
- }
- });
+ const setDatabaseId = (databaseId: DatabaseId) => {
+ if (question.databaseId() !== databaseId) {
+ setDatasetQuery(query.setDatabaseId(databaseId).setDefaultCollection());
+ onSetDatabaseId?.(databaseId);
+ focusEditor();
+ }
+ };
- return (
- <Flex align="flex-start" data-testid="native-query-top-bar" ref={ref}>
- {canChangeDatabase && (
- <DataSourceSelectors
- isNativeEditorOpen={isNativeEditorOpen}
- query={query}
- question={question}
- readOnly={readOnly}
- setDatabaseId={setDatabaseId}
- setTableId={setTableId}
- editorContext={editorContext}
- databaseIsDisabled={databaseIsDisabled}
- databaseDisabledTooltip={databaseDisabledTooltip}
- />
- )}
- {leftActions}
- <Flex ml="auto" gap="xl" mr="xl" align="center" h="3rem" pl="lg">
- {rightActions}
- </Flex>
+ return (
+ <Flex align="flex-start" data-testid="native-query-top-bar" ref={ref}>
+ {canChangeDatabase && (
+ <DataSourceSelectors
+ isNativeEditorOpen={isNativeEditorOpen}
+ query={query}
+ question={question}
+ readOnly={readOnly}
+ setDatabaseId={setDatabaseId}
+ setTableId={setTableId}
+ editorContext={editorContext}
+ databaseIsDisabled={databaseIsDisabled}
+ databaseDisabledTooltip={databaseDisabledTooltip}
+ />
+ )}
+ {leftContent}
+ <Flex ml="auto" gap="xl" mr="xl" align="center" h="3rem" pl="lg">
+ {children}
</Flex>
- );
- },
-);
+ </Flex>
+ );
+});
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx
index 417453876d9..82514f7b2d1 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.tsx
@@ -1,16 +1,15 @@
-import { useRef, useState } from "react";
+import { type ComponentType, useState } from "react";
import { useMount } from "react-use";
import { match } from "ts-pattern";
-import { useListDatabasesQuery } from "metabase/api";
-import { TagEditorSidebar } from "metabase/querying/components/template_tags/TagEditorSidebar";
import { Box } from "metabase/ui";
-import * as Lib from "metabase-lib";
+import type * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type { NativeQuerySnippet, RowValue } from "metabase-types/api";
import { DataReference } from "../../../../components/DataReference/DataReference";
import { SnippetSidebar } from "../../../../components/SnippetSidebar";
+import type { TemplateTagsSidebarProps } from "../../../types";
import S from "./NativeQuerySidebar.module.css";
@@ -32,6 +31,7 @@ type NativeQuerySidebarProps = {
setParameterValues: (newParameterValues: Record<string, RowValue>) => void;
parametersAreUserVisible?: boolean;
canUseSampleDatabase?: boolean;
+ templateTagsSidebar: ComponentType<TemplateTagsSidebarProps>;
};
export function NativeQuerySidebar({
@@ -62,7 +62,7 @@ export function NativeQuerySidebar({
<QueryDataReferenceSidebar {...props} />
))
.with({ isTemplateTagsSidebarOpen: true }, () => (
- <TemplateTagsSidebar {...props} />
+ <QueryTemplateTagsSidebar {...props} />
))
.otherwise(() => null)}
</Box>
@@ -122,9 +122,8 @@ function QuerySnippetSidebar({
);
}
-const VISIBILITY_ALWAYS_ENABLED = () => "enabled" as const;
-
-function TemplateTagsSidebar({
+function QueryTemplateTagsSidebar({
+ templateTagsSidebar: TemplateTagsSidebar,
question,
query,
onToggleTemplateTagsSidebar,
@@ -134,60 +133,16 @@ function TemplateTagsSidebar({
onChangeQuery,
canUseSampleDatabase,
}: NativeQuerySidebarProps) {
- const { data: databases } = useListDatabasesQuery();
- const sampleDatabaseId = databases?.data.find(
- (database) => database.is_sample,
- )?.id;
-
- // The template-tag editor fires several query mutations within a single event
- // handler (e.g. switching a variable's type updates both the tag and its
- // value-source config). React props don't update between those synchronous
- // calls, so we track the latest query in a ref and compose each change on top
- // of it; otherwise the second `onChangeQuery` would clobber the first.
- const latestQueryRef = useRef(query);
- latestQueryRef.current = query;
-
- const commitQuery = (newQuery: Lib.Query) => {
- latestQueryRef.current = newQuery;
- onChangeQuery(newQuery);
- };
-
return (
- <TagEditorSidebar
+ <TemplateTagsSidebar
question={question}
- query={question.legacyNativeQuery()!}
- onClose={onToggleTemplateTagsSidebar}
- sampleDatabaseId={
- canUseSampleDatabase === false ? undefined : sampleDatabaseId
- }
- setTemplateTag={(tag) => {
- const currentQuery = latestQueryRef.current;
- const templateTags = Lib.templateTags(currentQuery);
- commitQuery(
- Lib.withTemplateTags(currentQuery, {
- ...templateTags,
- [tag.name]: tag,
- }),
- );
- }}
- setParameterValue={(tagId, value) => {
- setParameterValues({
- ...parameterValues,
- [tagId]: value,
- });
- }}
- setTemplateTagConfig={(tag, config) => {
- const newQuery = question
- .setQuery(latestQueryRef.current)
- .legacyNativeQuery()!
- .setTemplateTagConfig(tag, config);
- commitQuery(newQuery.question().query());
- }}
- setDatasetQuery={(newQuery) => {
- commitQuery(question.setDatasetQuery(newQuery).query());
- }}
- getEmbeddedParameterVisibility={VISIBILITY_ALWAYS_ENABLED}
+ query={query}
+ parameterValues={parameterValues}
parametersAreUserVisible={parametersAreUserVisible}
+ canUseSampleDatabase={canUseSampleDatabase}
+ onChangeQuery={onChangeQuery}
+ setParameterValues={setParameterValues}
+ onClose={onToggleTemplateTagsSidebar}
/>
);
}
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.unit.spec.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.unit.spec.tsx
index 13f69e43ba9..de036510380 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.unit.spec.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/NativeQuerySidebar/NativeQuerySidebar.unit.spec.tsx
@@ -1,108 +1,128 @@
-import userEvent from "@testing-library/user-event";
-
+import { createMockMetadata } from "__support__/metadata";
import {
setupDatabasesEndpoints,
- setupParameterValuesEndpoints,
setupSearchEndpoints,
} from "__support__/server-mocks";
-import { createMockEntitiesState } from "__support__/store";
-import { renderWithProviders, screen } from "__support__/ui";
-import { getMetadata } from "metabase/metadata-store";
-import { createMockState } from "metabase/redux/store/mocks";
+import {
+ renderWithProviders,
+ screen,
+ waitForLoaderToBeRemoved,
+} from "__support__/ui";
import Question from "metabase-lib/v1/Question";
import {
createMockCard,
createMockDatabase,
createMockNativeDatasetQuery,
- createMockTemplateTag,
} from "metabase-types/api/mocks";
+import type { TemplateTagsSidebarProps } from "../../../types";
+
import { NativeQuerySidebar } from "./NativeQuerySidebar";
-const SAMPLE_DB_ID = 1;
-const WRITABLE_DB_ID = 2;
+const TemplateTagsSidebarStub = jest.fn((_props: TemplateTagsSidebarProps) => (
+ <div data-testid="template-tags-sidebar" />
+));
-interface SetupOpts {
- canUseSampleDatabase?: boolean;
-}
+type SetupOpts = {
+ isDataReferenceOpen?: boolean;
+ isTemplateTagsSidebarOpen?: boolean;
+};
-const setup = ({ canUseSampleDatabase }: SetupOpts = {}) => {
- const sampleDatabase = createMockDatabase({
- id: SAMPLE_DB_ID,
- name: "Sample Database",
- is_sample: true,
- });
- const writableDatabase = createMockDatabase({
- id: WRITABLE_DB_ID,
- name: "Writable Postgres",
- engine: "postgres",
- });
- const card = createMockCard({
- dataset_query: createMockNativeDatasetQuery({
- database: WRITABLE_DB_ID,
- native: {
- query: "SELECT {{x}}",
- "template-tags": {
- x: createMockTemplateTag({
- name: "x",
- "display-name": "X",
- type: "text",
- }),
- },
- },
- }),
- });
- const state = createMockState({
- entities: createMockEntitiesState({
- databases: [sampleDatabase, writableDatabase],
+function setup({
+ isDataReferenceOpen = false,
+ isTemplateTagsSidebarOpen = false,
+}: SetupOpts = {}) {
+ const database = createMockDatabase();
+ const metadata = createMockMetadata({ databases: [database] });
+ const question = new Question(
+ createMockCard({
+ dataset_query: createMockNativeDatasetQuery({ database: database.id }),
}),
- });
- const metadata = getMetadata(state);
- const question = new Question(card, metadata);
+ metadata,
+ );
+ const query = question.query();
+ const parameterValues = { tag: "value" };
+ const onChangeQuery = jest.fn();
+ const setParameterValues = jest.fn();
+ const onToggleTemplateTagsSidebar = jest.fn();
- setupDatabasesEndpoints([sampleDatabase, writableDatabase]);
+ setupDatabasesEndpoints([database]);
setupSearchEndpoints([]);
- setupParameterValuesEndpoints({ values: [], has_more_values: false });
renderWithProviders(
<NativeQuerySidebar
question={question}
- query={question.query()}
+ query={query}
isNative
- isTemplateTagsSidebarOpen
- onChangeQuery={jest.fn()}
+ isDataReferenceOpen={isDataReferenceOpen}
+ isTemplateTagsSidebarOpen={isTemplateTagsSidebarOpen}
+ parameterValues={parameterValues}
+ setParameterValues={setParameterValues}
+ parametersAreUserVisible={false}
+ canUseSampleDatabase={false}
+ onChangeQuery={onChangeQuery}
onInsertSnippet={jest.fn()}
onToggleDataReference={jest.fn()}
onToggleSnippetSidebar={jest.fn()}
- onToggleTemplateTagsSidebar={jest.fn()}
+ onToggleTemplateTagsSidebar={onToggleTemplateTagsSidebar}
onChangeModalSnippet={jest.fn()}
onOpenSnippetModalWithSelectedText={jest.fn()}
- parameterValues={{}}
- setParameterValues={jest.fn()}
- canUseSampleDatabase={canUseSampleDatabase}
+ templateTagsSidebar={TemplateTagsSidebarStub}
/>,
- { storeInitialState: state },
);
-};
-describe("NativeQuerySidebar template-tag help", () => {
- it("hides the 'Try it' examples when the sample database can't be used, e.g. in transforms (metabase#78037)", async () => {
- setup({ canUseSampleDatabase: false });
+ return {
+ database,
+ question,
+ query,
+ parameterValues,
+ onChangeQuery,
+ setParameterValues,
+ onToggleTemplateTagsSidebar,
+ };
+}
+
+describe("NativeQuerySidebar", () => {
+ beforeEach(() => {
+ TemplateTagsSidebarStub.mockClear();
+ });
+
+ it("should render nothing when no sidebar is open", () => {
+ setup();
+
+ expect(screen.queryByTestId("editor-sidebar")).not.toBeInTheDocument();
+ });
- await userEvent.click(screen.getByRole("tab", { name: "Help" }));
+ it("should render the injected template tags sidebar when the variables sidebar is open", () => {
+ const {
+ question,
+ query,
+ parameterValues,
+ onChangeQuery,
+ setParameterValues,
+ onToggleTemplateTagsSidebar,
+ } = setup({ isTemplateTagsSidebarOpen: true });
- expect(
- screen.queryByRole("button", { name: "Try it" }),
- ).not.toBeInTheDocument();
+ expect(screen.getByTestId("template-tags-sidebar")).toBeInTheDocument();
+ const [props] = TemplateTagsSidebarStub.mock.calls[0];
+ expect(props).toEqual({
+ question,
+ query,
+ parameterValues,
+ parametersAreUserVisible: false,
+ canUseSampleDatabase: false,
+ onChangeQuery,
+ setParameterValues,
+ onClose: onToggleTemplateTagsSidebar,
+ });
});
- it("shows the 'Try it' examples when the sample database is available", async () => {
- setup({});
+ it("should render the data reference for the question's database when that sidebar is open", async () => {
+ const { database } = setup({ isDataReferenceOpen: true });
- await userEvent.click(screen.getByRole("tab", { name: "Help" }));
+ await waitForLoaderToBeRemoved();
- expect(
- screen.getAllByRole("button", { name: "Try it" }).length,
- ).toBeGreaterThan(0);
+ expect(screen.getByText(database.name)).toBeInTheDocument();
+ expect(TemplateTagsSidebarStub).not.toHaveBeenCalled();
});
});
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
index 081c156f0d7..874a7d743c3 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx
@@ -1,5 +1,5 @@
import { useElementSize } from "@mantine/hooks";
-import type { ReactNode } from "react";
+import type { ComponentType, ReactNode } from "react";
import { t } from "ttag";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
@@ -9,7 +9,11 @@ import type * as Lib from "metabase-lib";
import type { DatasetQuery } from "metabase-types/api";
import { useQueryEditor } from "../../hooks/use-query-editor";
-import type { QueryEditorUiOptions, QueryEditorUiState } from "../../types";
+import type {
+ QueryEditorUiOptions,
+ QueryEditorUiState,
+ TemplateTagsSidebarProps,
+} from "../../types";
import {
NativeQueryPreviewSidebar,
@@ -34,6 +38,8 @@ export type QueryEditorProps = {
height?: string | number;
extraEditorButton?: ReactNode;
parametersAreUserVisible?: boolean;
+ parametersList: ReactNode;
+ templateTagsSidebar: ComponentType<TemplateTagsSidebarProps>;
};
export function QueryEditor({
@@ -51,6 +57,8 @@ export function QueryEditor({
height = "100%",
extraEditorButton,
parametersAreUserVisible = true,
+ parametersList,
+ templateTagsSidebar,
}: QueryEditorProps) {
const {
question,
@@ -106,6 +114,7 @@ export function QueryEditor({
<Flex flex="2 1 0" miw={0} direction="column" pos="relative">
<QueryEditorBody
availableHeight={availableHeight}
+ parametersList={parametersList}
question={question}
proposedQuestion={proposedQuestion}
modalSnippet={uiState.modalSnippet}
@@ -187,6 +196,7 @@ export function QueryEditor({
onChangeQuery={onChangeQuery}
parametersAreUserVisible={parametersAreUserVisible}
canUseSampleDatabase={uiOptions?.canUseSampleDatabase}
+ templateTagsSidebar={templateTagsSidebar}
/>
)}
{!isNative && uiState.sidebarType === "native-query" && (
diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
index eb1f4918c64..3a93b18ccf0 100644
--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx
@@ -39,6 +39,7 @@ const NATIVE_EDITOR_SIDEBAR_FEATURES = {
type QueryEditorBodyProps = {
extraButton?: ReactNode;
+ parametersList: ReactNode;
question: Question;
proposedQuestion: Question | undefined;
modalSnippet?:
@@ -83,6 +84,7 @@ type QueryEditorBodyProps = {
export function QueryEditorBody({
extraButton,
+ parametersList,
question,
proposedQuestion,
modalSnippet,
@@ -208,8 +210,7 @@ export function QueryEditorBody({
onAcceptProposed={onAcceptProposed}
onRejectProposed={onRejectProposed}
>
- <NativeQueryEditor.TopBar>
- <NativeQueryEditor.ParametersList />
+ <NativeQueryEditor.TopBar leftContent={parametersList}>
{topBarInnerContent}
<NativeQueryEditor.Sidebar
features={NATIVE_EDITOR_SIDEBAR_FEATURES}
diff --git a/frontend/src/metabase/querying/editor/types.ts b/frontend/src/metabase/querying/editor/types.ts
index 5931682270d..adadf061e95 100644
--- a/frontend/src/metabase/querying/editor/types.ts
+++ b/frontend/src/metabase/querying/editor/types.ts
@@ -1,5 +1,7 @@
import type { OmniPickerItem } from "metabase/common/components/Pickers";
import type { MiniPickerTableItem } from "metabase/common/components/Pickers/MiniPicker/types";
+import type * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
import type {
CardDisplayType,
CardType,
@@ -8,6 +10,7 @@ import type {
DatasetQuery,
NativeQuerySnippet,
RecentCollectionItem,
+ RowValue,
VisualizationSettings,
} from "metabase-types/api";
@@ -80,3 +83,17 @@ export type QueryEditorUiOptions = {
hideRunButton?: boolean;
resizable?: boolean;
};
+
+/**
+ * The component always renders content, because NativeQuerySidebar draws the sidebar panel around it before it runs.
+ */
+export type TemplateTagsSidebarProps = {
+ question: Question;
+ query: Lib.Query;
+ parameterValues: Record<string, RowValue>;
+ parametersAreUserVisible?: boolean;
+ canUseSampleDatabase?: boolean;
+ onChangeQuery: (newQuery: Lib.Query) => void;
+ setParameterValues: (newParameterValues: Record<string, RowValue>) => void;
+ onClose: () => void;
+};
diff --git a/frontend/src/metabase/transforms/components/TransformEditor/TransformEditor.tsx b/frontend/src/metabase/transforms/components/TransformEditor/TransformEditor.tsx
index a94cd080b99..6767e595c25 100644
--- a/frontend/src/metabase/transforms/components/TransformEditor/TransformEditor.tsx
+++ b/frontend/src/metabase/transforms/components/TransformEditor/TransformEditor.tsx
@@ -1,10 +1,10 @@
import { useMemo } from "react";
import { getMetadata } from "metabase/metadata-store";
-import {
- QueryEditor,
- type QueryEditorUiOptions,
- type QueryEditorUiState,
+import { QueryEditorWithParameters } from "metabase/parameters/components/QueryEditorWithParameters";
+import type {
+ QueryEditorUiOptions,
+ QueryEditorUiState,
} from "metabase/querying/editor/components/QueryEditor";
import { useSelector } from "metabase/redux";
import * as Lib from "metabase-lib";
@@ -81,7 +81,7 @@ export function TransformEditor({
};
return (
- <QueryEditor
+ <QueryEditorWithParameters
query={query}
uiState={uiState}
uiOptions={mergedUiOptions}
diff --git a/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx b/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx
index 084a090b5bc..ce980099a4d 100644
--- a/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx
+++ b/frontend/src/metabase/transforms/pages/NewTransformPage/NewTransformPage.tsx
@@ -15,11 +15,9 @@ import {
PaneHeaderInput,
} from "metabase/common/data-studio/components/PaneHeader";
import { getMetadata } from "metabase/metadata-store";
+import { loadQueryEditorWithParameters } from "metabase/parameters/components/QueryEditorWithParameters";
import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";
-import {
- getInitialUiState,
- loadQueryEditor,
-} from "metabase/querying/editor/components/QueryEditor";
+import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";
import { useSelector } from "metabase/redux";
import { type Location, useNavigate, useParams } from "metabase/router";
import { useRegisterMetabotTransformContext } from "metabase/transforms/hooks/use-register-transform-metabot-context";
@@ -285,7 +283,7 @@ const useQueryEditorChunk = () => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
let cancelled = false;
- loadQueryEditor().then(() => {
+ loadQueryEditorWithParameters().then(() => {
if (!cancelled) {
setIsLoaded(true);
}
diff --git a/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx b/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx
index 0df33dee1b2..b868bbe66d9 100644
--- a/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx
+++ b/frontend/src/metabase/transforms/pages/TransformQueryPage/TransformQueryPage.tsx
@@ -16,11 +16,9 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErr
import { PageContainer } from "metabase/common/data-studio/components/PageContainer";
import { useMetadataToasts } from "metabase/common/hooks";
import { getMetadata } from "metabase/metadata-store";
+import { loadQueryEditorWithParameters } from "metabase/parameters/components/QueryEditorWithParameters";
import { PLUGIN_TRANSFORMS_PYTHON } from "metabase/plugins";
-import {
- getInitialUiState,
- loadQueryEditor,
-} from "metabase/querying/editor/components/QueryEditor";
+import { getInitialUiState } from "metabase/querying/editor/components/QueryEditor";
import { useSelector } from "metabase/redux";
import { useLocation, useNavigate, useParams } from "metabase/router";
import { useRegisterMetabotTransformContext } from "metabase/transforms/hooks/use-register-transform-metabot-context";
@@ -395,7 +393,7 @@ const useQueryEditorChunk = () => {
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
let cancelled = false;
- loadQueryEditor().then(() => {
+ loadQueryEditorWithParameters().then(() => {
if (!cancelled) {
setIsLoaded(true);
}