File size: 10,888 Bytes
c2ea5ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
 * Context Document Modal Component
 *
 * Modal for viewing and editing context documents with markdown rendering support
 */

import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Edit,
  Save,
  Download,
  FileText,
  Trash2,
  X,
  Calendar,
  AlertCircle,
} from "lucide-react";
import {
  ContextDocument,
  ContextDocumentType,
  CONTEXT_DOCUMENT_TYPES,
} from "@/types/context";
import { shouldRenderAsMarkdown } from "@/lib/markdown-utils";
import Editor from "@monaco-editor/react";
import ReactMarkdown from "react-markdown";

interface ContextDocumentModalProps {
  document: ContextDocument;
  isOpen: boolean;
  onClose: () => void;
  onSave: (updates: {
    title?: string;
    content?: string;
    document_type?: ContextDocumentType;
  }) => Promise<boolean>;
  onDelete: () => Promise<boolean>;
}

export function ContextDocumentModal({
  document,
  isOpen,
  onClose,
  onSave,
  onDelete,
}: ContextDocumentModalProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editedTitle, setEditedTitle] = useState(document.title);
  const [editedContent, setEditedContent] = useState(document.content);
  const [editedType, setEditedType] = useState(document.document_type);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDirty, setIsDirty] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Update local state when document changes
  useEffect(() => {
    setEditedTitle(document.title);
    setEditedContent(document.content);
    setEditedType(document.document_type);
    setIsDirty(false);
    setError(null);
  }, [document]);

  // Check if content has changed
  useEffect(() => {
    const hasChanges =
      editedTitle !== document.title ||
      editedContent !== document.content ||
      editedType !== document.document_type;
    setIsDirty(hasChanges);
  }, [editedTitle, editedContent, editedType, document]);

  const handleEdit = () => {
    setIsEditing(true);
    setError(null);
  };

  const handleSave = async () => {
    if (!isDirty) return;

    setIsSaving(true);
    setError(null);

    try {
      const updates: any = {};
      if (editedTitle !== document.title) updates.title = editedTitle;
      if (editedContent !== document.content) updates.content = editedContent;
      if (editedType !== document.document_type)
        updates.document_type = editedType;

      const success = await onSave(updates);
      if (success) {
        setIsEditing(false);
        setIsDirty(false);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save document");
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    setEditedTitle(document.title);
    setEditedContent(document.content);
    setEditedType(document.document_type);
    setIsEditing(false);
    setIsDirty(false);
    setError(null);
  };

  const handleDownload = () => {
    const blob = new Blob([document.content], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = window.document.createElement("a");
    a.href = url;
    a.download = `${document.title}.${
      shouldRenderAsMarkdown(document.content, document.file_name)
        ? "md"
        : "txt"
    }`;
    window.document.body.appendChild(a);
    a.click();
    window.document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleDelete = async () => {
    if (
      !window.confirm(
        "Are you sure you want to delete this context document? This action cannot be undone."
      )
    ) {
      return;
    }

    setIsDeleting(true);
    setError(null);

    try {
      const success = await onDelete();
      if (success) {
        onClose();
      }
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Failed to delete document"
      );
    } finally {
      setIsDeleting(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("en-US", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatDocumentType = (type: ContextDocumentType) => {
    const typeConfig = CONTEXT_DOCUMENT_TYPES.find((t) => t.value === type);
    return typeConfig?.label || type.replace(/_/g, " ");
  };

  const isMarkdown = shouldRenderAsMarkdown(
    document.content,
    document.file_name
  );

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader className="space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2 flex-1 min-w-0">
              <FileText className="h-5 w-5 text-primary" />
              {isEditing ? (
                <Input
                  value={editedTitle}
                  onChange={(e) => setEditedTitle(e.target.value)}
                  className="text-lg font-semibold"
                  placeholder="Document title"
                />
              ) : (
                <DialogTitle className="truncate">{document.title}</DialogTitle>
              )}
            </div>

            <div className="flex items-center gap-2">
              {!isEditing ? (
                <>
                  <Button variant="outline" size="sm" onClick={handleEdit}>
                    <Edit className="h-4 w-4 mr-2" />
                    Edit
                  </Button>
                  <Button variant="outline" size="sm" onClick={handleDownload}>
                    <Download className="h-4 w-4 mr-2" />
                    Download
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleDelete}
                    disabled={isDeleting}
                    className="text-destructive hover:text-destructive"
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    {isDeleting ? "Deleting..." : "Delete"}
                  </Button>
                </>
              ) : (
                <>
                  <Button variant="outline" size="sm" onClick={handleCancel}>
                    <X className="h-4 w-4 mr-2" />
                    Cancel
                  </Button>
                  <Button
                    size="sm"
                    onClick={handleSave}
                    disabled={!isDirty || isSaving}
                  >
                    <Save className="h-4 w-4 mr-2" />
                    {isSaving ? "Saving..." : "Save"}
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* Document metadata */}
          <div className="flex flex-wrap gap-2 text-sm">
            {isEditing ? (
              <div className="flex items-center gap-2">
                <Label htmlFor="document-type">Type:</Label>
                <Select
                  value={editedType}
                  onValueChange={(value: ContextDocumentType) =>
                    setEditedType(value)
                  }
                >
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {CONTEXT_DOCUMENT_TYPES.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            ) : (
              <Badge variant="outline" className="flex items-center gap-1">
                <FileText className="h-3 w-3" />
                {formatDocumentType(document.document_type)}
              </Badge>
            )}

            <Badge variant="outline" className="flex items-center gap-1">
              <Calendar className="h-3 w-3" />
              {formatDate(document.created_at)}
            </Badge>

            <Badge variant="outline">
              {document.content.length.toLocaleString()} chars
            </Badge>
          </div>

          {error && (
            <div className="flex items-center gap-2 text-destructive text-sm p-3 bg-destructive/10 rounded-lg">
              <AlertCircle className="h-4 w-4" />
              {error}
            </div>
          )}
        </DialogHeader>

        <div className="flex-1 overflow-hidden flex flex-col">
          {/* Single content area - conditional rendering based on editing state */}
          <div className="flex-1 overflow-hidden">
            {isEditing ? (
              /* Edit Mode */
              <div className="border rounded-lg h-full overflow-hidden">
                <Editor
                  height="100%"
                  defaultLanguage={isMarkdown ? "markdown" : "plaintext"}
                  value={editedContent}
                  onChange={(value) => setEditedContent(value || "")}
                  theme="vs"
                  options={{
                    minimap: { enabled: false },
                    scrollBeyondLastLine: false,
                    wordWrap: "on",
                    lineNumbers: "on",
                    folding: false,
                    renderWhitespace: "selection",
                    fontSize: 14,
                    lineHeight: 20,
                    fontFamily:
                      "'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace",
                    padding: { top: 10, bottom: 10 },
                    automaticLayout: true,
                  }}
                />
              </div>
            ) : (
              /* View Mode */
              <div className="border rounded-lg h-full overflow-auto">
                <div className="p-4">
                  {isMarkdown ? (
                    <div className="prose prose-sm max-w-none">
                      <ReactMarkdown>{document.content}</ReactMarkdown>
                    </div>
                  ) : (
                    <pre className="whitespace-pre-wrap font-mono text-sm text-foreground">
                      {document.content}
                    </pre>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}