8000 Fix multiselect chip clear for labeled user profile options by blakefrain · Pull Request #55021 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/user/EditUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export default function EditUser() {
setBruteForced({ isBruteForceProtected, isLocked });
setRealmHasOrganizations(organizations.length === 1);

form.reset(toUserFormFields(user));
form.reset(toUserFormFields(user, userProfileMetadata));
},
[refreshCount],
);
Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/user/UserForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export const UserForm = ({

const => {
if (user?.id) {
reset(toUserFormFields(user));
reset(toUserFormFields(user, userProfileMetadata));
} else {
void navigate(toUsers({ realm: realm.realm! }));
}
Expand Down
79 changes: 79 additions & 0 deletions js/apps/admin-ui/src/user/form-state.test.ts
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import { toUserFormFields, toUserRepresentation } from "./form-state";

const metadata = {
attributes: [
{ name: "username" },
{ name: "email" },
{
name: "l2",
multivalued: false,
annotations: {
inputType: "multiselect",
inputOptionLabels: { foo: "FOO", ops: "OPS56" },
},
},
{
name: "tags",
multivalued: true,
},
],
};

describe("toUserFormFields", () => {
it("seeds cleared multiselect attributes as empty arrays so reset drops chips", () => {
const fields = toUserFormFields(
{
username: "qrqwe",
// Server omits cleared attributes from the representation.
attributes: undefined,
},
metadata,
);

expect(fields.attributes).toEqual({
l2: [],
tags: [],
});
});

it("keeps server values over empty seeds", () => {
const fields = toUserFormFields(
{
username: "qrqwe",
attributes: { l2: ["foo"] },
},
metadata,
);

expect(fields.attributes).toEqual({
l2: ["foo"],
tags: [],
});
});

it("does not put root attributes into the attributes map", () => {
const fields = toUserFormFields(
{ username: "qrqwe", email: "a@b.c", attributes: {} },
metadata,
);

expect(fields.attributes).toEqual({
l2: [],
tags: [],
});
expect(fields.username).toBe("qrqwe");
expect(fields.email).toBe("a@b.c");
});
});

describe("toUserRepresentation", () => {
it("preserves empty arrays so the server clears the attribute", () => {
const user = toUserRepresentation({
username: "qrqwe",
attributes: { l2: [] },
});

expect(user.attributes).toEqual({ l2: [] });
});
});
37 changes: 36 additions & 1 deletion js/apps/admin-ui/src/user/form-state.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation";
import type { UserProfileMetadata } from "@keycloak/keycloak-admin-client/lib/defs/userProfileMetadata";
import { isRootAttribute } from "@keycloak/keycloak-ui-shared";
import {
KeyValueType,
arrayToKeyValue,
Expand All @@ -18,8 +20,41 @@ export interface UIUserRepresentation extends UserRepresentation {
unmanagedAttributes?: Record<string, string[]>;
}

export function toUserFormFields(data: UIUserRepresentation): UserFormFields {
function emptyAttributeValue(
attribute: NonNullable<UserProfileMetadata["attributes"]>[number],
): string | string[] {
const inputType = attribute.annotations?.inputType;
if (
attribute.multivalued ||
inputType === "multiselect" ||
inputType === "multiselect-checkboxes"
) {
return [];
}
return "";
}

/**
* Convert a user representation into react-hook-form values.
*
* When `userProfileMetadata` is provided, every managed non-root attribute is
* seeded with an empty value before applying server attributes. Cleared
* attributes are omitted from Keycloak's GET response, and without these seeds
* `form.reset` can leave the previous nested value in the form (e.g. a
* multiselect chip reappears after save).
*/
export function toUserFormFields(
data: UIUserRepresentation,
userProfileMetadata?: UserProfileMetadata,
): UserFormFields {
const attributes: Record<string, string | string[]> = {};

userProfileMetadata?.attributes?.forEach((attribute) => {
if (!isRootAttribute(attribute.name)) {
attributes[beerify(attribute.name!)] = emptyAttributeValue(attribute);
}
});

Object.entries(data.attributes || {}).forEach(
([k, v]) => (attributes[beerify(k)] = v),
);
Expand Down
1 change: 1 addition & 0 deletions js/libs/ui-shared/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export {
beerify,
debeerify,
isBundleKey,
isRootAttribute,
isUserProfileError,
label,
setUserProfileServerError,
Expand Down
91 changes: 91 additions & 0 deletions js/libs/ui-shared/src/user-profile/SelectComponent.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {
cleanup,
fireEvent,
render,
screen,
within,
} from "@testing-library/react";
import { TFunction } from "i18next";
import { FormProvider, useForm, useWatch } from "react-hook-form";
import { afterEach, describe, expect, it } from "vitest";
import { SelectComponent } from "./SelectComponent";
import { UserFormFields } from "./utils";

const t = ((key: string) => key) as TFunction;

const Value = () => (
<output data-testid="value">
{JSON.stringify(useWatch({ name: "attributes.l2" }))}
</output>
);

const Harness = ({ value = ["ops"] }: { value?: string[] }) => {
const form = useForm<UserFormFields>({
defaultValues: { attributes: { l2: value } },
});

return (
<FormProvider {...form}>
<SelectComponent
t={t}
form={form}
inputType="multiselect"
attribute={{
name: "l2",
displayName: "L2",
required: false,
readOnly: false,
validators: {
options: { options: ["ops", "foo"] },
},
annotations: {
inputType: "multiselect",
inputOptionLabels: {
ops: "OPS56",
foo: "FOO",
},
},
}}
/>
<Value />
</FormProvider>
);
};

const formValue = () => screen.getByTestId("value").textContent;
const chipGroup = () => document.querySelector(".pf-v5-c-chip-group")!;
const removeChip = () =>
fireEvent.click(
within(chipGroup() as HTMLElement).getByRole("button", {
name: /close/i,
}),
);

describe("SelectComponent multiselect chips", () => {
afterEach(cleanup);

it("shows the option label on the chip", () => {
render(<Harness />);

expect(within(chipGroup() as HTMLElement).getByText("OPS56")).toBeTruthy();
expect(formValue()).toBe('["ops"]');
});

it("removes the selected option key when the chip is cleared", () => {
render(<Harness />);

removeChip();

expect(chipGroup()).toBeNull();
expect(formValue()).toBe("[]");
});

it("does not add the label string when clearing a labeled chip", () => {
render(<Harness />);

removeChip();

expect(formValue()).not.toContain("OPS56");
expect(formValue()).toBe("[]");
});
});
26 changes: 23 additions & 3 deletions js/libs/ui-shared/src/user-profile/SelectComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SelectOption } from "@patternfly/react-core";
import { Chip, ChipGroup, SelectOption } from "@patternfly/react-core";
import { useState } from "react";
import { Controller, ControllerRenderProps } from "react-hook-form";
import { KeycloakSelect, SelectVariant } from "../select/KeycloakSelect";
Expand Down Expand Up @@ -76,7 +76,7 @@ export const SelectComponent = (props: UserProfileFieldProps) => {
<KeycloakSelect
toggleId={attribute.name}
=> setOpen(b)}
=> setValue("", field)}
=> field.onChange(isMultiValue ? [] : "")}
=> {
const option = value.toString();
setValue(option, field);
Expand All @@ -86,9 +86,29 @@ export const SelectComponent = (props: UserProfileFieldProps) => {
}}
selections={
isMultiValue && Array.isArray(field.value)
? field.value.map((option) => fetchLabel(option))
? field.value
: fetchLabel(field.value)
}
// Chips must remove by option key, but display inputOptionLabels.
// Passing labels as selections made chip clicks toggle/add the label
// string instead of removing the selected option key.
chipGroupComponent={
isMultiValue && Array.isArray(field.value) ? (
<ChipGroup>
{field.value.map((option: string) => (
<Chip
key={option}
=> {
event.stopPropagation();
setValue(option, field);
}}
>
{fetchLabel(option)}
</Chip>
))}
</ChipGroup>
) : undefined
}
variant={
isMultiValue
? SelectVariant.typeaheadMulti
Expand Down
Loading
0