Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/users/RolesPage.tsx
T

547 lines
24 KiB
TypeScript

// R-P2b — D-P2 "WF-P2 Admin RBAC" S02 "Rollen und Berechtigungen" in David's
// Subframe optics. Pure presentational: renders the server-built RolesListVM
// and reports mutations through injected actions (route owns the fetcher).
// S02 — merged roles tab: search + type/in-use filters, Typ/Mitglieder columns
// M04A — "Rolle anlegen" basics step → M02
// M04B — "Rolle duplizieren" basics step (copied permissions) → M02
// M02 — large permission editor (L 1200): section sidebar + search + switches
// D03 — "Rolle in Nutzung blockiert" delete blocker
// David's "Status" column has no data-model backing (no Role.status) and the
// "Bereich/Kategorie" select has no Role.category — both omitted, tracked as
// design-nachzug. Role duplication = create with the source's permission set
// preloaded into the editor (same audited createWorkspaceRole path).
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import * as SubframeCore from "@subframe/core";
import { FeatherCopy, FeatherEdit2, FeatherMoreHorizontal, FeatherPlus, FeatherShield, FeatherTrash, FeatherUserCheck } from "@subframe/core";
import type { RoleEditorInputPermission, RolesListRow, RolesListVM, RoleTypeKey } from "@hivegrid/view-models";
import { buildRoleEditorVM, filterRoleEditorSections, togglePermission, EMPTY_ROLES_FILTER, filterRolesRows, type RolesListFilterState } from "@hivegrid/view-models";
import { permissionDisplayDescription, permissionDisplayName, roleDisplayDescription, roleDisplayName } from "~/components/core/roles/roleDisplay";
import { FacetFilterBar, type ClientFacet } from "../shared/FacetFilterBar";
import { PageIntro } from "../shared/PageShell";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { Button } from "~/ui/components/Button";
import { FormDialog } from "../shared/FormDialog";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { SearchInput } from "~/ui/components/SearchInput";
import { Switch } from "~/ui/components/Switch";
import { Table } from "~/ui/components/Table";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
export type RoleMutationInput = { name: string; description: string; permissionNames: string[] };
export type RolesActions = {
/** POSTs the existing create contract (roles/new, action=create). */
onCreate: (input: RoleMutationInput) => void;
/** POSTs the existing update contract (roles/:id, action=edit). */
onUpdate: (roleId: string, input: RoleMutationInput) => void;
/** POSTs the existing delete contract (roles/:id, action=delete). */
onDelete: (roleId: string) => void;
};
export type RolesPageProps = {
vm: RolesListVM;
/** App permission catalog feeding the M02 editor sections. */
editorCatalog: readonly RoleEditorInputPermission[];
/** roleId → assigned permission names (editor prefill + M04B duplication). */
rolePermissionNames: Readonly<Record<string, readonly string[]>>;
/** Tab bar back to S01 (members). */
actions: RolesActions;
submitting: boolean;
errorMessage: string | null;
/** Increments after a successful mutation — closes any open dialog. */
closeSignal: number;
};
/** M04A/M04B basics step. */
type BasicsState = { source: RolesListRow | null; name: string; description: string };
/** M02 editor state. roleId null = create (after M04A/M04B). */
type EditorState = {
roleId: string | null;
duplicatedFromName: string | null;
name: string;
description: string;
enabled: ReadonlySet<string>;
};
export function RolesPage({ vm, editorCatalog, rolePermissionNames, actions, submitting, errorMessage, closeSignal }: RolesPageProps) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [filter, setFilter] = useState<RolesListFilterState>(EMPTY_ROLES_FILTER);
const [basics, setBasics] = useState<BasicsState | null>(null);
const [editor, setEditor] = useState<EditorState | null>(null);
const [deleteRow, setDeleteRow] = useState<RolesListRow | null>(null);
useEffect(() => {
if (closeSignal > 0) {
setBasics(null);
setEditor(null);
setDeleteRow(null);
}
}, [closeSignal]);
if (vm.status !== "ready" || !vm.data) {
return <div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles" />;
}
const data = vm.data;
const rows = filterRolesRows(data.rows, filter);
const facets: ClientFacet[] = [
{
key: "type",
label: t("settings.rolesAndPermissions.columns.type"),
icon: <FeatherShield />,
tone: "violet-subtle",
options: [
{ value: "system", label: t("settings.rolesAndPermissions.type.system") },
{ value: "custom", label: t("settings.rolesAndPermissions.type.custom") },
],
selected: new Set(filter.type ? [filter.type] : []),
},
{
key: "inUse",
label: t("settings.rolesAndPermissions.filters.inUse"),
icon: <FeatherUserCheck />,
tone: "blue-subtle",
options: [
{ value: "yes", label: t("settings.rolesAndPermissions.filters.inUseYes") },
{ value: "no", label: t("settings.rolesAndPermissions.filters.inUseNo") },
],
selected: new Set(filter.inUse === null ? [] : [filter.inUse ? "yes" : "no"]),
},
];
function toggleFacet(facetKey: string, value: string) {
if (facetKey === "type") {
return setFilter((prev) => ({ ...prev, type: prev.type === value ? null : (value as RoleTypeKey) }));
}
if (facetKey === "inUse") {
const next = value === "yes";
return setFilter((prev) => ({ ...prev, inUse: prev.inUse === next ? null : next }));
}
return undefined;
}
function openEditorFor(row: RolesListRow) {
setEditor({
roleId: row.id,
duplicatedFromName: null,
name: row.name,
description: row.description,
enabled: new Set(rolePermissionNames[row.id] ?? []),
});
}
function continueToPermissions(state: BasicsState) {
setBasics(null);
setEditor({
roleId: null,
duplicatedFromName: state.source ? state.source.name : null,
name: state.name,
description: state.description,
enabled: new Set(state.source ? (rolePermissionNames[state.source.id] ?? []) : []),
});
}
return (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.settings.rolesAndPermissions.roles">
{/* The page header (title + subtitle) is rendered by the route above the layout, like Mitglieder. */}
{/* AK-SET-01: the Team-Hub renders the tab bar this screen used to carry. */}
{/* Intro + create CTA on one row, exactly as the Mitglieder tab next door
hosts its own; the hub header above carries only title and subtitle. */}
<div className="mobile:flex-col mobile:items-start flex w-full items-start justify-between gap-4">
<PageIntro uiId="ui.settings.rolesAndPermissions.intro">{t("settings.rolesAndPermissions.subtitle")}</PageIntro>
{data.canCreate ? (
<Button
icon={<FeatherPlus />}
onClick={() => setBasics({ source: null, name: "", description: "" })}
data-ui-id="ui.settings.rolesAndPermissions.roles.new"
>
{t("settings.rolesAndPermissions.create")}
</Button>
) : null}
</div>
{/* --- Filter bar: the shared facet strip the sibling tabs and the board
lists wear - free-text box, facet buttons, chips for what is active
and one reset. Both facets are single-select, so picking the active
option again clears it, just as the chip's X does. --- */}
<FacetFilterBar
uiId="ui.settings.rolesAndPermissions.roles.filter"
facets={facets}
onToggle={toggleFacet}
search={filter.query}
onSearchChange={(value) => setFilter((prev) => ({ ...prev, query: value }))}
searchPlaceholder={t("settings.rolesAndPermissions.filters.searchPlaceholder")}
onReset={() => setFilter(EMPTY_ROLES_FILTER)}
labels={{
reset: t("settings.rolesAndPermissions.filters.reset"),
removeChip: t("settings.rolesAndPermissions.filters.removeChip"),
}}
/>
{data.rows.length === 0 ? (
<div data-ui-id="ui.settings.rolesAndPermissions.roles.empty">
<EmptyState title={t(data.emptyHeadlineKey)} body={t(data.emptyBodyKey)} />
</div>
) : (
<div className="w-full overflow-x-auto">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("models.role.object")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.role.description")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.rolesAndPermissions.columns.type")}</Table.HeaderCell>
<Table.HeaderCell>{t("settings.rolesAndPermissions.columns.members")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.permission.plural")}</Table.HeaderCell>
<Table.HeaderCell> </Table.HeaderCell>
</Table.HeaderRow>
}
>
{rows.map((row) => (
<Table.Row key={row.id} data-ui-id="ui.settings.rolesAndPermissions.roles.row">
<Table.Cell>
<span className="whitespace-nowrap text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{roleDisplayName({ name: row.name, description: row.description }, t)}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
{roleDisplayDescription({ name: row.name, description: row.description }, t) || "—"}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t(row.typeLabelKey)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{formatters.number(row.memberCount)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{t("models.permission.count", { count: row.permissionCount, formattedCount: formatters.number(row.permissionCount) })}
</span>
</Table.Cell>
<Table.Cell variant="align-right">
{row.canEdit || row.canDuplicate || row.canDelete ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton
variant="ghost"
size="small"
icon={<FeatherMoreHorizontal />}
aria-label={`${t("shared.actions")}: ${roleDisplayName({ name: row.name, description: row.description }, t)}`}
data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions"
/>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
{row.canEdit ? (
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />} onClick={() => openEditorFor(row)}>
{t("shared.edit")}
</DropdownMenu.DropdownItem>
) : null}
{row.canDuplicate ? (
<DropdownMenu.DropdownItem
icon={<FeatherCopy />}
onClick={() =>
setBasics({
source: row,
name: t("settings.rolesAndPermissions.duplicate.copyName", { name: row.name }),
description: row.description,
})
}
>
{t("settings.rolesAndPermissions.duplicate.action")}
</DropdownMenu.DropdownItem>
) : null}
{row.canDelete ? (
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setDeleteRow(row)}>
{t("shared.delete")}
</DropdownMenu.DropdownItem>
) : null}
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</Table.Cell>
</Table.Row>
))}
</Table>
{rows.length === 0 ? (
<div className="pt-4">
<EmptyState variant="no-results" title={t(data.noMatchesKey)} body={t(data.emptyBodyKey)} />
</div>
) : null}
</div>
)}
{/* M04A / M04B — basics step (S 560) */}
{basics ? (
<RoleBasicsDialog state={basics} onChange={setBasics} onContinue={continueToPermissions} onCancel={() => setBasics(null)} />
) : null}
{/* M02 — large permission editor (L 1200) */}
{editor ? (
<RoleEditorDialog
state={editor}
onChange={setEditor}
editorCatalog={editorCatalog}
submitting={submitting}
errorMessage={errorMessage}
onCancel={() => setEditor(null)}
onSave={() => {
const input = { name: editor.name, description: editor.description, permissionNames: [...editor.enabled] };
if (editor.roleId) actions.onUpdate(editor.roleId, input);
else actions.onCreate(input);
}}
/>
) : null}
{/* Delete confirm / D03 blocker (XS 420) */}
{deleteRow ? (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : setDeleteRow(null))}
size="xs"
uiId="ui.settings.rolesAndPermissions.roles.deleteConfirm"
title={deleteRow.deleteBlockedInUse ? t("settings.rolesAndPermissions.deleteBlocked.title") : t("settings.rolesAndPermissions.delete.title")}
footer={
<>
<Button className="mobile:w-full" variant="tertiary" onClick={() => setDeleteRow(null)}>
{deleteRow.deleteBlockedInUse ? t("shared.close") : t("shared.cancel")}
</Button>
{!deleteRow.deleteBlockedInUse ? (
<Button
className="mobile:w-full"
variant="destructive"
loading={submitting}
onClick={() => actions.onDelete(deleteRow.id)}
data-ui-id="ui.settings.rolesAndPermissions.roles.deleteSubmit"
>
{t("shared.delete")}
</Button>
) : null}
</>
}
>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{deleteRow.deleteBlockedInUse
? t("settings.rolesAndPermissions.deleteBlocked.description", { name: deleteRow.name, count: deleteRow.memberCount })
: t("settings.rolesAndPermissions.delete.description", { name: deleteRow.name })}
</span>
</FormDialog>
) : null}
</div>
);
}
function RoleBasicsDialog({
state,
onChange,
onContinue,
onCancel,
}: {
state: BasicsState;
onChange: (state: BasicsState) => void;
onContinue: (state: BasicsState) => void;
onCancel: () => void;
}) {
const { t } = useTranslation();
const isDuplicate = state.source !== null;
const nameMissing = state.name.trim().length === 0;
return (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : onCancel())}
uiId="ui.settings.rolesAndPermissions.roles.basics"
title={isDuplicate ? t("settings.rolesAndPermissions.duplicate.title") : t("settings.rolesAndPermissions.createDialog.title")}
subtitle={
isDuplicate
? t("settings.rolesAndPermissions.duplicate.hint", { name: state.source?.name ?? "" })
: t("settings.rolesAndPermissions.createDialog.description")
}
footer={
<>
<Button className="mobile:w-full" variant="tertiary" onClick={onCancel}>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
disabled={nameMissing}
onClick={() => onContinue(state)}
data-ui-id="ui.settings.rolesAndPermissions.roles.basics.continue"
>
{t("settings.rolesAndPermissions.editor.continue")}
</Button>
</>
}
>
<TextInput className="w-full max-w-full" label={t("models.role.name")} showLabel>
<TextInput.Input value={state.name} onChange={(event) => onChange({ ...state, name: event.target.value })} required autoFocus />
</TextInput>
<TextArea className="w-full max-w-full" label={t("models.role.description")} showLabel>
<TextArea.Input value={state.description} onChange={(event) => onChange({ ...state, description: event.target.value })} />
</TextArea>
</FormDialog>
);
}
function RoleEditorDialog({
state,
onChange,
editorCatalog,
submitting,
errorMessage,
onCancel,
onSave,
}: {
state: EditorState;
onChange: (state: EditorState) => void;
editorCatalog: readonly RoleEditorInputPermission[];
submitting: boolean;
errorMessage: string | null;
onCancel: () => void;
onSave: () => void;
}) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [selectedSection, setSelectedSection] = useState<string | null>(null);
// Pure VM grouping (scope → David's sections); enabled state comes from the dialog.
const sections = useMemo(() => {
const vm = buildRoleEditorVM({
role: state.roleId ? { id: state.roleId, name: state.name, description: state.description } : null,
duplicatedFromName: state.duplicatedFromName,
appPermissions: editorCatalog,
assignedPermissionNames: [...state.enabled],
});
return vm.data?.sections ?? [];
}, [state.roleId, state.name, state.description, state.duplicatedFromName, state.enabled, editorCatalog]);
const searched = useMemo(() => filterRoleEditorSections(sections, query), [sections, query]);
const visible = query.trim() ? searched : selectedSection ? searched.filter((section) => section.id === selectedSection) : searched;
const nameMissing = state.name.trim().length === 0;
return (
<FormDialog
open
onOpenChange={(open: boolean) => (open ? undefined : onCancel())}
size="large"
uiId="ui.settings.rolesAndPermissions.roles.editor"
title={state.roleId ? t("settings.rolesAndPermissions.editor.title") : t("settings.rolesAndPermissions.createDialog.title")}
subtitle={state.duplicatedFromName ? t("settings.rolesAndPermissions.duplicate.hint", { name: state.duplicatedFromName }) : undefined}
// The editor's permission column scrolls on its own, so the body must not
// add a second scroll container around it.
bodyClassName="max-h-none overflow-visible"
footer={
<>
<Button className="mobile:w-full" variant="tertiary" onClick={onCancel}>
{t("shared.cancel")}
</Button>
<Button
className="mobile:w-full"
loading={submitting}
disabled={nameMissing}
onClick={onSave}
data-ui-id="ui.settings.rolesAndPermissions.roles.editor.save"
>
{t("shared.save")}
</Button>
</>
}
>
{errorMessage ? <Alert variant="error" title={errorMessage} /> : null}
<div className="flex w-full gap-6 mobile:flex-col">
{/* Sidebar: search + sections (Apple-settings pattern from David's M02) */}
<div className="flex w-64 flex-none flex-col gap-4 mobile:w-full">
<SearchInput
placeholder={t("settings.rolesAndPermissions.editor.searchPlaceholder")}
hideShortcut
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<div className="flex flex-col gap-1">
<Button
variant={selectedSection === null ? "secondary" : "ghost"}
className="justify-start"
onClick={() => setSelectedSection(null)}
>
{t("settings.rolesAndPermissions.editor.allSections")}
</Button>
{sections.map((section) => (
<Button
key={section.id}
variant={selectedSection === section.id ? "secondary" : "ghost"}
className="justify-start"
onClick={() => setSelectedSection(section.id)}
>
{`${t(section.labelKey)} (${section.enabledCount}/${section.permissions.length})`}
</Button>
))}
</div>
</div>
{/* Main: role base data + permission rows as switches */}
<div className="flex max-h-[60vh] w-full flex-col gap-6 overflow-y-auto pr-2">
<div className="flex w-full flex-col gap-4">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
{t("settings.rolesAndPermissions.editor.roleSection")}
</span>
<TextInput className="w-full" label={t("models.role.name")} showLabel>
<TextInput.Input value={state.name} onChange={(event) => onChange({ ...state, name: event.target.value })} required />
</TextInput>
<TextArea className="w-full" label={t("models.role.description")} showLabel>
<TextArea.Input value={state.description} onChange={(event) => onChange({ ...state, description: event.target.value })} />
</TextArea>
</div>
{visible.length === 0 ? (
<EmptyState variant="no-results" title={t("settings.rolesAndPermissions.editor.noMatches")} />
) : (
visible.map((section) => (
<div key={section.id} className="flex w-full flex-col gap-4" data-editor-section={section.id}>
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t(section.labelKey)}</span>
<div className="flex w-full flex-col gap-4">
{section.permissions.map((permission) => (
<div key={permission.name} className="flex w-full items-start justify-between gap-4" data-editor-permission={permission.name}>
<div className="flex flex-col gap-0">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">
{permissionDisplayName({ name: permission.name, description: permission.description }, t)}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{permissionDisplayDescription({ name: permission.name, description: permission.description }, t) ?? permission.name}
</span>
</div>
<Switch
checked={state.enabled.has(permission.name)}
onCheckedChange={(checked: boolean) => onChange({ ...state, enabled: togglePermission(state.enabled, permission.name, checked) })}
/>
</div>
))}
</div>
</div>
))
)}
</div>
</div>
</FormDialog>
);
}