import {
Button,
ContextSelector,
ContextSelectorItem,
Divider,
Dropdown,
DropdownItem,
DropdownToggle,
Label,
Split,
SplitItem,
} from "@patternfly/react-core";
import { CheckIcon } from "@patternfly/react-icons";
import React, { ReactElement, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { useRealm } from "../../context/realm-context/RealmContext";
import { useRealms } from "../../context/RealmsContext";
import { useWhoAmI } from "../../context/whoami/WhoAmI";
import { toDashboard } from "../../dashboard/routes/Dashboard";
import { toAddRealm } from "../../realm/routes/AddRealm";
import { toUpperCase } from "../../util";
import { RecentUsed } from "./recent-used";
import "./realm-selector.css";
export const RealmSelector = () => {
const { realm } = useRealm();
const { realms } = useRealms();
const { whoAmI } = useWhoAmI();
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
const history = useHistory();
const { t } = useTranslation("common");
const recentUsed = new RecentUsed();
const all = recentUsed.used
.filter((r) => r !== realm)
.map((name) => {
return { name, used: true };
})
.concat(
realms
.filter((r) => !recentUsed.used.includes(r.realm!) || r.realm === realm)
.map((r) => {
return { name: r.realm!, used: false };
})
);
const filteredItems = useMemo(() => {
if (search === "") {
return undefined;
}
return all.filter((r) =>
r.name.toLowerCase().includes(search.toLowerCase())
);
}, [search, all]);
const RealmText = ({ value }: { value: string }) => (
{toUpperCase(value)}
{value === realm && }
);
const AddRealm = () => (
);
const selectRealm = (realm: string) => {
setOpen(!open);
history.push(toDashboard({ realm }));
};
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)}
className="keycloak__realm_selector__context_selector"
footer={
whoAmI.canCreateRealm() && (
)
}
>
{(filteredItems || all).map((item) => (
{" "}
{item.used && }
))}
)}
{realms.length <= 5 && (
setOpen(!open)}
className="keycloak__realm_selector_dropdown__toggle"
>
{toUpperCase(realm)}
}
dropdownItems={[...dropdownItems, addRealmComponent]}
/>
)}
>
);
};