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