feat: enhance dashboard CRUD functionality with support for boolean and multi-select fields; update related types and utilities

This commit is contained in:
mlogclub
2026-05-28 09:45:24 +08:00
parent 0ca0332a5f
commit 2cb834efa3
6 changed files with 442 additions and 28 deletions
@@ -1,9 +1,25 @@
"use client"
import type { FieldError as HookFormFieldError } from "react-hook-form"
import { useState } from "react"
import { CheckIcon, ChevronsUpDownIcon } from "lucide-react"
import type {
FieldError as HookFormFieldError,
UseFormReturn,
} from "react-hook-form"
import { Controller, type Control, type UseFormRegister } from "react-hook-form"
import { OptionCombobox } from "@/components/option-combobox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Field,
FieldContent,
@@ -11,31 +27,73 @@ import {
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { useI18n } from "@/i18n/provider"
import { cn } from "@/lib/utils"
import type { DashboardCrudFormField } from "./dashboard-crud-utils"
import type {
DashboardCrudFormField,
DashboardCrudFormInputValue,
DashboardCrudFormOption,
} from "./dashboard-crud-utils"
export function DashboardCrudFieldControl<TItem>({
field,
control,
form,
register,
error,
}: {
field: DashboardCrudFormField<TItem>
control: Control<Record<string, string>>
register: UseFormRegister<Record<string, string>>
control: Control<Record<string, DashboardCrudFormInputValue>>
form: UseFormReturn<
Record<string, DashboardCrudFormInputValue>,
undefined,
Record<string, DashboardCrudFormInputValue>
>
register: UseFormRegister<Record<string, DashboardCrudFormInputValue>>
error?: HookFormFieldError
}) {
const inputId = `dashboard-crud-field-${field.name}`
if (field.type === "section" || field.type === "group") {
return (
<div className="md:col-span-2">
<div className="border-t pt-4">
<div className="text-sm font-medium">{field.label}</div>
{field.description ? (
<div className="mt-1 text-sm text-muted-foreground">
{field.description}
</div>
) : null}
</div>
</div>
)
}
return (
<Field
data-invalid={!!error}
className={cn(
(field.colSpan === 2 || field.type === "textarea") && "md:col-span-2"
(field.colSpan === 2 ||
["textarea", "json", "code", "custom"].includes(field.type ?? "")) &&
"md:col-span-2"
)}
>
<FieldLabel htmlFor={field.type === "select" ? undefined : inputId}>
<FieldLabel
htmlFor={
["select", "multiSelect", "switch", "checkbox", "custom"].includes(
field.type ?? ""
)
? undefined
: inputId
}
>
{field.label}
</FieldLabel>
<FieldContent>
@@ -45,13 +103,77 @@ export function DashboardCrudFieldControl<TItem>({
name={field.name}
render={({ field: controllerField }) => (
<OptionCombobox
value={controllerField.value}
value={String(controllerField.value ?? "")}
options={[...(field.options ?? [])]}
placeholder={field.placeholder ?? field.label}
onChange={controllerField.onChange}
/>
)}
/>
) : field.type === "multiSelect" ? (
<Controller
control={control}
name={field.name}
render={({ field: controllerField }) => (
<DashboardCrudMultiSelect
value={
Array.isArray(controllerField.value)
? controllerField.value
: []
}
options={[...(field.options ?? [])]}
placeholder={field.placeholder ?? field.label}
onChange={controllerField.onChange}
/>
)}
/>
) : field.type === "switch" ? (
<Controller
control={control}
name={field.name}
render={({ field: controllerField }) => (
<Switch
checked={Boolean(controllerField.value)}
onCheckedChange={controllerField.onChange}
aria-label={field.label}
/>
)}
/>
) : field.type === "checkbox" ? (
<Controller
control={control}
name={field.name}
render={({ field: controllerField }) => (
<label className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox
checked={Boolean(controllerField.value)}
onCheckedChange={controllerField.onChange}
aria-label={field.label}
/>
<span>{field.description ?? field.label}</span>
</label>
)}
/>
) : field.type === "custom" && field.render ? (
<Controller
control={control}
name={field.name}
render={({ field: controllerField }) => (
<>
{field.render?.({
name: field.name,
label: field.label,
value: controllerField.value,
values: form.watch(),
setValue: (name, value) =>
form.setValue(name, value, {
shouldDirty: true,
shouldValidate: true,
}),
})}
</>
)}
/>
) : field.type === "textarea" ? (
<Textarea
id={inputId}
@@ -60,10 +182,26 @@ export function DashboardCrudFieldControl<TItem>({
aria-invalid={!!error}
{...register(field.name)}
/>
) : field.type === "json" || field.type === "code" ? (
<Textarea
id={inputId}
rows={field.rows ?? 8}
placeholder={field.placeholder}
aria-invalid={!!error}
spellCheck={false}
className="font-mono text-xs leading-5"
{...register(field.name)}
/>
) : (
<Input
id={inputId}
type={field.type === "number" ? "number" : "text"}
type={
field.type === "number"
? "number"
: field.type === "password"
? "password"
: "text"
}
min={field.type === "number" ? field.min : undefined}
max={field.type === "number" ? field.max : undefined}
step={field.type === "number" ? field.step : undefined}
@@ -72,8 +210,97 @@ export function DashboardCrudFieldControl<TItem>({
{...register(field.name)}
/>
)}
{field.description && field.type !== "checkbox" ? (
<div className="text-sm text-muted-foreground">{field.description}</div>
) : null}
<FieldError errors={error ? [error] : []} />
</FieldContent>
</Field>
)
}
function DashboardCrudMultiSelect({
value,
options,
placeholder,
onChange,
}: {
value: string[]
options: DashboardCrudFormOption[]
placeholder: string
onChange: (value: string[]) => void
}) {
const t = useI18n()
const [open, setOpen] = useState(false)
const selectedOptions = options.filter((option) => value.includes(option.value))
const selectedText =
selectedOptions.length > 0
? selectedOptions.map((option) => option.label).join(", ")
: placeholder
function toggleValue(nextValue: string) {
if (value.includes(nextValue)) {
onChange(value.filter((item) => item !== nextValue))
return
}
onChange([...value, nextValue])
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
render={
<Button
type="button"
variant="outline"
role="combobox"
className="w-full justify-between font-normal"
/>
}
>
<span className="truncate">{selectedText}</span>
<ChevronsUpDownIcon className="ml-2 size-4 shrink-0 opacity-50" />
</PopoverTrigger>
<PopoverContent className="w-(--radix-popover-trigger-width) p-0" align="start">
<Command>
<CommandInput placeholder={t("common.searchKeyword")} />
<CommandList>
<CommandEmpty>{t("common.emptyOptions")}</CommandEmpty>
<CommandGroup>
{options.map((option) => {
const checked = value.includes(option.value)
return (
<CommandItem
key={option.value}
value={`${option.label} ${option.value}`}
onSelect={() => toggleValue(option.value)}
>
<CheckIcon
className={cn(
"mr-2 size-4 shrink-0",
checked ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{option.label}</span>
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
</Command>
{selectedOptions.length > 0 ? (
<div className="flex flex-wrap gap-1 border-t p-2">
{selectedOptions.slice(0, 8).map((option) => (
<Badge key={option.value} variant="secondary">
{option.label}
</Badge>
))}
{selectedOptions.length > 8 ? (
<Badge variant="outline">+{selectedOptions.length - 8}</Badge>
) : null}
</div>
) : null}
</PopoverContent>
</Popover>
)
}
@@ -11,6 +11,7 @@ import { Button } from "@/components/ui/button"
import {
buildDashboardCrudFormValues,
normalizeDashboardCrudSubmitValues,
type DashboardCrudFormInputValue,
type DashboardCrudFormField,
type DashboardCrudFormOption,
} from "./dashboard-crud-utils"
@@ -24,7 +25,7 @@ type DashboardCrudFormDialogProps<TItem, TPayload> = {
fields: DashboardCrudFormField<TItem>[]
fetchDetail?: (id: number) => Promise<TItem>
transformSubmitValues?: (
values: Record<string, string | number>,
values: Record<string, string | number | boolean | string[] | number[]>,
context: { mode: "create" | "edit"; item: TItem | null }
) => TPayload
labels: {
@@ -48,9 +49,28 @@ function createFormSchema<TItem>(
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
labels: DashboardCrudFormDialogProps<TItem, unknown>["labels"]
) {
const shape: Record<string, z.ZodType<string>> = {}
const shape: Record<string, z.ZodType> = {}
fields.forEach((field) => {
if (field.type === "section" || field.type === "group") {
return
}
if (field.type === "switch" || field.type === "checkbox") {
shape[field.name] = field.required
? z.boolean().refine((value) => value, field.requiredMessage ?? labels.required)
: z.boolean()
return
}
if (field.type === "multiSelect") {
shape[field.name] = field.required
? z.array(z.string()).min(1, field.requiredMessage ?? labels.required)
: z.array(z.string())
return
}
if (field.type === "custom") {
shape[field.name] = z.any()
return
}
let schema = field.trim ? z.string().trim() : z.string()
if (field.required) {
schema = schema.min(1, field.requiredMessage ?? labels.required)
@@ -74,6 +94,17 @@ function createFormSchema<TItem>(
})
}
}
if (field.type === "json" && field.validateJson !== false) {
schema = schema.refine((value) => {
if (!value.trim()) return !field.required
try {
JSON.parse(value)
return true
} catch {
return false
}
}, field.patternMessage ?? labels.required)
}
shape[field.name] = schema
})
@@ -82,7 +113,11 @@ function createFormSchema<TItem>(
function normalizeFormLayoutFields<TItem>(fields: DashboardCrudFormField<TItem>[]) {
return fields.map((field) =>
field.type === "textarea" ? { ...field, colSpan: field.colSpan ?? 2 } : field
["textarea", "json", "code", "custom", "section", "group"].includes(
field.type ?? ""
)
? { ...field, colSpan: field.colSpan ?? 2 }
: field
)
}
@@ -107,9 +142,9 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
const resolver = useMemo(
() =>
zodResolver(schema as never) as Resolver<
Record<string, string>,
Record<string, DashboardCrudFormInputValue>,
undefined,
Record<string, string>
Record<string, DashboardCrudFormInputValue>
>,
[schema]
)
@@ -120,7 +155,11 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
const [fieldOptions, setFieldOptions] = useState<
Record<string, ReadonlyArray<DashboardCrudFormOption>>
>({})
const form = useForm<Record<string, string>, undefined, Record<string, string>>({
const form = useForm<
Record<string, DashboardCrudFormInputValue>,
undefined,
Record<string, DashboardCrudFormInputValue>
>({
resolver,
defaultValues: initialValues,
})
@@ -166,7 +205,11 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
let cancelled = false
const loaders = fields
.filter((field) => field.type === "select" && field.loadOptions)
.filter(
(field) =>
(field.type === "select" || field.type === "multiSelect") &&
field.loadOptions
)
.map(async (field) => {
const options = await field.loadOptions!()
return [field.name, options] as const
@@ -187,7 +230,7 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
}
}, [fields, open])
async function submit(values: Record<string, string>) {
async function submit(values: Record<string, DashboardCrudFormInputValue>) {
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
const payload = transformSubmitValues
? transformSubmitValues(normalizedValues, { mode, item: detailItem })
@@ -240,6 +283,7 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
options: fieldOptions[field.name] ?? field.options,
}}
control={control}
form={form}
register={register}
error={errors[field.name]}
/>
@@ -122,7 +122,7 @@ export type DashboardCrudPageProps<TItem, TPayload> = {
fields: DashboardCrudFormField<TItem>[]
fetchDetail?: (id: number) => Promise<TItem>
transformSubmitValues?: (
values: Record<string, string | number>,
values: Record<string, string | number | boolean | string[] | number[]>,
context: { mode: "create" | "edit"; item: TItem | null }
) => TPayload
labels: {
@@ -137,6 +137,35 @@ describe("buildDashboardCrudFormValues", () => {
}
)
})
it("normalizes boolean and multi-select defaults", async () => {
const { buildDashboardCrudFormValues } = await loadModule()
const fields = [
{ name: "enabled", type: "switch", defaultValue: true },
{ name: "required", type: "checkbox" },
{ name: "toolIds", type: "multiSelect", defaultValue: [1, "2"] },
]
assert.deepEqual(plain(buildDashboardCrudFormValues(fields)), {
enabled: true,
required: false,
toolIds: ["1", "2"],
})
assert.deepEqual(
plain(
buildDashboardCrudFormValues(fields, {
enabled: 0,
required: "1",
toolIds: [3, "4"],
})
),
{
enabled: false,
required: true,
toolIds: ["3", "4"],
}
)
})
})
describe("normalizeDashboardCrudSubmitValues", () => {
@@ -163,6 +192,32 @@ describe("normalizeDashboardCrudSubmitValues", () => {
}
)
})
it("converts boolean and multi-select fields", async () => {
const { normalizeDashboardCrudSubmitValues } = await loadModule()
const fields = [
{ name: "enabled", type: "switch" },
{ name: "toolCodes", type: "multiSelect" },
{ name: "roleIds", type: "multiSelect", valueType: "number" },
{ name: "section", type: "section" },
]
assert.deepEqual(
plain(
normalizeDashboardCrudSubmitValues(fields, {
enabled: true,
toolCodes: ["search", "faq"],
roleIds: ["1", "2", "bad"],
section: "",
})
),
{
enabled: true,
toolCodes: ["search", "faq"],
roleIds: [1, 2],
}
)
})
})
describe("dashboard CRUD action rules", () => {
@@ -1,3 +1,5 @@
import type { ReactNode } from "react"
export type DashboardCrudQueryValue = string | number | undefined
export type DashboardCrudQueryFilter = {
@@ -23,23 +25,52 @@ export type DashboardCrudPageResult<T> = {
}
}
export type DashboardCrudFormValue = string | number | undefined
export type DashboardCrudFormValue =
| string
| number
| boolean
| ReadonlyArray<string | number>
| undefined
export type DashboardCrudFormOption = {
value: string
label: string
}
export type DashboardCrudFormInputValue = string | boolean | string[]
export type DashboardCrudFormCustomRenderContext = {
name: string
label: string
value: DashboardCrudFormInputValue
values: Record<string, DashboardCrudFormInputValue>
setValue: (name: string, value: DashboardCrudFormInputValue) => void
}
export type DashboardCrudFormField<TItem = unknown> = {
name: string
label: string
type?: "text" | "textarea" | "number" | "select"
type?:
| "text"
| "textarea"
| "number"
| "select"
| "multiSelect"
| "switch"
| "checkbox"
| "password"
| "json"
| "code"
| "custom"
| "section"
| "group"
placeholder?: string
defaultValue?: DashboardCrudFormValue
description?: string
required?: boolean
requiredMessage?: string
trim?: boolean
valueType?: "string" | "number"
valueType?: "string" | "number" | "boolean"
min?: number
max?: number
step?: number
@@ -49,7 +80,10 @@ export type DashboardCrudFormField<TItem = unknown> = {
loadOptions?: () => Promise<ReadonlyArray<DashboardCrudFormOption>>
colSpan?: 1 | 2
rows?: number
language?: string
validateJson?: boolean
valueFromItem?: (item: TItem) => DashboardCrudFormValue
render?: (context: DashboardCrudFormCustomRenderContext) => ReactNode
}
export type DashboardCrudActionRule<TItem> = {
@@ -125,10 +159,10 @@ export function normalizeDashboardCrudPageResult<T>(
export function buildDashboardCrudFormValues<TItem>(
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
item?: TItem | null
): Record<string, string> {
): Record<string, DashboardCrudFormInputValue> {
return Object.fromEntries(
fields.map((field) => {
let value: unknown = field.defaultValue ?? ""
let value: unknown = field.defaultValue ?? getDashboardCrudFormDefaultValue(field)
if (item) {
if (field.valueFromItem) {
value = field.valueFromItem(item)
@@ -136,20 +170,40 @@ export function buildDashboardCrudFormValues<TItem>(
value = (item as Record<string, unknown>)[field.name]
}
}
return [field.name, value === undefined || value === null ? "" : String(value)]
return [field.name, normalizeDashboardCrudFormInputValue(field, value)]
})
)
}
export function normalizeDashboardCrudSubmitValues<TItem>(
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
values: Record<string, string>
): Record<string, string | number> {
const output: Record<string, string | number> = {}
values: Record<string, DashboardCrudFormInputValue>
): Record<string, string | number | boolean | string[] | number[]> {
const output: Record<string, string | number | boolean | string[] | number[]> = {}
fields.forEach((field) => {
const rawValue = values[field.name] ?? ""
const text = field.trim ? rawValue.trim() : rawValue
if (field.type === "section" || field.type === "group") {
return
}
const rawValue = values[field.name] ?? getDashboardCrudFormDefaultValue(field)
if (field.type === "switch" || field.type === "checkbox" || field.valueType === "boolean") {
output[field.name] = Boolean(rawValue)
return
}
if (field.type === "multiSelect") {
const list = Array.isArray(rawValue) ? rawValue : []
if (field.valueType === "number") {
output[field.name] = list
.map((value) => Number(value))
.filter((value) => Number.isFinite(value))
return
}
output[field.name] = list.map(String)
return
}
const rawText = typeof rawValue === "string" ? rawValue : String(rawValue ?? "")
const text = field.trim ? rawText.trim() : rawText
if (field.type === "number" || field.valueType === "number") {
const numberValue = Number(text)
output[field.name] = Number.isFinite(numberValue) ? numberValue : 0
@@ -161,6 +215,37 @@ export function normalizeDashboardCrudSubmitValues<TItem>(
return output
}
function getDashboardCrudFormDefaultValue<TItem>(
field: DashboardCrudFormField<TItem>
): DashboardCrudFormInputValue {
if (field.type === "switch" || field.type === "checkbox") {
return false
}
if (field.type === "multiSelect") {
return []
}
return ""
}
function normalizeDashboardCrudFormInputValue<TItem>(
field: DashboardCrudFormField<TItem>,
value: unknown
): DashboardCrudFormInputValue {
if (value === undefined || value === null) {
return getDashboardCrudFormDefaultValue(field)
}
if (field.type === "switch" || field.type === "checkbox" || field.valueType === "boolean") {
return value === true || value === "true" || value === 1 || value === "1"
}
if (field.type === "multiSelect") {
if (!Array.isArray(value)) return []
return value
.filter((item) => item !== undefined && item !== null)
.map((item) => String(item))
}
return String(value)
}
export function isDashboardCrudActionVisible<TItem>(
action: DashboardCrudActionRule<TItem>,
item: TItem
+3
View File
@@ -19,6 +19,9 @@ export type {
} from "./dashboard-crud-page"
export type {
DashboardCrudFormField,
DashboardCrudFormInputValue,
DashboardCrudFormOption,
DashboardCrudFormValue,
DashboardCrudFilterStateConfig,
DashboardCrudPageResult,
DashboardCrudQueryFilter,