From f0aa84d3b59485d86182348ccc958f0417def838 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Thu, 23 Jul 2026 13:31:33 +0200 Subject: [PATCH 1/3] make multi value toggle less confusing Align multivalued rendering precedence across user profile UIs Ensure inputType-specific controls (select, multiselect, select-radiobuttons, multiselect-checkboxes, textarea) take precedence over generic multi-input rendering in React, and mirror the same fallback behavior in FreeMarker when inputType is unset. Clarify the Multivalued help text in Admin UI and update the user profile Playwright spec to assert the new precedence rules. fixes: #34763 Signed-off-by: Erik Jan de Wit --- .../admin/messages/messages_en.properties | 2 +- .../test/realm-settings/userprofile.spec.ts | 104 +++++++++++++++++- .../src/user-profile/UserProfileFields.tsx | 20 +++- .../theme/base/login/user-profile-commons.ftl | 3 +- 4 files changed, 120 insertions(+), 9 deletions(-) diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index 9d3d8ca1783..0842cf201a3 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -3596,7 +3596,7 @@ bruteForceMode.PermanentAfterTemporaryLockout=Lockout permanently after temporar bruteForceMode=Brute Force Mode error-invalid-multivalued-size=Attribute {{0}} must have at least {{1}} and at most {{2}} value(s). multivalued=Multivalued -multivaluedHelp=If this attribute supports multiple values. This setting is an indicator and does not enable any validation. For that, make sure to use any of the built-in validators to properly validate the size and the values. +multivaluedHelp=If enabled, this attribute can store multiple values. Rendering depends on inputType annotations (for example, multiselect and multiselect-checkboxes use their own controls). Use validators to enforce allowed value counts. defaultValue=Default value defaultValueHelp=Default value when attribute value is not specified. sendIdTokenOnLogout=Send 'id_token_hint' in logout requests diff --git a/js/apps/admin-ui/test/realm-settings/userprofile.spec.ts b/js/apps/admin-ui/test/realm-settings/userprofile.spec.ts index 1f0eaa1e200..a389d5fe216 100644 --- a/js/apps/admin-ui/test/realm-settings/userprofile.spec.ts +++ b/js/apps/admin-ui/test/realm-settings/userprofile.spec.ts @@ -1,7 +1,12 @@ import { expect, test } from "@playwright/test"; import { v4 as uuid } from "uuid"; import adminClient from "../utils/AdminClient.ts"; -import { assertFieldError, selectItem, switchOn } from "../utils/form.ts"; +import { + assertFieldError, + selectItem, + switchOff, + switchOn, +} from "../utils/form.ts"; import { login } from "../utils/login.ts"; import { assertNotificationMessage } from "../utils/masthead.ts"; import { confirmModal } from "../utils/modal.ts"; @@ -34,6 +39,29 @@ test.describe.serial("User profile tabs", () => { const group = `realm-settings-group-${uuid()}`; const realmName = `sessions-realm-user-profile-${uuid()}`; + const userProfilePermissions = { + view: ["admin", "user"], + edit: ["admin", "user"], + }; + + const addMultiselectCheckboxAttribute = async ( + attributeName: string, + optionValues: string[], + multivalued = true, + ) => { + await adminClient.addUserProfile(realmName, { + attributes: [ + { + name: attributeName, + displayName: attributeName, + permissions: userProfilePermissions, + multivalued, + annotations: { inputType: "multiselect-checkboxes" }, + validations: { options: { options: optionValues } }, + }, + ], + }); + }; test.beforeAll(async () => { await adminClient.createRealm(realmName); @@ -295,4 +323,78 @@ test.describe.serial("User profile tabs", () => { await expect(page.getByRole("heading", { name: group })).toBeVisible(); }); + + test("Persists multivalued switch state when editing a configured attribute", async ({ + page, + }) => { + const suffix = uuid().slice(0, 8); + const attributeName = `multivalued-switch-${suffix}`; + + await addMultiselectCheckboxAttribute(attributeName, [ + `option-a-${suffix}`, + `option-b-${suffix}`, + ]); + await goToRealmSettings(page); + await goToUserProfileTab(page); + await goToAttributesTab(page); + await assertRowExists(page, attributeName, true); + + await clickTableRowItem(page, attributeName); + await expect(page.locator("#multivalued")).toBeChecked(); + + await switchOff(page, "#multivalued"); + await clickSaveAttribute(page); + await assertNotificationMessage( + page, + "Success! User Profile configuration has been saved.", + ); + + await clickTableRowItem(page, attributeName); + await expect(page.locator("#multivalued")).not.toBeChecked(); + }); + + test("Uses inputType precedence over multivalued switch for multiselect-checkboxes rendering", async ({ + page, + }) => { + const suffix = uuid().slice(0, 8); + const attributeName = `multivalued-render-${suffix}`; + const optionOne = `option-one-${suffix}`; + const optionTwo = `option-two-${suffix}`; + + await addMultiselectCheckboxAttribute(attributeName, [ + optionOne, + optionTwo, + ]); + await goToRealmSettings(page); + await goToUserProfileTab(page); + await goToAttributesTab(page); + await assertRowExists(page, attributeName, true); + + await goToUsers(page); + await page.getByTestId("no-users-found-empty-action").click(); + await expect(page.getByTestId(optionOne)).toBeVisible(); + await expect(page.getByTestId(optionTwo)).toBeVisible(); + await expect(page.getByTestId(`attributes.${attributeName}0`)).toHaveCount( + 0, + ); + + await goToRealmSettings(page); + await goToUserProfileTab(page); + await goToAttributesTab(page); + await clickTableRowItem(page, attributeName); + await switchOff(page, "#multivalued"); + await clickSaveAttribute(page); + await assertNotificationMessage( + page, + "Success! User Profile configuration has been saved.", + ); + + await goToUsers(page); + await page.getByTestId("no-users-found-empty-action").click(); + await expect(page.getByTestId(optionOne)).toBeVisible(); + await expect(page.getByTestId(optionTwo)).toBeVisible(); + await expect(page.getByTestId(`attributes.${attributeName}0`)).toHaveCount( + 0, + ); + }); }); diff --git a/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx b/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx index 4554ef5d318..e03c3a80307 100644 --- a/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx +++ b/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx @@ -187,12 +187,20 @@ const FormField = ({ fieldName(attribute.name) as FieldPath, ); const inputType = useMemo(() => determineInputType(attribute), [attribute]); - - const Component = - attribute.multivalued || - (isMultiValue(value) && attribute.annotations?.inputType === undefined) - ? FIELDS["multi-input"] - : FIELDS[inputType]; + const hasDedicatedInputComponent = + inputType === "textarea" || + inputType === "select" || + inputType === "multiselect" || + inputType === "select-radiobuttons" || + inputType === "multiselect-checkboxes"; + const shouldRenderMultiInput = + !hasDedicatedInputComponent && + (attribute.multivalued || + (isMultiValue(value) && attribute.annotations?.inputType === undefined)); + + const Component = shouldRenderMultiInput + ? FIELDS["multi-input"] + : FIELDS[inputType]; if (attribute.name === "locale") return ( diff --git a/themes/src/main/resources/theme/base/login/user-profile-commons.ftl b/themes/src/main/resources/theme/base/login/user-profile-commons.ftl index 0d1a261a271..3547a8bf571 100644 --- a/themes/src/main/resources/theme/base/login/user-profile-commons.ftl +++ b/themes/src/main/resources/theme/base/login/user-profile-commons.ftl @@ -77,7 +77,8 @@ <@inputTagSelects attribute=attribute/> <#break> <#default> - <#if attribute.multivalued && attribute.values?has_content> + <#assign inferredMultivalued = !attribute.annotations.inputType?? && (attribute.values?size > 1)> + <#if (attribute.multivalued || inferredMultivalued) && attribute.values?has_content> <#list attribute.values as value> <@inputTag attribute=attribute value=value!''/> From 1c4b5d3d28b6fa20dcc72dfb94145ff9165be546 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Thu, 3 Dec 2026 16:20:48 +0100 Subject: [PATCH 2/3] Address Copilot review for multivalued user profile controls Resolve options from inputOptionsFromValidation, normalize multiselect string defaults to arrays, keep multi-input for multivalued textareas, and infer kcMultivalued for FreeMarker when multiple values are present. Signed-off-by: Erik Jan de Wit --- .../user-profile/OptionsComponent.test.tsx | 82 ++++++++++ .../src/user-profile/OptionsComponent.tsx | 81 +++++----- .../src/user-profile/SelectComponent.test.tsx | 77 ++++++--- .../src/user-profile/SelectComponent.tsx | 148 +++++++++--------- .../src/user-profile/UserProfileFields.tsx | 11 +- js/libs/ui-shared/src/user-profile/utils.ts | 36 +++++ .../model/AbstractUserProfileBean.java | 12 +- 7 files changed, 318 insertions(+), 129 deletions(-) create mode 100644 js/libs/ui-shared/src/user-profile/OptionsComponent.test.tsx diff --git a/js/libs/ui-shared/src/user-profile/OptionsComponent.test.tsx b/js/libs/ui-shared/src/user-profile/OptionsComponent.test.tsx new file mode 100644 index 00000000000..1b7e0c69937 --- /dev/null +++ b/js/libs/ui-shared/src/user-profile/OptionsComponent.test.tsx @@ -0,0 +1,82 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { TFunction } from "i18next"; +import { FormProvider, useForm, useWatch } from "react-hook-form"; +import { afterEach, describe, expect, it } from "vitest"; +import { OptionComponent } from "./OptionsComponent"; +import { asStringArray, UserFormFields } from "./utils"; + +const t = ((key: string) => key) as TFunction; + +const Value = () => ( + + {JSON.stringify(useWatch({ name: "attributes.roles" }))} + +); + +const Harness = ({ + value, + defaultValue, +}: { + value?: string | string[]; + defaultValue?: string; +}) => { + const form = useForm({ + defaultValues: { + attributes: { + roles: value !== undefined ? value : asStringArray(defaultValue), + }, + }, + }); + + return ( + + + + + ); +}; + +const formValue = () => screen.getByTestId("value").textContent; + +describe("OptionComponent multiselect-checkboxes", () => { + afterEach(cleanup); + + it("normalizes a string default and supports select/deselect", () => { + render(); + + expect(formValue()).toBe('["admin"]'); + expect((screen.getByTestId("admin") as HTMLInputElement).checked).toBe( + true, + ); + + fireEvent.click(screen.getByTestId("user")); + expect(formValue()).toBe('["admin","user"]'); + + fireEvent.click(screen.getByTestId("admin")); + expect(formValue()).toBe('["user"]'); + }); + + it("does not split a string value into characters when selecting another option", () => { + render(); + + fireEvent.click(screen.getByTestId("user")); + expect(formValue()).toBe('["admin","user"]'); + }); +}); diff --git a/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx b/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx index 29b472babd4..d6d32a26025 100644 --- a/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx @@ -1,20 +1,21 @@ import { Checkbox, Radio } from "@patternfly/react-core"; import { Controller } from "react-hook-form"; -import { - OptionLabel, - Options, - UserProfileFieldProps, -} from "./UserProfileFields"; +import { OptionLabel, UserProfileFieldProps } from "./UserProfileFields"; import { UserProfileGroup } from "./UserProfileGroup"; -import { fieldName, isRequiredAttribute, label } from "./utils"; +import { + asStringArray, + fieldName, + getAttributeOptions, + isRequiredAttribute, + label, +} from "./utils"; export const OptionComponent = (props: UserProfileFieldProps) => { const { form, inputType, attribute } = props; const isRequired = isRequiredAttribute(attribute); const isMultiSelect = inputType.startsWith("multiselect"); const Component = isMultiSelect ? Checkbox : Radio; - const options = - (attribute.validators?.options as Options | undefined)?.options || []; + const options = getAttributeOptions(attribute); const optionLabel = (attribute.annotations?.["inputOptionLabels"] as OptionLabel) || {}; @@ -27,36 +28,44 @@ export const OptionComponent = (props: UserProfileFieldProps) => { ( - <> - {options.map((option) => ( - { - if (isMultiSelect) { - if (field.value?.includes(option)) { - field.onChange( - field.value?.filter((item: string) => item !== option), - ); + defaultValue={ + isMultiSelect + ? asStringArray(attribute.defaultValue) + : attribute.defaultValue + } + render={({ field }) => { + const selectedValues = asStringArray(field.value); + + return ( + <> + {options.map((option) => ( + { + if (isMultiSelect) { + if (selectedValues.includes(option)) { + field.onChange( + selectedValues.filter((item) => item !== option), + ); + } else { + field.onChange([...selectedValues, option]); + } } else { - field.onChange([...(field.value || []), option]); + field.onChange([option]); } - } else { - field.onChange([option]); - } - }} - readOnly={attribute.readOnly} - isRequired={isRequired} - /> - ))} - - )} + }} + readOnly={attribute.readOnly} + isRequired={isRequired} + /> + ))} + + ); + }} /> ); diff --git a/js/libs/ui-shared/src/user-profile/SelectComponent.test.tsx b/js/libs/ui-shared/src/user-profile/SelectComponent.test.tsx index 29732232477..2a131c3fd52 100644 --- a/js/libs/ui-shared/src/user-profile/SelectComponent.test.tsx +++ b/js/libs/ui-shared/src/user-profile/SelectComponent.test.tsx @@ -9,19 +9,40 @@ 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"; +import { asStringArray, UserFormFields } from "./utils"; const t = ((key: string) => key) as TFunction; -const Value = () => ( +const Value = ({ name = "attributes.l2" }: { name?: string }) => ( - {JSON.stringify(useWatch({ name: "attributes.l2" }))} + {JSON.stringify(useWatch({ name: name as "attributes.l2" }))} ); -const Harness = ({ value = ["ops"] }: { value?: string[] }) => { +const Harness = ({ + value, + defaultValue, + validators = { + options: { options: ["ops", "foo"] }, + }, + annotations = { + inputType: "multiselect", + inputOptionLabels: { + ops: "OPS56", + foo: "FOO", + }, + }, +}: { + value?: string | string[]; + defaultValue?: string; + validators?: Record; + annotations?: Record; +}) => { const form = useForm({ - defaultValues: { attributes: { l2: value } }, + defaultValues: + value === undefined + ? { attributes: { l2: asStringArray(defaultValue) } } + : { attributes: { l2: value } }, }); return ( @@ -35,16 +56,9 @@ const Harness = ({ value = ["ops"] }: { value?: string[] }) => { displayName: "L2", required: false, readOnly: false, - validators: { - options: { options: ["ops", "foo"] }, - }, - annotations: { - inputType: "multiselect", - inputOptionLabels: { - ops: "OPS56", - foo: "FOO", - }, - }, + defaultValue, + validators, + annotations, }} /> @@ -65,14 +79,14 @@ describe("SelectComponent multiselect chips", () => { afterEach(cleanup); it("shows the option label on the chip", () => { - render(); + render(); expect(within(chipGroup() as HTMLElement).getByText("OPS56")).toBeTruthy(); expect(formValue()).toBe('["ops"]'); }); it("removes the selected option key when the chip is cleared", () => { - render(); + render(); removeChip(); @@ -81,11 +95,38 @@ describe("SelectComponent multiselect chips", () => { }); it("does not add the label string when clearing a labeled chip", () => { - render(); + render(); removeChip(); expect(formValue()).not.toContain("OPS56"); expect(formValue()).toBe("[]"); }); + + it("normalizes a string default so deselect keeps an array", () => { + render(); + + expect(formValue()).toBe('["ops"]'); + removeChip(); + expect(formValue()).toBe("[]"); + }); + + it("resolves options from inputOptionsFromValidation", () => { + render( + , + ); + + fireEvent.click(screen.getByRole("button")); + expect(screen.getByText("alpha")).toBeTruthy(); + expect(screen.getByText("beta")).toBeTruthy(); + }); }); diff --git a/js/libs/ui-shared/src/user-profile/SelectComponent.tsx b/js/libs/ui-shared/src/user-profile/SelectComponent.tsx index ee505595b49..8f455003222 100644 --- a/js/libs/ui-shared/src/user-profile/SelectComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/SelectComponent.tsx @@ -2,13 +2,15 @@ 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"; -import { - OptionLabel, - Options, - UserProfileFieldProps, -} from "./UserProfileFields"; +import { OptionLabel, UserProfileFieldProps } from "./UserProfileFields"; import { UserProfileGroup } from "./UserProfileGroup"; -import { UserFormFields, fieldName, label } from "./utils"; +import { + UserFormFields, + asStringArray, + fieldName, + getAttributeOptions, + label, +} from "./utils"; export const SelectComponent = (props: UserProfileFieldProps) => { const { t, form, inputType, attribute } = props; @@ -21,22 +23,18 @@ export const SelectComponent = (props: UserProfileFieldProps) => { field: ControllerRenderProps, ) => { if (isMultiValue) { - if (field.value?.includes(value)) { - field.onChange(field.value.filter((item: string) => item !== value)); + const current = asStringArray(field.value); + if (current.includes(value)) { + field.onChange(current.filter((item) => item !== value)); } else { - if (Array.isArray(field.value)) { - field.onChange([...field.value, value]); - } else { - field.onChange([value]); - } + field.onChange([...current, value]); } } else { field.onChange(value === field.value ? "" : value); } }; - const options = - (attribute.validators?.options as Options | undefined)?.options || []; + const options = getAttributeOptions(attribute); const optionLabel = (attribute.annotations?.["inputOptionLabels"] as OptionLabel) || {}; @@ -70,63 +68,73 @@ export const SelectComponent = (props: UserProfileFieldProps) => { ( - setOpen(b)} - onClear={() => field.onChange(isMultiValue ? [] : "")} - onSelect={(value) => { - const option = value.toString(); - setValue(option, field); - if (!Array.isArray(field.value)) { - setOpen(false); + render={({ field }) => { + const selectedValues = isMultiValue + ? asStringArray(field.value) + : field.value; + + return ( + setOpen(b)} + onClear={() => field.onChange(isMultiValue ? [] : "")} + onSelect={(value) => { + const option = value.toString(); + setValue(option, field); + if (!isMultiValue) { + setOpen(false); + } + }} + selections={ + isMultiValue + ? selectedValues + : fetchLabel(field.value as string) + } + // 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 ? ( + + {selectedValues.map((option: string) => ( + { + event.stopPropagation(); + setValue(option, field); + }} + > + {fetchLabel(option)} + + ))} + + ) : undefined + } + variant={ + isMultiValue + ? SelectVariant.typeaheadMulti + : options.length >= 10 + ? SelectVariant.typeahead + : SelectVariant.single } - }} - selections={ - isMultiValue && Array.isArray(field.value) - ? 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) ? ( - - {field.value.map((option: string) => ( - { - event.stopPropagation(); - setValue(option, field); - }} - > - {fetchLabel(option)} - - ))} - - ) : undefined - } - variant={ - isMultiValue - ? SelectVariant.typeaheadMulti - : options.length >= 10 - ? SelectVariant.typeahead - : SelectVariant.single - } - aria-label={t("selectOne")} - isOpen={open} - isDisabled={attribute.readOnly} - onFilter={(value) => { - setFilter(value); - return convertOptions(field.value); - }} - > - {convertOptions(field.value)} - - )} + aria-label={t("selectOne")} + isOpen={open} + isDisabled={attribute.readOnly} + onFilter={(value) => { + setFilter(value); + return convertOptions(selectedValues); + }} + > + {convertOptions(selectedValues)} + + ); + }} /> ); diff --git a/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx b/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx index e03c3a80307..d2f03c4c090 100644 --- a/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx +++ b/js/libs/ui-shared/src/user-profile/UserProfileFields.tsx @@ -187,16 +187,19 @@ const FormField = ({ fieldName(attribute.name) as FieldPath, ); const inputType = useMemo(() => determineInputType(attribute), [attribute]); - const hasDedicatedInputComponent = - inputType === "textarea" || + // Select-like controls can represent multiple values themselves. Textarea cannot + // preserve individual multivalued entries, so keep the multi-input renderer there. + const isSelectLikeInput = inputType === "select" || inputType === "multiselect" || inputType === "select-radiobuttons" || inputType === "multiselect-checkboxes"; const shouldRenderMultiInput = - !hasDedicatedInputComponent && + !isSelectLikeInput && (attribute.multivalued || - (isMultiValue(value) && attribute.annotations?.inputType === undefined)); + (isMultiValue(value) && + (attribute.annotations?.inputType === undefined || + inputType === "textarea"))); const Component = shouldRenderMultiInput ? FIELDS["multi-input"] diff --git a/js/libs/ui-shared/src/user-profile/utils.ts b/js/libs/ui-shared/src/user-profile/utils.ts index 058dd23e85b..203ecc88fee 100644 --- a/js/libs/ui-shared/src/user-profile/utils.ts +++ b/js/libs/ui-shared/src/user-profile/utils.ts @@ -100,6 +100,42 @@ export function isRequiredAttribute({ return required as boolean; } +type AttributeOptions = { options?: string[] }; + +/** + * Resolves selectable options the same way FreeMarker does: prefer + * `inputOptionsFromValidation`, then fall back to the standard `options` validator. + */ +export function getAttributeOptions( + attribute: UserProfileAttributeMetadata, +): string[] { + const fromValidation = attribute.annotations?.inputOptionsFromValidation; + if (typeof fromValidation === "string") { + const custom = attribute.validators?.[fromValidation] as + | AttributeOptions + | undefined; + if (Array.isArray(custom?.options)) { + return custom.options; + } + } + + const standard = attribute.validators?.options as + | AttributeOptions + | undefined; + return Array.isArray(standard?.options) ? standard.options : []; +} + +/** Normalizes multiselect field values/defaults so change handlers always see an array. */ +export function asStringArray(value: unknown): string[] { + if (Array.isArray(value)) { + return value.filter((item): item is string => typeof item === "string"); + } + if (typeof value === "string" && value.length > 0) { + return [value]; + } + return []; +} + export function isUserProfileError(error: unknown): error is UserProfileError { // Check if the error is an object with a 'responseData' property. if ( diff --git a/services/src/main/java/org/keycloak/forms/login/freemarker/model/AbstractUserProfileBean.java b/services/src/main/java/org/keycloak/forms/login/freemarker/model/AbstractUserProfileBean.java index bb141db353b..cb73ed1c905 100644 --- a/services/src/main/java/org/keycloak/forms/login/freemarker/model/AbstractUserProfileBean.java +++ b/services/src/main/java/org/keycloak/forms/login/freemarker/model/AbstractUserProfileBean.java @@ -209,13 +209,23 @@ public Map getHtml5DataAnnotations() { Map annotations = Stream.concat(getAnnotations().entrySet().stream(), groupAnnotations.entrySet().stream()) .filter((entry) -> entry.getKey().startsWith("kc")).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); - if (isMultivalued()) { + // Mirror React: when inputType is unset and multiple values are present, treat the + // attribute as multivalued so kcMultivalued.js can offer add/remove controls. + if (isMultivalued() || isInferredMultivalued()) { annotations = new HashMap<>(annotations); annotations.put("kcMultivalued", ""); } return annotations; } + + private boolean isInferredMultivalued() { + if (getAnnotations().get("inputType") != null) { + return false; + } + List values = getValues(); + return values != null && values.size() > 1; + } /** * Get info about validators applied to attribute. From 443b058fbad182d98be0a06cf1028b77f9b7f6a8 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Thu, 3 Dec 2026 16:43:36 +0100 Subject: [PATCH 3/3] Address remaining Copilot review for multivalued controls Namespace option IDs, keep radios single-select, render textarea multi-inputs with rows/cols, and skip inferred kcMultivalued for read-only attributes. Signed-off-by: Erik Jan de Wit --- .../src/user-profile/MultiInputComponent.tsx | 39 +++++++++--- .../user-profile/OptionsComponent.test.tsx | 61 ++++++++++++++++--- .../src/user-profile/OptionsComponent.tsx | 11 +++- .../model/AbstractUserProfileBean.java | 4 +- 4 files changed, 94 insertions(+), 21 deletions(-) diff --git a/js/libs/ui-shared/src/user-profile/MultiInputComponent.tsx b/js/libs/ui-shared/src/user-profile/MultiInputComponent.tsx index ecb3571080f..c52904f5969 100644 --- a/js/libs/ui-shared/src/user-profile/MultiInputComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/MultiInputComponent.tsx @@ -12,6 +12,7 @@ import { type TFunction } from "i18next"; import { Fragment, useEffect, useMemo } from "react"; import { FieldPath, UseFormReturn, useWatch } from "react-hook-form"; +import { KeycloakTextArea } from "../controls/keycloak-text-area/KeycloakTextArea"; import { InputType, UserProfileFieldProps } from "./UserProfileFields"; import { UserProfileGroup } from "./UserProfileGroup"; import { UserFormFields, fieldName, labelAttribute } from "./utils"; @@ -34,6 +35,8 @@ export const MultiInputComponent = ({ fieldLabel: labelAttribute(t, attribute), })} isDisabled={attribute.readOnly} + cols={attribute.annotations?.["inputTypeCols"] as number | undefined} + rows={attribute.annotations?.["inputTypeRows"] as number | undefined} {...rest} /> @@ -47,6 +50,8 @@ export type MultiLineInputProps = Omit & { isDisabled?: boolean; defaultValue?: string[]; inputType: InputType; + cols?: number; + rows?: number; }; const MultiLineInput = ({ @@ -58,6 +63,8 @@ const MultiLineInput = ({ isDisabled = false, defaultValue, id, + cols, + rows, ...rest }: MultiLineInputProps) => { const { register, setValue, control } = form; @@ -95,6 +102,7 @@ const MultiLineInput = ({ const type = inputType.startsWith("html") ? (inputType.substring("html".length + 2) as TextInputTypes) : "text"; + const useTextArea = inputType === "textarea"; useEffect(() => { register(name); @@ -106,15 +114,28 @@ const MultiLineInput = ({ - updateValue(index, value)} - name={`${name}.${index}.value`} - value={value} - isDisabled={isDisabled} - type={type} - {...rest} - /> + {useTextArea ? ( + updateValue(index, value)} + name={`${name}.${index}.value`} + value={value} + isDisabled={isDisabled} + cols={cols} + rows={rows} + aria-label={rest["aria-label"]} + /> + ) : ( + updateValue(index, value)} + name={`${name}.${index}.value`} + value={value} + isDisabled={isDisabled} + type={type} + {...rest} + /> + )}