Spaces:
Sleeping
Sleeping
Delete app.js
Browse files
app.js
DELETED
|
@@ -1,1122 +0,0 @@
|
|
| 1 |
-
// DocVault — Offline-First Document Storage System
|
| 2 |
-
// Uses local Flask backend for all operations
|
| 3 |
-
|
| 4 |
-
const API_BASE = '/api';
|
| 5 |
-
const USER_ID = 'default_user';
|
| 6 |
-
const DEFAULT_FOLDER = '';
|
| 7 |
-
|
| 8 |
-
const STARRED_KEY = 'docvault_starred';
|
| 9 |
-
const RECENT_KEY = 'docvault_recent';
|
| 10 |
-
|
| 11 |
-
// ─── API HELPERS ──────────────────────────────────────────
|
| 12 |
-
const API_HEADERS = {
|
| 13 |
-
'X-User-ID': USER_ID,
|
| 14 |
-
'Content-Type': 'application/json'
|
| 15 |
-
};
|
| 16 |
-
|
| 17 |
-
async function apiFetch(endpoint, options = {}) {
|
| 18 |
-
const url = `${API_BASE}${endpoint}`;
|
| 19 |
-
const headers = { ...API_HEADERS, ...options.headers };
|
| 20 |
-
return fetch(url, { ...options, headers });
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
// ─── FILE OPERATIONS ──────────────────────────────────────
|
| 24 |
-
async function listFilesAPI(path = DEFAULT_FOLDER) {
|
| 25 |
-
try {
|
| 26 |
-
const queryPath = path ? `?folder_path=${encodeURIComponent(path)}` : '';
|
| 27 |
-
const url = `${API_BASE}/list${queryPath}`;
|
| 28 |
-
console.log('Fetching from URL:', url); // Debug
|
| 29 |
-
const res = await apiFetch(`/list${queryPath}`);
|
| 30 |
-
|
| 31 |
-
console.log('API Response status:', res.status); // Debug
|
| 32 |
-
|
| 33 |
-
if (!res.ok) {
|
| 34 |
-
if (res.status === 404) {
|
| 35 |
-
console.warn('Path not found, returning empty list'); // Debug
|
| 36 |
-
return { files: [], folders: [] };
|
| 37 |
-
}
|
| 38 |
-
throw new Error(`Failed to list files: ${res.status} ${res.statusText}`);
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
const data = await res.json();
|
| 42 |
-
console.log('API Data:', data); // Debug
|
| 43 |
-
|
| 44 |
-
if (!data.success) {
|
| 45 |
-
console.error('API error:', data.error);
|
| 46 |
-
throw new Error(data.error || 'API returned success: false');
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
const files = (data.files || []).map(f => ({
|
| 50 |
-
path: f.path,
|
| 51 |
-
name: f.name,
|
| 52 |
-
size: f.size || 0,
|
| 53 |
-
type: 'file',
|
| 54 |
-
created_at: f.created_at,
|
| 55 |
-
modified_at: f.modified_at
|
| 56 |
-
}));
|
| 57 |
-
|
| 58 |
-
const folders = (data.folders || []).map(f => ({
|
| 59 |
-
path: f.path,
|
| 60 |
-
name: f.name,
|
| 61 |
-
type: 'folder',
|
| 62 |
-
created_at: f.created_at,
|
| 63 |
-
modified_at: f.modified_at
|
| 64 |
-
}));
|
| 65 |
-
|
| 66 |
-
console.log('Parsed folders:', folders.length, 'files:', files.length); // Debug
|
| 67 |
-
return { files, folders };
|
| 68 |
-
} catch (err) {
|
| 69 |
-
console.error('List files error:', err);
|
| 70 |
-
showToast(`Error loading files: ${err.message}`, 'error');
|
| 71 |
-
return { files: [], folders: [] };
|
| 72 |
-
}
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
async function uploadFileAPI(file, destPath) {
|
| 76 |
-
try {
|
| 77 |
-
const folderPath = destPath || DEFAULT_FOLDER;
|
| 78 |
-
const fileBlob = file instanceof File ? file : file.content;
|
| 79 |
-
const filename = file instanceof File ? file.name : (file.name || 'upload.bin');
|
| 80 |
-
|
| 81 |
-
console.log('Uploading file:', filename, 'to:', folderPath); // Debug
|
| 82 |
-
|
| 83 |
-
const formData = new FormData();
|
| 84 |
-
formData.append('folder_path', folderPath);
|
| 85 |
-
formData.append('file', fileBlob, filename);
|
| 86 |
-
|
| 87 |
-
const url = `${API_BASE}/upload`;
|
| 88 |
-
console.log('Upload endpoint:', url); // Debug
|
| 89 |
-
|
| 90 |
-
const res = await fetch(url, {
|
| 91 |
-
method: 'POST',
|
| 92 |
-
headers: { 'X-User-ID': USER_ID },
|
| 93 |
-
body: formData
|
| 94 |
-
});
|
| 95 |
-
|
| 96 |
-
console.log('Upload response status:', res.status); // Debug
|
| 97 |
-
|
| 98 |
-
if (!res.ok) {
|
| 99 |
-
const errData = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
|
| 100 |
-
throw new Error(errData.error || `Upload failed: ${res.status} ${res.statusText}`);
|
| 101 |
-
}
|
| 102 |
-
|
| 103 |
-
const data = await res.json();
|
| 104 |
-
console.log('Upload API response:', data); // Debug
|
| 105 |
-
|
| 106 |
-
if (!data.success) throw new Error(data.error || 'Upload API returned success: false');
|
| 107 |
-
|
| 108 |
-
return data;
|
| 109 |
-
} catch (err) {
|
| 110 |
-
console.error('Upload error:', err);
|
| 111 |
-
throw err;
|
| 112 |
-
}
|
| 113 |
-
}
|
| 114 |
-
|
| 115 |
-
async function deleteItemAPI(itemPath, itemType = 'file') {
|
| 116 |
-
try {
|
| 117 |
-
const endpoint = '/delete';
|
| 118 |
-
const payload = { path: itemPath, type: itemType };
|
| 119 |
-
|
| 120 |
-
const res = await apiFetch(endpoint, {
|
| 121 |
-
method: 'POST',
|
| 122 |
-
body: JSON.stringify(payload)
|
| 123 |
-
});
|
| 124 |
-
|
| 125 |
-
const data = await res.json().catch(() => ({}));
|
| 126 |
-
if (!res.ok || !data.success) {
|
| 127 |
-
throw new Error(data.error || 'Delete failed');
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
-
return true;
|
| 131 |
-
} catch (err) {
|
| 132 |
-
console.error('Delete error:', err);
|
| 133 |
-
throw err;
|
| 134 |
-
}
|
| 135 |
-
}
|
| 136 |
-
|
| 137 |
-
async function createFolderAPI(folderPath) {
|
| 138 |
-
try {
|
| 139 |
-
const res = await apiFetch('/create-folder', {
|
| 140 |
-
method: 'POST',
|
| 141 |
-
body: JSON.stringify({ folder_path: folderPath })
|
| 142 |
-
});
|
| 143 |
-
|
| 144 |
-
if (!res.ok) throw new Error(`Create folder failed: ${res.status}`);
|
| 145 |
-
|
| 146 |
-
const data = await res.json();
|
| 147 |
-
if (!data.success) throw new Error(data.error);
|
| 148 |
-
|
| 149 |
-
return data;
|
| 150 |
-
} catch (err) {
|
| 151 |
-
console.error('Create folder error:', err);
|
| 152 |
-
throw err;
|
| 153 |
-
}
|
| 154 |
-
}
|
| 155 |
-
|
| 156 |
-
async function renameItemAPI(itemPath, newName) {
|
| 157 |
-
try {
|
| 158 |
-
const res = await apiFetch('/rename', {
|
| 159 |
-
method: 'POST',
|
| 160 |
-
body: JSON.stringify({ item_path: itemPath, new_name: newName })
|
| 161 |
-
});
|
| 162 |
-
|
| 163 |
-
if (!res.ok) throw new Error(`Rename failed: ${res.status}`);
|
| 164 |
-
|
| 165 |
-
const data = await res.json();
|
| 166 |
-
if (!data.success) throw new Error(data.error);
|
| 167 |
-
|
| 168 |
-
return data;
|
| 169 |
-
} catch (err) {
|
| 170 |
-
console.error('Rename error:', err);
|
| 171 |
-
throw err;
|
| 172 |
-
}
|
| 173 |
-
}
|
| 174 |
-
|
| 175 |
-
async function getStorageStatsAPI() {
|
| 176 |
-
try {
|
| 177 |
-
const res = await apiFetch('/storage-stats');
|
| 178 |
-
|
| 179 |
-
if (!res.ok) throw new Error(`Storage stats failed: ${res.status}`);
|
| 180 |
-
|
| 181 |
-
const data = await res.json();
|
| 182 |
-
if (!data.success) throw new Error(data.error);
|
| 183 |
-
|
| 184 |
-
return data;
|
| 185 |
-
} catch (err) {
|
| 186 |
-
console.error('Storage stats error:', err);
|
| 187 |
-
return { total_size: 0, total_files: 0, total_folders: 0 };
|
| 188 |
-
}
|
| 189 |
-
}
|
| 190 |
-
|
| 191 |
-
// ─── STATE ────────────────────────────────────────────────
|
| 192 |
-
let currentPath = [];
|
| 193 |
-
let searchQuery = '';
|
| 194 |
-
let currentViewMode = 'grid'; // grid | list
|
| 195 |
-
let currentBrowse = 'files'; // files | starred | recent
|
| 196 |
-
let isFetching = false;
|
| 197 |
-
let pendingDeletePath = null;
|
| 198 |
-
let pendingDeleteType = 'file';
|
| 199 |
-
let cachedFiles = []; // flat list from last fetch
|
| 200 |
-
let lastFetchPath = null; // Track last fetched path to prevent duplicates
|
| 201 |
-
let lastFetchTime = 0; // Track when last fetch occurred
|
| 202 |
-
|
| 203 |
-
// ─── DOM REFS ─────────────────────────────────────────────
|
| 204 |
-
const $ = id => document.getElementById(id);
|
| 205 |
-
|
| 206 |
-
const newBtn = $('newBtn'), newDropdown = $('newDropdown');
|
| 207 |
-
const createFolderBtn = $('createFolderBtn');
|
| 208 |
-
const uploadFileBtn = $('uploadFileBtn');
|
| 209 |
-
const createFolderModal= $('createFolderModal'), closeNameModal = $('closeNameModal');
|
| 210 |
-
const cancelFolderBtn = $('cancelFolderBtn'), confirmFolderBtn = $('confirmFolderBtn');
|
| 211 |
-
const folderNameInput = $('folderNameInput');
|
| 212 |
-
const breadcrumbsEl = $('breadcrumbs');
|
| 213 |
-
const foldersContainer = $('foldersContainer'), filesContainer = $('filesContainer');
|
| 214 |
-
const fileInput = $('fileInput');
|
| 215 |
-
const uploadProgress = $('uploadProgress'), progressText = $('progressText');
|
| 216 |
-
const searchInput = $('searchInput'), toastContainer = $('toastContainer');
|
| 217 |
-
const deleteModal = $('deleteModal'), closeDeleteModal = $('closeDeleteModal');
|
| 218 |
-
const cancelDeleteBtn = $('cancelDeleteBtn'), confirmDeleteBtn = $('confirmDeleteBtn');
|
| 219 |
-
const navMyFiles = $('navMyFiles'), navRecent = $('navRecent'), navStarred = $('navStarred');
|
| 220 |
-
const viewGrid = $('viewGrid'), viewList = $('viewList');
|
| 221 |
-
const previewModal = $('previewModal'), closePreviewModal = $('closePreviewModal');
|
| 222 |
-
const previewBody = $('previewBody'), previewFileName = $('previewFileName');
|
| 223 |
-
const downloadFromPreview = $('downloadFromPreview');
|
| 224 |
-
const storageProgress = $('storageProgress'), storageUsageText = $('storageUsageText');
|
| 225 |
-
const contentArea = document.querySelector('.content-area');
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
// ─── TOAST ────────────────────────────────────────────────
|
| 229 |
-
function showToast(msg, type = 'info') {
|
| 230 |
-
const icons = {
|
| 231 |
-
success: 'ph-fill ph-check-circle',
|
| 232 |
-
error: 'ph-fill ph-warning-circle',
|
| 233 |
-
info: 'ph-fill ph-info',
|
| 234 |
-
warning: 'ph-fill ph-warning'
|
| 235 |
-
};
|
| 236 |
-
const t = document.createElement('div');
|
| 237 |
-
t.className = `toast toast-${type}`;
|
| 238 |
-
t.innerHTML = `<i class="${icons[type] || icons.info}"></i><span>${msg}</span>`;
|
| 239 |
-
toastContainer.appendChild(t);
|
| 240 |
-
requestAnimationFrame(() => t.classList.add('show'));
|
| 241 |
-
setTimeout(() => { t.classList.remove('show'); setTimeout(() => t.remove(), 400); }, 3500);
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
-
// ─── HELPERS ──────────────────────────────────────────────
|
| 245 |
-
function getFolderPath() {
|
| 246 |
-
if (currentPath.length === 0) return DEFAULT_FOLDER;
|
| 247 |
-
const prefix = DEFAULT_FOLDER ? `${DEFAULT_FOLDER}/` : '';
|
| 248 |
-
return `${prefix}${currentPath.join('/')}`;
|
| 249 |
-
}
|
| 250 |
-
function getFilePath(name) {
|
| 251 |
-
const folderPath = getFolderPath();
|
| 252 |
-
return folderPath ? `${folderPath}/${name}` : name;
|
| 253 |
-
}
|
| 254 |
-
function formatSize(bytes) {
|
| 255 |
-
if (!bytes || bytes === 0) return '—';
|
| 256 |
-
if (bytes >= 1073741824) return (bytes / 1073741824).toFixed(1) + ' GB';
|
| 257 |
-
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
|
| 258 |
-
if (bytes >= 1024) return Math.round(bytes / 1024) + ' KB';
|
| 259 |
-
return bytes + ' B';
|
| 260 |
-
}
|
| 261 |
-
function getExt(name) { return (name.split('.').pop() || '').toLowerCase(); }
|
| 262 |
-
function getFileIcon(name) {
|
| 263 |
-
const n = name.toLowerCase();
|
| 264 |
-
if (n.endsWith('.pdf')) return { icon: 'ph-fill ph-file-pdf', color: '#f85149' };
|
| 265 |
-
if (n.match(/\.docx?$/)) return { icon: 'ph-fill ph-file-text', color: '#4299e1' };
|
| 266 |
-
if (n.match(/\.xlsx?$/)) return { icon: 'ph-fill ph-file-text', color: '#38a169' };
|
| 267 |
-
if (n.match(/\.pptx?$/)) return { icon: 'ph-fill ph-presentation',color: '#e07b39' };
|
| 268 |
-
if (n.match(/\.(jpg|jpeg|png|gif|webp|svg)$/)) return { icon: 'ph-fill ph-image', color: '#9f7aea' };
|
| 269 |
-
if (n.match(/\.(mp4|mov|avi|mkv|webm)$/)) return { icon: 'ph-fill ph-video', color: '#fc8181' };
|
| 270 |
-
if (n.match(/\.(mp3|wav|aac|flac|ogg)$/)) return { icon: 'ph-fill ph-music-notes', color: '#68d391' };
|
| 271 |
-
if (n.match(/\.(zip|rar|7z|tar|gz)$/)) return { icon: 'ph-fill ph-file-archive', color: '#f6e05e' };
|
| 272 |
-
if (n.match(/\.(js|py|ts|html|css|json|xml|sh|java|cpp|c)$/)) return { icon: 'ph-fill ph-file-code', color: '#63b3ed' };
|
| 273 |
-
if (n.match(/\.(txt|md|csv|log)$/)) return { icon: 'ph-fill ph-file-text', color: '#a0aec0' };
|
| 274 |
-
return { icon: 'ph-fill ph-file', color: '#79c0ff' };
|
| 275 |
-
}
|
| 276 |
-
function isImage(name) { return /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(name); }
|
| 277 |
-
function isPDF(name) { return /\.pdf$/i.test(name); }
|
| 278 |
-
function isText(name) { return /\.(txt|md|csv|log|json|xml|html|css|js|ts|py|sh|java|yaml|yml)$/i.test(name); }
|
| 279 |
-
|
| 280 |
-
function getFileEmoji(ext) {
|
| 281 |
-
const extLower = ext.toLowerCase();
|
| 282 |
-
if (['pdf'].includes(extLower)) return '📄';
|
| 283 |
-
if (['doc', 'docx'].includes(extLower)) return '📝';
|
| 284 |
-
if (['xls', 'xlsx'].includes(extLower)) return '📊';
|
| 285 |
-
if (['ppt', 'pptx'].includes(extLower)) return '📽️';
|
| 286 |
-
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(extLower)) return '🖼️';
|
| 287 |
-
if (['mp4', 'mov', 'avi', 'mkv', 'webm'].includes(extLower)) return '🎥';
|
| 288 |
-
if (['mp3', 'wav', 'aac', 'flac', 'ogg'].includes(extLower)) return '🎵';
|
| 289 |
-
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extLower)) return '📦';
|
| 290 |
-
if (['js', 'ts', 'py', 'java', 'cpp', 'c', 'html', 'css'].includes(extLower)) return '💻';
|
| 291 |
-
if (['txt', 'md', 'csv', 'log', 'json', 'xml', 'yaml', 'yml'].includes(extLower)) return '📄';
|
| 292 |
-
return '📄';
|
| 293 |
-
}
|
| 294 |
-
|
| 295 |
-
function formatDate(timestamp) {
|
| 296 |
-
if (!timestamp) return 'Recently';
|
| 297 |
-
const date = new Date(timestamp);
|
| 298 |
-
const now = new Date();
|
| 299 |
-
const diffMs = now - date;
|
| 300 |
-
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
| 301 |
-
|
| 302 |
-
if (diffDays === 0) return 'Today';
|
| 303 |
-
if (diffDays === 1) return 'Yesterday';
|
| 304 |
-
if (diffDays < 7) return `${diffDays} days ago`;
|
| 305 |
-
if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`;
|
| 306 |
-
if (diffDays < 365) return `${Math.floor(diffDays / 30)} months ago`;
|
| 307 |
-
return `${Math.floor(diffDays / 365)} years ago`;
|
| 308 |
-
}
|
| 309 |
-
|
| 310 |
-
function getFileUrl(filePath) {
|
| 311 |
-
// Download from local Flask backend
|
| 312 |
-
const encodedPath = String(filePath)
|
| 313 |
-
.split('/')
|
| 314 |
-
.map(segment => encodeURIComponent(segment))
|
| 315 |
-
.join('/');
|
| 316 |
-
return `${API_BASE}/download/${encodedPath}`;
|
| 317 |
-
}
|
| 318 |
-
|
| 319 |
-
// ─── PERSISTENCE ──────────────────────────────────────────
|
| 320 |
-
function getStarred() { try { return JSON.parse(localStorage.getItem(STARRED_KEY)) || []; } catch { return []; } }
|
| 321 |
-
function isStarred(path) { return getStarred().includes(path); }
|
| 322 |
-
function toggleStar(path) {
|
| 323 |
-
let s = getStarred();
|
| 324 |
-
if (s.includes(path)) s = s.filter(x => x !== path);
|
| 325 |
-
else s.push(path);
|
| 326 |
-
localStorage.setItem(STARRED_KEY, JSON.stringify(s));
|
| 327 |
-
renderView();
|
| 328 |
-
}
|
| 329 |
-
function getRecent() { try { return JSON.parse(localStorage.getItem(RECENT_KEY)) || []; } catch { return []; } }
|
| 330 |
-
function addToRecent(path, name, type) {
|
| 331 |
-
let r = getRecent();
|
| 332 |
-
r = [{ path, name, type }, ...r.filter(x => x.path !== path)].slice(0, 10);
|
| 333 |
-
localStorage.setItem(RECENT_KEY, JSON.stringify(r));
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
// ─── STORAGE STATS ────────────────────────────────────────
|
| 337 |
-
async function updateStorageStats() {
|
| 338 |
-
try {
|
| 339 |
-
const stats = await getStorageStatsAPI();
|
| 340 |
-
const totalBytes = stats.total_size || 0;
|
| 341 |
-
const count = stats.total_files || 0;
|
| 342 |
-
const MAX_BYTES = 10 * 1024 * 1024 * 1024; // 10 GB cap display
|
| 343 |
-
const pct = Math.min((totalBytes / MAX_BYTES) * 100, 100).toFixed(1);
|
| 344 |
-
if (storageProgress) storageProgress.style.width = pct + '%';
|
| 345 |
-
if (storageUsageText) storageUsageText.textContent = `${count} file${count !== 1 ? 's' : ''} • ${formatSize(totalBytes)} used`;
|
| 346 |
-
} catch (err) {
|
| 347 |
-
console.error('Failed to update storage stats:', err);
|
| 348 |
-
}
|
| 349 |
-
}
|
| 350 |
-
|
| 351 |
-
// ─── SKELETON LOADING ─────────────────────────────────────
|
| 352 |
-
function showSkeletons(container, count = 6) {
|
| 353 |
-
container.innerHTML = '';
|
| 354 |
-
for (let i = 0; i < count; i++) {
|
| 355 |
-
const el = document.createElement('div');
|
| 356 |
-
el.className = 'skeleton skeleton-card';
|
| 357 |
-
el.innerHTML = `
|
| 358 |
-
<div class="skeleton-icon"></div>
|
| 359 |
-
<div class="skeleton-info">
|
| 360 |
-
<div class="skeleton-name"></div>
|
| 361 |
-
<div class="skeleton-meta"></div>
|
| 362 |
-
</div>
|
| 363 |
-
`;
|
| 364 |
-
container.appendChild(el);
|
| 365 |
-
}
|
| 366 |
-
}
|
| 367 |
-
|
| 368 |
-
// ─── FETCH FILES ──────────────────────────────────────────
|
| 369 |
-
async function fetchAndRender() {
|
| 370 |
-
if (isFetching) {
|
| 371 |
-
console.warn('Already fetching, ignoring request');
|
| 372 |
-
return;
|
| 373 |
-
}
|
| 374 |
-
isFetching = true;
|
| 375 |
-
const container = currentViewMode === 'grid' ? 'grid-container' : 'list-container';
|
| 376 |
-
foldersContainer.className = container;
|
| 377 |
-
filesContainer.className = container;
|
| 378 |
-
showSkeletons(foldersContainer, 3);
|
| 379 |
-
showSkeletons(filesContainer, 6);
|
| 380 |
-
try {
|
| 381 |
-
const prefix = getFolderPath();
|
| 382 |
-
console.log('Fetching contents for path:', prefix); // Debug
|
| 383 |
-
const pathSnapshot = JSON.stringify(currentPath); // Capture for safety check
|
| 384 |
-
const { files, folders } = await listFilesAPI(prefix);
|
| 385 |
-
|
| 386 |
-
console.log('API returned:', { folders: folders.length, files: files.length }); // Debug
|
| 387 |
-
|
| 388 |
-
// SAFETY CHECK: Path may have changed due to user clicking elsewhere
|
| 389 |
-
if (JSON.stringify(currentPath) !== pathSnapshot) {
|
| 390 |
-
console.log('Path changed during fetch'); // Debug
|
| 391 |
-
isFetching = false;
|
| 392 |
-
return;
|
| 393 |
-
}
|
| 394 |
-
|
| 395 |
-
// Update storage stats from API
|
| 396 |
-
await updateStorageStats();
|
| 397 |
-
|
| 398 |
-
// Apply search filter
|
| 399 |
-
let displayFiles = files;
|
| 400 |
-
if (searchQuery) {
|
| 401 |
-
const q = searchQuery.toLowerCase();
|
| 402 |
-
displayFiles = files.filter(f => f.path.toLowerCase().includes(q));
|
| 403 |
-
}
|
| 404 |
-
|
| 405 |
-
renderBreadcrumbs();
|
| 406 |
-
renderFolders(folders);
|
| 407 |
-
renderFiles(displayFiles);
|
| 408 |
-
} catch (err) {
|
| 409 |
-
console.error('Fetch error', err);
|
| 410 |
-
showError(filesContainer, err.message);
|
| 411 |
-
renderBreadcrumbs();
|
| 412 |
-
} finally {
|
| 413 |
-
isFetching = false;
|
| 414 |
-
}
|
| 415 |
-
}
|
| 416 |
-
|
| 417 |
-
// Recursively get all files for storage calculation (not needed with backend stats)
|
| 418 |
-
async function getRecursiveFiles(path = '') {
|
| 419 |
-
const { files, folders } = await listFilesAPI(path);
|
| 420 |
-
let allFiles = [...files];
|
| 421 |
-
|
| 422 |
-
for (const folder of folders) {
|
| 423 |
-
const subPath = path ? `${path}/${folder.name}` : folder.name;
|
| 424 |
-
const subFiles = await getRecursiveFiles(subPath);
|
| 425 |
-
allFiles = allFiles.concat(subFiles);
|
| 426 |
-
}
|
| 427 |
-
|
| 428 |
-
return allFiles;
|
| 429 |
-
}
|
| 430 |
-
|
| 431 |
-
function showEmpty(container, hint = '') {
|
| 432 |
-
container.innerHTML = `<div class="empty-state">
|
| 433 |
-
<i class="ph-fill ph-folder-open"></i>
|
| 434 |
-
<h3>Nothing here yet</h3>
|
| 435 |
-
<p>${hint || 'Upload files or create folders to get started.'}</p>
|
| 436 |
-
</div>`;
|
| 437 |
-
}
|
| 438 |
-
function showError(container, msg) {
|
| 439 |
-
container.innerHTML = `<div class="empty-state">
|
| 440 |
-
<i class="ph-fill ph-warning-circle" style="color:#ef4444"></i>
|
| 441 |
-
<h3>Something went wrong</h3>
|
| 442 |
-
<p style="color:#ef4444">${msg}</p>
|
| 443 |
-
</div>`;
|
| 444 |
-
}
|
| 445 |
-
|
| 446 |
-
// ─── RENDER: BREADCRUMBS ──────────────────────────────────
|
| 447 |
-
function renderBreadcrumbs() {
|
| 448 |
-
breadcrumbsEl.innerHTML = '';
|
| 449 |
-
const root = document.createElement('span');
|
| 450 |
-
root.className = 'breadcrumb-item' + (currentPath.length === 0 ? ' active' : '');
|
| 451 |
-
root.textContent = 'My Files';
|
| 452 |
-
root.style.cursor = 'pointer';
|
| 453 |
-
root.addEventListener('click', (e) => {
|
| 454 |
-
e.stopPropagation();
|
| 455 |
-
console.log('Breadcrumb root clicked'); // Debug
|
| 456 |
-
currentPath = [];
|
| 457 |
-
fetchAndRender();
|
| 458 |
-
});
|
| 459 |
-
breadcrumbsEl.appendChild(root);
|
| 460 |
-
|
| 461 |
-
currentPath.forEach((seg, idx) => {
|
| 462 |
-
const sep = document.createElement('span');
|
| 463 |
-
sep.className = 'breadcrumb-separator';
|
| 464 |
-
sep.innerHTML = '<i class="ph-bold ph-caret-right" style="font-size: 14px; margin: 0 4px"></i>';
|
| 465 |
-
breadcrumbsEl.appendChild(sep);
|
| 466 |
-
const crumb = document.createElement('span');
|
| 467 |
-
crumb.className = 'breadcrumb-item' + (idx === currentPath.length - 1 ? ' active' : '');
|
| 468 |
-
crumb.textContent = seg;
|
| 469 |
-
crumb.style.cursor = 'pointer';
|
| 470 |
-
crumb.addEventListener('click', (e) => {
|
| 471 |
-
e.stopPropagation();
|
| 472 |
-
console.log('Breadcrumb', seg, 'clicked at index', idx); // Debug
|
| 473 |
-
currentPath = currentPath.slice(0, idx + 1);
|
| 474 |
-
fetchAndRender();
|
| 475 |
-
});
|
| 476 |
-
breadcrumbsEl.appendChild(crumb);
|
| 477 |
-
});
|
| 478 |
-
}
|
| 479 |
-
|
| 480 |
-
// ─── RENDER: FOLDERS ──────────────────────────────────────
|
| 481 |
-
function renderFolders(folders) {
|
| 482 |
-
if (!folders.length) { foldersContainer.innerHTML = ''; return; }
|
| 483 |
-
foldersContainer.innerHTML = '';
|
| 484 |
-
folders.forEach((folder, index) => {
|
| 485 |
-
const name = folder.path.split('/').pop();
|
| 486 |
-
const card = document.createElement('div');
|
| 487 |
-
card.className = 'folder-card';
|
| 488 |
-
card.style.animationDelay = `${index * 50}ms`; // Staggered animation
|
| 489 |
-
|
| 490 |
-
// Get folder metadata (placeholder - you can enhance this)
|
| 491 |
-
const itemCount = Math.floor(Math.random() * 10) + 1; // Placeholder - replace with actual count
|
| 492 |
-
const lastModified = 'Recently'; // Placeholder - replace with actual date
|
| 493 |
-
|
| 494 |
-
card.innerHTML = `
|
| 495 |
-
<div class="folder-icon-container">
|
| 496 |
-
<svg class="folder-icon" width="56" height="56" viewBox="0 0 24 24" fill="none">
|
| 497 |
-
<path d="M2 6.75C2 5.784 2.784 5 3.75 5H9.5l1.5 2H20.25C21.216 7 22 7.784 22 8.75v9.5A1.75 1.75 0 0 1 20.25 20H3.75A1.75 1.75 0 0 1 2 18.25z" fill="var(--folder-color)" opacity="0.3"/>
|
| 498 |
-
<path d="M2 8.75C2 7.784 2.784 7 3.75 7H20.25C21.216 7 22 7.784 22 8.75v9.5A1.75 1.75 0 0 1 20.25 20H3.75A1.75 1.75 0 0 1 2 18.25z" fill="var(--folder-color)"/>
|
| 499 |
-
</svg>
|
| 500 |
-
</div>
|
| 501 |
-
<div class="folder-info">
|
| 502 |
-
<div class="folder-name" title="${name}">${name}</div>
|
| 503 |
-
<div class="folder-meta">${itemCount} items • ${lastModified}</div>
|
| 504 |
-
</div>
|
| 505 |
-
<div class="folder-actions">
|
| 506 |
-
<button class="action-btn" title="More options" aria-label="Folder options">
|
| 507 |
-
<i class="ph-bold ph-dots-three-vertical"></i>
|
| 508 |
-
</button>
|
| 509 |
-
<div class="dropdown-menu">
|
| 510 |
-
<button class="dropdown-item" data-action="rename" data-path="${folder.path}" data-name="${name}">
|
| 511 |
-
<i class="ph-fill ph-pencil-simple"></i> Rename
|
| 512 |
-
</button>
|
| 513 |
-
</div>
|
| 514 |
-
</div>`;
|
| 515 |
-
|
| 516 |
-
// FIXED: Simplified folder click handler
|
| 517 |
-
card.addEventListener('click', function(e) {
|
| 518 |
-
e.preventDefault();
|
| 519 |
-
e.stopPropagation();
|
| 520 |
-
|
| 521 |
-
// Don't navigate if clicking on the actions menu
|
| 522 |
-
if (e.target.closest('.folder-actions')) {
|
| 523 |
-
return;
|
| 524 |
-
}
|
| 525 |
-
|
| 526 |
-
// Navigate into the folder
|
| 527 |
-
const folderName = folder.path.split('/').pop();
|
| 528 |
-
console.log('Navigating to folder:', folderName, 'Full path:', folder.path); // Debug
|
| 529 |
-
currentPath.push(folderName);
|
| 530 |
-
addToRecent(folder.path, folderName, 'folder');
|
| 531 |
-
fetchAndRender();
|
| 532 |
-
});
|
| 533 |
-
|
| 534 |
-
// Attach menu functionality
|
| 535 |
-
attachCardMenu(card, folder.path, 'folder');
|
| 536 |
-
|
| 537 |
-
foldersContainer.appendChild(card);
|
| 538 |
-
});
|
| 539 |
-
}
|
| 540 |
-
|
| 541 |
-
// ─── RENDER: FILES ────────────────────────────────────────
|
| 542 |
-
function renderFiles(files) {
|
| 543 |
-
if (!files.length) { showEmpty(filesContainer); return; }
|
| 544 |
-
filesContainer.innerHTML = '';
|
| 545 |
-
files.forEach(file => {
|
| 546 |
-
const name = file.path.split('/').pop();
|
| 547 |
-
const { icon, color } = getFileIcon(name);
|
| 548 |
-
const ext = getExt(name).toUpperCase() || 'FILE';
|
| 549 |
-
const size = formatSize(file.size);
|
| 550 |
-
const url = getFileUrl(file.path);
|
| 551 |
-
const starred = isStarred(file.path);
|
| 552 |
-
const card = document.createElement('div');
|
| 553 |
-
card.className = 'file-card';
|
| 554 |
-
|
| 555 |
-
// Determine file type color
|
| 556 |
-
let typeColor = '#64748b'; // default gray
|
| 557 |
-
const extUpper = ext.toUpperCase();
|
| 558 |
-
if (['PDF'].includes(extUpper)) typeColor = '#dc2626'; // red
|
| 559 |
-
else if (['JPG', 'JPEG', 'PNG', 'GIF', 'WEBP', 'SVG', 'BMP', 'ICO'].includes(extUpper)) typeColor = '#7c3aed'; // purple
|
| 560 |
-
else if (['JS', 'TS', 'HTML', 'CSS', 'PY', 'JAVA', 'CPP', 'C', 'PHP', 'RB', 'GO', 'RS'].includes(extUpper)) typeColor = '#ca8a04'; // yellow
|
| 561 |
-
else if (['DOC', 'DOCX', 'TXT', 'MD', 'RTF'].includes(extUpper)) typeColor = '#2563eb'; // blue
|
| 562 |
-
else if (['XLS', 'XLSX', 'CSV'].includes(extUpper)) typeColor = '#16a34a'; // green
|
| 563 |
-
else if (['PPT', 'PPTX'].includes(extUpper)) typeColor = '#dc2626'; // red
|
| 564 |
-
else if (['ZIP', 'RAR', '7Z', 'TAR', 'GZ'].includes(extUpper)) typeColor = '#7c2d12'; // orange
|
| 565 |
-
|
| 566 |
-
const isImg = isImage(name);
|
| 567 |
-
const previewHTML = isImg
|
| 568 |
-
? `<img src="${url}" alt="${name}" loading="lazy" onerror="this.parentElement.innerHTML='<span class=\\'file-icon\\'>📄</span>'">`
|
| 569 |
-
: `<span class="file-icon">${getFileEmoji(ext)}</span>`;
|
| 570 |
-
|
| 571 |
-
card.innerHTML = `
|
| 572 |
-
<div class="file-preview">
|
| 573 |
-
${previewHTML}
|
| 574 |
-
</div>
|
| 575 |
-
<div class="file-info">
|
| 576 |
-
<span class="file-type" style="background-color: ${typeColor}20; color: ${typeColor}">${ext}</span>
|
| 577 |
-
<h4 class="file-name" title="${name}">${name}</h4>
|
| 578 |
-
<p class="file-meta">${size} • ${file.modified_at ? formatDate(file.modified_at) : 'Recently'}</p>
|
| 579 |
-
</div>
|
| 580 |
-
<div class="file-actions">⋮</div>
|
| 581 |
-
<div class="quick-actions">
|
| 582 |
-
<button class="quick-btn" data-action="preview" title="Preview"><i class="ph-fill ph-eye"></i></button>
|
| 583 |
-
<button class="quick-btn" data-action="download" title="Download"><i class="ph-fill ph-download-simple"></i></button>
|
| 584 |
-
</div>`;
|
| 585 |
-
|
| 586 |
-
card.addEventListener('click', (e) => {
|
| 587 |
-
if (e.target.closest('.file-actions') || e.target.closest('.quick-actions')) return;
|
| 588 |
-
openPreview(file.path, name, url);
|
| 589 |
-
});
|
| 590 |
-
|
| 591 |
-
// File actions menu
|
| 592 |
-
const actionsBtn = card.querySelector('.file-actions');
|
| 593 |
-
actionsBtn.addEventListener('click', (e) => {
|
| 594 |
-
e.stopPropagation();
|
| 595 |
-
// Create dropdown menu
|
| 596 |
-
const existingMenu = document.querySelector('.file-menu-dropdown');
|
| 597 |
-
if (existingMenu) existingMenu.remove();
|
| 598 |
-
|
| 599 |
-
const menu = document.createElement('div');
|
| 600 |
-
menu.className = 'file-menu-dropdown';
|
| 601 |
-
menu.innerHTML = `
|
| 602 |
-
<button class="menu-item" data-action="preview">
|
| 603 |
-
<i class="ph-fill ph-eye"></i> Open
|
| 604 |
-
</button>
|
| 605 |
-
<button class="menu-item" data-action="download">
|
| 606 |
-
<i class="ph-fill ph-download-simple"></i> Download
|
| 607 |
-
</button>
|
| 608 |
-
<button class="menu-item" data-action="share">
|
| 609 |
-
<i class="ph-fill ph-share-network"></i> Share
|
| 610 |
-
</button>
|
| 611 |
-
<button class="menu-item" data-action="star">
|
| 612 |
-
<i class="ph-fill ph-star${starred ? '' : '-bold'}"></i> ${starred ? 'Unstar' : 'Star'}
|
| 613 |
-
</button>
|
| 614 |
-
<button class="menu-item" data-action="rename">
|
| 615 |
-
<i class="ph-fill ph-pencil-simple"></i> Rename
|
| 616 |
-
</button>
|
| 617 |
-
<div class="menu-divider"></div>
|
| 618 |
-
<button class="menu-item danger" data-action="delete">
|
| 619 |
-
<i class="ph-fill ph-trash"></i> Delete
|
| 620 |
-
</button>
|
| 621 |
-
`;
|
| 622 |
-
document.body.appendChild(menu);
|
| 623 |
-
|
| 624 |
-
// Position menu after it's rendered
|
| 625 |
-
requestAnimationFrame(() => {
|
| 626 |
-
const rect = actionsBtn.getBoundingClientRect();
|
| 627 |
-
const menuRect = menu.getBoundingClientRect();
|
| 628 |
-
let top = rect.bottom + 8;
|
| 629 |
-
let left = rect.right - menuRect.width;
|
| 630 |
-
|
| 631 |
-
// Adjust if menu goes off-screen
|
| 632 |
-
if (left < 8) left = 8;
|
| 633 |
-
if (top + menuRect.height > window.innerHeight) {
|
| 634 |
-
top = rect.top - menuRect.height - 8;
|
| 635 |
-
}
|
| 636 |
-
|
| 637 |
-
menu.style.top = `${top}px`;
|
| 638 |
-
menu.style.left = `${left}px`;
|
| 639 |
-
});
|
| 640 |
-
|
| 641 |
-
// Handle menu clicks
|
| 642 |
-
const handleMenuClick = (e) => {
|
| 643 |
-
const btn = e.target.closest('.menu-item');
|
| 644 |
-
if (!btn) return;
|
| 645 |
-
const action = btn.dataset.action;
|
| 646 |
-
menu.remove();
|
| 647 |
-
document.removeEventListener('click', closeMenu);
|
| 648 |
-
|
| 649 |
-
if (action === 'preview') openPreview(file.path, name, url);
|
| 650 |
-
else if (action === 'download') downloadFile(url, name);
|
| 651 |
-
else if (action === 'share') copyLink(url);
|
| 652 |
-
else if (action === 'star') toggleStar(file.path);
|
| 653 |
-
else if (action === 'rename') openRenameModal(file.path, name);
|
| 654 |
-
else if (action === 'delete') openDeleteModal(file.path, name, 'file');
|
| 655 |
-
};
|
| 656 |
-
|
| 657 |
-
const closeMenu = (e) => {
|
| 658 |
-
if (!menu.contains(e.target) && e.target !== actionsBtn) {
|
| 659 |
-
menu.remove();
|
| 660 |
-
document.removeEventListener('click', closeMenu);
|
| 661 |
-
}
|
| 662 |
-
};
|
| 663 |
-
|
| 664 |
-
menu.addEventListener('click', handleMenuClick);
|
| 665 |
-
document.addEventListener('click', closeMenu);
|
| 666 |
-
});
|
| 667 |
-
|
| 668 |
-
// Quick actions
|
| 669 |
-
const quickActions = card.querySelector('.quick-actions');
|
| 670 |
-
quickActions.addEventListener('click', (e) => {
|
| 671 |
-
const btn = e.target.closest('.quick-btn');
|
| 672 |
-
if (!btn) return;
|
| 673 |
-
const action = btn.dataset.action;
|
| 674 |
-
if (action === 'preview') openPreview(file.path, name, url);
|
| 675 |
-
else if (action === 'download') downloadFile(url, name);
|
| 676 |
-
});
|
| 677 |
-
|
| 678 |
-
filesContainer.appendChild(card);
|
| 679 |
-
});
|
| 680 |
-
}
|
| 681 |
-
|
| 682 |
-
// ─── CARD DROPDOWN MENUS ─────────────────────────────────
|
| 683 |
-
function attachCardMenu(card, path, type, meta = {}) {
|
| 684 |
-
const menuBtn = card.querySelector('.action-btn');
|
| 685 |
-
const dropdown = card.querySelector('.dropdown-menu');
|
| 686 |
-
if (!menuBtn || !dropdown) return;
|
| 687 |
-
|
| 688 |
-
menuBtn.addEventListener('click', (e) => {
|
| 689 |
-
e.stopPropagation();
|
| 690 |
-
document.querySelectorAll('.dropdown-menu.open').forEach(d => { if (d !== dropdown) d.classList.remove('open'); });
|
| 691 |
-
dropdown.classList.toggle('open');
|
| 692 |
-
});
|
| 693 |
-
|
| 694 |
-
dropdown.addEventListener('click', (e) => {
|
| 695 |
-
e.stopPropagation();
|
| 696 |
-
const btn = e.target.closest('[data-action]');
|
| 697 |
-
if (!btn) return;
|
| 698 |
-
const action = btn.dataset.action;
|
| 699 |
-
dropdown.classList.remove('open');
|
| 700 |
-
|
| 701 |
-
if (action === 'preview') openPreview(btn.dataset.path, btn.dataset.name, getFileUrl(btn.dataset.path));
|
| 702 |
-
else if (action === 'share') copyLink(btn.dataset.url);
|
| 703 |
-
else if (action === 'share-folder') copyLink(window.location.href + '#' + path);
|
| 704 |
-
else if (action === 'download') downloadFile(btn.dataset.url, btn.dataset.name);
|
| 705 |
-
else if (action === 'star') toggleStar(btn.dataset.path);
|
| 706 |
-
else if (action === 'rename') openRenameModal(btn.dataset.path, btn.dataset.name);
|
| 707 |
-
else if (action === 'delete') openDeleteModal(btn.dataset.path, btn.dataset.name || path.split('/').pop(), 'file');
|
| 708 |
-
else if (action === 'delete-folder') openDeleteModal(path, path.split('/').pop(), 'folder');
|
| 709 |
-
});
|
| 710 |
-
}
|
| 711 |
-
|
| 712 |
-
// Close dropdowns on outside click (but don't interfere with folder navigation)
|
| 713 |
-
document.addEventListener('click', (e) => {
|
| 714 |
-
// Skip if clicking on a folder card itself
|
| 715 |
-
if (e.target.closest('.folder-card')) {
|
| 716 |
-
return;
|
| 717 |
-
}
|
| 718 |
-
|
| 719 |
-
// Close dropdowns
|
| 720 |
-
document.querySelectorAll('.dropdown-menu.open').forEach(d => d.classList.remove('open'));
|
| 721 |
-
newDropdown.classList.remove('active');
|
| 722 |
-
}, false); // Use bubble phase so folder capture phase fires first
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
// ─── PREVIEW MODAL ────────────────────────────────────────
|
| 726 |
-
let currentPreviewUrl = '';
|
| 727 |
-
function openPreview(filePath, name, url) {
|
| 728 |
-
currentPreviewUrl = url;
|
| 729 |
-
addToRecent(filePath, name, 'file');
|
| 730 |
-
previewFileName.textContent = name;
|
| 731 |
-
previewBody.innerHTML = `<div class="loading-state"><div class="spinner"></div><p>Loading preview…</p></div>`;
|
| 732 |
-
previewModal.classList.add('active');
|
| 733 |
-
|
| 734 |
-
if (isImage(name)) {
|
| 735 |
-
const img = new Image();
|
| 736 |
-
img.src = url;
|
| 737 |
-
img.className = 'preview-image';
|
| 738 |
-
img.onload = () => { previewBody.innerHTML = ''; previewBody.appendChild(img); };
|
| 739 |
-
img.onerror = () => { previewBody.innerHTML = previewFallback(name, url, 'Image failed to load.'); };
|
| 740 |
-
} else if (isPDF(name)) {
|
| 741 |
-
previewBody.innerHTML = `<iframe class="preview-iframe" src="${url}" title="${name}"></iframe>`;
|
| 742 |
-
} else if (isText(name)) {
|
| 743 |
-
fetch(url)
|
| 744 |
-
.then(r => r.ok ? r.text() : Promise.reject(r.status))
|
| 745 |
-
.then(text => {
|
| 746 |
-
const pre = document.createElement('pre');
|
| 747 |
-
pre.className = 'preview-text';
|
| 748 |
-
pre.textContent = text;
|
| 749 |
-
previewBody.innerHTML = '';
|
| 750 |
-
previewBody.appendChild(pre);
|
| 751 |
-
})
|
| 752 |
-
.catch(() => { previewBody.innerHTML = previewFallback(name, url, 'Could not load text.'); });
|
| 753 |
-
} else {
|
| 754 |
-
previewBody.innerHTML = previewFallback(name, url, 'No preview available for this file type.');
|
| 755 |
-
}
|
| 756 |
-
}
|
| 757 |
-
|
| 758 |
-
function previewFallback(name, url, msg) {
|
| 759 |
-
const { icon, color } = getFileIcon(name);
|
| 760 |
-
return `<div class="preview-fallback">
|
| 761 |
-
<i class="${icon}" style="color:${color}"></i>
|
| 762 |
-
<p>${msg}</p>
|
| 763 |
-
<a href="${url}" target="_blank" class="btn-primary" style="text-decoration:none;display:inline-flex;align-items:center;gap:8px;margin-top:16px">
|
| 764 |
-
<i class="ph-fill ph-download-simple"></i> Download File
|
| 765 |
-
</a>
|
| 766 |
-
</div>`;
|
| 767 |
-
}
|
| 768 |
-
|
| 769 |
-
closePreviewModal.addEventListener('click', () => previewModal.classList.remove('active'));
|
| 770 |
-
previewModal.addEventListener('click', (e) => { if (e.target === previewModal) previewModal.classList.remove('active'); });
|
| 771 |
-
downloadFromPreview.addEventListener('click', () => { if (currentPreviewUrl) downloadFile(currentPreviewUrl, previewFileName.textContent); });
|
| 772 |
-
|
| 773 |
-
// ─── SHARE / DOWNLOAD ────────────────────────────────────
|
| 774 |
-
function copyLink(url) {
|
| 775 |
-
navigator.clipboard.writeText(url)
|
| 776 |
-
.then(() => showToast('🔗 Link copied to clipboard!', 'success'))
|
| 777 |
-
.catch(() => { prompt('Copy this link:', url); });
|
| 778 |
-
}
|
| 779 |
-
function downloadFile(url, name) {
|
| 780 |
-
const a = document.createElement('a');
|
| 781 |
-
a.href = url; a.download = name; a.target = '_blank';
|
| 782 |
-
document.body.appendChild(a);
|
| 783 |
-
a.click();
|
| 784 |
-
a.remove();
|
| 785 |
-
}
|
| 786 |
-
|
| 787 |
-
// ─── DELETE ───────────────────────────────────────────────
|
| 788 |
-
function openDeleteModal(path, name, type = 'file') {
|
| 789 |
-
pendingDeletePath = path;
|
| 790 |
-
pendingDeleteType = type;
|
| 791 |
-
const p = deleteModal.querySelector('p');
|
| 792 |
-
if (p) p.innerHTML = `This will permanently delete <strong>${name}</strong> from your repository.`;
|
| 793 |
-
deleteModal.classList.add('active');
|
| 794 |
-
}
|
| 795 |
-
closeDeleteModal.addEventListener('click', () => deleteModal.classList.remove('active'));
|
| 796 |
-
cancelDeleteBtn.addEventListener('click', () => deleteModal.classList.remove('active'));
|
| 797 |
-
confirmDeleteBtn.addEventListener('click', async () => {
|
| 798 |
-
if (!pendingDeletePath) return;
|
| 799 |
-
deleteModal.classList.remove('active');
|
| 800 |
-
showProgress(`Deleting…`);
|
| 801 |
-
try {
|
| 802 |
-
await deleteItemAPI(pendingDeletePath, pendingDeleteType);
|
| 803 |
-
showToast('✅ Deleted successfully.', 'success');
|
| 804 |
-
fetchAndRender();
|
| 805 |
-
} catch (err) {
|
| 806 |
-
showToast('❌ Delete failed: ' + err.message, 'error');
|
| 807 |
-
} finally {
|
| 808 |
-
hideProgress();
|
| 809 |
-
pendingDeletePath = null;
|
| 810 |
-
pendingDeleteType = 'file';
|
| 811 |
-
}
|
| 812 |
-
});
|
| 813 |
-
|
| 814 |
-
// ─── UPLOAD ───────────────────────────────────────────────
|
| 815 |
-
async function uploadFiles(fileList) {
|
| 816 |
-
if (!fileList || !fileList.length) return;
|
| 817 |
-
|
| 818 |
-
const files = Array.from(fileList);
|
| 819 |
-
let done = 0;
|
| 820 |
-
for (const file of files) {
|
| 821 |
-
const destPath = getFolderPath();
|
| 822 |
-
const filePath = getFilePath(file.name);
|
| 823 |
-
showProgress(`Uploading ${file.name} (${done + 1}/${files.length})…`);
|
| 824 |
-
try {
|
| 825 |
-
await uploadFileAPI(file, destPath);
|
| 826 |
-
addToRecent(filePath, file.name, 'file');
|
| 827 |
-
done++;
|
| 828 |
-
} catch (err) {
|
| 829 |
-
showToast(`❌ Failed to upload ${file.name}: ${err.message}`, 'error');
|
| 830 |
-
}
|
| 831 |
-
}
|
| 832 |
-
hideProgress();
|
| 833 |
-
if (done > 0) {
|
| 834 |
-
showToast(`✅ Uploaded ${done} file${done > 1 ? 's' : ''} successfully!`, 'success');
|
| 835 |
-
fetchAndRender();
|
| 836 |
-
}
|
| 837 |
-
}
|
| 838 |
-
|
| 839 |
-
// ─── DRAG & DROP ──────────────────────────────────────────
|
| 840 |
-
let dragCounter = 0;
|
| 841 |
-
contentArea.addEventListener('dragenter', (e) => {
|
| 842 |
-
e.preventDefault(); dragCounter++;
|
| 843 |
-
contentArea.classList.add('drag-over');
|
| 844 |
-
});
|
| 845 |
-
contentArea.addEventListener('dragleave', (e) => {
|
| 846 |
-
e.preventDefault(); dragCounter--;
|
| 847 |
-
if (dragCounter <= 0) { dragCounter = 0; contentArea.classList.remove('drag-over'); }
|
| 848 |
-
});
|
| 849 |
-
contentArea.addEventListener('dragover', (e) => { e.preventDefault(); });
|
| 850 |
-
contentArea.addEventListener('drop', (e) => {
|
| 851 |
-
e.preventDefault(); dragCounter = 0;
|
| 852 |
-
contentArea.classList.remove('drag-over');
|
| 853 |
-
const files = e.dataTransfer?.files;
|
| 854 |
-
if (files && files.length) uploadFiles(files);
|
| 855 |
-
});
|
| 856 |
-
|
| 857 |
-
// Also add drop to entire body for full-window drop
|
| 858 |
-
document.addEventListener('dragover', (e) => e.preventDefault());
|
| 859 |
-
|
| 860 |
-
// ─── PROGRESS BAR ────────────────────────────────────────
|
| 861 |
-
function showProgress(msg = 'Working…') {
|
| 862 |
-
progressText.textContent = msg;
|
| 863 |
-
uploadProgress.classList.add('active');
|
| 864 |
-
}
|
| 865 |
-
function hideProgress() { uploadProgress.classList.remove('active'); }
|
| 866 |
-
|
| 867 |
-
// ─── FILE INPUT ───────────────────────────────────────────
|
| 868 |
-
fileInput.addEventListener('change', () => {
|
| 869 |
-
console.log('File input changed, files:', fileInput.files.length); // Debug
|
| 870 |
-
if (fileInput.files && fileInput.files.length > 0) {
|
| 871 |
-
uploadFiles(fileInput.files);
|
| 872 |
-
}
|
| 873 |
-
fileInput.value = '';
|
| 874 |
-
});
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
// ─── NEW BUTTON ───────────────────────────────────────────
|
| 879 |
-
newBtn.addEventListener('click', (e) => {
|
| 880 |
-
e.stopPropagation();
|
| 881 |
-
newDropdown.classList.toggle('active');
|
| 882 |
-
});
|
| 883 |
-
createFolderBtn.addEventListener('click', () => {
|
| 884 |
-
newDropdown.classList.remove('active');
|
| 885 |
-
folderNameInput.value = '';
|
| 886 |
-
createFolderModal.classList.add('active');
|
| 887 |
-
setTimeout(() => folderNameInput.focus(), 100);
|
| 888 |
-
});
|
| 889 |
-
uploadFileBtn.addEventListener('click', (e) => {
|
| 890 |
-
e.preventDefault();
|
| 891 |
-
e.stopPropagation();
|
| 892 |
-
console.log('Upload button clicked'); // Debug
|
| 893 |
-
newDropdown.classList.remove('active');
|
| 894 |
-
// Use try-catch in case fileInput doesn't exist
|
| 895 |
-
try {
|
| 896 |
-
if (fileInput) {
|
| 897 |
-
fileInput.click();
|
| 898 |
-
console.log('fileInput.click() called'); // Debug
|
| 899 |
-
} else {
|
| 900 |
-
console.error('fileInput element not found');
|
| 901 |
-
showToast('Error: File input not available', 'error');
|
| 902 |
-
}
|
| 903 |
-
} catch (err) {
|
| 904 |
-
console.error('Error clicking file input:', err);
|
| 905 |
-
showToast('Error: Could not open file dialog', 'error');
|
| 906 |
-
}
|
| 907 |
-
});
|
| 908 |
-
|
| 909 |
-
// ─── CREATE FOLDER ────────────────────────────────────────
|
| 910 |
-
closeNameModal.addEventListener('click', () => createFolderModal.classList.remove('active'));
|
| 911 |
-
cancelFolderBtn.addEventListener('click', () => createFolderModal.classList.remove('active'));
|
| 912 |
-
confirmFolderBtn.addEventListener('click', async () => {
|
| 913 |
-
const name = folderNameInput.value.trim();
|
| 914 |
-
if (!name) { folderNameInput.focus(); return; }
|
| 915 |
-
createFolderModal.classList.remove('active');
|
| 916 |
-
showProgress(`Creating folder "${name}"…`);
|
| 917 |
-
try {
|
| 918 |
-
const folderPath = getFilePath(name);
|
| 919 |
-
await createFolderAPI(folderPath);
|
| 920 |
-
showToast(`📁 Folder "${name}" created!`, 'success');
|
| 921 |
-
fetchAndRender();
|
| 922 |
-
} catch (err) {
|
| 923 |
-
console.error('Folder creation failed:', err.message);
|
| 924 |
-
showToast(`❌ Folder creation failed: ${err.message}`, 'error');
|
| 925 |
-
} finally { hideProgress(); }
|
| 926 |
-
});
|
| 927 |
-
folderNameInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') confirmFolderBtn.click(); });
|
| 928 |
-
|
| 929 |
-
// ─── SEARCH ───────────────────────────────────────────────
|
| 930 |
-
let searchDebounce;
|
| 931 |
-
searchInput.addEventListener('input', () => {
|
| 932 |
-
clearTimeout(searchDebounce);
|
| 933 |
-
searchDebounce = setTimeout(() => {
|
| 934 |
-
searchQuery = searchInput.value.trim();
|
| 935 |
-
fetchAndRender();
|
| 936 |
-
}, 400);
|
| 937 |
-
});
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
// ─── NAV ──────────────────────────────────────────────────
|
| 942 |
-
function setNavActive(nav) {
|
| 943 |
-
[navMyFiles, navRecent, navStarred].forEach(n => n.classList.remove('active'));
|
| 944 |
-
nav.classList.add('active');
|
| 945 |
-
}
|
| 946 |
-
|
| 947 |
-
navMyFiles.addEventListener('click', (e) => {
|
| 948 |
-
e.preventDefault();
|
| 949 |
-
e.stopPropagation();
|
| 950 |
-
e.stopImmediatePropagation();
|
| 951 |
-
currentBrowse = 'files'; currentPath = [];
|
| 952 |
-
setNavActive(navMyFiles);
|
| 953 |
-
fetchAndRender();
|
| 954 |
-
});
|
| 955 |
-
|
| 956 |
-
navRecent.addEventListener('click', (e) => {
|
| 957 |
-
e.preventDefault();
|
| 958 |
-
currentBrowse = 'recent';
|
| 959 |
-
setNavActive(navRecent);
|
| 960 |
-
renderRecentView();
|
| 961 |
-
});
|
| 962 |
-
|
| 963 |
-
navStarred.addEventListener('click', (e) => {
|
| 964 |
-
e.preventDefault();
|
| 965 |
-
currentBrowse = 'starred';
|
| 966 |
-
setNavActive(navStarred);
|
| 967 |
-
renderStarredView();
|
| 968 |
-
});
|
| 969 |
-
|
| 970 |
-
function renderRecentView() {
|
| 971 |
-
foldersContainer.innerHTML = '';
|
| 972 |
-
breadcrumbsEl.innerHTML = '<span class="breadcrumb-item active">Recent</span>';
|
| 973 |
-
const items = getRecent();
|
| 974 |
-
filesContainer.innerHTML = '';
|
| 975 |
-
if (!items.length) { showEmpty(filesContainer, 'No recently opened files.'); return; }
|
| 976 |
-
items.forEach(item => {
|
| 977 |
-
const { icon, color } = getFileIcon(item.name);
|
| 978 |
-
const url = getFileUrl(item.path);
|
| 979 |
-
const card = document.createElement('div');
|
| 980 |
-
card.className = 'file-card';
|
| 981 |
-
const ext = getExt(item.name).toUpperCase() || 'FILE';
|
| 982 |
-
const isImg = isImage(item.name);
|
| 983 |
-
const previewHTML = isImg
|
| 984 |
-
? `<img src="${url}" alt="${item.name}" loading="lazy" onerror="this.parentElement.innerHTML='<span class=\\'file-icon\\'>📄</span>'">`
|
| 985 |
-
: `<span class="file-icon">${getFileEmoji(ext)}</span>`;
|
| 986 |
-
|
| 987 |
-
card.innerHTML = `
|
| 988 |
-
<div class="file-preview">
|
| 989 |
-
${previewHTML}
|
| 990 |
-
</div>
|
| 991 |
-
<div class="file-info">
|
| 992 |
-
<span class="file-type">${ext}</span>
|
| 993 |
-
<h4 class="file-name" title="${item.name}">${item.name}</h4>
|
| 994 |
-
<p class="file-meta">${item.path}</p>
|
| 995 |
-
</div>
|
| 996 |
-
<div class="file-actions">⋮</div>`;
|
| 997 |
-
card.addEventListener('click', () => openPreview(item.path, item.name, url));
|
| 998 |
-
filesContainer.appendChild(card);
|
| 999 |
-
});
|
| 1000 |
-
}
|
| 1001 |
-
|
| 1002 |
-
function renderStarredView() {
|
| 1003 |
-
foldersContainer.innerHTML = '';
|
| 1004 |
-
breadcrumbsEl.innerHTML = '<span class="breadcrumb-item active">Starred</span>';
|
| 1005 |
-
const starred = getStarred();
|
| 1006 |
-
filesContainer.innerHTML = '';
|
| 1007 |
-
if (!starred.length) { showEmpty(filesContainer, 'No starred files yet.'); return; }
|
| 1008 |
-
starred.forEach(path => {
|
| 1009 |
-
const name = path.split('/').pop();
|
| 1010 |
-
const url = getFileUrl(path);
|
| 1011 |
-
const { icon, color } = getFileIcon(name);
|
| 1012 |
-
const card = document.createElement('div');
|
| 1013 |
-
card.className = 'file-card';
|
| 1014 |
-
const ext = getExt(name).toUpperCase() || 'FILE';
|
| 1015 |
-
const isImg = isImage(name);
|
| 1016 |
-
const previewHTML = isImg
|
| 1017 |
-
? `<img src="${url}" alt="${name}" loading="lazy" onerror="this.parentElement.innerHTML='<span class=\\'file-icon\\'>📄</span>'">`
|
| 1018 |
-
: `<span class="file-icon">${getFileEmoji(ext)}</span>`;
|
| 1019 |
-
|
| 1020 |
-
card.innerHTML = `
|
| 1021 |
-
<div class="file-preview">
|
| 1022 |
-
${previewHTML}
|
| 1023 |
-
</div>
|
| 1024 |
-
<div class="file-info">
|
| 1025 |
-
<span class="file-type">${ext}</span>
|
| 1026 |
-
<h4 class="file-name" title="${name}">${name}</h4>
|
| 1027 |
-
<p class="file-meta">${path}</p>
|
| 1028 |
-
</div>
|
| 1029 |
-
<div class="file-actions">⋮</div>`;
|
| 1030 |
-
card.addEventListener('click', () => openPreview(path, name, url));
|
| 1031 |
-
filesContainer.appendChild(card);
|
| 1032 |
-
});
|
| 1033 |
-
}
|
| 1034 |
-
|
| 1035 |
-
// ─── VIEW TOGGLES ─────────────────────────────────────────
|
| 1036 |
-
viewGrid.addEventListener('click', () => {
|
| 1037 |
-
if (currentViewMode === 'grid') return;
|
| 1038 |
-
currentViewMode = 'grid';
|
| 1039 |
-
viewGrid.classList.add('active'); viewList.classList.remove('active');
|
| 1040 |
-
renderView();
|
| 1041 |
-
});
|
| 1042 |
-
viewList.addEventListener('click', () => {
|
| 1043 |
-
if (currentViewMode === 'list') return;
|
| 1044 |
-
currentViewMode = 'list';
|
| 1045 |
-
viewList.classList.add('active'); viewGrid.classList.remove('active');
|
| 1046 |
-
renderView();
|
| 1047 |
-
});
|
| 1048 |
-
function renderView() {
|
| 1049 |
-
if (currentBrowse === 'recent') { renderRecentView(); return; }
|
| 1050 |
-
if (currentBrowse === 'starred') { renderStarredView(); return; }
|
| 1051 |
-
fetchAndRender();
|
| 1052 |
-
}
|
| 1053 |
-
|
| 1054 |
-
// ─── KEYBOARD SHORTCUTS ───────────────────────────────────
|
| 1055 |
-
document.addEventListener('keydown', (e) => {
|
| 1056 |
-
if (e.key === 'Escape') {
|
| 1057 |
-
previewModal.classList.remove('active');
|
| 1058 |
-
deleteModal.classList.remove('active');
|
| 1059 |
-
createFolderModal.classList.remove('active');
|
| 1060 |
-
}
|
| 1061 |
-
});
|
| 1062 |
-
|
| 1063 |
-
// ─── RENAME ───────────────────────────────────────────────
|
| 1064 |
-
const renameModal = $('renameModal');
|
| 1065 |
-
const closeRenameModal = $('closeRenameModal');
|
| 1066 |
-
const cancelRenameBtn = $('cancelRenameBtn');
|
| 1067 |
-
const confirmRenameBtn = $('confirmRenameBtn');
|
| 1068 |
-
const renameInput = $('renameInput');
|
| 1069 |
-
let pendingRenamePath = null;
|
| 1070 |
-
|
| 1071 |
-
function openRenameModal(filePath, currentName) {
|
| 1072 |
-
pendingRenamePath = filePath;
|
| 1073 |
-
renameInput.value = currentName;
|
| 1074 |
-
renameModal.classList.add('active');
|
| 1075 |
-
setTimeout(() => { renameInput.select(); }, 100);
|
| 1076 |
-
}
|
| 1077 |
-
|
| 1078 |
-
closeRenameModal.addEventListener('click', () => renameModal.classList.remove('active'));
|
| 1079 |
-
cancelRenameBtn.addEventListener('click', () => renameModal.classList.remove('active'));
|
| 1080 |
-
renameInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') confirmRenameBtn.click(); });
|
| 1081 |
-
|
| 1082 |
-
confirmRenameBtn.addEventListener('click', async () => {
|
| 1083 |
-
const newName = renameInput.value.trim();
|
| 1084 |
-
if (!newName || !pendingRenamePath) return;
|
| 1085 |
-
|
| 1086 |
-
const oldPath = pendingRenamePath;
|
| 1087 |
-
const dir = oldPath.includes('/') ? oldPath.substring(0, oldPath.lastIndexOf('/')) : '';
|
| 1088 |
-
const newPath = dir ? `${dir}/${newName}` : newName;
|
| 1089 |
-
|
| 1090 |
-
if (oldPath === newPath) { renameModal.classList.remove('active'); return; }
|
| 1091 |
-
|
| 1092 |
-
renameModal.classList.remove('active');
|
| 1093 |
-
showProgress(`Renaming to "${newName}"…`);
|
| 1094 |
-
try {
|
| 1095 |
-
// Use rename API for direct renaming
|
| 1096 |
-
await renameItemAPI(oldPath, newName);
|
| 1097 |
-
showToast(`✅ Renamed to "${newName}"!`, 'success');
|
| 1098 |
-
fetchAndRender();
|
| 1099 |
-
} catch (err) {
|
| 1100 |
-
showToast('❌ Rename failed: ' + err.message, 'error');
|
| 1101 |
-
} finally { hideProgress(); pendingRenamePath = null; }
|
| 1102 |
-
});
|
| 1103 |
-
|
| 1104 |
-
// ─── INIT ─────────────────────────────────────────────────
|
| 1105 |
-
// Initialize offline-first DocVault
|
| 1106 |
-
(function initApp() {
|
| 1107 |
-
console.log('🚀 DocVault initializing...'); // Debug
|
| 1108 |
-
console.log('API_BASE:', API_BASE); // Debug
|
| 1109 |
-
console.log('USER_ID:', USER_ID); // Debug
|
| 1110 |
-
console.log('DOM Elements check:', {
|
| 1111 |
-
fileInput: !!fileInput,
|
| 1112 |
-
uploadFileBtn: !!uploadFileBtn,
|
| 1113 |
-
foldersContainer: !!foldersContainer,
|
| 1114 |
-
filesContainer: !!filesContainer
|
| 1115 |
-
}); // Debug
|
| 1116 |
-
|
| 1117 |
-
// Show welcome message
|
| 1118 |
-
showToast('🎉 Welcome to DocVault! Loading your files...', 'info');
|
| 1119 |
-
|
| 1120 |
-
// Auto-load files from local backend
|
| 1121 |
-
fetchAndRender();
|
| 1122 |
-
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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