import {
UserProfileAttributeGroupMetadata,
UserProfileAttributeMetadata,
UserProfileMetadata,
} from "@keycloak/keycloak-admin-client/lib/defs/userProfileMetadata";
import { TFunction } from "i18next";
import { ReactNode, useMemo, type JSX } from "react";
import { FieldPath, UseFormReturn } from "react-hook-form";
import { ScrollForm } from "../scroll-form/ScrollForm";
import { LocaleSelector } from "./LocaleSelector";
import { MultiInputComponent } from "./MultiInputComponent";
import { OptionComponent } from "./OptionsComponent";
import { SelectComponent } from "./SelectComponent";
import { TextAreaComponent } from "./TextAreaComponent";
import { TextComponent } from "./TextComponent";
import { UserFormFields, fieldName, isRootAttribute, label } from "./utils";
export type UserProfileError = {
responseData: { errors?: { errorMessage: string }[] };
};
export type Options = {
options?: string[];
};
export type InputType =
| "text"
| "textarea"
| "select"
| "select-radiobuttons"
| "multiselect"
| "multiselect-checkboxes"
| "html5-email"
| "html5-tel"
| "html5-url"
| "html5-number"
| "html5-range"
| "html5-datetime-local"
| "html5-date"
| "html5-month"
| "html5-time"
| "multi-input";
export type UserProfileFieldProps = {
t: TFunction;
form: UseFormReturn<UserFormFields>;
inputType: InputType;
attribute: UserProfileAttributeMetadata;
renderer?: (attribute: UserProfileAttributeMetadata) => ReactNode;
};
export type OptionLabel = Record<string, string> | undefined;
export const FIELDS: {
[type in InputType]: (props: UserProfileFieldProps) => JSX.Element;
} = {
text: TextComponent,
textarea: TextAreaComponent,
select: SelectComponent,
"select-radiobuttons": OptionComponent,
multiselect: SelectComponent,
"multiselect-checkboxes": OptionComponent,
"html5-email": TextComponent,
"html5-tel": TextComponent,
"html5-url": TextComponent,
"html5-number": TextComponent,
"html5-range": TextComponent,
"html5-datetime-local": TextComponent,
"html5-date": TextComponent,
"html5-month": TextComponent,
"html5-time": TextComponent,
"multi-input": MultiInputComponent,
} as const;
export type UserProfileFieldsProps = {
t: TFunction;
form: UseFormReturn<UserFormFields>;
userProfileMetadata: UserProfileMetadata;
supportedLocales: string[];
currentLocale: string;
hideReadOnly?: boolean;
renderer?: (
attribute: UserProfileAttributeMetadata,
) => JSX.Element | undefined;
};
type GroupWithAttributes = {
group: UserProfileAttributeGroupMetadata;
attributes: UserProfileAttributeMetadata[];
};
export const UserProfileFields = ({
t,
form,
userProfileMetadata,
supportedLocales,
currentLocale,
hideReadOnly = false,
renderer,
}: UserProfileFieldsProps) => {
const groupsWithAttributes = useMemo(() => {
if (!userProfileMetadata.attributes) {
return [];
}
const attributes = hideReadOnly
? userProfileMetadata.attributes.filter(({ readOnly }) => !readOnly)
: userProfileMetadata.attributes;
return [
{ name: undefined },
...(userProfileMetadata.groups ?? []),
].map<GroupWithAttributes>((group) => ({
group,
attributes: attributes.filter(
(attribute) => attribute.group === group.name,
),
}));
}, [
hideReadOnly,
userProfileMetadata.groups,
userProfileMetadata.attributes,
]);
if (groupsWithAttributes.length === 0) {
return null;
}
return (
<ScrollForm
label={t("jumpToSection")}
sections={groupsWithAttributes
.filter((group) => group.attributes.length > 0)
.map(({ group, attributes }) => ({
title: label(t, group.displayHeader, group.name) || t("general"),
panel: (
<div className="space-y-4"> {}
{group.displayDescription && (
<p className="pb-6 text-gray-700"> {}
{label(t, group.displayDescription, "")}
</p>
)}
{attributes.map((attribute) => (
<FormField
key={attribute.name}
t={t}
form={form}
supportedLocales={supportedLocales}
currentLocale={currentLocale}
renderer={renderer}
attribute={attribute}
/>
))}
</div>
),
}))}
/>
);
};
type FormFieldProps = {
t: TFunction;
form: UseFormReturn<UserFormFields>;
supportedLocales: string[];
currentLocale: string;
attribute: UserProfileAttributeMetadata;
renderer?: (
attribute: UserProfileAttributeMetadata,
) => JSX.Element | undefined;
};
const FormField = ({
t,
form,
renderer,
supportedLocales,
currentLocale,
attribute,
}: FormFieldProps) => {
const value = form.watch(
fieldName(attribute.name) as FieldPath<UserFormFields>,
);
const inputType = useMemo(() => determineInputType(attribute), [attribute]);
const Component =
attribute.multivalued ||
(isMultiValue(value) && attribute.annotations?.inputType === undefined)
? FIELDS["multi-input"]
: FIELDS[inputType];
if (attribute.name === "locale")
return (
<LocaleSelector
form={form}
supportedLocales={supportedLocales}
currentLocale={currentLocale}
t={t}
attribute={attribute}
/>
);
return (
<Component
t={t}
form={form}
inputType={inputType}
attribute={attribute}
renderer={renderer}
/>
);
};
const DEFAULT_INPUT_TYPE = "text" satisfies InputType;
function determineInputType(
attribute: UserProfileAttributeMetadata,
): InputType {
if (isRootAttribute(attribute.name)) {
return "text";
}
const inputType = attribute.annotations?.inputType;
if (isValidInputType(inputType)) {
return inputType;
}
return DEFAULT_INPUT_TYPE;
}
const isValidInputType = (value: unknown): value is InputType =>
typeof value === "string" && value in FIELDS;
const isMultiValue = (value: unknown): boolean =>
Array.isArray(value) && value.length > 1;
###
### src/keycloak-theme/shared/keycloak-ui-shared/user-profile/utils.ts
import { UserProfileAttributeMetadata } from "@keycloak/keycloak-admin-client/lib/defs/userProfileMetadata";
import UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation";
import { TFunction } from "i18next";
import { FieldPath } from "react-hook-form";
export type KeyValueType = { key: string; value: string };
export type UserFormFields = Omit<
UserRepresentation,
"attributes" | "userProfileMetadata"
> & {
attributes?: KeyValueType[] | Record<string, string | string[]>;
};
type FieldError = {
field: string;
errorMessage: string;
params?: string[];
};
type ErrorArray = { errors?: FieldError[] };
export type UserProfileError = {
responseData: ErrorArray | FieldError;
};
const isBundleKey = (displayName?: string) => displayName?.includes("${");
const unWrap = (key: string) => key.substring(2, key.length - 1);
export const label = (
t: TFunction,
text: string | undefined,
fallback?: string,
prefix?: string,
) => {
const value = text || fallback;
const bundleKey = isBundleKey(value) ? unWrap(value!) : value;
const key = prefix ? `${prefix}.${bundleKey}` : bundleKey;
return t(key || "");
};
export const labelAttribute = (
t: TFunction,
attribute: UserProfileAttributeMetadata,
) => label(t, attribute.displayName, attribute.name);
const ROOT_ATTRIBUTES = ["username", "firstName", "lastName", "email"];
export const isRootAttribute = (attr?: string) =>
attr && ROOT_ATTRIBUTES.includes(attr);
export const fieldName = (name?: string) =>
`${isRootAttribute(name) ? "" : "attributes."}${name?.replaceAll(
".",
"🍺",
)}` as FieldPath<UserFormFields>;
export const beerify = <T extends string>(name: T) =>
name.replaceAll(".", "🍺");
export const debeerify = <T extends string>(name: T) =>
name.replaceAll("🍺", ".");
export function setUserProfileServerError<T>(
error: UserProfileError,
setError: (field: keyof T, params: object) => void,
t: TFunction,
) {
(
((error.responseData as ErrorArray).errors !== undefined
? (error.responseData as ErrorArray).errors
: [error.responseData]) as FieldError[]
).forEach((e) => {
const params = Object.assign(
{},
e.params?.map((p) => (isBundleKey(p.toString()) ? t(unWrap(p)) : p)),
);
setError(fieldName(e.field) as keyof T, {
message: t(
isBundleKey(e.errorMessage) ? unWrap(e.errorMessage) : e.errorMessage,
{
...params,
defaultValue: e.errorMessage || e.field,
},
),
type: "server",
});
});
}
export function isRequiredAttribute({
required,
validators,
}: UserProfileAttributeMetadata): boolean {
return required || hasRequiredValidators(validators);
}
function hasRequiredValidators(
validators?: UserProfileAttributeMetadata["validators"],
): boolean {
if (!validators) {
return false;
}
if (
"length" in validators &&
"min" in validators.length &&
typeof validators.length.min === "number"
) {
return validators.length.min > 0;
}
return false;
}
export function isUserProfileError(error: unknown): error is UserProfileError {
if (
typeof error !== "object" ||
error === null ||
!("responseData" in error)
) {
return false;
}
const { responseData } = error;
if (isFieldError(responseData)) {
return true;
}
if (
typeof responseData !== "object" ||
responseData === null ||
!("errors" in responseData) ||
!Array.isArray(responseData.errors)
) {
return false;
}
return responseData.errors.every(isFieldError);
}
function isFieldError(error: unknown): error is FieldError {
if (typeof error !== "object" || error === null) {
return false;
}
if (!("field" in error) || typeof error.field !== "string") {
return false;
}
if (!("errorMessage" in error) || typeof error.errorMessage !== "string") {
return false;
}
return true;
}