add option to disable autoformat

This commit is contained in:
Aykut Saraç 2022-02-16 15:30:13 +03:00
parent f1450c7953
commit 89720cc828
4 changed files with 38 additions and 12 deletions

View File

@ -3,7 +3,12 @@ import Link from "next/link";
import styled from "styled-components";
import { useLocalStorage } from "usehooks-ts";
import { FaFileImport } from "react-icons/fa";
import { MdUnfoldMore, MdUnfoldLess } from "react-icons/md";
import {
MdUnfoldMore,
MdUnfoldLess,
MdAutoFixHigh,
MdOutlineAutoFixOff,
} from "react-icons/md";
import {
AiFillHome,
AiOutlineClear,
@ -118,7 +123,7 @@ const Sidebar: React.FC<{
if (e.target.files) setJsonFile(e.target.files?.item(0));
};
const toggle = (setting: "expand" | "controls") => {
const toggle = (setting: "expand" | "controls" | "autoformat") => {
setConfig((c) => ({
...c,
[setting]: !c[setting],
@ -147,12 +152,17 @@ const Sidebar: React.FC<{
</StyledLogo>
</StyledElement>
</Link>
<StyledElement title="Home">
<Link href="/">
<a>
<AiFillHome />
</a>
</Link>
<Link href="/">
<StyledElement as="a" title="Home">
<AiFillHome />
</StyledElement>
</Link>
<StyledElement
as="a"
title="Auto Format"
onClick={() => toggle("autoformat")}
>
{config.autoformat ? <MdAutoFixHigh /> : <MdOutlineAutoFixOff />}
</StyledElement>
<StyledElement
as="a"

View File

@ -39,4 +39,5 @@ export const defaultConfig: StorageConfig = {
layout: "LEFT",
expand: true,
controls: true,
autoformat: true,
};

View File

@ -1,7 +1,10 @@
import dynamic from "next/dynamic";
import React, { ComponentType } from "react";
import dynamic from "next/dynamic";
import { IAceEditorProps } from "react-ace";
import toast from "react-hot-toast";
import { StorageConfig } from "src/typings/global";
import { useLocalStorage } from "usehooks-ts";
import { defaultConfig } from "src/constants/data";
function isJson(value: string) {
value = typeof value !== "string" ? JSON.stringify(value) : value;
@ -36,23 +39,34 @@ const JsonEditor: React.FC<{
json: string;
setJson: React.Dispatch<React.SetStateAction<string>>;
}> = ({ json, setJson }) => {
const [config] = useLocalStorage<StorageConfig>("config", defaultConfig);
const [value, setValue] = React.useState(
JSON.stringify(JSON.parse(json), null, 2)
);
React.useEffect(() => {
setValue(JSON.stringify(JSON.parse(json), null, 2));
if (config.autoformat) {
return setValue(JSON.stringify(JSON.parse(json), null, 2));
}
setValue(json);
}, [json]);
React.useEffect(() => {
const formatTimer = setTimeout(() => {
if (!isJson(value)) return;
setValue(JSON.stringify(JSON.parse(value), null, 2));
if (config.autoformat) {
setValue(JSON.stringify(JSON.parse(value), null, 2));
} else {
setValue(value);
}
setJson(value);
}, 2000);
return () => clearTimeout(formatTimer);
}, [value]);
}, [value, config.autoformat]);
return (
<AceEditor

View File

@ -4,4 +4,5 @@ export interface StorageConfig {
layout: CanvasDirection;
expand: boolean;
controls: boolean;
autoformat: boolean;
}