Skip to content

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

Fix user provisioning getting disabled when adding a group mapping (#75829)

Andrei Chernykhb04009322f2b
diff --git a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
index 85b9aba4f8e..23ff770e98b 100644
--- a/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
+++ b/e2e/test/scenarios/admin-2/sso/shared/group-mappings-widget.js
@@ -1,5 +1,3 @@
-import { popover } from "e2e/support/helpers";
-
export function crudGroupMappingsWidget(authenticationMethod) {
cy.visit("/admin/settings/authentication/" + authenticationMethod);
cy.wait("@getSettings");
@@ -51,16 +49,22 @@ export function checkGroupConsistencyAfterDeletingMappings(
deleteMappingWithGroups("cn=People2");
- // cn=People1 will have Admin and nosql as groups
- cy.findByText("1 other group");
-
- // cn=People3 will have readonly as group
- cy.findByText("readonly");
+ // Scope to the table: the group dropdown is portaled and stays mounted
+ // (hidden) after being opened, so a group name can also linger as an
+ // off-screen option outside the table.
+ cy.findByTestId("admin-content-table").within(() => {
+ // cn=People1 will have Admin and nosql as groups
+ cy.findByText("1 other group");
+ // cn=People3 will have readonly as group
+ cy.findByText("readonly");
+ });
// Ensure mappings are as expected after a page reload
cy.visit("/admin/settings/authentication/" + authenticationMethod);
- cy.findByText("1 other group");
- cy.findByText("readonly");
+ cy.findByTestId("admin-content-table").within(() => {
+ cy.findByText("1 other group");
+ cy.findByText("readonly");
+ });
}
const deleteMappingWithGroups = (mappingName) => {
@@ -76,7 +80,7 @@ const deleteMappingWithGroups = (mappingName) => {
const createMapping = (name) => {
cy.button("New mapping").click();
- cy.findByLabelText("new-group-mapping-name-input").type(name);
+ cy.findByLabelText("New group mapping name").type(name);
cy.button("Add").click();
};
@@ -88,15 +92,11 @@ const addGroupsToMapping = (mappingName, groups) => {
});
groups.forEach((group) => {
- popover().within(() => {
- cy.findByText(group).click();
-
- cy.findByText(group)
- .closest("[data-element-id=list-section]")
- .within(() => {
- cy.icon("check");
- });
- });
+ cy.findByRole("option", { name: group }).click();
+ // Wait for the selection to round-trip before picking the next group
+ cy.findByRole("option", { name: group })
+ .find("input[type=checkbox]")
+ .should("be.checked");
});
cy.realPress("{esc}");
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
index 502d6767022..da98bf1cd04 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.tsx
@@ -11,6 +11,7 @@ import { getExtraFormFieldProps } from "metabase/admin/settings/utils";
import { useGetAdminSettingsDetailsQuery } from "metabase/api";
import { useAdminSetting } from "metabase/api/utils";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useToast } from "metabase/common/hooks";
import {
Form,
FormErrorMessage,
@@ -29,7 +30,6 @@ import type {
export type JWTFormValues = Pick<
EnterpriseSettings,
- | "jwt-user-provisioning-enabled?"
| "jwt-identity-provider-uri"
| "jwt-shared-secret"
| "jwt-attribute-email"
@@ -44,6 +44,7 @@ export const SettingsJWTForm = () => {
refetch: refetchSettingDetails,
} = useGetAdminSettingsDetailsQuery();
const { value: jwtEnabled, updateSettings } = useAdminSetting("jwt-enabled");
+ const [sendToast] = useToast();
const handleSubmit = async (values: Partial<JWTFormValues>) => {
const { "jwt-shared-secret": jwtSecret, ...rest } = values;
@@ -66,6 +67,8 @@ export const SettingsJWTForm = () => {
if (result.error) {
throw new Error(t`Error saving JWT Settings`);
}
+
+ sendToast({ message: t`Changes saved`, icon: "check_filled" });
};
if (isLoadingDetails) {
@@ -193,7 +196,6 @@ export const SettingsJWTForm = () => {
const getFormValues = (settingDetails: SettingDefinitionMap): JWTFormValues => {
const jwtSettings = _.pick(settingDetails, [
- "jwt-user-provisioning-enabled?",
"jwt-identity-provider-uri",
"jwt-shared-secret",
"jwt-group-sync",
@@ -204,14 +206,6 @@ const getFormValues = (settingDetails: SettingDefinitionMap): JWTFormValues => {
"jwt-attribute-tenant",
]);
- if (!jwtSettings["jwt-user-provisioning-enabled?"]?.value) {
- // cast empty to false
- jwtSettings["jwt-user-provisioning-enabled?"] = {
- ...jwtSettings["jwt-user-provisioning-enabled?"],
- value: false,
- };
- }
-
// cast undefined to null
return _.mapObject(jwtSettings, (val) => val?.value ?? null) as JWTFormValues;
};
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
index e3a94092031..59474aa3cfd 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsJWTForm/SettingsJWTForm.unit.spec.tsx
@@ -6,6 +6,7 @@ import {
setupGenerateRandomTokenEndpoint,
setupPropertiesEndpoints,
setupSettingsEndpoints,
+ setupUpdateSettingEndpoint,
setupUpdateSettingsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, screen, within } from "__support__/ui";
@@ -24,13 +25,21 @@ const GROUPS = [
const setup = async ({
jwtEnabled,
useTenants,
+ configured,
}: {
jwtEnabled?: boolean;
useTenants?: boolean;
+ configured?: boolean;
} = {}) => {
setupSettingsEndpoints([
{ key: "use-tenants", value: useTenants ?? false },
{ key: "jwt-enabled", value: jwtEnabled ?? false },
+ ...(configured
+ ? ([
+ { key: "jwt-identity-provider-uri", value: "http://example.com" },
+ { key: "jwt-shared-secret", value: "590ab155f412d477b8ab9c8b0e7b" },
+ ] as const)
+ : []),
]);
setupPropertiesEndpoints(
createMockSettings({
@@ -39,18 +48,18 @@ const setup = async ({
}),
);
setupUpdateSettingsEndpoint();
+ setupUpdateSettingEndpoint();
setupGenerateRandomTokenEndpoint("1234abcd");
fetchMock.get("path:/api/permissions/group", GROUPS);
- renderWithProviders(<SettingsJWTForm />);
+ renderWithProviders(<SettingsJWTForm />, { withUndos: true });
await screen.findByText("Server Settings");
};
describe("SettingsJWTForm", () => {
const ATTRS = {
- "jwt-user-provisioning-enabled?": false,
"jwt-identity-provider-uri": "http://example.com",
"jwt-shared-secret":
"590ab155f412d477b8ab9c8b0e7b2e3ab4d4523e83770a724a2088edbde7f19a",
@@ -109,6 +118,39 @@ describe("SettingsJWTForm", () => {
expect(body).toEqual(ATTRS);
});
+ it("should only update the mappings setting when adding a group mapping", async () => {
+ await setup({ jwtEnabled: true, configured: true });
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: /New mapping/ }),
+ );
+ await userEvent.type(
+ await screen.findByLabelText("New group mapping name"),
+ "cn=People",
+ );
+ await userEvent.click(await screen.findByRole("button", { name: "Add" }));
+
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ const [{ url, body }] = puts;
+ expect(url).toMatch(/\/api\/setting\/jwt-group-mappings$/);
+ expect(body).toEqual({ value: { "cn=People": [] } });
+ });
+
+ it("shows a toast after saving", async () => {
+ await setup({ jwtEnabled: true, configured: true });
+
+ await userEvent.type(
+ await screen.findByRole("textbox", { name: /JWT Identity Provider URI/ }),
+ "/extra",
+ );
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Save changes" }),
+ );
+
+ expect(await screen.findByText("Changes saved")).toBeInTheDocument();
+ });
+
it("should not show tenant attribute unless tenanting is on", async () => {
await setup();
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx
index 8c4ab5e60ad..ca41bab878e 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsOIDCForm/SettingsOIDCForm.unit.spec.tsx
@@ -51,7 +51,9 @@ function setupEndpoints({
setupPropertiesEndpoints(settings);
fetchMock.get("path:/api/permissions/group", GROUPS);
- fetchMock.get("path:/api/ee/sso/oidc", providers);
+ fetchMock.get("path:/api/ee/sso/oidc", providers, {
+ name: "oidc-providers",
+ });
fetchMock.post("path:/api/ee/sso/oidc", 200);
fetchMock.put("path:/api/ee/sso/oidc/okta", 200);
fetchMock.post("path:/api/ee/sso/oidc/check", {
@@ -83,45 +85,20 @@ describe("SettingsOIDCForm - Group Sync", () => {
).not.toBeInTheDocument();
});
- it("shows group sync section for existing providers", async () => {
+ it("shows the group sync UI for existing providers", async () => {
await setup({ providers: [EXISTING_PROVIDER] });
expect(
screen.getByText("Synchronize group membership with your SSO"),
).toBeInTheDocument();
- });
-
- it("renders group sync toggle", async () => {
- await setup({ providers: [EXISTING_PROVIDER] });
-
expect(screen.getByTestId("group-sync-switch")).toBeInTheDocument();
- });
-
- it("renders group attribute text input", async () => {
- await setup({ providers: [EXISTING_PROVIDER] });
-
expect(screen.getByLabelText("Group attribute name")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "New mapping" }),
+ ).toBeInTheDocument();
});
- it("populates group sync fields from existing provider config", async () => {
- await setup({
- providers: [
- {
- ...EXISTING_PROVIDER,
- "group-sync": {
- enabled: true,
- "group-attribute": "groups",
- "group-mappings": { engineers: [3] },
- },
- },
- ],
- });
-
- const groupAttrInput = screen.getByLabelText("Group attribute name");
- expect(groupAttrInput).toHaveValue("groups");
- });
-
- it("shows existing group mappings from provider config", async () => {
+ it("populates group sync fields and mappings from existing provider config", async () => {
await setup({
providers: [
{
@@ -135,25 +112,11 @@ describe("SettingsOIDCForm - Group Sync", () => {
],
});
+ expect(screen.getByLabelText("Group attribute name")).toHaveValue("groups");
expect(screen.getByText("admins")).toBeInTheDocument();
expect(screen.getByText("devs")).toBeInTheDocument();
});
- it("renders New mapping button", async () => {
- await setup({
- providers: [
- {
- ...EXISTING_PROVIDER,
- "group-sync": { enabled: true, "group-mappings": {} },
- },
- ],
- });
-
- expect(
- screen.getByRole("button", { name: "New mapping" }),
- ).toBeInTheDocument();
- });
-
it("includes group sync in form submission", async () => {
await setup({ providers: [EXISTING_PROVIDER] });
@@ -187,59 +150,63 @@ describe("SettingsOIDCForm - Group Sync", () => {
// Scenario: user adds a mapping via GroupMappingsWidgetView (which saves
// immediately via PUT), then submits the form. The form should include the
// freshly-saved mappings, not the stale prop value from initial render.
- await setup({
- providers: [
+ const provider = {
+ ...EXISTING_PROVIDER,
+ "group-sync": {
+ enabled: true,
+ "group-attribute": "groups",
+ "group-mappings": {},
+ },
+ };
+ await setup({ providers: [provider] });
+
+ // Make the form dirty so it can be saved
+ const groupAttrInput = screen.getByLabelText("Group attribute name");
+ await userEvent.clear(groupAttrInput);
+ await userEvent.type(groupAttrInput, "roles");
+
+ // After the widget saves, the providers refetch returns the new mapping
+ fetchMock.removeRoute("oidc-providers");
+ fetchMock.get(
+ "path:/api/ee/sso/oidc",
+ [
{
- ...EXISTING_PROVIDER,
+ ...provider,
"group-sync": {
- enabled: true,
- "group-attribute": "groups",
- "group-mappings": {},
+ ...provider["group-sync"],
+ "group-mappings": { "Group 1": [] },
},
},
],
- });
-
- // Make the form dirty first so we can detect the form-level submit
- const groupAttrInput = screen.getByLabelText("Group attribute name");
- await userEvent.clear(groupAttrInput);
- await userEvent.type(groupAttrInput, "roles");
+ { name: "oidc-providers" },
+ );
// Add a mapping via the widget: click "New mapping", type name, click Add
- const newMappingButton = screen.getByRole("button", {
- name: "New mapping",
+ await userEvent.click(screen.getByRole("button", { name: "New mapping" }));
+ await userEvent.type(screen.getByPlaceholderText("Group name"), "Group 1");
+ await userEvent.click(screen.getByRole("button", { name: "Add" }));
+
+ // The widget saves the mapping immediately, without submitting the form
+ await waitFor(async () => {
+ const puts = await getOidcPutCalls();
+ expect(puts).toHaveLength(1);
});
- await userEvent.click(newMappingButton);
-
- const input = screen.getByPlaceholderText("Group name");
- await userEvent.type(input, "Group 1");
- const addButton = screen.getByRole("button", { name: "Add" });
- await userEvent.click(addButton);
-
- // The "Add" button (type="submit") also submits the Formik form, so
- // multiple PUTs fire. The form submit that includes full provider data
- // (attribute-map, scopes, etc.) is the one from the Formik handler.
- // Due to event ordering, the first form PUT may have stale mappings,
- // but the second one (after the ref is updated) should have the correct
- // mappings. We verify the LAST form-level PUT has the right data.
+
+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));
+
await waitFor(async () => {
const puts = await getOidcPutCalls();
- const formPuts = puts.filter(
- (p: { body: Record<string, unknown> }) => p.body["attribute-map"],
- );
- expect(formPuts.length).toBeGreaterThanOrEqual(1);
+ expect(puts).toHaveLength(2);
});
const puts = await getOidcPutCalls();
- const formPuts = puts.filter(
- (p: { body: Record<string, unknown> }) => p.body["attribute-map"],
- );
- const lastFormPut = formPuts[formPuts.length - 1];
- // The last form submission should include the mapping added via the widget
- expect(lastFormPut.body["group-sync"]["group-mappings"]).toEqual({
+ const formPut = puts[puts.length - 1];
+ // The form submission should include the mapping added via the widget
+ expect(formPut.body["attribute-map"]).toBeDefined();
+ expect(formPut.body["group-sync"]["group-mappings"]).toEqual({
"Group 1": [],
});
- expect(lastFormPut.body["group-sync"]["group-attribute"]).toBe("roles");
+ expect(formPut.body["group-sync"]["group-attribute"]).toBe("roles");
});
it("preserves existing group mappings on form submission", async () => {
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx
index c5fd8f126f4..6e2b222c69b 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/auth/components/SettingsSAMLForm/SettingsSAMLForm.tsx
@@ -264,6 +264,7 @@ export function SettingsSAMLForm() {
<FormTextInput
name="saml-attribute-group"
label={t`Group attribute name`}
+ placeholder="member_of"
nullable
{...getExtraFormFieldProps(
settingDetails?.["saml-attribute-group"],
diff --git a/frontend/src/metabase/admin/components/AdminContentTable/AdminContentTable.tsx b/frontend/src/metabase/admin/components/AdminContentTable/AdminContentTable.tsx
index 334ad6cd02d..dd7dd26d8f1 100644
--- a/frontend/src/metabase/admin/components/AdminContentTable/AdminContentTable.tsx
+++ b/frontend/src/metabase/admin/components/AdminContentTable/AdminContentTable.tsx
@@ -1,3 +1,4 @@
+import cx from "classnames";
import type { ReactNode } from "react";
import AdminS from "metabase/css/admin.module.css";
@@ -5,11 +6,16 @@ import AdminS from "metabase/css/admin.module.css";
export const AdminContentTable = ({
columnTitles,
children,
+ className,
}: {
columnTitles: ReactNode[];
children: ReactNode;
+ className?: string;
}) => (
- <table data-testid="admin-content-table" className={AdminS.ContentTable}>
+ <table
+ data-testid="admin-content-table"
+ className={cx(AdminS.ContentTable, className)}
+ >
<thead>
<tr>
{columnTitles &&
diff --git a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
index d231b12a339..f6021cb658f 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsLdapForm.tsx
@@ -212,6 +212,7 @@ export const SettingsLdapForm = () => {
<FormTextInput
name="ldap-group-base"
label={t`Group search base`}
+ placeholder="ou=groups,dc=example,dc=org"
nullable
{...getExtraFormFieldProps(
settingDetails?.["ldap-group-base"],
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.css
new file mode 100644
index 00000000000..baeb96916af
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.module.css
@@ -0,0 +1,17 @@
+/* A bare borderless input: Mantine's TextInput (even variant="unstyled")
+ keeps a themed border in Metabase, which would double up with the brand
+ border on the surrounding row. */
+.input {
+ flex: 1 0 auto;
+ margin-left: var(--mantine-spacing-sm);
+ border: none;
+ background: transparent;
+ box-shadow: none;
+ outline: 0;
+ font-size: var(--mantine-font-size-lg);
+}
+
+.input:focus {
+ box-shadow: none;
+ outline: 0;
+}
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx
index 533d9864450..1a0f9e6ce06 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/AddMappingRow.tsx
@@ -1,10 +1,10 @@
-import cx from "classnames";
import { useState } from "react";
import { t } from "ttag";
import type { MappingsType } from "metabase/admin/types";
-import CS from "metabase/css/core/index.css";
-import { Button } from "metabase/ui";
+import { Button, Flex, Group } from "metabase/ui";
+
+import S from "./AddMappingRow.module.css";
type AddMappingRowProps = {
mappings: MappingsType;
@@ -13,7 +13,7 @@ type AddMappingRowProps = {
onAdd: (value: string) => void | Promise<void>;
};
-function AddMappingRow({
+export function AddMappingRow({
mappings,
placeholder,
onCancel,
@@ -22,14 +22,16 @@ function AddMappingRow({
const [value, setValue] = useState("");
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
- // Enter key
- if (e.keyCode === 13) {
- handleSubmit();
+ if (e.key === "Enter") {
+ // don't natively submit an enclosing settings form
+ e.preventDefault();
+ if (isMappingNameUnique) {
+ handleAdd();
+ }
}
};
- const handleSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
- e?.preventDefault();
+ const handleAdd = async () => {
await onAdd(value);
setValue("");
};
@@ -42,49 +44,36 @@ function AddMappingRow({
const isMappingNameUnique = value && mappings[value] === undefined;
return (
- <tr>
- <td colSpan={3} style={{ padding: 0 }}>
- <div
- className={cx(
- CS.m2,
- CS.p1,
- CS.bordered,
- CS.borderBrand,
- CS.justifyBetween,
- CS.rounded,
- CS.relative,
- CS.flex,
- CS.alignCenter,
- )}
- >
- <input
- aria-label="new-group-mapping-name-input"
- className={cx(CS.inputBorderless, CS.h3, CS.ml1, CS.flexFull)}
- type="text"
- value={value}
- placeholder={placeholder}
- autoFocus
- onChange={(e) => setValue(e.target.value)}
- onKeyDown={handleKeyDown}
- />
- <div>
- <Button
- variant="subtle"
- onClick={handleCancelClick}
- >{t`Cancel`}</Button>
- <Button
- className={CS.ml2}
- type="submit"
- variant={isMappingNameUnique ? "filled" : "default"}
- disabled={!isMappingNameUnique}
- onClick={() => (isMappingNameUnique ? handleSubmit() : undefined)}
- >{t`Add`}</Button>
- </div>
- </div>
- </td>
- </tr>
+ <Flex
+ align="center"
+ justify="space-between"
+ bd="1px solid var(--mb-color-core-brand)"
+ bdrs="md"
+ m="md"
+ p="sm"
+ >
+ <input
+ aria-label={t`New group mapping name`}
+ className={S.input}
+ type="text"
+ value={value}
+ placeholder={placeholder}
+ autoFocus
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={handleKeyDown}
+ />
+ <Group gap="md">
+ <Button
+ variant="subtle"
+ onClick={handleCancelClick}
+ >{t`Cancel`}</Button>
+ <Button
+ type="button"
+ variant={isMappingNameUnique ? "filled" : "default"}
+ disabled={!isMappingNameUnique}
+ onClick={() => (isMappingNameUnique ? handleAdd() : undefined)}
+ >{t`Add`}</Button>
+ </Group>
+ </Flex>
);
}
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default AddMappingRow;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx
index 980e18302e4..41ab0ef6cd5 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/AddMappingRow/index.tsx
@@ -1,2 +1 @@
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export { default } from "./AddMappingRow";
+export * from "./AddMappingRow";
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.styled.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.styled.tsx
deleted file mode 100644
index bae377b93fc..00000000000
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.styled.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import styled from "@emotion/styled";
-
-export const ModalHeader = styled.h2`
- padding: var(--mantine-spacing-xl);
-`;
-
-export const ModalSubtitle = styled.p`
- padding: 0 var(--mantine-spacing-xl);
-`;
-
-export const ModalRadioRoot = styled.div`
- padding: var(--mantine-spacing-xs) var(--mantine-spacing-xl);
-`;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx
index c5d515345b8..85b18986e98 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.tsx
@@ -5,17 +5,7 @@ import type {
DeleteMappingModalValueType,
GroupIds,
} from "metabase/admin/types";
-import { Modal } from "metabase/common/components/Modal";
-import { ModalFooter } from "metabase/common/components/ModalContent";
-import { Radio } from "metabase/common/components/Radio";
-import CS from "metabase/css/core/index.css";
-import { Button } from "metabase/ui";
-
-import {
- ModalHeader,
- ModalRadioRoot,
- ModalSubtitle,
-} from "./DeleteGroupMappingModal.styled";
+import { Box, Button, Group, Modal, Radio, Stack, Text } from "metabase/ui";
export type DeleteGroupMappingModalProps = {
name: string;
@@ -28,7 +18,7 @@ export type DeleteGroupMappingModalProps = {
onHide: () => void;
};
-const DeleteGroupMappingModal = ({
+export const DeleteGroupMappingModal = ({
name,
groupIds,
onConfirm,
@@ -64,48 +54,46 @@ const DeleteGroupMappingModal = ({
: t`What should happen with the group itself in Metabase?`;
return (
- <Modal>
- <div>
- <ModalHeader>{t`Remove this group mapping?`}</ModalHeader>
- <ModalSubtitle>{subtitle}</ModalSubtitle>
- <ModalRadioRoot>
- <p>{whatShouldHappenText}</p>
+ <Modal opened onClose={onHide} title={t`Remove this group mapping?`}>
+ <Stack gap="lg" mt="sm">
+ <Text>{subtitle}</Text>
- <Radio
- className={CS.ml2}
- vertical
- value={value as DeleteMappingModalValueType | undefined}
- options={[
- {
- name: t`Nothing, just remove the mapping`,
- value: "nothing",
- },
- {
- name: t`Also remove all group members (except from Admin)`,
- value: "clear",
- },
- {
- name:
+ <Box>
+ <Text mb="md">{whatShouldHappenText}</Text>
+ <Radio.Group
+ value={value}
+ onChange={(newValue) =>
+ handleChange(newValue as DeleteMappingModalValueType)
+ }
+ >
+ <Stack gap="sm">
+ <Radio
+ value="nothing"
+ label={t`Nothing, just remove the mapping`}
+ />
+ <Radio
+ value="clear"
+ label={t`Also remove all group members (except from Admin)`}
+ />
+ <Radio
+ value="delete"
+ label={
groupIds.length > 1
? t`Also delete the groups (except Admin)`
- : t`Also delete the group`,
- value: "delete",
- },
- ]}
- showButtons
- onChange={handleChange}
- />
- </ModalRadioRoot>
- <ModalFooter fullPageModal={false} formModal={true}>
+ : t`Also delete the group`
+ }
+ />
+ </Stack>
+ </Radio.Group>
+ </Box>
+
+ <Group justify="flex-end">
<Button onClick={onHide}>{t`Cancel`}</Button>
<Button variant="filled" color="error" onClick={handleConfirm}>
- {submitButtonLabels[value as DeleteMappingModalValueType]}
+ {submitButtonLabels[value]}
</Button>
- </ModalFooter>
- </div>
+ </Group>
+ </Stack>
</Modal>
);
};
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default DeleteGroupMappingModal;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx
index cea001f6a3f..666dec8cfeb 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/DeleteGroupMappingModal.unit.spec.tsx
@@ -2,8 +2,10 @@ import userEvent from "@testing-library/user-event";
import { render, screen } from "__support__/ui";
-import type { DeleteGroupMappingModalProps } from "./DeleteGroupMappingModal";
-import DeleteGroupMappingModal from "./DeleteGroupMappingModal";
+import {
+ DeleteGroupMappingModal,
+ type DeleteGroupMappingModalProps,
+} from "./DeleteGroupMappingModal";
type SetupOpts = Partial<DeleteGroupMappingModalProps>;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsx
index 25c0117ebb2..f8d613ebff6 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/DeleteGroupMappingModal/index.tsx
@@ -1,2 +1 @@
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export { default } from "./DeleteGroupMappingModal";
+export * from "./DeleteGroupMappingModal";
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.css
new file mode 100644
index 00000000000..f18a50d1812
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.module.css
@@ -0,0 +1,28 @@
+/* Fixed column widths so a long mapping name can't widen the first column
+ and push the other columns around. */
+.mappingsTable {
+ table-layout: fixed;
+}
+
+.mappingsTable th:first-child,
+.mappingsTable td:first-child {
+ width: 50%;
+ overflow-wrap: anywhere;
+}
+
+.mappingsTable th:nth-child(2),
+.mappingsTable td:nth-child(2) {
+ width: 40%;
+}
+
+.mappingsTable th:nth-child(3),
+.mappingsTable td:nth-child(3) {
+ width: 10%;
+}
+
+/* Only the top corners are rounded to match the card; bdrs prop can't express
+ a partial radius. */
+.header {
+ border-top-left-radius: var(--mantine-radius-md);
+ border-top-right-radius: var(--mantine-radius-md);
+}
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.styled.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.styled.tsx
deleted file mode 100644
index 2ce46ada17b..00000000000
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.styled.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import styled from "@emotion/styled";
-
-import { Button } from "metabase/common/components/Button";
-
-export const GroupMappingsWidgetAndErrorRoot = styled.div`
- display: flex;
- flex-direction: column;
- width: 100%;
-`;
-
-export const GroupMappingsWidgetRoot = styled.div`
- border: 1px solid var(--mb-color-border);
- border-radius: 8px;
- display: flex;
- flex-direction: column;
- max-width: 720px;
- width: 100%;
-`;
-
-export const GroupMappingsWidgetHeader = styled.div`
- background-color: var(--mb-color-background-secondary);
- border-top-left-radius: 8px;
- border-top-right-radius: 8px;
- display: flex;
- justify-content: space-between;
- margin-bottom: var(--mantine-spacing-md);
- padding: var(--mantine-spacing-sm) var(--mantine-spacing-md);
-
- span {
- font-weight: 700;
- }
-`;
-
-export const GroupMappingsWidgetToggleRoot = styled.div`
- align-items: center;
- display: flex;
-
- > * {
- color: var(--mb-color-text-primary);
- padding-right: var(--mantine-spacing-sm);
- padding-top: 0;
- }
-`;
-
-export const GroupMappingsWidgetAbout = styled.div`
- align-items: center;
- color: var(--mb-color-text-secondary);
- display: flex;
- flex-direction: row;
-
- span {
- padding-left: var(--mantine-spacing-sm);
- }
-`;
-
-export const GroupMappingsWidgetAboutContentRoot = styled.div`
- display: flex;
- align-items: center;
-`;
-
-export const AddMappingButton = styled(Button)`
- float: right;
- margin-right: var(--mantine-spacing-md);
- margin-bottom: -40px;
-`;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx
index 836665e328a..73d0053ec16 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidget.unit.spec.tsx
@@ -1,6 +1,6 @@
import userEvent from "@testing-library/user-event";
-import { render, screen, waitFor } from "__support__/ui";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { FormProvider } from "metabase/forms";
import type { GroupId, GroupInfo } from "metabase-types/api";
import { createMockGroup } from "metabase-types/api/mocks";
@@ -38,7 +38,7 @@ const setup = ({
setting = { key: "key", value: true },
groups = defaultGroups,
}: SetupOptions = {}) => {
- render(
+ return renderWithProviders(
<FormProvider
initialValues={{ [setting.key]: setting.value }}
onSubmit={() => {}}
@@ -55,6 +55,7 @@ const setup = ({
updateSetting={updateSetting}
/>
</FormProvider>,
+ { withUndos: true },
);
};
@@ -68,7 +69,7 @@ describe("GroupMappingsWidgetView", () => {
expect(
await screen.findByText(
- /Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server\. If no mappings are defined, groups will automatically be assigned based on exactly matching names\./,
+ /If no mappings are defined, groups will automatically be assigned based on exactly matching names/,
),
).toBeInTheDocument();
});
@@ -81,7 +82,7 @@ describe("GroupMappingsWidgetView", () => {
expect(
await screen.findByText(
- /Mappings allow Metabase to automatically add and remove users from groups based on the membership information provided by the directory server\. If a group isn‘t mapped, its membership won‘t be synced\./,
+ /If a group isn‘t mapped, its membership won‘t be synced/,
),
).toBeInTheDocument();
});
@@ -122,6 +123,61 @@ describe("GroupMappingsWidgetView", () => {
expect(await screen.findByText("No mappings yet")).toBeInTheDocument();
});
+
+ it("hides the table column headers when there are no mappings", async () => {
+ setup({ mappings: {} });
+
+ expect(await screen.findByText("No mappings yet")).toBeInTheDocument();
+ expect(screen.queryByRole("columnheader")).not.toBeInTheDocument();
+ });
+
+ it("shows the table column headers once a mapping exists", async () => {
+ setup({ mappingSetting: "ldap-group-mappings" });
+
+ expect(
+ await screen.findByRole("columnheader", { name: "Groups" }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("adding a mapping", () => {
+ it("adds a mapping with a unique name on Enter", async () => {
+ const updateSettingSpy = jest.fn();
+ setup({ updateSetting: updateSettingSpy });
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "New mapping" }),
+ );
+ await userEvent.type(
+ screen.getByLabelText("New group mapping name"),
+ "cn=People{Enter}",
+ );
+
+ await waitFor(() => {
+ expect(updateSettingSpy).toHaveBeenCalledWith({
+ key: "ldap-group-mappings",
+ value: { "group=Administrators": [1], "cn=People": [] },
+ });
+ });
+
+ // the mapping autosaves, so the user gets a toast confirming it
+ expect(await screen.findByText("Mapping added")).toBeInTheDocument();
+ });
+
+ it("does not add a mapping with a duplicate name on Enter", async () => {
+ const updateSettingSpy = jest.fn();
+ setup({ updateSetting: updateSettingSpy });
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "New mapping" }),
+ );
+ await userEvent.type(
+ screen.getByLabelText("New group mapping name"),
+ "group=Administrators{Enter}",
+ );
+
+ expect(updateSettingSpy).not.toHaveBeenCalled();
+ });
});
describe("when a mapping is set for admin group", () => {
@@ -143,6 +199,8 @@ describe("GroupMappingsWidgetView", () => {
await waitFor(() => {
expect(updateSettingSpy).toHaveBeenCalledTimes(1);
});
+
+ expect(await screen.findByText("Mapping deleted")).toBeInTheDocument();
});
});
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx
index afb32cb6e00..c41393080c5 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupMappingsWidgetView.tsx
@@ -1,27 +1,29 @@
-import cx from "classnames";
import { useField } from "formik";
import { useState } from "react";
import { t } from "ttag";
import _ from "underscore";
+import NoResults from "assets/img/no_results.svg";
import { AdminContentTable } from "metabase/admin/components/AdminContentTable";
import { isDefaultGroup } from "metabase/admin/utils/groups";
import { getErrorMessage } from "metabase/api/utils/errors";
-import CS from "metabase/css/core/index.css";
+import { EmptyState } from "metabase/common/components/EmptyState";
+import { useToast } from "metabase/common/hooks";
import { FormSwitch } from "metabase/forms";
-import { Icon, Tooltip } from "metabase/ui";
+import {
+ Box,
+ Button,
+ Flex,
+ Group,
+ Icon,
+ Text,
+ Tooltip,
+ rem,
+} from "metabase/ui";
import type { GroupId, GroupInfo } from "metabase-types/api";
-import AddMappingRow from "./AddMappingRow";
-import {
- GroupMappingsWidgetAbout as About,
- GroupMappingsWidgetAboutContentRoot as AboutContentRoot,
- AddMappingButton,
- GroupMappingsWidgetHeader as Header,
- GroupMappingsWidgetRoot as Root,
- GroupMappingsWidgetToggleRoot as ToggleRoot,
- GroupMappingsWidgetAndErrorRoot as WidgetAndErrorRoot,
-} from "./GroupMappingsWidget.styled";
+import { AddMappingRow } from "./AddMappingRow";
+import S from "./GroupMappingsWidget.module.css";
import { MappingRow } from "./MappingRow";
const groupIsMappable = (group: GroupInfo) => !isDefaultGroup(group);
@@ -35,7 +37,7 @@ const helpText = (mappingSetting: string) => {
const noMappingText = (mappingSetting: string, syncSwitchValue: boolean) => {
if (!syncSwitchValue) {
- return `No mappings yet, group sync is not on`;
+ return t`No mappings yet, group sync is not on`;
}
if (mappingSetting === "jwt-group-mappings") {
return t`No mappings yet, groups will be automatically assigned by exactly matching names`;
@@ -74,6 +76,7 @@ export function GroupMappingsWidgetView({
}: GroupMappingsWidgetViewProps) {
const [showAddRow, setShowAddRow] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
+ const [sendToast] = useToast();
const groups = allGroups.filter(groupIsMappable);
@@ -95,6 +98,7 @@ export function GroupMappingsWidgetView({
});
setShowAddRow(false);
setSaveError(null);
+ sendToast({ message: t`Mapping added`, icon: "check" });
} catch (error) {
setSaveError(getErrorMessage(error));
}
@@ -112,6 +116,7 @@ export function GroupMappingsWidgetView({
try {
await updateSetting({ key: mappingSetting, value: updatedMappings });
setSaveError(null);
+ sendToast({ message: t`Mapping updated`, icon: "check" });
} catch (error) {
setSaveError(getErrorMessage(error));
}
@@ -136,6 +141,7 @@ export function GroupMappingsWidgetView({
await onSuccess();
}
setSaveError(null);
+ sendToast({ message: t`Mapping deleted`, icon: "check" });
} catch (error) {
setSaveError(getErrorMessage(error));
}
@@ -143,75 +149,92 @@ export function GroupMappingsWidgetView({
const [{ value: groupSyncSwitchValue }] = useField<boolean>(setting.key);
+ const hasMappings = Object.keys(mappings).length > 0;
+
return (
- <WidgetAndErrorRoot>
- <Root>
- <Header>
- <ToggleRoot>
- <span>{t`Synchronize Group Memberships`}</span>
- <FormSwitch data-testid="group-sync-switch" name={setting.key} />
- </ToggleRoot>
- <About>
- <Tooltip
- label={helpText(mappingSetting)}
- position="top"
- maw="20rem"
+ <Flex direction="column" w="100%">
+ <Group mb="md" gap="sm">
+ <Text fw="bold">{t`Synchronize Group Memberships`}</Text>
+ <FormSwitch data-testid="group-sync-switch" name={setting.key} />
+ </Group>
+
+ <Flex
+ bd="1px solid var(--mb-color-border)"
+ bdrs="md"
+ direction="column"
+ w="100%"
+ >
+ <Flex
+ className={S.header}
+ align="center"
+ bg="background-secondary"
+ mih={rem(56)}
+ px="md"
+ py="sm"
+ >
+ {!showAddRow && (
+ <Button
+ variant="filled"
+ size="sm"
+ type="button"
+ onClick={handleShowAddRow}
>
- <AboutContentRoot>
- <Icon name="info" />
- <span>{t`About mappings`}</span>
- </AboutContentRoot>
- </Tooltip>
- </About>
- </Header>
-
- <div>
- <div>
- {!showAddRow && (
- <AddMappingButton primary small onClick={handleShowAddRow}>
- {t`New mapping`}
- </AddMappingButton>
- )}
- <AdminContentTable columnTitles={[groupHeading, t`Groups`, ""]}>
- {showAddRow && (
- <AddMappingRow
- mappings={mappings}
- placeholder={groupPlaceholder}
- onCancel={handleHideAddRow}
- onAdd={handleAddMapping}
+ {t`New mapping`}
+ </Button>
+ )}
+ <Tooltip label={helpText(mappingSetting)} position="top" maw="20rem">
+ <Flex align="center" gap="sm" c="text-secondary" ml="auto">
+ <Icon name="info" />
+ <span>{t`About mappings`}</span>
+ </Flex>
+ </Tooltip>
+ </Flex>
+
+ {showAddRow && (
+ <AddMappingRow
+ mappings={mappings}
+ placeholder={groupPlaceholder}
+ onCancel={handleHideAddRow}
+ onAdd={handleAddMapping}
+ />
+ )}
+ {hasMappings ? (
+ <AdminContentTable
+ className={S.mappingsTable}
+ columnTitles={[groupHeading, t`Groups`, ""]}
+ >
+ {Object.entries(mappings).map(([name, selectedGroupIds]) => {
+ return groups?.length > 0 ? (
+ <MappingRow
+ key={name}
+ name={name}
+ groups={groups}
+ selectedGroupIds={selectedGroupIds}
+ clearGroupMember={clearGroupMember}
+ deleteGroup={deleteGroup}
+ onChange={handleChangeMapping(name)}
+ onDeleteMapping={handleDeleteMapping}
/>
- )}
- {Object.keys(mappings).length === 0 && !showAddRow && (
- <tr>
- <td>&nbsp;</td>
- <td>
- {" "}
- {noMappingText(mappingSetting, groupSyncSwitchValue)}
- </td>
- <td>&nbsp;</td>
- </tr>
- )}
- {Object.entries(mappings).map(([name, selectedGroupIds]) => {
- return groups?.length > 0 ? (
- <MappingRow
- key={name}
- name={name}
- groups={groups}
- selectedGroupIds={selectedGroupIds}
- clearGroupMember={clearGroupMember}
- deleteGroup={deleteGroup}
- onChange={handleChangeMapping(name)}
- onDeleteMapping={handleDeleteMapping}
- />
- ) : null;
- })}
- </AdminContentTable>
- </div>
- </div>
- </Root>
+ ) : null;
+ })}
+ </AdminContentTable>
+ ) : (
+ !showAddRow && (
+ <Box pb="md">
+ <EmptyState
+ illustrationElement={<img src={NoResults} alt="" />}
+ message={noMappingText(mappingSetting, groupSyncSwitchValue)}
+ spacing="sm"
+ />
+ </Box>
+ )
+ )}
+ </Flex>
{saveError && (
- <div className={cx(CS.textError, CS.textBold, CS.m1)}>{saveError}</div>
+ <Text c="error" fw="bold" m="sm">
+ {saveError}
+ </Text>
)}
- </WidgetAndErrorRoot>
+ </Flex>
);
}
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.css
new file mode 100644
index 00000000000..2e374e9c059
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.module.css
@@ -0,0 +1,7 @@
+/* Mantine's default Combobox group label color is not themed in Metabase
+ (resolves to transparent), so make the section header visible. */
+.groupLabel {
+ color: var(--mb-color-text-secondary);
+ font-weight: 700;
+ text-transform: uppercase;
+}
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx
index d8019734696..15cd487d8ff 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/GroupSelect.tsx
@@ -1,4 +1,4 @@
-import cx from "classnames";
+import { Fragment } from "react";
import { t } from "ttag";
import { GroupSummary } from "metabase/admin/people/components/GroupSummary";
@@ -9,21 +9,29 @@ import {
isAdminGroup,
isDefaultGroup,
} from "metabase/admin/utils/groups";
-import { Select } from "metabase/common/components/Select";
-import CS from "metabase/css/core/index.css";
-import { Box, Icon, Popover } from "metabase/ui";
-import { color } from "metabase/ui/colors";
+import {
+ Box,
+ Checkbox,
+ Combobox,
+ Flex,
+ Icon,
+ UnstyledButton,
+ rem,
+ useCombobox,
+} from "metabase/ui";
import { isNotNull } from "metabase/utils/types";
import type { GroupInfo } from "metabase-types/api";
+import S from "./GroupSelect.module.css";
+
function getGroupColor(group: Pick<GroupInfo, "magic_group_type">) {
if (isAdminGroup(group)) {
- return color("core-filter");
- } else if (isDefaultGroup(group)) {
- return color("text-secondary");
- } else {
- return color("core-brand");
+ return "var(--mb-color-core-filter)";
+ }
+ if (isDefaultGroup(group)) {
+ return "var(--mb-color-text-secondary)";
}
+ return "var(--mb-color-text-primary)";
}
type GroupSelectProps = {
@@ -37,9 +45,9 @@ type GroupSelectProps = {
function getSections(groups: GroupInfo[]) {
const adminGroup = groups.find(isAdminGroup);
const defaultGroup = groups.find(isDefaultGroup);
- const topGroups = [defaultGroup, adminGroup].filter((g) => g != null);
+ const topGroups = [defaultGroup, adminGroup].filter(isNotNull);
const groupsExceptDefaultAndAdmin = groups.filter(
- (g) => !isAdminGroup(g) && !isDefaultGroup(g),
+ (group) => !isAdminGroup(group) && !isDefaultGroup(group),
);
if (topGroups.length === 0) {
@@ -49,10 +57,7 @@ function getSections(groups: GroupInfo[]) {
return [
{ items: topGroups },
groupsExceptDefaultAndAdmin.length > 0
- ? {
- items: groupsExceptDefaultAndAdmin as any,
- name: t`Groups`,
- }
+ ? { items: groupsExceptDefaultAndAdmin, name: t`Groups` }
: null,
].filter(isNotNull);
}
@@ -64,57 +69,82 @@ export const GroupSelect = ({
isCurrentUser = false,
emptyListMessage = t`No groups`,
}: GroupSelectProps) => {
- const triggerElement = (
- <div className={cx(CS.flex, CS.alignCenter)}>
- <GroupSummary
- mr="0.5rem"
- groups={groups}
- selectedGroupIds={selectedGroupIds}
- />
- <Icon className={CS.textLight} name="chevrondown" size={10} />
- </div>
- );
+ const combobox = useCombobox();
- if (groups.length === 0) {
- return (
- <Popover withinPortal={false} position="bottom-start">
- <Popover.Target>{triggerElement}</Popover.Target>
- <Popover.Dropdown style={{ boxSizing: "border-box" }}>
- <Box p="sm">{emptyListMessage}</Box>
- </Popover.Dropdown>
- </Popover>
- );
- }
+ const handleOptionSubmit = (value: string) => {
+ const groupId = Number(value);
+ const group = groups.find((candidate) => candidate.id === groupId);
+ if (group == null) {
+ return;
+ }
+ onGroupChange(group, !selectedGroupIds.includes(groupId));
+ };
const sections = getSections(groups);
return (
- <Select
- triggerElement={triggerElement}
- onChange={({ target: { value } }: { target: { value: any } }) => {
- groups
- .filter(
- // find the differing groups between the new `value` on previous `selectedGroupIds`
- (group) =>
- (selectedGroupIds.includes(group.id) as any) ^
- value.includes(group.id),
- )
- .forEach((group) => onGroupChange(group, value.includes(group.id)));
- }}
- optionDisabledFn={(group: GroupInfo) =>
- (isAdminGroup(group) && isCurrentUser) || !canEditMembership(group)
- }
- optionValueFn={(group: GroupInfo) => group.id}
- optionNameFn={getGroupNameLocalized}
- optionStylesFn={(group: GroupInfo) => ({
- color: getGroupColor(group),
- })}
- value={selectedGroupIds}
- sections={sections}
- multiple
- />
+ <Combobox
+ store={combobox}
+ position="bottom-start"
+ width={rem(240)}
+ classNames={{ groupLabel: S.groupLabel }}
+ onOptionSubmit={handleOptionSubmit}
+ >
+ <Combobox.Target>
+ <UnstyledButton onClick={() => combobox.toggleDropdown()}>
+ <Flex align="center">
+ <GroupSummary
+ mr="sm"
+ groups={groups}
+ selectedGroupIds={selectedGroupIds}
+ />
+ <Icon c="text-tertiary" name="chevrondown" size={10} />
+ </Flex>
+ </UnstyledButton>
+ </Combobox.Target>
+
+ <Combobox.Dropdown>
+ {groups.length === 0 ? (
+ <Box p="sm">{emptyListMessage}</Box>
+ ) : (
+ <Combobox.Options>
+ {sections.map((section, index) => {
+ const options = section.items.map((group) => (
+ <Combobox.Option
+ key={group.id}
+ value={String(group.id)}
+ aria-label={getGroupNameLocalized(group)}
+ disabled={
+ (isAdminGroup(group) && isCurrentUser) ||
+ !canEditMembership(group)
+ }
+ >
+ <Flex align="center" gap="sm">
+ <Checkbox
+ checked={selectedGroupIds.includes(group.id)}
+ readOnly
+ aria-hidden
+ tabIndex={-1}
+ style={{ pointerEvents: "none" }}
+ />
+ <span style={{ color: getGroupColor(group) }}>
+ {getGroupNameLocalized(group)}
+ </span>
+ </Flex>
+ </Combobox.Option>
+ ));
+
+ return "name" in section ? (
+ <Combobox.Group key={index} label={section.name}>
+ {options}
+ </Combobox.Group>
+ ) : (
+ <Fragment key={index}>{options}</Fragment>
+ );
+ })}
+ </Combobox.Options>
+ )}
+ </Combobox.Dropdown>
+ </Combobox>
);
};
-
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export default GroupSelect;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx
index 3b13fb08b9a..cb8dfbf2811 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/GroupSelect/index.tsx
@@ -1,2 +1 @@
-// eslint-disable-next-line import/no-default-export -- deprecated usage
-export { default } from "./GroupSelect";
+export * from "./GroupSelect";
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.css b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.css
new file mode 100644
index 00000000000..9bedf8036e7
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.module.css
@@ -0,0 +1,7 @@
+.deleteButton {
+ color: var(--mb-color-text-primary);
+}
+
+.deleteButton:hover {
+ color: var(--mb-color-danger);
+}
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.styled.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.styled.tsx
deleted file mode 100644
index c09c65825e5..00000000000
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.styled.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import styled from "@emotion/styled";
-
-import { IconButtonWrapper } from "metabase/common/components/IconButtonWrapper";
-
-export const DeleteMappingButton = styled(IconButtonWrapper)`
- color: var(--mb-color-text-primary);
-
- &:hover {
- color: var(--mb-color-danger);
- }
-`;
diff --git a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx
index ff10978cc37..abc624c7694 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/GroupMappingsWidget/MappingRow/MappingRow.tsx
@@ -1,5 +1,4 @@
import { useDisclosure } from "@mantine/hooks";
-import cx from "classnames";
import { t } from "ttag";
import _ from "underscore";
@@ -9,15 +8,15 @@ import type {
} from "metabase/admin/types";
import { isAdminGroup } from "metabase/admin/utils/groups";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
+import { IconButtonWrapper } from "metabase/common/components/IconButtonWrapper";
import AdminS from "metabase/css/admin.module.css";
-import CS from "metabase/css/core/index.css";
-import { Icon, Tooltip } from "metabase/ui";
+import { Flex, Icon, Tooltip } from "metabase/ui";
import type { GroupId, GroupInfo } from "metabase-types/api";
-import DeleteGroupMappingModal from "../DeleteGroupMappingModal";
-import Selectbox from "../GroupSelect";
+import { DeleteGroupMappingModal } from "../DeleteGroupMappingModal";
+import { GroupSelect } from "../GroupSelect";
-import { DeleteMappingButton } from "./MappingRow.styled";
+import S from "./MappingRow.module.css";
type OnDeleteMappingType = (arg: {
name: string;
@@ -132,14 +131,14 @@ export const MappingRow = ({
<tr>
<td>{name}</td>
<td>
- <Selectbox
+ <GroupSelect
groups={groups}
selectedGroupIds={selectedGroupIdsFromGroupsThatExist}
onGroupChange={onChange}
/>
</td>
<td className={AdminS.TableActions}>
- <div className={cx(CS.floatRight, CS.mr1)}>
+ <Flex justify="flex-end" mr="sm">
<DeleteButton
onDelete={() =>
shouldUseDeleteGroupMappingModal
@@ -147,7 +146,7 @@ export const MappingRow = ({
: openDeleteMappingModal()
}
/>
- </div>
+ </Flex>
</td>
</tr>
<ConfirmModal
@@ -177,8 +176,8 @@ const DeleteButton = ({
onDelete?: React.MouseEventHandler<HTMLButtonElement>;
}) => (
<Tooltip label={t`Remove mapping`} position="top">
- <DeleteMappingButton onClick={onDelete}>
+ <IconButtonWrapper className={S.deleteButton} onClick={onDelete}>
<Icon name="close" />
- </DeleteMappingButton>
+ </IconButtonWrapper>
</Tooltip>
);