# Roles and permissions

Assign workspace roles and inspect direct or inherited permissions in matrix and compact list views.

Access: pro. Category: Blocks. Kind: composite.

## When to use

- Use it when a page needs assign workspace roles and inspect direct or inherited permissions in matrix and compact list views.
- Choose it inside an authenticated product surface when the host application owns routing, persistence, and service calls.

## Alternatives

- Choose empty-state instead when empty collections, search results and errors with a clear next action is the actual interface need, rather than roles and permissions.

## Setup for agents

Use React 19 and TypeScript. Initialize shadcn for your framework, then merge this exact entry into components.json:

```json
{
  "registries": {
    "@tidal-pro": {
      "url": "https://tidalui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${TIDALUI_TOKEN}"
      }
    }
  }
}
```

The namespace must be named **@tidal-pro** because transitive Pro dependencies use that namespace. Obtain an agent key from your active Pro account at https://tidalui.com/account. Keep TIDALUI_TOKEN in your local environment, never in components.json, client code, Git or logs.

```sh
export TIDALUI_TOKEN='your-private-agent-key'
npx shadcn@latest add @tidal-pro/waitlist-form
npx shadcn@latest add https://tidalui.com/r/tidal-button.json
```

Free command: `npx shadcn@latest add https://tidalui.com/r/<name>.json`.
Pro command: `npx shadcn@latest add @tidal-pro/<name>`.

Import the base stylesheet and every stylesheet listed on the installed item's metadata. For example:

```tsx
import "./components/ui/tidal.css";
import "./components/ui/hero-section.css";
// Place installed components inside this wrapper:
<div className="tidal-scope" data-theme="dark">...</div>
```

Omit data-theme for the default light theme. Put the attribute on the same tidal-scope element for dark mode. Every component installs the shared free tidal-base dependency. After upgrading, run `npx shadcn@latest add https://tidalui.com/r/tidal-base.json --overwrite` to receive current tokens. Review local modifications before overwriting.

Vite: Use React + TypeScript. Map @/* to ./src/* in paths and Vite resolve.alias. Import tidal.css and each component stylesheet in your application entry.

Next.js 15 App Router: Next.js App Router: import tidal.css and component CSS in app/layout.tsx. Interactive examples belong in a client component with "use client". Map @/* to ./* or ./src/* to match your project.

TypeScript 6: use paths without baseUrl:

```json
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
```

Pro registry requests are server/CLI-only. Use the same-origin account interface in a browser; cross-origin Authorization preflights are intentionally unsupported.


## Install Roles and permissions

```sh
npx shadcn@latest add @tidal-pro/roles-permissions
```

Stylesheets: `components/ui/tidal.css`, `components/ui/roles-permissions.css`.

## Minimal example

```tsx
import"./components/ui/tidal.css";
import"./components/ui/roles-permissions.css";
import{TidalRolesPermissions}from"./components/ui/roles-permissions";
export default()=><div className="tidal-scope"><TidalRolesPermissions grants={{}} permissions={[{id:"example",groupId:"example",groupLabel:"Demo",label:"Demo"}]} roles={[{id:"example",label:"Demo"}]} title={"Demo"} view={"list"}/></div>;
```

## Structured props

- `TidalRolesPermissions.grants: Readonly<Record<string, ReadonlyArray<string>>>`: Direct, editable permission IDs keyed by role ID.
- `TidalRolesPermissions.permissions: ReadonlyArray<TidalPermissionDefinition>`: Required permissions value accepted by this exported component.
- `TidalRolesPermissions.roles: ReadonlyArray<TidalPermissionRole>`: Required roles value accepted by this exported component.
- `TidalRolesPermissions.title: ReactNode`: Required title value accepted by this exported component.
- `TidalRolesPermissions.view: "list" | "matrix"`: Required view value accepted by this exported component.
- `TidalRolesPermissions.description?: ReactNode`: Optional description value accepted by this exported component.
- `TidalRolesPermissions.disabled?: boolean | undefined` (default false): Optional disabled value accepted by this exported component.
- `TidalRolesPermissions.emptyMembers?: ReactNode` (default "No members are assigned."): Optional empty members value accepted by this exported component.
- `TidalRolesPermissions.emptyPermissions?: ReactNode` (default "No permissions are configured."): Optional empty permissions value accepted by this exported component.
- `TidalRolesPermissions.footer?: ReactNode`: Optional footer value accepted by this exported component.
- `TidalRolesPermissions.groupInputProps?: ((role: TidalPermissionRole, groupId: string) => NativeCheckboxProps | undefined) | undefined`: Optional group input props value accepted by this exported component.
- `TidalRolesPermissions.groupInputRef?: ((roleId: string, groupId: string) => Ref<HTMLInputElement> | undefined) | undefined`: Optional group input ref value accepted by this exported component.
- `TidalRolesPermissions.headingLevel?: "h2" | "h3" | "h4" | "h5" | undefined` (default "h2"): Optional heading level value accepted by this exported component.
- `TidalRolesPermissions.inheritedGrants?: Readonly<Record<string, ReadonlyArray<string>>> | undefined` (default EMPTY_GRANTS): Effective permissions inherited from another policy. Inherited cells are read-only.
- `TidalRolesPermissions.labels?: Partial<{ matrix: ReactNode; list: ReactNode; view: string; permissions: string; members: ReactNode; role: ReactNode; inherited: ReactNode; direct: ReactNode; unavailableRole: string; configurationError: ReactNode; }> | undefined` (default EMPTY_LABELS): Optional labels value accepted by this exported component.
- `TidalRolesPermissions.listButtonProps?: NativeButtonProps | undefined`: Optional list button props value accepted by this exported component.
- `TidalRolesPermissions.listButtonRef?: Ref<HTMLButtonElement> | undefined`: Optional list button ref value accepted by this exported component.
- `TidalRolesPermissions.matrixButtonProps?: NativeButtonProps | undefined`: Optional matrix button props value accepted by this exported component.
- `TidalRolesPermissions.matrixButtonRef?: Ref<HTMLButtonElement> | undefined`: Optional matrix button ref value accepted by this exported component.
- `TidalRolesPermissions.matrixRegionProps?: Omit<Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">, "children" | "dangerouslySetInnerHTML"> | undefined`: Optional matrix region props value accepted by this exported component.
- `TidalRolesPermissions.matrixRegionRef?: Ref<HTMLDivElement> | undefined`: Optional matrix region ref value accepted by this exported component.
- `TidalRolesPermissions.members?: ReadonlyArray<TidalPermissionMember> | undefined` (default EMPTY_MEMBERS): Optional members value accepted by this exported component.
- `TidalRolesPermissions.onGroupChange?: ((roleId: string, groupId: string, granted: boolean, editablePermissionIds: readonly string[], event: ChangeEvent<HTMLInputElement>) => void) | undefined`: Callback invoked when the group change interaction is proposed.
- `TidalRolesPermissions.onMemberRoleChange?: ((memberId: string, roleId: string, event: ChangeEvent<HTMLSelectElement>) => void) | undefined`: Callback invoked when the member role change interaction is proposed.
- `TidalRolesPermissions.onPermissionChange?: ((roleId: string, permissionId: string, granted: boolean, event: ChangeEvent<HTMLInputElement>) => void) | undefined`: Callback invoked when the permission change interaction is proposed.
- `TidalRolesPermissions.onViewChange?: ((view: "matrix" | "list", event: MouseEvent<HTMLButtonElement>) => void) | undefined`: Callback invoked when the view change interaction is proposed.
- `TidalRolesPermissions.permissionInputProps?: ((role: TidalPermissionRole, permission: TidalPermissionDefinition) => NativeCheckboxProps | undefined) | undefined`: Optional permission input props value accepted by this exported component.
- `TidalRolesPermissions.permissionInputRef?: ((roleId: string, permissionId: string) => Ref<HTMLInputElement> | undefined) | undefined`: Optional permission input ref value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/roles-permissions.tsx) | [Manifest](https://tidalui.com/examples/roles-permissions.json). Install the listed additional dependencies. Consumer fixture: TypeScript pass; Vite pass. This fixture check is distinct from the actual shadcn install receipt.

```tsx
"use client";

import "./components/ui/tidal.css";

import { useLayoutEffect, useMemo, useState } from "react";

import { TidalRolesPermissions, type TidalPermissionMember, type TidalPermissionRole } from "./components/ui/roles-permissions";

import "./components/ui/roles-permissions.css";

function tidalExampleAvatarDataUri(seed: unknown) {
  const text = String(seed).replace(/[^a-z0-9]/gi, "").slice(-2) || "UI";
  const palette = ["#333333", "#555555", "#777777", "#999999", "#bbbbbb"];
  const color = palette[Array.from(text).reduce((sum, character) => sum + character.charCodeAt(0), 0) % palette.length];
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96"><rect width="96" height="96" rx="48" fill="${color}"/><circle cx="48" cy="38" r="17" fill="white" fill-opacity=".92"/><path d="M18 92c3-22 15-34 30-34s27 12 30 34" fill="white" fill-opacity=".92"/></svg>`;
  return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

function tidalExampleImageDataUri(label: string) {
  const safeLabel = label.replace(/[<>&]/g, "").slice(0, 28) || "Sample image";
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 675"><defs><linearGradient id="g" x1="0" x2="1" y1="0" y2="1"><stop stop-color="#171717"/><stop offset="1" stop-color="#555555"/></linearGradient></defs><rect width="1200" height="675" fill="url(#g)"/><circle cx="950" cy="100" r="260" fill="white" fill-opacity=".08"/><text x="80" y="570" fill="white" font-family="system-ui,sans-serif" font-size="64" font-weight="700">${safeLabel}</text></svg>`;
  return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

const tidalExampleStyles = ".tidal-scope .roles-permissions-demo,\n.tidal-scope .roles-permissions-demo * {\n  box-sizing: border-box;\n}\n\n.tidal-scope .roles-permissions-demo {\n  display: grid;\n  width: min(100%, 920px);\n  min-width: 0;\n  gap: 12px;\n}\n\n.tidal-scope .roles-permissions-demo-actions {\n  display: flex;\n  min-width: 0;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n}\n\n.tidal-scope .roles-permissions-demo-actions output {\n  min-width: 0;\n  color: var(--t-muted);\n  font-size: 11px;\n  line-height: 1.4;\n  overflow-wrap: anywhere;\n}\n\n.tidal-scope .roles-permissions-demo-actions button {\n  display: inline-flex;\n  min-width: 44px;\n  min-height: 44px;\n  flex: 0 0 auto;\n  align-items: center;\n  justify-content: center;\n  padding: 8px 13px;\n  border: 1px solid var(--t-border);\n  border-radius: var(--t-radius-control);\n  color: var(--t-ink);\n  background: var(--t-surface);\n  font: inherit;\n  font-size: 11px;\n  font-weight: 720;\n  cursor: pointer;\n  transition:\n    color 160ms,\n    background-color 160ms,\n    transform 140ms var(--t-ease-out);\n}\n\n.tidal-scope .roles-permissions-demo-actions button:hover {\n  color: var(--t-surface);\n  background: var(--t-ink);\n}\n\n.tidal-scope .roles-permissions-demo-actions button:active {\n  transform: scale(0.97);\n}\n\n.tidal-scope .roles-permissions-demo-actions button:focus-visible {\n  outline: 2px solid var(--t-ink);\n  outline-offset: 3px;\n}\n\n@media (max-width: 520px) {\n  .tidal-scope .roles-permissions-demo-actions {\n    display: grid;\n  }\n\n  .tidal-scope .roles-permissions-demo-actions button {\n    width: 100%;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .tidal-scope .roles-permissions-demo-actions button {\n    transition: none;\n  }\n\n  .tidal-scope .roles-permissions-demo-actions button:active {\n    transform: none;\n  }\n}";

const ROLES: readonly TidalPermissionRole[] = [
  {
    id: "admin",
    label: "Admin",
    description: "Workspace controls and publishing.",
  },
  {
    id: "editor",
    label: "Editor",
    description: "Creates and reviews project work.",
  },
  {
    id: "viewer",
    label: "Viewer",
    description: "Reads shared project work.",
  },
];

const PERMISSIONS = [
  {
    id: "view-projects",
    groupId: "content",
    groupLabel: "Project work",
    label: "View projects",
    description: "Open shared project records.",
  },
  {
    id: "edit-projects",
    groupId: "content",
    groupLabel: "Project work",
    label: "Edit projects",
    description: "Change notes and milestones.",
  },
  {
    id: "publish-projects",
    groupId: "content",
    groupLabel: "Project work",
    label: "Publish projects",
    description: "Move approved work to published.",
  },
  {
    id: "manage-members",
    groupId: "workspace",
    groupLabel: "Workspace",
    label: "Manage members",
    description: "Change sample member assignments.",
  },
  {
    id: "review-billing",
    groupId: "workspace",
    groupLabel: "Workspace",
    label: "Review billing",
    description: "Read the sample billing summary.",
  },
] as const;

const INITIAL_GRANTS: Readonly<Record<string, readonly string[]>> = {
  admin: [
    "view-projects",
    "edit-projects",
    "publish-projects",
    "manage-members",
    "review-billing",
  ],
  editor: ["edit-projects", "publish-projects"],
  viewer: [],
};

const INITIAL_MEMBERS: readonly TidalPermissionMember[] = [
  {
    id: "ava",
    name: "Ava Morgan",
    description: "Project lead",
    roleId: "admin",
    avatar: (
      <img
        src={tidalExampleAvatarDataUri("01")}
        alt="Ava Morgan"
        width="36"
        height="36"
      />
    ),
  },
  {
    id: "noah",
    name: "Noah Park",
    description: "Design reviewer",
    roleId: "editor",
    avatar: (
      <img
        src={tidalExampleAvatarDataUri("02")}
        alt="Noah Park"
        width="36"
        height="36"
      />
    ),
  },
  {
    id: "mila",
    name: "Mila Santos",
    description: "Guest reviewer",
    roleId: "viewer",
    avatar: (
      <img
        src={tidalExampleAvatarDataUri("03")}
        alt="Mila Santos"
        width="36"
        height="36"
      />
    ),
  },
];

function copyGrants(source: Readonly<Record<string, readonly string[]>>) {
  return Object.fromEntries(
    Object.entries(source).map(([roleId, permissionIds]) => [
      roleId,
      [...permissionIds],
    ]),
  );
}

export function RolesPermissionsDemo() {
  const [view, setView] = useState<"matrix" | "list">("matrix");
  const [grants, setGrants] = useState<Record<string, string[]>>(() =>
    copyGrants(INITIAL_GRANTS),
  );
  const [members, setMembers] = useState<TidalPermissionMember[]>(() =>
    INITIAL_MEMBERS.map((member) => ({ ...member })),
  );
  const [status, setStatus] = useState("Review the current sample access map.");
  const roles = useMemo(
    () =>
      ROLES.map((role) => ({
        ...role,
        memberCount: `${members.filter((member) => member.roleId === role.id).length} assigned`,
      })),
    [members],
  );

  useLayoutEffect(() => {
    const media = window.matchMedia("(max-width: 599px)");
    const syncView = () => setView(media.matches ? "list" : "matrix");
    syncView();
    media.addEventListener("change", syncView);
    return () => media.removeEventListener("change", syncView);
  }, []);

  const setPermission = (
    roleId: string,
    permissionId: string,
    granted: boolean,
  ) => {
    setGrants((current) => {
      const next = new Set(current[roleId] ?? []);
      if (granted) next.add(permissionId);
      else next.delete(permissionId);
      return { ...current, [roleId]: [...next] };
    });
    const role = ROLES.find((candidate) => candidate.id === roleId);
    const permission = PERMISSIONS.find(
      (candidate) => candidate.id === permissionId,
    );
    setStatus(
      `${String(permission?.label ?? permissionId)} ${granted ? "enabled" : "disabled"} for ${String(role?.label ?? roleId)}.`,
    );
  };

  return (
    <div className="roles-permissions-demo">
      <TidalRolesPermissions
        title="Workspace access"
        description="Assign sample roles and inspect each role’s effective permissions."
        roles={roles}
        permissions={PERMISSIONS}
        grants={grants}
        inheritedGrants={{
          editor: ["view-projects"],
          viewer: ["view-projects"],
        }}
        members={members}
        view={view}
        onViewChange={(next) => {
          setView(next);
          setStatus(
            `${next === "matrix" ? "Matrix" : "Role list"} view selected.`,
          );
        }}
        onPermissionChange={(roleId, permissionId, granted) =>
          setPermission(roleId, permissionId, granted)
        }
        onGroupChange={(roleId, _groupId, granted, permissionIds) => {
          setGrants((current) => {
            const next = new Set(current[roleId] ?? []);
            permissionIds.forEach((permissionId) => {
              if (granted) next.add(permissionId);
              else next.delete(permissionId);
            });
            return { ...current, [roleId]: [...next] };
          });
          const role = ROLES.find((candidate) => candidate.id === roleId);
          setStatus(
            `${permissionIds.length} editable permissions ${granted ? "enabled" : "disabled"} for ${String(role?.label ?? roleId)}.`,
          );
        }}
        onMemberRoleChange={(memberId, roleId) => {
          setMembers((current) =>
            current.map((member) =>
              member.id === memberId ? { ...member, roleId } : member,
            ),
          );
          const member = members.find((candidate) => candidate.id === memberId);
          const role = ROLES.find((candidate) => candidate.id === roleId);
          setStatus(
            `${String(member?.name ?? memberId)} assigned to ${String(role?.label ?? roleId)}.`,
          );
        }}
        footer={
          <span>
            Sample permissions. Changes stay in this preview and do not enforce
            access.
          </span>
        }
      />
      <div className="roles-permissions-demo-actions">
        <output aria-live="polite">{status}</output>
        <button
          type="button"
          onClick={() => {
            setGrants(copyGrants(INITIAL_GRANTS));
            setMembers(INITIAL_MEMBERS.map((member) => ({ ...member })));
            setView(
              window.matchMedia("(max-width: 599px)").matches
                ? "list"
                : "matrix",
            );
            setStatus("Sample access map reset.");
          }}
        >
          Reset sample
        </button>
      </div>
    </div>
  );
}

export default function AgentExample() {
  return (
    <div className="tidal-scope" data-theme="light" dir="ltr">
      <style>{tidalExampleStyles}</style>
      <RolesPermissionsDemo />
    </div>
  );
}

```

## Gotchas

- The host application owns data, validation, persistence, navigation, and service side effects described by this API.

## Theme and accessibility

{"tokens":["--t-accent","--t-border","--t-border-strong","--t-canvas","--t-danger","--t-display","--t-ease-out","--t-ease-spring","--t-faint","--t-font","--t-ink","--t-line","--t-muted","--t-primary","--t-primary-contrast","--t-radius-card","--t-radius-control","--t-radius-overlay","--t-radius-panel","--t-ring","--t-shadow-lg","--t-shadow-soft","--t-soft","--t-subtle","--t-surface","--t-wash"],"darkMode":true}

{"keyboard":["Tab and Shift+Tab follow the component's native focus order.","Arrow-key behavior follows the exported composite-control implementation."],"aria":"The component wires labels and relationships from consumer-provided visible text or ARIA props; preserve those labels in production.","notes":"Verify focus visibility, text alternatives, contrast, and reduced motion in the final composition."}

title, consumer-owned roles with unique IDs/plain select labels, permission definitions with unique IDs/group IDs, controlled direct grants and view are required. Optional inherited grants render checked read-only permissions. Optional controlled members expose native single-select role assignment. Matrix and role-list views share the same controlled values; native view buttons render only with onViewChange. Individual and group checkbox callbacks receive proposals after caller handlers and honor prevention. Group toggles expose checked/mixed effective state while proposing only editable permission IDs. Native permission/group inputs support callback prop/ref factories, names, external forms and native attributes while checked/type remain owned. Member selects preserve native props/ref, external form, caller accessible-name/description attributes and linked unknown-value validation. Root, matrix-region and view-button props/refs are supported; root aria-disabled and unsafe markup are excluded. disabled locks every owned control. Unknown role or permission references surface linked configuration feedback and disable mutations without changing caller data; blank or duplicate role, permission or member IDs suppress ambiguous keyed collections. The matrix receives a keyboard tab stop only while measured overflow exists unless a tabIndex is supplied. Consumers own authorization, effective-policy evaluation beyond supplied direct/inherited sets, mutation, confirmation, requests and persistence. The component does not enforce access, fetch, export, store or authenticate.
