Skip to content

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

Fix picker search fired twice on metrics viewer page load (#75290)

Anderson5bf39260bab1
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
index ae1820984f4..072358be4b0 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/PublishTablesModal/PublishTablesModal.tsx
@@ -109,14 +109,15 @@ function ModalBody({
const [publishTables] = usePublishTablesMutation();
const { sendSuccessToast } = useMetadataToasts();
const dispatch = useDispatch();
- const dataCollection = PLUGIN_LIBRARY.useGetLibraryChildCollectionByType({
- type: "library-data",
- });
+ const { data: dataCollection, isLoading: isLoadingDataCollection } =
+ PLUGIN_LIBRARY.useGetLibraryChildCollectionByType({
+ type: "library-data",
+ });
if (isLoading || error != null || data == null || dataCollection == null) {
return (
<DelayedLoadingAndErrorWrapper
- loading={isLoading || dataCollection == null}
+ loading={isLoading || isLoadingDataCollection || dataCollection == null}
error={error}
/>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
index 85f855daeb9..087b20fe959 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/utils.ts
@@ -44,17 +44,25 @@ export const useGetLibraryChildCollectionByType = ({
skip?: boolean;
type: CollectionType;
}) => {
- const { data: rootLibraryCollection } = useGetLibraryCollection({ skip });
- const { data: libraryCollections } = useListCollectionItemsQuery(
- rootLibraryCollection ? { id: rootLibraryCollection.id } : skipToken,
- );
- return useMemo(
+ const { data: rootLibraryCollection, isLoading: isLoadingLibrary } =
+ useGetLibraryCollection({ skip });
+ const { data: libraryCollections, isLoading: isLoadingItems } =
+ useListCollectionItemsQuery(
+ rootLibraryCollection ? { id: rootLibraryCollection.id } : skipToken,
+ );
+ const data = useMemo(
() =>
libraryCollections?.data.find(
(collection: CollectionItem) => collection.type === type,
),
[libraryCollections, type],
);
+
+ return {
+ data,
+ isLoading:
+ isLoadingLibrary || (rootLibraryCollection != null && isLoadingItems),
+ };
};
// This hook will return the library collection if there are both metrics and models in the library,
// the library-metrics collection if the library has no models, or the library-data collection
diff --git a/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx b/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
index fec9b4291c5..f7190df03e0 100644
--- a/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
+++ b/frontend/src/metabase/browse/metrics/BrowseMetrics.tsx
@@ -48,7 +48,7 @@ export function BrowseMetrics() {
const isEmpty = !isLoading && !error && !metrics?.length;
const titleId = useMemo(() => _.uniqueId("browse-metrics"), []);
- const libraryMetricCollection =
+ const { data: libraryMetricCollection } =
PLUGIN_LIBRARY.useGetLibraryChildCollectionByType({
type: "library-metrics",
});
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
index 7e9b4d19ec7..ea1843fba82 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
@@ -63,7 +63,7 @@ export const MetricSearchDropdown = forwardRef<
) {
const [isBrowsing, setIsBrowsing] = useState(false);
- const libraryMetricsCollection =
+ const { data: libraryMetricsCollection, isLoading: isLoadingLibraryMetrics } =
PLUGIN_LIBRARY.useGetLibraryChildCollectionByType({
type: "library-metrics",
});
@@ -178,36 +178,38 @@ export const MetricSearchDropdown = forwardRef<
return (
<>
- <MiniPicker
- opened={!isBrowsing}
- searchQuery={searchQuery}
- onChange={handleSelectResult}
- onClose={onClose}
- models={MINI_PICKER_MODELS}
- onBrowseAll={() => setIsBrowsing(true)}
- forceSearch={true}
- showSearchInput={searchQuery === undefined}
- searchInputPlaceholder={t`Search metrics and measures…`}
- searchParams={getSearchParams}
- onSearchResults={handleSearchResults}
- shouldHide={shouldHide}
- menuProps={menuProps}
- menuDropdownRef={miniPickerRef}
- >
- {anchorRect && (
- <span
- aria-hidden
- style={{
- position: "fixed",
- left: anchorRect.left,
- top: anchorRect.top,
- width: 0,
- height: 0,
- pointerEvents: "none",
- }}
- />
- )}
- </MiniPicker>
+ {!isLoadingLibraryMetrics && (
+ <MiniPicker
+ opened={!isBrowsing}
+ searchQuery={searchQuery}
+ onChange={handleSelectResult}
+ onClose={onClose}
+ models={MINI_PICKER_MODELS}
+ onBrowseAll={() => setIsBrowsing(true)}
+ forceSearch={true}
+ showSearchInput={searchQuery === undefined}
+ searchInputPlaceholder={t`Search metrics and measures…`}
+ searchParams={getSearchParams}
+ onSearchResults={handleSearchResults}
+ shouldHide={shouldHide}
+ menuProps={menuProps}
+ menuDropdownRef={miniPickerRef}
+ >
+ {anchorRect && (
+ <span
+ aria-hidden
+ style={{
+ position: "fixed",
+ left: anchorRect.left,
+ top: anchorRect.top,
+ width: 0,
+ height: 0,
+ pointerEvents: "none",
+ }}
+ />
+ )}
+ </MiniPicker>
+ )}
{isBrowsing && (
<EntityPickerModal
title={t`Pick a metric or measure`}
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.unit.spec.tsx
new file mode 100644
index 00000000000..1e4f106a1db
--- /dev/null
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.unit.spec.tsx
@@ -0,0 +1,106 @@
+import fetchMock from "fetch-mock";
+
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import {
+ setupCollectionItemsEndpoint,
+ setupSearchEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ waitFor,
+} from "__support__/ui";
+import { reinitialize } from "metabase/plugins";
+import {
+ createMockCollection,
+ createMockCollectionItem,
+ createMockSearchResult,
+ createMockSettings,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
+
+import { MetricSearchDropdown } from "./MetricSearchDropdown";
+
+const LIBRARY_COLLECTION = createMockCollection({
+ id: 1,
+ name: "Library",
+ type: "library",
+ below: ["metric"],
+});
+
+const LIBRARY_METRICS_COLLECTION = createMockCollectionItem({
+ id: 2,
+ name: "Metrics",
+ model: "collection",
+ type: "library-metrics",
+ here: ["metric"],
+});
+
+function setup() {
+ mockGetBoundingClientRect();
+
+ fetchMock.get("path:/api/ee/library", LIBRARY_COLLECTION, {
+ delay: 100,
+ });
+ setupCollectionItemsEndpoint({
+ collection: LIBRARY_COLLECTION,
+ collectionItems: [LIBRARY_METRICS_COLLECTION],
+ });
+ setupSearchEndpoints([
+ createMockSearchResult({
+ id: 1,
+ model: "metric",
+ name: "Revenue",
+ collection: {
+ id: LIBRARY_METRICS_COLLECTION.id,
+ name: LIBRARY_METRICS_COLLECTION.name,
+ archived: false,
+ },
+ }),
+ ]);
+
+ const settings = mockSettings(
+ createMockSettings({
+ "token-features": createMockTokenFeatures({ library: true }),
+ }),
+ );
+ setupEnterprisePlugins();
+
+ renderWithProviders(
+ <MetricSearchDropdown
+ searchQuery=""
+ onSelect={jest.fn()}
+ onClose={jest.fn()}
+ />,
+ { storeInitialState: { settings } },
+ );
+}
+
+describe("MetricSearchDropdown", () => {
+ afterEach(() => {
+ reinitialize();
+ });
+
+ it("waits for library metric search scope before searching", async () => {
+ setup();
+
+ expect(fetchMock.callHistory.calls("path:/api/search")).toHaveLength(0);
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.calls("path:/api/search")).toHaveLength(1);
+ });
+
+ const searchCall = fetchMock.callHistory.lastCall("path:/api/search");
+ const searchUrl = new URL(searchCall?.url as string);
+
+ expect(searchUrl.searchParams.get("q")).toBe("");
+ expect(searchUrl.searchParams.getAll("models")).toEqual([
+ "metric",
+ "measure",
+ ]);
+ expect(searchUrl.searchParams.get("collection")).toBe(
+ String(LIBRARY_METRICS_COLLECTION.id),
+ );
+ });
+});
diff --git a/frontend/src/metabase/plugins/oss/library.ts b/frontend/src/metabase/plugins/oss/library.ts
index 6ae2f3083f4..9c8b530176b 100644
--- a/frontend/src/metabase/plugins/oss/library.ts
+++ b/frontend/src/metabase/plugins/oss/library.ts
@@ -87,7 +87,10 @@ type LibraryPlugin = {
}: {
skip?: boolean;
type: CollectionType;
- }) => CollectionItem | undefined;
+ }) => {
+ data: CollectionItem | undefined;
+ isLoading: boolean;
+ };
useGetResolvedLibraryCollection: (params?: { skip?: boolean }) => {
data: undefined | LibraryCollection | CollectionItem;
isLoading: boolean;
@@ -124,7 +127,10 @@ const getDefaultPluginLibrary = (): LibraryPlugin => ({
isEnabled: false,
getDataStudioLibraryRoutes: () => null,
useGetLibraryCollection: () => ({ isLoading: false, data: undefined }),
- useGetLibraryChildCollectionByType: () => undefined,
+ useGetLibraryChildCollectionByType: () => ({
+ data: undefined,
+ isLoading: false,
+ }),
useGetResolvedLibraryCollection: () => ({
isLoading: false,
data: undefined,