80 lines
3.1 KiB
TypeScript
80 lines
3.1 KiB
TypeScript
import { useState } from "react";
|
|
import type { WidgetProps } from "./types";
|
|
import { ReservedControls } from "./ReservedControls";
|
|
|
|
export function MultiselectWidget({ descriptor, onRespond }: WidgetProps) {
|
|
const options = descriptor.options ?? [];
|
|
const initialChecked = new Set(options.filter((o) => o.selected).map((o) => o.id));
|
|
const [checked, setChecked] = useState<Set<string>>(initialChecked);
|
|
|
|
const allChecked = options.length > 0 && options.every((o) => checked.has(o.id));
|
|
|
|
function toggle(id: string) {
|
|
setChecked((prev) => {
|
|
const next = new Set(prev);
|
|
if (next.has(id)) next.delete(id);
|
|
else next.add(id);
|
|
return next;
|
|
});
|
|
}
|
|
|
|
const isDisabled = descriptor.allow_empty === false && checked.size === 0;
|
|
|
|
return (
|
|
<div className="space-y-4 rounded-xl border border-border/70 bg-card p-4 shadow-sm">
|
|
{descriptor.title && (
|
|
<p className="text-[0.95rem] font-semibold leading-snug text-foreground">
|
|
{descriptor.title}
|
|
</p>
|
|
)}
|
|
<div className="flex flex-col">
|
|
{/* Prominent select-all control at the head of the list. */}
|
|
<div className="flex items-center justify-between border-b border-border/60 pb-2">
|
|
<button
|
|
className="text-sm font-semibold text-primary transition-colors hover:text-[oklch(var(--primary-hover))]"
|
|
onClick={() =>
|
|
setChecked(allChecked ? new Set() : new Set(options.map((o) => o.id)))
|
|
}
|
|
>
|
|
{allChecked ? "Deselect all" : "Select all"}
|
|
</button>
|
|
<span className="text-xs tabular-nums text-muted-foreground">
|
|
{checked.size} / {options.length} {descriptor.selection_label ?? "selected"}
|
|
</span>
|
|
</div>
|
|
<div className="flex flex-col gap-1 pt-2">
|
|
{options.map((o) => (
|
|
<label
|
|
key={o.id}
|
|
className={`flex cursor-pointer items-center gap-2.5 rounded-lg border px-2.5 py-2 text-sm text-foreground transition-colors hover:bg-accent ${
|
|
checked.has(o.id) ? "border-border/60 bg-accent/60" : "border-transparent"
|
|
}`}
|
|
>
|
|
<input
|
|
type="checkbox"
|
|
className="size-4 shrink-0 accent-[oklch(var(--primary))]"
|
|
checked={checked.has(o.id)}
|
|
onChange={() => toggle(o.id)}
|
|
/>
|
|
<span>{o.label}</span>
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<button
|
|
className="rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground shadow-xs transition-colors hover:bg-[oklch(var(--primary-hover))] disabled:cursor-not-allowed disabled:opacity-50"
|
|
disabled={isDisabled}
|
|
onClick={() => onRespond({ id: descriptor.id, kind: "multiselect", choices: Array.from(checked) })}
|
|
>
|
|
{descriptor.confirm_label ?? "Confirm"}
|
|
</button>
|
|
</div>
|
|
<ReservedControls
|
|
reserved={descriptor.reserved}
|
|
onControl={(c, t) => onRespond({ id: descriptor.id, control: c, ...(t !== undefined ? { text: t } : {}) })}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|