Files
SkyArtShop/website/admin/media-library-old.html
Local Server 2a2a3d99e5 webupdate
2026-01-18 02:22:05 -06:00

1710 lines
51 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Media Library - Sky Art Shop</title>
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<!-- Immediate select mode detection to prevent flash -->
<script>
(function () {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("selectMode") === "true") {
document.documentElement.classList.add("select-mode");
}
})();
</script>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"
/>
<link rel="stylesheet" href="/admin/css/admin-style.css" />
<style>
/* Select mode styles - applied immediately to prevent flash */
.select-mode .sidebar {
display: none !important;
}
.select-mode .main-content {
margin-left: 0 !important;
width: 100% !important;
}
.select-mode #logoutBtn {
display: none !important;
}
.select-mode #deleteSelectedBtn {
display: none !important;
}
.media-container {
display: flex;
flex-direction: column;
gap: 20px;
}
.toolbar {
background: #fff;
padding: 15px 20px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 15px;
margin-bottom: 20px;
border-bottom: 2px solid #e5e7eb;
}
.toolbar-left {
display: flex;
align-items: center;
gap: 10px;
}
.back-button {
background: #7c3aed;
color: white;
border: none;
width: 32px;
height: 32px;
border-radius: 6px;
display: none;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s;
flex-shrink: 0;
}
.back-button:hover {
background: #6d28d9;
transform: translateX(-2px);
}
.back-button i {
font-size: 16px;
}
.toolbar-right {
display: flex;
gap: 10px;
}
.breadcrumb {
background: transparent;
padding: 0;
margin: 0;
font-size: 14px;
}
.breadcrumb-item a {
color: #7c3aed;
text-decoration: none;
}
.breadcrumb-item a:hover {
text-decoration: underline;
}
.selected-count {
background: #7c3aed;
color: white;
padding: 6px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 500;
}
.media-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 12px;
padding: 20px;
background: #fff;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
min-height: 400px;
border-top: 2px solid #d1d5db;
}
.media-item {
position: relative;
border: 2px solid #e5e7eb;
border-radius: 8px;
overflow: hidden;
cursor: pointer;
transition: all 0.2s;
background: #fff;
display: flex;
flex-direction: column;
height: 200px;
width: 200px;
}
.media-item:hover {
border-color: #7c3aed;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(124, 58, 237, 0.2);
}
.media-item.selected {
border-color: #7c3aed;
border-width: 3px;
box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
}
.media-checkbox {
margin: 8px;
width: 20px;
height: 20px;
cursor: pointer;
flex-shrink: 0;
}
.folder-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 10px;
height: 100%;
background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
}
.folder-item.drag-over {
background: linear-gradient(135deg, #ddd6fe 0%, #c4b5fd 100%);
border: 2px dashed #7c3aed;
}
.media-item[draggable="true"] {
cursor: move;
}
.media-item.dragging {
opacity: 0.5;
}
.folder-item i {
font-size: 32px;
color: #7c3aed;
margin-bottom: 6px;
}
.folder-name {
font-size: 11px;
font-weight: 500;
text-align: center;
word-break: break-word;
color: #374151;
}
.file-item {
display: flex;
flex-direction: column;
flex: 1;
}
.file-item img {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
background: #f9fafb;
padding: 5px;
}
.file-name {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 4px 6px;
background: rgba(249, 250, 251, 0.95);
font-size: 9px;
text-align: center;
word-break: break-all;
color: #6b7280;
max-height: 30px;
overflow: hidden;
text-overflow: ellipsis;
}
/* Custom Notification */
.custom-notification {
position: fixed;
top: 20px;
right: 20px;
max-width: 400px;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
padding: 20px;
z-index: 10000;
display: none;
animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
.custom-notification.success {
border-left: 4px solid #10b981;
}
.custom-notification.error {
border-left: 4px solid #ef4444;
}
.notification-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.notification-title {
display: flex;
align-items: center;
gap: 10px;
font-weight: 600;
font-size: 16px;
}
.notification-title i {
font-size: 24px;
}
.notification-title.success {
color: #10b981;
}
.notification-title.error {
color: #ef4444;
}
.notification-close {
background: none;
border: none;
font-size: 20px;
color: #9ca3af;
cursor: pointer;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
transition: all 0.2s;
}
.notification-close:hover {
background: #f3f4f6;
color: #374151;
}
.notification-message {
color: #6b7280;
font-size: 14px;
line-height: 1.5;
}
.upload-zone {
border: 3px dashed #d1d5db;
border-radius: 10px;
padding: 40px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
background: #f9fafb;
margin-bottom: 20px;
}
.upload-zone:hover,
.upload-zone.dragover {
border-color: #7c3aed;
background: #f3f0ff;
}
.upload-zone i {
font-size: 48px;
color: #7c3aed;
margin-bottom: 15px;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #9ca3af;
}
.empty-state i {
font-size: 64px;
margin-bottom: 20px;
opacity: 0.5;
}
.progress-container {
position: fixed;
bottom: 20px;
right: 20px;
width: 350px;
background: white;
border-radius: 8px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
padding: 20px;
z-index: 1000;
}
.modal-content {
border-radius: 12px;
}
/* Image Viewer Lightbox */
.image-viewer {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.95);
z-index: 10000;
display: none;
align-items: center;
justify-content: center;
animation: fadeIn 0.2s ease;
}
.image-viewer.active {
display: flex;
}
.image-viewer-content {
position: relative;
max-width: 90%;
max-height: 90%;
display: flex;
flex-direction: column;
align-items: center;
}
.image-viewer img {
max-width: 100%;
max-height: 85vh;
object-fit: contain;
border-radius: 4px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}
.image-viewer-close {
position: absolute;
top: -50px;
right: 0;
background: rgba(255, 255, 255, 0.1);
border: 2px solid rgba(255, 255, 255, 0.3);
color: white;
width: 40px;
height: 40px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
font-size: 24px;
transition: all 0.2s;
backdrop-filter: blur(10px);
}
.image-viewer-close:hover {
background: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.5);
transform: scale(1.1);
}
.image-viewer-filename {
color: white;
margin-top: 15px;
padding: 8px 16px;
background: rgba(255, 255, 255, 0.1);
border-radius: 20px;
font-size: 14px;
backdrop-filter: blur(10px);
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
</style>
</head>
<body>
<!-- Sidebar -->
<div class="sidebar">
<div class="sidebar-brand">🛍️ Sky Art Shop</div>
<ul class="sidebar-menu">
<li>
<a href="/admin/dashboard"
><i class="bi bi-speedometer2"></i> Dashboard</a
>
</li>
<li>
<a href="/admin/homepage"
><i class="bi bi-house"></i> Homepage Editor</a
>
</li>
<li>
<a href="/admin/products"><i class="bi bi-box"></i> Products</a>
</li>
<li>
<a href="/admin/portfolio"
><i class="bi bi-easel"></i> Portfolio</a
>
</li>
<li>
<a href="/admin/blog"><i class="bi bi-newspaper"></i> Blog</a>
</li>
<li>
<a href="/admin/pages"
><i class="bi bi-file-text"></i> Custom Pages</a
>
</li>
<li>
<a href="/admin/media-library" class="active"
><i class="bi bi-images"></i> Media Library</a
>
</li>
<li>
<a href="/admin/menu"><i class="bi bi-list"></i> Menu</a>
</li>
<li>
<a href="/admin/settings"><i class="bi bi-gear"></i> Settings</a>
</li>
<li>
<a href="/admin/users"><i class="bi bi-people"></i> Users</a>
</li>
</ul>
</div>
<!-- Main Content -->
<div class="main-content">
<!-- Custom Notification -->
<div class="custom-notification" id="customNotification">
<div class="notification-header">
<div class="notification-title" id="notificationTitle">
<i class="bi bi-check-circle-fill"></i>
<span id="notificationTitleText">Success</span>
</div>
<button class="notification-close" id="notificationClose">
<i class="bi bi-x"></i>
</button>
</div>
<div class="notification-message" id="notificationMessage">
Operation completed successfully
</div>
</div>
<!-- Top Bar -->
<div class="top-bar">
<div>
<h3>Media Library</h3>
<p class="mb-0 text-muted">Manage your images and media files</p>
</div>
<div>
<button class="btn-logout" id="logoutBtn">
<i class="bi bi-box-arrow-right"></i> Logout
</button>
</div>
</div>
<div class="container-fluid">
<!-- Toolbar -->
<div class="toolbar">
<div class="toolbar-left">
<button class="back-button" id="backButton" title="Go back">
<i class="bi bi-arrow-left"></i>
</button>
<nav aria-label="breadcrumb">
<ol class="breadcrumb" id="breadcrumb">
<li class="breadcrumb-item">
<a href="#" data-folder-id="null"
><i class="bi bi-house-door"></i> Root</a
>
</li>
</ol>
</nav>
<span
class="selected-count"
id="selectedCount"
style="display: none"
>0 selected</span
>
</div>
<div class="toolbar-right">
<button class="btn btn-sm btn-success" id="newFolderBtn">
<i class="bi bi-folder-plus"></i> New Folder
</button>
<button class="btn btn-sm btn-primary" id="uploadFilesBtn">
<i class="bi bi-cloud-upload"></i> Upload Files
</button>
<button
class="btn btn-sm btn-danger"
id="deleteSelectedBtn"
style="display: none"
>
<i class="bi bi-trash"></i> Delete Selected
</button>
</div>
</div>
<!-- Upload Zone (hidden by default) -->
<div class="upload-zone" id="uploadZone" style="display: none">
<i class="bi bi-cloud-arrow-up d-block"></i>
<h5>Drop files here or click to browse</h5>
<p class="text-muted mb-0">
Supported: JPG, PNG, GIF, WebP (Max 5MB each)
</p>
<input
type="file"
id="fileInput"
multiple
accept="image/*"
style="display: none"
/>
</div>
<!-- Progress Bar -->
<div
class="progress-container"
id="uploadProgress"
style="display: none"
>
<h6 class="mb-3">Uploading files...</h6>
<div class="progress">
<div
class="progress-bar progress-bar-striped progress-bar-animated"
id="progressBar"
style="width: 0%"
>
0%
</div>
</div>
</div>
<!-- Media Grid -->
<div class="media-grid" id="mediaGrid">
<div class="empty-state">
<i class="bi bi-folder-x d-block"></i>
<h5>No files yet</h5>
<p>Upload files or create folders to get started</p>
</div>
</div>
</div>
</div>
<!-- Image Viewer -->
<div class="image-viewer" id="imageViewer">
<div class="image-viewer-content">
<button class="image-viewer-close" id="imageViewerClose">
<i class="bi bi-x"></i>
</button>
<img id="imageViewerImg" src="" alt="" />
<div class="image-viewer-filename" id="imageViewerFilename"></div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-danger text-white">
<h5 class="modal-title">
<i class="bi bi-exclamation-triangle-fill"></i> Confirm Deletion
</h5>
<button
type="button"
class="btn-close btn-close-white"
data-bs-dismiss="modal"
></button>
</div>
<div class="modal-body">
<p id="deleteConfirmMessage" class="mb-0">
Are you sure you want to delete the selected items?
</p>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Cancel
</button>
<button type="button" class="btn btn-danger" id="confirmDeleteBtn">
<i class="bi bi-trash"></i> Delete
</button>
</div>
</div>
</div>
</div>
<!-- Create Folder Modal -->
<div class="modal fade" id="createFolderModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Create New Folder</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Folder Name</label>
<input
type="text"
class="form-control"
id="folderNameInput"
placeholder="Enter folder name"
/>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Cancel
</button>
<button type="button" class="btn btn-primary" id="createFolderBtn">
Create Folder
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentFolderId = null;
let allFolders = [];
let allFiles = [];
let selectedItems = new Set(); // Store IDs: 'f-{id}' for folders, 'u-{id}' for files
let folderPath = [];
let isSelectMode = false;
async function init() {
console.log("Initializing media library...");
// Check if we're in select mode
const urlParams = new URLSearchParams(window.location.search);
isSelectMode = urlParams.get("selectMode") === "true";
if (isSelectMode) {
// Change title for select mode
document.querySelector(".top-bar h3").textContent = "Select Images";
document.querySelector(".top-bar p").textContent =
"Choose one or more images to add to your product";
// Add select button to toolbar
const toolbar = document.querySelector(".toolbar-right");
const selectBtn = document.createElement("button");
selectBtn.className = "btn btn-sm btn-success";
selectBtn.id = "confirmSelectionBtn";
selectBtn.style.display = "none";
selectBtn.innerHTML =
'<i class="bi bi-check-circle"></i> Select Images';
selectBtn.onclick = confirmSelection;
toolbar.appendChild(selectBtn);
console.log("Media library in SELECT MODE");
}
// Load both folders and files in parallel, then render
await Promise.all([loadFolders(), loadFiles()]);
// Render media AFTER both are loaded
renderMedia();
updateBreadcrumb();
console.log("Media library initialized");
}
async function loadFolders() {
try {
console.log("Loading folders from /api/admin/folders...");
const response = await fetch("/api/admin/folders", {
credentials: "include",
});
console.log("Folders response status:", response.status);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Folders API response:", data);
if (data.success) {
allFolders = data.folders || [];
console.log("✓ Loaded folders:", allFolders.length, allFolders);
} else {
console.error(
"Failed to load folders:",
data.message || data.error
);
allFolders = [];
if (data.message && data.message.includes("Authentication")) {
window.location.href = "/admin/login";
}
}
} catch (error) {
console.error("Failed to load folders:", error);
allFolders = [];
alert("Failed to load folders. Please refresh the page.");
}
}
async function loadFiles(folderId = null) {
try {
currentFolderId = folderId;
let url = "/api/admin/uploads";
if (folderId !== null) {
url += `?folder_id=${folderId}`;
} else {
url += "?folder_id=null";
}
console.log("Loading files from:", url);
const response = await fetch(url, {
credentials: "include",
});
console.log("Files response status:", response.status);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Files API response:", data);
if (data.success) {
allFiles = data.files || [];
console.log("✓ Loaded files:", allFiles.length, allFiles);
// Don't render here - let init() render after both folders and files load
} else {
console.error("Failed to load files:", data.message || data.error);
allFiles = [];
if (data.message && data.message.includes("Authentication")) {
window.location.href = "/admin/login";
}
}
} catch (error) {
console.error("Failed to load files:", error);
allFiles = [];
// Render will be called by init() after Promise.all completes
alert("Failed to load media library");
}
}
function renderMedia() {
const grid = document.getElementById("mediaGrid");
// Get subfolders of current folder
const subfolders = allFolders.filter(
(f) => f.parentId === currentFolderId
);
if (subfolders.length === 0 && allFiles.length === 0) {
grid.innerHTML = `
<div class="empty-state">
<i class="bi bi-folder-x d-block"></i>
<h5>No files yet</h5>
<p>Upload files or create folders to get started</p>
</div>
`;
return;
}
let html = "";
// Render folders first
for (const folder of subfolders) {
const isSelected = selectedItems.has(`f-${folder.id}`);
html += `
<div class="media-item ${
isSelected ? "selected" : ""
}" data-type="folder" data-id="${folder.id}">
<input type="checkbox" class="media-checkbox form-check-input"
data-item-id="f-${folder.id}"
${isSelected ? "checked" : ""} />
<div class="folder-item" data-folder-id="${folder.id}">
<i class="bi bi-folder-fill"></i>
<div class="folder-name">${escapeHtml(folder.name)}</div>
<small class="text-muted">${folder.fileCount} files</small>
</div>
</div>
`;
}
// Render files
for (const file of allFiles) {
const isSelected = selectedItems.has(`u-${file.id}`);
html += `
<div class="media-item ${
isSelected ? "selected" : ""
}" data-type="file" data-id="${file.id}">
<input type="checkbox" class="media-checkbox form-check-input drag-handle"
data-item-id="u-${file.id}"
${isSelected ? "checked" : ""} />
<div class="file-item" data-file-id="${file.id}">
<img src="${file.path}" alt="${escapeHtml(file.originalName)}"
loading="lazy" />
<div class="file-name" title="${escapeHtml(
file.originalName
)}">${escapeHtml(file.originalName)}</div>
</div>
</div>
`;
}
grid.innerHTML = html;
// Attach event listeners to checkboxes
grid.querySelectorAll(".media-checkbox").forEach((checkbox) => {
checkbox.addEventListener("click", (e) => {
e.stopPropagation();
const itemId = e.target.getAttribute("data-item-id");
toggleSelection(itemId, e);
});
});
// Attach double-click listeners to folders
grid.querySelectorAll(".folder-item").forEach((item) => {
item.addEventListener("dblclick", (e) => {
const folderId = parseInt(
e.currentTarget.getAttribute("data-folder-id")
);
navigateToFolder(folderId);
});
});
// Attach click listeners to file items to open image viewer
grid.querySelectorAll(".file-item").forEach((item) => {
item.addEventListener("click", (e) => {
// Don't open viewer if checkbox was clicked
if (e.target.classList.contains("media-checkbox")) {
return;
}
e.preventDefault();
e.stopPropagation();
const img = item.querySelector("img");
const filename =
item.querySelector(".file-name")?.textContent || "Image";
if (img && img.src) {
console.log("Opening image viewer:", img.src);
openImageViewer(img.src, filename);
}
});
});
// Add error handling for images
grid.querySelectorAll(".file-item img").forEach((img) => {
img.addEventListener("error", function () {
// Replace failed image with icon placeholder
const container = this.parentElement;
if (container) {
this.style.display = "none";
const placeholder = document.createElement("div");
placeholder.style.cssText = `
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #f3f4f6;
color: #9ca3af;
`;
placeholder.innerHTML =
'<i class="bi bi-image" style="font-size: 48px;"></i>';
container.insertBefore(placeholder, this);
}
});
});
// Add drag and drop functionality for files
grid
.querySelectorAll('.media-item[data-type="file"]')
.forEach((item) => {
const checkbox = item.querySelector(".media-checkbox");
let isDragging = false;
// Make item draggable when mousedown on checkbox area
if (checkbox) {
checkbox.addEventListener("mousedown", (e) => {
if (e.button === 0) {
// Left click only
item.setAttribute("draggable", "true");
}
});
}
item.addEventListener("dragstart", (e) => {
isDragging = true;
e.currentTarget.classList.add("dragging");
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", e.currentTarget.dataset.id);
});
item.addEventListener("dragend", (e) => {
isDragging = false;
e.currentTarget.classList.remove("dragging");
item.removeAttribute("draggable");
});
// Prevent drag from starting on image clicks
const fileItem = item.querySelector(".file-item");
if (fileItem) {
fileItem.addEventListener("mousedown", (e) => {
item.removeAttribute("draggable");
});
}
});
// Add drop targets for folders
grid.querySelectorAll(".folder-item").forEach((folderItem) => {
const folderElement = folderItem.closest(".media-item");
folderElement.addEventListener("dragover", (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
folderItem.classList.add("drag-over");
});
folderElement.addEventListener("dragleave", (e) => {
// Only remove if we're actually leaving the folder element
if (!folderElement.contains(e.relatedTarget)) {
folderItem.classList.remove("drag-over");
}
});
folderElement.addEventListener("drop", async (e) => {
e.preventDefault();
folderItem.classList.remove("drag-over");
const fileId = e.dataTransfer.getData("text/plain");
const targetFolderId = folderItem.dataset.folderId;
if (fileId && targetFolderId) {
await moveFileToFolder(
parseInt(fileId),
parseInt(targetFolderId)
);
}
});
});
}
function toggleSelection(itemId, event) {
event.stopPropagation();
if (selectedItems.has(itemId)) {
selectedItems.delete(itemId);
} else {
selectedItems.add(itemId);
}
updateSelectionUI();
// In select mode, show/hide select button based on file selections
if (isSelectMode) {
const selectBtn = document.getElementById("confirmSelectionBtn");
const fileSelections = Array.from(selectedItems).filter((id) =>
id.startsWith("u-")
);
if (selectBtn) {
selectBtn.style.display =
fileSelections.length > 0 ? "inline-block" : "none";
}
}
}
function updateSelectionUI() {
const countEl = document.getElementById("selectedCount");
const deleteBtn = document.getElementById("deleteSelectedBtn");
if (selectedItems.size > 0) {
countEl.textContent = `${selectedItems.size} selected`;
countEl.style.display = "inline-block";
// Delete button visibility is handled by CSS in select mode
if (!isSelectMode) {
deleteBtn.style.display = "inline-block";
}
} else {
countEl.style.display = "none";
if (!isSelectMode) {
deleteBtn.style.display = "none";
}
}
renderMedia();
}
// Function to confirm selection and send back to parent
function confirmSelection() {
// Get only file selections (not folders)
const fileSelections = Array.from(selectedItems)
.filter((id) => id.startsWith("u-"))
.map((id) => parseInt(id.substring(2)));
// Build array of selected files
const selectedFiles = allFiles
.filter((file) => fileSelections.includes(file.id))
.map((file) => ({
url: file.path,
filename: file.originalName,
id: file.id,
}));
console.log("Sending selected files to parent:", selectedFiles);
// Send message to parent window
if (window.parent && window.parent !== window) {
window.parent.postMessage(
{
type: "mediaSelected",
media: selectedFiles,
},
"*"
);
}
}
async function navigateToFolder(folderId) {
selectedItems.clear();
updateSelectionUI();
if (folderId === null) {
folderPath = [];
} else {
// Build path
folderPath = [];
let currentId = folderId;
while (currentId !== null) {
const folder = allFolders.find((f) => f.id === currentId);
if (!folder) break;
folderPath.unshift({ id: folder.id, name: folder.name });
currentId = folder.parentId;
}
}
await loadFiles(folderId);
renderMedia();
updateBreadcrumb();
}
function updateBreadcrumb() {
const breadcrumb = document.getElementById("breadcrumb");
const backButton = document.getElementById("backButton");
let html =
'<li class="breadcrumb-item"><a href="#" data-folder-id="null"><i class="bi bi-house-door"></i> Root</a></li>';
for (const folder of folderPath) {
html += `<li class="breadcrumb-item"><a href="#" data-folder-id="${
folder.id
}">${escapeHtml(folder.name)}</a></li>`;
}
breadcrumb.innerHTML = html;
// Show/hide back button based on folder depth
if (folderPath.length > 0) {
backButton.style.display = "flex";
} else {
backButton.style.display = "none";
}
// Attach event listeners to breadcrumb links
breadcrumb.querySelectorAll("a").forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const folderId = e.currentTarget.getAttribute("data-folder-id");
navigateToFolder(folderId === "null" ? null : parseInt(folderId));
});
});
}
function showUploadZone() {
const zone = document.getElementById("uploadZone");
if (zone.style.display === "none" || zone.style.display === "") {
zone.style.display = "block";
console.log("Upload zone opened");
} else {
zone.style.display = "none";
console.log("Upload zone closed");
}
}
async function handleFileSelect(event) {
event.stopPropagation();
const files = Array.from(event.target.files);
console.log("Files selected:", files.length);
if (files.length > 0) {
await uploadFiles(files);
}
event.target.value = ""; // Reset input
}
async function handleDrop(event) {
event.preventDefault();
event.stopPropagation();
event.currentTarget.classList.remove("dragover");
const files = Array.from(event.dataTransfer.files);
console.log("Files dropped:", files.length);
if (files.length > 0) {
await uploadFiles(files);
}
}
async function uploadFiles(files) {
if (files.length === 0) {
console.log("No files to upload");
return;
}
console.log("Starting upload of", files.length, "files");
const formData = new FormData();
files.forEach((file) => {
console.log("Adding file:", file.name, file.type, file.size);
formData.append("files", file);
});
if (currentFolderId !== null) {
formData.append("folder_id", currentFolderId);
console.log("Uploading to folder:", currentFolderId);
}
const progressBar = document.getElementById("progressBar");
const progressContainer = document.getElementById("uploadProgress");
progressContainer.style.display = "block";
progressBar.style.width = "0%";
progressBar.textContent = "0%";
try {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
progressBar.style.width = percentComplete + "%";
progressBar.textContent = Math.round(percentComplete) + "%";
console.log(
"Upload progress:",
Math.round(percentComplete) + "%"
);
}
});
xhr.addEventListener("load", function () {
console.log("Upload complete, status:", xhr.status);
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log("Upload response:", data);
if (data.success) {
showNotification(
`Successfully uploaded ${data.files.length} file(s)!`,
"success"
);
setTimeout(() => {
progressContainer.style.display = "none";
progressBar.style.width = "0%";
document.getElementById("uploadZone").style.display = "none";
loadFiles(currentFolderId).then(() => renderMedia());
}, 500);
} else {
console.error("Upload failed:", data.message || data.error);
showNotification(
"Upload failed: " +
(data.message || data.error || "Unknown error"),
"error"
);
progressContainer.style.display = "none";
}
} else {
console.error("Upload HTTP error:", xhr.status, xhr.responseText);
showNotification(
"Upload failed with status " + xhr.status,
"error"
);
progressContainer.style.display = "none";
}
});
xhr.addEventListener("error", function () {
console.error("Upload network error");
showNotification("Upload failed due to network error", "error");
progressContainer.style.display = "none";
});
xhr.open("POST", "/api/admin/upload");
xhr.withCredentials = true;
console.log("Sending upload request...");
xhr.send(formData);
} catch (error) {
console.error("Upload failed:", error);
showNotification("Upload failed: " + error.message, "error");
progressContainer.style.display = "none";
}
}
function showCreateFolderModal() {
const modal = new bootstrap.Modal(
document.getElementById("createFolderModal")
);
document.getElementById("folderNameInput").value = "";
modal.show();
}
async function createFolder() {
const nameInput = document.getElementById("folderNameInput");
const name = nameInput.value.trim();
if (!name) {
showNotification("Please enter a folder name", "error");
return;
}
console.log("Creating folder:", name, "in parent:", currentFolderId);
try {
const response = await fetch("/api/admin/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
name: name,
parent_id: currentFolderId,
}),
});
const data = await response.json();
console.log("Create folder response:", data);
if (data.success) {
showNotification(
`Folder "${name}" created successfully!`,
"success"
);
const modalElement = document.getElementById("createFolderModal");
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
// Blur any focused elements before hiding modal
const focusedElement = document.activeElement;
if (focusedElement && modalElement.contains(focusedElement)) {
focusedElement.blur();
}
modal.hide();
}
nameInput.value = "";
await loadFolders();
await loadFiles(currentFolderId);
renderMedia();
} else {
console.error("Failed to create folder:", data.error);
showNotification(
"Failed to create folder: " + (data.error || "Unknown error"),
"error"
);
}
} catch (error) {
console.error("Failed to create folder:", error);
showNotification(
"Failed to create folder: " + error.message,
"error"
);
}
}
async function handleDeleteSelected() {
if (selectedItems.size === 0) return;
const folderIds = Array.from(selectedItems)
.filter((id) => id.startsWith("f-"))
.map((id) => parseInt(id.substring(2)));
const fileIds = Array.from(selectedItems)
.filter((id) => id.startsWith("u-"))
.map((id) => parseInt(id.substring(2)));
// Show custom delete confirmation modal
const message = document.getElementById("deleteConfirmMessage");
message.textContent = `Are you sure you want to delete ${selectedItems.size} item(s)? This action cannot be undone.`;
const modalElement = document.getElementById("deleteConfirmModal");
const modal = new bootstrap.Modal(modalElement);
modal.show();
return; // Exit here, deletion will be handled by modal button
}
async function performDelete() {
const folderIds = Array.from(selectedItems)
.filter((id) => id.startsWith("f-"))
.map((id) => parseInt(id.substring(2)));
const fileIds = Array.from(selectedItems)
.filter((id) => id.startsWith("u-"))
.map((id) => parseInt(id.substring(2)));
try {
// Close modal
const modalElement = document.getElementById("deleteConfirmModal");
const modal = bootstrap.Modal.getInstance(modalElement);
if (modal) {
const focusedElement = document.activeElement;
if (focusedElement && modalElement.contains(focusedElement)) {
focusedElement.blur();
}
modal.hide();
}
try {
// Delete files
if (fileIds.length > 0) {
const response = await fetch("/api/admin/uploads/bulk-delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ file_ids: fileIds }),
});
const data = await response.json();
if (!data.success) {
showNotification(
"Failed to delete some files: " + data.error,
"error"
);
return;
}
}
// Delete folders
for (const folderId of folderIds) {
await fetch(
`/api/admin/folders/${folderId}?delete_contents=true`,
{
method: "DELETE",
credentials: "include",
}
);
}
showNotification(
`Successfully deleted ${selectedItems.size} item(s)`,
"success"
);
selectedItems.clear();
await loadFolders();
await loadFiles(currentFolderId);
renderMedia();
} catch (error) {
console.error("Failed to delete items:", error);
showNotification(
"Failed to delete items: " + error.message,
"error"
);
}
} catch (error) {
console.error("Failed to delete items:", error);
showNotification("Failed to delete items: " + error.message, "error");
}
}
async function moveFileToFolder(fileId, targetFolderId) {
try {
const response = await fetch(`/api/admin/uploads/move`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
file_ids: [fileId],
folder_id: targetFolderId,
}),
});
const data = await response.json();
if (data.success) {
showNotification("File moved successfully!", "success");
await loadFolders();
await loadFiles(currentFolderId);
renderMedia();
} else {
showNotification(
"Failed to move file: " + (data.error || "Unknown error"),
"error"
);
}
} catch (error) {
console.error("Failed to move file:", error);
showNotification("Failed to move file: " + error.message, "error");
}
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// Custom notification function
function showNotification(message, type = "success") {
const notification = document.getElementById("customNotification");
const title = document.getElementById("notificationTitle");
const titleText = document.getElementById("notificationTitleText");
const messageEl = document.getElementById("notificationMessage");
// Set content
messageEl.textContent = message;
// Set type
notification.className = `custom-notification ${type}`;
title.className = `notification-title ${type}`;
if (type === "success") {
title.querySelector("i").className = "bi bi-check-circle-fill";
titleText.textContent = "Success";
} else {
title.querySelector("i").className = "bi bi-exclamation-circle-fill";
titleText.textContent = "Error";
}
// Show notification
notification.style.display = "block";
// Auto hide after 4 seconds
setTimeout(() => {
notification.style.animation = "slideOut 0.3s ease-out";
setTimeout(() => {
notification.style.display = "none";
notification.style.animation = "slideIn 0.3s ease-out";
}, 300);
}, 4000);
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// Setup all event listeners
function setupEventListeners() {
// Logout button is handled by auth.js automatically
// Notification close button
const notificationClose = document.getElementById("notificationClose");
if (notificationClose) {
notificationClose.addEventListener("click", () => {
const notification = document.getElementById("customNotification");
notification.style.animation = "slideOut 0.3s ease-out";
setTimeout(() => {
notification.style.display = "none";
notification.style.animation = "slideIn 0.3s ease-out";
}, 300);
});
}
// Back button
const backButton = document.getElementById("backButton");
if (backButton) {
backButton.addEventListener("click", () => {
if (folderPath.length > 0) {
// Go to parent folder
if (folderPath.length === 1) {
// Go to root
navigateToFolder(null);
} else {
// Go to previous folder in path
const parentFolder = folderPath[folderPath.length - 2];
navigateToFolder(parentFolder.id);
}
}
});
}
// New Folder button
const newFolderBtn = document.getElementById("newFolderBtn");
if (newFolderBtn) {
newFolderBtn.addEventListener("click", showCreateFolderModal);
}
// Upload Files button
const uploadFilesBtn = document.getElementById("uploadFilesBtn");
if (uploadFilesBtn) {
uploadFilesBtn.addEventListener("click", showUploadZone);
}
// Delete Selected button
const deleteSelectedBtn = document.getElementById("deleteSelectedBtn");
if (deleteSelectedBtn) {
deleteSelectedBtn.addEventListener("click", handleDeleteSelected);
}
// Confirm Delete button in modal
const confirmDeleteBtn = document.getElementById("confirmDeleteBtn");
if (confirmDeleteBtn) {
confirmDeleteBtn.addEventListener("click", performDelete);
}
// Upload zone
const uploadZone = document.getElementById("uploadZone");
if (uploadZone) {
uploadZone.addEventListener("click", () => {
document.getElementById("fileInput").click();
});
uploadZone.addEventListener("drop", handleDrop);
uploadZone.addEventListener("dragover", (e) => {
e.preventDefault();
e.currentTarget.classList.add("dragover");
});
uploadZone.addEventListener("dragleave", (e) => {
e.currentTarget.classList.remove("dragover");
});
}
// File input
const fileInput = document.getElementById("fileInput");
if (fileInput) {
fileInput.addEventListener("change", handleFileSelect);
}
// Create Folder button in modal
const createFolderBtn = document.getElementById("createFolderBtn");
if (createFolderBtn) {
createFolderBtn.addEventListener("click", createFolder);
}
// Allow Enter key in folder name input
const folderNameInput = document.getElementById("folderNameInput");
if (folderNameInput) {
folderNameInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
createFolder();
}
});
}
}
// Image viewer functions
function openImageViewer(imageSrc, filename) {
const viewer = document.getElementById("imageViewer");
const img = document.getElementById("imageViewerImg");
const filenameEl = document.getElementById("imageViewerFilename");
img.src = imageSrc;
img.alt = filename;
filenameEl.textContent = filename;
viewer.classList.add("active");
// Prevent body scroll
document.body.style.overflow = "hidden";
}
function closeImageViewer() {
const viewer = document.getElementById("imageViewer");
viewer.classList.remove("active");
// Restore body scroll
document.body.style.overflow = "";
}
// Close viewer with ESC key
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
const viewer = document.getElementById("imageViewer");
if (viewer.classList.contains("active")) {
closeImageViewer();
}
}
});
// Close viewer by clicking close button or outside
document.addEventListener("click", (e) => {
if (
e.target.id === "imageViewerClose" ||
e.target.closest("#imageViewerClose")
) {
closeImageViewer();
}
// Close by clicking the dark background
if (e.target.id === "imageViewer") {
closeImageViewer();
}
});
// Initialize after authentication is confirmed
document.addEventListener("DOMContentLoaded", async function () {
setupEventListeners();
// Ensure authentication completes before initializing
// auth.js will also call checkAuth, but we need to ensure it's done
try {
const authenticated = await window.checkAuth();
if (authenticated) {
await init();
}
} catch (error) {
console.error("Failed to initialize media library:", error);
}
});
</script>
<script src="/admin/js/auth.js"></script>
</body>
</html>