Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";
import { ChevronDown, XMark } from "@unkey/icons";
import type { UnkeyPermission } from "@unkey/rbac";
import { Badge, Button } from "@unkey/ui";
import { useMemo } from "react";
import { apiPermissions, workspacePermissions } from "../../../[keyId]/permissions/permissions";

type Props = {
apiId: string;
name: string;
selectedPermissions: UnkeyPermission[];
expandCount: number;
title: string;
removePermission: (permission: string) => void;
};

type InfoType = { permission: UnkeyPermission; category: string; action: string }[];

const PermissionBadgeList = ({
apiId,
name,
selectedPermissions,
title,
expandCount,
removePermission,
}: Props) => {
const workspace = workspacePermissions;
const allPermissions = apiId === "workspace" ? workspace : apiPermissions(apiId);

// Flatten allPermissions into an array of {permission, action} objects
const allPermissionsArray = useMemo(
() =>
Object.entries(allPermissions).flatMap(([category, permissions]) =>
Object.entries(permissions).map(([action, permissionData]) => ({
permission: permissionData.permission,
category,
action,
})),
),
[allPermissions],
);

const info = useMemo(
() => findPermission(allPermissionsArray, selectedPermissions),
[allPermissionsArray, selectedPermissions],
);
if (info.length === 0) {
return null;
}

return info.length > expandCount ? (
<div className="flex flex-col gap-2">
<CollapsibleList
info={info as InfoType}
title={title}
expandCount={expandCount}
removePermission={removePermission}
name={name}
/>
</div>
) : (
<div className="flex flex-col gap-2">
<ListTitle title={title} count={info.length} category={name} />
<ListBadges info={info as InfoType} removePermission={removePermission} />
</div>
);
};

const ListBadges = ({
info,
removePermission,
}: { info: InfoType; removePermission: (permission: string) => void }) => {
const handleRemovePermission = (e: React.MouseEvent<HTMLButtonElement>, permission: string) => {
e.stopPropagation();
removePermission(permission);
};
return (
<div className="flex flex-wrap gap-2 pt-2">
{info?.map((permission) => {
if (!permission) {
return null;
}

return (
<Badge
key={permission.permission}
variant="primary"
className="flex items-center h-[22px] p-[6px] px-2 text-xs font-normal text-grayA-11 hover:bg-grayA-2 hover:text-grayA-12 gap-2"
>
<span>{permission.action}</span>
<Button
variant="ghost"
size="icon"
className="w-4 h-4"
onClick={(e) => handleRemovePermission(e, permission.permission)}
>
<XMark className="w-4 h-4" />
</Button>
</Badge>
);
})}
</div>
);
};

type CollapsibleListProps = {
info: InfoType;
title: string;
expandCount: number;
removePermission: (permission: string) => void;
name: string;
className?: string;
} & React.ComponentProps<typeof CollapsibleTrigger>;

const CollapsibleList = ({
info,
title,
expandCount,
removePermission,
name,
className,
...props
}: CollapsibleListProps) => {
return (
<Collapsible>
<CollapsibleTrigger
{...props}
className={cn(
"flex flex-row gap-3 transition-all [&[data-state=open]>svg]:rotate-180 w-full",
className,
)}
>
<ListTitle title={title} count={info.length} category={name} />
<ChevronDown className="w-4 h-4 transition-transform duration-200 ml-auto text-grayA-8" />
</CollapsibleTrigger>
<CollapsibleContent>
<ListBadges info={info} removePermission={removePermission} />
</CollapsibleContent>
</Collapsible>
);
};

const ListTitle = ({
title,
count,
category,
}: { title: string; count: number; category: string }) => {
return (
<p className="text-sm w-full text-grayA-10 justify-start text-left">
{title}
<span className="font-bold text-gray-11 ml-2">{category}</span>
<Badge
variant="primary"
size="sm"
className="text-[11px] font-normal text-grayA-11 rounded-full px-2 ml-4 h-[18px] min-w-[22px] border-[1px] border-grayA-3 "
>
{count}
</Badge>
</p>
);
};

const findPermission = (allPermissions: InfoType, selectedPermissions: UnkeyPermission[]) => {
if (!selectedPermissions || !Array.isArray(selectedPermissions)) {
return [];
}
return selectedPermissions
.map((permission) => {
return allPermissions.find((p) => p.permission === permission);
})
.filter(Boolean);
};

export { PermissionBadgeList };
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,11 @@
import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible";
import type { CheckedState } from "@radix-ui/react-checkbox";
import type { UnkeyPermission } from "@unkey/rbac";
import { useEffect, useReducer } from "react";
import { useCallback, useEffect, useMemo, useReducer } from "react";
import { apiPermissions, workspacePermissions } from "../../../[keyId]/permissions/permissions";
import { ExpandableCategory } from "./expandable-category";
import { PermissionToggle } from "./permission-toggle";

type Props = {
type: "workspace" | "api";
api?:
| {
id: string;
name: string;
}
| undefined;
onPermissionChange: (permissions: UnkeyPermission[]) => void;
};

// Helper type for permission list structure
type PermissionCategory = Record<string, { description: string; permission: UnkeyPermission }>;
type PermissionList = Record<string, PermissionCategory>;
Expand Down Expand Up @@ -51,6 +40,7 @@ function computeCheckedStates(
// Compute rootChecked
const allPermissionNames = getAllPermissionNames(permissionList);
let rootChecked: CheckedState = false;

if (selectedPermissions.length === 0) {
rootChecked = false;
} else if (selectedPermissions.length === allPermissionNames.length) {
Expand All @@ -60,6 +50,7 @@ function computeCheckedStates(
}
// Compute categoryChecked
const categoryChecked: Record<string, CheckedState> = {};

Object.entries(permissionList).forEach(([category, allPermissions]) => {
const allPermissionNames = Object.values(allPermissions).map(({ permission }) => permission);
if (allPermissionNames.every((p) => selectedPermissions.includes(p))) {
Expand All @@ -70,6 +61,7 @@ function computeCheckedStates(
categoryChecked[category] = false;
}
});

return { rootChecked, categoryChecked };
}

Expand All @@ -89,6 +81,7 @@ function permissionReducer(state: PermissionState, action: PermissionAction): Pe
);
return { selectedPermissions, rootChecked, categoryChecked };
}

case "TOGGLE_CATEGORY": {
const { category, permissionList } = action;
const categoryPermissions = getCategoryPermissionNames(permissionList, category);
Expand All @@ -111,6 +104,7 @@ function permissionReducer(state: PermissionState, action: PermissionAction): Pe
);
return { selectedPermissions, rootChecked, categoryChecked };
}

case "TOGGLE_ROOT": {
const { permissionList } = action;
const allPermissionNames = getAllPermissionNames(permissionList);
Expand All @@ -126,38 +120,89 @@ function permissionReducer(state: PermissionState, action: PermissionAction): Pe
);
return { selectedPermissions, rootChecked, categoryChecked };
}

default:
return state;
}
}

export const PermissionContentList = ({ type, api, onPermissionChange }: Props) => {
const permissionList: PermissionList =
type === "workspace" ? workspacePermissions : api ? apiPermissions(api.id) : {};
type Props = {
type: "workspace" | "api";
api?:
| {
id: string;
name: string;
}
| undefined;
onPermissionChange: (permissions: UnkeyPermission[]) => void;
selected: UnkeyPermission[];
};

export const PermissionContentList = ({ type, api, onPermissionChange, selected }: Props) => {
const permissionList: PermissionList = useMemo(
() => (type === "workspace" ? workspacePermissions : api ? apiPermissions(api.id) : {}),
[type, api?.id],
);

const initialState = useMemo(() => {
const initState =
type === "workspace"
? Object.values(workspacePermissions)
.flatMap((category) =>
Object.values(category).map(({ permission }) =>
selected.includes(permission) ? permission : null,
),
)
.filter((permission) => permission !== null)
: api
? Object.values(apiPermissions(api.id))
.flatMap((category) =>
Object.values(category).map(({ permission }) =>
selected.includes(permission) ? permission : null,
),
)
.filter((permission) => permission !== null)
: [];

const { rootChecked, categoryChecked } = computeCheckedStates(initState, permissionList);

const selectedPermissions = getAllPermissionNames(permissionList).filter((permission) =>
initState.includes(permission),
);

return { rootChecked, categoryChecked, selectedPermissions };
}, [type, selected, permissionList, api]);

const [state, dispatch] = useReducer(permissionReducer, {
selectedPermissions: [],
categoryChecked: {},
rootChecked: false,
selectedPermissions: selected.length > 0 ? initialState.selectedPermissions : [],
categoryChecked: selected.length > 0 ? initialState.categoryChecked : {},
rootChecked: selected.length > 0 ? initialState.rootChecked : false,
});

// Notify parent when selectedPermissions changes
useEffect(() => {
onPermissionChange(state.selectedPermissions);

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state.selectedPermissions]);

const handleRootChecked = () => {
const handleRootChecked = useCallback(() => {
dispatch({ type: "TOGGLE_ROOT", permissionList });
};
}, [permissionList]);

const handleCategoryChecked = (category: string) => {
dispatch({ type: "TOGGLE_CATEGORY", category, permissionList });
};
const handleCategoryChecked = useCallback(
(category: string) => {
dispatch({ type: "TOGGLE_CATEGORY", category, permissionList });
},
[permissionList],
);

const handlePermissionChecked = (permission: UnkeyPermission) => {
dispatch({ type: "TOGGLE_PERMISSION", permission, permissionList });
};
const handlePermissionChecked = useCallback(
(permission: UnkeyPermission) => {
dispatch({ type: "TOGGLE_PERMISSION", permission, permissionList });
},
[permissionList],
);

return (
<div className="flex flex-col gap-2">
Expand Down
Loading