|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { Button } from "@/components/ui/button"; |
| 4 | +import { |
| 5 | + Dialog, |
| 6 | + DialogContent, |
| 7 | + DialogDescription, |
| 8 | + DialogFooter, |
| 9 | + DialogHeader, |
| 10 | + DialogTitle, |
| 11 | + DialogTrigger, |
| 12 | +} from "@/components/ui/dialog"; |
| 13 | +import { Textarea } from "@/components/ui/textarea"; |
| 14 | +import { useFormBuilderStore } from "@/stores/form-builder-store"; |
| 15 | +import { useState } from "react"; |
| 16 | +import { FormRow } from "@/types/form-builder.types"; |
| 17 | +import { FormComponentModel } from "@/models/FormComponent"; |
| 18 | + |
| 19 | +export function OpenJsonDialog() { |
| 20 | + const [open, setOpen] = useState(false); |
| 21 | + const [jsonInput, setJsonInput] = useState(""); |
| 22 | + const [error, setError] = useState<string | null>(null); |
| 23 | + const updateRows = useFormBuilderStore((state) => state.updateRows); |
| 24 | + |
| 25 | + const handleSubmit = () => { |
| 26 | + try { |
| 27 | + const parsedJson = JSON.parse(jsonInput); |
| 28 | + |
| 29 | + // Validate the structure |
| 30 | + if (!Array.isArray(parsedJson)) { |
| 31 | + throw new Error("JSON must be an array of rows"); |
| 32 | + } |
| 33 | + |
| 34 | + // Convert the parsed JSON into FormRow objects |
| 35 | + const rows: FormRow[] = parsedJson.map((row, index) => ({ |
| 36 | + id: index + 1, |
| 37 | + components: row.components.map((comp: any) => new FormComponentModel(comp)) |
| 38 | + })); |
| 39 | + |
| 40 | + updateRows(rows); |
| 41 | + setOpen(false); |
| 42 | + setError(null); |
| 43 | + } catch (err) { |
| 44 | + setError(err instanceof Error ? err.message : "Invalid JSON format"); |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + return ( |
| 49 | + <Dialog open={open} onOpenChange={setOpen}> |
| 50 | + <DialogTrigger asChild> |
| 51 | + <Button variant="outline" size="sm"> |
| 52 | + Load JSON |
| 53 | + </Button> |
| 54 | + </DialogTrigger> |
| 55 | + <DialogContent className="w-full lg:max-w-4xl"> |
| 56 | + <DialogHeader> |
| 57 | + <DialogTitle>Open Form JSON</DialogTitle> |
| 58 | + <DialogDescription> |
| 59 | + Paste your form JSON code here. The JSON should be an array of rows with components. |
| 60 | + </DialogDescription> |
| 61 | + </DialogHeader> |
| 62 | + <div className="min-h-[500px] w-full overflow-y-auto flex flex-col gap-4"> |
| 63 | + <Textarea |
| 64 | + value={jsonInput} |
| 65 | + onChange={(e) => setJsonInput(e.target.value)} |
| 66 | + placeholder="Paste your JSON here..." |
| 67 | + className="h-full font-mono text-sm bg-primary text-white" |
| 68 | + /> |
| 69 | + {error && ( |
| 70 | + <div className="text-sm text-red-500"> |
| 71 | + {error} |
| 72 | + </div> |
| 73 | + )} |
| 74 | + </div> |
| 75 | + <DialogFooter> |
| 76 | + <Button onClick={handleSubmit} variant="outline">Load JSON</Button> |
| 77 | + </DialogFooter> |
| 78 | + </DialogContent> |
| 79 | + </Dialog> |
| 80 | + ); |
| 81 | +} |
0 commit comments