File size: 4,574 Bytes
c89a5a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import Editor from "@monaco-editor/react";
import { useEditor } from "@/hooks/useEditor";

const TEXT_EXT = ["js","ts","tsx","jsx","json","md","css","html","txt","mjs","cjs","tsconfig","eslintrc","prettierrc"];
function isTextFile(path: string) {
  const ext = (path.split('.').pop() || '').toLowerCase();
  return TEXT_EXT.includes(ext) || path.endsWith('.d.ts');
}

export function FilesExplorerButton() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button size="xs" variant="outline" className="!rounded-md" onClick={() => setOpen(true)}>Files</Button>
      {open && <FilesExplorer open={open} onClose={() => setOpen(false)} />}
    </>
  );
}

function FilesExplorer({ open, onClose }: { open: boolean; onClose: () => void }) {
  const { project } = useEditor();
  const space = project?.space_id || '';
  const [namespace, repoId] = space.split('/');
  const [paths, setPaths] = useState<{ path: string; type: string }[]>([]);
  const [selected, setSelected] = useState<string | null>(null);
  const [content, setContent] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);

  const canSave = useMemo(() => !!selected && isTextFile(selected!), [selected]);

  useEffect(() => {
    (async () => {
      if (!namespace || !repoId) return;
      const res = await fetch(`/api/me/projects/${namespace}/${repoId}/files`);
      const data = await res.json();
      if (data?.ok) setPaths(data.paths || []);
    })();
  }, [namespace, repoId]);

  const openFile = async (p: string) => {
    setSelected(p);
    setContent('');
    setLoading(true);
    try {
      if (isTextFile(p)) {
        const res = await fetch(`/api/me/projects/${namespace}/${repoId}/file?path=${encodeURIComponent(p)}`);
        const data = await res.json();
        if (data?.ok) setContent(data.content || '');
      }
    } finally {
      setLoading(false);
    }
  };

  const saveFile = async () => {
    if (!selected) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/me/projects/${namespace}/${repoId}/apply`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ files: [{ path: selected, action: 'update', content }], commitTitle: `Edit ${selected}` })
      });
      await res.json();
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={() => onClose()}>
      <DialogContent className="sm:max-w-5xl !bg-neutral-900 !border-neutral-800">
        <DialogHeader>
          <DialogTitle className="text-neutral-100">Project Files</DialogTitle>
        </DialogHeader>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3 min-h-[420px]">
          <div className="border border-neutral-800 rounded-lg p-2 overflow-y-auto">
            <ul className="text-sm text-neutral-300">
              {paths.map(p => (
                <li key={p.path} className="py-1 px-2 rounded hover:bg-neutral-800 cursor-pointer" onClick={() => openFile(p.path)}>
                  {p.path}
                </li>
              ))}
            </ul>
          </div>
          <div className="md:col-span-2 border border-neutral-800 rounded-lg overflow-hidden relative">
            {!selected && <div className="p-4 text-neutral-400 text-sm">Select a file to preview/edit</div>}
            {selected && isTextFile(selected) && (
              <Editor
                defaultLanguage="plaintext"
                theme="vs-dark"
                value={content}
                loading={<div className="p-4 text-neutral-400 text-sm">{loading ? 'Loading…' : ''}</div>}
                onChange={(v) => setContent(v || '')}
                options={{ minimap: { enabled: false }, wordWrap: 'on' }}
              />
            )}
            {selected && !isTextFile(selected) && (
              <div className="p-4 text-neutral-400 text-sm">Binary/non-text file. Download/edit locally if needed.</div>
            )}
          </div>
        </div>
        <DialogFooter>
          <Button variant="bordered" size="sm" onClick={() => onClose()}>Close</Button>
          <Button size="sm" onClick={saveFile} disabled={!canSave || saving}>{saving ? 'Saving…' : 'Save File'}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}