feat: add breadcrumb navigation and refactor SPA view management

- Add breadcrumb navigation with folder hierarchy display
- Create setCurrentSection() helper to centralize view state management
- Derive nav item section dynamically from DOM data-i18n attribute
- Remove remnant /shared page and consolidate to SPA sharedView
- Add search input to sharedView for client-side filtering
- Fix 'Go to Files' button to use switchToFilesView()
This commit is contained in:
George Wu
2026-02-22 20:20:00 -08:00
parent 85908311dc
commit 6a9554d23f
10 changed files with 196 additions and 903 deletions
-6
View File
@@ -23,7 +23,6 @@ pub fn create_web_routes() -> Router<AppState> {
.route("/login", get(serve_login_page))
.route("/profile", get(serve_profile_page))
.route("/admin", get(serve_admin_page))
.route("/shared", get(serve_shared_page))
// Serve static files with compression + cache headers
.fallback_service(static_service)
.layer(CompressionLayer::new().br(true).gzip(true))
@@ -47,8 +46,3 @@ async fn serve_profile_page() -> Html<&'static str> {
async fn serve_admin_page() -> Html<&'static str> {
Html(include_str!("../../../static/admin.html"))
}
/// Serve the shared page
async fn serve_shared_page() -> Html<&'static str> {
Html(include_str!("../../../static/shared.html"))
}
+17
View File
@@ -38,3 +38,20 @@
font-size: 12px;
user-select: none;
}
.breadcrumb-home {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border-radius: 4px;
}
.breadcrumb-home i {
font-size: 12px;
}
.breadcrumb-home.breadcrumb-link:hover {
background: rgba(255, 94, 58, 0.1);
}
+9
View File
@@ -97,6 +97,15 @@
color: #64748b;
}
[data-theme="dark"] .breadcrumb-home {
color: #94a3b8;
}
[data-theme="dark"] .breadcrumb-home.breadcrumb-link:hover {
color: #ff5e3a;
background: rgba(255, 94, 58, 0.15);
}
[data-theme="dark"] .btn-secondary {
background-color: #1e293b;
color: #cbd5e1;
+2 -35
View File
@@ -467,41 +467,8 @@ function setupEventListeners() {
// Load trash items
window.loadTrashItems();
} else {
// Check if we need to reset shared view
if (app.isSharedView) {
// Hide shared view
if (window.sharedView) {
window.sharedView.hide();
}
// Reset shared view flag
app.isSharedView = false;
// Clean up shared containers if they exist
const sharedContainer = document.getElementById('shared-container');
if (sharedContainer) {
sharedContainer.style.display = 'none';
}
}
// Show regular files view
app.isTrashView = false;
app.currentSection = 'files';
// Reset UI
elements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.files') : 'Files';
setActionsBarMode('files');
// Show files containers
const filesGrid = document.getElementById('files-grid');
const filesListView = document.getElementById('files-list-view');
if (filesGrid) filesGrid.style.display = app.currentView === 'grid' ? 'grid' : 'none';
if (filesListView) filesListView.style.display = app.currentView === 'list' ? 'block' : 'none';
// Load regular files
app.currentPath = '';
ui.updateBreadcrumb('');
window.loadFiles();
// Use the proper switchToFilesView function which handles all UI restoration
window.switchToFilesView();
}
});
});
+78 -110
View File
@@ -3,35 +3,71 @@
* Extracted from main.js to keep navigation concerns isolated.
*/
function switchToSharedView() {
window.app.isTrashView = false;
window.app.isSharedView = true;
window.app.currentSection = 'shared';
// Mapping of section names to their corresponding view flags
const VIEW_FLAGS = {
'files': 'isFilesView',
'shared': 'isSharedView',
'recent': 'isRecentView',
'favorites': 'isFavoritesView',
'trash': 'isTrashView'
};
window.appElements.navItems.forEach(navItem => navItem.classList.remove('active'));
/**
* Derive section name from nav item's data-i18n attribute.
* @param {HTMLElement} navItem - The nav item element
* @returns {string|null} - Section name or null if not found
*/
function getSectionFromNavItem(navItem) {
const i18nKey = navItem.querySelector('span[data-i18n]')?.getAttribute('data-i18n');
return i18nKey ? i18nKey.replace('nav.', '') : null;
}
const sharedNavItem = document.querySelector('.nav-item:nth-child(2)');
if (sharedNavItem) {
sharedNavItem.classList.add('active');
/**
* Set the current active section, updating all view flags and nav UI.
* @param {string} section - The section to activate ('files', 'shared', 'recent', 'favorites', 'trash')
*/
function setCurrentSection(section) {
// Set all view flags - true for active section, false for others
Object.entries(VIEW_FLAGS).forEach(([key, flag]) => {
window.app[flag] = (key === section);
});
window.app.currentSection = section;
// Update nav item active classes by finding matching item from DOM
window.appElements.navItems.forEach(item => {
const itemSection = getSectionFromNavItem(item);
item.classList.toggle('active', itemSection === section);
});
// Update page title
const titleKey = `nav.${section}`;
const defaultTitle = section.charAt(0).toUpperCase() + section.slice(1);
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t(titleKey) : defaultTitle;
window.appElements.pageTitle.setAttribute('data-i18n', titleKey);
// Hide sharedView when switching to any other section
if (section !== 'shared' && window.sharedView) {
window.sharedView.hide();
}
}
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.shared') : 'Shared';
window.appElements.pageTitle.setAttribute('data-i18n', 'nav.shared');
window.ui.updateBreadcrumb('');
function switchToSharedView() {
setCurrentSection('shared');
// Hide breadcrumb (only shown in Files view)
const breadcrumb = document.querySelector('.breadcrumb');
if (breadcrumb) breadcrumb.style.display = 'none';
if (window.appElements.actionsBar) {
window.appElements.actionsBar.style.display = 'none';
}
// Hide actions-bar for shared view
window.setActionsBarMode('hidden');
const filesGrid = document.getElementById('files-grid');
const filesListView = document.getElementById('files-list-view');
if (filesGrid) filesGrid.style.display = 'none';
if (filesListView) filesListView.style.display = 'none';
// Show shared view
if (window.sharedView) {
window.sharedView.init();
window.sharedView.show();
@@ -39,92 +75,47 @@ function switchToSharedView() {
}
function switchToFilesView() {
window.app.isTrashView = false;
window.app.isSharedView = false;
window.app.isFavoritesView = false;
window.app.isRecentView = false;
window.app.currentSection = 'files';
setCurrentSection('files');
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.files') : 'Files';
window.appElements.pageTitle.setAttribute('data-i18n', 'nav.files');
// Set actions bar mode
window.setActionsBarMode('files', true);
// Show breadcrumb (only in Files view)
const breadcrumb = document.querySelector('.breadcrumb');
if (breadcrumb) breadcrumb.style.display = '';
window.appElements.navItems.forEach(navItem => navItem.classList.remove('active'));
const filesNavItem = document.querySelector('.nav-item:first-child');
if (filesNavItem) {
filesNavItem.classList.add('active');
}
window.setActionsBarMode('files');
if (window.sharedView) {
window.sharedView.hide();
}
const filesGrid = document.getElementById('files-grid');
if (filesGrid) {
filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
}
const filesListView = document.getElementById('files-list-view');
if (filesListView) {
filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
}
if (filesGrid) filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
if (filesListView) filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
// Reset to home folder and update breadcrumb
window.app.currentPath = window.app.userHomeFolderId || '';
window.app.breadcrumbPath = [];
window.ui.updateBreadcrumb();
if (window.app.userHomeFolderId) {
window.app.currentPath = window.app.userHomeFolderId;
window.app.breadcrumbPath = [];
window.ui.updateBreadcrumb();
} else {
window.app.currentPath = '';
}
window.loadFiles();
}
function switchToFavoritesView() {
window.app.isTrashView = false;
window.app.isSharedView = false;
window.app.isFavoritesView = true;
window.app.currentSection = 'favorites';
window.appElements.navItems.forEach(navItem => navItem.classList.remove('active'));
const favoritesNavItem = document.querySelector('.nav-item:nth-child(4)');
if (favoritesNavItem) {
favoritesNavItem.classList.add('active');
}
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.favorites') : 'Favorites';
window.appElements.pageTitle.setAttribute('data-i18n', 'nav.favorites');
window.ui.updateBreadcrumb('');
if (window.sharedView) {
window.sharedView.hide();
}
setCurrentSection('favorites');
// Set actions bar mode
window.setActionsBarMode('favorites');
// Hide breadcrumb (only shown in Files view)
const breadcrumb = document.querySelector('.breadcrumb');
if (breadcrumb) breadcrumb.style.display = 'none';
const filesGrid = document.getElementById('files-grid');
const filesListView = document.getElementById('files-list-view');
if (filesGrid) {
filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
}
if (filesListView) {
filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
}
if (filesGrid) filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
if (filesListView) filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
if (window.favorites) {
window.favorites.displayFavorites();
} else {
console.error('Favorites module not loaded or initialized');
const filesGridError = document.getElementById('files-grid');
if (filesGridError) {
filesGridError.innerHTML = `
@@ -138,47 +129,24 @@ function switchToFavoritesView() {
}
function switchToRecentFilesView() {
window.app.isTrashView = false;
window.app.isSharedView = false;
window.app.isFavoritesView = false;
window.app.isRecentView = true;
window.app.currentSection = 'recent';
window.appElements.navItems.forEach(navItem => navItem.classList.remove('active'));
const recentNavItem = document.querySelector('.nav-item:nth-child(3)');
if (recentNavItem) {
recentNavItem.classList.add('active');
}
window.appElements.pageTitle.textContent = window.i18n ? window.i18n.t('nav.recent') : 'Recent';
window.appElements.pageTitle.setAttribute('data-i18n', 'nav.recent');
window.ui.updateBreadcrumb('');
if (window.sharedView) {
window.sharedView.hide();
}
setCurrentSection('recent');
// Set actions bar mode
window.setActionsBarMode('recent');
// Hide breadcrumb (only shown in Files view)
const breadcrumb = document.querySelector('.breadcrumb');
if (breadcrumb) breadcrumb.style.display = 'none';
const filesGrid = document.getElementById('files-grid');
const filesListView = document.getElementById('files-list-view');
if (filesGrid) {
filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
}
if (filesListView) {
filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
}
if (filesGrid) filesGrid.style.display = window.app.currentView === 'grid' ? 'grid' : 'none';
if (filesListView) filesListView.style.display = window.app.currentView === 'list' ? 'block' : 'none';
if (window.recent) {
window.recent.displayRecentFiles();
} else {
console.error('Recent files module not loaded or initialized');
const filesGridError = document.getElementById('files-grid');
if (filesGridError) {
filesGridError.innerHTML = `
+3
View File
@@ -11,6 +11,7 @@ window.app = {
contextMenuTargetFile: null,
selectedTargetFolderId: '',
moveDialogMode: 'file',
isFilesView: true,
isTrashView: false,
isSharedView: false,
isFavoritesView: false,
@@ -20,6 +21,8 @@ window.app = {
shareDialogItem: null,
shareDialogItemType: null,
notificationShareUrl: null,
userHomeFolderId: null,
userHomeFolderName: null,
breadcrumbPath: [] // Array of {id, name} tracking folder navigation hierarchy
};
+56 -30
View File
@@ -129,7 +129,7 @@ const ui = {
`;
document.body.appendChild(moveDialog);
}
// Share dialog
if (!document.getElementById('share-dialog')) {
const shareDialog = document.createElement('div');
@@ -144,25 +144,25 @@ const ui = {
<div class="shared-item-info">
<strong>Item:</strong> <span id="shared-item-name"></span>
</div>
<div id="existing-shares-section" style="display:none; margin: 15px 0;">
<h3 data-i18n="dialogs.existing_shares">Existing shared links</h3>
<div id="existing-shares-container"></div>
</div>
<div class="share-options">
<h3 data-i18n="dialogs.share_options">Share options</h3>
<div class="form-group">
<label for="share-password" data-i18n="dialogs.password">Password (optional):</label>
<input type="password" id="share-password" placeholder="Protect with password">
</div>
<div class="form-group">
<label for="share-expiration" data-i18n="dialogs.expiration">Expiration date (optional):</label>
<input type="date" id="share-expiration">
</div>
<div class="form-group">
<label data-i18n="dialogs.permissions">Permissions:</label>
<div class="permission-options">
@@ -181,7 +181,7 @@ const ui = {
</div>
</div>
</div>
<div id="new-share-section" style="display:none; margin: 15px 0;">
<h3 data-i18n="dialogs.generated_link">Generated link</h3>
<div class="form-group">
@@ -196,7 +196,7 @@ const ui = {
</div>
</div>
</div>
<div class="share-dialog-buttons">
<button class="btn btn-secondary" id="share-cancel-btn" data-i18n="actions.cancel">Cancel</button>
<button class="btn btn-primary" id="share-confirm-btn" data-i18n="actions.share">Share</button>
@@ -204,27 +204,27 @@ const ui = {
</div>
`;
document.body.appendChild(shareDialog);
// Add event listeners for share dialog
document.getElementById('share-cancel-btn').addEventListener('click', () => {
contextMenus.closeShareDialog();
});
document.getElementById('share-confirm-btn').addEventListener('click', async () => {
await contextMenus.createSharedLink();
});
document.getElementById('copy-share-btn').addEventListener('click', async () => {
const shareUrl = document.getElementById('generated-share-url').value;
await fileSharing.copyLinkToClipboard(shareUrl);
});
document.getElementById('notify-share-btn').addEventListener('click', () => {
const shareUrl = document.getElementById('generated-share-url').value;
contextMenus.showEmailNotificationDialog(shareUrl);
});
}
// Notification dialog
if (!document.getElementById('notification-dialog')) {
const notificationDialog = document.createElement('div');
@@ -236,19 +236,19 @@ const ui = {
<i class="fas fa-envelope" style="color:#ff5e3a"></i>
<span data-i18n="dialogs.notify">Notify shared link</span>
</div>
<p><strong>URL:</strong> <span id="notification-share-url"></span></p>
<div class="form-group">
<label for="notification-email" data-i18n="dialogs.recipient">Recipient:</label>
<input type="email" id="notification-email" placeholder="Email address">
</div>
<div class="form-group">
<label for="notification-message" data-i18n="dialogs.message">Message (optional):</label>
<textarea id="notification-message" rows="3"></textarea>
</div>
<div class="share-dialog-buttons">
<button class="btn btn-secondary" id="notification-cancel-btn" data-i18n="actions.cancel">Cancel</button>
<button class="btn btn-primary" id="notification-send-btn" data-i18n="actions.send">Send</button>
@@ -256,12 +256,12 @@ const ui = {
</div>
`;
document.body.appendChild(notificationDialog);
// Add event listeners for notification dialog
document.getElementById('notification-cancel-btn').addEventListener('click', () => {
contextMenus.closeNotificationDialog();
});
document.getElementById('notification-send-btn').addEventListener('click', () => {
contextMenus.sendShareNotification();
});
@@ -495,24 +495,50 @@ const ui = {
return window.i18n.t(key);
};
// -- Home item (always present) --
const homeItem = document.createElement('span');
homeItem.className = 'breadcrumb-item';
homeItem.textContent = getTranslatedText('breadcrumb.home', 'Home');
// -- Home icon (always present, clickable to go to root) --
const homeIcon = document.createElement('span');
homeIcon.className = 'breadcrumb-item breadcrumb-home';
homeIcon.innerHTML = '<i class="fas fa-home"></i>';
homeIcon.title = getTranslatedText('breadcrumb.home', 'Home');
// If we have deeper segments, Home is clickable
if (path.length > 0 && window.app.userHomeFolderId) {
homeItem.classList.add('breadcrumb-link');
homeItem.addEventListener('click', () => {
// Home is always clickable if we have a home folder
if (window.app.userHomeFolderId) {
homeIcon.classList.add('breadcrumb-link');
homeIcon.addEventListener('click', () => {
window.app.breadcrumbPath = [];
window.app.currentPath = window.app.userHomeFolderId;
self.updateBreadcrumb();
window.loadFiles();
});
} else {
homeItem.classList.add('breadcrumb-current');
}
breadcrumb.appendChild(homeItem);
breadcrumb.appendChild(homeIcon);
// -- Root/Home folder name (if available) --
if (window.app.userHomeFolderName) {
const separator1 = document.createElement('span');
separator1.className = 'breadcrumb-separator';
separator1.textContent = '>';
breadcrumb.appendChild(separator1);
const rootFolderItem = document.createElement('span');
rootFolderItem.className = 'breadcrumb-item';
rootFolderItem.textContent = window.app.userHomeFolderName;
// If we're at the home folder level (no deeper navigation), show as current
if (path.length === 0) {
rootFolderItem.classList.add('breadcrumb-current');
} else {
// Otherwise clickable to go back to home
rootFolderItem.classList.add('breadcrumb-link');
rootFolderItem.addEventListener('click', () => {
window.app.breadcrumbPath = [];
window.app.currentPath = window.app.userHomeFolderId;
self.updateBreadcrumb();
window.loadFiles();
});
}
breadcrumb.appendChild(rootFolderItem);
}
// -- Intermediate + current segments --
path.forEach((segment, index) => {
-406
View File
@@ -1,406 +0,0 @@
/**
* OxiCloud - Shared Resources Page (/shared)
* All operations go through the backend API at /api/shares.
*/
// Authentication check
function checkAuthentication() {
const token = localStorage.getItem('oxicloud_token');
const tokenExpiry = localStorage.getItem('oxicloud_token_expiry');
if (!token || !tokenExpiry || new Date(tokenExpiry) < new Date()) {
window.location.href = '/login';
}
}
document.addEventListener('DOMContentLoaded', async () => {
// ── i18n ── (translatePage is called automatically by i18n.js on init)
function t(key, fallback) {
return (window.i18n && window.i18n.t) ? window.i18n.t(key, fallback) : fallback;
}
// ── Auth headers helper ──
function authHeaders(json = false) {
const h = {};
const token = localStorage.getItem('oxicloud_token');
if (token) h['Authorization'] = `Bearer ${token}`;
if (json) h['Content-Type'] = 'application/json';
return h;
}
// ── Elements ──
const sharedItemsList = document.getElementById('shared-items-list');
const emptySharedState = document.getElementById('empty-shared-state');
const filterType = document.getElementById('filter-type');
const sortBy = document.getElementById('sort-by');
const sharedSearch = document.getElementById('shared-search');
const sharedSearchBtn = document.getElementById('shared-search-btn');
const goToFilesBtn = document.getElementById('go-to-files');
// Share dialog elements
const shareDialog = document.getElementById('share-dialog');
const shareDialogCloseBtn = shareDialog ? shareDialog.querySelector('.close-dialog-btn') : null;
const shareDialogIcon = document.getElementById('share-dialog-icon');
const shareDialogName = document.getElementById('share-dialog-name');
const shareLinkUrl = document.getElementById('share-link-url');
const copyLinkBtn = document.getElementById('copy-link-btn');
const enablePassword = document.getElementById('enable-password');
const sharePassword = document.getElementById('share-password');
const generatePasswordBtn = document.getElementById('generate-password');
const enableExpiration = document.getElementById('enable-expiration');
const shareExpiration = document.getElementById('share-expiration');
const permissionRead = document.getElementById('permission-read');
const permissionWrite = document.getElementById('permission-write');
const permissionReshare = document.getElementById('permission-reshare');
const updateShareBtn = document.getElementById('update-share-btn');
const removeShareBtn = document.getElementById('remove-share-btn');
// Notification dialog elements
const notificationDialog = document.getElementById('share-notification-dialog');
const notificationCloseBtn = notificationDialog ? notificationDialog.querySelector('.close-dialog-btn') : null;
const notifyDialogIcon = document.getElementById('notify-dialog-icon');
const notifyDialogName = document.getElementById('notify-dialog-name');
const notificationEmail = document.getElementById('notification-email');
const notificationMessage = document.getElementById('notification-message');
const sendNotificationBtn = document.getElementById('send-notification-btn');
// Notification banner
const notificationBanner = document.getElementById('notification-banner');
const notificationBannerMessage = document.getElementById('notification-message');
const closeNotificationBtn = document.getElementById('close-notification');
// ── State ──
let currentSharedItem = null;
let allSharedItems = [];
let filteredItems = [];
// ── Init ──
checkAuthentication();
await loadSharedItems();
// ── Event listeners ──
if (filterType) filterType.addEventListener('change', filterAndSortItems);
if (sortBy) sortBy.addEventListener('change', filterAndSortItems);
if (sharedSearchBtn) sharedSearchBtn.addEventListener('click', filterAndSortItems);
if (sharedSearch) {
let searchDebounce;
sharedSearch.addEventListener('input', () => {
clearTimeout(searchDebounce);
searchDebounce = setTimeout(filterAndSortItems, 250);
});
sharedSearch.addEventListener('keyup', e => { if (e.key === 'Enter') { clearTimeout(searchDebounce); filterAndSortItems(); } });
}
if (goToFilesBtn) goToFilesBtn.addEventListener('click', () => window.location.href = '/');
if (shareDialogCloseBtn) shareDialogCloseBtn.addEventListener('click', closeShareDialog);
if (copyLinkBtn) copyLinkBtn.addEventListener('click', copyShareLink);
if (enablePassword) enablePassword.addEventListener('change', () => {
if (sharePassword) { sharePassword.disabled = !enablePassword.checked; if (enablePassword.checked) sharePassword.focus(); }
});
if (generatePasswordBtn) generatePasswordBtn.addEventListener('click', generatePassword);
if (enableExpiration) enableExpiration.addEventListener('change', () => {
if (shareExpiration) { shareExpiration.disabled = !enableExpiration.checked; if (enableExpiration.checked) shareExpiration.focus(); }
});
if (updateShareBtn) updateShareBtn.addEventListener('click', updateSharedItem);
if (removeShareBtn) removeShareBtn.addEventListener('click', removeSharedItem);
if (notificationCloseBtn) notificationCloseBtn.addEventListener('click', closeNotificationDialog);
if (sendNotificationBtn) sendNotificationBtn.addEventListener('click', sendNotification);
if (closeNotificationBtn) closeNotificationBtn.addEventListener('click', () => {
if (notificationBanner) notificationBanner.classList.remove('active');
});
// ── Load shares from backend ──
async function loadSharedItems() {
try {
const res = await fetch('/api/shares?page=1&per_page=1000', {
headers: authHeaders()
});
if (res.ok) {
const data = await res.json();
allSharedItems = data.items || [];
} else {
allSharedItems = [];
}
} catch (err) {
console.error('Error loading shared items:', err);
allSharedItems = [];
}
filterAndSortItems();
}
// ── Filter & sort ──
function filterAndSortItems() {
const type = filterType ? filterType.value : 'all';
const sort = sortBy ? sortBy.value : 'date';
const searchTerm = sharedSearch ? sharedSearch.value.toLowerCase() : '';
filteredItems = allSharedItems.filter(item => {
if (type !== 'all' && item.item_type !== type) return false;
const name = (item.item_name || item.item_id || '').toLowerCase();
return name.includes(searchTerm);
});
filteredItems.sort((a, b) => {
if (sort === 'name') {
return (a.item_name || a.item_id || '').localeCompare(b.item_name || b.item_id || '');
} else if (sort === 'date') {
return (b.created_at || 0) - (a.created_at || 0);
} else if (sort === 'expiration') {
if (!a.expires_at && !b.expires_at) return 0;
if (!a.expires_at) return 1;
if (!b.expires_at) return -1;
return a.expires_at - b.expires_at;
}
return 0;
});
displaySharedItems();
}
// ── Display table ──
function displaySharedItems() {
if (!sharedItemsList) return;
sharedItemsList.innerHTML = '';
if (filteredItems.length === 0) {
if (emptySharedState) emptySharedState.style.display = 'flex';
const listContainer = document.querySelector('.shared-list-container');
if (listContainer) listContainer.style.display = 'none';
return;
}
if (emptySharedState) emptySharedState.style.display = 'none';
const listContainer = document.querySelector('.shared-list-container');
if (listContainer) listContainer.style.display = 'block';
filteredItems.forEach(item => {
const row = document.createElement('tr');
const displayName = item.item_name || item.item_id || 'Unknown';
// Name
const nameCell = document.createElement('td');
nameCell.className = 'shared-item-name';
nameCell.innerHTML = `<span class="item-icon">${item.item_type === 'file' ? '📄' : '📁'}</span><span>${displayName}</span>`;
// Type
const typeCell = document.createElement('td');
typeCell.textContent = item.item_type === 'file' ? t('shared_typeFile', 'File') : t('shared_typeFolder', 'Folder');
// Date
const dateCell = document.createElement('td');
dateCell.textContent = formatDate(item.created_at);
// Expiration
const expirationCell = document.createElement('td');
expirationCell.textContent = item.expires_at ? formatDate(item.expires_at) : t('shared_noExpiration', 'No expiration');
// Permissions
const permissionsCell = document.createElement('td');
const perms = [];
if (item.permissions?.read) perms.push(t('share_permissionRead', 'Read'));
if (item.permissions?.write) perms.push(t('share_permissionWrite', 'Write'));
if (item.permissions?.reshare) perms.push(t('share_permissionReshare', 'Reshare'));
permissionsCell.textContent = perms.join(', ') || 'Read';
// Password
const passwordCell = document.createElement('td');
passwordCell.textContent = item.has_password ? t('shared_hasPassword', 'Yes') : t('shared_noPassword', 'No');
// Actions
const actionsCell = document.createElement('td');
actionsCell.className = 'shared-item-actions';
const editBtn = document.createElement('button');
editBtn.className = 'action-btn edit-btn';
editBtn.innerHTML = '<span class="action-icon">✏️</span>';
editBtn.title = t('shared_editShare', 'Edit Share');
editBtn.addEventListener('click', () => openShareDialog(item));
const notifyBtn = document.createElement('button');
notifyBtn.className = 'action-btn notify-btn';
notifyBtn.innerHTML = '<span class="action-icon">📧</span>';
notifyBtn.title = t('shared_notifyShare', 'Notify Someone');
notifyBtn.addEventListener('click', () => openNotificationDialog(item));
const cpBtn = document.createElement('button');
cpBtn.className = 'action-btn copy-btn';
cpBtn.innerHTML = '<span class="action-icon">📋</span>';
cpBtn.title = t('shared_copyLink', 'Copy Link');
cpBtn.addEventListener('click', () => {
navigator.clipboard.writeText(item.url)
.then(() => showNotification(t('shared_linkCopied', 'Link copied!')))
.catch(() => showNotification(t('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
});
const rmBtn = document.createElement('button');
rmBtn.className = 'action-btn remove-btn';
rmBtn.innerHTML = '<span class="action-icon">🗑️</span>';
rmBtn.title = t('shared_removeShare', 'Remove Share');
rmBtn.addEventListener('click', () => { currentSharedItem = item; removeSharedItem(); });
actionsCell.append(editBtn, notifyBtn, cpBtn, rmBtn);
row.append(nameCell, typeCell, dateCell, expirationCell, permissionsCell, passwordCell, actionsCell);
sharedItemsList.appendChild(row);
});
}
// ── Share dialog ──
function openShareDialog(item) {
currentSharedItem = item;
const dn = item.item_name || item.item_id || 'Unknown';
if (shareDialogIcon) shareDialogIcon.textContent = item.item_type === 'file' ? '📄' : '📁';
if (shareDialogName) shareDialogName.textContent = dn;
if (shareLinkUrl) shareLinkUrl.value = item.url || '';
if (permissionRead) permissionRead.checked = item.permissions?.read !== false;
if (permissionWrite) permissionWrite.checked = !!item.permissions?.write;
if (permissionReshare) permissionReshare.checked = !!item.permissions?.reshare;
if (enablePassword) {
enablePassword.checked = item.has_password;
if (sharePassword) { sharePassword.disabled = !enablePassword.checked; sharePassword.value = ''; }
}
if (enableExpiration) {
enableExpiration.checked = !!item.expires_at;
if (shareExpiration) {
shareExpiration.disabled = !enableExpiration.checked;
shareExpiration.value = item.expires_at ? new Date(item.expires_at * 1000).toISOString().split('T')[0] : '';
}
}
if (shareDialog) shareDialog.classList.add('active');
}
function closeShareDialog() {
if (shareDialog) shareDialog.classList.remove('active');
currentSharedItem = null;
}
// ── Notification dialog ──
function openNotificationDialog(item) {
currentSharedItem = item;
const dn = item.item_name || item.item_id || 'Unknown';
if (notifyDialogIcon) notifyDialogIcon.textContent = item.item_type === 'file' ? '📄' : '📁';
if (notifyDialogName) notifyDialogName.textContent = dn;
if (notificationEmail) notificationEmail.value = '';
if (notificationMessage) notificationMessage.value = '';
if (notificationDialog) notificationDialog.classList.add('active');
}
function closeNotificationDialog() {
if (notificationDialog) notificationDialog.classList.remove('active');
currentSharedItem = null;
}
function copyShareLink() {
if (!shareLinkUrl) return;
navigator.clipboard.writeText(shareLinkUrl.value)
.then(() => showNotification(t('shared_linkCopied', 'Link copied!')))
.catch(() => showNotification(t('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
}
// ── Generate secure password with crypto API ──
function generatePassword() {
if (!sharePassword || !enablePassword) return;
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
const array = new Uint32Array(16);
crypto.getRandomValues(array);
let password = '';
for (let i = 0; i < 16; i++) {
password += chars[array[i] % chars.length];
}
sharePassword.value = password;
enablePassword.checked = true;
sharePassword.disabled = false;
}
// ── Update share via API ──
async function updateSharedItem() {
if (!currentSharedItem) return;
const body = {
permissions: {
read: permissionRead ? permissionRead.checked : true,
write: permissionWrite ? permissionWrite.checked : false,
reshare: permissionReshare ? permissionReshare.checked : false
},
password: (enablePassword && enablePassword.checked && sharePassword && sharePassword.value) ? sharePassword.value : null,
expires_at: (enableExpiration && enableExpiration.checked && shareExpiration && shareExpiration.value)
? Math.floor(new Date(shareExpiration.value).getTime() / 1000)
: null
};
try {
const res = await fetch(`/api/shares/${currentSharedItem.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Server error ${res.status}`);
}
showNotification(t('shared_itemUpdated', 'Share settings updated'));
} catch (err) {
console.error('Error updating share:', err);
showNotification(err.message || 'Error updating share', 'error');
}
closeShareDialog();
await loadSharedItems();
}
// ── Remove share via API ──
async function removeSharedItem() {
if (!currentSharedItem) return;
try {
const res = await fetch(`/api/shares/${currentSharedItem.id}`, {
method: 'DELETE',
headers: authHeaders()
});
if (!res.ok && res.status !== 204) throw new Error(`Server error ${res.status}`);
showNotification(t('shared_itemRemoved', 'Share removed'));
} catch (err) {
console.error('Error removing share:', err);
showNotification('Error removing share', 'error');
}
closeShareDialog();
await loadSharedItems();
}
// ── Send notification (stub) ──
function sendNotification() {
if (!currentSharedItem) return;
const email = notificationEmail ? notificationEmail.value.trim() : '';
const message = notificationMessage ? notificationMessage.value.trim() : '';
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
showNotification(t('shared_invalidEmail', 'Please enter a valid email address'), 'error');
return;
}
if (window.fileSharing && window.fileSharing.sendShareNotification) {
window.fileSharing.sendShareNotification(currentSharedItem.url, email, message)
.then(() => { closeNotificationDialog(); showNotification(t('shared_notificationSent', 'Notification sent')); })
.catch(() => showNotification(t('shared_notificationFailed', 'Failed to send notification'), 'error'));
}
}
// ── Helpers ──
function showNotification(message, type = 'success') {
if (notificationBannerMessage && notificationBanner) {
notificationBannerMessage.textContent = message;
notificationBanner.className = 'notification-banner active ' + type;
setTimeout(() => notificationBanner.classList.remove('active'), 5000);
} else if (window.ui && window.ui.showNotification) {
window.ui.showNotification(message, type);
} else {
alert(message);
}
}
function formatDate(value) {
return window.formatDateShort ? window.formatDateShort(value) : String(value);
}
});
+31 -3
View File
@@ -68,6 +68,9 @@ const sharedView = {
container.style.display = 'block';
container.innerHTML = `
<div class="shared-header">
<div class="shared-search">
<input type="text" id="shared-search-input" data-i18n-placeholder="actions.search" placeholder="Search shared items...">
</div>
<div class="shared-filters">
<div class="shared-custom-select" id="filter-type-wrapper">
<button class="shared-select-toggle" id="filter-type-toggle">
@@ -98,6 +101,7 @@ const sharedView = {
<i class="fas fa-share-alt" style="font-size: 48px; color: #ddd; margin-bottom: 16px;"></i>
<p data-i18n="shared_emptyStateTitle">No shared items</p>
<p data-i18n="shared_emptyStateDesc">Items you share will appear here</p>
<button id="go-to-files-btn" class="button primary" data-i18n="shared.goToFiles">Go to Files</button>
</div>
<div class="shared-list-container" style="display:none;">
@@ -239,6 +243,30 @@ const sharedView = {
const sendBtn = document.getElementById('sv-send-notification-btn');
if (sendBtn) sendBtn.addEventListener('click', () => this.sendNotification());
}
// "Go to Files" button in empty state
const goToFilesBtn = document.getElementById('go-to-files-btn');
if (goToFilesBtn) {
goToFilesBtn.addEventListener('click', () => {
if (window.switchToFilesView) window.switchToFilesView();
});
}
// Search input
const searchInput = document.getElementById('shared-search-input');
if (searchInput) {
let searchDebounce;
searchInput.addEventListener('input', () => {
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => this.filterAndSortItems(), 250);
});
searchInput.addEventListener('keyup', e => {
if (e.key === 'Enter') {
clearTimeout(searchDebounce);
this.filterAndSortItems();
}
});
}
},
// Initialize a custom select dropdown
@@ -282,9 +310,9 @@ const sharedView = {
const type = filterTypeActive ? filterTypeActive.dataset.value : 'all';
const sort = sortByActive ? sortByActive.dataset.value : 'date';
// Use the top-bar search if available, otherwise no filter
const topSearch = document.getElementById('shared-search');
const searchTerm = topSearch ? topSearch.value.toLowerCase() : '';
// Use the shared view search input
const searchInput = document.getElementById('shared-search-input');
const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
this.filteredItems = this.items.filter(item => {
if (type !== 'all' && item.item_type !== type) return false;
-313
View File
@@ -1,313 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud - Shared Resources</title>
<!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script>
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/views/shared.css">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<script src="/js/core/icons.js" defer></script>
</head>
<body>
<!-- Main layout similar to index.html -->
<div class="sidebar">
<a href="/" class="logo-container" style="text-decoration:none;color:inherit;">
<div class="logo">
<svg viewBox="0 0 500 500">
<path d="M345 310c32 0 58-26 58-58s-26-58-58-58c-6.2 0-12 0.9-17.5 2.7C318 166 289 143 255 143c-34.3 0-63.1 22.6-73 53.7C176.9 195.7 171 195 165 195c-32 0-58 26-58 58s26 58 58 58h180z" fill="#fff"/>
</svg>
</div>
<div class="app-name">OxiCloud</div>
</a>
<div class="nav-menu">
<a href="/" class="nav-item">
<i class="fas fa-folder"></i>
<span data-i18n="nav.files">Files</span>
</a>
<a href="/shared" class="nav-item active">
<i class="fas fa-share-alt"></i>
<span data-i18n="nav.shared">Shared</span>
</a>
<a href="/#recent" class="nav-item">
<i class="fas fa-clock"></i>
<span data-i18n="nav.recent">Recent</span>
</a>
<a href="/#favorites" class="nav-item">
<i class="fas fa-star"></i>
<span data-i18n="nav.favorites">Favorites</span>
</a>
<a href="/#trash" class="nav-item">
<i class="fas fa-trash"></i>
<span data-i18n="nav.trash">Trash</span>
</a>
</div>
<div class="storage-container">
<div class="storage-title"><i class="fas fa-database" style="margin-right:6px;color:#ff5e3a"></i><span data-i18n="storage.title">Storage</span></div>
<div class="storage-bar">
<div class="storage-fill"></div>
</div>
<div class="storage-info" data-i18n="storage.calculating">Calculating...</div>
</div>
</div>
<!-- Main Content -->
<div class="main-content">
<!-- Top Bar -->
<div class="top-bar">
<div class="search-container">
<i class="fas fa-search search-icon"></i>
<input type="text" id="shared-search" data-i18n-placeholder="actions.search" placeholder="Search shared items...">
<button id="shared-search-btn" class="search-button" data-i18n-title="actions.search_btn" title="Search">
<i class="fas fa-search"></i>
</button>
</div>
<div class="user-controls">
<div id="language-selector"></div>
<div class="user-menu-wrapper">
<div class="user-avatar" id="user-avatar">AD</div>
<div class="user-menu" id="user-menu">
<div class="user-menu-header">
<span class="user-name" id="user-menu-name">Admin</span>
<span class="user-email" id="user-menu-email">admin@oxicloud.local</span>
</div>
<div class="user-menu-divider"></div>
<div class="user-menu-item" id="menu-theme">
<i class="fas fa-moon"></i>
<span data-i18n="user_menu.appearance">Appearance</span>
<div class="theme-toggle-pill" id="theme-toggle-pill">
<div class="theme-toggle-knob"></div>
</div>
</div>
<div class="user-menu-item" id="menu-logout">
<i class="fas fa-sign-out-alt"></i>
<span data-i18n="actions.logout">Log out</span>
</div>
</div>
</div>
</div>
</div>
<div class="content-area">
<h1 class="page-title" data-i18n="shared.pageTitle">Shared Resources</h1>
<p class="page-description" data-i18n="shared.pageDescription">Manage your shared files and folders</p>
<div class="shared-filters">
<div class="filter-group">
<label for="filter-type" data-i18n="shared.filterType">Type:</label>
<select id="filter-type">
<option value="all" data-i18n="shared.filterAll">All</option>
<option value="file" data-i18n="shared.filterFiles">Files</option>
<option value="folder" data-i18n="shared.filterFolders">Folders</option>
</select>
</div>
<div class="filter-group">
<label for="sort-by" data-i18n="shared.sortBy">Sort by:</label>
<select id="sort-by">
<option value="name" data-i18n="shared.sortByName">Name</option>
<option value="date" data-i18n="shared.sortByDate">Date shared</option>
<option value="expiration" data-i18n="shared.sortByExpiration">Expiration</option>
</select>
</div>
</div>
<div class="shared-list-container">
<table class="shared-list">
<thead>
<tr>
<th data-i18n="shared.colName">Name</th>
<th data-i18n="shared.colType">Type</th>
<th data-i18n="shared.colDateShared">Date Shared</th>
<th data-i18n="shared.colExpiration">Expiration</th>
<th data-i18n="shared.colPermissions">Permissions</th>
<th data-i18n="shared.colPassword">Password</th>
<th data-i18n="shared.colActions">Actions</th>
</tr>
</thead>
<tbody id="shared-items-list">
<!-- Shared items will be loaded here dynamically -->
</tbody>
</table>
</div>
<div id="empty-shared-state" class="empty-state">
<div class="empty-state-icon">📂</div>
<h3 data-i18n="shared.emptyStateTitle">No shared resources yet</h3>
<p data-i18n="shared.emptyStateDesc">When you share files or folders, they will appear here</p>
<a href="/" class="button primary" data-i18n="shared.goToFiles">Go to Files</a>
</div>
</div>
</div>
<!-- Share Link Dialog (for editing existing shares) -->
<div id="share-dialog" class="dialog">
<div class="dialog-content">
<div class="dialog-header">
<h3 data-i18n="share.dialogTitle">Share Link</h3>
<button class="close-dialog-btn">&times;</button>
</div>
<div class="dialog-body">
<div class="share-item-info">
<span id="share-dialog-icon" class="item-icon">📄</span>
<span id="share-dialog-name" class="item-name">filename.ext</span>
</div>
<div class="share-link-section">
<label for="share-link-url" data-i18n="share.linkLabel">Share Link:</label>
<div class="share-link-container">
<input type="text" id="share-link-url" readonly>
<button id="copy-link-btn" data-i18n="share.copyLink">Copy</button>
</div>
</div>
<div class="share-settings">
<div class="share-setting">
<label data-i18n="share.permissions">Permissions:</label>
<div class="permissions-options">
<label>
<input type="checkbox" id="permission-read" checked>
<span data-i18n="share.permissionRead">Read</span>
</label>
<label>
<input type="checkbox" id="permission-write">
<span data-i18n="share.permissionWrite">Write</span>
</label>
<label>
<input type="checkbox" id="permission-reshare">
<span data-i18n="share.permissionReshare">Reshare</span>
</label>
</div>
</div>
<div class="share-setting">
<label for="share-password" data-i18n="share.password">Password Protection:</label>
<div class="password-setting">
<input type="checkbox" id="enable-password">
<input type="password" id="share-password" placeholder="Enter password" disabled>
<button id="generate-password" data-i18n="share.generatePassword">Generate</button>
</div>
</div>
<div class="share-setting">
<label for="share-expiration" data-i18n="share.expiration">Expiration Date:</label>
<div class="expiration-setting">
<input type="checkbox" id="enable-expiration">
<input type="date" id="share-expiration" disabled>
</div>
</div>
</div>
<div class="share-actions">
<button id="update-share-btn" class="button primary" data-i18n="share.update">Update Share</button>
<button id="remove-share-btn" class="button danger" data-i18n="share.remove">Remove Share</button>
</div>
</div>
</div>
</div>
<!-- Email Notification Dialog -->
<div id="share-notification-dialog" class="dialog">
<div class="dialog-content">
<div class="dialog-header">
<h3 data-i18n="share.notifyTitle">Send Notification</h3>
<button class="close-dialog-btn">&times;</button>
</div>
<div class="dialog-body">
<div class="share-item-info">
<span id="notify-dialog-icon" class="item-icon">📄</span>
<span id="notify-dialog-name" class="item-name">filename.ext</span>
</div>
<div class="notification-form">
<div class="form-group">
<label for="notification-email" data-i18n="share.notifyEmailLabel">Email Address:</label>
<input type="email" id="notification-email" placeholder="Enter recipient email">
</div>
<div class="form-group">
<label for="notification-message" data-i18n="share.notifyMessageLabel">Message (optional):</label>
<textarea id="notification-msg-text" placeholder="Add a personal message" rows="3"></textarea>
</div>
</div>
<div class="notification-actions">
<button id="send-notification-btn" class="button primary" data-i18n="share.notifySend">Send Notification</button>
</div>
</div>
</div>
</div>
<!-- Notification Banner -->
<div id="notification-banner" class="notification-banner">
<span id="notification-message"></span>
<button id="close-notification" class="close-notification-btn">×</button>
</div>
<script src="/js/core/i18n.js"></script>
<script src="/js/core/languageSelector.js"></script>
<script src="/js/core/formatters.js"></script>
<script src="/js/features/sharing/fileSharing.js"></script>
<script>
// Auth check — redirect to login if no token
(function() {
const token = localStorage.getItem('oxicloud_token');
if (!token) {
window.location.href = '/login';
return;
}
// Set user avatar initials
const userData = JSON.parse(localStorage.getItem('oxicloud_user') || '{}');
const avatarEl = document.getElementById('user-avatar');
const nameEl = document.getElementById('user-menu-name');
const emailEl = document.getElementById('user-menu-email');
if (userData.username && avatarEl) {
const initials = userData.username.substring(0, 2).toUpperCase();
avatarEl.textContent = initials;
}
if (nameEl) nameEl.textContent = userData.username || 'User';
if (emailEl) emailEl.textContent = userData.email || '';
// User menu toggle
if (avatarEl) {
avatarEl.addEventListener('click', (e) => {
e.stopPropagation();
document.getElementById('user-menu').classList.toggle('active');
});
}
document.addEventListener('click', () => {
const menu = document.getElementById('user-menu');
if (menu) menu.classList.remove('active');
});
const logoutBtn = document.getElementById('menu-logout');
if (logoutBtn) {
logoutBtn.addEventListener('click', () => {
localStorage.removeItem('oxicloud_token');
localStorage.removeItem('oxicloud_user');
window.location.href = '/login';
});
}
// Theme toggle (dark mode)
const themeBtn = document.getElementById('menu-theme');
const pill = document.getElementById('theme-toggle-pill');
if (themeBtn && pill) {
const isDark = localStorage.getItem('oxicloud_theme') === 'dark';
if (isDark) pill.classList.add('active');
themeBtn.addEventListener('click', (e) => {
e.stopPropagation();
pill.classList.toggle('active');
const dark = pill.classList.contains('active');
localStorage.setItem('oxicloud_theme', dark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
});
}
})();
</script>
<script src="/js/views/shared/shared.js"></script>
</body>
</html>