"use client"; import { useState, useTransition } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { assignPermissions } from "../../../actions"; export type PermNode = { id: number; title: string; name: string; children: PermNode[]; }; export function AssignPermissions({ roleId, tree, checkedIds, }: { roleId: number; tree: PermNode[]; checkedIds: number[]; }) { const router = useRouter(); const [checked, setChecked] = useState>(new Set(checkedIds)); const [pending, start] = useTransition(); function toggle(node: PermNode, on: boolean) { const next = new Set(checked); const walk = (n: PermNode) => { if (on) next.add(n.id); else next.delete(n.id); n.children.forEach(walk); }; walk(node); setChecked(next); } function save() { start(async () => { const res = await assignPermissions(roleId, [...checked]); if (res.ok) { toast.success("权限已保存"); router.push("/rbac/roles"); router.refresh(); } else toast.error(res.error ?? "保存失败"); }); } const renderNode = (node: PermNode, depth: number) => (
{node.children.map((c) => renderNode(c, depth + 1))}
); return (
{tree.map((n) => renderNode(n, 0))}
); }