metis-desk/modules/companies/src/web/access/shared/ui/access-field-control.tsx

118 lines
3.0 KiB
TypeScript
Raw Normal View History

import type { SelectAction } from "@repo/rdx-ui/components/select-with-action";
import { SelectWithAction } from "@repo/rdx-ui/components/select-with-action";
import { SwitchField } from "@repo/rdx-ui/components/switch-field";
import { Input } from "@repo/shadcn-ui/components/input";
import { Label } from "@repo/shadcn-ui/components/label";
import { Textarea } from "@repo/shadcn-ui/components/textarea";
import type { UseFormReturn } from "react-hook-form";
import { useTranslation } from "react-i18next";
import type { AccessField, AccessFormValues } from "../helpers";
import type { Option } from "../types";
2026-10-08 12:14:01 +00:00
import { PermissionsControl } from "./permissions-control";
export function AccessFieldControl({
field,
id,
form,
value,
options,
disabled,
onSelected,
onCreate,
createDisabled = false,
createLabel,
}: {
field: AccessField;
id: string;
form: UseFormReturn<AccessFormValues>;
value: string | boolean | string[] | undefined;
options: readonly Option[];
disabled: boolean;
onSelected: (value: string) => void;
onCreate?: (() => void) | undefined;
createDisabled?: boolean;
createLabel?: string | undefined;
}) {
const { t } = useTranslation("access");
2026-10-10 10:01:58 +00:00
if (field.type === "boolean") {
return (
<SwitchField
checked={Boolean(value)}
disabled={disabled}
id={id}
label={t(field.key)}
onCheckedChange={(checked) => form.setValue(field.key, checked)}
/>
);
}
if (field.type === "permissions") {
return (
<PermissionsControl
fieldKey={field.key}
form={form}
id={id}
options={options}
value={value}
/>
);
}
2026-10-10 10:01:58 +00:00
return (
<div className="space-y-2">
<Label htmlFor={id}>
{t(field.key)}
{field.required ? "" : t("optional")}
</Label>
{field.type === "note" ? (
<Textarea id={id} maxLength={4000} rows={4} {...form.register(field.key)} />
) : field.type === "select" ? (
<SelectWithAction
action={selectAction(
onCreate,
createDisabled,
createLabel ?? t(quickAddLabel(field.key))
)}
disabled={disabled}
id={id}
label={t(field.key)}
onValueChange={onSelected}
options={options}
placeholder={t("choose")}
value={stringValue(value)}
/>
) : (
<Input
id={id}
maxLength={field.key === "name" ? 100 : 255}
required={field.required}
type={field.type === "date" ? "date" : "text"}
{...form.register(field.key)}
/>
)}
</div>
);
}
function stringValue(value: string | boolean | string[] | undefined) {
return typeof value === "string" ? value : "";
}
function quickAddLabel(key: string) {
return key === "systemId" ? "quickAddSystem" : "quickAddEnvironment";
}
2026-10-08 12:14:01 +00:00
function selectAction(
onClick: (() => void) | undefined,
disabled: boolean,
label: string
): SelectAction | undefined {
if (!onClick) {
return undefined;
}
2026-10-10 10:01:58 +00:00
return { onClick, disabled, label };
}