"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { SearchInput } from "@suphark/ui/components/shared/form/search-input"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Checkbox } from "@suphark/ui/components/ui/checkbox"; import { cn } from "@suphark/ui/lib/utils"; import { LockIcon, RotateCcwIcon } from "lucide-react"; import { Fragment, useDeferredValue, useMemo, useState } from "react"; export interface PermissionMatrixRole { id: string; label: string; description?: string; /** สิทธิ์ของบทบาทนี้กำหนดโดยระบบ (เช่น เจ้าของมีทุกสิทธิ์) — แสดงแต่แก้ไม่ได้ */ locked?: boolean; } export interface PermissionMatrixPermission { id: string; label: string; description?: string; } export interface PermissionMatrixGroup { id: string; label: string; permissions: ReadonlyArray; } /** บทบาท → รายการ id สิทธิ์ที่ได้ */ export type PermissionMatrixValue = Readonly>>; export interface PermissionMatrixProps { roles: ReadonlyArray; groups: ReadonlyArray; value: PermissionMatrixValue; /** ไม่ส่ง = อ่านอย่างเดียว */ onChange?: (next: PermissionMatrixValue) => void; /** ค่าที่บันทึกไว้ — ช่องที่ต่างจากนี้ถูกไฮไลต์ + แถบ "แก้แล้ว n จุด · คืนค่า" */ baseline?: PermissionMatrixValue; /** ช่องค้นหาสิทธิ์ (ค่าเริ่มต้น แสดงเมื่อมีสิทธิ์ > 12 รายการ) */ searchable?: boolean; /** ชื่อ field สำหรับฟอร์ม — input ซ่อน 1 ตัวต่อช่องที่ติ๊ก ค่า `":"` */ name?: string; className?: string; } const INDETERMINATE = "data-indeterminate:border-primary data-indeterminate:bg-primary data-indeterminate:text-primary-foreground data-indeterminate:before:absolute data-indeterminate:before:h-0.5 data-indeterminate:before:w-2 data-indeterminate:before:rounded-full data-indeterminate:before:bg-current [&[data-indeterminate]_svg]:hidden"; /** จำนวนช่อง (บทบาท × สิทธิ์) ที่ต่างจาก baseline */ export function countPermissionChanges( value: PermissionMatrixValue, baseline: PermissionMatrixValue, ): number { let changes = 0; for (const role of new Set([...Object.keys(value), ...Object.keys(baseline)])) { const now = new Set(value[role] ?? []); const before = new Set(baseline[role] ?? []); for (const id of now) if (!before.has(id)) changes++; for (const id of before) if (!now.has(id)) changes++; } return changes; } /** * ตารางบทบาท × สิทธิ์ (Pi Auth roles, supplychain สิทธิ์ตามแผนก) — ติ๊กทีละช่อง, ทั้งหมวดต่อบทบาท หรือทั้งคอลัมน์ * คอลัมน์สิทธิ์ตรึงซ้าย เลื่อนแนวนอนบนจอแคบ · ค้นหาสิทธิ์ · ไฮไลต์ช่องที่แก้เทียบ `baseline` · บทบาท `locked` แก้ไม่ได้ * * const [value, setValue] = useState(saved); * * */ export function PermissionMatrix({ roles, groups, value, onChange, baseline, searchable, name, className, }: PermissionMatrixProps) { const text = useUiText(); const t = text.permissionMatrix; const [query, setQuery] = useState(""); const deferred = useDeferredValue(query).trim().toLowerCase(); const total = groups.reduce((n, g) => n + g.permissions.length, 0); const showSearch = searchable ?? total > 12; const readOnly = !onChange; const sets = useMemo(() => { const map = new Map>(); for (const role of roles) map.set(role.id, new Set(value[role.id] ?? [])); return map; }, [roles, value]); const baseSets = useMemo(() => { if (!baseline) return null; const map = new Map>(); for (const role of roles) map.set(role.id, new Set(baseline[role.id] ?? [])); return map; }, [roles, baseline]); const visibleGroups = useMemo(() => { if (!deferred) return groups; return groups .map((g) => ({ ...g, permissions: g.label.toLowerCase().includes(deferred) ? g.permissions : g.permissions.filter((p) => [p.label, p.id, p.description ?? ""].some((s) => s.toLowerCase().includes(deferred)), ), })) .filter((g) => g.permissions.length > 0); }, [groups, deferred]); const changes = baseline ? countPermissionChanges(value, baseline) : 0; /** ตั้งค่าหลายช่องของบทบาทเดียว */ const setMany = (roleId: string, ids: ReadonlyArray, on: boolean) => { if (!onChange) return; const next = new Set(sets.get(roleId) ?? []); for (const id of ids) { if (on) next.add(id); else next.delete(id); } // คงลำดับตาม groups (diff/บันทึกอ่านง่าย) — id ที่ไม่อยู่ใน groups ต่อท้ายไว้ไม่ทิ้ง const ordered = groups .flatMap((g) => g.permissions.map((p) => p.id)) .filter((id) => next.has(id)); const extra = [...next].filter((id) => !ordered.includes(id)); onChange({ ...value, [roleId]: [...ordered, ...extra] }); }; const state = (roleId: string, ids: ReadonlyArray) => { const set = sets.get(roleId); const on = ids.filter((id) => set?.has(id)).length; return { checked: ids.length > 0 && on === ids.length, indeterminate: on > 0 && on < ids.length, }; }; const fill = (template: string, vars: Record) => Object.entries(vars).reduce((s, [k, v]) => s.replace(`{${k}}`, v), template); const allIds = visibleGroups.flatMap((g) => g.permissions.map((p) => p.id)); return (
{showSearch && ( )}
{roles.map((role) => { const s = state(role.id, allIds); return ( ); })} {visibleGroups.map((group) => { const ids = group.permissions.map((p) => p.id); return ( {roles.map((role) => { const s = state(role.id, ids); return ( ); })} {group.permissions.map((permission) => ( {roles.map((role) => { const on = sets.get(role.id)?.has(permission.id) ?? false; const changed = baseSets ? (baseSets.get(role.id)?.has(permission.id) ?? false) !== on : false; return ( ); })} ))} ); })} {visibleGroups.length === 0 && ( )}
{t?.permission ?? "สิทธิ์"}
{role.locked && ( )} {role.label} {!readOnly && !role.locked && ( setMany(role.id, allIds, checked === true)} aria-label={fill(t?.toggleRole ?? "ให้สิทธิ์ทั้งหมดแก่ {role}", { role: role.label, })} className={INDETERMINATE} /> )}
{group.label} {!readOnly && !role.locked && ids.length > 1 && ( setMany(role.id, ids, checked === true)} aria-label={fill(t?.toggleGroup ?? "{group} ทั้งหมดสำหรับ {role}", { group: group.label, role: role.label, })} className={cn("mx-auto", INDETERMINATE)} /> )}
{permission.label} {permission.description && ( {permission.description} )} setMany(role.id, [permission.id], checked === true) } aria-label={`${role.label}: ${permission.label}`} className="mx-auto" />
{fill(t?.empty ?? "ไม่พบสิทธิ์ที่ตรงกับ “{query}”", { query: query.trim() })}
{/* ส่งค่าจาก value ทั้งหมด ไม่ใช่เฉพาะแถวที่ผ่านช่องค้นหา — ไม่งั้นบันทึกระหว่างค้นหาแล้วสิทธิ์ที่ซ่อนอยู่ถูกถอน */} {name && Object.entries(value).flatMap(([roleId, ids]) => ids.map((permissionId) => ( )), )}
{baseline && changes > 0 && onChange && (
)}
); }