Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add one click format button #403

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 39 additions & 2 deletions src/containers/Toolbar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from "react";
import Link from "next/link";
import { Badge, Flex, Group, Select, Text } from "@mantine/core";
import yaml from "js-yaml";
import toast from "react-hot-toast";
import { AiOutlineFullscreen } from "react-icons/ai";
import { AiFillGift } from "react-icons/ai";
import { AiOutlineFullscreen, AiFillGift, AiOutlineEdit } from "react-icons/ai";
import { BsBoxArrowUpLeft } from "react-icons/bs";
import { FiDownload } from "react-icons/fi";
import { SearchInput } from "src/components/SearchInput";
Expand Down Expand Up @@ -31,11 +31,39 @@ function fullscreenBrowser() {
}
}

function formatContent(content, format) {
try {
switch (format) {
case FileFormat.JSON:
return JSON.stringify(JSON.parse(content), null, 2);
case FileFormat.YAML:
return yaml.dump(yaml.load(content));
case FileFormat.XML:
return content.replace(/(>)(<)(\/*)/g, "$1\n$2$3");
case FileFormat.TOML:
return content;
case FileFormat.CSV:
return content;
default:
return content;
}
} catch (e) {
toast.error(`Failed to format as ${format}.`);
return content;
}
}

export const Toolbar: React.FC<{ isWidget?: boolean }> = ({ isWidget = false }) => {
const setVisible = useModal(state => state.setVisible);
const setFormat = useFile(state => state.setFormat);
const format = useFile(state => state.format);
const premium = useUser(state => state.premium);
const { contents: json, setContents: setJson } = useFile();

const handleFormat = async () => {
const formattedContent = formatContent(json, format);
setJson({ contents: formattedContent });
};

return (
<Styles.StyledTools>
Expand Down Expand Up @@ -74,6 +102,15 @@ export const Toolbar: React.FC<{ isWidget?: boolean }> = ({ isWidget = false })
</Group>
)}
<Group gap="xs" justify="right" w="100%" style={{ flexWrap: "nowrap" }}>
{!premium && !isWidget && (
<Styles.StyledToolElement onClick={handleFormat}>
<Text display="flex" c="blue" fz="xs" fw={600} style={{ textAlign: "center", gap: 4 }}>
<AiOutlineEdit size="18" />
Format
</Text>
</Styles.StyledToolElement>
)}

{!premium && !isWidget && (
<Styles.StyledToolElement onClick={() => setVisible("premium")(true)}>
<Text display="flex" c="teal" fz="xs" fw={600} style={{ textAlign: "center", gap: 4 }}>
Expand Down