modernizing frontend

This commit is contained in:
Diocrafts
2026-02-08 22:44:42 +01:00
parent 03b409bbbc
commit 5bd505ccd7
31 changed files with 3262 additions and 451 deletions
+274 -54
View File
@@ -126,7 +126,6 @@ function cacheElements() {
elements.gridViewBtn = document.getElementById('grid-view-btn');
elements.listViewBtn = document.getElementById('list-view-btn');
elements.breadcrumb = document.querySelector('.breadcrumb');
elements.logoutBtn = document.getElementById('logout-btn');
elements.pageTitle = document.querySelector('.page-title');
elements.actionsBar = document.querySelector('.actions-bar');
elements.navItems = document.querySelectorAll('.nav-item');
@@ -134,6 +133,197 @@ function cacheElements() {
elements.searchInput = document.querySelector('.search-container input');
}
/**
* Setup the user menu (avatar dropdown with profile, storage, theme, about, logout)
*/
function setupUserMenu() {
const wrapper = document.getElementById('user-menu-wrapper');
const avatarBtn = document.getElementById('user-avatar-btn');
const menu = document.getElementById('user-menu');
const logoutBtn = document.getElementById('user-menu-logout');
const themeBtn = document.getElementById('user-menu-theme');
const aboutBtn = document.getElementById('user-menu-about');
if (!wrapper || !avatarBtn || !menu) return;
// Toggle menu
avatarBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = wrapper.classList.contains('open');
wrapper.classList.toggle('open');
if (!isOpen) {
updateUserMenuData();
}
});
// Close menu on outside click
document.addEventListener('click', (e) => {
if (wrapper.classList.contains('open') && !wrapper.contains(e.target)) {
wrapper.classList.remove('open');
}
});
// Logout
if (logoutBtn) {
logoutBtn.addEventListener('click', () => {
wrapper.classList.remove('open');
logout();
});
}
// Theme toggle (dark mode placeholder — toggles pill visually)
if (themeBtn) {
const pill = document.getElementById('theme-toggle-pill');
const isDark = localStorage.getItem('oxicloud_theme') === 'dark';
if (isDark && pill) pill.classList.add('active');
themeBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (pill) {
pill.classList.toggle('active');
const dark = pill.classList.contains('active');
localStorage.setItem('oxicloud_theme', dark ? 'dark' : 'light');
// Theme switching could be expanded here in the future
window.ui.showNotification(
dark ? '🌙' : '☀️',
dark ? 'Modo oscuro activado (próximamente)' : 'Modo claro activado'
);
}
});
}
// About modal
if (aboutBtn) {
aboutBtn.addEventListener('click', () => {
wrapper.classList.remove('open');
const overlay = document.getElementById('about-modal-overlay');
if (overlay) overlay.classList.add('show');
});
}
// About modal close
const aboutCloseBtn = document.getElementById('about-close-btn');
const aboutOverlay = document.getElementById('about-modal-overlay');
if (aboutCloseBtn) {
aboutCloseBtn.addEventListener('click', () => {
aboutOverlay.classList.remove('show');
});
}
if (aboutOverlay) {
aboutOverlay.addEventListener('click', (e) => {
if (e.target === aboutOverlay) {
aboutOverlay.classList.remove('show');
}
});
}
// Fetch version from backend (centralized in Cargo.toml)
fetchAppVersion();
}
/**
* Update user menu data (name, email, storage) from localStorage
*/
function updateUserMenuData() {
const USER_DATA_KEY = 'oxicloud_user';
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
const nameEl = document.getElementById('user-menu-name');
const emailEl = document.getElementById('user-menu-email');
const avatarEl = document.getElementById('user-menu-avatar');
const storageFill = document.getElementById('user-menu-storage-fill');
const storageText = document.getElementById('user-menu-storage-text');
if (userData.username) {
if (nameEl) nameEl.textContent = userData.username;
if (emailEl) emailEl.textContent = userData.email || '';
if (avatarEl) avatarEl.textContent = userData.username.substring(0, 2).toUpperCase();
}
// Storage info
const usedBytes = userData.storage_used_bytes || 0;
const quotaBytes = userData.storage_quota_bytes || 10737418240;
const percentage = quotaBytes > 0 ? Math.min(Math.round((usedBytes / quotaBytes) * 100), 100) : 0;
if (storageFill) storageFill.style.width = percentage + '%';
if (storageText) {
const used = formatFileSize(usedBytes);
const total = formatFileSize(quotaBytes);
storageText.textContent = `${percentage}% · ${used} / ${total}`;
}
}
/**
* Fetch app version from backend (centralized in Cargo.toml)
* Updates the about modal version display
*/
async function fetchAppVersion() {
try {
const response = await fetch('/api/version');
if (response.ok) {
const data = await response.json();
const versionEl = document.getElementById('about-version');
if (versionEl && data.version) {
versionEl.textContent = `v${data.version}`;
}
}
} catch (err) {
console.warn('Could not fetch app version:', err);
// Fallback: leave placeholder
}
}
/**
* Setup the upload dropdown button and menu
* Handles opening/closing the dropdown and triggering file/folder inputs
*/
function setupUploadDropdown() {
const dropdown = document.getElementById('upload-dropdown');
const uploadBtn = document.getElementById('upload-btn');
const menu = document.getElementById('upload-dropdown-menu');
const uploadFilesBtn = document.getElementById('upload-files-btn');
const uploadFolderBtn = document.getElementById('upload-folder-btn');
if (!uploadBtn || !menu) return;
// Toggle dropdown on button click
uploadBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = menu.classList.contains('show');
// Close any other open dropdowns
document.querySelectorAll('.upload-dropdown-menu.show').forEach(m => m.classList.remove('show'));
if (!isOpen) {
menu.classList.add('show');
}
});
// Upload files option
if (uploadFilesBtn) {
uploadFilesBtn.addEventListener('click', (e) => {
e.stopPropagation();
menu.classList.remove('show');
elements.fileInput.click();
});
}
// Upload folder option
if (uploadFolderBtn) {
uploadFolderBtn.addEventListener('click', (e) => {
e.stopPropagation();
menu.classList.remove('show');
const folderInput = document.getElementById('folder-input');
if (folderInput) {
folderInput.click();
}
});
}
// Close dropdown when clicking outside
document.addEventListener('click', () => {
document.querySelectorAll('.upload-dropdown-menu.show').forEach(m => m.classList.remove('show'));
});
}
/**
* Setup event listeners for main UI elements
*/
@@ -165,21 +355,28 @@ function setupEventListeners() {
}
});
// Upload button
elements.uploadBtn.addEventListener('click', () => {
elements.dropzone.style.display = elements.dropzone.style.display === 'none' ? 'block' : 'none';
if (elements.dropzone.style.display === 'block') {
elements.fileInput.click();
}
});
// Upload dropdown
setupUploadDropdown();
// File input
elements.fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
fileOps.uploadFiles(e.target.files);
e.target.value = ''; // reset so same file can be re-uploaded
}
});
// Folder input
const folderInput = document.getElementById('folder-input');
if (folderInput) {
folderInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
fileOps.uploadFolderFiles(e.target.files);
e.target.value = '';
}
});
}
// New folder button
elements.newFolderBtn.addEventListener('click', async () => {
const folderName = await window.Modal.promptNewFolder();
@@ -298,9 +495,23 @@ function setupEventListeners() {
elements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.files') : 'Archivos';
elements.actionsBar.innerHTML = `
<div class="action-buttons">
<button class="btn btn-primary" id="upload-btn">
<i class="fas fa-upload" style="margin-right: 5px;"></i> <span data-i18n="actions.upload">Subir</span>
</button>
<div class="upload-dropdown" id="upload-dropdown">
<button class="btn btn-primary" id="upload-btn">
<i class="fas fa-cloud-upload-alt" style="margin-right: 5px;"></i>
<span data-i18n="actions.upload">Subir</span>
<i class="fas fa-caret-down" style="margin-left: 4px; font-size: 12px;"></i>
</button>
<div class="upload-dropdown-menu" id="upload-dropdown-menu">
<button class="upload-dropdown-item" id="upload-files-btn">
<i class="fas fa-file"></i>
<span data-i18n="actions.upload_files">Subir archivos</span>
</button>
<button class="upload-dropdown-item" id="upload-folder-btn">
<i class="fas fa-folder-open"></i>
<span data-i18n="actions.upload_folder">Subir carpeta</span>
</button>
</div>
</div>
<button class="btn btn-secondary" id="new-folder-btn">
<i class="fas fa-folder-plus" style="margin-right: 5px;"></i> <span data-i18n="actions.new_folder">Nueva carpeta</span>
</button>
@@ -323,12 +534,7 @@ function setupEventListeners() {
if (filesListView) filesListView.style.display = app.currentView === 'list' ? 'block' : 'none';
// Restore event listeners
document.getElementById('upload-btn').addEventListener('click', () => {
elements.dropzone.style.display = elements.dropzone.style.display === 'none' ? 'block' : 'none';
if (elements.dropzone.style.display === 'block') {
elements.fileInput.click();
}
});
setupUploadDropdown();
document.getElementById('new-folder-btn').addEventListener('click', async () => {
const folderName = await window.Modal.promptNewFolder();
@@ -360,10 +566,10 @@ function setupEventListeners() {
ui.switchToListView();
}
// Logout button
elements.logoutBtn.addEventListener('click', logout);
// User menu
setupUserMenu();
// Global events to close context menus
// Global events to close context menus and deselect cards
document.addEventListener('click', (e) => {
const folderMenu = document.getElementById('folder-context-menu');
const fileMenu = document.getElementById('file-context-menu');
@@ -377,6 +583,11 @@ function setupEventListeners() {
!fileMenu.contains(e.target)) {
ui.closeFileContextMenu();
}
// Deselect all cards when clicking empty area (not on a card, menu, or modal)
if (!e.target.closest('.file-card') && !e.target.closest('.context-menu') && !e.target.closest('.about-modal')) {
document.querySelectorAll('.file-card.selected').forEach(c => c.classList.remove('selected'));
}
});
}
@@ -398,6 +609,14 @@ async function loadFiles(options = {}) {
window.isLoadingFiles = true;
// Show loading spinner
elements.filesGrid.innerHTML = `
<div class="files-loading-spinner">
<div class="spinner"></div>
<span>${window.i18n ? window.i18n.t('files.loading') : 'Cargando archivos…'}</span>
</div>
`;
// Always ensure a userHomeFolderId is set
if (!app.userHomeFolderId) {
// If we don't have a home folder ID yet, try to get the user's username
@@ -606,8 +825,8 @@ async function loadTrashItems() {
window.i18n.translatePage();
}
// Update breadcrumb for trash
ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.trash') : 'Papelera');
// Update breadcrumb - just show Home
ui.updateBreadcrumb('');
// Get trash items
const trashItems = await fileOps.getTrashItems();
@@ -833,7 +1052,7 @@ function switchToSharedView() {
elements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.shared') : 'Compartidos';
// Clear breadcrumb and show root
ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.shared') : 'Compartidos');
ui.updateBreadcrumb('');
// Hide standard actions bar
if (elements.actionsBar) {
@@ -873,9 +1092,23 @@ function switchToFilesView() {
// Reset UI
elements.actionsBar.innerHTML = `
<div class="action-buttons">
<button class="btn btn-primary" id="upload-btn">
<i class="fas fa-upload" style="margin-right: 5px;"></i> <span data-i18n="actions.upload">Subir</span>
</button>
<div class="upload-dropdown" id="upload-dropdown">
<button class="btn btn-primary" id="upload-btn">
<i class="fas fa-cloud-upload-alt" style="margin-right: 5px;"></i>
<span data-i18n="actions.upload">Subir</span>
<i class="fas fa-caret-down" style="margin-left: 4px; font-size: 12px;"></i>
</button>
<div class="upload-dropdown-menu" id="upload-dropdown-menu">
<button class="upload-dropdown-item" id="upload-files-btn">
<i class="fas fa-file"></i>
<span data-i18n="actions.upload_files">Subir archivos</span>
</button>
<button class="upload-dropdown-item" id="upload-folder-btn">
<i class="fas fa-folder-open"></i>
<span data-i18n="actions.upload_folder">Subir carpeta</span>
</button>
</div>
</div>
<button class="btn btn-secondary" id="new-folder-btn">
<i class="fas fa-folder-plus" style="margin-right: 5px;"></i> <span data-i18n="actions.new_folder">Nueva carpeta</span>
</button>
@@ -892,12 +1125,7 @@ function switchToFilesView() {
elements.actionsBar.style.display = 'flex';
// Restore event listeners
document.getElementById('upload-btn').addEventListener('click', () => {
elements.dropzone.style.display = elements.dropzone.style.display === 'none' ? 'block' : 'none';
if (elements.dropzone.style.display === 'block') {
elements.fileInput.click();
}
});
setupUploadDropdown();
document.getElementById('new-folder-btn').addEventListener('click', async () => {
const folderName = await window.Modal.promptNewFolder();
@@ -967,7 +1195,7 @@ function switchToFavoritesView() {
elements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.favorites') : 'Favoritos';
// Clear breadcrumb and show root
ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.favorites') : 'Favoritos');
ui.updateBreadcrumb('');
// Hide shared view if it exists
if (window.sharedView) {
@@ -1056,7 +1284,7 @@ function switchToRecentFilesView() {
elements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.recent') : 'Recientes';
// Clear breadcrumb and show root
ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.recent') : 'Recientes');
ui.updateBreadcrumb('');
// Hide shared view if it exists
if (window.sharedView) {
@@ -1231,20 +1459,14 @@ function checkAuthentication() {
localStorage.setItem(USER_DATA_KEY, JSON.stringify(defaultUserData));
// Update avatar with default initials
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = 'US';
}
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => el.textContent = 'US');
// Update storage display with default values
updateStorageUsageDisplay(defaultUserData);
} else {
// Update avatar with user initials
const userInitials = userData.username.substring(0, 2).toUpperCase();
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = userInitials;
}
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => el.textContent = userInitials);
// Show cached storage first, then try to refresh from server
updateStorageUsageDisplay(userData);
@@ -1302,10 +1524,14 @@ function checkAuthentication() {
if (userData.username) {
// Update user avatar with initials
const userInitials = userData.username.substring(0, 2).toUpperCase();
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = userInitials;
}
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => {
el.textContent = userInitials;
});
// Update user menu info
const menuName = document.getElementById('user-menu-name');
const menuEmail = document.getElementById('user-menu-email');
if (menuName) menuName.textContent = userData.username;
if (menuEmail) menuEmail.textContent = userData.email || '';
// Update storage usage information with cached data first (for fast display)
updateStorageUsageDisplay(userData);
@@ -1335,10 +1561,7 @@ function checkAuthentication() {
localStorage.setItem(USER_DATA_KEY, JSON.stringify(defaultUserData));
// Update avatar with default initials
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = 'US';
}
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => el.textContent = 'US');
// Update storage display with default values
updateStorageUsageDisplay(defaultUserData);
@@ -1367,10 +1590,7 @@ function checkAuthentication() {
localStorage.setItem('oxicloud_user', JSON.stringify(defaultUserData));
// Update avatar
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = 'US';
}
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => el.textContent = 'US');
// Update storage display with default values
updateStorageUsageDisplay(defaultUserData);
+243 -26
View File
@@ -23,25 +23,79 @@ const LANGUAGE_TEXTS = {
en: {
title: 'Welcome to OxiCloud',
subtitle: 'Please select your language',
continue: 'Continue'
continue: 'Continue',
autodetected: 'We detected your language',
moreLanguages: 'More languages...',
modalTitle: 'Select language',
searchPlaceholder: 'Search language...'
},
es: {
title: 'Bienvenido a OxiCloud',
subtitle: 'Por favor, selecciona tu idioma',
continue: 'Continuar'
continue: 'Continuar',
autodetected: 'Hemos detectado tu idioma',
moreLanguages: 'Más idiomas...',
modalTitle: 'Seleccionar idioma',
searchPlaceholder: 'Buscar idioma...'
},
zh: {
title: '欢迎使用 OxiCloud',
subtitle: '请选择您的语言',
continue: '继续'
continue: '继续',
autodetected: '我们检测到了您的语言',
moreLanguages: '更多语言...',
modalTitle: '选择语言',
searchPlaceholder: '搜索语言...'
},
fa: {
title: 'به OxiCloud خوش آمدید',
subtitle: 'لطفا زبان خود را انتخاب کنید',
continue: 'ادامه'
continue: 'ادامه',
autodetected: 'زبان شما شناسایی شد',
moreLanguages: 'زبان‌های بیشتر...',
modalTitle: 'انتخاب زبان',
searchPlaceholder: 'جستجوی زبان...'
}
};
// Complete language registry — add new languages here, they'll appear automatically
// `popular: true` languages show as cards on the main screen, the rest in the modal
const ALL_LANGUAGES = [
{ code: 'en', name: 'English', nativeName: 'English', flag: '🇬🇧', popular: true },
{ code: 'es', name: 'Spanish', nativeName: 'Español', flag: '🇪🇸', popular: true },
{ code: 'zh', name: 'Chinese', nativeName: '中文', flag: '🇨🇳', popular: true },
{ code: 'fa', name: 'Persian', nativeName: 'فارسی', flag: '🇮🇷', popular: true },
{ code: 'fr', name: 'French', nativeName: 'Français', flag: '🇫🇷', popular: false },
{ code: 'de', name: 'German', nativeName: 'Deutsch', flag: '🇩🇪', popular: false },
{ code: 'pt', name: 'Portuguese', nativeName: 'Português', flag: '🇧🇷', popular: false },
{ code: 'it', name: 'Italian', nativeName: 'Italiano', flag: '🇮🇹', popular: false },
{ code: 'ru', name: 'Russian', nativeName: 'Русский', flag: '🇷🇺', popular: false },
{ code: 'ja', name: 'Japanese', nativeName: '日本語', flag: '🇯🇵', popular: false },
{ code: 'ko', name: 'Korean', nativeName: '한국어', flag: '🇰🇷', popular: false },
{ code: 'ar', name: 'Arabic', nativeName: 'العربية', flag: '🇸🇦', popular: false },
{ code: 'hi', name: 'Hindi', nativeName: 'हिन्दी', flag: '🇮🇳', popular: false },
{ code: 'tr', name: 'Turkish', nativeName: 'Türkçe', flag: '🇹🇷', popular: false },
{ code: 'nl', name: 'Dutch', nativeName: 'Nederlands', flag: '🇳🇱', popular: false },
{ code: 'pl', name: 'Polish', nativeName: 'Polski', flag: '🇵🇱', popular: false },
{ code: 'sv', name: 'Swedish', nativeName: 'Svenska', flag: '🇸🇪', popular: false },
{ code: 'da', name: 'Danish', nativeName: 'Dansk', flag: '🇩🇰', popular: false },
{ code: 'fi', name: 'Finnish', nativeName: 'Suomi', flag: '🇫🇮', popular: false },
{ code: 'no', name: 'Norwegian', nativeName: 'Norsk', flag: '🇳🇴', popular: false },
{ code: 'uk', name: 'Ukrainian', nativeName: 'Українська', flag: '🇺🇦', popular: false },
{ code: 'cs', name: 'Czech', nativeName: 'Čeština', flag: '🇨🇿', popular: false },
{ code: 'el', name: 'Greek', nativeName: 'Ελληνικά', flag: '🇬🇷', popular: false },
{ code: 'he', name: 'Hebrew', nativeName: 'עברית', flag: '🇮🇱', popular: false },
{ code: 'th', name: 'Thai', nativeName: 'ไทย', flag: '🇹🇭', popular: false },
{ code: 'vi', name: 'Vietnamese', nativeName: 'Tiếng Việt', flag: '🇻🇳', popular: false },
{ code: 'id', name: 'Indonesian', nativeName: 'Bahasa Indonesia', flag: '🇮🇩', popular: false },
{ code: 'ms', name: 'Malay', nativeName: 'Bahasa Melayu', flag: '🇲🇾', popular: false },
{ code: 'ro', name: 'Romanian', nativeName: 'Română', flag: '🇷🇴', popular: false },
{ code: 'hu', name: 'Hungarian', nativeName: 'Magyar', flag: '🇭🇺', popular: false },
{ code: 'ca', name: 'Catalan', nativeName: 'Català', flag: '🏴', popular: false },
{ code: 'eu', name: 'Basque', nativeName: 'Euskara', flag: '🏴', popular: false },
{ code: 'gl', name: 'Galician', nativeName: 'Galego', flag: '🏴', popular: false },
];
// Check if this is a first run (no locale saved)
function isFirstRun() {
return !localStorage.getItem(LOCALE_KEY);
@@ -62,35 +116,117 @@ async function checkSystemStatus() {
}
}
// Initialize language selector panel
// Detect user's browser language and return the best matching language from ALL_LANGUAGES
function detectBrowserLanguage() {
const browserLangs = navigator.languages || [navigator.language || navigator.userLanguage || 'en'];
for (const bl of browserLangs) {
const code = bl.substring(0, 2).toLowerCase();
const match = ALL_LANGUAGES.find(l => l.code === code);
if (match) return match;
}
return ALL_LANGUAGES[0]; // fallback to English
}
// Build a language option element (card style)
function buildLanguageCard(lang, isSelected) {
const label = document.createElement('label');
label.className = 'language-option' + (isSelected ? ' selected' : '');
label.setAttribute('data-lang', lang.code);
label.innerHTML = `
<input type="radio" name="language" value="${lang.code}" ${isSelected ? 'checked' : ''}>
<span class="language-radio"></span>
<span class="language-flag">${lang.flag}</span>
<span class="language-name">${lang.nativeName}</span>
`;
return label;
}
// Initialize language selector panel with hybrid approach
function initLanguageSelector() {
const languagePanel = document.getElementById('language-panel');
const languageOptions = document.querySelectorAll('.language-option');
const continueBtn = document.getElementById('language-continue');
const optionsContainer = document.getElementById('language-options');
const moreLangBtn = document.getElementById('lang-more-btn');
if (!languagePanel || !optionsContainer) return;
let selectedLanguage = null;
if (!languagePanel) return;
// --- Auto-detect browser language ---
const detected = detectBrowserLanguage();
// Handle language option clicks
languageOptions.forEach(option => {
option.addEventListener('click', () => {
// Remove selected class from all options
languageOptions.forEach(opt => opt.classList.remove('selected'));
// Add selected class to clicked option
option.classList.add('selected');
// Check the radio button
option.querySelector('input[type="radio"]').checked = true;
// Store selected language
selectedLanguage = option.getAttribute('data-lang');
// Enable continue button
// Build the list of popular languages to show as cards
// If the detected language isn't already popular, promote it to the top
let popularLangs = ALL_LANGUAGES.filter(l => l.popular);
const detectedInPopular = popularLangs.find(l => l.code === detected.code);
if (!detectedInPopular) {
// Insert detected language at the top of popular cards
popularLangs = [detected, ...popularLangs];
}
// Auto-select the detected language
selectedLanguage = detected.code;
continueBtn.disabled = false;
// Show autodetection banner
const autodetectedBanner = document.getElementById('lang-autodetected');
if (autodetectedBanner) {
autodetectedBanner.style.display = 'flex';
}
updateLanguagePanelTexts(detected.code);
// --- Render popular language cards ---
optionsContainer.innerHTML = '';
popularLangs.forEach(lang => {
const card = buildLanguageCard(lang, lang.code === selectedLanguage);
card.addEventListener('click', () => {
// Deselect all
optionsContainer.querySelectorAll('.language-option').forEach(o => o.classList.remove('selected'));
card.classList.add('selected');
card.querySelector('input[type="radio"]').checked = true;
selectedLanguage = lang.code;
continueBtn.disabled = false;
// Update UI texts based on selected language
updateLanguagePanelTexts(selectedLanguage);
updateLanguagePanelTexts(lang.code);
});
optionsContainer.appendChild(card);
});
// Handle continue button click
// --- "More languages" button opens the modal ---
if (moreLangBtn) {
moreLangBtn.addEventListener('click', () => openLanguageModal(selectedLanguage, (langCode) => {
selectedLanguage = langCode;
continueBtn.disabled = false;
updateLanguagePanelTexts(langCode);
// Update cards to reflect new selection
optionsContainer.querySelectorAll('.language-option').forEach(o => {
const isThis = o.getAttribute('data-lang') === langCode;
o.classList.toggle('selected', isThis);
o.querySelector('input[type="radio"]').checked = isThis;
});
// If selected lang is not in the popular cards, add it temporarily
if (!optionsContainer.querySelector(`[data-lang="${langCode}"]`)) {
const lang = ALL_LANGUAGES.find(l => l.code === langCode);
if (lang) {
// Deselect all existing
optionsContainer.querySelectorAll('.language-option').forEach(o => o.classList.remove('selected'));
const card = buildLanguageCard(lang, true);
card.addEventListener('click', () => {
optionsContainer.querySelectorAll('.language-option').forEach(o => o.classList.remove('selected'));
card.classList.add('selected');
card.querySelector('input[type="radio"]').checked = true;
selectedLanguage = lang.code;
updateLanguagePanelTexts(lang.code);
});
// Insert at the top
optionsContainer.insertBefore(card, optionsContainer.firstChild);
}
}
}));
}
// --- Continue button ---
continueBtn.addEventListener('click', async () => {
if (!selectedLanguage) return;
@@ -111,19 +247,16 @@ function initLanguageSelector() {
console.log('System status after language selection:', systemStatus);
if (!systemStatus.initialized) {
// No admin exists - show admin setup
console.log('No admin exists, showing admin setup panel');
document.getElementById('login-panel').style.display = 'none';
document.getElementById('register-panel').style.display = 'none';
document.getElementById('admin-setup-panel').style.display = 'block';
// Hide the "Already set up? Sign in" link
const backToLoginLink = document.getElementById('back-to-login');
if (backToLoginLink) {
backToLoginLink.parentElement.style.display = 'none';
}
} else {
// Admin exists - show login panel
document.getElementById('login-panel').style.display = 'block';
}
@@ -134,16 +267,100 @@ function initLanguageSelector() {
});
}
// Open the full language modal with search
function openLanguageModal(currentSelection, onSelect) {
const overlay = document.getElementById('lang-modal-overlay');
const list = document.getElementById('lang-modal-list');
const searchInput = document.getElementById('lang-search-input');
const closeBtn = document.getElementById('lang-modal-close');
if (!overlay || !list) return;
// Render all languages
function renderList(filter = '') {
list.innerHTML = '';
const filterLower = filter.toLowerCase();
const filtered = ALL_LANGUAGES.filter(lang => {
if (!filter) return true;
return lang.name.toLowerCase().includes(filterLower) ||
lang.nativeName.toLowerCase().includes(filterLower) ||
lang.code.toLowerCase().includes(filterLower);
});
if (filtered.length === 0) {
list.innerHTML = '<div class="lang-modal-empty">No languages found</div>';
return;
}
filtered.forEach(lang => {
const item = document.createElement('div');
item.className = 'lang-modal-item' + (lang.code === currentSelection ? ' selected' : '');
item.setAttribute('data-lang', lang.code);
item.innerHTML = `
<span class="lang-modal-flag">${lang.flag}</span>
<span class="lang-modal-native">${lang.nativeName}</span>
<span class="lang-modal-english">${lang.name}</span>
${lang.code === currentSelection ? '<i class="fas fa-check lang-modal-check"></i>' : ''}
`;
item.addEventListener('click', () => {
currentSelection = lang.code;
onSelect(lang.code);
closeModal();
});
list.appendChild(item);
});
}
function closeModal() {
overlay.style.display = 'none';
if (searchInput) searchInput.value = '';
}
// Show modal
overlay.style.display = 'flex';
renderList();
// Focus search
if (searchInput) {
setTimeout(() => searchInput.focus(), 100);
searchInput.value = '';
searchInput.oninput = () => renderList(searchInput.value);
}
// Close handlers
if (closeBtn) {
closeBtn.onclick = closeModal;
}
overlay.onclick = (e) => {
if (e.target === overlay) closeModal();
};
document.addEventListener('keydown', function escHandler(e) {
if (e.key === 'Escape') {
closeModal();
document.removeEventListener('keydown', escHandler);
}
});
}
// Update language panel texts based on selected language
function updateLanguagePanelTexts(lang) {
const texts = LANGUAGE_TEXTS[lang] || LANGUAGE_TEXTS.en;
const titleEl = document.getElementById('language-title');
const subtitleEl = document.getElementById('language-subtitle');
const continueBtn = document.getElementById('language-continue');
const autodetectedText = document.getElementById('lang-autodetected-text');
const moreText = document.getElementById('lang-more-text');
const modalTitle = document.getElementById('lang-modal-title');
const searchInput = document.getElementById('lang-search-input');
if (titleEl) titleEl.textContent = texts.title;
if (subtitleEl) subtitleEl.textContent = texts.subtitle;
if (continueBtn) continueBtn.textContent = texts.continue;
if (autodetectedText) autodetectedText.textContent = texts.autodetected;
if (moreText) moreText.textContent = texts.moreLanguages;
if (modalTitle) modalTitle.textContent = texts.modalTitle;
if (searchInput) searchInput.placeholder = texts.searchPlaceholder;
}
// Show appropriate panel based on system status and first run
+1 -11
View File
@@ -60,14 +60,6 @@ const sharedView = {
// Update container
sharedContainer.innerHTML = `
<div class="actions-bar">
<div class="action-buttons">
<button class="btn btn-secondary" id="go-to-files-btn">
<i class="fas fa-arrow-left" style="margin-right: 5px;"></i> <span data-i18n="shared.backToFiles">Back to Files</span>
</button>
</div>
</div>
<div class="shared-filters">
<div class="filter-group">
<label for="filter-type" data-i18n="shared.filterType">Type:</label>
@@ -234,7 +226,6 @@ const sharedView = {
const sortBy = document.getElementById('sort-by');
const searchFilter = document.getElementById('shared-search-filter');
const searchBtn = document.getElementById('shared-search-filter-btn');
const goToFilesBtn = document.getElementById('go-to-files-btn');
const emptyGoToFiles = document.getElementById('empty-go-to-files');
if (filterType) filterType.addEventListener('change', () => this.filterAndSortItems());
@@ -244,8 +235,7 @@ const sharedView = {
});
if (searchBtn) searchBtn.addEventListener('click', () => this.filterAndSortItems());
// Back to files buttons
if (goToFilesBtn) goToFilesBtn.addEventListener('click', () => window.switchToFilesView());
// Back to files button (empty state)
if (emptyGoToFiles) emptyGoToFiles.addEventListener('click', () => window.switchToFilesView());
// Share dialog buttons
+73 -22
View File
@@ -82,7 +82,10 @@ const contextMenus = {
document.getElementById('view-file-option').addEventListener('click', () => {
if (window.app.contextMenuTargetFile) {
// Fetch file details to get the mime type
fetch(`/api/files/${window.app.contextMenuTargetFile.id}?metadata=true`)
const token = localStorage.getItem('oxicloud_token');
fetch(`/api/files/${window.app.contextMenuTargetFile.id}?metadata=true`, {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(response => response.json())
.then(fileDetails => {
// Check if viewable file type
@@ -157,6 +160,13 @@ const contextMenus = {
window.ui.closeFileContextMenu();
});
document.getElementById('rename-file-option').addEventListener('click', () => {
if (window.app.contextMenuTargetFile) {
this.showRenameFileDialog(window.app.contextMenuTargetFile);
}
window.ui.closeFileContextMenu();
});
document.getElementById('move-file-option').addEventListener('click', () => {
if (window.app.contextMenuTargetFile) {
this.showMoveDialog(window.app.contextMenuTargetFile, 'file');
@@ -187,12 +197,12 @@ const contextMenus = {
const renameInput = document.getElementById('rename-input');
renameCancelBtn.addEventListener('click', this.closeRenameDialog);
renameConfirmBtn.addEventListener('click', this.renameFolder);
renameConfirmBtn.addEventListener('click', () => contextMenus.renameItem());
// Rename on Enter key
renameInput.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
this.renameFolder();
contextMenus.renameItem();
} else if (e.key === 'Escape') {
this.closeRenameDialog();
}
@@ -232,7 +242,29 @@ const contextMenus = {
const renameInput = document.getElementById('rename-input');
const renameDialog = document.getElementById('rename-dialog');
window.app.renameMode = 'folder';
renameInput.value = folder.name;
// Update header text
const headerSpan = renameDialog.querySelector('.rename-dialog-header span');
if (headerSpan) headerSpan.textContent = window.i18n ? window.i18n.t('dialogs.rename_folder') : 'Renombrar carpeta';
renameDialog.style.display = 'flex';
renameInput.focus();
renameInput.select();
},
/**
* Show rename dialog for a file
* @param {Object} file - File object
*/
showRenameFileDialog(file) {
const renameInput = document.getElementById('rename-input');
const renameDialog = document.getElementById('rename-dialog');
window.app.renameMode = 'file';
renameInput.value = file.name;
// Update header text
const headerSpan = renameDialog.querySelector('.rename-dialog-header span');
if (headerSpan) headerSpan.textContent = window.i18n ? window.i18n.t('dialogs.rename_file') : 'Renombrar archivo';
renameDialog.style.display = 'flex';
renameInput.focus();
renameInput.select();
@@ -258,11 +290,12 @@ const contextMenus = {
// Reset selection
window.app.selectedTargetFolderId = "";
// Update dialog title
// Update dialog title (preserve icon)
const dialogHeader = document.getElementById('move-file-dialog').querySelector('.rename-dialog-header');
dialogHeader.textContent = mode === 'file' ?
const titleText = mode === 'file' ?
(window.i18n ? window.i18n.t('dialogs.move_file') : 'Mover archivo') :
(window.i18n ? window.i18n.t('dialogs.move_folder') : 'Mover carpeta');
dialogHeader.innerHTML = `<i class="fas fa-arrows-alt" style="color:#ff5e3a"></i> <span>${titleText}</span>`;
// Load all available folders
await this.loadAllFolders(item.id, mode);
@@ -281,24 +314,35 @@ const contextMenus = {
},
/**
* Rename the selected folder
* Rename the selected folder or file
*/
async renameFolder() {
if (!window.app.contextMenuTargetFolder) return;
async renameItem() {
const newName = document.getElementById('rename-input').value.trim();
if (!newName) {
alert(window.i18n ? window.i18n.t('errors.empty_name') : 'El nombre no puede estar vacío');
return;
}
const success = await window.fileOps.renameFolder(window.app.contextMenuTargetFolder.id, newName);
if (success) {
contextMenus.closeRenameDialog();
window.loadFiles();
if (window.app.renameMode === 'file' && window.app.contextMenuTargetFile) {
const success = await window.fileOps.renameFile(window.app.contextMenuTargetFile.id, newName);
if (success) {
contextMenus.closeRenameDialog();
window.loadFiles();
}
} else if (window.app.contextMenuTargetFolder) {
const success = await window.fileOps.renameFolder(window.app.contextMenuTargetFolder.id, newName);
if (success) {
contextMenus.closeRenameDialog();
window.loadFiles();
}
}
},
// Keep backward compat
renameFolder() {
return contextMenus.renameItem();
},
/**
* Load all folders for the move dialog
* @param {string} itemId - ID of the item being moved
@@ -306,7 +350,10 @@ const contextMenus = {
*/
async loadAllFolders(itemId, mode) {
try {
const response = await fetch('/api/folders');
const token = localStorage.getItem('oxicloud_token');
const response = await fetch('/api/folders', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (response.ok) {
const folders = await response.json();
const folderSelectContainer = document.getElementById('folder-select-container');
@@ -459,15 +506,19 @@ const contextMenus = {
e.preventDefault();
const shareId = btn.getAttribute('data-share-id');
if (confirm('¿Estás seguro de que quieres eliminar este enlace compartido?')) {
window.fileSharing.removeSharedLink(shareId);
btn.closest('.existing-share-item').remove();
// Check if we still have shares
if (existingSharesContainer.children.length === 0) {
document.getElementById('existing-shares-section').style.display = 'none';
showConfirmDialog({
title: window.i18n ? window.i18n.t('dialogs.confirm_delete_share') : 'Eliminar enlace',
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_share_msg') : '¿Estás seguro de que quieres eliminar este enlace compartido?',
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Eliminar',
}).then(confirmed => {
if (confirmed) {
window.fileSharing.removeSharedLink(shareId);
btn.closest('.existing-share-item').remove();
if (existingSharesContainer.children.length === 0) {
document.getElementById('existing-shares-section').style.display = 'none';
}
}
}
});
});
});
} else {
+2 -2
View File
@@ -317,8 +317,8 @@ const favorites = {
</div>
`;
// Update breadcrumb for favorites
window.ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.favorites') : 'Favoritos');
// Update breadcrumb - just show Home
window.ui.updateBreadcrumb('');
// Show empty state if no favorites
if (favorites.length === 0) {
+270 -38
View File
@@ -3,6 +3,19 @@
* This file handles file and folder operations (create, move, delete, rename, upload)
*/
/**
* Get authorization headers for API requests
* @returns {Object} Headers object with Authorization bearer token
*/
function getAuthHeaders() {
const token = localStorage.getItem('oxicloud_token');
const headers = {};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return headers;
}
// File Operations Module
const fileOps = {
/**
@@ -49,6 +62,7 @@ const fileOps = {
// Añadir cache: 'no-store' para evitar problemas de caché durante la subida
cache: 'no-store',
headers: {
...getAuthHeaders(),
// Agregar este encabezado para forzar recargas frescas
'Cache-Control': 'no-cache, no-store, must-revalidate'
}
@@ -104,6 +118,133 @@ const fileOps = {
}
},
/**
* Upload folder files maintaining directory structure
* Creates subfolders as needed, then uploads files into them
* @param {FileList} files - Files from folder input (with webkitRelativePath)
*/
async uploadFolderFiles(files) {
if (!files || files.length === 0) return;
const progressBar = document.querySelector('.progress-fill');
const uploadProgressDiv = document.querySelector('.upload-progress');
uploadProgressDiv.style.display = 'block';
progressBar.style.width = '0%';
const currentFolderId = window.app.currentPath || window.app.userHomeFolderId;
// Build folder structure from relative paths
// webkitRelativePath looks like: "folderName/subfolder/file.txt"
const folderMap = new Map(); // path -> folder_id
folderMap.set('', currentFolderId); // root = current folder
// Collect all unique folder paths
const folderPaths = new Set();
for (const file of files) {
const parts = file.webkitRelativePath.split('/');
// Remove filename, keep folder parts
for (let i = 1; i < parts.length; i++) {
const path = parts.slice(0, i).join('/');
folderPaths.add(path);
}
}
// Sort paths by depth so parents are created first
const sortedPaths = [...folderPaths].sort((a, b) =>
a.split('/').length - b.split('/').length
);
// Create folders
for (const folderPath of sortedPaths) {
const parts = folderPath.split('/');
const folderName = parts[parts.length - 1];
const parentPath = parts.slice(0, -1).join('/');
const parentId = folderMap.get(parentPath) || currentFolderId;
try {
const response = await fetch('/api/folders', {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, must-revalidate'
},
body: JSON.stringify({
name: folderName,
parent_id: parentId
})
});
if (response.ok) {
const folder = await response.json();
folderMap.set(folderPath, folder.id);
console.log(`Created folder: ${folderPath} -> ${folder.id}`);
} else {
console.error(`Error creating folder ${folderPath}:`, await response.text());
window.ui.showNotification('Error', `Error creando carpeta: ${folderName}`);
}
} catch (error) {
console.error(`Network error creating folder ${folderPath}:`, error);
}
}
// Upload files into their respective folders
let uploadedCount = 0;
const totalFiles = files.length;
for (let i = 0; i < totalFiles; i++) {
const file = files[i];
const parts = file.webkitRelativePath.split('/');
const parentPath = parts.slice(0, -1).join('/');
const targetFolderId = folderMap.get(parentPath) || currentFolderId;
const formData = new FormData();
formData.append('folder_id', targetFolderId);
formData.append('file', file);
try {
const response = await fetch('/api/files/upload', {
method: 'POST',
body: formData,
cache: 'no-store',
headers: {
...getAuthHeaders(),
'Cache-Control': 'no-cache, no-store, must-revalidate'
}
});
uploadedCount++;
const percentComplete = (uploadedCount / totalFiles) * 100;
progressBar.style.width = percentComplete + '%';
if (response.ok) {
console.log(`Uploaded: ${file.webkitRelativePath}`);
} else {
console.error(`Error uploading ${file.webkitRelativePath}:`, await response.text());
}
} catch (error) {
console.error(`Network error uploading ${file.webkitRelativePath}:`, error);
}
}
// Finish up
window.ui.showNotification('Carpeta subida', `${uploadedCount} archivos subidos correctamente`);
await new Promise(resolve => setTimeout(resolve, 800));
try {
await window.loadFiles({ forceRefresh: true });
} catch (reloadError) {
console.error('Error reloading files:', reloadError);
}
setTimeout(() => {
const dropzone = document.getElementById('dropzone');
if (dropzone) dropzone.style.display = 'none';
uploadProgressDiv.style.display = 'none';
}, 500);
},
/**
* Create a new folder
* @param {string} name - Folder name
@@ -116,6 +257,7 @@ const fileOps = {
const response = await fetch('/api/folders', {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, must-revalidate'
},
@@ -162,6 +304,7 @@ const fileOps = {
const response = await fetch(`/api/files/${fileId}/move`, {
method: 'PUT',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify({
@@ -203,6 +346,7 @@ const fileOps = {
const response = await fetch(`/api/folders/${folderId}/move`, {
method: 'PUT',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify({
@@ -233,6 +377,53 @@ const fileOps = {
}
},
/**
* Rename a file
* @param {string} fileId - File ID
* @param {string} newName - New file name
* @returns {Promise<boolean>} - Success status
*/
async renameFile(fileId, newName) {
try {
console.log(`Renaming file ${fileId} to "${newName}"`);
const response = await fetch(`/api/files/${fileId}/rename`, {
method: 'PUT',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: newName })
});
console.log('Response status:', response.status);
if (response.ok) {
window.ui.showNotification(
window.i18n ? window.i18n.t('notifications.file_renamed') : 'Archivo renombrado',
window.i18n ? window.i18n.t('notifications.file_renamed_to', { name: newName }) : `Archivo renombrado a "${newName}"`
);
return true;
} else {
const errorText = await response.text();
console.error('Error response:', errorText);
let errorMessage = 'Error desconocido';
try {
const errorData = JSON.parse(errorText);
errorMessage = errorData.error || response.statusText;
} catch (e) {
errorMessage = errorText || response.statusText;
}
window.ui.showNotification('Error', `Error al renombrar el archivo: ${errorMessage}`);
return false;
}
} catch (error) {
console.error('Error renaming file:', error);
window.ui.showNotification('Error', 'Error al renombrar el archivo');
return false;
}
},
/**
* Rename a folder
* @param {string} folderId - Folder ID
@@ -246,6 +437,7 @@ const fileOps = {
const response = await fetch(`/api/folders/${folderId}/rename`, {
method: 'PUT',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: newName })
@@ -287,14 +479,18 @@ const fileOps = {
* @returns {Promise<boolean>} - Success status
*/
async deleteFile(fileId, fileName) {
if (!confirm(`¿Estás seguro de que quieres mover a la papelera el archivo "${fileName}"?`)) {
return false;
}
const confirmed = await showConfirmDialog({
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Mover a papelera',
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_file', { name: fileName }) : `¿Estás seguro de que quieres mover a la papelera el archivo "${fileName}"?`,
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Eliminar',
});
if (!confirmed) return false;
try {
// Use the trash API endpoint
const response = await fetch(`/api/trash/files/${fileId}`, {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (response.ok) {
@@ -304,7 +500,8 @@ const fileOps = {
} else {
// Fallback to direct deletion if trash fails
const fallbackResponse = await fetch(`/api/files/${fileId}`, {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (fallbackResponse.ok) {
@@ -330,14 +527,18 @@ const fileOps = {
* @returns {Promise<boolean>} - Success status
*/
async deleteFolder(folderId, folderName) {
if (!confirm(`¿Estás seguro de que quieres mover a la papelera la carpeta "${folderName}" y todo su contenido?`)) {
return false;
}
const confirmed = await showConfirmDialog({
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Mover a papelera',
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_folder', { name: folderName }) : `¿Estás seguro de que quieres mover a la papelera la carpeta "${folderName}" y todo su contenido?`,
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Eliminar',
});
if (!confirmed) return false;
try {
// Use the trash API endpoint
const response = await fetch(`/api/trash/folders/${folderId}`, {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (response.ok) {
@@ -352,7 +553,8 @@ const fileOps = {
} else {
// Fallback to direct deletion if trash fails
const fallbackResponse = await fetch(`/api/folders/${folderId}`, {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (fallbackResponse.ok) {
@@ -382,7 +584,9 @@ const fileOps = {
*/
async getTrashItems() {
try {
const response = await fetch('/api/trash');
const response = await fetch('/api/trash', {
headers: getAuthHeaders()
});
if (response.ok) {
return await response.json();
@@ -406,6 +610,7 @@ const fileOps = {
const response = await fetch(`/api/trash/${trashId}/restore`, {
method: 'POST',
headers: {
...getAuthHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify({})
@@ -431,13 +636,17 @@ const fileOps = {
* @returns {Promise<boolean>} - Éxito de la operación
*/
async deletePermanently(trashId) {
if (!confirm('¿Estás seguro de que quieres eliminar permanentemente este elemento? Esta acción no se puede deshacer.')) {
return false;
}
const confirmed = await showConfirmDialog({
title: window.i18n ? window.i18n.t('dialogs.confirm_permanent_delete') : 'Eliminar permanentemente',
message: window.i18n ? window.i18n.t('dialogs.confirm_permanent_delete_msg') : '¿Estás seguro de que quieres eliminar permanentemente este elemento? Esta acción no se puede deshacer.',
confirmText: window.i18n ? window.i18n.t('actions.delete_permanently') : 'Eliminar permanentemente',
});
if (!confirmed) return false;
try {
const response = await fetch(`/api/trash/${trashId}`, {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (response.ok) {
@@ -459,14 +668,17 @@ const fileOps = {
* @returns {Promise<boolean>} - Éxito de la operación
*/
async emptyTrash() {
const confirmMsg = window.i18n ? window.i18n.t('trash.empty_confirm') : '¿Estás seguro de que quieres vaciar la papelera? Esta acción eliminará permanentemente todos los elementos.';
if (!confirm(confirmMsg)) {
return false;
}
const confirmed = await showConfirmDialog({
title: window.i18n ? window.i18n.t('dialogs.confirm_empty_trash') : 'Vaciar papelera',
message: window.i18n ? window.i18n.t('trash.empty_confirm') : '¿Estás seguro de que quieres vaciar la papelera? Esta acción eliminará permanentemente todos los elementos.',
confirmText: window.i18n ? window.i18n.t('actions.empty_trash') : 'Vaciar papelera',
});
if (!confirmed) return false;
try {
const response = await fetch('/api/trash/empty', {
method: 'DELETE'
method: 'DELETE',
headers: getAuthHeaders()
});
if (response.ok) {
@@ -488,15 +700,28 @@ const fileOps = {
* @param {string} fileId - ID del archivo
* @param {string} fileName - Nombre del archivo
*/
downloadFile(fileId, fileName) {
// Create a link and trigger download
const link = document.createElement('a');
link.href = `/api/files/${fileId}`;
link.download = fileName;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
async downloadFile(fileId, fileName) {
try {
const response = await fetch(`/api/files/${fileId}`, {
headers: getAuthHeaders()
});
if (response.ok) {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} else {
window.ui.showNotification('Error', 'Error al descargar el archivo');
}
} catch (error) {
console.error('Error downloading file:', error);
window.ui.showNotification('Error', 'Error al descargar el archivo');
}
},
/**
@@ -509,15 +734,22 @@ const fileOps = {
// Show notification to user
window.ui.showNotification('Preparando descarga', 'Preparando la carpeta para descargar...');
// Request the server to create a ZIP of the folder
// Since the API might not support this directly, we will simply download with zip parameter
const link = document.createElement('a');
link.href = `/api/folders/${folderId}/download?format=zip`;
link.download = `${folderName}.zip`;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
const response = await fetch(`/api/folders/${folderId}/download?format=zip`, {
headers: getAuthHeaders()
});
if (response.ok) {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${folderName}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} else {
window.ui.showNotification('Error', 'Error al descargar la carpeta');
}
} catch (error) {
console.error('Error downloading folder:', error);
window.ui.showNotification('Error', 'Error al descargar la carpeta');
+2 -1
View File
@@ -11,7 +11,8 @@ let currentLocale =
(navigator.userLanguage && navigator.userLanguage.substring(0, 2)) ||
'en';
// Supported locales
// Supported locales (languages that have locale files on the server)
// When a locale file is not found, the system gracefully falls back to English
const supportedLocales = ['en', 'es', 'zh', 'fa'];
// Fallback to English if locale is not supported
+25 -8
View File
@@ -164,6 +164,12 @@ class InlineViewer {
xhr.open('GET', `/api/files/${file.id}?inline=true`, true);
xhr.responseType = 'blob';
// Add auth header
const token = localStorage.getItem('oxicloud_token');
if (token) {
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
}
// Create a promise to handle the XHR
const response = await new Promise((resolve, reject) => {
xhr.onload = function() {
@@ -288,14 +294,25 @@ class InlineViewer {
}
downloadFile(file) {
// Create a link and click it
const link = document.createElement('a');
link.href = `/api/files/${file.id}`;
link.download = file.name;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
const token = localStorage.getItem('oxicloud_token');
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
fetch(`/api/files/${file.id}`, { headers })
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
})
.then(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = file.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
})
.catch(err => console.error('Download error:', err));
}
zoomImage(factor) {
+14 -6
View File
@@ -4,12 +4,18 @@
*/
// Language codes, names, and flag emojis
const languages = [
{ code: 'en', name: 'English', flag: '🇬🇧' },
{ code: 'es', name: 'Español', flag: '🇪🇸' },
{ code: 'zh', name: '中文', flag: '🇨🇳' },
{ code: 'fa', name: 'فارسی', flag: '🦁' }
];
// Uses ALL_LANGUAGES from auth.js if available, otherwise fallback
function getAvailableLanguages() {
if (typeof ALL_LANGUAGES !== 'undefined') {
return ALL_LANGUAGES.map(l => ({ code: l.code, name: l.nativeName, flag: l.flag }));
}
return [
{ code: 'en', name: 'English', flag: '🇬🇧' },
{ code: 'es', name: 'Español', flag: '🇪🇸' },
{ code: 'zh', name: '中文', flag: '🇨🇳' },
{ code: 'fa', name: 'فارسی', flag: '🇮🇷' }
];
}
// RTL languages
const rtlLanguages = ['fa']; // ['fa', 'ar']
@@ -47,6 +53,7 @@ function createLanguageSelector(containerId = 'language-selector') {
container.className = 'language-selector';
// Get current language
const languages = getAvailableLanguages();
const currentLocale = window.i18n ? window.i18n.getCurrentLocale() : 'en';
const currentLang = languages.find(l => l.code === currentLocale) || languages[0];
@@ -182,6 +189,7 @@ async function selectLanguage(langCode, container) {
* Update the UI to reflect selected language
*/
function updateSelectedLanguage(langCode, container) {
const languages = getAvailableLanguages();
const lang = languages.find(l => l.code === langCode) || languages[0];
// Update toggle button text
+2 -2
View File
@@ -117,8 +117,8 @@ const recent = {
</div>
`;
// Update breadcrumb for recents
window.ui.updateBreadcrumb(window.i18n ? window.i18n.t('nav.recent') : 'Recientes');
// Update breadcrumb - just show Home
window.ui.updateBreadcrumb('');
// Show empty state if no recent files
if (recentFiles.length === 0) {
+424 -63
View File
@@ -21,17 +21,19 @@ const ui = {
<div class="context-menu-item" id="favorite-folder-option">
<i class="fas fa-star"></i> <span data-i18n="actions.favorite">Añadir a favoritos</span>
</div>
<div class="context-menu-item" id="rename-folder-option">
<i class="fas fa-edit"></i> <span data-i18n="actions.rename">Renombrar</span>
</div>
<div class="context-menu-item" id="move-folder-option">
<i class="fas fa-exchange-alt"></i> <span data-i18n="actions.move">Mover a...</span>
</div>
<div class="context-menu-item" id="share-folder-option">
<i class="fas fa-share-alt"></i> <span data-i18n="actions.share">Compartir</span>
</div>
<div class="context-menu-item" id="delete-folder-option">
<i class="fas fa-trash"></i> <span data-i18n="actions.delete">Eliminar</span>
<div class="context-menu-separator"></div>
<div class="context-menu-item" id="rename-folder-option">
<i class="fas fa-pen"></i> <span data-i18n="actions.rename">Renombrar</span>
</div>
<div class="context-menu-item" id="move-folder-option">
<i class="fas fa-arrows-alt"></i> <span data-i18n="actions.move">Mover a...</span>
</div>
<div class="context-menu-separator"></div>
<div class="context-menu-item context-menu-item-danger" id="delete-folder-option">
<i class="fas fa-trash-alt"></i> <span data-i18n="actions.delete">Eliminar</span>
</div>
`;
document.body.appendChild(folderMenu);
@@ -49,33 +51,44 @@ const ui = {
<div class="context-menu-item" id="download-file-option">
<i class="fas fa-download"></i> <span data-i18n="actions.download">Descargar</span>
</div>
<div class="context-menu-separator"></div>
<div class="context-menu-item" id="favorite-file-option">
<i class="fas fa-star"></i> <span data-i18n="actions.favorite">Añadir a favoritos</span>
</div>
<div class="context-menu-item" id="share-file-option">
<i class="fas fa-share-alt"></i> <span data-i18n="actions.share">Compartir</span>
</div>
<div class="context-menu-item" id="move-file-option">
<i class="fas fa-exchange-alt"></i> <span data-i18n="actions.move">Mover a...</span>
<div class="context-menu-separator"></div>
<div class="context-menu-item" id="rename-file-option">
<i class="fas fa-pen"></i> <span data-i18n="actions.rename">Renombrar</span>
</div>
<div class="context-menu-item" id="delete-file-option">
<i class="fas fa-trash"></i> <span data-i18n="actions.delete">Eliminar</span>
<div class="context-menu-item" id="move-file-option">
<i class="fas fa-arrows-alt"></i> <span data-i18n="actions.move">Mover a...</span>
</div>
<div class="context-menu-separator"></div>
<div class="context-menu-item context-menu-item-danger" id="delete-file-option">
<i class="fas fa-trash-alt"></i> <span data-i18n="actions.delete">Eliminar</span>
</div>
`;
document.body.appendChild(fileMenu);
}
// Rename dialog
// Rename dialog — modern
if (!document.getElementById('rename-dialog')) {
const renameDialog = document.createElement('div');
renameDialog.className = 'rename-dialog';
renameDialog.id = 'rename-dialog';
renameDialog.innerHTML = `
<div class="rename-dialog-content">
<div class="rename-dialog-header" data-i18n="dialogs.rename_folder">Renombrar carpeta</div>
<input type="text" id="rename-input" data-i18n-placeholder="dialogs.new_name" placeholder="Nuevo nombre">
<div class="rename-dialog-header">
<i class="fas fa-pen" style="color:#ff5e3a"></i>
<span data-i18n="dialogs.rename_folder">Renombrar</span>
</div>
<div class="rename-dialog-body">
<input type="text" id="rename-input" data-i18n-placeholder="dialogs.new_name" placeholder="Nuevo nombre">
</div>
<div class="rename-dialog-buttons">
<button class="btn" id="rename-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-secondary" id="rename-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="rename-confirm-btn" data-i18n="actions.rename">Renombrar</button>
</div>
</div>
@@ -83,23 +96,27 @@ const ui = {
document.body.appendChild(renameDialog);
}
// Move dialog
// Move dialog — modern
if (!document.getElementById('move-file-dialog')) {
const moveDialog = document.createElement('div');
moveDialog.className = 'rename-dialog';
moveDialog.id = 'move-file-dialog';
moveDialog.innerHTML = `
<div class="rename-dialog-content">
<div class="rename-dialog-header" data-i18n="dialogs.move_file">Mover archivo</div>
<p data-i18n="dialogs.select_destination">Selecciona la carpeta destino:</p>
<div id="folder-select-container" style="max-height: 200px; overflow-y: auto; margin: 15px 0; border: 1px solid #ddd; border-radius: 4px; padding: 10px;">
<!-- Las carpetas se cargarán aquí dinámicamente -->
<div class="folder-select-item" data-folder-id="">
<i class="fas fa-folder"></i> <span data-i18n="dialogs.root">Raíz</span>
<div class="rename-dialog-header">
<i class="fas fa-arrows-alt" style="color:#ff5e3a"></i>
<span data-i18n="dialogs.move_file">Mover</span>
</div>
<div class="rename-dialog-body">
<p style="margin:0 0 12px;color:#718096;font-size:14px" data-i18n="dialogs.select_destination">Selecciona la carpeta destino:</p>
<div id="folder-select-container" style="max-height:220px;overflow-y:auto;">
<div class="folder-select-item selected" data-folder-id="">
<i class="fas fa-folder"></i> <span data-i18n="dialogs.root">Raíz</span>
</div>
</div>
</div>
<div class="rename-dialog-buttons">
<button class="btn" id="move-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-secondary" id="move-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="move-confirm-btn" data-i18n="actions.move_to">Mover</button>
</div>
</div>
@@ -114,7 +131,10 @@ const ui = {
shareDialog.id = 'share-dialog';
shareDialog.innerHTML = `
<div class="share-dialog-content">
<div class="share-dialog-header" data-i18n="dialogs.share_file">Compartir archivo</div>
<div class="share-dialog-header">
<i class="fas fa-share-alt" style="color:#ff5e3a"></i>
<span data-i18n="dialogs.share_file">Compartir archivo</span>
</div>
<div class="shared-item-info">
<strong>Elemento:</strong> <span id="shared-item-name"></span>
</div>
@@ -172,7 +192,7 @@ const ui = {
</div>
<div class="share-dialog-buttons">
<button class="btn" id="share-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-secondary" id="share-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="share-confirm-btn" data-i18n="actions.share">Compartir</button>
</div>
</div>
@@ -206,7 +226,10 @@ const ui = {
notificationDialog.id = 'notification-dialog';
notificationDialog.innerHTML = `
<div class="share-dialog-content">
<div class="share-dialog-header" data-i18n="dialogs.notify">Notificar enlace compartido</div>
<div class="share-dialog-header">
<i class="fas fa-envelope" style="color:#ff5e3a"></i>
<span data-i18n="dialogs.notify">Notificar enlace compartido</span>
</div>
<p><strong>URL:</strong> <span id="notification-share-url"></span></p>
@@ -221,7 +244,7 @@ const ui = {
</div>
<div class="share-dialog-buttons">
<button class="btn" id="notification-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-secondary" id="notification-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="notification-send-btn" data-i18n="actions.send">Enviar</button>
</div>
</div>
@@ -473,40 +496,132 @@ const ui = {
if (iconElement.classList.contains('folder-icon')) {
iconElement.innerHTML = '';
return;
}
else if (fileName.endsWith('.docx') || fileName.endsWith('.pdf') || fileName.endsWith('.txt') || fileName.endsWith('.xlsx')) {
iconElement.classList.add('doc-icon');
iconElement.innerHTML = '';
}
else if (fileName.endsWith('.jpg') || fileName.endsWith('.png') || fileName.endsWith('.gif') || fileName.endsWith('.jpeg')) {
iconElement.classList.add('image-icon');
iconElement.innerHTML = '';
}
else if (fileName.endsWith('.mp4') || fileName.endsWith('.avi') || fileName.endsWith('.mov') || fileName.endsWith('.mkv')) {
iconElement.classList.add('video-icon');
iconElement.innerHTML = '';
}
else {
const extension = fileName.split('.').pop().toLowerCase();
if (['json', 'js', 'jsx', 'ts', 'tsx', 'html', 'css', 'scss', 'py', 'java', 'c', 'cpp', 'cs', 'php', 'rb', 'go', 'rs', 'swift', 'kt'].includes(extension)) {
iconElement.className = 'file-icon code-icon';
const extension = fileName.includes('.') ? fileName.split('.').pop().toLowerCase() : '';
// Map extensions to icon types
const iconMap = {
// Documents
pdf: { cls: 'pdf-icon', fa: 'fas fa-file-pdf' },
doc: { cls: 'doc-icon', fa: 'fas fa-file-word' },
docx: { cls: 'doc-icon', fa: 'fas fa-file-word' },
txt: { cls: 'doc-icon', fa: 'fas fa-file-alt' },
rtf: { cls: 'doc-icon', fa: 'fas fa-file-alt' },
odt: { cls: 'doc-icon', fa: 'fas fa-file-alt' },
// Spreadsheets
xlsx: { cls: 'spreadsheet-icon' },
xls: { cls: 'spreadsheet-icon' },
csv: { cls: 'spreadsheet-icon' },
ods: { cls: 'spreadsheet-icon' },
// Presentations
pptx: { cls: 'presentation-icon' },
ppt: { cls: 'presentation-icon' },
odp: { cls: 'presentation-icon' },
// Images
jpg: { cls: 'image-icon' },
jpeg: { cls: 'image-icon' },
png: { cls: 'image-icon' },
gif: { cls: 'image-icon' },
svg: { cls: 'image-icon' },
webp: { cls: 'image-icon' },
bmp: { cls: 'image-icon' },
ico: { cls: 'image-icon' },
// Videos
mp4: { cls: 'video-icon' },
avi: { cls: 'video-icon' },
mov: { cls: 'video-icon' },
mkv: { cls: 'video-icon' },
webm: { cls: 'video-icon' },
flv: { cls: 'video-icon' },
// Audio
mp3: { cls: 'audio-icon' },
wav: { cls: 'audio-icon' },
ogg: { cls: 'audio-icon' },
flac: { cls: 'audio-icon' },
aac: { cls: 'audio-icon' },
m4a: { cls: 'audio-icon' },
// Archives
zip: { cls: 'archive-icon' },
rar: { cls: 'archive-icon' },
'7z': { cls: 'archive-icon' },
tar: { cls: 'archive-icon' },
gz: { cls: 'archive-icon' },
bz2: { cls: 'archive-icon' },
// Installers
dmg: { cls: 'installer-icon' },
exe: { cls: 'installer-icon' },
msi: { cls: 'installer-icon' },
deb: { cls: 'installer-icon' },
rpm: { cls: 'installer-icon' },
pkg: { cls: 'installer-icon' },
app: { cls: 'installer-icon' },
// Scripts
sh: { cls: 'script-icon', fa: 'fas fa-terminal' },
bash: { cls: 'script-icon', fa: 'fas fa-terminal' },
zsh: { cls: 'script-icon', fa: 'fas fa-terminal' },
bat: { cls: 'script-icon', fa: 'fas fa-terminal' },
ps1: { cls: 'script-icon', fa: 'fas fa-terminal' },
// Code — each with sub-type
json: { cls: 'code-icon', sub: 'json-icon' },
js: { cls: 'code-icon', sub: 'js-icon' },
jsx: { cls: 'code-icon', sub: 'js-icon' },
ts: { cls: 'code-icon', sub: 'ts-icon' },
tsx: { cls: 'code-icon', sub: 'ts-icon' },
html: { cls: 'code-icon', sub: 'html-icon' },
htm: { cls: 'code-icon', sub: 'html-icon' },
css: { cls: 'code-icon', sub: 'css-icon' },
scss: { cls: 'code-icon', sub: 'css-icon' },
py: { cls: 'code-icon', sub: 'py-icon' },
rs: { cls: 'code-icon', sub: 'rust-icon' },
go: { cls: 'code-icon', sub: 'go-icon' },
java: { cls: 'code-icon', sub: 'java-icon' },
c: { cls: 'code-icon', sub: 'c-icon' },
cpp: { cls: 'code-icon', sub: 'c-icon' },
cs: { cls: 'code-icon', sub: 'cs-icon' },
php: { cls: 'code-icon', sub: 'php-icon' },
rb: { cls: 'code-icon', sub: 'ruby-icon' },
swift: { cls: 'code-icon', sub: 'swift-icon' },
kt: { cls: 'code-icon', sub: 'kotlin-icon' },
sql: { cls: 'code-icon', sub: 'sql-icon' },
yaml: { cls: 'code-icon', sub: 'yaml-icon' },
yml: { cls: 'code-icon', sub: 'yaml-icon' },
toml: { cls: 'code-icon', sub: 'toml-icon' },
xml: { cls: 'code-icon', sub: 'html-icon' },
md: { cls: 'code-icon', sub: 'md-icon' },
// Config
ini: { cls: 'config-icon', fa: 'fas fa-cog' },
cfg: { cls: 'config-icon', fa: 'fas fa-cog' },
conf: { cls: 'config-icon', fa: 'fas fa-cog' },
env: { cls: 'config-icon', fa: 'fas fa-cog' },
};
const mapping = iconMap[extension];
if (mapping) {
iconElement.className = `file-icon ${mapping.cls}`;
if (mapping.cls === 'code-icon') {
// Code icons use pseudo-element lines
iconElement.innerHTML = `
<div class="code-line-1"></div>
<div class="code-line-2"></div>
<div class="code-line-3"></div>
`;
if (extension === 'json') {
iconElement.classList.add('json-icon');
} else if (['js', 'jsx', 'ts', 'tsx'].includes(extension)) {
iconElement.classList.add('js-icon');
} else if (extension === 'html') {
iconElement.classList.add('html-icon');
} else if (['css', 'scss'].includes(extension)) {
iconElement.classList.add('css-icon');
} else if (extension === 'py') {
iconElement.classList.add('py-icon');
if (mapping.sub) iconElement.classList.add(mapping.sub);
} else {
// Types with pure CSS visuals — clear the <i>
const pureCssTypes = ['image-icon','video-icon','spreadsheet-icon','presentation-icon','audio-icon','archive-icon','installer-icon'];
if (pureCssTypes.includes(mapping.cls)) {
iconElement.innerHTML = '';
} else if (mapping.fa) {
// Types that keep the FA icon — update <i> class
let iEl = iconElement.querySelector('i');
if (!iEl) {
iEl = document.createElement('i');
iconElement.innerHTML = '';
iconElement.appendChild(iEl);
}
iEl.className = mapping.fa;
}
}
}
@@ -534,6 +649,8 @@ const ui = {
folderGridElement.dataset.folderName = folder.name;
folderGridElement.dataset.parentId = folder.parent_id || "";
folderGridElement.innerHTML = `
<div class="file-card-checkbox"><i class="fas fa-check"></i></div>
<button class="file-card-more"><i class="fas fa-ellipsis-v"></i></button>
<div class="file-icon folder-icon">
<i class="fas fa-folder"></i>
</div>
@@ -546,6 +663,10 @@ const ui = {
folderGridElement.setAttribute('draggable', 'true');
folderGridElement.addEventListener('dragstart', (e) => {
if (!folderGridElement.classList.contains('selected')) {
e.preventDefault();
return;
}
e.dataTransfer.setData('text/plain', folder.id);
e.dataTransfer.setData('application/oxicloud-folder', 'true');
folderGridElement.classList.add('dragging');
@@ -559,13 +680,36 @@ const ui = {
});
}
// Click to navigate
folderGridElement.addEventListener('click', () => {
// Single click to select, double click to navigate
folderGridElement.addEventListener('click', (e) => {
if (e.target.closest('.file-card-more') || e.target.closest('.file-card-checkbox')) return;
toggleCardSelection(folderGridElement, e);
});
folderGridElement.addEventListener('dblclick', () => {
window.app.currentPath = folder.id;
this.updateBreadcrumb(folder.name);
window.loadFiles();
});
// Checkbox click
folderGridElement.querySelector('.file-card-checkbox').addEventListener('click', (e) => {
e.stopPropagation();
toggleCardSelection(folderGridElement, e);
});
// More actions button
folderGridElement.querySelector('.file-card-more').addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
window.app.contextMenuTargetFolder = {
id: folder.id,
name: folder.name,
parent_id: folder.parent_id || ""
};
showContextMenuAtElement(e.currentTarget, 'folder-context-menu');
});
// Context menu
folderGridElement.addEventListener('contextmenu', (e) => {
e.preventDefault();
@@ -766,6 +910,8 @@ const ui = {
const fileGridElement = document.createElement('div');
fileGridElement.className = 'file-card';
fileGridElement.innerHTML = `
<div class="file-card-checkbox"><i class="fas fa-check"></i></div>
<button class="file-card-more"><i class="fas fa-ellipsis-v"></i></button>
<div class="file-icon">
<i class="${iconClass}"></i>
</div>
@@ -781,6 +927,10 @@ const ui = {
fileGridElement.setAttribute('draggable', 'true');
fileGridElement.addEventListener('dragstart', (e) => {
if (!fileGridElement.classList.contains('selected')) {
e.preventDefault();
return;
}
e.dataTransfer.setData('text/plain', file.id);
fileGridElement.classList.add('dragging');
});
@@ -792,8 +942,13 @@ const ui = {
});
});
// View or download on click
fileGridElement.addEventListener('click', () => {
// Single click = select, double click = open/download
fileGridElement.addEventListener('click', (e) => {
if (e.target.closest('.file-card-more') || e.target.closest('.file-card-checkbox')) return;
toggleCardSelection(fileGridElement, e);
});
fileGridElement.addEventListener('dblclick', () => {
// Track this file access for recent files
if (window.recent) {
document.dispatchEvent(new CustomEvent('file-accessed', {
@@ -804,22 +959,36 @@ const ui = {
// Check if it's a viewable file type
if ((file.mime_type && file.mime_type.startsWith('image/')) ||
(file.mime_type && file.mime_type === 'application/pdf')) {
// Open in the inline viewer
if (window.inlineViewer) {
window.inlineViewer.openFile(file);
} else if (window.fileViewer) {
// Fallback to standard file viewer
window.fileViewer.open(file);
} else {
// No viewer available, download directly
window.location.href = `/api/files/${file.id}`;
}
} else {
// For other file types, download directly
window.location.href = `/api/files/${file.id}`;
}
});
// Checkbox click
fileGridElement.querySelector('.file-card-checkbox').addEventListener('click', (e) => {
e.stopPropagation();
toggleCardSelection(fileGridElement, e);
});
// More actions button
fileGridElement.querySelector('.file-card-more').addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
window.app.contextMenuTargetFile = {
id: file.id,
name: file.name,
folder_id: file.folder_id || ""
};
showContextMenuAtElement(e.currentTarget, 'file-context-menu');
});
// Context menu
fileGridElement.addEventListener('contextmenu', (e) => {
e.preventDefault();
@@ -920,5 +1089,197 @@ const ui = {
}
};
// --- Global helper functions for card interactions ---
/**
* Toggle selection state of a file/folder card.
* Each click toggles that card independently (multi-select by default).
*/
function toggleCardSelection(card, event) {
card.classList.toggle('selected');
}
/**
* Show the context menu anchored next to a trigger element (the 3-dot button).
*/
function showContextMenuAtElement(triggerElement, menuId) {
// Hide any open menus first
document.querySelectorAll('.context-menu').forEach(m => m.style.display = 'none');
const menu = document.getElementById(menuId);
if (!menu) return;
const rect = triggerElement.getBoundingClientRect();
const menuWidth = 200; // approximate
// Position below the trigger, aligned to the right edge
let left = rect.right - menuWidth + window.scrollX;
let top = rect.bottom + 4 + window.scrollY;
// Keep inside viewport
if (left < 8) left = 8;
if (top + 300 > window.innerHeight + window.scrollY) {
top = rect.top - 4 + window.scrollY; // flip above if no room
}
menu.style.left = `${left}px`;
menu.style.top = `${top}px`;
menu.style.display = 'block';
}
/**
* Rubber band (lasso) selection — click + drag on empty grid area
* to draw a rectangle and select all cards it touches.
*/
function initRubberBandSelection() {
// Create the visual rectangle element once
let selRect = document.getElementById('selection-rect');
if (!selRect) {
selRect = document.createElement('div');
selRect.id = 'selection-rect';
selRect.className = 'selection-rect';
document.body.appendChild(selRect);
}
let active = false;
let startX = 0, startY = 0;
// We listen on the whole files-container (covers grid + empty space)
const container = document.querySelector('.files-container') || document.getElementById('files-grid');
if (!container) return;
container.addEventListener('mousedown', (e) => {
// Only start if clicking empty area (not on a card, button, menu, input…)
if (e.button !== 0) return; // left click only
if (e.target.closest('.file-card') || e.target.closest('.context-menu') ||
e.target.closest('.upload-dropdown') || e.target.closest('button') ||
e.target.closest('input') || e.target.closest('.breadcrumb')) return;
active = true;
startX = e.clientX;
startY = e.clientY;
selRect.style.left = `${startX}px`;
selRect.style.top = `${startY}px`;
selRect.style.width = '0px';
selRect.style.height = '0px';
selRect.style.display = 'none'; // show only after a small movement
e.preventDefault(); // prevent text selection
});
document.addEventListener('mousemove', (e) => {
if (!active) return;
const curX = e.clientX;
const curY = e.clientY;
const left = Math.min(startX, curX);
const top = Math.min(startY, curY);
const width = Math.abs(curX - startX);
const height = Math.abs(curY - startY);
// Only show the rect after a small threshold to avoid flicker on click
if (width > 5 || height > 5) {
selRect.style.display = 'block';
}
selRect.style.left = `${left}px`;
selRect.style.top = `${top}px`;
selRect.style.width = `${width}px`;
selRect.style.height = `${height}px`;
// Highlight cards that intersect with the rectangle
const rectBounds = { left, top, right: left + width, bottom: top + height };
document.querySelectorAll('#files-grid .file-card').forEach(card => {
const cardRect = card.getBoundingClientRect();
const intersects =
cardRect.left < rectBounds.right &&
cardRect.right > rectBounds.left &&
cardRect.top < rectBounds.bottom &&
cardRect.bottom > rectBounds.top;
if (intersects) {
card.classList.add('selected');
} else {
card.classList.remove('selected');
}
});
});
document.addEventListener('mouseup', () => {
if (!active) return;
active = false;
selRect.style.display = 'none';
});
}
// Initialize rubber band once DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initRubberBandSelection);
} else {
initRubberBandSelection();
}
// Expose helpers globally
window.toggleCardSelection = toggleCardSelection;
window.showContextMenuAtElement = showContextMenuAtElement;
window.initRubberBandSelection = initRubberBandSelection;
/**
* Show a modern confirm dialog (replaces native confirm())
* @param {Object} options
* @param {string} options.title - Dialog title
* @param {string} options.message - Dialog message/body
* @param {string} [options.confirmText='Confirmar'] - Text for confirm button
* @param {string} [options.cancelText='Cancelar'] - Text for cancel button
* @param {boolean} [options.danger=false] - Use danger styling (red)
* @returns {Promise<boolean>} true if confirmed, false if cancelled
*/
function showConfirmDialog({ title, message, confirmText, cancelText, danger = true } = {}) {
const ct = confirmText || (window.i18n ? window.i18n.t('actions.delete') : 'Eliminar');
const cc = cancelText || (window.i18n ? window.i18n.t('actions.cancel') : 'Cancelar');
const t = title || (window.i18n ? window.i18n.t('dialogs.confirm_title') : 'Confirmar acción');
return new Promise((resolve) => {
// Remove any previous confirm dialog
const prev = document.getElementById('confirm-dialog-overlay');
if (prev) prev.remove();
const overlay = document.createElement('div');
overlay.id = 'confirm-dialog-overlay';
overlay.className = 'confirm-dialog';
overlay.innerHTML = `
<div class="confirm-dialog-content">
<div class="confirm-dialog-icon">
<i class="fas ${danger ? 'fa-exclamation-triangle' : 'fa-question-circle'}"></i>
</div>
<div class="confirm-dialog-title">${t}</div>
<div class="confirm-dialog-message">${message || ''}</div>
<div class="confirm-dialog-buttons">
<button class="btn btn-secondary confirm-dialog-cancel">${cc}</button>
<button class="btn ${danger ? 'btn-danger' : 'btn-primary'} confirm-dialog-ok">${ct}</button>
</div>
</div>
`;
document.body.appendChild(overlay);
// Force layout then show
requestAnimationFrame(() => { overlay.classList.add('active'); });
const cleanup = (result) => {
overlay.classList.remove('active');
setTimeout(() => overlay.remove(), 200);
resolve(result);
};
overlay.querySelector('.confirm-dialog-cancel').addEventListener('click', () => cleanup(false));
overlay.querySelector('.confirm-dialog-ok').addEventListener('click', () => cleanup(true));
overlay.addEventListener('click', (e) => { if (e.target === overlay) cleanup(false); });
});
}
window.showConfirmDialog = showConfirmDialog;
// Expose UI module globally
window.ui = ui;