({ projectId, projectIdRef }: UseFileTreeOptions)
| 8 | } |
| 9 | |
| 10 | export function useFileTree({ projectId, projectIdRef }: UseFileTreeOptions) { |
| 11 | const [projectDir, setProjectDir] = useState<string | null>(null); |
| 12 | const [fileTree, setFileTree] = useState<string[]>([]); |
| 13 | const [compositionPaths, setCompositionPaths] = useState<string[]>([]); |
| 14 | const [fileTreeLoaded, setFileTreeLoaded] = useState(false); |
| 15 | |
| 16 | // eslint-disable-next-line no-restricted-syntax |
| 17 | useEffect(() => { |
| 18 | if (!projectId) { |
| 19 | setFileTreeLoaded(false); |
| 20 | return; |
| 21 | } |
| 22 | let cancelled = false; |
| 23 | setFileTreeLoaded(false); |
| 24 | fetch(`/api/projects/${projectId}`) |
| 25 | .then((r) => r.json()) |
| 26 | .then((data: { files?: string[]; dir?: string; compositions?: string[] }) => { |
| 27 | if (!cancelled && data.files) setFileTree(data.files); |
| 28 | if (!cancelled && data.compositions) setCompositionPaths(data.compositions); |
| 29 | if (!cancelled) setProjectDir(typeof data.dir === "string" ? data.dir : null); |
| 30 | }) |
| 31 | .catch(() => { |
| 32 | if (!cancelled) setProjectDir(null); |
| 33 | }) |
| 34 | .finally(() => { |
| 35 | if (!cancelled) setFileTreeLoaded(true); |
| 36 | }); |
| 37 | return () => { |
| 38 | cancelled = true; |
| 39 | }; |
| 40 | }, [projectId]); |
| 41 | |
| 42 | const refreshFileTree = useCallback(async () => { |
| 43 | const pid = projectIdRef.current; |
| 44 | if (!pid) return; |
| 45 | const res = await fetch(`/api/projects/${pid}`); |
| 46 | const data = await res.json(); |
| 47 | if (data.files) setFileTree(data.files); |
| 48 | }, [projectIdRef]); |
| 49 | |
| 50 | const compositions = compositionPaths; |
| 51 | |
| 52 | const assets = useMemo( |
| 53 | () => |
| 54 | fileTree.filter((f) => !f.endsWith(".html") && !f.endsWith(".md") && !f.endsWith(".json")), |
| 55 | [fileTree], |
| 56 | ); |
| 57 | |
| 58 | const fontAssets = useMemo<ImportedFontAsset[]>( |
| 59 | () => |
| 60 | assets |
| 61 | .filter((asset) => FONT_EXT.test(asset)) |
| 62 | .map((asset) => ({ |
| 63 | family: fontFamilyFromAssetPath(asset), |
| 64 | path: asset, |
| 65 | url: `/api/projects/${projectId}/preview/${asset}`, |
| 66 | })), |
| 67 | [assets, projectId], |
no test coverage detected