All files / src/components/admin taxonomy-form.tsx

100% Statements 41/41
100% Branches 32/32
100% Functions 14/14
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                                                                    171x 171x 171x 171x   171x 60x 5x   55x 55x 189x 26x   163x     55x   60x     171x       14x     171x 7x     7x 28x 4x   7x 2x 2x     5x 5x 5x 4x   1x 1x   5x       171x   90x                                                                         348x                         1x                 1x         164x                     6x                       6x                                                    
import { useState, useEffect } from "react";
import { X } from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { GENERIC_ERROR_MESSAGE, type TaxonomyItem } from "../../lib/api";
import { useDialogAccessibility } from "../../hooks";
 
type TaxonomyFormField = {
	name: string;
	label: string;
	type: "text" | "textarea" | "select" | "number";
	required?: boolean;
	options?: Array<{ value: string; label: string }>;
	placeholder?: string;
	help?: string;
};
 
type TaxonomyFormProps = {
	isOpen: boolean;
	onClose: () => void;
	onSubmit: (data: Record<string, unknown>) => Promise<void>;
	item?: TaxonomyItem | null;
	title: string;
	fields: TaxonomyFormField[];
};
 
export function TaxonomyForm({
	isOpen,
	onClose,
	onSubmit,
	item,
	title,
	fields,
}: TaxonomyFormProps) {
	const [formData, setFormData] = useState<Record<string, unknown>>({});
	const [isSubmitting, setIsSubmitting] = useState(false);
	const [error, setError] = useState<string | null>(null);
	const { dialogRef, handleFocusTrap } = useDialogAccessibility(onClose);
 
	useEffect(() => {
		if (item) {
			setFormData(item);
		} else {
			const initialData: Record<string, unknown> = {};
			fields.forEach((field) => {
				if (field.type === "number") {
					initialData[field.name] = 0;
				} else {
					initialData[field.name] = "";
				}
			});
			setFormData(initialData);
		}
		setError(null);
	}, [item, fields]);
 
	const handleChange = (
		field: string,
		value: string | number | boolean | string[],
	) => {
		setFormData((prev) => ({ ...prev, [field]: value }));
	};
 
	const handleSubmit = async () => {
		setError(null);
 
		// Validate required fields
		const missingFields = fields
			.filter((field) => field.required && !formData[field.name])
			.map((field) => field.label);
 
		if (missingFields.length > 0) {
			setError(`Please fill in required fields: ${missingFields.join(", ")}`);
			return;
		}
 
		setIsSubmitting(true);
		try {
			await onSubmit(formData);
			onClose();
		} catch (err) {
			console.error("Failed to submit form:", err);
			setError(GENERIC_ERROR_MESSAGE);
		} finally {
			setIsSubmitting(false);
		}
	};
 
	if (!isOpen) return null;
 
	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center" tabIndex={-1}>
			<button
				type="button"
				aria-label="Close modal"
				className="absolute inset-0 bg-black/50 cursor-default"
				onClick={onClose}
				tabIndex={-1}
			/>
			<div
				ref={dialogRef}
				role="dialog"
				aria-modal="true"
				aria-labelledby="taxonomy-form-dialog-title"
				onKeyDown={handleFocusTrap}
				className="relative bg-background-elevated rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden flex flex-col"
			>
				<div className="flex items-center justify-between p-4 border-b border-border-default">
					<h3 id="taxonomy-form-dialog-title" className="text-lg font-semibold">{title}</h3>
					<button
						type="button"
						onClick={onClose}
						aria-label="Close"
						className="p-1 hover:bg-background-muted rounded"
					>
						<X className="h-5 w-5" />
					</button>
				</div>
 
				<div className="flex-1 overflow-y-auto p-4 space-y-4">
					{error && (
						<div className="bg-error-light text-error px-3 py-2 rounded text-sm">
							{error}
						</div>
					)}
 
					{fields.map((field) => (
						<div key={field.name}>
							<label
								htmlFor={field.name}
								className="block text-sm font-medium text-foreground-default mb-1"
							>
								{field.label}
								{field.required && <span className="text-error ml-1">*</span>}
							</label>
 
							{field.type === "textarea" ? (
								<textarea
									id={field.name}
									value={(formData[field.name] as string) || ""}
									onChange={(e) => handleChange(field.name, e.target.value)}
									placeholder={field.placeholder}
									className="flex min-h-[80px] w-full rounded-md border border-border-default bg-background-elevated px-3 py-2 text-sm text-foreground-default placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent disabled:cursor-not-allowed disabled:opacity-50"
									rows={3}
								/>
							) : field.type === "select" ? (
								<select
									id={field.name}
									value={(formData[field.name] as string) || ""}
									onChange={(e) => handleChange(field.name, e.target.value)}
									className="h-10 w-full rounded-md border border-border-default bg-background-elevated px-3 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500"
								>
									<option value="">Select {field.label.toLowerCase()}</option>
									{field.options?.map((opt) => (
										<option key={opt.value} value={opt.value}>
											{opt.label}
										</option>
									))}
								</select>
							) : field.type === "number" ? (
								<Input
									id={field.name}
									type="number"
									value={(formData[field.name] as number) || 0}
									onChange={(e) =>
										handleChange(
											field.name,
											Number.parseInt(e.target.value, 10),
										)
									}
									placeholder={field.placeholder}
								/>
							) : (
								<Input
									id={field.name}
									type="text"
									value={(formData[field.name] as string) || ""}
									onChange={(e) => handleChange(field.name, e.target.value)}
									placeholder={field.placeholder}
								/>
							)}
 
							{field.help && (
								<p className="mt-1 text-xs text-foreground-muted">
									{field.help}
								</p>
							)}
						</div>
					))}
				</div>
 
				<div className="flex justify-end gap-2 p-4 border-t border-border-default">
					<Button variant="outline" onClick={onClose} disabled={isSubmitting}>
						Cancel
					</Button>
					<Button onClick={handleSubmit} isLoading={isSubmitting}>
						{item ? "Update" : "Create"}
					</Button>
				</div>
			</div>
		</div>
	);
}