import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { Button, Modal, ModalVariant } from "@patternfly/react-core"; import { useTranslation } from "react-i18next"; import { useForm } from "react-hook-form"; import { useAdminClient } from "../context/auth/AdminClient"; import RoleRepresentation from "keycloak-admin/lib/defs/roleRepresentation"; import { KeycloakDataTable } from "../components/table-toolbar/KeycloakDataTable"; import { ListEmptyState } from "../components/list-empty-state/ListEmptyState"; import { boolFormatter } from "../util"; export type AssociatedRolesModalProps = { open: boolean; toggleDialog: () => void; onConfirm: (newReps: RoleRepresentation[]) => void; existingCompositeRoles: RoleRepresentation[]; }; const attributesToArray = (attributes: { [key: string]: string }): any => { if (!attributes || Object.keys(attributes).length == 0) { return [ { key: "", value: "", }, ]; } return Object.keys(attributes).map((key) => ({ key: key, value: attributes[key], })); }; export const AssociatedRolesModal = (props: AssociatedRolesModalProps) => { const { t } = useTranslation("roles"); const form = useForm({ mode: "onChange" }); const [name, setName] = useState(""); const adminClient = useAdminClient(); const [selectedRows, setSelectedRows] = useState([]); const { id } = useParams<{ id: string }>(); const loader = async () => { const allRoles = await adminClient.roles.find(); const existingAdditionalRoles = await adminClient.roles.getCompositeRoles({ id, }); return allRoles.filter((role: RoleRepresentation) => { return ( existingAdditionalRoles.find( (existing: RoleRepresentation) => existing.name === role.name ) === undefined && role.name !== name ); }); }; useEffect(() => { (async () => { if (id) { const fetchedRole = await adminClient.roles.findOneById({ id }); setName(fetchedRole.name!); setupForm(fetchedRole); } else { setName(t("createRole")); } })(); }, []); const setupForm = (role: RoleRepresentation) => { Object.entries(role).map((entry) => { if (entry[0] === "attributes") { form.setValue(entry[0], attributesToArray(entry[1])); } else { form.setValue(entry[0], entry[1]); } }); }; return ( { props.toggleDialog(); props.onConfirm(selectedRows); }} > {t("common:add")} , , ]} > { setSelectedRows([...rows]); }} columns={[ { name: "name", displayKey: "roles:roleName", }, { name: "composite", displayKey: "roles:composite", cellFormatters: [boolFormatter()], }, { name: "description", displayKey: "roles:description", }, ]} emptyState={ } /> ); };