feat: add JSON Formatter tool component

- Introduced a new JSON Formatter tool for formatting and validating JSON input.
- Added functionality for minifying and prettifying JSON.
- Updated tools list to include the new JSON Formatter with appropriate icon and description.
This commit is contained in:
typist
2025-10-28 03:41:26 +08:00
parent cd9e0c1f66
commit 9009b9a1c6
2 changed files with 68 additions and 1 deletions

View File

@@ -1,7 +1,8 @@
import type { ReactNode } from 'react';
import { Hash } from 'lucide-react'
import { FileJson, Hash } from 'lucide-react'
import UUID from './uuid'
import JSON from './json'
export interface Tool {
path: string;
@@ -18,5 +19,12 @@ export const tools: Tool[] = [
description: "Generate a UUID",
icon: <Hash />,
component: <UUID />,
},
{
path: "json",
name: "JSON Formatter",
description: "Format and validate JSON",
icon: <FileJson />,
component: <JSON />,
}
];

View File

@@ -0,0 +1,59 @@
import { useState, type FC } from "react";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
const Tool: FC = () => {
const [json, setJson] = useState<string>("");
const [error, setError] = useState<string>("");
const validateJson = () => {
try {
JSON.parse(json);
setError("");
return true;
} catch (error: unknown) {
if (error instanceof Error) {
setError(error.message);
} else {
setError("Invalid JSON");
}
return false;
}
};
const minifyJson = () => {
if (!validateJson()) return;
const formattedJson = JSON.stringify(JSON.parse(json), null, 0);
setJson(formattedJson);
};
const prettifyJson = () => {
if (!validateJson()) return;
const formattedJson = JSON.stringify(JSON.parse(json), null, 2);
setJson(formattedJson);
};
return (
<div className="h-full flex flex-col gap-4">
<Textarea className="flex-1 w-full resize-none" placeholder="Enter your JSON here" value={json} onChange={(e) => {
setJson(e.target.value);
setError("");
}} />
<div className="flex flex-row gap-2">
<Button onClick={validateJson}>Validate</Button>
<Button onClick={minifyJson}>Minify</Button>
<Button onClick={prettifyJson}>Pretty</Button>
</div>
{error && (
<Alert variant="destructive">
<AlertTitle>Error</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
</div>
);
};
export default Tool;