Skip to content

Commit

Permalink
refactor(web): style code update style on blur (#1159)
Browse files Browse the repository at this point in the history
  • Loading branch information
airslice authored Oct 1, 2024
1 parent 16722ac commit b00aca9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CodeInput } from "@reearth/beta/lib/reearth-ui";
import { LayerStyle } from "@reearth/services/api/layerStyleApi/utils";
import { styled } from "@reearth/services/theme";
import { SetStateAction } from "jotai";
import { Dispatch, FC, useCallback, useEffect, useState } from "react";
import { Dispatch, FC, useCallback, useEffect, useRef, useState } from "react";

import NoStyleMessage from "../NoStyleMessage";

Expand All @@ -13,36 +13,34 @@ type CodeProps = {

const StyleCode: FC<CodeProps> = ({ layerStyle, setLayerStyle }) => {
const [styleCode, setStyleCode] = useState<string | undefined>("");
const styleCodeRef = useRef<string | undefined>(styleCode);
styleCodeRef.current = styleCode;

useEffect(() => {
setStyleCode(JSON.stringify(layerStyle?.value, null, 2));
}, [layerStyle]);

const handleStyleCodeChange = useCallback(
(newStyleCode?: string) => {
try {
const parsedStyle = JSON.parse(newStyleCode || "");
setLayerStyle((prev) => {
if (!prev?.id) return prev;
return {
...prev,
value: parsedStyle
};
});
} catch (_error) {
// Do nothing
}

setStyleCode(newStyleCode);
},
[setLayerStyle]
);
const updateStyle = useCallback(() => {
try {
const parsedStyle = JSON.parse(styleCodeRef.current || "");
setLayerStyle((prev) => {
if (!prev?.id) return prev;
return {
...prev,
value: parsedStyle
};
});
} catch (_error) {
// Do nothing
}
}, [setLayerStyle]);

return layerStyle?.id ? (
<CodeWrapper>
<CodeInput
value={styleCode}
onChange={handleStyleCodeChange}
onChange={setStyleCode}
onBlur={updateStyle}
language="json"
showLines={false}
/>
Expand Down
3 changes: 2 additions & 1 deletion web/src/beta/lib/reearth-ui/components/CodeInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ export const CodeInput: FC<CodeInputProps> = ({
},
scrollbar: {
horizontal: "hidden"
}
},
tabSize: 2
}),
[disabled, showLines]
);
Expand Down

0 comments on commit b00aca9

Please sign in to comment.