feat: enhance dashboard CRUD functionality with support for boolean and multi-select fields; update related types and utilities
This commit is contained in:
@@ -1,9 +1,25 @@
|
|||||||
"use client"
|
"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 { Controller, type Control, type UseFormRegister } from "react-hook-form"
|
||||||
|
|
||||||
import { OptionCombobox } from "@/components/option-combobox"
|
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 {
|
import {
|
||||||
Field,
|
Field,
|
||||||
FieldContent,
|
FieldContent,
|
||||||
@@ -11,31 +27,73 @@ import {
|
|||||||
FieldLabel,
|
FieldLabel,
|
||||||
} from "@/components/ui/field"
|
} from "@/components/ui/field"
|
||||||
import { Input } from "@/components/ui/input"
|
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 { Textarea } from "@/components/ui/textarea"
|
||||||
|
import { useI18n } from "@/i18n/provider"
|
||||||
import { cn } from "@/lib/utils"
|
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>({
|
export function DashboardCrudFieldControl<TItem>({
|
||||||
field,
|
field,
|
||||||
control,
|
control,
|
||||||
|
form,
|
||||||
register,
|
register,
|
||||||
error,
|
error,
|
||||||
}: {
|
}: {
|
||||||
field: DashboardCrudFormField<TItem>
|
field: DashboardCrudFormField<TItem>
|
||||||
control: Control<Record<string, string>>
|
control: Control<Record<string, DashboardCrudFormInputValue>>
|
||||||
register: UseFormRegister<Record<string, string>>
|
form: UseFormReturn<
|
||||||
|
Record<string, DashboardCrudFormInputValue>,
|
||||||
|
undefined,
|
||||||
|
Record<string, DashboardCrudFormInputValue>
|
||||||
|
>
|
||||||
|
register: UseFormRegister<Record<string, DashboardCrudFormInputValue>>
|
||||||
error?: HookFormFieldError
|
error?: HookFormFieldError
|
||||||
}) {
|
}) {
|
||||||
const inputId = `dashboard-crud-field-${field.name}`
|
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 (
|
return (
|
||||||
<Field
|
<Field
|
||||||
data-invalid={!!error}
|
data-invalid={!!error}
|
||||||
className={cn(
|
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}
|
{field.label}
|
||||||
</FieldLabel>
|
</FieldLabel>
|
||||||
<FieldContent>
|
<FieldContent>
|
||||||
@@ -45,13 +103,77 @@ export function DashboardCrudFieldControl<TItem>({
|
|||||||
name={field.name}
|
name={field.name}
|
||||||
render={({ field: controllerField }) => (
|
render={({ field: controllerField }) => (
|
||||||
<OptionCombobox
|
<OptionCombobox
|
||||||
value={controllerField.value}
|
value={String(controllerField.value ?? "")}
|
||||||
options={[...(field.options ?? [])]}
|
options={[...(field.options ?? [])]}
|
||||||
placeholder={field.placeholder ?? field.label}
|
placeholder={field.placeholder ?? field.label}
|
||||||
onChange={controllerField.onChange}
|
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" ? (
|
) : field.type === "textarea" ? (
|
||||||
<Textarea
|
<Textarea
|
||||||
id={inputId}
|
id={inputId}
|
||||||
@@ -60,10 +182,26 @@ export function DashboardCrudFieldControl<TItem>({
|
|||||||
aria-invalid={!!error}
|
aria-invalid={!!error}
|
||||||
{...register(field.name)}
|
{...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
|
<Input
|
||||||
id={inputId}
|
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}
|
min={field.type === "number" ? field.min : undefined}
|
||||||
max={field.type === "number" ? field.max : undefined}
|
max={field.type === "number" ? field.max : undefined}
|
||||||
step={field.type === "number" ? field.step : undefined}
|
step={field.type === "number" ? field.step : undefined}
|
||||||
@@ -72,8 +210,97 @@ export function DashboardCrudFieldControl<TItem>({
|
|||||||
{...register(field.name)}
|
{...register(field.name)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{field.description && field.type !== "checkbox" ? (
|
||||||
|
<div className="text-sm text-muted-foreground">{field.description}</div>
|
||||||
|
) : null}
|
||||||
<FieldError errors={error ? [error] : []} />
|
<FieldError errors={error ? [error] : []} />
|
||||||
</FieldContent>
|
</FieldContent>
|
||||||
</Field>
|
</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 {
|
import {
|
||||||
buildDashboardCrudFormValues,
|
buildDashboardCrudFormValues,
|
||||||
normalizeDashboardCrudSubmitValues,
|
normalizeDashboardCrudSubmitValues,
|
||||||
|
type DashboardCrudFormInputValue,
|
||||||
type DashboardCrudFormField,
|
type DashboardCrudFormField,
|
||||||
type DashboardCrudFormOption,
|
type DashboardCrudFormOption,
|
||||||
} from "./dashboard-crud-utils"
|
} from "./dashboard-crud-utils"
|
||||||
@@ -24,7 +25,7 @@ type DashboardCrudFormDialogProps<TItem, TPayload> = {
|
|||||||
fields: DashboardCrudFormField<TItem>[]
|
fields: DashboardCrudFormField<TItem>[]
|
||||||
fetchDetail?: (id: number) => Promise<TItem>
|
fetchDetail?: (id: number) => Promise<TItem>
|
||||||
transformSubmitValues?: (
|
transformSubmitValues?: (
|
||||||
values: Record<string, string | number>,
|
values: Record<string, string | number | boolean | string[] | number[]>,
|
||||||
context: { mode: "create" | "edit"; item: TItem | null }
|
context: { mode: "create" | "edit"; item: TItem | null }
|
||||||
) => TPayload
|
) => TPayload
|
||||||
labels: {
|
labels: {
|
||||||
@@ -48,9 +49,28 @@ function createFormSchema<TItem>(
|
|||||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||||
labels: DashboardCrudFormDialogProps<TItem, unknown>["labels"]
|
labels: DashboardCrudFormDialogProps<TItem, unknown>["labels"]
|
||||||
) {
|
) {
|
||||||
const shape: Record<string, z.ZodType<string>> = {}
|
const shape: Record<string, z.ZodType> = {}
|
||||||
|
|
||||||
fields.forEach((field) => {
|
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()
|
let schema = field.trim ? z.string().trim() : z.string()
|
||||||
if (field.required) {
|
if (field.required) {
|
||||||
schema = schema.min(1, field.requiredMessage ?? labels.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
|
shape[field.name] = schema
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -82,7 +113,11 @@ function createFormSchema<TItem>(
|
|||||||
|
|
||||||
function normalizeFormLayoutFields<TItem>(fields: DashboardCrudFormField<TItem>[]) {
|
function normalizeFormLayoutFields<TItem>(fields: DashboardCrudFormField<TItem>[]) {
|
||||||
return fields.map((field) =>
|
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(
|
const resolver = useMemo(
|
||||||
() =>
|
() =>
|
||||||
zodResolver(schema as never) as Resolver<
|
zodResolver(schema as never) as Resolver<
|
||||||
Record<string, string>,
|
Record<string, DashboardCrudFormInputValue>,
|
||||||
undefined,
|
undefined,
|
||||||
Record<string, string>
|
Record<string, DashboardCrudFormInputValue>
|
||||||
>,
|
>,
|
||||||
[schema]
|
[schema]
|
||||||
)
|
)
|
||||||
@@ -120,7 +155,11 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
const [fieldOptions, setFieldOptions] = useState<
|
const [fieldOptions, setFieldOptions] = useState<
|
||||||
Record<string, ReadonlyArray<DashboardCrudFormOption>>
|
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,
|
resolver,
|
||||||
defaultValues: initialValues,
|
defaultValues: initialValues,
|
||||||
})
|
})
|
||||||
@@ -166,7 +205,11 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
|
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
const loaders = fields
|
const loaders = fields
|
||||||
.filter((field) => field.type === "select" && field.loadOptions)
|
.filter(
|
||||||
|
(field) =>
|
||||||
|
(field.type === "select" || field.type === "multiSelect") &&
|
||||||
|
field.loadOptions
|
||||||
|
)
|
||||||
.map(async (field) => {
|
.map(async (field) => {
|
||||||
const options = await field.loadOptions!()
|
const options = await field.loadOptions!()
|
||||||
return [field.name, options] as const
|
return [field.name, options] as const
|
||||||
@@ -187,7 +230,7 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
}
|
}
|
||||||
}, [fields, open])
|
}, [fields, open])
|
||||||
|
|
||||||
async function submit(values: Record<string, string>) {
|
async function submit(values: Record<string, DashboardCrudFormInputValue>) {
|
||||||
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
const normalizedValues = normalizeDashboardCrudSubmitValues(fields, values)
|
||||||
const payload = transformSubmitValues
|
const payload = transformSubmitValues
|
||||||
? transformSubmitValues(normalizedValues, { mode, item: detailItem })
|
? transformSubmitValues(normalizedValues, { mode, item: detailItem })
|
||||||
@@ -240,6 +283,7 @@ export function DashboardCrudFormDialog<TItem, TPayload>({
|
|||||||
options: fieldOptions[field.name] ?? field.options,
|
options: fieldOptions[field.name] ?? field.options,
|
||||||
}}
|
}}
|
||||||
control={control}
|
control={control}
|
||||||
|
form={form}
|
||||||
register={register}
|
register={register}
|
||||||
error={errors[field.name]}
|
error={errors[field.name]}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -122,7 +122,7 @@ export type DashboardCrudPageProps<TItem, TPayload> = {
|
|||||||
fields: DashboardCrudFormField<TItem>[]
|
fields: DashboardCrudFormField<TItem>[]
|
||||||
fetchDetail?: (id: number) => Promise<TItem>
|
fetchDetail?: (id: number) => Promise<TItem>
|
||||||
transformSubmitValues?: (
|
transformSubmitValues?: (
|
||||||
values: Record<string, string | number>,
|
values: Record<string, string | number | boolean | string[] | number[]>,
|
||||||
context: { mode: "create" | "edit"; item: TItem | null }
|
context: { mode: "create" | "edit"; item: TItem | null }
|
||||||
) => TPayload
|
) => TPayload
|
||||||
labels: {
|
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", () => {
|
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", () => {
|
describe("dashboard CRUD action rules", () => {
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { ReactNode } from "react"
|
||||||
|
|
||||||
export type DashboardCrudQueryValue = string | number | undefined
|
export type DashboardCrudQueryValue = string | number | undefined
|
||||||
|
|
||||||
export type DashboardCrudQueryFilter = {
|
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 = {
|
export type DashboardCrudFormOption = {
|
||||||
value: string
|
value: string
|
||||||
label: 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> = {
|
export type DashboardCrudFormField<TItem = unknown> = {
|
||||||
name: string
|
name: string
|
||||||
label: string
|
label: string
|
||||||
type?: "text" | "textarea" | "number" | "select"
|
type?:
|
||||||
|
| "text"
|
||||||
|
| "textarea"
|
||||||
|
| "number"
|
||||||
|
| "select"
|
||||||
|
| "multiSelect"
|
||||||
|
| "switch"
|
||||||
|
| "checkbox"
|
||||||
|
| "password"
|
||||||
|
| "json"
|
||||||
|
| "code"
|
||||||
|
| "custom"
|
||||||
|
| "section"
|
||||||
|
| "group"
|
||||||
placeholder?: string
|
placeholder?: string
|
||||||
defaultValue?: DashboardCrudFormValue
|
defaultValue?: DashboardCrudFormValue
|
||||||
|
description?: string
|
||||||
required?: boolean
|
required?: boolean
|
||||||
requiredMessage?: string
|
requiredMessage?: string
|
||||||
trim?: boolean
|
trim?: boolean
|
||||||
valueType?: "string" | "number"
|
valueType?: "string" | "number" | "boolean"
|
||||||
min?: number
|
min?: number
|
||||||
max?: number
|
max?: number
|
||||||
step?: number
|
step?: number
|
||||||
@@ -49,7 +80,10 @@ export type DashboardCrudFormField<TItem = unknown> = {
|
|||||||
loadOptions?: () => Promise<ReadonlyArray<DashboardCrudFormOption>>
|
loadOptions?: () => Promise<ReadonlyArray<DashboardCrudFormOption>>
|
||||||
colSpan?: 1 | 2
|
colSpan?: 1 | 2
|
||||||
rows?: number
|
rows?: number
|
||||||
|
language?: string
|
||||||
|
validateJson?: boolean
|
||||||
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
valueFromItem?: (item: TItem) => DashboardCrudFormValue
|
||||||
|
render?: (context: DashboardCrudFormCustomRenderContext) => ReactNode
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DashboardCrudActionRule<TItem> = {
|
export type DashboardCrudActionRule<TItem> = {
|
||||||
@@ -125,10 +159,10 @@ export function normalizeDashboardCrudPageResult<T>(
|
|||||||
export function buildDashboardCrudFormValues<TItem>(
|
export function buildDashboardCrudFormValues<TItem>(
|
||||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||||
item?: TItem | null
|
item?: TItem | null
|
||||||
): Record<string, string> {
|
): Record<string, DashboardCrudFormInputValue> {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
fields.map((field) => {
|
fields.map((field) => {
|
||||||
let value: unknown = field.defaultValue ?? ""
|
let value: unknown = field.defaultValue ?? getDashboardCrudFormDefaultValue(field)
|
||||||
if (item) {
|
if (item) {
|
||||||
if (field.valueFromItem) {
|
if (field.valueFromItem) {
|
||||||
value = field.valueFromItem(item)
|
value = field.valueFromItem(item)
|
||||||
@@ -136,20 +170,40 @@ export function buildDashboardCrudFormValues<TItem>(
|
|||||||
value = (item as Record<string, unknown>)[field.name]
|
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>(
|
export function normalizeDashboardCrudSubmitValues<TItem>(
|
||||||
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
fields: ReadonlyArray<DashboardCrudFormField<TItem>>,
|
||||||
values: Record<string, string>
|
values: Record<string, DashboardCrudFormInputValue>
|
||||||
): Record<string, string | number> {
|
): Record<string, string | number | boolean | string[] | number[]> {
|
||||||
const output: Record<string, string | number> = {}
|
const output: Record<string, string | number | boolean | string[] | number[]> = {}
|
||||||
|
|
||||||
fields.forEach((field) => {
|
fields.forEach((field) => {
|
||||||
const rawValue = values[field.name] ?? ""
|
if (field.type === "section" || field.type === "group") {
|
||||||
const text = field.trim ? rawValue.trim() : rawValue
|
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") {
|
if (field.type === "number" || field.valueType === "number") {
|
||||||
const numberValue = Number(text)
|
const numberValue = Number(text)
|
||||||
output[field.name] = Number.isFinite(numberValue) ? numberValue : 0
|
output[field.name] = Number.isFinite(numberValue) ? numberValue : 0
|
||||||
@@ -161,6 +215,37 @@ export function normalizeDashboardCrudSubmitValues<TItem>(
|
|||||||
return output
|
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>(
|
export function isDashboardCrudActionVisible<TItem>(
|
||||||
action: DashboardCrudActionRule<TItem>,
|
action: DashboardCrudActionRule<TItem>,
|
||||||
item: TItem
|
item: TItem
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ export type {
|
|||||||
} from "./dashboard-crud-page"
|
} from "./dashboard-crud-page"
|
||||||
export type {
|
export type {
|
||||||
DashboardCrudFormField,
|
DashboardCrudFormField,
|
||||||
|
DashboardCrudFormInputValue,
|
||||||
|
DashboardCrudFormOption,
|
||||||
|
DashboardCrudFormValue,
|
||||||
DashboardCrudFilterStateConfig,
|
DashboardCrudFilterStateConfig,
|
||||||
DashboardCrudPageResult,
|
DashboardCrudPageResult,
|
||||||
DashboardCrudQueryFilter,
|
DashboardCrudQueryFilter,
|
||||||
|
|||||||
Reference in New Issue
Block a user