85 lines
2.3 KiB
TypeScript
85 lines
2.3 KiB
TypeScript
"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<Set<number>>(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) => (
|
||
|
|
<div key={node.id}>
|
||
|
|
<label
|
||
|
|
className="flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-[var(--color-muted)]"
|
||
|
|
style={{ paddingLeft: depth * 20 + 8 }}
|
||
|
|
>
|
||
|
|
<input
|
||
|
|
type="checkbox"
|
||
|
|
className="h-4 w-4 accent-[var(--color-primary)]"
|
||
|
|
checked={checked.has(node.id)}
|
||
|
|
onChange={(e) => toggle(node, e.target.checked)}
|
||
|
|
/>
|
||
|
|
<span className="text-sm">{node.title}</span>
|
||
|
|
<span className="text-xs text-[var(--color-muted-foreground)]">{node.name}</span>
|
||
|
|
</label>
|
||
|
|
{node.children.map((c) => renderNode(c, depth + 1))}
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
|
||
|
|
return (
|
||
|
|
<div className="space-y-4">
|
||
|
|
<div className="rounded-[var(--radius)] border p-2">
|
||
|
|
{tree.map((n) => renderNode(n, 0))}
|
||
|
|
</div>
|
||
|
|
<div className="flex gap-2">
|
||
|
|
<Button onClick={save} disabled={pending}>
|
||
|
|
{pending ? "保存中…" : `保存(已选 ${checked.size} 项)`}
|
||
|
|
</Button>
|
||
|
|
<Link href="/rbac/roles"><Button variant="outline">取消</Button></Link>
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
);
|
||
|
|
}
|