'use client' import { cn } from '../../lib/cn' import { Checkbox } from '../Checkbox' import { Surface } from '../Surface' import { Text } from '../Text' import { VisuallyHidden } from '../VisuallyHidden' import { LockIcon } from '../internal/icons' export interface PermissionRole { id: string name: string description?: string /** A built-in role whose permissions cannot be edited — Owner, usually. */ locked?: boolean } export interface PermissionGroup { title: string permissions: { id: string; label: string; description?: string }[] } export interface RolePermissionsProps { roles: PermissionRole[] groups: PermissionGroup[] /** role id → the permission ids it holds. */ value: Record /** Omit for a read-only matrix. */ onChange?: (value: Record) => void /** Caption for the table. */ label: string className?: string } /** * Which role can do what, as a grid of checkboxes. * * Every checkbox is named for its intersection — "Admin: Delete projects" — since * a column of unlabelled boxes gives a screen reader nothing but "checkbox, * checked" forty times. Locked roles are shown, not hidden: seeing that Owner * can do everything is how people understand what the other roles cannot. * * The permission column stays pinned while the roles scroll, which is what * makes a six-role matrix usable on a laptop. */ export function RolePermissions({ roles, groups, value, onChange, label, className }: RolePermissionsProps) { const total = groups.reduce((sum, group) => sum + group.permissions.length, 0) const toggle = (roleId: string, permissionId: string, granted: boolean) => { if (!onChange) return const current = new Set(value[roleId] ?? []) if (granted) current.add(permissionId) else current.delete(permissionId) onChange({ ...value, [roleId]: [...current] }) } return ( ))} {groups.map((group) => ( {group.permissions.map((permission) => ( {roles.map((role) => { const granted = (value[role.id] ?? []).includes(permission.id) return ( ) })} ))} ))}
{label}
{roles.map((role) => ( {role.locked && } {role.name} {(value[role.id] ?? []).length}/{total} {role.locked && , cannot be edited}
{group.title}
{permission.label} {permission.description && ( {permission.description} )} toggle(role.id, permission.id, event.target.checked)} aria-label={`${role.name}: ${permission.label}`} />
) }