feat: add copy JSON value

This commit is contained in:
Francisco Veiras 2025-06-27 17:30:30 -03:00
commit d6864b8c71

View file

@ -5,6 +5,8 @@ import JsonEditor from "./JsonEditor";
import { updateValueAtPath } from "@/utils/jsonUtils"; import { updateValueAtPath } from "@/utils/jsonUtils";
import { generateDefaultValue } from "@/utils/schemaUtils"; import { generateDefaultValue } from "@/utils/schemaUtils";
import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils"; import type { JsonValue, JsonSchemaType } from "@/utils/jsonUtils";
import { useToast } from "@/lib/hooks/useToast";
import { CheckCheck, Copy } from "lucide-react";
interface DynamicJsonFormProps { interface DynamicJsonFormProps {
schema: JsonSchemaType; schema: JsonSchemaType;
@ -31,6 +33,9 @@ const DynamicJsonForm = ({
const isOnlyJSON = !isSimpleObject(schema); const isOnlyJSON = !isSimpleObject(schema);
const [isJsonMode, setIsJsonMode] = useState(isOnlyJSON); const [isJsonMode, setIsJsonMode] = useState(isOnlyJSON);
const [jsonError, setJsonError] = useState<string>(); const [jsonError, setJsonError] = useState<string>();
const [copiedJson, setCopiedJson] = useState<boolean>(false);
const { toast } = useToast();
// Store the raw JSON string to allow immediate feedback during typing // Store the raw JSON string to allow immediate feedback during typing
// while deferring parsing until the user stops typing // while deferring parsing until the user stops typing
const [rawJsonValue, setRawJsonValue] = useState<string>( const [rawJsonValue, setRawJsonValue] = useState<string>(
@ -246,19 +251,55 @@ const DynamicJsonForm = ({
} }
}, [shouldUseJsonMode, isJsonMode]); }, [shouldUseJsonMode, isJsonMode]);
const handleCopyJson = useCallback(() => {
try {
navigator.clipboard
.writeText(JSON.stringify(value, null, 2) ?? "[]")
.then(() => {
setCopiedJson(true);
toast({
title: "JSON copied",
description:
"The JSON data has been successfully copied to your clipboard.",
});
setTimeout(() => {
setCopiedJson(false);
}, 2000);
})
.catch((error) => {
reportError(error);
});
} catch (error) {
reportError(error);
}
}, [toast, value]);
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="flex justify-end space-x-2"> <div className="flex justify-end space-x-2">
{isJsonMode && ( {isJsonMode && (
<Button <>
type="button" <Button variant="outline" size="sm" onClick={handleCopyJson}>
variant="outline" {copiedJson ? (
size="sm" <CheckCheck className="h-4 w-4 mr-2" />
onClick={formatJson} ) : (
> <Copy className="h-4 w-4 mr-2" />
Format JSON )}
</Button> Copy JSON
</Button>
<Button
type="button"
variant="outline"
size="sm"
onClick={formatJson}
>
Format JSON
</Button>
</>
)} )}
{!isOnlyJSON && ( {!isOnlyJSON && (
<Button variant="outline" size="sm" onClick={handleSwitchToFormMode}> <Button variant="outline" size="sm" onClick={handleSwitchToFormMode}>
{isJsonMode ? "Switch to Form" : "Switch to JSON"} {isJsonMode ? "Switch to Form" : "Switch to JSON"}