File size: 1,851 Bytes
61e6dfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useProject } from "@/components/projects/useProject";
import { useMemo } from "react";

const LANGUAGE_MAP = {
  "py": "python",
  "js": "javascript",
  "ts": "typescript",
  "html": "html",
  "css": "css",
  "json": "json",
  "txt": "text",
}

export const useEditor = () => {
  const queryClient = useQueryClient();
  const { files } = useProject();

  const { data: isFileListOpen } = useQuery<boolean>({
    queryKey: ["isFileListOpen"],
    queryFn: () => {
      return false;
    },
    initialData: false,
    refetchInterval: false,
    refetchOnWindowFocus: false,
  });

  const setIsFileListOpen = (isOpen: boolean) => {
    queryClient.setQueryData<boolean>(["isFileListOpen"], () => isOpen);
  }

  const { data: editorFilePath } = useQuery<string>({
    queryKey: ["editorFile"],
    queryFn: () => {
      return "app.py";
    },
    initialData: "app.py",
    refetchInterval: false,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: false,
    refetchIntervalInBackground: false,
  });

  const setEditorFilePath = (path: string) => {
    queryClient.setQueryData<string>(["editorFile"], () => path);
  }

  const editorFileData = useMemo(() => {
    const finalFile = { path: "", content: "", language: "" };
    if (editorFilePath) {
      const file = files?.find((file) => file.path === editorFilePath);
      if (file) {
        finalFile.path = file.path;
        finalFile.content = file.content ?? "";
        finalFile.language = LANGUAGE_MAP[file.path.split(".").pop()?.toLowerCase() as keyof typeof LANGUAGE_MAP] ?? "text";
      }
    }

    return finalFile
  }, [editorFilePath, files])

  return {
    editorFilePath,
    editorFileData,
    setEditorFilePath,
    isFileListOpen,
    setIsFileListOpen,
  }
}