import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Controller, useFormContext } from "react-hook-form-v7"; import { Select, SelectOption, SelectVariant } from "@patternfly/react-core"; import type ScopeRepresentation from "@keycloak/keycloak-admin-client/lib/defs/scopeRepresentation"; import { useAdminClient, useFetch } from "../../context/auth/AdminClient"; type ScopeSelectProps = { clientId: string; resourceId?: string; preSelected?: string; }; export const ScopeSelect = ({ clientId, resourceId, preSelected, }: ScopeSelectProps) => { const { t } = useTranslation("clients"); const { adminClient } = useAdminClient(); const { control, getValues, setValue, formState: { errors }, } = useFormContext(); const [scopes, setScopes] = useState([]); const [selectedScopes, setSelectedScopes] = useState( [] ); const [search, setSearch] = useState(""); const [open, setOpen] = useState(false); const firstUpdate = useRef(true); const values: string[] | undefined = getValues("scopes"); const toSelectOptions = (scopes: ScopeRepresentation[]) => scopes.map((scope) => ( {scope.name} )); useFetch( async (): Promise => { if (!resourceId) { return adminClient.clients.listAllScopes( Object.assign( { id: clientId, deep: false }, search === "" ? null : { name: search } ) ); } if (resourceId && !firstUpdate.current) { setValue("scopes", []); } firstUpdate.current = false; return adminClient.clients.listScopesByResource({ id: clientId, resourceName: resourceId, }); }, (scopes) => { setScopes(scopes); if (!search) setSelectedScopes( scopes.filter((s: ScopeRepresentation) => values?.includes(s.id!)) ); }, [resourceId, search] ); return ( value.length > 0 }} render={({ field }) => ( )} /> ); };