UNPKG

@keycloakify/keycloak-admin-ui

Version:
54 lines 3.12 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { KeycloakSelect, SelectVariant, useFetch, } from "../../ui-shared"; import { SelectOption } from "@patternfly/react-core"; import { useRef, useState } from "react"; import { Controller, useFormContext } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { useAdminClient } from "../../admin-client"; export const ScopeSelect = ({ clientId, resourceId, preSelected, }) => { const { adminClient } = useAdminClient(); const { t } = useTranslation(); 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 = getValues("scopes"); const toSelectOptions = (scopes) => scopes.map((scope) => (_jsx(SelectOption, { value: scope, children: scope.name }, scope.id))); useFetch(async () => { 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) => values === null || values === void 0 ? void 0 : values.includes(s.id))); }, [resourceId, search]); return (_jsx(Controller, { name: "scopes", defaultValue: preSelected ? [preSelected] : [], control: control, rules: { validate: (value) => value.length > 0 }, render: ({ field }) => (_jsx(KeycloakSelect, { toggleId: "scopes", variant: SelectVariant.typeaheadMulti, onToggle: (val) => setOpen(val), onFilter: (filter) => { setSearch(filter); return toSelectOptions(scopes); }, onClear: () => { field.onChange([]); setSearch(""); }, selections: selectedScopes.map((s) => s.name), onSelect: (selectedValue) => { const option = typeof selectedValue === "string" ? selectedScopes.find((s) => s.name === selectedValue) : selectedValue; const changedValue = selectedScopes.find((p) => p.id === option.id) ? selectedScopes.filter((p) => p.id !== option.id) : [...selectedScopes, option]; field.onChange(changedValue.map((s) => s.id)); setSelectedScopes(changedValue); setSearch(""); }, isOpen: open, "aria-labelledby": t("scopes"), validated: errors.scopes ? "error" : "default", isDisabled: !!preSelected, typeAheadAriaLabel: t("scopes"), children: toSelectOptions(scopes) })) })); }; //# sourceMappingURL=ScopeSelect.js.map