({
projectId,
showToast,
recordEdit,
domEditSaveTimestampRef,
setRefreshKey,
}: UseFileManagerOptions)
| 32 | // ── Hook ── |
| 33 | |
| 34 | export function useFileManager({ |
| 35 | projectId, |
| 36 | showToast, |
| 37 | recordEdit, |
| 38 | domEditSaveTimestampRef, |
| 39 | setRefreshKey, |
| 40 | }: UseFileManagerOptions) { |
| 41 | // ── Shared refs ── |
| 42 | |
| 43 | const [editingFile, setEditingFile] = useState<EditingFile | null>(null); |
| 44 | const [revealSourceOffset, setRevealSourceOffset] = useState<number | null>(null); |
| 45 | |
| 46 | const editingPathRef = useRef(editingFile?.path); |
| 47 | editingPathRef.current = editingFile?.path; |
| 48 | |
| 49 | const projectIdRef = useRef(projectId); |
| 50 | projectIdRef.current = projectId; |
| 51 | |
| 52 | const importedFontAssetsRef = useRef<ImportedFontAsset[]>([]); |
| 53 | |
| 54 | // ── File tree ── |
| 55 | |
| 56 | const { |
| 57 | projectDir, |
| 58 | fileTree, |
| 59 | setFileTree, |
| 60 | fileTreeLoaded, |
| 61 | refreshFileTree, |
| 62 | compositions, |
| 63 | assets, |
| 64 | fontAssets, |
| 65 | } = useFileTree({ projectId, projectIdRef }); |
| 66 | |
| 67 | // ── Core file I/O ── |
| 68 | |
| 69 | const readProjectFile = useCallback(async (path: string): Promise<string> => { |
| 70 | const pid = projectIdRef.current; |
| 71 | if (!pid) throw new Error("No active project"); |
| 72 | const response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`); |
| 73 | if (!response.ok) throw new Error(`Failed to read ${path}`); |
| 74 | const data = (await response.json()) as { content?: string }; |
| 75 | if (typeof data.content !== "string") throw new Error(`Missing file contents for ${path}`); |
| 76 | return data.content; |
| 77 | }, []); |
| 78 | |
| 79 | const writeProjectFile = useCallback(async (path: string, content: string): Promise<void> => { |
| 80 | const pid = projectIdRef.current; |
| 81 | if (!pid) throw new Error("No active project"); |
| 82 | await retryStudioSave(async () => { |
| 83 | let response: Response; |
| 84 | try { |
| 85 | response = await fetch(`/api/projects/${pid}/files/${encodeURIComponent(path)}`, { |
| 86 | method: "PUT", |
| 87 | headers: { "Content-Type": "text/plain" }, |
| 88 | body: content, |
| 89 | }); |
| 90 | } catch (error) { |
| 91 | throw new StudioSaveNetworkError(`Failed to save ${path}: network error`, { |
no test coverage detected