Combine tree view and list for groups (#3401)

This commit is contained in:
Erik Jan de Wit 2022-10-10 17:03:27 +02:00 committed by GitHub
parent daf8d6c3f0
commit 11d8461620
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 295 additions and 376 deletions

View file

@ -117,6 +117,7 @@ describe("Group test", () => {
.searchGroup(groupNames[0], true) .searchGroup(groupNames[0], true)
.deleteGroupItem(groupNames[0]) .deleteGroupItem(groupNames[0])
.assertNotificationGroupDeleted() .assertNotificationGroupDeleted()
.searchGroup(groupNames[0], true)
.assertNoSearchResultsMessageExist(true); .assertNoSearchResultsMessageExist(true);
}); });
@ -199,8 +200,8 @@ describe("Group test", () => {
it("Navigate to sub-group details", () => { it("Navigate to sub-group details", () => {
searchGroupPage searchGroupPage
.searchGroup(predefinedGroups[1]) .searchGlobal(predefinedGroups[1])
.goToGroupChildGroupsTab(predefinedGroups[1]) .goToGroupChildGroupsFromTree(predefinedGroups[1])
.assertGroupItemExist(predefinedGroups[2], true); .assertGroupItemExist(predefinedGroups[2], true);
}); });
}); });
@ -462,12 +463,12 @@ describe("Group test", () => {
it("Assign roles from empty state", () => { it("Assign roles from empty state", () => {
roleMappingTab.assignRole(); roleMappingTab.assignRole();
groupDetailPage.createRoleMappingSearch(); groupDetailPage.createRoleMapping();
roleMappingTab.assign(); roleMappingTab.assign();
}); });
it("Show and search roles", () => { it("Show and search roles", () => {
groupDetailPage.checkRoles(); groupDetailPage.checkDefaultRole();
}); });
it("Check hide inherited roles option", () => { it("Check hide inherited roles option", () => {
@ -476,7 +477,7 @@ describe("Group test", () => {
}); });
it("Remove roles", () => { it("Remove roles", () => {
roleMappingTab.selectRow("offline_access"); roleMappingTab.selectRow("default-roles");
roleMappingTab.unAssign(); roleMappingTab.unAssign();
groupDetailPage.deleteRole(); groupDetailPage.deleteRole();
}); });

View file

@ -15,7 +15,7 @@ export default class GroupPage extends PageObject {
protected createGroupEmptyStateBtn = "no-groups-in-this-realm-empty-action"; protected createGroupEmptyStateBtn = "no-groups-in-this-realm-empty-action";
private createGroupBtn = "openCreateGroupModal"; private createGroupBtn = "openCreateGroupModal";
protected actionDrpDwnButton = "action-dropdown"; protected actionDrpDwnButton = "action-dropdown";
private actionDrpDwnItemSearchGroup = "searchGroup"; private searchField = "[data-testid='group-search']";
public openCreateGroupModal(emptyState: boolean) { public openCreateGroupModal(emptyState: boolean) {
if (emptyState) { if (emptyState) {
@ -36,11 +36,32 @@ export default class GroupPage extends PageObject {
return this; return this;
} }
public searchGroup(groupName: string, wait: boolean = false) { public searchGroup(searchValue: string, wait: boolean = false) {
listingPage.searchItem(groupName, wait); this.search(this.searchField, searchValue, wait);
return this; return this;
} }
protected search(searchField: string, searchValue: string, wait: boolean) {
if (wait) {
const searchUrl = `/admin/realms/master/*${searchValue}*`;
cy.intercept(searchUrl).as("search");
}
cy.get(searchField + " input").clear();
if (searchValue) {
cy.get(searchField + " input").type(searchValue);
cy.get(searchField + " button[type='submit']").click({ force: true });
} else {
// TODO: Remove else and move clickSearchButton outside of the if
cy.get(searchField).type("{enter}");
}
if (wait) {
cy.wait(["@search"]);
}
}
public goToGroupChildGroupsTab(groupName: string) { public goToGroupChildGroupsTab(groupName: string) {
listingPage.goToItemDetails(groupName); listingPage.goToItemDetails(groupName);
cy.intercept("GET", "*/admin/realms/master/groups/*").as("get"); cy.intercept("GET", "*/admin/realms/master/groups/*").as("get");

View file

@ -1,8 +1,10 @@
import SidebarPage from "../../SidebarPage";
import GroupPage from "./GroupPage"; import GroupPage from "./GroupPage";
export class SearchGroupPage extends GroupPage { export class SearchGroupPage extends GroupPage {
private searchField = "group-search"; private groupSearchField = "group-search";
private searchButton = "[data-testid='group-search'] > button"; private searchButton = "[data-testid='group-search'] > button";
private sidebarPage = new SidebarPage();
public searchGroup(groupName: string) { public searchGroup(groupName: string) {
this.typeSearchInput(groupName); this.typeSearchInput(groupName);
@ -10,8 +12,20 @@ export class SearchGroupPage extends GroupPage {
return this; return this;
} }
public searchGlobal(searchValue: string) {
this.search("[data-testid='searchForGroups']", searchValue, true);
return this;
}
public goToGroupChildGroupsFromTree(item: string) {
cy.get(".pf-c-tree-view__content").contains(item).click();
this.sidebarPage.waitForPageLoad();
return this;
}
public typeSearchInput(value: string) { public typeSearchInput(value: string) {
cy.findByTestId(this.searchField).type(value); cy.findByTestId(this.groupSearchField).type(value);
return this; return this;
} }

View file

@ -154,15 +154,19 @@ export default class GroupDetailPage extends GroupPage {
listingPage.clickItemCheckbox("default-roles-"); listingPage.clickItemCheckbox("default-roles-");
} }
checkDefaultRole() {
listingPage.itemExist("default-roles");
}
createRoleMappingSearch() { createRoleMappingSearch() {
listingPage.searchItemInModal("offline_access"); listingPage.searchItemInModal("offline_access");
listingPage.clickItemCheckbox("offline_access"); listingPage.clickItemCheckbox("offline_access");
} }
checkRoles() { checkRoles(roleName: string | undefined = "offline_access") {
listingPage.itemExist("offline_access"); listingPage.itemExist(roleName);
listingPage.searchItem("offline_access", false); listingPage.searchItem(roleName, false);
listingPage.itemExist("offline_access"); listingPage.itemExist(roleName);
listingPage.searchItem("non-existant-role", false); listingPage.searchItem("non-existant-role", false);
groupPage.assertNoSearchResultsMessageExist(true); groupPage.assertNoSearchResultsMessageExist(true);
} }

View file

@ -9,6 +9,7 @@
"global": "Global", "global": "Global",
"local": "Local", "local": "Local",
"searchGroups": "Search groups", "searchGroups": "Search groups",
"filterGroups": "Filter groups",
"searchGroup": "Search group", "searchGroup": "Search group",
"renameGroup": "Rename group", "renameGroup": "Rename group",
"deleteGroup": "Delete group", "deleteGroup": "Delete group",

View file

@ -10,7 +10,6 @@ import { Breadcrumb, BreadcrumbItem } from "@patternfly/react-core";
import { useRealm } from "../../context/realm-context/RealmContext"; import { useRealm } from "../../context/realm-context/RealmContext";
import { routes } from "../../route-config"; import { routes } from "../../route-config";
import { GroupBreadCrumbs } from "./GroupBreadCrumbs";
export const PageBreadCrumbs = () => { export const PageBreadCrumbs = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@ -30,19 +29,17 @@ export const PageBreadCrumbs = () => {
}), }),
elementText elementText
); );
return ( return crumbs.length > 1 ? (
<> <Breadcrumb>
{crumbs.length > 1 && ( {crumbs.map(({ match, breadcrumb: crumb }, i) => (
<Breadcrumb> <BreadcrumbItem key={i} isActive={crumbs.length - 1 === i}>
{crumbs.map(({ match, breadcrumb: crumb }, i) => ( {crumbs.length - 1 !== i ? (
<BreadcrumbItem key={i} isActive={crumbs.length - 1 === i}> <Link to={match.url}>{crumb}</Link>
{crumbs.length - 1 !== i && <Link to={match.url}>{crumb}</Link>} ) : (
{crumbs.length - 1 === i && crumb} crumb
</BreadcrumbItem> )}
))} </BreadcrumbItem>
</Breadcrumb> ))}
)} </Breadcrumb>
<GroupBreadCrumbs /> ) : null;
</>
);
}; };

View file

@ -108,9 +108,8 @@ export const GroupPickerDialog = ({
].some((group) => group === row?.name); ].some((group) => group === row?.name);
}; };
const hasSubgroups = (group: GroupRepresentation) => { const hasSubgroups = (group: GroupRepresentation) =>
return group.subGroups!.length !== 0; group.subGroups?.length !== 0;
};
const findSubGroup = ( const findSubGroup = (
group: GroupRepresentation, group: GroupRepresentation,

View file

@ -54,7 +54,7 @@ export const TableToolbar: FunctionComponent<TableToolbarProps> = ({
<ToolbarContent> <ToolbarContent>
{inputGroupName && ( {inputGroupName && (
<ToolbarItem> <ToolbarItem>
<InputGroup> <InputGroup data-testid={inputGroupName}>
{searchTypeComponent} {searchTypeComponent}
{inputGroupPlaceholder && ( {inputGroupPlaceholder && (
<SearchInput <SearchInput

View file

@ -3,11 +3,11 @@ import KeycloakAdminClient from "@keycloak/keycloak-admin-client";
import { getAuthorizationHeaders } from "../../utils/getAuthorizationHeaders"; import { getAuthorizationHeaders } from "../../utils/getAuthorizationHeaders";
import { joinPath } from "../../utils/joinPath"; import { joinPath } from "../../utils/joinPath";
export async function fetchAdminUI( export async function fetchAdminUI<T>(
adminClient: KeycloakAdminClient, adminClient: KeycloakAdminClient,
endpoint: string, endpoint: string,
query?: Record<string, string> query?: Record<string, string>
) { ): Promise<T> {
const accessToken = await adminClient.getAccessToken(); const accessToken = await adminClient.getAccessToken();
const baseUrl = adminClient.baseUrl; const baseUrl = adminClient.baseUrl;

View file

@ -2,13 +2,7 @@ import { useState } from "react";
import { Link } from "react-router-dom-v5-compat"; import { Link } from "react-router-dom-v5-compat";
import { useLocation, useNavigate } from "react-router-dom-v5-compat"; import { useLocation, useNavigate } from "react-router-dom-v5-compat";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { SearchInput, ToolbarItem } from "@patternfly/react-core";
Radio,
SearchInput,
Split,
SplitItem,
ToolbarItem,
} from "@patternfly/react-core";
import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation"; import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation";
import { useAdminClient } from "../context/auth/AdminClient"; import { useAdminClient } from "../context/auth/AdminClient";
@ -23,33 +17,14 @@ import { toGroups } from "./routes/Groups";
import { useAccess } from "../context/access/Access"; import { useAccess } from "../context/access/Access";
import useToggle from "../utils/useToggle"; import useToggle from "../utils/useToggle";
import { DeleteGroup } from "./components/DeleteGroup"; import { DeleteGroup } from "./components/DeleteGroup";
import { GroupToolbar, ViewType } from "./components/GroupToolbar"; import { GroupToolbar } from "./components/GroupToolbar";
import { MoveDialog } from "./components/MoveDialog"; import { MoveDialog } from "./components/MoveDialog";
import { GroupPath } from "../components/group/GroupPath";
type GroupTableProps = { type GroupTableProps = {
toggleView?: (viewType: ViewType) => void; refresh: () => void;
}; };
type SearchType = "global" | "local"; export const GroupTable = ({ refresh: viewRefresh }: GroupTableProps) => {
type SearchGroup = GroupRepresentation & {
link?: string;
};
const flatten = (groups: GroupRepresentation[], id?: string): SearchGroup[] => {
let result: SearchGroup[] = [];
for (const group of groups) {
const link = `${id || ""}${id ? "/" : ""}${group.id}`;
result.push({ ...group, link });
if (group.subGroups) {
result = [...result, ...flatten(group.subGroups, link)];
}
}
return result;
};
export const GroupTable = ({ toggleView }: GroupTableProps) => {
const { t } = useTranslation("groups"); const { t } = useTranslation("groups");
const { adminClient } = useAdminClient(); const { adminClient } = useAdminClient();
@ -68,9 +43,6 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const id = getLastId(location.pathname); const id = getLastId(location.pathname);
const [searchType, setSearchType] = useState<SearchType>(
id ? "local" : "global"
);
const { hasAccess } = useAccess(); const { hasAccess } = useAccess();
const isManager = hasAccess("manage-users") || currentGroup()?.access?.manage; const isManager = hasAccess("manage-users") || currentGroup()?.access?.manage;
@ -78,19 +50,12 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
hasAccess("query-groups", "view-users") || hasAccess("query-groups", "view-users") ||
hasAccess("manage-users", "query-groups"); hasAccess("manage-users", "query-groups");
const loader = async ( const loader = async (first?: number, max?: number) => {
first?: number,
max?: number
): Promise<SearchGroup[]> => {
const params: Record<string, string> = { const params: Record<string, string> = {
search: search || "", search: search || "",
first: first?.toString() || "", first: first?.toString() || "",
max: max?.toString() || "", max: max?.toString() || "",
}; };
if (searchType === "global" && search) {
const result = await fetchAdminUI(adminClient, "admin-ui-groups", params);
return flatten(result);
}
let groupsData = undefined; let groupsData = undefined;
if (id) { if (id) {
@ -103,10 +68,14 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
? group.subGroups ? group.subGroups
: group.subGroups?.filter((g) => g.name?.includes(search)); : group.subGroups?.filter((g) => g.name?.includes(search));
} else { } else {
groupsData = await fetchAdminUI(adminClient, "admin-ui-groups", { groupsData = await fetchAdminUI<GroupRepresentation[]>(
...params, adminClient,
global: "false", "admin-ui-groups",
}); {
...params,
global: "false",
}
);
} }
if (!groupsData) { if (!groupsData) {
@ -123,12 +92,7 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
<Link <Link
key={group.id} key={group.id}
to={`${location.pathname}/${group.id}`} to={`${location.pathname}/${group.id}`}
onClick={async () => { onClick={() => setSubGroups([...subGroups, group])}
const loadedGroup = await adminClient.groups.findOne({
id: group.id!,
});
setSubGroups([...subGroups, loadedGroup!]);
}}
> >
{group.name} {group.name}
</Link> </Link>
@ -139,9 +103,6 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
setIsCreateModalOpen(!isCreateModalOpen); setIsCreateModalOpen(!isCreateModalOpen);
}; };
const Path = (group: SearchGroup) =>
group.link ? <GroupPath group={group} /> : undefined;
return ( return (
<> <>
<DeleteGroup <DeleteGroup
@ -150,6 +111,7 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
selectedRows={selectedRows} selectedRows={selectedRows}
refresh={() => { refresh={() => {
refresh(); refresh();
viewRefresh();
setSelectedRows([]); setSelectedRows([]);
}} }}
/> />
@ -166,7 +128,7 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
<ToolbarItem> <ToolbarItem>
<SearchInput <SearchInput
data-testid="group-search" data-testid="group-search"
placeholder={t("searchForGroups")} placeholder={t("filterGroups")}
value={search} value={search}
onChange={setSearch} onChange={setSearch}
onSearch={refresh} onSearch={refresh}
@ -177,48 +139,12 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
/> />
</ToolbarItem> </ToolbarItem>
<GroupToolbar <GroupToolbar
currentView={ViewType.Table}
toggleView={toggleView}
toggleCreate={handleModalToggle} toggleCreate={handleModalToggle}
toggleDelete={toggleShowDelete} toggleDelete={toggleShowDelete}
kebabDisabled={selectedRows!.length === 0} kebabDisabled={selectedRows!.length === 0}
/> />
</> </>
} }
subToolbar={
!!search &&
!id && (
<ToolbarItem>
<Split hasGutter>
<SplitItem>{t("searchFor")}</SplitItem>
<SplitItem>
<Radio
id="global"
isChecked={searchType === "global"}
onChange={() => {
setSearchType("global");
refresh();
}}
name="searchType"
label={t("global")}
/>
</SplitItem>
<SplitItem>
<Radio
id="local"
isChecked={searchType === "local"}
onChange={() => {
setSearchType("local");
refresh();
}}
name="searchType"
label={t("local")}
/>
</SplitItem>
</Split>
</ToolbarItem>
)
}
actions={ actions={
!isManager !isManager
? [] ? []
@ -246,11 +172,6 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
displayKey: "groups:groupName", displayKey: "groups:groupName",
cellRenderer: GroupNameCell, cellRenderer: GroupNameCell,
}, },
{
name: "path",
displayKey: "groups:path",
cellRenderer: Path,
},
]} ]}
emptyState={ emptyState={
<ListEmptyState <ListEmptyState
@ -268,7 +189,10 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
<GroupsModal <GroupsModal
id={id} id={id}
handleModalToggle={handleModalToggle} handleModalToggle={handleModalToggle}
refresh={refresh} refresh={() => {
refresh();
viewRefresh();
}}
/> />
)} )}
{move && ( {move && (
@ -277,6 +201,7 @@ export const GroupTable = ({ toggleView }: GroupTableProps) => {
refresh={() => { refresh={() => {
setMove(undefined); setMove(undefined);
refresh(); refresh();
viewRefresh();
}} }}
onClose={() => setMove(undefined)} onClose={() => setMove(undefined)}
/> />

View file

@ -8,6 +8,11 @@ import {
Tab, Tab,
TabTitleText, TabTitleText,
Tabs, Tabs,
Drawer,
DrawerContent,
DrawerContentBody,
DrawerPanelContent,
DrawerHead,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation"; import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation";
@ -27,9 +32,9 @@ import helpUrls from "../help-urls";
import { PermissionsTab } from "../components/permission-tab/PermissionTab"; import { PermissionsTab } from "../components/permission-tab/PermissionTab";
import { useAccess } from "../context/access/Access"; import { useAccess } from "../context/access/Access";
import { GroupTree } from "./components/GroupTree"; import { GroupTree } from "./components/GroupTree";
import { ViewType } from "./components/GroupToolbar";
import { DeleteGroup } from "./components/DeleteGroup"; import { DeleteGroup } from "./components/DeleteGroup";
import useToggle from "../utils/useToggle"; import useToggle from "../utils/useToggle";
import { GroupBreadCrumbs } from "../components/bread-crumb/GroupBreadCrumbs";
import "./GroupsSection.css"; import "./GroupsSection.css";
@ -42,13 +47,15 @@ export default function GroupsSection() {
const { realm } = useRealm(); const { realm } = useRealm();
const [rename, setRename] = useState<string>(); const [rename, setRename] = useState<string>();
const [viewType, setViewType] = useState<ViewType>(ViewType.Table);
const [deleteOpen, toggleDeleteOpen] = useToggle(); const [deleteOpen, toggleDeleteOpen] = useToggle();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const id = getLastId(location.pathname); const id = getLastId(location.pathname);
const [key, setKey] = useState(0);
const refresh = () => setKey(key + 1);
const { hasAccess } = useAccess(); const { hasAccess } = useAccess();
const canViewPermissions = hasAccess( const canViewPermissions = hasAccess(
"manage-authorization", "manage-authorization",
@ -93,108 +100,129 @@ export default function GroupsSection() {
show={deleteOpen} show={deleteOpen}
toggleDialog={toggleDeleteOpen} toggleDialog={toggleDeleteOpen}
selectedRows={[currentGroup()!]} selectedRows={[currentGroup()!]}
refresh={() => navigate(toGroups({ realm }))} refresh={() => {
navigate(toGroups({ realm }));
refresh();
}}
/> />
{rename && ( {rename && (
<GroupsModal <GroupsModal
id={id} id={id}
rename={rename} rename={rename}
refresh={(group) => refresh={(group) => {
setSubGroups([...subGroups.slice(0, subGroups.length - 1), group!]) refresh();
} setSubGroups([...subGroups.slice(0, subGroups.length - 1), group!]);
}}
handleModalToggle={() => setRename(undefined)} handleModalToggle={() => setRename(undefined)}
/> />
)} )}
<ViewHeader
titleKey={!id ? "groups:groups" : currentGroup()?.name!}
subKey={!id ? "groups:groupsDescription" : ""}
helpUrl={!id ? helpUrls.groupsUrl : ""}
divider={!id}
dropdownItems={
id && canManageGroup
? [
<DropdownItem
data-testid="renameGroupAction"
key="renameGroup"
onClick={() => setRename(currentGroup()?.name)}
>
{t("renameGroup")}
</DropdownItem>,
<DropdownItem
data-testid="deleteGroup"
key="deleteGroup"
onClick={toggleDeleteOpen}
>
{t("deleteGroup")}
</DropdownItem>,
]
: undefined
}
/>
<PageSection variant={PageSectionVariants.light} className="pf-u-p-0"> <PageSection variant={PageSectionVariants.light} className="pf-u-p-0">
{subGroups.length > 0 && ( <Drawer isInline isExpanded key={key}>
<Tabs <DrawerContent
inset={{ panelContent={
default: "insetNone", <DrawerPanelContent isResizable defaultSize="80%" minSize="500px">
md: "insetSm", <DrawerHead>
xl: "insetLg", <GroupBreadCrumbs />
"2xl": "inset2xl", <ViewHeader
}} titleKey={!id ? "groups:groups" : currentGroup()?.name!}
activeKey={activeTab} subKey={!id ? "groups:groupsDescription" : ""}
onSelect={(_, key) => setActiveTab(key as number)} helpUrl={!id ? helpUrls.groupsUrl : ""}
isBox divider={!id}
dropdownItems={
id && canManageGroup
? [
<DropdownItem
data-testid="renameGroupAction"
key="renameGroup"
onClick={() => setRename(currentGroup()?.name)}
>
{t("renameGroup")}
</DropdownItem>,
<DropdownItem
data-testid="deleteGroup"
key="deleteGroup"
onClick={toggleDeleteOpen}
>
{t("deleteGroup")}
</DropdownItem>,
]
: undefined
}
/>
{subGroups.length > 0 && (
<Tabs
inset={{
default: "insetNone",
md: "insetSm",
xl: "insetLg",
"2xl": "inset2xl",
}}
activeKey={activeTab}
onSelect={(_, key) => setActiveTab(key as number)}
isBox
>
<Tab
data-testid="groups"
eventKey={0}
title={<TabTitleText>{t("childGroups")}</TabTitleText>}
>
<GroupTable refresh={refresh} />
</Tab>
<Tab
data-testid="members"
eventKey={1}
title={<TabTitleText>{t("members")}</TabTitleText>}
>
<Members />
</Tab>
<Tab
data-testid="attributes"
eventKey={2}
title={
<TabTitleText>{t("common:attributes")}</TabTitleText>
}
>
<GroupAttributes />
</Tab>
{canManageRoles && (
<Tab
eventKey={3}
data-testid="role-mapping-tab"
title={
<TabTitleText>{t("roleMapping")}</TabTitleText>
}
>
<GroupRoleMapping
id={id!}
name={currentGroup()?.name!}
/>
</Tab>
)}
{canViewPermissions && (
<Tab
eventKey={4}
data-testid="permissionsTab"
title={
<TabTitleText>
{t("common:permissions")}
</TabTitleText>
}
>
<PermissionsTab id={id} type="groups" />
</Tab>
)}
</Tabs>
)}
{subGroups.length === 0 && <GroupTable refresh={refresh} />}
</DrawerHead>
</DrawerPanelContent>
}
> >
<Tab <DrawerContentBody>
data-testid="groups" <GroupTree refresh={refresh} />
eventKey={0} </DrawerContentBody>
title={<TabTitleText>{t("childGroups")}</TabTitleText>} </DrawerContent>
> </Drawer>
<GroupTable />
</Tab>
<Tab
data-testid="members"
eventKey={1}
title={<TabTitleText>{t("members")}</TabTitleText>}
>
<Members />
</Tab>
<Tab
data-testid="attributes"
eventKey={2}
title={<TabTitleText>{t("common:attributes")}</TabTitleText>}
>
<GroupAttributes />
</Tab>
{canManageRoles && (
<Tab
eventKey={3}
data-testid="role-mapping-tab"
title={<TabTitleText>{t("roleMapping")}</TabTitleText>}
>
<GroupRoleMapping id={id!} name={currentGroup()?.name!} />
</Tab>
)}
{canViewPermissions && (
<Tab
eventKey={4}
data-testid="permissionsTab"
title={<TabTitleText>{t("common:permissions")}</TabTitleText>}
>
<PermissionsTab id={id} type="groups" />
</Tab>
)}
</Tabs>
)}
{subGroups.length === 0 && (
<>
{viewType === ViewType.Table && (
<GroupTable toggleView={setViewType} />
)}
{viewType === ViewType.Tree && (
<GroupTree toggleView={setViewType} />
)}
</>
)}
</PageSection> </PageSection>
</> </>
); );

View file

@ -4,34 +4,22 @@ import {
Dropdown, Dropdown,
DropdownItem, DropdownItem,
KebabToggle, KebabToggle,
ToggleGroup,
ToggleGroupItem,
ToolbarItem, ToolbarItem,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import { TableIcon, DomainIcon } from "@patternfly/react-icons";
import { useSubGroups } from "../SubGroupsContext"; import { useSubGroups } from "../SubGroupsContext";
import { useAccess } from "../../context/access/Access"; import { useAccess } from "../../context/access/Access";
import useToggle from "../../utils/useToggle"; import useToggle from "../../utils/useToggle";
export enum ViewType {
Table,
Tree,
}
type GroupToolbarProps = { type GroupToolbarProps = {
toggleCreate: () => void; toggleCreate: () => void;
toggleDelete: () => void; toggleDelete: () => void;
currentView?: ViewType;
toggleView?: (type: ViewType) => void;
kebabDisabled: boolean; kebabDisabled: boolean;
}; };
export const GroupToolbar = ({ export const GroupToolbar = ({
toggleCreate, toggleCreate,
toggleDelete, toggleDelete,
currentView,
toggleView,
kebabDisabled, kebabDisabled,
}: GroupToolbarProps) => { }: GroupToolbarProps) => {
const { t } = useTranslation("groups"); const { t } = useTranslation("groups");
@ -45,26 +33,6 @@ export const GroupToolbar = ({
return ( return (
<> <>
{toggleView && (
<ToolbarItem>
<ToggleGroup>
<ToggleGroupItem
icon={<TableIcon />}
aria-label={t("tableView")}
buttonId="tableView"
isSelected={currentView === ViewType.Table}
onChange={() => toggleView(ViewType.Table)}
/>
<ToggleGroupItem
icon={<DomainIcon />}
aria-label={t("diagramView")}
buttonId="diagramView"
isSelected={currentView === ViewType.Tree}
onChange={() => toggleView(ViewType.Tree)}
/>
</ToggleGroup>
</ToolbarItem>
)}
<ToolbarItem> <ToolbarItem>
<Button <Button
data-testid="openCreateGroupModal" data-testid="openCreateGroupModal"

View file

@ -1,24 +1,27 @@
import { useState } from "react"; import { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom-v5-compat"; import { Link } from "react-router-dom-v5-compat";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
Dropdown, Dropdown,
DropdownItem, DropdownItem,
DropdownPosition, DropdownPosition,
KebabToggle, KebabToggle,
TreeView,
TreeViewDataItem, TreeViewDataItem,
} from "@patternfly/react-core"; } from "@patternfly/react-core";
import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation"; import type GroupRepresentation from "@keycloak/keycloak-admin-client/lib/defs/groupRepresentation";
import { useAdminClient, useFetch } from "../../context/auth/AdminClient"; import { useAdminClient, useFetch } from "../../context/auth/AdminClient";
import { KeycloakSpinner } from "../../components/keycloak-spinner/KeycloakSpinner"; import { KeycloakSpinner } from "../../components/keycloak-spinner/KeycloakSpinner";
import { TableToolbar } from "../../components/table-toolbar/TableToolbar";
import useToggle from "../../utils/useToggle"; import useToggle from "../../utils/useToggle";
import { CheckableTreeView } from "./CheckableTreeView";
import { DeleteGroup } from "./DeleteGroup"; import { DeleteGroup } from "./DeleteGroup";
import { GroupToolbar, ViewType } from "./GroupToolbar";
import { GroupsModal } from "../GroupsModal"; import { GroupsModal } from "../GroupsModal";
import { MoveDialog } from "./MoveDialog"; import { MoveDialog } from "./MoveDialog";
import { PaginatingTableToolbar } from "../../components/table-toolbar/PaginatingTableToolbar";
import { useSubGroups } from "../SubGroupsContext";
import { fetchAdminUI } from "../../context/auth/admin-ui-endpoint";
import { useRealm } from "../../context/realm-context/RealmContext";
import { joinPath } from "../../utils/joinPath";
type GroupTreeContextMenuProps = { type GroupTreeContextMenuProps = {
group: GroupRepresentation; group: GroupRepresentation;
@ -31,9 +34,6 @@ const GroupTreeContextMenu = ({
}: GroupTreeContextMenuProps) => { }: GroupTreeContextMenuProps) => {
const { t } = useTranslation("groups"); const { t } = useTranslation("groups");
const location = useLocation();
const navigate = useNavigate();
const [isOpen, toggleOpen] = useToggle(); const [isOpen, toggleOpen] = useToggle();
const [createOpen, toggleCreateOpen] = useToggle(); const [createOpen, toggleCreateOpen] = useToggle();
const [moveOpen, toggleMoveOpen] = useToggle(); const [moveOpen, toggleMoveOpen] = useToggle();
@ -69,12 +69,6 @@ const GroupTreeContextMenu = ({
<DropdownItem key="move" onClick={toggleMoveOpen}> <DropdownItem key="move" onClick={toggleMoveOpen}>
{t("moveTo")} {t("moveTo")}
</DropdownItem>, </DropdownItem>,
<DropdownItem
key="edit"
onClick={() => navigate(`${location.pathname}/${group.id}`)}
>
{t("common:edit")}
</DropdownItem>,
<DropdownItem key="delete" onClick={toggleDeleteOpen}> <DropdownItem key="delete" onClick={toggleDeleteOpen}>
{t("common:delete")} {t("common:delete")}
</DropdownItem>, </DropdownItem>,
@ -84,124 +78,91 @@ const GroupTreeContextMenu = ({
); );
}; };
const mapGroup = (
group: GroupRepresentation,
refresh: () => void
): TreeViewDataItem => ({
id: group.id,
name: group.name,
checkProps: { checked: false },
children:
group.subGroups && group.subGroups.length > 0
? group.subGroups.map((g) => mapGroup(g, refresh))
: undefined,
action: <GroupTreeContextMenu group={group} refresh={refresh} />,
});
const filterGroup = (
group: TreeViewDataItem,
search: string
): TreeViewDataItem | null => {
const name = group.name as string;
if (name.toLowerCase().includes(search)) {
return { ...group, defaultExpanded: true, children: undefined };
}
const children: TreeViewDataItem[] = [];
if (group.children) {
for (const g of group.children) {
const found = filterGroup(g, search);
if (found) children.push(found);
}
if (children.length > 0) {
return { ...group, defaultExpanded: true, children };
}
}
return null;
};
const filterGroups = (
groups: TreeViewDataItem[],
search: string
): TreeViewDataItem[] => {
const result: TreeViewDataItem[] = [];
groups
.map((g) => filterGroup(g, search))
.forEach((g) => {
if (g !== null) result.push(g);
});
return result;
};
type GroupTreeProps = { type GroupTreeProps = {
toggleView?: (viewType: ViewType) => void; refresh: () => void;
}; };
export const GroupTree = ({ toggleView }: GroupTreeProps) => { export const GroupTree = ({ refresh: viewRefresh }: GroupTreeProps) => {
const { t } = useTranslation("groups"); const { t } = useTranslation("groups");
const { adminClient } = useAdminClient(); const { adminClient } = useAdminClient();
const { realm } = useRealm();
const [data, setData] = useState<TreeViewDataItem[]>(); const [data, setData] = useState<TreeViewDataItem[]>();
const [filteredData, setFilteredData] = useState<TreeViewDataItem[]>(); const { subGroups, setSubGroups } = useSubGroups();
const [selectedRows, setSelectedRows] = useState<GroupRepresentation[]>([]);
const [showDelete, toggleShowDelete] = useToggle(); const [search, setSearch] = useState("");
const [showCreate, toggleShowCreate] = useToggle(); const [max, setMax] = useState(20);
const [first, setFirst] = useState(0);
const [key, setKey] = useState(0); const [key, setKey] = useState(0);
const refresh = () => setKey(key + 1); const refresh = () => {
setKey(key + 1);
viewRefresh();
};
const mapGroup = (
group: GroupRepresentation,
parents: GroupRepresentation[],
refresh: () => void
): TreeViewDataItem => {
const groups = [...parents, group];
return {
id: group.id,
name: (
<Link
key={group.id}
to={`/${realm}/groups/${joinPath(...groups.map((g) => g.id!))}`}
onClick={() => setSubGroups(groups)}
>
{group.name}
</Link>
),
children:
group.subGroups && group.subGroups.length > 0
? group.subGroups.map((g) => mapGroup(g, groups, refresh))
: undefined,
action: <GroupTreeContextMenu group={group} refresh={refresh} />,
defaultExpanded: subGroups.map((g) => g.id).includes(group.id),
};
};
useFetch( useFetch(
() => () =>
adminClient.groups.find({ fetchAdminUI<GroupRepresentation[]>(
briefRepresentation: false, adminClient,
}), "admin-ui-groups",
(groups) => setData(groups.map((g) => mapGroup(g, refresh))), Object.assign(
[key] {
first: `${first}`,
max: `${max + 1}`,
},
search === "" ? null : { search }
)
),
(groups) => setData(groups.map((g) => mapGroup(g, [], refresh))),
[key, first, max, search]
); );
return ( return data ? (
<> <PaginatingTableToolbar
<DeleteGroup count={data.length || 0}
show={showDelete} first={first}
toggleDialog={toggleShowDelete} max={max}
selectedRows={selectedRows} onNextClick={setFirst}
refresh={refresh} onPreviousClick={setFirst}
/> onPerPageSelect={(first, max) => {
{showCreate && ( setFirst(first);
<GroupsModal handleModalToggle={toggleShowCreate} refresh={refresh} /> setMax(max);
}}
inputGroupName="searchForGroups"
inputGroupPlaceholder={t("groups:searchForGroups")}
inputGroupOnEnter={setSearch}
>
{data.length > 0 && (
<TreeView data={data} allExpanded={search.length > 0} />
)} )}
{data ? ( </PaginatingTableToolbar>
<> ) : (
<TableToolbar <KeycloakSpinner />
inputGroupName="searchForGroups"
inputGroupPlaceholder={t("groups:searchForGroups")}
inputGroupOnEnter={(search) => {
if (search === "") {
setFilteredData(undefined);
} else {
setFilteredData(filterGroups(data, search));
}
}}
toolbarItem={
<GroupToolbar
currentView={ViewType.Tree}
toggleView={toggleView}
toggleDelete={toggleShowDelete}
toggleCreate={toggleShowCreate}
kebabDisabled={selectedRows.length === 0}
/>
}
/>
<CheckableTreeView
data={filteredData || data}
onSelect={(items) =>
setSelectedRows(items.reverse() as GroupRepresentation[])
}
/>
</>
) : (
<KeycloakSpinner />
)}
</>
); );
}; };