import React, { useState, useContext, useEffect } from "react"; import { useHistory } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { Dropdown, DropdownToggle, DropdownItem, Button, Divider, SplitItem, Split, ContextSelector, ContextSelectorItem, } from "@patternfly/react-core"; import { CheckIcon } from "@patternfly/react-icons"; import { toUpperCase } from "../../util"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; import { useRealm } from "../../context/realm-context/RealmContext"; import { WhoAmIContext } from "../../context/whoami/WhoAmI"; import "./realm-selector.css"; type RealmSelectorProps = { realmList: RealmRepresentation[]; }; export const RealmSelector = ({ realmList }: RealmSelectorProps) => { const { realm, setRealm } = useRealm(); const { whoAmI } = useContext(WhoAmIContext); const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const [filteredItems, setFilteredItems] = useState(realmList); const history = useHistory(); const { t } = useTranslation("common"); const RealmText = ({ value }: { value: string }) => ( {toUpperCase(value)} {value === realm && } ); const AddRealm = ({ className }: { className?: string }) => ( ); const onFilter = () => { const filtered = search === "" ? realmList : realmList.filter( (r) => r.realm!.toLowerCase().indexOf(search.toLowerCase()) !== -1 ); setFilteredItems(filtered || []); }; useEffect(() => { onFilter(); }, [search]); const dropdownItems = realmList.map((r) => ( { setRealm(r.realm!); history.push(`/${r.realm}/`); setOpen(!open); }} > )); const addRealmComponent = ( {whoAmI.canCreateRealm() && ( <> )} ); return ( <> {realmList.length > 5 && ( setOpen(!open)} onSelect={(_, r) => { const value = ((r as unknown) as any).props.value; setRealm(value || "master"); setOpen(!open); }} searchInputValue={search} onSearchInputChange={(value) => setSearch(value)} onSearchButtonClick={() => onFilter()} className="keycloak__realm_selector__context_selector" > {filteredItems.map((item) => ( ))} )} {realmList.length <= 5 && ( setOpen(!open)} className="keycloak__realm_selector_dropdown__toggle" > {toUpperCase(realm)} } dropdownItems={[...dropdownItems, addRealmComponent]} /> )} ); };