mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 11:06:29 +00:00
b149903b2e
Make parent menus gate child permissions and cascade select or clear actions through descendants. Update role detail rendering for nested menus and the revised API shape, with related RBAC UI and sidebar adjustments.
333 lines
13 KiB
TypeScript
333 lines
13 KiB
TypeScript
'use client';
|
|
|
|
import React, { FC, useState, useMemo } from 'react';
|
|
import { Input } from 'antd';
|
|
import { Search, Shield, ShieldCheck } from 'lucide-react';
|
|
import { type IMenu } from './type';
|
|
import RolePermissionRow from './role-permission-row';
|
|
|
|
export interface IMenuPermissionTreeProps {
|
|
menus: IMenu[];
|
|
allowAdminPanel: boolean;
|
|
// Map of menu_id -> array of selected action names
|
|
selectedPermissions: Record<number, string[]>;
|
|
onPermissionToggle: (menuId: number, actionName: string, checked: boolean) => void;
|
|
onMenuSelectAll: (menuId: number, allActions: string[]) => void;
|
|
onMenuClearAll: (menuId: number) => void;
|
|
onBatchSelectAll?: (updates: Record<number, string[]>) => void;
|
|
onBatchClearAll?: (menuIds: number[]) => void;
|
|
}
|
|
|
|
interface TreeNode extends IMenu {
|
|
children?: TreeNode[];
|
|
level: number;
|
|
}
|
|
|
|
// Transform flat list to tree
|
|
function buildTree(items: IMenu[], parentId: number | null = null, level: number = 0): TreeNode[] {
|
|
const result: TreeNode[] = [];
|
|
const directChildren = items.filter(i => {
|
|
if (parentId === null) {
|
|
return i.menu_parent_id === null || i.menu_parent_id === undefined;
|
|
}
|
|
return i.menu_parent_id === parentId;
|
|
});
|
|
|
|
for (const item of directChildren) {
|
|
if (item.id === undefined) continue;
|
|
const children = buildTree(items, item.id, level + 1);
|
|
const node: TreeNode = {
|
|
...item,
|
|
level,
|
|
children: children.length > 0 ? children : undefined,
|
|
};
|
|
result.push(node);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
export const MenuPermissionTree: FC<IMenuPermissionTreeProps> = ({
|
|
menus,
|
|
allowAdminPanel,
|
|
selectedPermissions,
|
|
onPermissionToggle,
|
|
onMenuSelectAll,
|
|
onMenuClearAll,
|
|
onBatchSelectAll,
|
|
onBatchClearAll,
|
|
}) => {
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const [collapsedIds, setCollapsedIds] = useState<Set<number>>(new Set());
|
|
|
|
const toggleCollapse = (id: number) => {
|
|
setCollapsedIds(prev => {
|
|
const next = new Set(prev);
|
|
if (next.has(id)) {
|
|
next.delete(id);
|
|
} else {
|
|
next.add(id);
|
|
}
|
|
return next;
|
|
});
|
|
};
|
|
|
|
// Group all menus by ID for quick ancestor & descendant traversal
|
|
const menuMap = useMemo(() => {
|
|
const map = new Map<number, IMenu>();
|
|
menus.forEach(m => {
|
|
if (m.id !== undefined) map.set(m.id, m);
|
|
});
|
|
return map;
|
|
}, [menus]);
|
|
|
|
// Helper: get all descendants recursively for a menu ID
|
|
const getDescendants = (menuId: number): IMenu[] => {
|
|
const list: IMenu[] = [];
|
|
const directChildren = menus.filter(m => m.menu_parent_id === menuId && m.id !== undefined);
|
|
directChildren.forEach(child => {
|
|
list.push(child);
|
|
list.push(...getDescendants(child.id!));
|
|
});
|
|
return list;
|
|
};
|
|
|
|
// Helper: is a menu considered "checked" (has at least 1 action or is explicitly marked)
|
|
const isMenuChecked = (menuId: number): boolean => {
|
|
const acts = selectedPermissions[menuId];
|
|
return Boolean(acts && acts.length > 0);
|
|
};
|
|
|
|
// Helper: check if a menu is enabled (all ancestors must be checked)
|
|
const isMenuEnabled = (node: TreeNode | IMenu): boolean => {
|
|
if (!node.menu_parent_id) return true; // Root menu is always enabled
|
|
const parent = menuMap.get(node.menu_parent_id);
|
|
if (!parent || parent.id === undefined) return true;
|
|
// Parent must be checked AND parent must be enabled
|
|
return isMenuChecked(parent.id) && isMenuEnabled(parent);
|
|
};
|
|
|
|
// Separate Non-Admin and Admin menus
|
|
const { nonAdminTree, adminTree } = useMemo(() => {
|
|
const nonAdminList = menus.filter(m => !(m.is_admin_menu));
|
|
const adminList = menus.filter(m => Boolean(m.is_admin_menu));
|
|
|
|
return {
|
|
nonAdminTree: buildTree(nonAdminList),
|
|
adminTree: buildTree(adminList),
|
|
};
|
|
}, [menus]);
|
|
|
|
// Filter matching IDs when searching
|
|
const searchMatchIds = useMemo(() => {
|
|
if (!searchQuery.trim()) return null;
|
|
const lower = searchQuery.toLowerCase();
|
|
const matches = new Set<number>();
|
|
|
|
menus.forEach(m => {
|
|
const matchName = m.name?.toLowerCase().includes(lower);
|
|
const matchPath = m.path_url?.toLowerCase().includes(lower);
|
|
const matchActions = m.action?.some(a => a.toLowerCase().includes(lower));
|
|
|
|
if (matchName || matchPath || matchActions) {
|
|
if (m.id !== undefined) matches.add(m.id);
|
|
// Also add parent IDs so parent stays visible
|
|
let parentId = m.menu_parent_id;
|
|
while (parentId) {
|
|
matches.add(parentId);
|
|
const parent = menus.find(p => p.id === parentId);
|
|
parentId = parent?.menu_parent_id;
|
|
}
|
|
}
|
|
});
|
|
|
|
return matches;
|
|
}, [menus, searchQuery]);
|
|
|
|
// Helper: compute aggregate isAllChecked and isIndeterminate for a node (including its descendants)
|
|
const computeNodeSelectionState = (node: TreeNode) => {
|
|
const descendants = getDescendants(node.id!);
|
|
const allNodes = [node, ...descendants];
|
|
|
|
let totalActionsCount = 0;
|
|
let selectedActionsCount = 0;
|
|
let hasAnyActionSelected = false;
|
|
|
|
allNodes.forEach(m => {
|
|
const valid = m.action && m.action.length > 0 ? m.action : ['__CHECKED__'];
|
|
totalActionsCount += valid.length;
|
|
const cur = selectedPermissions[m.id!] || [];
|
|
const matching = cur.filter(a => valid.includes(a));
|
|
selectedActionsCount += matching.length;
|
|
if (matching.length > 0) hasAnyActionSelected = true;
|
|
});
|
|
|
|
const isAllChecked = totalActionsCount > 0 && selectedActionsCount === totalActionsCount;
|
|
const isIndeterminate = hasAnyActionSelected && !isAllChecked;
|
|
|
|
return { isAllChecked, isIndeterminate };
|
|
};
|
|
|
|
// When selecting a node: select all actions of the node AND all of its descendants
|
|
const handleNodeSelectAll = (node: TreeNode) => {
|
|
const descendants = getDescendants(node.id!);
|
|
const allNodes = [node, ...descendants];
|
|
const updates: Record<number, string[]> = {};
|
|
|
|
allNodes.forEach(m => {
|
|
if (m.id !== undefined) {
|
|
const actions = m.action && m.action.length > 0 ? [...m.action] : ['__CHECKED__'];
|
|
updates[m.id] = actions;
|
|
}
|
|
});
|
|
|
|
if (onBatchSelectAll) {
|
|
onBatchSelectAll(updates);
|
|
} else {
|
|
Object.entries(updates).forEach(([idStr, acts]) => {
|
|
onMenuSelectAll(Number(idStr), acts);
|
|
});
|
|
}
|
|
};
|
|
|
|
// When clearing a node: clear the node AND all of its descendants
|
|
const handleNodeClearAll = (node: TreeNode) => {
|
|
const descendants = getDescendants(node.id!);
|
|
const allIds = [node.id!, ...descendants.map(d => d.id!).filter(Boolean) as number[]];
|
|
|
|
if (onBatchClearAll) {
|
|
onBatchClearAll(allIds);
|
|
} else {
|
|
allIds.forEach(id => {
|
|
onMenuClearAll(id);
|
|
});
|
|
}
|
|
};
|
|
|
|
// Renders a single menu row and recursively its children using unified RolePermissionRow
|
|
const renderNode = (node: TreeNode) => {
|
|
if (node.id === undefined) return null;
|
|
if (searchMatchIds && !searchMatchIds.has(node.id)) {
|
|
return null;
|
|
}
|
|
|
|
const isCollapsed = collapsedIds.has(node.id);
|
|
const hasChildren = Boolean(node.children && node.children.length > 0);
|
|
const assignedActions = node.action || [];
|
|
const currentSelectedActions = selectedPermissions[node.id] || [];
|
|
const isEnabled = isMenuEnabled(node);
|
|
const { isAllChecked, isIndeterminate } = computeNodeSelectionState(node);
|
|
|
|
return (
|
|
<React.Fragment key={node.id}>
|
|
<RolePermissionRow
|
|
node={{
|
|
id: node.id,
|
|
name: node.name,
|
|
path_url: node.path_url,
|
|
icon: node.icon,
|
|
is_menu_admin: Boolean(node.is_admin_menu),
|
|
level: node.level,
|
|
hasChildren,
|
|
isCollapsed,
|
|
action: assignedActions,
|
|
}}
|
|
mode="interactive"
|
|
disabled={!isEnabled}
|
|
isAllChecked={isAllChecked}
|
|
isIndeterminate={isIndeterminate}
|
|
selectedActions={currentSelectedActions}
|
|
onToggleCollapse={() => toggleCollapse(node.id!)}
|
|
onPermissionToggle={(actionName, checked) =>
|
|
onPermissionToggle(node.id!, actionName, checked)
|
|
}
|
|
onSelectAll={() => handleNodeSelectAll(node)}
|
|
onClearAll={() => handleNodeClearAll(node)}
|
|
/>
|
|
|
|
{/* Render children recursively if not collapsed */}
|
|
{hasChildren && !isCollapsed && node.children!.map(child => renderNode(child))}
|
|
</React.Fragment>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className="flex flex-col space-y-6">
|
|
{/* Search Bar & Instruction */}
|
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
|
<div className="w-full sm:w-64 md:w-72">
|
|
<Input
|
|
prefix={<Search size={14} className="text-muted-foreground mr-1" />}
|
|
placeholder="Search menu or permission..."
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
allowClear
|
|
className="h-9"
|
|
/>
|
|
</div>
|
|
<div className="text-xs text-muted-foreground flex items-center gap-1.5">
|
|
<span>Tip: Click</span>
|
|
<span className="px-1.5 py-0.5 rounded bg-zinc-100 dark:bg-zinc-800 font-mono text-[11px] font-semibold text-zinc-700 dark:text-zinc-300">
|
|
Select All
|
|
</span>
|
|
<span>to quickly grant all permissions for that menu</span>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Section 1: Non-Admin Menus */}
|
|
<div className="border border-zinc-200 dark:border-zinc-800 rounded-lg overflow-hidden bg-white dark:bg-zinc-950">
|
|
<div className="py-3 px-4 bg-zinc-100/80 dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<Shield size={16} className="text-his" />
|
|
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 m-0">
|
|
Non-Admin Menus (General Application)
|
|
</h4>
|
|
</div>
|
|
<span className="text-xs text-muted-foreground font-mono font-medium">
|
|
{menus.filter(m => !(m.is_admin_menu)).length} menus
|
|
</span>
|
|
</div>
|
|
|
|
<div className="divide-y divide-zinc-200/80 dark:divide-zinc-800/80">
|
|
{nonAdminTree.length > 0 ?
|
|
nonAdminTree.map(node => renderNode(node))
|
|
:
|
|
<div className="py-8 text-center text-xs text-muted-foreground">
|
|
No non-admin menus available.
|
|
</div>
|
|
}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Section 2: Admin Menus (Rendered ONLY if allowAdminPanel === true) */}
|
|
{allowAdminPanel && (
|
|
<div className="border border-zinc-200 dark:border-zinc-800 rounded-lg overflow-hidden bg-white dark:bg-zinc-950">
|
|
<div className="py-3 px-4 bg-zinc-100/80 dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-800 flex items-center justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<ShieldCheck size={16} className="text-red-600 dark:text-red-400" />
|
|
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 m-0">
|
|
Admin Menus (Admin Panel)
|
|
</h4>
|
|
</div>
|
|
<span className="text-xs text-muted-foreground font-mono font-medium">
|
|
{menus.filter(m => Boolean(m.is_admin_menu)).length} menus
|
|
</span>
|
|
</div>
|
|
|
|
<div className="divide-y divide-zinc-200/80 dark:divide-zinc-800/80">
|
|
{adminTree.length > 0 ?
|
|
adminTree.map(node => renderNode(node))
|
|
:
|
|
<div className="py-8 text-center text-xs text-muted-foreground">
|
|
No admin panel menus available.
|
|
</div>
|
|
}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default MenuPermissionTree;
|