style: apply biome CSS/JS format
This commit is contained in:
+490
-290
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,9 @@ const contextMenus = {
|
||||
if (!label) return;
|
||||
label.textContent = window.i18n
|
||||
? window.i18n.t(isFavorite ? 'actions.unfavorite' : 'actions.favorite')
|
||||
: (isFavorite ? 'Remove from favorites' : 'Add to favorites');
|
||||
: isFavorite
|
||||
? 'Remove from favorites'
|
||||
: 'Add to favorites';
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -26,10 +28,7 @@ const contextMenus = {
|
||||
const targetFile = window.app && window.app.contextMenuTargetFile;
|
||||
// Don't show WOPI editor for image files - they should use inline preview
|
||||
const isImage = targetFile && targetFile.mime_type && targetFile.mime_type.startsWith('image/');
|
||||
const show = targetFile &&
|
||||
!isImage &&
|
||||
window.wopiEditor &&
|
||||
await window.wopiEditor.canEdit(targetFile.name);
|
||||
const show = targetFile && !isImage && window.wopiEditor && (await window.wopiEditor.canEdit(targetFile.name));
|
||||
|
||||
wopiEdit.classList.toggle('hidden', !show);
|
||||
wopiEditTab.classList.toggle('hidden', !show);
|
||||
@@ -59,10 +58,7 @@ const contextMenus = {
|
||||
// Folder context menu options
|
||||
document.getElementById('download-folder-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFolder) {
|
||||
window.fileOps.downloadFolder(
|
||||
window.app.contextMenuTargetFolder.id,
|
||||
window.app.contextMenuTargetFolder.name
|
||||
);
|
||||
window.fileOps.downloadFolder(window.app.contextMenuTargetFolder.id, window.app.contextMenuTargetFolder.name);
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
@@ -80,12 +76,7 @@ const contextMenus = {
|
||||
}
|
||||
} else {
|
||||
// Add to favorites
|
||||
const ok = await window.favorites.addToFavorites(
|
||||
folder.id,
|
||||
folder.name,
|
||||
'folder',
|
||||
folder.parent_id
|
||||
);
|
||||
const ok = await window.favorites.addToFavorites(folder.id, folder.name, 'folder', folder.parent_id);
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(folder.id, 'folder', true);
|
||||
}
|
||||
@@ -130,9 +121,11 @@ const contextMenus = {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
// Capture reference before context menu cleanup nullifies it
|
||||
const file = window.app.contextMenuTargetFile;
|
||||
fetch(`/api/files/${file.id}?metadata=true`, { credentials: 'same-origin' })
|
||||
.then(response => response.json())
|
||||
.then(fileDetails => {
|
||||
fetch(`/api/files/${file.id}?metadata=true`, {
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.then((fileDetails) => {
|
||||
// Check if viewable file type (images, PDFs, text files)
|
||||
if (window.ui && window.ui.isViewableFile(fileDetails)) {
|
||||
// Open with inline viewer
|
||||
@@ -147,7 +140,7 @@ const contextMenus = {
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
.catch((error) => {
|
||||
console.error('Error fetching file details:', error);
|
||||
// On error, fallback to download
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
@@ -174,10 +167,7 @@ const contextMenus = {
|
||||
|
||||
document.getElementById('download-file-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
window.fileOps.downloadFile(
|
||||
window.app.contextMenuTargetFile.id,
|
||||
window.app.contextMenuTargetFile.name
|
||||
);
|
||||
window.fileOps.downloadFile(window.app.contextMenuTargetFile.id, window.app.contextMenuTargetFile.name);
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
@@ -195,12 +185,7 @@ const contextMenus = {
|
||||
}
|
||||
} else {
|
||||
// Add to favorites
|
||||
const ok = await window.favorites.addToFavorites(
|
||||
file.id,
|
||||
file.name,
|
||||
'file',
|
||||
file.folder_id
|
||||
);
|
||||
const ok = await window.favorites.addToFavorites(file.id, file.name, 'file', file.folder_id);
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(file.id, 'file', true);
|
||||
}
|
||||
@@ -285,33 +270,27 @@ const contextMenus = {
|
||||
const targetId = window.app.selectedTargetFolderId;
|
||||
const items = window.app.batchMoveItems || [];
|
||||
|
||||
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
|
||||
const folderIds = items.filter(i => i.type === 'folder').map(i => i.id);
|
||||
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id);
|
||||
const folderIds = items.filter((i) => i.type === 'folder').map((i) => i.id);
|
||||
|
||||
let result = await window.fileOps.batchCopy(fileIds, folderIds, targetId);
|
||||
|
||||
let result = await window.fileOps.batchCopy( fileIds, folderIds, targetId);
|
||||
|
||||
this.closeMoveDialog();
|
||||
window.multiSelect.clear();
|
||||
window.loadFiles();
|
||||
|
||||
window.multiSelect.showBatchResult( "copy", result);
|
||||
window.multiSelect.showBatchResult('copy', result);
|
||||
return;
|
||||
}
|
||||
|
||||
// Single item copy
|
||||
if (window.app.moveDialogMode === 'file' && window.app.contextMenuTargetFile) {
|
||||
const success = await window.fileOps.copyFile(
|
||||
window.app.contextMenuTargetFile.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
const success = await window.fileOps.copyFile(window.app.contextMenuTargetFile.id, window.app.selectedTargetFolderId);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
} else if (window.app.moveDialogMode === 'folder' && window.app.contextMenuTargetFolder) {
|
||||
const success = await window.fileOps.copyFolder(
|
||||
window.app.contextMenuTargetFolder.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
const success = await window.fileOps.copyFolder(window.app.contextMenuTargetFolder.id, window.app.selectedTargetFolderId);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
@@ -324,32 +303,26 @@ const contextMenus = {
|
||||
const targetId = window.app.selectedTargetFolderId;
|
||||
const items = window.app.batchMoveItems || [];
|
||||
|
||||
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
|
||||
const folderIds = items.filter(i => i.type === 'folder' && i.id !== targetId).map(i => i.id);
|
||||
|
||||
let result = await window.fileOps.batchMove( fileIds, folderIds, targetId);
|
||||
|
||||
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id);
|
||||
const folderIds = items.filter((i) => i.type === 'folder' && i.id !== targetId).map((i) => i.id);
|
||||
|
||||
let result = await window.fileOps.batchMove(fileIds, folderIds, targetId);
|
||||
|
||||
this.closeMoveDialog();
|
||||
window.multiSelect.clear();
|
||||
window.loadFiles();
|
||||
window.multiSelect.showBatchResult( "move", result);
|
||||
|
||||
window.multiSelect.showBatchResult('move', result);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.app.moveDialogMode === 'file' && window.app.contextMenuTargetFile) {
|
||||
const success = await window.fileOps.moveFile(
|
||||
window.app.contextMenuTargetFile.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
const success = await window.fileOps.moveFile(window.app.contextMenuTargetFile.id, window.app.selectedTargetFolderId);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
} else if (window.app.moveDialogMode === 'folder' && window.app.contextMenuTargetFolder) {
|
||||
const success = await window.fileOps.moveFolder(
|
||||
window.app.contextMenuTargetFolder.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
const success = await window.fileOps.moveFolder(window.app.contextMenuTargetFolder.id, window.app.selectedTargetFolderId);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
@@ -416,7 +389,7 @@ const contextMenus = {
|
||||
window.app.moveDialogMode = mode;
|
||||
|
||||
// Reset selection
|
||||
window.app.selectedTargetFolderId = "";
|
||||
window.app.selectedTargetFolderId = '';
|
||||
|
||||
// Ensure we have the home folder ID BEFORE calculating startFolderId
|
||||
if (!window.app.userHomeFolderId) {
|
||||
@@ -442,7 +415,16 @@ const contextMenus = {
|
||||
startFolderId = window.app.userHomeFolderId || null;
|
||||
}
|
||||
|
||||
console.log('[Move Dialog] showMoveDialog - item:', item, 'mode:', mode, 'startFolderId:', startFolderId, 'userHomeFolderId:', window.app.userHomeFolderId);
|
||||
console.log(
|
||||
'[Move Dialog] showMoveDialog - item:',
|
||||
item,
|
||||
'mode:',
|
||||
mode,
|
||||
'startFolderId:',
|
||||
startFolderId,
|
||||
'userHomeFolderId:',
|
||||
window.app.userHomeFolderId
|
||||
);
|
||||
|
||||
// Store the item being moved and navigation state
|
||||
window.app.moveDialogItemId = item.id;
|
||||
@@ -460,9 +442,14 @@ const contextMenus = {
|
||||
|
||||
// Update dialog title (preserve icon)
|
||||
const dialogHeader = document.getElementById('move-file-dialog').querySelector('.rename-dialog-header');
|
||||
const titleText = mode === 'file' ?
|
||||
(window.i18n ? window.i18n.t('dialogs.move_file') : 'Move file') :
|
||||
(window.i18n ? window.i18n.t('dialogs.move_folder') : 'Move folder');
|
||||
const titleText =
|
||||
mode === 'file'
|
||||
? window.i18n
|
||||
? window.i18n.t('dialogs.move_file')
|
||||
: 'Move file'
|
||||
: window.i18n
|
||||
? window.i18n.t('dialogs.move_folder')
|
||||
: 'Move folder';
|
||||
dialogHeader.innerHTML = `<i class="fas fa-arrows-alt dialog-header-icon"></i> <span>${titleText}</span>`;
|
||||
|
||||
// Load folders for the starting location
|
||||
@@ -525,7 +512,6 @@ const contextMenus = {
|
||||
*/
|
||||
async loadMoveDialogFolders(parentFolderId) {
|
||||
try {
|
||||
|
||||
// Ensure we have the home folder ID before proceeding
|
||||
if (!window.app.userHomeFolderId) {
|
||||
await window.resolveHomeFolder();
|
||||
@@ -555,7 +541,7 @@ const contextMenus = {
|
||||
|
||||
// The contents endpoint returns an array of child folders
|
||||
// The fallback /api/folders returns root folders (home folder itself)
|
||||
const folders = Array.isArray(data) ? data : (data.folders || []);
|
||||
const folders = Array.isArray(data) ? data : data.folders || [];
|
||||
console.log('[Move Dialog] Loaded folders:', folders.length, 'folders:', folders);
|
||||
|
||||
const folderSelectContainer = document.getElementById('folder-select-container');
|
||||
@@ -582,7 +568,7 @@ const contextMenus = {
|
||||
<span>${window.i18n ? window.i18n.t('dialogs.select_this_folder') : 'Select this folder'}</span>
|
||||
`;
|
||||
currentFolderOption.addEventListener('click', () => {
|
||||
document.querySelectorAll('.folder-select-item').forEach(item => {
|
||||
document.querySelectorAll('.folder-select-item').forEach((item) => {
|
||||
item.classList.remove('selected');
|
||||
});
|
||||
currentFolderOption.classList.add('selected');
|
||||
@@ -606,9 +592,7 @@ const contextMenus = {
|
||||
if (currentBreadcrumb.length > 0) {
|
||||
// Remove current folder from breadcrumb
|
||||
currentBreadcrumb.pop();
|
||||
const parentFolder = currentBreadcrumb.length > 0
|
||||
? currentBreadcrumb[currentBreadcrumb.length - 1]
|
||||
: null;
|
||||
const parentFolder = currentBreadcrumb.length > 0 ? currentBreadcrumb[currentBreadcrumb.length - 1] : null;
|
||||
window.app.moveDialogBreadcrumb = currentBreadcrumb;
|
||||
window.app.moveDialogCurrentFolderId = parentFolder ? parentFolder.id : null;
|
||||
this.loadMoveDialogFolders(parentFolder ? parentFolder.id : null);
|
||||
@@ -623,7 +607,7 @@ const contextMenus = {
|
||||
}
|
||||
|
||||
// Add subfolders (clicking navigates INTO the folder)
|
||||
folders.forEach(folder => {
|
||||
folders.forEach((folder) => {
|
||||
// Skip the item being moved (to prevent moving a folder into itself)
|
||||
if (mode === 'folder' && folder.id === itemId) {
|
||||
return;
|
||||
@@ -661,11 +645,11 @@ const contextMenus = {
|
||||
<span>${window.i18n ? window.i18n.t('dialogs.move_to_home') : 'Move to Home folder'}</span>
|
||||
`;
|
||||
homeOption.addEventListener('click', () => {
|
||||
document.querySelectorAll('.folder-select-item').forEach(item => {
|
||||
document.querySelectorAll('.folder-select-item').forEach((item) => {
|
||||
item.classList.remove('selected');
|
||||
});
|
||||
homeOption.classList.add('selected');
|
||||
window.app.selectedTargetFolderId = ''; // Empty means root/home
|
||||
window.app.selectedTargetFolderId = ''; // Empty means root/home
|
||||
});
|
||||
folderSelectContainer.appendChild(homeOption);
|
||||
} else if (folders.length === 0) {
|
||||
@@ -780,147 +764,150 @@ const contextMenus = {
|
||||
*/
|
||||
async showShareDialog(item, itemType) {
|
||||
try {
|
||||
const shareDialog = document.getElementById('share-dialog');
|
||||
if (!shareDialog) {
|
||||
console.error('Share dialog element not found in DOM');
|
||||
window.ui.showNotification('Error', 'Share dialog not available');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update dialog title — use the <span> inside header to preserve <i> icon
|
||||
const dialogHeader = shareDialog.querySelector('.share-dialog-header');
|
||||
if (dialogHeader) {
|
||||
const headerSpan = dialogHeader.querySelector('span');
|
||||
const titleText = itemType === 'file' ?
|
||||
(window.i18n ? window.i18n.t('dialogs.share_file') : 'Share file') :
|
||||
(window.i18n ? window.i18n.t('dialogs.share_folder') : 'Share folder');
|
||||
if (headerSpan) {
|
||||
headerSpan.textContent = titleText;
|
||||
} else {
|
||||
dialogHeader.textContent = titleText;
|
||||
const shareDialog = document.getElementById('share-dialog');
|
||||
if (!shareDialog) {
|
||||
console.error('Share dialog element not found in DOM');
|
||||
window.ui.showNotification('Error', 'Share dialog not available');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const itemName = document.getElementById('shared-item-name');
|
||||
if (itemName) itemName.textContent = item.name;
|
||||
|
||||
// Reset form
|
||||
const pwField = document.getElementById('share-password');
|
||||
const expField = document.getElementById('share-expiration');
|
||||
if (pwField) pwField.value = '';
|
||||
if (expField) expField.value = '';
|
||||
const permRead = document.getElementById('share-permission-read');
|
||||
const permWrite = document.getElementById('share-permission-write');
|
||||
const permReshare = document.getElementById('share-permission-reshare');
|
||||
if (permRead) permRead.checked = true;
|
||||
if (permWrite) permWrite.checked = false;
|
||||
if (permReshare) permReshare.checked = false;
|
||||
|
||||
// Store the current item and type for use when creating the share
|
||||
window.app.shareDialogItem = item;
|
||||
window.app.shareDialogItemType = itemType;
|
||||
|
||||
// Check if item already has shares (async API call)
|
||||
const existingShares = await window.fileSharing.getSharedLinksForItem(item.id, itemType);
|
||||
const existingSharesContainer = document.getElementById('existing-shares-container');
|
||||
|
||||
// Clear existing shares container
|
||||
existingSharesContainer.innerHTML = '';
|
||||
|
||||
if (existingShares.length > 0) {
|
||||
document.getElementById('existing-shares-section').classList.remove('hidden');
|
||||
|
||||
// Create elements for each existing share
|
||||
existingShares.forEach(share => {
|
||||
const shareEl = document.createElement('div');
|
||||
shareEl.className = 'existing-share-item';
|
||||
|
||||
const expiresText = share.expires_at ?
|
||||
`Expires: ${window.fileSharing.formatExpirationDate(share.expires_at)}` :
|
||||
'No expiration';
|
||||
|
||||
// Share URL
|
||||
const urlDiv = document.createElement('div');
|
||||
urlDiv.className = 'share-url';
|
||||
urlDiv.textContent = share.url;
|
||||
shareEl.appendChild(urlDiv);
|
||||
|
||||
// Share info
|
||||
const infoDiv = document.createElement('div');
|
||||
infoDiv.className = 'share-info';
|
||||
if (share.has_password) {
|
||||
const protectedSpan = document.createElement('span');
|
||||
protectedSpan.className = 'share-protected';
|
||||
protectedSpan.innerHTML = '<i class="fas fa-lock"></i> Password protected';
|
||||
infoDiv.appendChild(protectedSpan);
|
||||
// Update dialog title — use the <span> inside header to preserve <i> icon
|
||||
const dialogHeader = shareDialog.querySelector('.share-dialog-header');
|
||||
if (dialogHeader) {
|
||||
const headerSpan = dialogHeader.querySelector('span');
|
||||
const titleText =
|
||||
itemType === 'file'
|
||||
? window.i18n
|
||||
? window.i18n.t('dialogs.share_file')
|
||||
: 'Share file'
|
||||
: window.i18n
|
||||
? window.i18n.t('dialogs.share_folder')
|
||||
: 'Share folder';
|
||||
if (headerSpan) {
|
||||
headerSpan.textContent = titleText;
|
||||
} else {
|
||||
dialogHeader.textContent = titleText;
|
||||
}
|
||||
const expirationSpan = document.createElement('span');
|
||||
expirationSpan.className = 'share-expiration';
|
||||
expirationSpan.textContent = expiresText;
|
||||
infoDiv.appendChild(expirationSpan);
|
||||
shareEl.appendChild(infoDiv);
|
||||
}
|
||||
|
||||
// Share actions
|
||||
const actionsDiv = document.createElement('div');
|
||||
actionsDiv.className = 'share-actions';
|
||||
const itemName = document.getElementById('shared-item-name');
|
||||
if (itemName) itemName.textContent = item.name;
|
||||
|
||||
const copyBtn = document.createElement('button');
|
||||
copyBtn.className = 'btn btn-small copy-link-btn';
|
||||
copyBtn.dataset.shareUrl = share.url;
|
||||
copyBtn.innerHTML = '<i class="fas fa-copy"></i> Copy';
|
||||
actionsDiv.appendChild(copyBtn);
|
||||
// Reset form
|
||||
const pwField = document.getElementById('share-password');
|
||||
const expField = document.getElementById('share-expiration');
|
||||
if (pwField) pwField.value = '';
|
||||
if (expField) expField.value = '';
|
||||
const permRead = document.getElementById('share-permission-read');
|
||||
const permWrite = document.getElementById('share-permission-write');
|
||||
const permReshare = document.getElementById('share-permission-reshare');
|
||||
if (permRead) permRead.checked = true;
|
||||
if (permWrite) permWrite.checked = false;
|
||||
if (permReshare) permReshare.checked = false;
|
||||
|
||||
const deleteBtn = document.createElement('button');
|
||||
deleteBtn.className = 'btn btn-small btn-danger delete-link-btn';
|
||||
deleteBtn.dataset.shareId = share.id;
|
||||
deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
|
||||
actionsDiv.appendChild(deleteBtn);
|
||||
// Store the current item and type for use when creating the share
|
||||
window.app.shareDialogItem = item;
|
||||
window.app.shareDialogItemType = itemType;
|
||||
|
||||
shareEl.appendChild(actionsDiv);
|
||||
// Check if item already has shares (async API call)
|
||||
const existingShares = await window.fileSharing.getSharedLinksForItem(item.id, itemType);
|
||||
const existingSharesContainer = document.getElementById('existing-shares-container');
|
||||
|
||||
existingSharesContainer.appendChild(shareEl);
|
||||
});
|
||||
// Clear existing shares container
|
||||
existingSharesContainer.innerHTML = '';
|
||||
|
||||
// Add event listeners for copy and delete buttons
|
||||
document.querySelectorAll('.copy-link-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const url = btn.getAttribute('data-share-url');
|
||||
window.fileSharing.copyLinkToClipboard(url);
|
||||
if (existingShares.length > 0) {
|
||||
document.getElementById('existing-shares-section').classList.remove('hidden');
|
||||
|
||||
// Create elements for each existing share
|
||||
existingShares.forEach((share) => {
|
||||
const shareEl = document.createElement('div');
|
||||
shareEl.className = 'existing-share-item';
|
||||
|
||||
const expiresText = share.expires_at ? `Expires: ${window.fileSharing.formatExpirationDate(share.expires_at)}` : 'No expiration';
|
||||
|
||||
// Share URL
|
||||
const urlDiv = document.createElement('div');
|
||||
urlDiv.className = 'share-url';
|
||||
urlDiv.textContent = share.url;
|
||||
shareEl.appendChild(urlDiv);
|
||||
|
||||
// Share info
|
||||
const infoDiv = document.createElement('div');
|
||||
infoDiv.className = 'share-info';
|
||||
if (share.has_password) {
|
||||
const protectedSpan = document.createElement('span');
|
||||
protectedSpan.className = 'share-protected';
|
||||
protectedSpan.innerHTML = '<i class="fas fa-lock"></i> Password protected';
|
||||
infoDiv.appendChild(protectedSpan);
|
||||
}
|
||||
const expirationSpan = document.createElement('span');
|
||||
expirationSpan.className = 'share-expiration';
|
||||
expirationSpan.textContent = expiresText;
|
||||
infoDiv.appendChild(expirationSpan);
|
||||
shareEl.appendChild(infoDiv);
|
||||
|
||||
// Share actions
|
||||
const actionsDiv = document.createElement('div');
|
||||
actionsDiv.className = 'share-actions';
|
||||
|
||||
const copyBtn = document.createElement('button');
|
||||
copyBtn.className = 'btn btn-small copy-link-btn';
|
||||
copyBtn.dataset.shareUrl = share.url;
|
||||
copyBtn.innerHTML = '<i class="fas fa-copy"></i> Copy';
|
||||
actionsDiv.appendChild(copyBtn);
|
||||
|
||||
const deleteBtn = document.createElement('button');
|
||||
deleteBtn.className = 'btn btn-small btn-danger delete-link-btn';
|
||||
deleteBtn.dataset.shareId = share.id;
|
||||
deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
|
||||
actionsDiv.appendChild(deleteBtn);
|
||||
|
||||
shareEl.appendChild(actionsDiv);
|
||||
|
||||
existingSharesContainer.appendChild(shareEl);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.delete-link-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const shareId = btn.getAttribute('data-share-id');
|
||||
|
||||
showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete_share') : 'Delete link',
|
||||
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_share_msg') : 'Are you sure you want to delete this shared link?',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete',
|
||||
}).then(async (confirmed) => {
|
||||
if (confirmed) {
|
||||
await window.fileSharing.removeSharedLink(shareId);
|
||||
btn.closest('.existing-share-item').remove();
|
||||
if (existingSharesContainer.children.length === 0) {
|
||||
document.getElementById('existing-shares-section').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
// Add event listeners for copy and delete buttons
|
||||
document.querySelectorAll('.copy-link-btn').forEach((btn) => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const url = btn.getAttribute('data-share-url');
|
||||
window.fileSharing.copyLinkToClipboard(url);
|
||||
});
|
||||
});
|
||||
});
|
||||
} else {
|
||||
document.getElementById('existing-shares-section').classList.add('hidden');
|
||||
}
|
||||
|
||||
// Hide new-share section from previous use
|
||||
const newShareSection = document.getElementById('new-share-section');
|
||||
if (newShareSection) newShareSection.classList.add('hidden');
|
||||
document.querySelectorAll('.delete-link-btn').forEach((btn) => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const shareId = btn.getAttribute('data-share-id');
|
||||
|
||||
// Show dialog
|
||||
shareDialog.style.display = 'flex';
|
||||
console.log('Share dialog opened for', itemType, item.name);
|
||||
showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete_share') : 'Delete link',
|
||||
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_share_msg') : 'Are you sure you want to delete this shared link?',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete'
|
||||
}).then(async (confirmed) => {
|
||||
if (confirmed) {
|
||||
await window.fileSharing.removeSharedLink(shareId);
|
||||
btn.closest('.existing-share-item').remove();
|
||||
if (existingSharesContainer.children.length === 0) {
|
||||
document.getElementById('existing-shares-section').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
} else {
|
||||
document.getElementById('existing-shares-section').classList.add('hidden');
|
||||
}
|
||||
|
||||
// Hide new-share section from previous use
|
||||
const newShareSection = document.getElementById('new-share-section');
|
||||
if (newShareSection) newShareSection.classList.add('hidden');
|
||||
|
||||
// Show dialog
|
||||
shareDialog.style.display = 'flex';
|
||||
console.log('Share dialog opened for', itemType, item.name);
|
||||
} catch (error) {
|
||||
console.error('Error opening share dialog:', error);
|
||||
window.ui.showNotification('Error', 'Could not open share dialog');
|
||||
@@ -961,7 +948,10 @@ const contextMenus = {
|
||||
};
|
||||
|
||||
try {
|
||||
const headers = { 'Content-Type': 'application/json', ...getCsrfHeaders() };
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...getCsrfHeaders()
|
||||
};
|
||||
|
||||
const response = await fetch('/api/shares', {
|
||||
method: 'POST',
|
||||
@@ -990,7 +980,6 @@ const contextMenus = {
|
||||
window.i18n ? window.i18n.t('notifications.link_created') : 'Link created',
|
||||
window.i18n ? window.i18n.t('notifications.share_success') : 'Shared link created successfully'
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating shared link:', error);
|
||||
window.ui.showNotification('Error', error.message || 'Could not create shared link');
|
||||
|
||||
@@ -14,18 +14,15 @@ function getAuthHeaders() {
|
||||
|
||||
// File Operations Module
|
||||
const fileOps = {
|
||||
|
||||
// ========================================================================
|
||||
// Upload progress — notification bell integration
|
||||
// ========================================================================
|
||||
_currentBatchId: null,
|
||||
_isUploading: false, // Guard against concurrent upload calls
|
||||
_isUploading: false, // Guard against concurrent upload calls
|
||||
|
||||
/** Start a new upload batch in the notification bell */
|
||||
_initUploadToast(totalFiles, folderName) {
|
||||
this._currentBatchId = window.notifications
|
||||
? window.notifications.addUploadBatch(totalFiles, folderName)
|
||||
: null;
|
||||
this._currentBatchId = window.notifications ? window.notifications.addUploadBatch(totalFiles, folderName) : null;
|
||||
},
|
||||
|
||||
/** Finalise the batch in the notification bell */
|
||||
@@ -100,7 +97,9 @@ const fileOps = {
|
||||
const resetStallTimer = () => {
|
||||
if (stallTimer) clearTimeout(stallTimer);
|
||||
stallTimer = setTimeout(() => {
|
||||
try { xhr.abort(); } catch (_) {}
|
||||
try {
|
||||
xhr.abort();
|
||||
} catch (_) {}
|
||||
safeUpdateFile(0, 'error');
|
||||
finalize({
|
||||
ok: false,
|
||||
@@ -112,7 +111,9 @@ const fileOps = {
|
||||
|
||||
resetStallTimer();
|
||||
hardTimer = setTimeout(() => {
|
||||
try { xhr.abort(); } catch (_) {}
|
||||
try {
|
||||
xhr.abort();
|
||||
} catch (_) {}
|
||||
safeUpdateFile(0, 'error');
|
||||
finalize({
|
||||
ok: false,
|
||||
@@ -144,7 +145,9 @@ const fileOps = {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
safeUpdateFile(100, 'done');
|
||||
let data = null;
|
||||
try { data = JSON.parse(xhr.responseText); } catch (_) {}
|
||||
try {
|
||||
data = JSON.parse(xhr.responseText);
|
||||
} catch (_) {}
|
||||
finalize({ ok: true, data });
|
||||
} else {
|
||||
safeUpdateFile(0, 'error');
|
||||
@@ -167,12 +170,20 @@ const fileOps = {
|
||||
|
||||
xhr.addEventListener('abort', () => {
|
||||
safeUpdateFile(0, 'error');
|
||||
finalize({ ok: false, isTimeout: true, errorMsg: `Upload aborted/stalled: ${fileName}` });
|
||||
finalize({
|
||||
ok: false,
|
||||
isTimeout: true,
|
||||
errorMsg: `Upload aborted/stalled: ${fileName}`
|
||||
});
|
||||
});
|
||||
|
||||
xhr.addEventListener('timeout', () => {
|
||||
safeUpdateFile(0, 'error');
|
||||
finalize({ ok: false, isTimeout: true, errorMsg: `Timeout after ${Math.round(timeoutMs / 1000)}s` });
|
||||
finalize({
|
||||
ok: false,
|
||||
isTimeout: true,
|
||||
errorMsg: `Timeout after ${Math.round(timeoutMs / 1000)}s`
|
||||
});
|
||||
});
|
||||
|
||||
xhr.open('POST', '/api/files/upload');
|
||||
@@ -218,18 +229,20 @@ const fileOps = {
|
||||
|
||||
// Read body as text first (always consume the response fully)
|
||||
let rawText = '';
|
||||
try { rawText = await response.text(); } catch (_) {}
|
||||
try {
|
||||
rawText = await response.text();
|
||||
} catch (_) {}
|
||||
|
||||
let body = null;
|
||||
try { body = JSON.parse(rawText); } catch (_) {}
|
||||
try {
|
||||
body = JSON.parse(rawText);
|
||||
} catch (_) {}
|
||||
|
||||
if (response.ok) {
|
||||
return { ok: true, data: body };
|
||||
}
|
||||
|
||||
const errorMsg = body && typeof body === 'object'
|
||||
? (body.error || null)
|
||||
: (rawText || null);
|
||||
const errorMsg = body && typeof body === 'object' ? body.error || null : rawText || null;
|
||||
const isQuotaError = (body && typeof body === 'object' && body.error_type === 'QuotaExceeded') || response.status === 507;
|
||||
return { ok: false, errorMsg, isQuotaError };
|
||||
} catch (e) {
|
||||
@@ -237,9 +250,7 @@ const fileOps = {
|
||||
return {
|
||||
ok: false,
|
||||
isTimeout,
|
||||
errorMsg: isTimeout
|
||||
? `Timeout after ${Math.round(timeoutMs / 1000)}s`
|
||||
: `Fetch upload failed: ${e?.message || 'network error'}`
|
||||
errorMsg: isTimeout ? `Timeout after ${Math.round(timeoutMs / 1000)}s` : `Fetch upload failed: ${e?.message || 'network error'}`
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
@@ -269,8 +280,12 @@ const fileOps = {
|
||||
// Legacy progress bar (inside dropzone) — keep working for drag-drop
|
||||
const progressBar = document.querySelector('.progress-fill');
|
||||
const uploadProgressDiv = document.querySelector('.upload-progress');
|
||||
if (uploadProgressDiv) { uploadProgressDiv.style.display = 'block'; }
|
||||
if (progressBar) { progressBar.style.width = '0%'; }
|
||||
if (uploadProgressDiv) {
|
||||
uploadProgressDiv.style.display = 'block';
|
||||
}
|
||||
if (progressBar) {
|
||||
progressBar.style.width = '0%';
|
||||
}
|
||||
|
||||
// Filter out unreadable entries (typically dropped folders/placeholders)
|
||||
const readableFiles = [];
|
||||
@@ -321,7 +336,8 @@ const fileOps = {
|
||||
formData.append('file', file);
|
||||
|
||||
console.log(`Uploading file to folder: ${targetFolderId || 'root'}`, {
|
||||
file: file.name, size: file.size
|
||||
file: file.name,
|
||||
size: file.size
|
||||
});
|
||||
|
||||
// Scale stall timeout with file size:
|
||||
@@ -334,7 +350,7 @@ const fileOps = {
|
||||
|
||||
// Legacy dropzone bar
|
||||
if (progressBar) {
|
||||
progressBar.style.width = ((uploadedCount / totalFiles) * 100) + '%';
|
||||
progressBar.style.width = (uploadedCount / totalFiles) * 100 + '%';
|
||||
}
|
||||
// Notify bell of per-file completion
|
||||
if (window.notifications && batchId) {
|
||||
@@ -378,7 +394,9 @@ const fileOps = {
|
||||
|
||||
// Refresh storage usage display
|
||||
if (typeof window.refreshUserData === 'function') {
|
||||
try { await window.refreshUserData(); } catch (_) {}
|
||||
try {
|
||||
await window.refreshUserData();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -425,8 +443,12 @@ const fileOps = {
|
||||
|
||||
const progressBar = document.querySelector('.progress-fill');
|
||||
const uploadProgressDiv = document.querySelector('.upload-progress');
|
||||
if (uploadProgressDiv) { uploadProgressDiv.style.display = 'block'; }
|
||||
if (progressBar) { progressBar.style.width = '0%'; }
|
||||
if (uploadProgressDiv) {
|
||||
uploadProgressDiv.style.display = 'block';
|
||||
}
|
||||
if (progressBar) {
|
||||
progressBar.style.width = '0%';
|
||||
}
|
||||
|
||||
try {
|
||||
// Filter unreadable entries
|
||||
@@ -460,9 +482,7 @@ const fileOps = {
|
||||
}
|
||||
}
|
||||
|
||||
const sortedPaths = [...folderPaths].sort((a, b) =>
|
||||
a.split('/').length - b.split('/').length
|
||||
);
|
||||
const sortedPaths = [...folderPaths].sort((a, b) => a.split('/').length - b.split('/').length);
|
||||
|
||||
// Create folders first
|
||||
for (const folderPath of sortedPaths) {
|
||||
@@ -498,16 +518,23 @@ const fileOps = {
|
||||
}
|
||||
|
||||
// Detect root folder(s) from entry paths
|
||||
const rootFolderNames = [...new Set(validEntries.map((entry) => {
|
||||
const rel = entry.relativePath || entry.file.name;
|
||||
return rel.split('/')[0] || '';
|
||||
}).filter(Boolean))];
|
||||
const rootFolderNames = [
|
||||
...new Set(
|
||||
validEntries
|
||||
.map((entry) => {
|
||||
const rel = entry.relativePath || entry.file.name;
|
||||
return rel.split('/')[0] || '';
|
||||
})
|
||||
.filter(Boolean)
|
||||
)
|
||||
];
|
||||
const locale = window.i18n?.getCurrentLocale?.() || 'en';
|
||||
const rootFolderLabel = rootFolderNames.length <= 1
|
||||
? (rootFolderNames[0] || '')
|
||||
: (locale.startsWith('es')
|
||||
? `${rootFolderNames.length} carpetas`
|
||||
: `${rootFolderNames.length} folders`);
|
||||
const rootFolderLabel =
|
||||
rootFolderNames.length <= 1
|
||||
? rootFolderNames[0] || ''
|
||||
: locale.startsWith('es')
|
||||
? `${rootFolderNames.length} carpetas`
|
||||
: `${rootFolderNames.length} folders`;
|
||||
|
||||
// Upload files — pass folder name for folder-level progress display
|
||||
this._initUploadToast(totalFiles, rootFolderLabel);
|
||||
@@ -522,8 +549,8 @@ const fileOps = {
|
||||
// so all files reaching fetch() are regular. Keep-alive
|
||||
// reuses TCP connections across workers for speed.
|
||||
const CONCURRENCY = 10;
|
||||
const TIMEOUT_MS = 10000; // 10s for normal files
|
||||
const TIMEOUT_MS_ZERO = 3000; // 3s for 0-byte files
|
||||
const TIMEOUT_MS = 10000; // 10s for normal files
|
||||
const TIMEOUT_MS_ZERO = 3000; // 3s for 0-byte files
|
||||
|
||||
const uploadOneFile = async (idx) => {
|
||||
if (quotaStop) return;
|
||||
@@ -542,13 +569,12 @@ const fileOps = {
|
||||
// but block on open(). Pre-read only 0-byte files into
|
||||
// memory; files with size>0 are always regular files and
|
||||
// go straight to FormData (zero extra memory copy).
|
||||
let uploadFile = file; // default: use original File
|
||||
let uploadFile = file; // default: use original File
|
||||
if (file.size === 0) {
|
||||
try {
|
||||
const buf = await Promise.race([
|
||||
file.arrayBuffer(),
|
||||
new Promise((_, rej) =>
|
||||
setTimeout(() => rej(new Error('read-timeout')), 2000))
|
||||
new Promise((_, rej) => setTimeout(() => rej(new Error('read-timeout')), 2000))
|
||||
]);
|
||||
uploadFile = new Blob([buf], {
|
||||
type: file.type || 'application/octet-stream'
|
||||
@@ -558,7 +584,9 @@ const fileOps = {
|
||||
uploadedCount++;
|
||||
successCount++;
|
||||
if (window.notifications && batchId) {
|
||||
try { window.notifications.fileCompleted(batchId, true); } catch (_) {}
|
||||
try {
|
||||
window.notifications.fileCompleted(batchId, true);
|
||||
} catch (_) {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -585,10 +613,12 @@ const fileOps = {
|
||||
uploadedCount++;
|
||||
|
||||
if (window.notifications && batchId) {
|
||||
try { window.notifications.fileCompleted(batchId, result.ok); } catch (_) {}
|
||||
try {
|
||||
window.notifications.fileCompleted(batchId, result.ok);
|
||||
} catch (_) {}
|
||||
}
|
||||
if (progressBar && uploadedCount % 10 === 0) {
|
||||
progressBar.style.width = ((uploadedCount / totalFiles) * 100) + '%';
|
||||
progressBar.style.width = (uploadedCount / totalFiles) * 100 + '%';
|
||||
}
|
||||
if (uploadedCount % 50 === 0 || uploadedCount === totalFiles) {
|
||||
console.log(`Progress: ${uploadedCount}/${totalFiles} (${successCount} ok)`);
|
||||
@@ -627,7 +657,9 @@ const fileOps = {
|
||||
this._finishUploadToast(successCount, totalFiles);
|
||||
|
||||
if (typeof window.refreshUserData === 'function') {
|
||||
try { await window.refreshUserData(); } catch (_) {}
|
||||
try {
|
||||
await window.refreshUserData();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -651,7 +683,7 @@ const fileOps = {
|
||||
async createFolder(name) {
|
||||
try {
|
||||
console.log('Creating folder with name:', name);
|
||||
|
||||
|
||||
// Send the actual request to the backend to create the folder
|
||||
const response = await fetch('/api/folders', {
|
||||
method: 'POST',
|
||||
@@ -670,11 +702,11 @@ const fileOps = {
|
||||
// Get the created folder from the backend
|
||||
const folder = await response.json();
|
||||
console.log('Folder created successfully:', folder);
|
||||
|
||||
|
||||
// Optimistic UI: add folder card directly from server response
|
||||
// — no reload needed since the backend already confirmed creation.
|
||||
window.ui.addFolderToView(folder);
|
||||
|
||||
|
||||
window.ui.showNotification('Folder created', `"${name}" created successfully`);
|
||||
} else {
|
||||
const errorData = await response.text();
|
||||
@@ -702,7 +734,7 @@ const fileOps = {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
folder_id: targetFolderId === "" ? null : targetFolderId
|
||||
folder_id: targetFolderId === '' ? null : targetFolderId
|
||||
})
|
||||
});
|
||||
|
||||
@@ -744,7 +776,7 @@ const fileOps = {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
parent_id: targetFolderId === "" ? null : targetFolderId
|
||||
parent_id: targetFolderId === '' ? null : targetFolderId
|
||||
})
|
||||
});
|
||||
|
||||
@@ -785,9 +817,9 @@ const fileOps = {
|
||||
* @returns {Promise<BatchResult>} - Success status
|
||||
*/
|
||||
async batchMove(fileIds, folderIds, targetFolderId) {
|
||||
|
||||
// TODO ensure not moving a folder into itself
|
||||
let success = 0, errors = 0;
|
||||
let success = 0,
|
||||
errors = 0;
|
||||
|
||||
try {
|
||||
// Batch move files in a single request
|
||||
@@ -795,7 +827,10 @@ const fileOps = {
|
||||
const res = await fetch('/api/batch/files/move', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ file_ids: fileIds, target_folder_id: targetFolderId })
|
||||
body: JSON.stringify({
|
||||
file_ids: fileIds,
|
||||
target_folder_id: targetFolderId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
success += data.stats?.successful || 0;
|
||||
@@ -807,14 +842,16 @@ const fileOps = {
|
||||
const res = await fetch('/api/batch/folders/move', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ folder_ids: folderIds, target_folder_id: targetFolderId })
|
||||
body: JSON.stringify({
|
||||
folder_ids: folderIds,
|
||||
target_folder_id: targetFolderId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
success += data.stats?.successful || 0;
|
||||
errors += data.stats?.failed || 0;
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
} catch (err) {
|
||||
console.error('Batch move error:', err);
|
||||
errors++;
|
||||
}
|
||||
@@ -841,7 +878,7 @@ const fileOps = {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
file_ids: [fileId],
|
||||
target_folder_id: targetFolderId === "" ? null : targetFolderId
|
||||
target_folder_id: targetFolderId === '' ? null : targetFolderId
|
||||
})
|
||||
});
|
||||
|
||||
@@ -890,17 +927,20 @@ const fileOps = {
|
||||
* @returns {Promise<boolean>} - Success status
|
||||
*/
|
||||
async batchCopy(fileIds, folderIds, targetFolderId) {
|
||||
|
||||
// FIXME ensure not moving a folder into itself
|
||||
|
||||
let success = 0, errors = 0;
|
||||
let success = 0,
|
||||
errors = 0;
|
||||
try {
|
||||
// Batch copy files
|
||||
if (fileIds.length > 0) {
|
||||
const res = await fetch('/api/batch/files/copy', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ file_ids: fileIds, target_folder_id: targetFolderId })
|
||||
body: JSON.stringify({
|
||||
file_ids: fileIds,
|
||||
target_folder_id: targetFolderId
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
success += data.stats?.successful || 0;
|
||||
@@ -1027,11 +1067,13 @@ const fileOps = {
|
||||
async deleteFile(fileId, fileName) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_file', { name: fileName }) : `Are you sure you want to move the file "${fileName}" to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_delete_file', { name: fileName })
|
||||
: `Are you sure you want to move the file "${fileName}" to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
|
||||
try {
|
||||
// Use the trash API endpoint
|
||||
const response = await fetch(`/api/trash/files/${fileId}`, {
|
||||
@@ -1049,7 +1091,7 @@ const fileOps = {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
|
||||
if (fallbackResponse.ok) {
|
||||
window.loadFiles();
|
||||
window.ui.showNotification('File deleted', `"${fileName}" deleted successfully`);
|
||||
@@ -1075,11 +1117,13 @@ const fileOps = {
|
||||
async deleteFolder(folderId, folderName) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_delete') : 'Move to trash',
|
||||
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_folder', { name: folderName }) : `Are you sure you want to move the folder "${folderName}" and all its contents to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_delete_folder', { name: folderName })
|
||||
: `Are you sure you want to move the folder "${folderName}" and all its contents to trash?`,
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
|
||||
try {
|
||||
// Use the trash API endpoint
|
||||
const response = await fetch(`/api/trash/folders/${folderId}`, {
|
||||
@@ -1102,7 +1146,7 @@ const fileOps = {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
|
||||
if (fallbackResponse.ok) {
|
||||
// If we're inside the folder we just deleted, go back up
|
||||
if (window.app.currentPath === folderId) {
|
||||
@@ -1123,7 +1167,7 @@ const fileOps = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Get trash items
|
||||
* @returns {Promise<Array>} - List of trash items
|
||||
@@ -1133,7 +1177,7 @@ const fileOps = {
|
||||
const response = await fetch('/api/trash', {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
} else {
|
||||
@@ -1145,7 +1189,7 @@ const fileOps = {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Restore an item from trash
|
||||
* @param {string} trashId - Trash item ID
|
||||
@@ -1161,7 +1205,7 @@ const fileOps = {
|
||||
},
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Item restored', 'Item restored successfully');
|
||||
return true;
|
||||
@@ -1175,7 +1219,7 @@ const fileOps = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Permanently delete a trash item
|
||||
* @param {string} trashId - Trash item ID
|
||||
@@ -1184,17 +1228,19 @@ const fileOps = {
|
||||
async deletePermanently(trashId) {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_permanent_delete') : 'Delete permanently',
|
||||
message: window.i18n ? window.i18n.t('dialogs.confirm_permanent_delete_msg') : 'Are you sure you want to permanently delete this item? This action cannot be undone.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete_permanently') : 'Delete permanently',
|
||||
message: window.i18n
|
||||
? window.i18n.t('dialogs.confirm_permanent_delete_msg')
|
||||
: 'Are you sure you want to permanently delete this item? This action cannot be undone.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.delete_permanently') : 'Delete permanently'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/trash/${trashId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Item deleted', 'Item permanently deleted');
|
||||
return true;
|
||||
@@ -1208,7 +1254,7 @@ const fileOps = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Empty the trash
|
||||
* @returns {Promise<boolean>} - Operation success
|
||||
@@ -1216,17 +1262,19 @@ const fileOps = {
|
||||
async emptyTrash() {
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: window.i18n ? window.i18n.t('dialogs.confirm_empty_trash') : 'Empty trash',
|
||||
message: window.i18n ? window.i18n.t('trash.empty_confirm') : 'Are you sure you want to empty the trash? This action will permanently delete all items.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.empty_trash') : 'Empty trash',
|
||||
message: window.i18n
|
||||
? window.i18n.t('trash.empty_confirm')
|
||||
: 'Are you sure you want to empty the trash? This action will permanently delete all items.',
|
||||
confirmText: window.i18n ? window.i18n.t('actions.empty_trash') : 'Empty trash'
|
||||
});
|
||||
if (!confirmed) return false;
|
||||
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/trash/empty', {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Trash emptied', 'The trash has been emptied successfully');
|
||||
return true;
|
||||
@@ -1240,7 +1288,7 @@ const fileOps = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Download a file
|
||||
* @param {string} fileId - File ID
|
||||
@@ -1269,7 +1317,7 @@ const fileOps = {
|
||||
window.ui.showNotification('Error', 'Error downloading the file');
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Download a folder as ZIP
|
||||
* @param {string} folderId - Folder ID
|
||||
@@ -1279,7 +1327,7 @@ const fileOps = {
|
||||
try {
|
||||
// Show notification to user
|
||||
window.ui.showNotification('Preparing download', 'Preparing the folder for download...');
|
||||
|
||||
|
||||
const response = await fetch(`/api/folders/${folderId}/download?format=zip`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
@@ -4,29 +4,29 @@
|
||||
*/
|
||||
|
||||
class InlineViewer {
|
||||
constructor() {
|
||||
this.setupViewer();
|
||||
this.currentFile = null;
|
||||
}
|
||||
|
||||
setupViewer() {
|
||||
// Create the viewer modal if it doesn't exist
|
||||
if (document.getElementById('inline-viewer-modal')) {
|
||||
return;
|
||||
constructor() {
|
||||
this.setupViewer();
|
||||
this.currentFile = null;
|
||||
}
|
||||
|
||||
// Verify document.body exists
|
||||
if (!document.body) {
|
||||
console.warn('Document body not available yet for inline viewer, will retry later');
|
||||
setTimeout(() => this.setupViewer(), 200);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create modal container
|
||||
const modal = document.createElement('div');
|
||||
modal.id = 'inline-viewer-modal';
|
||||
modal.className = 'inline-viewer-modal';
|
||||
modal.innerHTML = `
|
||||
|
||||
setupViewer() {
|
||||
// Create the viewer modal if it doesn't exist
|
||||
if (document.getElementById('inline-viewer-modal')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify document.body exists
|
||||
if (!document.body) {
|
||||
console.warn('Document body not available yet for inline viewer, will retry later');
|
||||
setTimeout(() => this.setupViewer(), 200);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create modal container
|
||||
const modal = document.createElement('div');
|
||||
modal.id = 'inline-viewer-modal';
|
||||
modal.className = 'inline-viewer-modal';
|
||||
modal.innerHTML = `
|
||||
<div class="inline-viewer-content">
|
||||
<div class="inline-viewer-header">
|
||||
<div class="inline-viewer-title">File Viewer</div>
|
||||
@@ -43,224 +43,222 @@ class InlineViewer {
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Add to document
|
||||
document.body.appendChild(modal);
|
||||
|
||||
// Add event listeners
|
||||
modal.querySelector('.inline-viewer-close').addEventListener('click', () => {
|
||||
this.closeViewer();
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-download').addEventListener('click', () => {
|
||||
if (this.currentFile) {
|
||||
this.downloadFile(this.currentFile);
|
||||
}
|
||||
});
|
||||
|
||||
// Add zoom controls for images
|
||||
modal.querySelector('.inline-viewer-zoom-in').addEventListener('click', () => {
|
||||
this.zoomImage(1.2);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-out').addEventListener('click', () => {
|
||||
this.zoomImage(0.8);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-reset').addEventListener('click', () => {
|
||||
this.resetZoom();
|
||||
});
|
||||
|
||||
// Close on ESC key
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && modal.classList.contains('active')) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Click outside to close
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Inline viewer initialized');
|
||||
}
|
||||
|
||||
async openFile(file) {
|
||||
console.log('Opening file:', file);
|
||||
|
||||
// WOPI editor intercept: open Office documents in the WOPI editor
|
||||
// But NOT image files - those should be previewed in the inline viewer
|
||||
// Detect images by mime type OR extension (uploads via WebDAV may lack correct mime)
|
||||
const ext = (file.name || '').split('.').pop().toLowerCase();
|
||||
const imageExts = ['jpg','jpeg','png','gif','svg','webp','bmp','ico','heic','heif','avif','tiff'];
|
||||
const isImage = (file.mime_type && file.mime_type.startsWith('image/')) || imageExts.includes(ext);
|
||||
if (!isImage && window.wopiEditor && await window.wopiEditor.canEdit(file.name)) {
|
||||
try {
|
||||
window.wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn('WOPI editor failed, falling back to inline viewer:', e);
|
||||
// Add to document
|
||||
document.body.appendChild(modal);
|
||||
|
||||
// Add event listeners
|
||||
modal.querySelector('.inline-viewer-close').addEventListener('click', () => {
|
||||
this.closeViewer();
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-download').addEventListener('click', () => {
|
||||
if (this.currentFile) {
|
||||
this.downloadFile(this.currentFile);
|
||||
}
|
||||
});
|
||||
|
||||
// Add zoom controls for images
|
||||
modal.querySelector('.inline-viewer-zoom-in').addEventListener('click', () => {
|
||||
this.zoomImage(1.2);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-out').addEventListener('click', () => {
|
||||
this.zoomImage(0.8);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-reset').addEventListener('click', () => {
|
||||
this.resetZoom();
|
||||
});
|
||||
|
||||
// Close on ESC key
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && modal.classList.contains('active')) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Click outside to close
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Inline viewer initialized');
|
||||
}
|
||||
|
||||
async openFile(file) {
|
||||
console.log('Opening file:', file);
|
||||
|
||||
// WOPI editor intercept: open Office documents in the WOPI editor
|
||||
// But NOT image files - those should be previewed in the inline viewer
|
||||
// Detect images by mime type OR extension (uploads via WebDAV may lack correct mime)
|
||||
const ext = (file.name || '').split('.').pop().toLowerCase();
|
||||
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp', 'ico', 'heic', 'heif', 'avif', 'tiff'];
|
||||
const isImage = (file.mime_type && file.mime_type.startsWith('image/')) || imageExts.includes(ext);
|
||||
if (!isImage && window.wopiEditor && (await window.wopiEditor.canEdit(file.name))) {
|
||||
try {
|
||||
window.wopiEditor.openInModal(file.id, file.name, 'edit');
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn('WOPI editor failed, falling back to inline viewer:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.currentFile = file;
|
||||
this.currentFile = file;
|
||||
|
||||
// Get container
|
||||
const modal = document.getElementById('inline-viewer-modal');
|
||||
const container = modal.querySelector('.inline-viewer-container');
|
||||
const title = modal.querySelector('.inline-viewer-title');
|
||||
// Get container
|
||||
const modal = document.getElementById('inline-viewer-modal');
|
||||
const container = modal.querySelector('.inline-viewer-container');
|
||||
const title = modal.querySelector('.inline-viewer-title');
|
||||
|
||||
// Clear container
|
||||
container.innerHTML = '';
|
||||
// Clear container
|
||||
container.innerHTML = '';
|
||||
|
||||
// Set title
|
||||
title.textContent = file.name;
|
||||
// Set title
|
||||
title.textContent = file.name;
|
||||
|
||||
// Set controls visibility
|
||||
const controls = modal.querySelector('.inline-viewer-controls');
|
||||
// Set controls visibility
|
||||
const controls = modal.querySelector('.inline-viewer-controls');
|
||||
|
||||
// Show viewer based on file type
|
||||
if (isImage) {
|
||||
// Show zoom controls
|
||||
controls.style.display = 'flex';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create image viewer using a blob URL
|
||||
this.createBlobUrlViewer(file, 'image', container, loader);
|
||||
}
|
||||
else if (file.mime_type && file.mime_type === 'application/pdf') {
|
||||
// Hide zoom controls for PDFs
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create PDF viewer using object tag with blob URL
|
||||
this.createBlobUrlViewer(file, 'pdf', container, loader);
|
||||
}
|
||||
else if (file.mime_type && this.isTextViewable(file.mime_type)) {
|
||||
// Hide zoom controls for text files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create text viewer using authenticated fetch
|
||||
this.createTextViewer(file, container, loader);
|
||||
}
|
||||
else if (file.mime_type && file.mime_type.startsWith('audio/')) {
|
||||
// Hide zoom controls for audio
|
||||
controls.style.display = 'none';
|
||||
// Show viewer based on file type
|
||||
if (isImage) {
|
||||
// Show zoom controls
|
||||
controls.style.display = 'flex';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create audio player
|
||||
this.createMediaViewer(file, 'audio', container, loader);
|
||||
}
|
||||
else if (file.mime_type && file.mime_type.startsWith('video/')) {
|
||||
// Hide zoom controls for video
|
||||
controls.style.display = 'none';
|
||||
// Create image viewer using a blob URL
|
||||
this.createBlobUrlViewer(file, 'image', container, loader);
|
||||
} else if (file.mime_type && file.mime_type === 'application/pdf') {
|
||||
// Hide zoom controls for PDFs
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create video player
|
||||
this.createMediaViewer(file, 'video', container, loader);
|
||||
}
|
||||
else {
|
||||
// Hide zoom controls for unsupported files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show unsupported file message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
// Create PDF viewer using object tag with blob URL
|
||||
this.createBlobUrlViewer(file, 'pdf', container, loader);
|
||||
} else if (file.mime_type && this.isTextViewable(file.mime_type)) {
|
||||
// Hide zoom controls for text files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create text viewer using authenticated fetch
|
||||
this.createTextViewer(file, container, loader);
|
||||
} else if (file.mime_type && file.mime_type.startsWith('audio/')) {
|
||||
// Hide zoom controls for audio
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create audio player
|
||||
this.createMediaViewer(file, 'audio', container, loader);
|
||||
} else if (file.mime_type && file.mime_type.startsWith('video/')) {
|
||||
// Hide zoom controls for video
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create video player
|
||||
this.createMediaViewer(file, 'video', container, loader);
|
||||
} else {
|
||||
// Hide zoom controls for unsupported files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show unsupported file message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-file"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>This file type cannot be previewed.</p>
|
||||
<p>Click "Download" to get the file.</p>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(message);
|
||||
}
|
||||
|
||||
// Show modal
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
// Check if a MIME type is text-viewable — delegates to window.isTextViewable
|
||||
isTextViewable(mimeType) {
|
||||
return window.isTextViewable ? window.isTextViewable(mimeType) : false;
|
||||
}
|
||||
|
||||
// Creates a text viewer using authenticated fetch
|
||||
async createTextViewer(file, container, loader) {
|
||||
try {
|
||||
console.log('Creating text viewer for:', file.name);
|
||||
|
||||
const response = await fetch(`/api/files/${file.id}?inline=true`, { credentials: 'same-origin' });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching file: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
// Create text viewer element
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'inline-viewer-text-content';
|
||||
pre.textContent = text;
|
||||
container.appendChild(pre);
|
||||
|
||||
console.log('Text viewer created successfully');
|
||||
} catch (error) {
|
||||
console.error('Error creating text viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates a viewer using a Blob URL to avoid content-disposition header
|
||||
async createBlobUrlViewer(file, type, container, loader) {
|
||||
try {
|
||||
console.log('Creating blob URL viewer for:', file.name, 'type:', type);
|
||||
container.appendChild(message);
|
||||
}
|
||||
|
||||
// Update loader to show progress bar for large files
|
||||
let progressBar = null;
|
||||
let progressText = null;
|
||||
if (loader && file.size > 10 * 1024 * 1024) { // Show progress for files > 10MB
|
||||
loader.innerHTML = `
|
||||
// Show modal
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
// Check if a MIME type is text-viewable — delegates to window.isTextViewable
|
||||
isTextViewable(mimeType) {
|
||||
return window.isTextViewable ? window.isTextViewable(mimeType) : false;
|
||||
}
|
||||
|
||||
// Creates a text viewer using authenticated fetch
|
||||
async createTextViewer(file, container, loader) {
|
||||
try {
|
||||
console.log('Creating text viewer for:', file.name);
|
||||
|
||||
const response = await fetch(`/api/files/${file.id}?inline=true`, {
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching file: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
// Create text viewer element
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'inline-viewer-text-content';
|
||||
pre.textContent = text;
|
||||
container.appendChild(pre);
|
||||
|
||||
console.log('Text viewer created successfully');
|
||||
} catch (error) {
|
||||
console.error('Error creating text viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates a viewer using a Blob URL to avoid content-disposition header
|
||||
async createBlobUrlViewer(file, type, container, loader) {
|
||||
try {
|
||||
console.log('Creating blob URL viewer for:', file.name, 'type:', type);
|
||||
|
||||
// Update loader to show progress bar for large files
|
||||
let progressBar = null;
|
||||
let progressText = null;
|
||||
if (loader && file.size > 10 * 1024 * 1024) {
|
||||
// Show progress for files > 10MB
|
||||
loader.innerHTML = `
|
||||
<div class="inline-viewer-progress">
|
||||
<i class="fas fa-spinner fa-spin"></i>
|
||||
<div class="inline-viewer-progress-bar">
|
||||
@@ -269,226 +267,225 @@ class InlineViewer {
|
||||
<div class="inline-viewer-progress-text">0%</div>
|
||||
</div>
|
||||
`;
|
||||
progressBar = loader.querySelector('.inline-viewer-progress-fill');
|
||||
progressText = loader.querySelector('.inline-viewer-progress-text');
|
||||
}
|
||||
progressBar = loader.querySelector('.inline-viewer-progress-fill');
|
||||
progressText = loader.querySelector('.inline-viewer-progress-text');
|
||||
}
|
||||
|
||||
// Use XMLHttpRequest instead of fetch to get better control over the response
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', `/api/files/${file.id}?inline=true`, true);
|
||||
xhr.responseType = 'blob';
|
||||
xhr.withCredentials = true;
|
||||
// Use XMLHttpRequest instead of fetch to get better control over the response
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', `/api/files/${file.id}?inline=true`, true);
|
||||
xhr.responseType = 'blob';
|
||||
xhr.withCredentials = true;
|
||||
|
||||
// Track download progress - use double precision for large file support (>2GB)
|
||||
xhr.onprogress = (e) => {
|
||||
if (e.lengthComputable && progressBar && progressText) {
|
||||
// Use direct division to avoid 32-bit overflow issues
|
||||
// e.loaded and e.total are JavaScript numbers (64-bit float)
|
||||
const progress = e.loaded / e.total;
|
||||
const pct = Math.round(progress * 100);
|
||||
progressBar.style.width = pct + '%';
|
||||
progressText.textContent = pct + '%';
|
||||
// Track download progress - use double precision for large file support (>2GB)
|
||||
xhr.onprogress = (e) => {
|
||||
if (e.lengthComputable && progressBar && progressText) {
|
||||
// Use direct division to avoid 32-bit overflow issues
|
||||
// e.loaded and e.total are JavaScript numbers (64-bit float)
|
||||
const progress = e.loaded / e.total;
|
||||
const pct = Math.round(progress * 100);
|
||||
progressBar.style.width = pct + '%';
|
||||
progressText.textContent = pct + '%';
|
||||
}
|
||||
};
|
||||
|
||||
// Create a promise to handle the XHR
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
xhr.onload = function () {
|
||||
if (this.status >= 200 && this.status < 300) {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
reject(new Error(`Error fetching file: ${this.status} ${this.statusText}`));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function () {
|
||||
reject(new Error('Network error'));
|
||||
};
|
||||
|
||||
xhr.send();
|
||||
});
|
||||
|
||||
// Create blob URL from response
|
||||
const blob = response;
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
console.log('Created blob URL:', blobUrl.substring(0, 30) + '...');
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
console.log('Creating image viewer');
|
||||
// Create image element
|
||||
const img = document.createElement('img');
|
||||
img.className = 'inline-viewer-image';
|
||||
img.src = blobUrl;
|
||||
img.alt = file.name;
|
||||
container.appendChild(img);
|
||||
|
||||
// Add loading indicator until image loads
|
||||
img.style.opacity = 0;
|
||||
img.onload = () => {
|
||||
console.log('Image loaded successfully');
|
||||
img.style.opacity = 1;
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
console.error('Failed to load image');
|
||||
container.removeChild(img);
|
||||
this.showErrorMessage(container);
|
||||
};
|
||||
} else if (type === 'pdf') {
|
||||
console.log('Creating PDF viewer');
|
||||
|
||||
// Create iframe for PDF (more reliable than object tag)
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.className = 'inline-viewer-pdf';
|
||||
iframe.src = blobUrl;
|
||||
iframe.setAttribute('allowfullscreen', 'true');
|
||||
container.appendChild(iframe);
|
||||
|
||||
// Monitor iframe for loading issues
|
||||
setTimeout(() => {
|
||||
if (!iframe.contentDocument || iframe.contentDocument.body.innerHTML === '') {
|
||||
console.warn('PDF viewer might be having issues, adding fallback');
|
||||
|
||||
// Add fallback embed
|
||||
const embed = document.createElement('embed');
|
||||
embed.className = 'inline-viewer-pdf-fallback';
|
||||
embed.type = 'application/pdf';
|
||||
embed.src = blobUrl;
|
||||
container.appendChild(embed);
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// Store blob URL for cleaning up later
|
||||
this.currentBlobUrl = blobUrl;
|
||||
} catch (error) {
|
||||
console.error('Error creating blob URL viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
};
|
||||
|
||||
// Create a promise to handle the XHR
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
xhr.onload = function() {
|
||||
if (this.status >= 200 && this.status < 300) {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
reject(new Error(`Error fetching file: ${this.status} ${this.statusText}`));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
reject(new Error('Network error'));
|
||||
};
|
||||
|
||||
xhr.send();
|
||||
});
|
||||
|
||||
// Create blob URL from response
|
||||
const blob = response;
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
console.log('Created blob URL:', blobUrl.substring(0, 30) + '...');
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
console.log('Creating image viewer');
|
||||
// Create image element
|
||||
const img = document.createElement('img');
|
||||
img.className = 'inline-viewer-image';
|
||||
img.src = blobUrl;
|
||||
img.alt = file.name;
|
||||
container.appendChild(img);
|
||||
|
||||
// Add loading indicator until image loads
|
||||
img.style.opacity = 0;
|
||||
img.onload = () => {
|
||||
console.log('Image loaded successfully');
|
||||
img.style.opacity = 1;
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
console.error('Failed to load image');
|
||||
container.removeChild(img);
|
||||
this.showErrorMessage(container);
|
||||
};
|
||||
}
|
||||
else if (type === 'pdf') {
|
||||
console.log('Creating PDF viewer');
|
||||
|
||||
// Create iframe for PDF (more reliable than object tag)
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.className = 'inline-viewer-pdf';
|
||||
iframe.src = blobUrl;
|
||||
iframe.setAttribute('allowfullscreen', 'true');
|
||||
container.appendChild(iframe);
|
||||
|
||||
// Monitor iframe for loading issues
|
||||
setTimeout(() => {
|
||||
if (!iframe.contentDocument ||
|
||||
iframe.contentDocument.body.innerHTML === '') {
|
||||
console.warn('PDF viewer might be having issues, adding fallback');
|
||||
|
||||
// Add fallback embed
|
||||
const embed = document.createElement('embed');
|
||||
embed.className = 'inline-viewer-pdf-fallback';
|
||||
embed.type = 'application/pdf';
|
||||
embed.src = blobUrl;
|
||||
container.appendChild(embed);
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// Store blob URL for cleaning up later
|
||||
this.currentBlobUrl = blobUrl;
|
||||
}
|
||||
catch (error) {
|
||||
console.error('Error creating blob URL viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates an audio or video player using blob URL (authenticated fetch)
|
||||
async createMediaViewer(file, mediaType, container, loader) {
|
||||
try {
|
||||
console.log(`Creating ${mediaType} player for:`, file.name);
|
||||
|
||||
// Fetch file (cookie auto-sent)
|
||||
const response = await fetch(`/api/files/${file.id}?inline=true`, { credentials: 'same-origin' });
|
||||
// Creates an audio or video player using blob URL (authenticated fetch)
|
||||
async createMediaViewer(file, mediaType, container, loader) {
|
||||
try {
|
||||
console.log(`Creating ${mediaType} player for:`, file.name);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching file: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
// Fetch file (cookie auto-sent)
|
||||
const response = await fetch(`/api/files/${file.id}?inline=true`, {
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
|
||||
const blob = await response.blob();
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching file: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
if (mediaType === 'audio') {
|
||||
// Wrapper with icon + player
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'inline-viewer-audio-wrapper';
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
const icon = document.createElement('div');
|
||||
icon.className = 'inline-viewer-audio-icon';
|
||||
icon.innerHTML = '<i class="fas fa-music"></i>';
|
||||
wrapper.appendChild(icon);
|
||||
if (mediaType === 'audio') {
|
||||
// Wrapper with icon + player
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'inline-viewer-audio-wrapper';
|
||||
|
||||
const nameEl = document.createElement('div');
|
||||
nameEl.className = 'inline-viewer-audio-name';
|
||||
nameEl.textContent = file.name;
|
||||
wrapper.appendChild(nameEl);
|
||||
const icon = document.createElement('div');
|
||||
icon.className = 'inline-viewer-audio-icon';
|
||||
icon.innerHTML = '<i class="fas fa-music"></i>';
|
||||
wrapper.appendChild(icon);
|
||||
|
||||
const audio = document.createElement('audio');
|
||||
audio.className = 'inline-viewer-audio';
|
||||
audio.controls = true;
|
||||
audio.preload = 'metadata';
|
||||
audio.src = blobUrl;
|
||||
wrapper.appendChild(audio);
|
||||
const nameEl = document.createElement('div');
|
||||
nameEl.className = 'inline-viewer-audio-name';
|
||||
nameEl.textContent = file.name;
|
||||
wrapper.appendChild(nameEl);
|
||||
|
||||
// Fallback message for unsupported codecs
|
||||
audio.addEventListener('error', () => {
|
||||
console.warn('Audio playback error — codec may not be supported');
|
||||
wrapper.innerHTML = '';
|
||||
const msg = document.createElement('div');
|
||||
msg.className = 'inline-viewer-message';
|
||||
msg.innerHTML = `
|
||||
const audio = document.createElement('audio');
|
||||
audio.className = 'inline-viewer-audio';
|
||||
audio.controls = true;
|
||||
audio.preload = 'metadata';
|
||||
audio.src = blobUrl;
|
||||
wrapper.appendChild(audio);
|
||||
|
||||
// Fallback message for unsupported codecs
|
||||
audio.addEventListener('error', () => {
|
||||
console.warn('Audio playback error — codec may not be supported');
|
||||
wrapper.innerHTML = '';
|
||||
const msg = document.createElement('div');
|
||||
msg.className = 'inline-viewer-message';
|
||||
msg.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-exclamation-circle"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>Your browser cannot play this audio format.</p>
|
||||
<p>Click "Download" to save the file.</p>
|
||||
</div>
|
||||
`;
|
||||
wrapper.appendChild(msg);
|
||||
});
|
||||
wrapper.appendChild(msg);
|
||||
});
|
||||
|
||||
container.appendChild(wrapper);
|
||||
} else {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'inline-viewer-video';
|
||||
video.controls = true;
|
||||
video.preload = 'metadata';
|
||||
video.src = blobUrl;
|
||||
video.setAttribute('playsinline', 'true');
|
||||
container.appendChild(wrapper);
|
||||
} else {
|
||||
const video = document.createElement('video');
|
||||
video.className = 'inline-viewer-video';
|
||||
video.controls = true;
|
||||
video.preload = 'metadata';
|
||||
video.src = blobUrl;
|
||||
video.setAttribute('playsinline', 'true');
|
||||
|
||||
// Fallback message for unsupported codecs
|
||||
video.addEventListener('error', () => {
|
||||
console.warn('Video playback error — codec may not be supported');
|
||||
if (video.parentNode) {
|
||||
video.parentNode.removeChild(video);
|
||||
}
|
||||
const msg = document.createElement('div');
|
||||
msg.className = 'inline-viewer-message';
|
||||
msg.innerHTML = `
|
||||
// Fallback message for unsupported codecs
|
||||
video.addEventListener('error', () => {
|
||||
console.warn('Video playback error — codec may not be supported');
|
||||
if (video.parentNode) {
|
||||
video.parentNode.removeChild(video);
|
||||
}
|
||||
const msg = document.createElement('div');
|
||||
msg.className = 'inline-viewer-message';
|
||||
msg.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-exclamation-circle"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>Your browser cannot play this video format.</p>
|
||||
<p>Click "Download" to save the file.</p>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(msg);
|
||||
});
|
||||
container.appendChild(msg);
|
||||
});
|
||||
|
||||
container.appendChild(video);
|
||||
}
|
||||
container.appendChild(video);
|
||||
}
|
||||
|
||||
// Store blob URL for cleanup on close
|
||||
this.currentBlobUrl = blobUrl;
|
||||
} catch (error) {
|
||||
console.error(`Error creating ${mediaType} viewer:`, error);
|
||||
// Store blob URL for cleanup on close
|
||||
this.currentBlobUrl = blobUrl;
|
||||
} catch (error) {
|
||||
console.error(`Error creating ${mediaType} viewer:`, error);
|
||||
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to show error message
|
||||
showErrorMessage(container) {
|
||||
// Show error message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
// Helper to show error message
|
||||
showErrorMessage(container) {
|
||||
// Show error message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-exclamation-triangle"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>Error loading the file.</p>
|
||||
@@ -578,19 +575,19 @@ class InlineViewer {
|
||||
|
||||
// Initialize viewer when document is ready
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Check if it's already initialized
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Initializing inline viewer on DOMContentLoaded');
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}
|
||||
// Check if it's already initialized
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Initializing inline viewer on DOMContentLoaded');
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Fallback initialization for cases where DOMContentLoaded already fired
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Fallback initialization for inline viewer');
|
||||
setTimeout(() => {
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Fallback initialization for inline viewer');
|
||||
setTimeout(() => {
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -56,7 +56,13 @@ const search = {
|
||||
} catch (error) {
|
||||
console.error('Error performing search:', error);
|
||||
window.ui.showNotification('Error', 'Error performing search');
|
||||
return { files: [], folders: [], total_count: 0, query_time_ms: 0, sort_by: 'relevance' };
|
||||
return {
|
||||
files: [],
|
||||
folders: [],
|
||||
total_count: 0,
|
||||
query_time_ms: 0,
|
||||
sort_by: 'relevance'
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -107,10 +113,8 @@ const search = {
|
||||
const filesList = document.getElementById('files-list');
|
||||
|
||||
// Search results header with query time and sort controls
|
||||
const totalCount = results.total_count || (results.files.length + results.folders.length);
|
||||
const queryTimeText = results.query_time_ms !== undefined
|
||||
? ` <span class="search-time">(${results.query_time_ms}ms)</span>`
|
||||
: '';
|
||||
const totalCount = results.total_count || results.files.length + results.folders.length;
|
||||
const queryTimeText = results.query_time_ms !== undefined ? ` <span class="search-time">(${results.query_time_ms}ms)</span>` : '';
|
||||
|
||||
const searchHeader = document.createElement('div');
|
||||
searchHeader.className = 'search-results-header';
|
||||
@@ -169,12 +173,12 @@ const search = {
|
||||
}
|
||||
|
||||
// Render folders (server-provided enriched data)
|
||||
results.folders.forEach(folder => {
|
||||
results.folders.forEach((folder) => {
|
||||
window.ui.addFolderToView(folder);
|
||||
});
|
||||
|
||||
// Render files (server-provided enriched data)
|
||||
results.files.forEach(file => {
|
||||
results.files.forEach((file) => {
|
||||
window.ui.addFileToView(file);
|
||||
});
|
||||
},
|
||||
|
||||
@@ -39,8 +39,7 @@ class WopiEditor {
|
||||
action = action || 'edit';
|
||||
try {
|
||||
var data = await this._getEditorUrlWithFallback(fileId, fileName, action);
|
||||
var hostUrl = '/wopi/edit/' + encodeURIComponent(fileId)
|
||||
+ '?access_token=' + encodeURIComponent(data.access_token);
|
||||
var hostUrl = '/wopi/edit/' + encodeURIComponent(fileId) + '?access_token=' + encodeURIComponent(data.access_token);
|
||||
window.open(hostUrl, '_blank');
|
||||
} catch (error) {
|
||||
console.error('Failed to open WOPI editor in tab:', error);
|
||||
@@ -54,10 +53,9 @@ class WopiEditor {
|
||||
* Fetch editor URL and WOPI token from the backend.
|
||||
*/
|
||||
async _getEditorUrl(fileId, action) {
|
||||
var response = await fetch(
|
||||
'/api/wopi/editor-url?file_id=' + encodeURIComponent(fileId) + '&action=' + encodeURIComponent(action),
|
||||
{ credentials: 'same-origin' }
|
||||
);
|
||||
var response = await fetch('/api/wopi/editor-url?file_id=' + encodeURIComponent(fileId) + '&action=' + encodeURIComponent(action), {
|
||||
credentials: 'same-origin'
|
||||
});
|
||||
if (!response.ok) {
|
||||
var text = await response.text();
|
||||
throw new Error('Editor URL request failed: ' + response.status + ' ' + text);
|
||||
@@ -101,7 +99,8 @@ class WopiEditor {
|
||||
modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;background:#fff;';
|
||||
|
||||
var header = document.createElement('div');
|
||||
header.style.cssText = 'height:40px;background:#333;color:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 16px;font-family:sans-serif;font-size:14px;';
|
||||
header.style.cssText =
|
||||
'height:40px;background:#333;color:#fff;display:flex;align-items:center;justify-content:space-between;padding:0 16px;font-family:sans-serif;font-size:14px;';
|
||||
|
||||
var title = document.createElement('span');
|
||||
title.textContent = fileName;
|
||||
@@ -138,7 +137,8 @@ class WopiEditor {
|
||||
// Loading spinner (removed once the editor signals ready)
|
||||
var spinner = document.createElement('div');
|
||||
spinner.id = 'wopi-loading-spinner';
|
||||
spinner.style.cssText = 'position:absolute;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;background:#f5f5f5;z-index:1;';
|
||||
spinner.style.cssText =
|
||||
'position:absolute;top:0;left:0;right:0;bottom:0;display:flex;align-items:center;justify-content:center;background:#f5f5f5;z-index:1;';
|
||||
spinner.innerHTML = '<i class="fas fa-spinner fa-spin empty-state-icon spinner"></i>';
|
||||
frameHolder.appendChild(spinner);
|
||||
|
||||
@@ -149,8 +149,7 @@ class WopiEditor {
|
||||
iframe.setAttribute('allowfullscreen', 'true');
|
||||
// Fix 9: allow clipboard access for copy/paste inside the editor
|
||||
iframe.setAttribute('allow', 'clipboard-read; clipboard-write');
|
||||
iframe.setAttribute('sandbox',
|
||||
'allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox');
|
||||
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-top-navigation allow-popups-to-escape-sandbox');
|
||||
frameHolder.appendChild(iframe);
|
||||
|
||||
modal.appendChild(header);
|
||||
@@ -159,13 +158,13 @@ class WopiEditor {
|
||||
document.body.appendChild(modal);
|
||||
|
||||
// ESC key handler
|
||||
this._escHandler = function(e) {
|
||||
this._escHandler = function (e) {
|
||||
if (e.key === 'Escape') this.closeEditor();
|
||||
}.bind(this);
|
||||
document.addEventListener('keydown', this._escHandler);
|
||||
|
||||
// Fix 7: Listen for postMessage from the editor iframe
|
||||
this._messageHandler = function(e) {
|
||||
this._messageHandler = function (e) {
|
||||
var data;
|
||||
try {
|
||||
data = JSON.parse(e.data);
|
||||
@@ -238,11 +237,7 @@ class WopiEditor {
|
||||
// Ignore — fall through to hardcoded list
|
||||
}
|
||||
// Fallback hardcoded list
|
||||
this._supportedExtensions = [
|
||||
'docx', 'doc', 'odt', 'rtf', 'txt',
|
||||
'xlsx', 'xls', 'ods', 'csv',
|
||||
'pptx', 'ppt', 'odp',
|
||||
];
|
||||
this._supportedExtensions = ['docx', 'doc', 'odt', 'rtf', 'txt', 'xlsx', 'xls', 'ods', 'csv', 'pptx', 'ppt', 'odp'];
|
||||
return this._supportedExtensions;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ const favorites = {
|
||||
window.ui.updateBreadcrumb('');
|
||||
|
||||
if (this._cache.size === 0) {
|
||||
window.ui.showError( `
|
||||
window.ui.showError(`
|
||||
<i class="fas fa-star empty-state-icon"></i>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_state') : 'No favorite items'}</p>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_hint') : 'To mark as favorite, right-click on any file or folder'}</p>
|
||||
|
||||
@@ -202,9 +202,7 @@ const photosView = {
|
||||
for (const file of files) tilesHtml += this._renderTile(file);
|
||||
|
||||
// Does this date-group already exist in the DOM?
|
||||
const existingHeader = this._container.querySelector(
|
||||
`.photos-day-header[data-group="${CSS.escape(label)}"]`
|
||||
);
|
||||
const existingHeader = this._container.querySelector(`.photos-day-header[data-group="${CSS.escape(label)}"]`);
|
||||
|
||||
if (existingHeader) {
|
||||
// Append tiles to existing grid and update count badge
|
||||
@@ -232,8 +230,7 @@ const photosView = {
|
||||
_renderTile(file) {
|
||||
const isVideo = file.mime_type && file.mime_type.startsWith('video/');
|
||||
const selected = this.selected.has(file.id) ? ' selected' : '';
|
||||
const cachedThumb = isVideo && this._videoThumbCache.has(file.id)
|
||||
? this._videoThumbCache.get(file.id) : null;
|
||||
const cachedThumb = isVideo && this._videoThumbCache.has(file.id) ? this._videoThumbCache.get(file.id) : null;
|
||||
const thumbUrl = cachedThumb || `/api/files/${file.id}/thumbnail/preview`;
|
||||
let h = `<div class="photo-tile${selected}" data-id="${this._escAttr(file.id)}" data-mime="${this._escAttr(file.mime_type)}">`;
|
||||
h += `<div class="photo-check"><i class="fas fa-check"></i></div>`;
|
||||
@@ -248,9 +245,12 @@ const photosView = {
|
||||
this._destroyObserver();
|
||||
const sentinel = this._container?.querySelector('.photos-sentinel');
|
||||
if (sentinel && !this.exhausted) {
|
||||
this._observer = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting) this._loadPage();
|
||||
}, { rootMargin: '400px' });
|
||||
this._observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0].isIntersecting) this._loadPage();
|
||||
},
|
||||
{ rootMargin: '400px' }
|
||||
);
|
||||
this._observer.observe(sentinel);
|
||||
}
|
||||
},
|
||||
@@ -266,9 +266,7 @@ const photosView = {
|
||||
* for items[startIndex..] — avoids re-scanning the entire DOM. */
|
||||
_setupVideoThumbnails(startIndex = 0) {
|
||||
const tiles = this._container.querySelectorAll('.photo-tile[data-mime^="video/"]');
|
||||
const newIds = startIndex > 0
|
||||
? new Set(this.items.slice(startIndex).map(f => f.id))
|
||||
: null;
|
||||
const newIds = startIndex > 0 ? new Set(this.items.slice(startIndex).map((f) => f.id)) : null;
|
||||
|
||||
for (const tile of tiles) {
|
||||
const fileId = tile.dataset.id;
|
||||
@@ -278,9 +276,13 @@ const photosView = {
|
||||
const img = tile.querySelector('img');
|
||||
if (!img) continue;
|
||||
|
||||
img.addEventListener('error', () => {
|
||||
this._enqueueVideoThumbnail(tile, img);
|
||||
}, { once: true });
|
||||
img.addEventListener(
|
||||
'error',
|
||||
() => {
|
||||
this._enqueueVideoThumbnail(tile, img);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -315,78 +317,96 @@ const photosView = {
|
||||
// Auth is handled via HttpOnly cookie — direct URL works
|
||||
video.src = `/api/files/${fileId}`;
|
||||
|
||||
video.addEventListener('loadeddata', () => {
|
||||
// Seek to 25 % of duration, clamped between 0.5 s and 5 s
|
||||
video.currentTime = Math.min(5, Math.max(0.5, video.duration * 0.25));
|
||||
}, { once: true });
|
||||
video.addEventListener(
|
||||
'loadeddata',
|
||||
() => {
|
||||
// Seek to 25 % of duration, clamped between 0.5 s and 5 s
|
||||
video.currentTime = Math.min(5, Math.max(0.5, video.duration * 0.25));
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
||||
video.addEventListener('seeked', () => {
|
||||
// Pre-scale to thumbnail size in the browser — saves ~22× RAM,
|
||||
// ~15× bandwidth, and lets the server skip resize entirely.
|
||||
const MAX_THUMB = 400; // must match ThumbnailSize::Preview
|
||||
const scale = Math.min(MAX_THUMB / video.videoWidth,
|
||||
MAX_THUMB / video.videoHeight, 1);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.round(video.videoWidth * scale);
|
||||
canvas.height = Math.round(video.videoHeight * scale);
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
video.addEventListener(
|
||||
'seeked',
|
||||
() => {
|
||||
// Pre-scale to thumbnail size in the browser — saves ~22× RAM,
|
||||
// ~15× bandwidth, and lets the server skip resize entirely.
|
||||
const MAX_THUMB = 400; // must match ThumbnailSize::Preview
|
||||
const scale = Math.min(MAX_THUMB / video.videoWidth, MAX_THUMB / video.videoHeight, 1);
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.round(video.videoWidth * scale);
|
||||
canvas.height = Math.round(video.videoHeight * scale);
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
|
||||
// JPEG: explicit quality control, universally supported,
|
||||
// and server stores as-is when dimensions fit (zero re-encode).
|
||||
const mimeType = 'image/jpeg';
|
||||
// JPEG: explicit quality control, universally supported,
|
||||
// and server stores as-is when dimensions fit (zero re-encode).
|
||||
const mimeType = 'image/jpeg';
|
||||
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) {
|
||||
this._drainDecodeQueue();
|
||||
return;
|
||||
}
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (!blob) {
|
||||
this._drainDecodeQueue();
|
||||
return;
|
||||
}
|
||||
|
||||
// Show immediately in the tile
|
||||
const url = URL.createObjectURL(blob);
|
||||
img.src = url;
|
||||
// Cache locally so re-renders are instant
|
||||
this._videoThumbCache.set(fileId, url);
|
||||
// Show immediately in the tile
|
||||
const url = URL.createObjectURL(blob);
|
||||
img.src = url;
|
||||
// Cache locally so re-renders are instant
|
||||
this._videoThumbCache.set(fileId, url);
|
||||
|
||||
// Upload to server for permanent caching
|
||||
const token = localStorage.getItem('token')
|
||||
|| sessionStorage.getItem('token');
|
||||
const headers = { 'Content-Type': blob.type, ...getCsrfHeaders() };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
// Upload to server for permanent caching
|
||||
const token = localStorage.getItem('token') || sessionStorage.getItem('token');
|
||||
const headers = { 'Content-Type': blob.type, ...getCsrfHeaders() };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
fetch(`/api/files/${fileId}/thumbnail/preview`, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
body: blob,
|
||||
}).then((resp) => {
|
||||
if (resp.ok) {
|
||||
// Switch from blob URL to server URL so the blob
|
||||
// can be garbage-collected and future loads use
|
||||
// the permanently cached JPEG from the server.
|
||||
const serverUrl = `/api/files/${fileId}/thumbnail/preview?v=1`;
|
||||
this._videoThumbCache.set(fileId, serverUrl);
|
||||
}
|
||||
}).catch(() => { /* best-effort */ });
|
||||
fetch(`/api/files/${fileId}/thumbnail/preview`, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
body: blob
|
||||
})
|
||||
.then((resp) => {
|
||||
if (resp.ok) {
|
||||
// Switch from blob URL to server URL so the blob
|
||||
// can be garbage-collected and future loads use
|
||||
// the permanently cached JPEG from the server.
|
||||
const serverUrl = `/api/files/${fileId}/thumbnail/preview?v=1`;
|
||||
this._videoThumbCache.set(fileId, serverUrl);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* best-effort */
|
||||
});
|
||||
|
||||
// Release video resources
|
||||
// Release video resources
|
||||
video.src = '';
|
||||
video.load();
|
||||
this._drainDecodeQueue();
|
||||
},
|
||||
mimeType,
|
||||
0.8
|
||||
);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
|
||||
// If the video can't be loaded at all, keep the generic play badge
|
||||
video.addEventListener(
|
||||
'error',
|
||||
() => {
|
||||
video.src = '';
|
||||
video.load();
|
||||
this._drainDecodeQueue();
|
||||
}, mimeType, 0.80);
|
||||
}, { once: true });
|
||||
|
||||
// If the video can't be loaded at all, keep the generic play badge
|
||||
video.addEventListener('error', () => {
|
||||
video.src = '';
|
||||
video.load();
|
||||
this._drainDecodeQueue();
|
||||
}, { once: true });
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
},
|
||||
|
||||
/** Render the group mode toolbar */
|
||||
_renderToolbar() {
|
||||
const t = (k, d) => window.i18n ? window.i18n.t(k) : d;
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
const modes = [
|
||||
['daily', t('photos.view_daily', 'Day')],
|
||||
['monthly', t('photos.view_monthly', 'Month')],
|
||||
@@ -403,7 +423,7 @@ const photosView = {
|
||||
|
||||
/** Render empty state */
|
||||
_renderEmpty() {
|
||||
const t = (k, d) => window.i18n ? window.i18n.t(k) : d;
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
this._container.innerHTML = `
|
||||
<div class="photos-empty">
|
||||
<i class="fas fa-images"></i>
|
||||
@@ -422,10 +442,16 @@ const photosView = {
|
||||
if (this.groupMode === 'yearly') {
|
||||
key = String(d.getFullYear());
|
||||
} else if (this.groupMode === 'monthly') {
|
||||
key = d.toLocaleDateString(undefined, { year: 'numeric', month: 'long' });
|
||||
key = d.toLocaleDateString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'long'
|
||||
});
|
||||
} else {
|
||||
key = d.toLocaleDateString(undefined, {
|
||||
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
}
|
||||
if (!map.has(key)) map.set(key, []);
|
||||
@@ -456,7 +482,7 @@ const photosView = {
|
||||
}
|
||||
|
||||
// Otherwise open lightbox
|
||||
const idx = this.items.findIndex(f => f.id === id);
|
||||
const idx = this.items.findIndex((f) => f.id === id);
|
||||
if (idx >= 0 && window.photosLightbox) {
|
||||
window.photosLightbox.open(this.items, idx);
|
||||
}
|
||||
@@ -490,7 +516,7 @@ const photosView = {
|
||||
document.body.appendChild(bar);
|
||||
}
|
||||
|
||||
const t = (k, d) => window.i18n ? window.i18n.t(k) : d;
|
||||
const t = (k, d) => (window.i18n ? window.i18n.t(k) : d);
|
||||
const count = this.selected.size;
|
||||
bar.innerHTML = `
|
||||
<span class="selection-count">${count} ${t('photos.items_selected', 'selected')}</span>
|
||||
@@ -501,7 +527,7 @@ const photosView = {
|
||||
|
||||
bar.querySelector('#photos-sel-clear').onclick = () => {
|
||||
this.selected.clear();
|
||||
this._container.querySelectorAll('.photo-tile.selected').forEach(t => t.classList.remove('selected'));
|
||||
this._container.querySelectorAll('.photo-tile.selected').forEach((t) => t.classList.remove('selected'));
|
||||
this._hideSelectionBar();
|
||||
};
|
||||
|
||||
@@ -518,7 +544,7 @@ const photosView = {
|
||||
console.error('Delete failed:', fid, err);
|
||||
}
|
||||
}
|
||||
this.items = this.items.filter(f => !this.selected.has(f.id));
|
||||
this.items = this.items.filter((f) => !this.selected.has(f.id));
|
||||
this.selected.clear();
|
||||
this._hideSelectionBar();
|
||||
this._renderedCount = 0;
|
||||
@@ -571,7 +597,9 @@ const photosView = {
|
||||
},
|
||||
|
||||
_escAttr(s) {
|
||||
return String(s || '').replace(/"/g, '"').replace(/</g, '<');
|
||||
return String(s || '')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -122,8 +122,11 @@ const photosLightbox = {
|
||||
// Format date
|
||||
const ts = (item.sort_date || item.created_at) * 1000;
|
||||
const dateStr = new Date(ts).toLocaleDateString(undefined, {
|
||||
year: 'numeric', month: 'short', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit'
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
meta.textContent = `${dateStr} · ${item.size_formatted || ''}`;
|
||||
|
||||
@@ -233,7 +236,7 @@ const photosLightbox = {
|
||||
});
|
||||
// Remove from photosView items too
|
||||
if (window.photosView) {
|
||||
window.photosView.items = window.photosView.items.filter(f => f.id !== item.id);
|
||||
window.photosView.items = window.photosView.items.filter((f) => f.id !== item.id);
|
||||
}
|
||||
this.items.splice(this.index, 1);
|
||||
if (this.items.length === 0) {
|
||||
@@ -274,7 +277,9 @@ const photosLightbox = {
|
||||
},
|
||||
|
||||
_escAttr(s) {
|
||||
return String(s || '').replace(/"/g, '"').replace(/</g, '<');
|
||||
return String(s || '')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -25,10 +25,12 @@ const fileSharing = {
|
||||
item_name: options.name || null,
|
||||
item_type: itemType,
|
||||
password: options.password || null,
|
||||
expires_at: options.expirationDate
|
||||
? Math.floor(new Date(options.expirationDate).getTime() / 1000)
|
||||
: null,
|
||||
permissions: options.permissions || { read: true, write: false, reshare: false }
|
||||
expires_at: options.expirationDate ? Math.floor(new Date(options.expirationDate).getTime() / 1000) : null,
|
||||
permissions: options.permissions || {
|
||||
read: true,
|
||||
write: false,
|
||||
reshare: false
|
||||
}
|
||||
};
|
||||
|
||||
const res = await fetch('/api/shares', {
|
||||
@@ -71,13 +73,16 @@ const fileSharing = {
|
||||
*/
|
||||
async getSharedLinksForItem(itemId, itemType) {
|
||||
try {
|
||||
const params = new URLSearchParams({ item_id: itemId, item_type: itemType });
|
||||
const params = new URLSearchParams({
|
||||
item_id: itemId,
|
||||
item_type: itemType
|
||||
});
|
||||
const res = await fetch(`/api/shares?${params}`, {
|
||||
headers: this._headers(false)
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return Array.isArray(data) ? data : (data.items || []);
|
||||
return Array.isArray(data) ? data : data.items || [];
|
||||
} catch (error) {
|
||||
console.error('Error getting shared links for item:', error);
|
||||
return [];
|
||||
@@ -184,7 +189,7 @@ const fileSharing = {
|
||||
*/
|
||||
init() {
|
||||
console.log('File sharing module initialized (API-backed)');
|
||||
document.querySelectorAll('.nav-item').forEach(item => {
|
||||
document.querySelectorAll('.nav-item').forEach((item) => {
|
||||
const span = item.querySelector('span');
|
||||
if (span && span.getAttribute('data-i18n') === 'nav.shared') {
|
||||
item.addEventListener('click', () => {
|
||||
@@ -204,4 +209,4 @@ window.fileSharing = fileSharing;
|
||||
window.getSharedLinks = () => fileSharing.getSharedLinks();
|
||||
window.updateSharedLink = (id, data) => fileSharing.updateSharedLink(id, data);
|
||||
window.removeSharedLink = (id) => fileSharing.removeSharedLink(id);
|
||||
window.sendShareNotification = (url, email, msg) => fileSharing.sendShareNotification(url, email, msg);
|
||||
window.sendShareNotification = (url, email, msg) => fileSharing.sendShareNotification(url, email, msg);
|
||||
|
||||
Reference in New Issue
Block a user