File size: 9,105 Bytes
e8a57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * File Upload Component with Drag & Drop and Preview
 * For image/file upload interfaces
 */

const { useState, useRef, useCallback, useEffect } = window.PreactLib || {};

export function FileUpload({ 
    accept = 'image/*',
    multiple = true,
    maxFiles = null,
    onFilesSelected,
    className = ''
}) {
    const html = window.html;
    const [isDragOver, setIsDragOver] = useState(false);
    const inputRef = useRef(null);

    const handleFiles = useCallback((files) => {
        const fileArray = Array.from(files);
        if (onFilesSelected) {
            onFilesSelected(fileArray);
        }
    }, [onFilesSelected]);

    const onDragOver = useCallback((e) => {
        e.preventDefault();
        setIsDragOver(true);
    }, []);

    const onDragLeave = useCallback((e) => {
        e.preventDefault();
        setIsDragOver(false);
    }, []);

    const onDrop = useCallback((e) => {
        e.preventDefault();
        setIsDragOver(false);
        handleFiles(e.dataTransfer.files);
    }, [handleFiles]);

    const onClick = () => {
        inputRef.current?.click();
    };

    const onInputChange = (e) => {
        handleFiles(e.target.files);
        // Reset input so same file can be selected again
        e.target.value = '';
    };

    return html`
        <div 
            class="border-2 border-dashed rounded-3 p-5 text-center ${isDragOver ? 'border-primary bg-primary bg-opacity-10' : 'border-secondary'} ${className}"
            onDragOver=${onDragOver}
            onDragLeave=${onDragLeave}
            onDrop=${onDrop}
            onClick=${onClick}
            style="cursor: pointer; transition: all 0.2s ease;"
        >
            <input 
                ref=${inputRef}
                type="file" 
                accept=${accept}
                multiple=${multiple}
                onChange=${onInputChange}
                style="display: none;"
            />
            <i class="bi bi-cloud-upload display-4 text-primary mb-3"></i>
            <h5 class="mb-2">Drag & Drop files here</h5>
            <p class="text-muted mb-0">or click to browse</p>
            ${accept ? html`<p class="text-muted small mt-2">Accepted: ${accept}</p>` : ''}
            ${multiple && maxFiles ? html`<p class="text-muted small">Max ${maxFiles} files</p>` : ''}
        </div>
    `;
}

// === File Preview Card ===
export function FilePreviewCard({ 
    file, 
    index, 
    onRemove, 
    onDragStart, 
    onDrop,
    onDragOver,
    isDragging = false
}) {
    const html = window.html;
    const [previewUrl, setPreviewUrl] = useState(null);

    useEffect(() => {
        if (file && file.type?.startsWith('image/')) {
            const url = URL.createObjectURL(file);
            setPreviewUrl(url);
            return () => URL.revokeObjectURL(url);
        }
    }, [file]);

    const cardClass = isDragging 
        ? 'preview-card dragging' 
        : 'preview-card';

    return html`
        <div 
            class="${cardClass}"
            draggable="true"
            data-index=${index}
            onDragStart=${(e) => onDragStart?.(e, index)}
            onDragOver=${(e) => onDragOver?.(e, index)}
            onDrop=${(e) => onDrop?.(e, index)}
        >
            ${previewUrl ? html`
                <img src=${previewUrl} class="preview-img" alt=${file.name} />
            ` : html`
                <div class="preview-img d-flex align-items-center justify-content-center bg-secondary">
                    <i class="bi bi-file-earmark display-4"></i>
                </div>
            `}
            <div class="preview-overlay">
                ${file.name}
            </div>
            <button 
                class="remove-btn"
                onClick=${(e) => {
                    e.stopPropagation();
                    onRemove?.(index);
                }}
            >
                &times;
            </button>
        </div>
    `;
}

// === File Preview Grid ===
export function FilePreviewGrid({ 
    files = [], 
    onFilesChange,
    sortable = true,
    className = ''
}) {
    const html = window.html;
    const [draggedIndex, setDraggedIndex] = useState(null);

    if (files.length === 0) return null;

    const removeFile = (index) => {
        const newFiles = files.filter((_, i) => i !== index);
        onFilesChange?.(newFiles);
    };

    const handleDragStart = (e, index) => {
        if (!sortable) return;
        setDraggedIndex(index);
        e.target.classList.add('dragging');
    };

    const handleDragOver = (e, index) => {
        if (!sortable || draggedIndex === null) return;
        e.preventDefault();
        if (draggedIndex !== index) {
            e.currentTarget.classList.add('drag-over');
        }
    };

    const handleDragLeave = (e) => {
        e.currentTarget.classList.remove('drag-over');
    };

    const handleDrop = (e, dropIndex) => {
        if (!sortable || draggedIndex === null) return;
        e.preventDefault();
        e.currentTarget.classList.remove('drag-over');

        if (draggedIndex !== dropIndex) {
            const newFiles = [...files];
            const [draggedFile] = newFiles.splice(draggedIndex, 1);
            newFiles.splice(dropIndex, 0, draggedFile);
            onFilesChange?.(newFiles);
        }
        setDraggedIndex(null);
    };

    const handleDragEnd = (e) => {
        e.target.classList.remove('dragging');
        setDraggedIndex(null);
        document.querySelectorAll('.drag-over').forEach(el => {
            el.classList.remove('drag-over');
        });
    };

    return html`
        <div class="row g-3 ${className}">
            ${files.map((file, index) => html`
                <div class="col-6 col-md-4 col-lg-3">
                    <${FilePreviewCard} 
                        file=${file}
                        index=${index}
                        onRemove=${removeFile}
                        onDragStart=${handleDragStart}
                        onDragOver=${handleDragOver}
                        onDrop=${handleDrop}
                        isDragging=${draggedIndex === index}
                    />
                </div>
            `)}
        </div>
    `;
}

// === Complete Upload Interface ===
export function UploadInterface({ 
    accept = 'image/*',
    multiple = true,
    maxFiles = null,
    onUpload,
    className = ''
}) {
    const html = window.html;
    const [files, setFiles] = useState([]);
    const [isUploading, setIsUploading] = useState(false);
    const [status, setStatus] = useState(null);

    const handleFilesSelected = (newFiles) => {
        if (maxFiles && files.length + newFiles.length > maxFiles) {
            setStatus({
                type: 'danger',
                message: `Maximum ${maxFiles} files allowed`
            });
            return;
        }
        setFiles([...files, ...newFiles]);
        setStatus(null);
    };

    const handleUpload = async () => {
        if (files.length === 0) return;

        setIsUploading(true);
        setStatus({ type: 'info', message: `Uploading ${files.length} files...` });

        try {
            if (onUpload) {
                await onUpload(files);
            }
            setStatus({ type: 'success', message: 'Upload successful!' });
            setFiles([]);
        } catch (error) {
            setStatus({ type: 'danger', message: `Upload failed: ${error.message}` });
        } finally {
            setIsUploading(false);
        }
    };

    return html`
        <div class="${className}">
            <${FileUpload} 
                accept=${accept}
                multiple=${multiple}
                onFilesSelected=${handleFilesSelected}
                className="mb-4"
            />

            ${files.length > 0 ? html`
                <>
                    <h6 class="text-white-50 border-bottom border-secondary pb-2 mb-3">
                        Preview ${sortable ? html`<span class="small">(Drag to reorder)</span>` : ''}
                    </h6>
                    <${FilePreviewGrid} 
                        files=${files}
                        onFilesChange=${setFiles}
                        sortable=${sortable}
                        className="mb-4"
                    />
                </>
            ` : ''}

            ${status ? html`
                <div class="alert alert-${status.type} alert-dismissible fade show" role="alert">
                    ${status.message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            ` : ''}

            ${files.length > 0 ? html`
                <${Button} 
                    variant="success" 
                    size="lg"
                    className="w-100 py-3"
                    onClick=${handleUpload}
                    loading=${isUploading}
                >
                    ${isUploading ? 'Uploading...' : `Upload ${files.length} File${files.length > 1 ? 's' : ''}`}
                </${Button}>
            ` : ''}
        </div>
    `;
}

export default FileUpload;