All files / client/src/hooks useSimulatorFileSystem.ts

94.59% Statements 70/74
76.47% Branches 26/34
100% Functions 18/18
95.23% Lines 60/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                              51x   20x 20x 20x 39x 10x 10x   20x         51x   20x 13x 13x 13x 13x 13x           51x 4x 4x           4x 4x 4x 4x     51x   3x 1x         1x     4x 4x   2x 1x 1x 1x 1x                   51x   6x   13x 6x 6x                     51x   4x 3x   5x 5x 3x   5x             3x   3x 3x 3x 3x 3x     1x           1x           51x                     51x           51x         1x 1x     1x         51x                                        
import { useCallback, useMemo } from "react";
 
import { useFileManager } from "@/hooks/use-file-manager";
import { generateUuidV4 } from "@/lib/uuid";
import type { Sketch } from "@shared/schema";
import type { ToastFn } from "@/hooks/use-toast";
 
type SourceFileInput = { name: string; path?: string; content: string };
type SourceTab = { id: string; name: string; path?: string; content: string };
 
interface UseSimulatorFileSystemParams {
  code: string;
  setCode: (value: string) => void;
  isModified: boolean;
  setIsModified: (value: boolean) => void;
  tabs: SourceTab[];
  setTabs: (tabs: SourceTab[]) => void;
  activeTabId: string | null;
  setActiveTabId: (id: string | null) => void;
  initializeDefaultSketch: (sketches: Sketch[] | undefined) => void;
  toast: ToastFn;
  onReplaceAllFiles?: () => void;
  onLoadExample?: () => void;
}
 
export function useSimulatorFileSystem({
  code,
  setCode,
  isModified,
  setIsModified,
  tabs,
  setTabs,
  activeTabId,
  setActiveTabId,
  initializeDefaultSketch,
  toast,
  onReplaceAllFiles,
  onLoadExample,
}: UseSimulatorFileSystemParams) {
  const syncActiveTabContent = useCallback(
    (currentTabs: SourceTab[]) => {
      Iif (!activeTabId) return currentTabs;
      let changed = false;
      const nextTabs = currentTabs.map((tab) => {
        if (tab.id !== activeTabId || tab.content === code) return tab;
        changed = true;
        return { ...tab, content: code };
      });
      return changed ? nextTabs : currentTabs;
    },
    [activeTabId, code],
  );
 
  const handleTabClick = useCallback(
    (tabId: string) => {
      const tab = tabs.find((t) => t.id === tabId);
      Eif (tab) {
        setTabs(syncActiveTabContent(tabs));
        setActiveTabId(tabId);
        setCode(tabId === activeTabId ? code : tab.content);
        setIsModified(false);
      }
    },
    [activeTabId, code, setActiveTabId, setCode, setIsModified, setTabs, syncActiveTabContent, tabs],
  );
 
  const handleTabAdd = useCallback(() => {
    const newTabId = generateUuidV4().replaceAll("-", "").slice(0, 9);
    const newTab = {
      id: newTabId,
      name: `header_${tabs.length}.h`,
      path: `header_${tabs.length}.h`,
      content: "",
    };
    setTabs([...syncActiveTabContent(tabs), newTab]);
    setActiveTabId(newTabId);
    setCode("");
    setIsModified(false);
  }, [setTabs, setActiveTabId, setCode, setIsModified, syncActiveTabContent, tabs]);
 
  const handleTabClose = useCallback(
    (tabId: string) => {
      if (tabId === tabs[0]?.id) {
        toast({
          title: "Cannot Delete",
          description: "The main sketch file cannot be deleted",
          variant: "destructive",
        });
        return;
      }
 
      const newTabs = tabs.filter((t) => t.id !== tabId);
      setTabs(syncActiveTabContent(tabs).filter((t) => t.id !== tabId));
 
      if (activeTabId === tabId) {
        const newActiveTab = newTabs.at(-1);
        if (newActiveTab) {
          setActiveTabId(newActiveTab.id);
          setCode(newActiveTab.content);
        } else E{
          setActiveTabId(null);
          setCode("");
        }
      }
    },
    [activeTabId, setActiveTabId, setCode, setTabs, syncActiveTabContent, tabs, toast],
  );
 
  const handleTabRename = useCallback(
    (tabId: string, newName: string) => {
      setTabs(
        tabs.map((tab) => {
          if (tab.id !== tabId) return tab;
          const followsDisplayName = tab.path === tab.name;
          return {
            ...tab,
            name: newName,
            ...(followsDisplayName ? { path: newName } : {}),
          };
        }),
      );
    },
    [tabs, setTabs],
  );
 
  const handleFilesLoaded = useCallback(
    (files: SourceFileInput[], replaceAll: boolean) => {
      if (replaceAll) {
        onReplaceAllFiles?.();
 
        const inoFiles = files.filter((f) => f.name.endsWith(".ino"));
        const otherFiles = files.filter((f) => !f.name.endsWith(".ino"));
        const orderedFiles = [...inoFiles, ...otherFiles];
 
        const newTabs = orderedFiles.map((file) => ({
          id: generateUuidV4().replaceAll("-", "").slice(0, 9),
          name: file.name,
          path: file.path ?? file.name,
          content: file.content,
        }));
 
        setTabs(newTabs);
 
        const inoTab = newTabs[0];
        Eif (inoTab) {
          setActiveTabId(inoTab.id);
          setCode(inoTab.content);
          setIsModified(false);
        }
      } else {
        const newHeaderFiles = files.map((file) => ({
          id: generateUuidV4().replaceAll("-", "").slice(0, 9),
          name: file.name,
          path: file.path ?? file.name,
          content: file.content,
        }));
        setTabs([...syncActiveTabContent(tabs), ...newHeaderFiles]);
      }
    },
    [onReplaceAllFiles, setTabs, setActiveTabId, setCode, setIsModified, syncActiveTabContent, tabs],
  );
 
  const toastAdapter = useMemo(
    () => (p: { title: string; description?: string; variant?: string }) =>
      toast({
        title: p.title,
        description: p.description,
        variant: p.variant === "destructive" ? "destructive" : undefined,
      }),
    [toast],
  );
 
  const { fileInputRef, onLoadFiles, downloadAllFiles, handleHiddenFileInput } =
    useFileManager({
      tabs,
      onFilesLoaded: handleFilesLoaded,
      toast: toastAdapter,
    });
 
  const handleLoadExample = useCallback(
    (
      filesOrName: SourceFileInput[] | string,
      contentOrTitle: string,
    ) => {
      onLoadExample?.();
      const files = typeof filesOrName === "string"
        ? [{ name: filesOrName, content: contentOrTitle }]
        : filesOrName;
      handleFilesLoaded(files, true);
    },
    [handleFilesLoaded, onLoadExample],
  );
 
  return {
    code,
    setCode,
    isModified,
    setIsModified,
    tabs,
    activeTabId,
    initializeDefaultSketch,
    fileInputRef,
    onLoadFiles,
    downloadAllFiles,
    handleHiddenFileInput,
    handleTabClick,
    handleTabAdd,
    handleTabClose,
    handleTabRename,
    handleFilesLoaded,
    handleLoadExample,
  } as const;
}