Skip to content

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

Remove snippets and snippet-collections entities (#74066)

Romeo Van Snick84315da751a3
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
index 647e7244800..4f2544bb4b4 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/components/CollectionPermissionsModal/CollectionPermissionsModal.tsx
@@ -1,23 +1,16 @@
-import { useEffect } from "react";
-
import CollectionPermissionsModalBase from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";
+import { skipToken, useListCollectionsQuery } from "metabase/api";
import { Modal } from "metabase/common/components/Modal";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
import type { CollectionPermissionsModalProps } from "metabase/plugins";
-import { useDispatch } from "metabase/redux";
export function CollectionPermissionsModal({
collectionId,
namespace,
onClose,
}: CollectionPermissionsModalProps) {
- const dispatch = useDispatch();
-
- useEffect(() => {
- if (namespace === "snippets") {
- dispatch(SnippetCollections.actions.fetchList());
- }
- }, [dispatch, namespace]);
+ useListCollectionsQuery(
+ namespace === "snippets" ? { namespace: "snippets" } : skipToken,
+ );
return (
<Modal onClose={onClose}>
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
index 4fc1e3d505c..9342ae6558b 100644
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/CollectionRow.jsx
@@ -1,55 +1,46 @@
/* eslint-disable react/prop-types */
import cx from "classnames";
-import { Component } from "react";
import { CollectionRowMenu } from "metabase/collections/components/CollectionRowMenu";
import CS from "metabase/css/core/index.css";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
import { Ellipsified, Icon } from "metabase/ui";
const ICON_SIZE = 16;
-class CollectionRow extends Component {
- render() {
- const { snippetCollection: collection, setSnippetCollectionId } =
- this.props;
- const onSelectCollection = () => {
- if (setSnippetCollectionId) {
- setSnippetCollectionId(collection.id);
- }
- };
+function CollectionRow({ item: collection, setSnippetCollectionId }) {
+ const onSelectCollection = () => {
+ if (setSnippetCollectionId) {
+ setSnippetCollectionId(collection.id);
+ }
+ };
- return (
- <div
- className={cx(
- { [cx(CS.bgLightHover, CS.cursorPointer)]: !collection.archived },
- CS.hoverParent,
- CS.hoverVisibility,
- CS.flex,
- CS.alignCenter,
- CS.py1,
- CS.px3,
- CS.textBrand,
- )}
- {...(collection.archived ? undefined : { onClick: onSelectCollection })}
- >
- <Icon
- name="folder"
- size={ICON_SIZE}
- style={{ opacity: 0.25 }}
- className={CS.flexNoShrink}
- />
- <Ellipsified className={cx(CS.flexFull, CS.ml1, CS.textBold)} flex={1}>
- {collection.name}
- </Ellipsified>
- <CollectionRowMenu collection={collection} />
- </div>
- );
- }
+ return (
+ <div
+ className={cx(
+ { [cx(CS.bgLightHover, CS.cursorPointer)]: !collection.archived },
+ CS.hoverParent,
+ CS.hoverVisibility,
+ CS.flex,
+ CS.alignCenter,
+ CS.py1,
+ CS.px3,
+ CS.textBrand,
+ )}
+ {...(collection.archived ? undefined : { onClick: onSelectCollection })}
+ >
+ <Icon
+ name="folder"
+ size={ICON_SIZE}
+ style={{ opacity: 0.25 }}
+ className={CS.flexNoShrink}
+ />
+ <Ellipsified className={cx(CS.flexFull, CS.ml1, CS.textBold)} flex={1}>
+ {collection.name}
+ </Ellipsified>
+ <CollectionRowMenu collection={collection} />
+ </div>
+ );
}
// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default SnippetCollections.load({
- id: (state, props) => props.item.id,
- wrapped: true,
-})(CollectionRow);
+export default CollectionRow;
diff --git a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPermissionsModal/SnippetCollectionPermissionsModal.tsx b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPermissionsModal/SnippetCollectionPermissionsModal.tsx
index ca45f92e6d8..9927b6d42ad 100644
--- a/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPermissionsModal/SnippetCollectionPermissionsModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/snippets/components/SnippetCollectionPermissionsModal/SnippetCollectionPermissionsModal.tsx
@@ -1,20 +1,13 @@
-import { useEffect } from "react";
-
import CollectionPermissionsModal from "metabase/admin/permissions/components/CollectionPermissionsModal/CollectionPermissionsModal";
+import { useListCollectionsQuery } from "metabase/api";
import { Modal } from "metabase/common/components/Modal";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
import type { SnippetCollectionPermissionsModalProps } from "metabase/plugins";
-import { useDispatch } from "metabase/redux";
export function SnippetCollectionPermissionsModal({
collectionId,
onClose,
}: SnippetCollectionPermissionsModalProps) {
- const dispatch = useDispatch();
-
- useEffect(() => {
- dispatch(SnippetCollections.actions.fetchList());
- }, [dispatch]);
+ useListCollectionsQuery({ namespace: "snippets" });
return (
<Modal onClose={onClose}>
diff --git a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
index 327000adde6..f9e3338707b 100644
--- a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
+++ b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsx
@@ -9,6 +9,7 @@ import {
getSpecialGroupType,
isDefaultGroup,
} from "metabase/admin/utils/groups";
+import { collectionApi } from "metabase/api";
import {
isInstanceAnalyticsCollection,
isLibraryCollection,
@@ -19,7 +20,6 @@ import {
ROOT_COLLECTION,
getCollectionIcon,
} from "metabase/entities/collections";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
import { PLUGIN_COLLECTIONS, PLUGIN_TENANTS } from "metabase/plugins";
import type {
CollectionTreeItem,
@@ -176,7 +176,7 @@ const findCollection = (
const getCollection = createSelector(
[getCurrentCollectionId, getCollections],
- (collectionId, collections) => {
+ (collectionId, collections): Collection | null => {
if (collectionId == null) {
return null;
}
@@ -184,6 +184,11 @@ const getCollection = createSelector(
if (collectionId === ROOT_COLLECTION.id) {
return {
...ROOT_COLLECTION,
+ description: null,
+ can_write: true,
+ can_restore: false,
+ can_delete: false,
+ namespace: null,
children: collections,
};
}
@@ -194,15 +199,20 @@ const getCollection = createSelector(
const getFolder = (state: State, props: CollectionIdProps) => {
const folderId = getCurrentCollectionId(state, props);
- const folders = SnippetCollections.selectors.getList(state);
+ const folders = collectionApi.endpoints.listCollections.select({
+ namespace: "snippets",
+ })(state).data;
return folders?.find((folder: Collection) => folder.id === folderId);
};
-export const getCollectionEntity = (state: State, props: CollectionIdProps) => {
+export const getCollectionEntity = (
+ state: State,
+ props: CollectionIdProps,
+): Collection | undefined => {
return props.namespace === "snippets"
? getFolder(state, props)
- : getCollection(state, props);
+ : (getCollection(state, props) ?? undefined);
};
const getCollectionPermission = (
@@ -250,7 +260,7 @@ export const getCollectionsPermissionEditor = createSelector(
return null;
}
- const hasChildren = collection.children?.length > 0;
+ const hasChildren = (collection.children?.length ?? 0) > 0;
const toggleLabel = hasChildren ? getToggleLabel(namespace) : null;
const isTenantCollection = PLUGIN_TENANTS.isTenantCollection(collection);
@@ -335,7 +345,11 @@ export const getCollectionsPermissionEditor = createSelector(
group.id,
collection.id,
),
- warning: getCollectionWarning(group.id, collection, permissions),
+ warning: getCollectionWarning(
+ group.id,
+ collection as ExpandedCollection,
+ permissions,
+ ),
confirmations,
options,
},
diff --git a/frontend/src/metabase/api/snippet.ts b/frontend/src/metabase/api/snippet.ts
index e5434e71fc0..80d00566052 100644
--- a/frontend/src/metabase/api/snippet.ts
+++ b/frontend/src/metabase/api/snippet.ts
@@ -47,8 +47,9 @@ export const snippetApi = Api.injectEndpoints({
}),
invalidatesTags: (_, error) =>
invalidateTags(error, [listTag("snippet")]),
+ onQueryStarted: hydrateLegacyEntities(SnippetSchema),
}),
- updateSnippet: builder.mutation<unknown, UpdateSnippetRequest>({
+ updateSnippet: builder.mutation<NativeQuerySnippet, UpdateSnippetRequest>({
query: ({ id, ...body }) => ({
method: "PUT",
url: `/api/native-query-snippet/${id}`,
@@ -56,6 +57,7 @@ export const snippetApi = Api.injectEndpoints({
}),
invalidatesTags: (_, error, { id }) =>
invalidateTags(error, [listTag("snippet"), idTag("snippet", id)]),
+ onQueryStarted: hydrateLegacyEntities(SnippetSchema),
}),
}),
});
diff --git a/frontend/src/metabase/common/components/SnippetCollectionName.tsx b/frontend/src/metabase/common/components/SnippetCollectionName.tsx
index 400db38d386..22de2234271 100644
--- a/frontend/src/metabase/common/components/SnippetCollectionName.tsx
+++ b/frontend/src/metabase/common/components/SnippetCollectionName.tsx
@@ -1,7 +1,7 @@
import { t } from "ttag";
+import { useGetCollectionQuery } from "metabase/api";
import { isRootCollection } from "metabase/collections/utils";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
import type { CollectionId } from "metabase-types/api";
export function SnippetCollectionName({ id }: { id: CollectionId }) {
@@ -11,5 +11,13 @@ export function SnippetCollectionName({ id }: { id: CollectionId }) {
if (!Number.isSafeInteger(id)) {
return null;
}
- return <SnippetCollections.Name id={id} />;
+ return <SnippetCollectionNameLoader id={id} />;
+}
+
+function SnippetCollectionNameLoader({ id }: { id: CollectionId }) {
+ const { data: collection } = useGetCollectionQuery({
+ id,
+ namespace: "snippets",
+ });
+ return <span>{collection?.name ?? ""}</span>;
}
diff --git a/frontend/src/metabase/entities/index.ts b/frontend/src/metabase/entities/index.ts
index e30fce8eae6..214220e69cc 100644
--- a/frontend/src/metabase/entities/index.ts
+++ b/frontend/src/metabase/entities/index.ts
@@ -69,12 +69,9 @@
*/
export { Collections as collections } from "./collections";
-export { SnippetCollections as snippetCollections } from "./snippet-collections";
export { Dashboards as dashboards } from "./dashboards";
export { Questions as questions } from "./questions";
export { Databases as databases } from "./databases";
export { Tables as tables } from "./tables";
export { Fields as fields } from "./fields";
-
-export { Snippets as snippets } from "./snippets";
diff --git a/frontend/src/metabase/entities/snippet-collections.js b/frontend/src/metabase/entities/snippet-collections.js
deleted file mode 100644
index 5a5e8278d00..00000000000
--- a/frontend/src/metabase/entities/snippet-collections.js
+++ /dev/null
@@ -1,76 +0,0 @@
-import { createSelector } from "@reduxjs/toolkit";
-import { t } from "ttag";
-import _ from "underscore";
-
-import { skipToken, useGetCollectionQuery } from "metabase/api";
-import {
- Collections,
- getExpandedCollectionsById,
- useListQuery as useListCollectionsQuery,
-} from "metabase/entities/collections";
-import { SnippetCollectionSchema } from "metabase/schema";
-
-import { createEntity } from "./utils";
-
-/**
- * @deprecated use "metabase/api" instead
- */
-export const SnippetCollections = createEntity({
- name: "snippetCollections",
- schema: SnippetCollectionSchema,
-
- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045
- displayNameOne: t`snippet collection`,
- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045
- displayNameMany: t`snippet collections`,
-
- rtk: () => ({
- getUseGetQuery: () => ({
- useGetQuery,
- }),
- useListQuery,
- }),
-
- api: _.mapObject(
- Collections.api,
- (request) =>
- (opts, ...rest) =>
- request({ ...opts, namespace: "snippets" }, ...rest),
- ),
-
- objectActions: {
- delete: null, // not implemented
- },
-
- selectors: {
- getExpandedCollectionsById: createSelector(
- (state) => SnippetCollections.selectors.getList(state) || [],
- (collections) => getExpandedCollectionsById(collections, null),
- ),
- },
-
- createSelectors: ({ getObject, getFetched }) => ({
- getFetched: (state, props) =>
- getFetched(state, props) || getObject(state, props),
- }),
-
- getAnalyticsMetadata() {
- return undefined; // not tracking
- },
-});
-
-const useGetQuery = (query, options) => {
- return useGetCollectionQuery(
- query === skipToken
- ? skipToken
- : {
- namespace: "snippets",
- ...query,
- },
- options,
- );
-};
-
-function useListQuery(query, options) {
- return useListCollectionsQuery({ ...query, namespace: "snippets" }, options);
-}
diff --git a/frontend/src/metabase/entities/snippets.js b/frontend/src/metabase/entities/snippets.js
deleted file mode 100644
index e0670dc98cc..00000000000
--- a/frontend/src/metabase/entities/snippets.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import {
- snippetApi,
- useGetSnippetQuery,
- useListSnippetsQuery,
-} from "metabase/api";
-
-import { createEntity, entityCompatibleQuery } from "./utils";
-
-/**
- * @deprecated use "metabase/api" instead
- */
-export const Snippets = createEntity({
- name: "snippets",
- nameOne: "snippet",
- path: "/api/native-query-snippet",
- createSelectors: ({ getObject, getFetched }) => ({
- getFetched: (state, props) =>
- getFetched(state, props) || getObject(state, props),
- }),
-
- rtk: () => ({
- getUseGetQuery: () => ({
- useGetQuery,
- }),
- useListQuery: useListSnippetsQuery,
- }),
-
- api: {
- list: (entityQuery, dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- snippetApi.endpoints.listSnippets,
- ),
- get: (entityQuery, options, dispatch) =>
- entityCompatibleQuery(
- entityQuery.id,
- dispatch,
- snippetApi.endpoints.getSnippet,
- ),
- create: (entityQuery, dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- snippetApi.endpoints.createSnippet,
- ),
- update: (entityQuery, dispatch) =>
- entityCompatibleQuery(
- entityQuery,
- dispatch,
- snippetApi.endpoints.updateSnippet,
- ),
- delete: () => {
- throw new TypeError("Snippets.api.delete is not supported");
- },
- },
-});
-
-const useGetQuery = ({ id }, options) => {
- return useGetSnippetQuery(id, options);
-};
diff --git a/frontend/src/metabase/entities/utils.ts b/frontend/src/metabase/entities/utils.ts
index 816acc7abc7..d659d94847b 100644
--- a/frontend/src/metabase/entities/utils.ts
+++ b/frontend/src/metabase/entities/utils.ts
@@ -973,7 +973,13 @@ type CombinedEntities = {
* another entity's normalizr schema (e.g. measures inside a table's
* `query_metadata` response).
*/
-const RETIRED_ENTITY_NAMES = ["measures", "metrics", "schemas", "segments"];
+const RETIRED_ENTITY_NAMES = [
+ "measures",
+ "metrics",
+ "schemas",
+ "segments",
+ "snippets",
+];
export function combineEntities(entities: Entity[]): CombinedEntities {
const entitiesMap: Record<string, Entity> = {};
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index 78370dbbcb7..2426a2a70d7 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -1,19 +1,20 @@
import type { LocationDescriptorObject } from "history";
import { replace } from "react-router-redux";
+import { snippetApi } from "metabase/api";
import {
cardIsEquivalent,
deserializeCard,
parseHash,
} from "metabase/common/utils/card";
import { Questions } from "metabase/entities/questions";
-import { Snippets } from "metabase/entities/snippets";
import {
getIsEditingInDashboard,
getNotebookNativePreviewSidebarWidth,
} from "metabase/query_builder/selectors";
import { loadMetadataForCard } from "metabase/questions/actions";
import { setErrorPage } from "metabase/redux/app";
+import type { DispatchFn } from "metabase/redux/hooks";
import { addFields } from "metabase/redux/metadata";
import { INITIALIZE_QB, resetQB } from "metabase/redux/query-builder";
import type {
@@ -246,9 +247,17 @@ export async function updateTemplateTagNames(
query = updateCardTemplateTagNames(query, referencedCards);
if (query.hasSnippets()) {
- await dispatch(Snippets.actions.fetchList());
- const snippets = Snippets.selectors.getList(getState());
- query = query.updateSnippetNames(snippets);
+ const action = (dispatch as DispatchFn)(
+ snippetApi.endpoints.listSnippets.initiate(undefined, {
+ forceRefetch: true,
+ }),
+ );
+ try {
+ const snippets = await action.unwrap();
+ query = query.updateSnippetNames(snippets);
+ } finally {
+ action.unsubscribe();
+ }
}
return query;
}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
index a0b11ed5c88..80347dbb23e 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts
@@ -2,9 +2,9 @@ import fetchMock from "fetch-mock";
import type { LocationDescriptorObject } from "history";
import { createMockEntitiesState } from "__support__/store";
+import { snippetApi } from "metabase/api";
import * as CardLib from "metabase/common/utils/card";
import { Databases } from "metabase/entities/databases";
-import { Snippets } from "metabase/entities/snippets";
import * as questionActions from "metabase/questions/actions";
import { setErrorPage } from "metabase/redux/app";
import * as sharedQB from "metabase/redux/query-builder";
@@ -83,7 +83,10 @@ async function baseSetup({
const metadata = getMetadata(state);
const getState = () => state;
- const dispatch = jest.fn();
+ // Pass actions through verbatim so callers that capture the result of
+ // `dispatch(thunk)` (e.g. RTK Query's `endpoint.initiate(...)`) can still
+ // call methods on it in tests where the snippet endpoint is mocked.
+ const dispatch = jest.fn((action) => action);
await initializeQB(location, params)(dispatch, getState);
jest.runAllTimers();
@@ -601,7 +604,7 @@ describe("QB Actions > initializeQB", () => {
type SnippetsSetupOpts = Omit<SetupOpts, "card"> & {
hasDatabaseWritePermission?: boolean;
- snippet?: unknown;
+ snippet?: { id: number; name: string };
};
function setupSnippets({
@@ -611,40 +614,46 @@ describe("QB Actions > initializeQB", () => {
}: SnippetsSetupOpts) {
const clone = { ...card };
- Snippets.actions.fetchList = jest.fn();
- Snippets.selectors.getList = jest
- .fn()
- .mockReturnValue(snippet ? [snippet] : []);
+ const initiateSpy = jest
+ .spyOn(snippetApi.endpoints.listSnippets, "initiate")
+ .mockReturnValue({
+ unwrap: () => Promise.resolve(snippet ? [snippet] : []),
+ unsubscribe: jest.fn(),
+ // RTK Query's internal action creator return shape — we only need
+ // `unwrap`/`unsubscribe` for the production code path.
+ } as any);
return setup({
card: clone,
hasDataPermissions: hasDatabaseWritePermission,
...opts,
- });
+ }).then((res) => ({ ...res, initiateSpy }));
}
describe(questionType, () => {
it("loads snippets if have DB write permissions", async () => {
- await setupSnippets({ hasDatabaseWritePermission: true });
- expect(Snippets.actions.fetchList).toHaveBeenCalledTimes(1);
+ const { initiateSpy } = await setupSnippets({
+ hasDatabaseWritePermission: true,
+ });
+ expect(initiateSpy).toHaveBeenCalledTimes(1);
});
it("does not load snippets if missing DB write permissions", async () => {
Databases.selectors.getObject = jest.fn().mockReturnValue({
native_permissions: "none",
});
- Snippets.actions.fetchList = jest.fn();
- Snippets.selectors.getList = jest.fn().mockReturnValue([SNIPPET]);
- await setupSnippets({ hasDatabaseWritePermission: false });
+ const { initiateSpy } = await setupSnippets({
+ hasDatabaseWritePermission: false,
+ });
- expect(Snippets.actions.fetchList).not.toHaveBeenCalled();
+ expect(initiateSpy).not.toHaveBeenCalled();
});
it("replaces snippet names with fresh ones from the backend", async () => {
const { result, metadata } = await setupSnippets({
snippet: {
- id: SNIPPET["snippet-id"],
+ id: SNIPPET["snippet-id"] as number,
name: "bar",
},
});
diff --git a/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx b/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
index d14f503d590..92baa7b8c69 100644
--- a/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
+++ b/frontend/src/metabase/query_builder/components/template_tags/SnippetForm/SnippetForm.tsx
@@ -1,15 +1,15 @@
import { useMemo } from "react";
import { t } from "ttag";
-import _ from "underscore";
import * as Yup from "yup";
+import { useListCollectionsQuery } from "metabase/api";
import FormCollectionPicker from "metabase/collections/containers/FormCollectionPicker";
import { Button } from "metabase/common/components/Button";
import { FormErrorMessage } from "metabase/common/components/FormErrorMessage";
import { FormInput } from "metabase/common/components/FormInput";
import { FormSubmitButton } from "metabase/common/components/FormSubmitButton";
import { FormTextArea } from "metabase/common/components/FormTextArea";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { Form, FormProvider } from "metabase/forms";
import { Flex } from "metabase/ui";
import * as Errors from "metabase/utils/errors";
@@ -136,6 +136,18 @@ function SnippetFormInner({
);
}
-export const SnippetForm = _.compose(SnippetCollections.loadList())(
- SnippetFormInner,
-);
+export function SnippetForm(props: SnippetFormOwnProps) {
+ const {
+ data: snippetCollections,
+ isLoading,
+ error,
+ } = useListCollectionsQuery({ namespace: "snippets" });
+ return (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ <SnippetFormInner
+ {...props}
+ snippetCollections={snippetCollections ?? []}
+ />
+ </LoadingAndErrorWrapper>
+ );
+}
diff --git a/frontend/src/metabase/query_builder/components/template_tags/SnippetFormModal/SnippetFormModal.tsx b/frontend/src/metabase/query_builder/components/template_tags/SnippetFormModal/SnippetFormModal.tsx
index b9a58873da6..48b40cec11b 100644
--- a/frontend/src/metabase/query_builder/components/template_tags/SnippetFormModal/SnippetFormModal.tsx
+++ b/frontend/src/metabase/query_builder/components/template_tags/SnippetFormModal/SnippetFormModal.tsx
@@ -1,9 +1,11 @@
import { useCallback, useState } from "react";
import { t } from "ttag";
-import { Snippets } from "metabase/entities/snippets";
+import {
+ useCreateSnippetMutation,
+ useUpdateSnippetMutation,
+} from "metabase/api";
import { PLUGIN_DEPENDENCIES } from "metabase/plugins";
-import { useDispatch } from "metabase/redux";
import { Flex, Modal } from "metabase/ui";
import type {
CreateSnippetRequest,
@@ -30,7 +32,8 @@ export function SnippetFormModal({
onClose,
}: SnippetModalProps) {
const [snippet, setSnippet] = useState(initialSnippet);
- const dispatch = useDispatch();
+ const [createSnippet] = useCreateSnippetMutation();
+ const [updateSnippet] = useUpdateSnippetMutation();
const isEditing = isSavedSnippet(snippet);
const modalTitle = isEditing
? t`Editing ${snippet.name}`
@@ -38,12 +41,11 @@ export function SnippetFormModal({
const handleCreate = useCallback(
async (values: CreateSnippetRequest) => {
- const action = await dispatch(Snippets.actions.create(values));
- const snippet = Snippets.HACK_getObjectFromAction(action);
- onCreate?.(snippet);
+ const created = await createSnippet(values).unwrap();
+ onCreate?.(created);
onClose?.();
},
- [dispatch, onCreate, onClose],
+ [createSnippet, onCreate, onClose],
);
const handleUpdate = useCallback(
@@ -51,21 +53,23 @@ export function SnippetFormModal({
if (!isSavedSnippet(snippet)) {
return;
}
- const action = await dispatch(Snippets.actions.update(snippet, values));
- const nextSnippet = Snippets.HACK_getObjectFromAction(action);
+ const nextSnippet = await updateSnippet({
+ ...values,
+ id: snippet.id,
+ }).unwrap();
onUpdate?.(nextSnippet, snippet);
onClose?.();
},
- [snippet, dispatch, onUpdate, onClose],
+ [snippet, updateSnippet, onUpdate, onClose],
);
const handleArchive = useCallback(async () => {
if (!isSavedSnippet(snippet)) {
return;
}
- await dispatch(Snippets.actions.update({ id: snippet.id, archived: true }));
+ await updateSnippet({ id: snippet.id, archived: true });
onClose?.();
- }, [snippet, dispatch, onClose]);
+ }, [snippet, updateSnippet, onClose]);
const {
checkData,
diff --git a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetRow/SnippetRow.jsx b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetRow/SnippetRow.jsx
index 6e413932403..302e7782559 100644
--- a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetRow/SnippetRow.jsx
+++ b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetRow/SnippetRow.jsx
@@ -1,127 +1,118 @@
/* eslint-disable react/prop-types */
import cx from "classnames";
-import { Component } from "react";
+import { useState } from "react";
import { t } from "ttag";
+import { useUpdateSnippetMutation } from "metabase/api";
import { Button } from "metabase/common/components/Button";
import CS from "metabase/css/core/index.css";
-import { Snippets } from "metabase/entities/snippets";
import { Ellipsified, Flex, Icon } from "metabase/ui";
import SnippetRowS from "./SnippetRow.module.css";
-class SnippetRowInner extends Component {
- constructor(props) {
- super(props);
- this.state = { isOpen: false };
- }
+export function SnippetRow({
+ item: snippet,
+ insertSnippet,
+ setModalSnippet,
+ canWrite,
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [updateSnippet] = useUpdateSnippetMutation();
- render() {
- const { snippet, insertSnippet, setModalSnippet, canWrite } = this.props;
+ const { description, content } = snippet;
- const { description, content } = snippet;
- const { isOpen } = this.state;
- return (
+ return (
+ <div
+ className={cx(
+ { [CS.borderTransparent]: !isOpen },
+ CS.borderBottom,
+ CS.borderTop,
+ )}
+ >
<div
className={cx(
- { [CS.borderTransparent]: !isOpen },
- CS.borderBottom,
- CS.borderTop,
+ CS.cursorPointer,
+ CS.bgLightHover,
+ CS.textBold,
+ CS.flex,
+ CS.alignCenter,
+ CS.justifyBetween,
+ CS.py2,
+ CS.px3,
+ CS.hoverParent,
+ CS.hoverDisplay,
)}
+ style={{ minWidth: 0 }}
+ onClick={() => setIsOpen(!isOpen)}
>
- <div
- className={cx(
- CS.cursorPointer,
- CS.bgLightHover,
- CS.textBold,
- CS.flex,
- CS.alignCenter,
- CS.justifyBetween,
- CS.py2,
- CS.px3,
- CS.hoverParent,
- CS.hoverDisplay,
- )}
- style={{ minWidth: 0 }}
- onClick={() => this.setState({ isOpen: !isOpen })}
+ <Flex
+ className={SnippetRowS.SnippetContent}
+ onClick={
+ snippet.archived
+ ? () => setIsOpen(true)
+ : (e) => {
+ e.stopPropagation();
+ insertSnippet(snippet);
+ }
+ }
+ miw={0}
>
- <Flex
- className={SnippetRowS.SnippetContent}
- onClick={
- snippet.archived
- ? () => this.setState({ isOpen: true })
- : (e) => {
- e.stopPropagation();
- insertSnippet(snippet);
- }
- }
- miw={0}
- >
- <Icon
- name="snippet"
- className={cx(
- CS.hoverChildHidden,
- CS.textLight,
- SnippetRowS.SnippetIcon,
- )}
- />
- <Icon
- name={insertSnippet ? "arrow_left_to_line" : "snippet"}
- className={cx(CS.hoverChild, SnippetRowS.SnippetIcon)}
- />
- <Ellipsified className={cx(CS.ml1)}>{snippet.name}</Ellipsified>
- </Flex>
<Icon
- name={isOpen ? "chevronup" : "chevrondown"}
+ name="snippet"
className={cx(
- { [CS.hoverChild]: !isOpen },
+ CS.hoverChildHidden,
+ CS.textLight,
SnippetRowS.SnippetIcon,
)}
/>
- </div>
- {isOpen && (
- <div className={cx(CS.px3, CS.pb2, CS.pt1)}>
- {description && (
- <p className={cx(CS.textMedium, CS.mt0)}>{description}</p>
+ <Icon
+ name={insertSnippet ? "arrow_left_to_line" : "snippet"}
+ className={cx(CS.hoverChild, SnippetRowS.SnippetIcon)}
+ />
+ <Ellipsified className={cx(CS.ml1)}>{snippet.name}</Ellipsified>
+ </Flex>
+ <Icon
+ name={isOpen ? "chevronup" : "chevrondown"}
+ className={cx({ [CS.hoverChild]: !isOpen }, SnippetRowS.SnippetIcon)}
+ />
+ </div>
+ {isOpen && (
+ <div className={cx(CS.px3, CS.pb2, CS.pt1)}>
+ {description && (
+ <p className={cx(CS.textMedium, CS.mt0)}>{description}</p>
+ )}
+ <pre
+ className={cx(
+ CS.bgLight,
+ CS.bordered,
+ CS.rounded,
+ CS.p1,
+ CS.textMonospace,
+ CS.textSmall,
+ CS.textPreWrap,
+ CS.overflowAuto,
)}
- <pre
- className={cx(
- CS.bgLight,
- CS.bordered,
- CS.rounded,
- CS.p1,
- CS.textMonospace,
- CS.textSmall,
- CS.textPreWrap,
- CS.overflowAuto,
- )}
- style={{ maxHeight: 320 }}
+ style={{ maxHeight: 320 }}
+ >
+ {content}
+ </pre>
+ {canWrite && (
+ <Button
+ className={SnippetRowS.SnippetButton}
+ onClick={
+ snippet.archived
+ ? () => updateSnippet({ id: snippet.id, archived: false })
+ : () => setModalSnippet(snippet)
+ }
+ borderless
+ medium
+ icon={snippet.archived ? "unarchive" : "pencil"}
>
- {content}
- </pre>
- {canWrite && (
- <Button
- className={SnippetRowS.SnippetButton}
- onClick={
- snippet.archived
- ? () => snippet.update({ archived: false })
- : () => setModalSnippet(snippet)
- }
- borderless
- medium
- icon={snippet.archived ? "unarchive" : "pencil"}
- >
- {snippet.archived ? t`Unarchive` : t`Edit`}
- </Button>
- )}
- </div>
- )}
- </div>
- );
- }
+ {snippet.archived ? t`Unarchive` : t`Edit`}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ );
}
-
-export const SnippetRow = Snippets.load({
- id: (state, props) => props.item.id,
- wrapped: true,
-})(SnippetRowInner);
diff --git a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
index fe8cd7773b0..0e310c66d31 100644
--- a/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
+++ b/frontend/src/metabase/querying/components/SnippetSidebar/SnippetSidebar.jsx
@@ -4,21 +4,24 @@ import * as React from "react";
import { t } from "ttag";
import _ from "underscore";
-import { useListCollectionItemsQuery } from "metabase/api";
+import {
+ useGetCollectionQuery,
+ useListCollectionItemsQuery,
+ useListCollectionsQuery,
+ useListSnippetsQuery,
+} from "metabase/api";
import { canonicalCollectionId } from "metabase/collections/utils";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { SidebarContent } from "metabase/common/components/SidebarContent";
import { SidebarHeader } from "metabase/common/components/SidebarHeader";
import CS from "metabase/css/core/index.css";
-import { SnippetCollections } from "metabase/entities/snippet-collections";
-import { Snippets } from "metabase/entities/snippets";
import {
PLUGIN_REMOTE_SYNC,
PLUGIN_SNIPPET_SIDEBAR_HEADER_BUTTONS,
PLUGIN_SNIPPET_SIDEBAR_PLUS_MENU_OPTIONS,
PLUGIN_SNIPPET_SIDEBAR_ROW_RENDERERS,
} from "metabase/plugins";
-import { connect } from "metabase/redux";
+import { useDispatch, useSelector } from "metabase/redux";
import { Box, Button, Flex, Icon, Menu } from "metabase/ui";
import { SnippetRow } from "./SnippetRow";
@@ -97,11 +100,22 @@ class SnippetSidebarInner extends React.Component {
);
}
+ const collectionsById = _.indexBy(snippetCollections, "id");
+ const snippetsById = _.indexBy(snippets, "id");
+ const hydrateSearchItem = (item) => {
+ const model = item.model || "snippet";
+ const full =
+ model === "collection"
+ ? collectionsById[item.id]
+ : snippetsById[item.id];
+ return full ? { ...full, model } : item;
+ };
+
const displayedItems = showSearch
? snippets.filter((snippet) =>
snippet.name.toLowerCase().includes(searchString.toLowerCase()),
)
- : _.sortBy(search, "model"); // relies on "collection" sorting before "snippet";
+ : _.sortBy(search, "model").map(hydrateSearchItem); // relies on "collection" sorting before "snippet";
const onSnippetCollectionBack = () => {
const parentCollectionId = snippetCollection.parent_id ?? "root";
@@ -267,18 +281,48 @@ function SnippetSidebarWithSearch(props) {
);
}
-export const SnippetSidebar = _.compose(
- Snippets.loadList(),
- SnippetCollections.loadList(),
- SnippetCollections.load({
- id: (state, props) =>
- props.snippetCollectionId === null ? "root" : props.snippetCollectionId,
- wrapped: true,
- }),
- connect((state, { list }) => ({
- isRemoteSyncReadOnly: PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly(state),
- })),
-)(SnippetSidebarWithSearch);
+export function SnippetSidebar(props) {
+ const dispatch = useDispatch();
+ const isRemoteSyncReadOnly = useSelector(
+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
+ );
+ const collectionId =
+ props.snippetCollectionId === null ? "root" : props.snippetCollectionId;
+
+ const {
+ data: snippets,
+ isLoading: snippetsLoading,
+ error: snippetsError,
+ } = useListSnippetsQuery();
+ const {
+ data: snippetCollections,
+ isLoading: collectionsLoading,
+ error: collectionsError,
+ } = useListCollectionsQuery({ namespace: "snippets" });
+ const {
+ data: snippetCollection,
+ isLoading: collectionLoading,
+ error: collectionError,
+ } = useGetCollectionQuery({ id: collectionId, namespace: "snippets" });
+
+ const isLoading = snippetsLoading || collectionsLoading || collectionLoading;
+ const error = snippetsError || collectionsError || collectionError;
+
+ return (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ {snippets && snippetCollections && snippetCollection && (
+ <SnippetSidebarWithSearch
+ {...props}
+ snippets={snippets}
+ snippetCollections={snippetCollections}
+ snippetCollection={snippetCollection}
+ isRemoteSyncReadOnly={isRemoteSyncReadOnly}
+ dispatch={dispatch}
+ />
+ )}
+ </LoadingAndErrorWrapper>
+ );
+}
function ArchivedSnippetsInner(props) {
const {
@@ -324,15 +368,45 @@ function ArchivedSnippetsInner(props) {
);
}
-const ArchivedSnippets = _.compose(
- SnippetCollections.loadList({ query: { archived: true }, wrapped: true }),
- connect((state, { list }) => ({
- isRemoteSyncReadOnly: PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly(state),
- archivedSnippetCollections: list,
- })),
- SnippetCollections.loadList(),
- Snippets.loadList({ query: { archived: true }, wrapped: true }),
-)(ArchivedSnippetsInner);
+function ArchivedSnippets(props) {
+ const isRemoteSyncReadOnly = useSelector(
+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
+ );
+
+ const {
+ data: snippets,
+ isLoading: snippetsLoading,
+ error: snippetsError,
+ } = useListSnippetsQuery({ archived: true });
+ const {
+ data: snippetCollections,
+ isLoading: collectionsLoading,
+ error: collectionsError,
+ } = useListCollectionsQuery({ namespace: "snippets" });
+ const {
+ data: archivedSnippetCollections,
+ isLoading: archivedCollectionsLoading,
+ error: archivedCollectionsError,
+ } = useListCollectionsQuery({ namespace: "snippets", archived: true });
+
+ const isLoading =
+ snippetsLoading || collectionsLoading || archivedCollectionsLoading;
+ const error = snippetsError || collectionsError || archivedCollectionsError;
+
+ return (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ {snippets && snippetCollections && archivedSnippetCollections && (
+ <ArchivedSnippetsInner
+ {...props}
+ snippets={snippets}
+ snippetCollections={snippetCollections}
+ archivedSnippetCollections={archivedSnippetCollections}
+ isRemoteSyncReadOnly={isRemoteSyncReadOnly}
+ />
+ )}
+ </LoadingAndErrorWrapper>
+ );
+}
function Row(props) {
const Component = {