Skip to content

Commit

Permalink
fix: editor
Browse files Browse the repository at this point in the history
  • Loading branch information
yongenaelf committed Jul 28, 2024
1 parent ceda335 commit 1ce924c
Showing 1 changed file with 13 additions and 28 deletions.
41 changes: 13 additions & 28 deletions components/workspace/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import React, { useEffect, useMemo } from "react";
import React, { useMemo } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { csharp } from "@replit/codemirror-lang-csharp";
import { githubLight, githubDark } from "@uiw/codemirror-theme-github";
Expand All @@ -11,9 +11,9 @@ import { getLang, Languages } from "./editor-enum";
import { xml } from "@codemirror/legacy-modes/mode/xml";
import { usePathname, useSearchParams } from "next/navigation";
import { db } from "@/data/db";
import { useDebounce } from "use-debounce";
import useSWR from "swr";

export default function Editor({ defaultValue }: { defaultValue?: string }) {
export default function Editor() {
const path = usePathname();
const params = useSearchParams();
const file = params.get("file");
Expand All @@ -24,8 +24,10 @@ export default function Editor({ defaultValue }: { defaultValue?: string }) {
const currentTheme = theme !== "system" ? theme : systemTheme;
const editorTheme = currentTheme === "light" ? githubLight : githubDark;

const [value, setValue] = React.useState(defaultValue || "");
const [debouncedValue] = useDebounce(value, 100);
const { data: value } = useSWR(
`editor-${pathname}`,
async () => (await db.files.get(pathname))?.contents
);

const lang = getLang(pathname);

Expand All @@ -42,29 +44,12 @@ export default function Editor({ defaultValue }: { defaultValue?: string }) {
}
}, [lang]);

const onChange = React.useCallback((val: string, viewUpdate: any) => {
setValue(val);
}, []);

useEffect(() => {
(async () => {
const existing = await db.files.get(pathname);

if (existing) {
setValue(existing.contents);
} else {
if (!pathname.includes("null"))
await db.files.add({ path: pathname, contents: value });
}
})();
}, [pathname]);

useEffect(() => {
(async () => {
if (!pathname.includes("null"))
await db.files.update(pathname, { contents: debouncedValue });
})();
}, [debouncedValue, pathname]);
const onChange = React.useCallback(
async (val: string, viewUpdate: any) => {
await db.files.update(pathname, { contents: val });
},
[pathname]
);

return (
<div className="h-full overflow-auto">
Expand Down

0 comments on commit 1ce924c

Please sign in to comment.