74 lines
2.1 KiB
TypeScript
74 lines
2.1 KiB
TypeScript
import { useState } from "react";
|
|
import { z } from "zod";
|
|
import Checkbox from "@mui/material/Checkbox";
|
|
import { usePlatform } from "@/lib/platform";
|
|
import { Pager, QueryView, Table, usePrivateQuery } from "./WorkspaceTools";
|
|
const record = z.object({
|
|
id: z.string().uuid(),
|
|
name: z.string(),
|
|
isSystem: z.boolean().optional(),
|
|
permissions: z.array(z.string()).optional(),
|
|
});
|
|
export function RecordSelection({
|
|
name,
|
|
label,
|
|
path,
|
|
initial = [],
|
|
roles = false,
|
|
}: {
|
|
name: string;
|
|
label: string;
|
|
path: string;
|
|
initial?: string[];
|
|
roles?: boolean;
|
|
}) {
|
|
const { principal } = usePlatform();
|
|
const [selected, setSelected] = useState(initial),
|
|
[offset, setOffset] = useState(0);
|
|
const query = usePrivateQuery(
|
|
`${path}?limit=25&offset=${offset}`,
|
|
z.array(record),
|
|
);
|
|
return (
|
|
<fieldset className="record-picker">
|
|
<legend>{label}</legend>
|
|
<p>{selected.length} selected. Selections are retained across pages.</p>
|
|
{selected.map((id) => (
|
|
<input key={id} type="hidden" name={name} value={id} />
|
|
))}
|
|
<QueryView query={query}>
|
|
{(items) => (
|
|
<>
|
|
<Table
|
|
head={["Select", "Name"]}
|
|
rowKeys={items.map((item) => item.id)}
|
|
rows={items.map((item) => [
|
|
<Checkbox
|
|
inputProps={{ "aria-label": `Select ${item.name}` }}
|
|
checked={selected.includes(item.id)}
|
|
disabled={
|
|
roles &&
|
|
(item.isSystem ||
|
|
item.permissions?.some(
|
|
(p) => !principal?.permissions.includes(p),
|
|
))
|
|
}
|
|
onChange={(_, checked) =>
|
|
setSelected((ids) =>
|
|
checked
|
|
? [...ids, item.id]
|
|
: ids.filter((id) => id !== item.id),
|
|
)
|
|
}
|
|
/>,
|
|
item.name,
|
|
])}
|
|
/>
|
|
<Pager offset={offset} count={items.length} onPage={setOffset} />
|
|
</>
|
|
)}
|
|
</QueryView>
|
|
</fieldset>
|
|
);
|
|
}
|