<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Free Cloud Storage 100TB</title>
<style>
/* Reset & basics */
* {
box-sizing: border-box;
}
body {
margin:0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #f5f7fa;
display: flex; flex-direction: column; min-height: 100vh;
}
header {
background: #2d89ef;
color: white;
padding: 1rem 1.5rem;
text-align: center;
font-size: 1.5rem;
font-weight: 600;
user-select: none;
}
main {
flex:1;
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem 1rem 2rem 1rem;
max-width: 1200px;
margin: 0 auto;
}
/* STORAGE USAGE BAR */
#storage-usage {
background: #e0e5ea;
border-radius: 10px;
height: 18px;
position: relative;
overflow: hidden;
}
#storage-used-bar {
background: #2d89ef;
height: 100%;
width: 0;
transition: width 0.25s ease-in-out;
}
#storage-text {
margin-top: 5px;
font-size: 0.9rem;
color: #555;
user-select:none;
}
/* UPLOAD AREA */
#upload-area {
border: 2px dashed #90a4ae;
border-radius: 8px;
padding: 30px;
text-align: center;
color: #607d8b;
cursor: pointer;
transition: background 0.3s;
position: relative;
}
#upload-area.dragover {
background: #d0e8ff;
border-color: #2196f3;
color: #0d47a1;
}
#upload-area input {
position: absolute;
width: 100%;
height: 100%;
top:0; left: 0;
opacity: 0;
cursor: pointer;
}
#upload-area p {
font-size: 1.2rem;
margin: 0;
}
#upload-hint {
margin-top: 8px;
font-size: 0.85rem;
color: #78909c;
}
/* LAYOUT FOR CATEGORIES + FILES */
#container {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
/* CATEGORIES PANEL */
#categories-panel {
width: 250px;
background: white;
border-radius: 8px;
box-shadow: 0 0 6px rgba(0,0,0,0.05);
display: flex;
flex-direction: column;
max-height: 600px;
}
#categories-header {
padding: 1rem;
font-weight: 700;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
#category-list {
overflow-y: auto;
flex: 1;
}
#category-list button.category-item {
all: unset;
display: block;
width: 100%;
padding: 0.6rem 1rem;
text-align: left;
cursor: pointer;
border-left: 4px solid transparent;
color: #455a64;
font-weight: 600;
user-select:none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#category-list button.category-item.selected {
background: #e3f2fd;
border-left: 4px solid #2d89ef;
color: #0d47a1;
}
#category-list button.category-item:hover {
background: #f0f7ff;
}
#categories-controls {
padding: 0.7rem 1rem;
border-top: 1px solid #eee;
display: flex;
gap: 0.5rem;
}
#categories-controls button {
flex: 1;
padding: 0.4rem 0.5rem;
font-size: 0.9rem;
border: none;
border-radius: 4px;
cursor: pointer;
background: #2d89ef;
color: white;
user-select:none;
transition: background 0.2s;
}
#categories-controls button:hover:not(:disabled) {
background: #1b5fbd;
}
#categories-controls button:disabled {
background: #90a4ae;
cursor: default;
}
#rename-category-input {
width: 100%;
padding: 0.3rem 0.5rem;
font-size: 0.9rem;
margin-bottom: 0.5rem;
}
/* FILES PANEL */
#files-panel {
flex: 1;
background: white;
border-radius: 8px;
box-shadow: 0 0 6px rgba(0,0,0,0.05);
display: flex;
flex-direction: column;
max-height: 600px;
overflow: hidden;
}
#files-header {
padding: 1rem;
border-bottom: 1px solid #eee;
font-weight: 700;
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
#files-header .left-controls {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
}
#files-header input[type="text"] {
padding: 0.3rem 0.5rem;
font-size: 1rem;
border-radius: 5px;
border: 1px solid #ddd;
}
#files-list {
overflow-y: auto;
flex: 1;
}
table {
border-collapse: collapse;
width: 100%;
min-width: 560px;
}
th, td {
border-bottom: 1px solid #eee;
padding: 0.7rem 0.8rem;
vertical-align: middle;
}
th {
background: #f9fbfc;
position: sticky;
top: 0;
z-index: 1;
user-select:none;
cursor: pointer;
}
tr:hover {
background: #f1f7ff;
}
td.file-name-cell {
display: flex;
align-items: center;
gap: 0.6rem;
}
td.file-name-cell img.thumbnail {
width: 36px;
height: 36px;
object-fit: cover;
border-radius: 4px;
user-select:none;
}
input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
button.file-action-btn {
border: none;
background: transparent;
cursor: pointer;
color: #2d89ef;
font-size: 1.1rem;
padding: 0 4px;
user-select:none;
}
button.file-action-btn:hover {
color: #0d47a1;
}
/* Scrollbar styling */
#category-list::-webkit-scrollbar,
#files-list::-webkit-scrollbar {
width: 8px;
height: 8px;
}
#category-list::-webkit-scrollbar-thumb,
#files-list::-webkit-scrollbar-thumb {
background-color: rgba(45,137,239,0.3);
border-radius: 10px;
}
/* FOOTER */
footer {
background: #e0e5ea;
padding: 0.5rem 1rem;
font-size: 0.8rem;
color:#666;
text-align: center;
user-select:none;
}
/* MODAL DIALOGS */
.modal-overlay {
position: fixed;
top:0; left:0; right:0; bottom:0;
background: rgba(0,0,0,0.25);
display: flex;
justify-content: center;
align-items: center;
z-index: 2000;
}
.modal {
background: white;
border-radius: 8px;
padding: 1.25rem 1.5rem;
max-width: 400px;
width: 90%;
box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}
.modal h2 {
margin-top: 0;
}
.modal-buttons {
margin-top: 1rem;
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.modal-buttons button {
padding: 0.5rem 1rem;
border-radius: 5px;
border: none;
cursor: pointer;
font-weight: 600;
}
.btn-danger {
background: #e53935;
color: white;
}
.btn-secondary {
background: #90a4ae;
color: white;
}
.btn-primary {
background: #2d89ef;
color: white;
}
.btn-primary:hover {
background: #1976d2;
}
.btn-danger:hover {
background: #b71c1c;
}
.btn-secondary:hover {
background: #718792;
}
/* Responsive */
@media (max-width: 768px) {
#container {
flex-direction: column;
}
#categories-panel {
width: 100%;
max-height: none;
}
#files-panel {
max-height: none;
}
table {
min-width: unset;
}
#files-header {
flex-direction: column;
align-items: start;
gap: 0.5rem;
}
}
</style>
</head>
<body>
<header>Free Cloud Storage — 100TB Limit, 10GB per File</header>
<main>
<section aria-label="Storage usage information">
<div id="storage-usage" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" aria-label="Storage usage bar">
<div id="storage-used-bar"></div>
</div>
<div id="storage-text" aria-live="polite" aria-atomic="true">Used: 0 B / 100 TB</div>
</section>
<section id="upload-area" tabindex="0" aria-label="File upload area" role="button">
<p>Drag and drop your files here or click to upload</p>
<small id="upload-hint">(Max 10GB per file, total 100TB capacity, multiple files accepted)</small>
<input type="file" id="file-input" multiple aria-describedby="upload-hint" />
</section>
<div id="container">
<aside id="categories-panel" aria-label="Categories panel">
<div id="categories-header">
Categories
</div>
<nav id="category-list" role="list" aria-label="List of file categories" tabindex="0">
<!-- Category list buttons inserted here -->
</nav>
<div id="categories-controls" role="group" aria-label="Category controls">
<button id="add-category-btn" aria-label="Add new category" title="Add new category">Add</button>
<button id="rename-category-btn" aria-label="Rename selected category" title="Rename selected category" disabled>Rename</button>
<button id="delete-category-btn" aria-label="Delete selected category" title="Delete selected category" disabled>Delete</button>
</div>
</aside>
<section id="files-panel" aria-label="Files panel">
<div id="files-header">
<div class="left-controls">
<input type="text" id="search-files" placeholder="Search files..." aria-label="Search files by name" autocomplete="off" />
<button id="select-all-files-btn" type="button" title="Select all files" aria-label="Select all files">Select All</button>
<button id="deselect-all-files-btn" type="button" title="Deselect all files" aria-label="Deselect all files">Deselect All</button>
<button id="delete-selected-files-btn" type="button" title="Delete selected files" aria-label="Delete selected files" disabled>Delete Selected</button>
<button id="download-selected-files-btn" type="button" title="Download selected files as ZIP" aria-label="Download selected files" disabled>Download Selected</button>
</div>
</div>
<div id="files-list" tabindex="0" aria-live="polite" aria-atomic="true" aria-relevant="additions removals">
<!-- Files table inserted here -->
</div>
</section>
</div>
</main>
<footer>© Free Cloud Storage • No signup required • Completely client-side • Powered by IndexedDB • <a href="#" id="clear-all-storage" style="color:#2d89ef; text-decoration:none;">Clear All Data</a></footer>
<!-- Confirm Dialog -->
<div id="modal-overlay" class="modal-overlay" hidden role="dialog" aria-modal="true" aria-labelledby="modal-title" aria-describedby="modal-desc">
<div class="modal" tabindex="-1">
<h2 id="modal-title"></h2>
<p id="modal-desc"></p>
<div class="modal-buttons">
<button type="button" id="modal-cancel-btn" class="btn-secondary">Cancel</button>
<button type="button" id="modal-confirm-btn" class="btn-danger">Confirm</button>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js" integrity="sha512-9vt5ri3HCk7vJqjHPt9NBCsLgDsjkIKaIFRGp1TYj9u3FmvuvUsGNVlqXPo2ZwLEpaE1/gTe+HodnWTV+c7ajg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
(function(){
"use strict";
/*******************
* CONSTANTS
*******************/
const MAX_FILE_SIZE = 10 * 1024 * 1024 * 1024; // 10 GB per file
const MAX_TOTAL_STORAGE = 100n * 1024n * 1024n * 1024n * 1024n; // 100 TB in bytes as BigInt
/*******************
* UTILITIES
*******************/
// Convert bytes (Number or BigInt) to human-readable string (B, KB, MB, GB, TB)
function formatBytes(bytes) {
if(typeof bytes === 'bigint') {
if (bytes < 1024n) return bytes.toString() + ' B';
const units = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
let val = bytes;
let i = 0;
while(val >= 1024n && i < units.length - 1) {
val /= 1024n;
i++;
}
// show 2 decimals. This can't exactly format bigint decimals, so we'll fallback to number if safe
if(val <= Number.MAX_SAFE_INTEGER) {
return (Number(val)/1).toFixed(2) + ' ' + units[i];
}
return val.toString() + ' ' + units[i];
}
// regular number bytes version (fallback)
if(bytes === 0) return '0 B';
const k=1024;
const sizes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
const i=Math.floor(Math.log(bytes)/Math.log(k));
return parseFloat((bytes/k**i).toFixed(2))+' '+sizes[i];
}
// Format date/time string
function formatDate(ts) {
const d = new Date(ts);
if(isNaN(d)) return '-';
return d.toLocaleString(undefined, {year:'numeric', month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'});
}
// Generate a UUIDv4 for unique file/category ID
function generateUUID() {
// simplified from https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{
const r = crypto.getRandomValues(new Uint8Array(1))[0]%16|0;
const v = c=='x'?r:(r&0x3|0x8);
return v.toString(16);
});
}
/*******************
* STORAGE KEYS
*******************/
const DB_NAME = 'FreeCloudStorageDB';
const DB_VERSION = 1;
const FILES_STORE = 'files';
const CATEGORIES_STORE = 'categories';
/*******************
* STATE
*******************/
let db;
let categories = []; // Array of { id:string, name:string }
let files = []; // Array of { id:string, name:string, size:bigint, uploadDate:number, categories:[]string, type:string, thumbnailUrl:string|null }
let selectedCategoryId = null; // string or null (null means un-categorized "All files")
let selectedFileIds = new Set();
let searchQuery = '';
let sortField = 'uploadDate';
let sortDirection = 'desc'; // or 'asc'
/*******************
* PERSISTENCE HELPER
*******************/
function openDatabase() {
return new Promise((resolve, reject)=>{
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve(db);
};
request.onupgradeneeded = ev => {
const db = ev.target.result;
if(!db.objectStoreNames.contains(FILES_STORE)){
const filesStore = db.createObjectStore(FILES_STORE, { keyPath: 'id' });
// Indexes for search by name, sorting
filesStore.createIndex('name', 'name', {unique:false});
filesStore.createIndex('uploadDate', 'uploadDate');
}
if(!db.objectStoreNames.contains(CATEGORIES_STORE)){
db.createObjectStore(CATEGORIES_STORE, { keyPath: 'id' });
}
};
});
}
// Get all categories from DB
function getAllCategories() {
return new Promise((resolve,reject)=>{
const tx = db.transaction(CATEGORIES_STORE, 'readonly');
const store = tx.objectStore(CATEGORIES_STORE);
const request = store.getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
// Get all files from DB
function getAllFiles() {
return new Promise((resolve,reject)=>{
const tx = db.transaction(FILES_STORE, 'readonly');
const store = tx.objectStore(FILES_STORE);
const request = store.getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
}
// Add or update category
function saveCategory(category) {
return new Promise((resolve,reject) => {
const tx = db.transaction(CATEGORIES_STORE, 'readwrite');
const store = tx.objectStore(CATEGORIES_STORE);
const req = store.put(category);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
});
}
// Delete category by id
async function deleteCategory(categoryId) {
// Before deleting, remove this category from any files assigned
for(const file of files){
if(file.categories.includes(categoryId)){
file.categories = file.categories.filter(c => c !== categoryId);
await saveFile(file);
}
}
return new Promise((resolve,reject)=>{
const tx = db.transaction(CATEGORIES_STORE, 'readwrite');
const store = tx.objectStore(CATEGORIES_STORE);
const req = store.delete(categoryId);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve();
});
}
// Add or update a file
function saveFile(file) {
return new Promise((resolve,reject) => {
const tx = db.transaction(FILES_STORE, 'readwrite');
const store = tx.objectStore(FILES_STORE);
const req = store.put(file);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
});
}
// Delete a file by id
function deleteFile(fileId) {
return new Promise((resolve,reject) => {
const tx = db.transaction(FILES_STORE, 'readwrite');
const store = tx.objectStore(FILES_STORE);
const req = store.delete(fileId);
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve();
});
}
// Get file data (blob) by id from IndexedDB
function getFileData(fileId) {
return new Promise((resolve,reject) => {
const tx = db.transaction(FILES_STORE, 'readonly');
const store = tx.objectStore(FILES_STORE);
const request = store.get(fileId);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const file = request.result;
if(!file){
reject(new Error('File not found'));
return;
}
resolve(file.data);
};
});
}
/*******************
* FILE READING & THUMBNAILS
*******************/
// Create thumbnail URLs for images & videos
async function createThumbnail(fileBlob, fileType) {
// Only create thumbnail for images (jpeg/png/gif) and short videos (mp4/webm)
if(fileType.startsWith('image/')){
return new Promise((resolve) => {
const url = URL.createObjectURL(fileBlob);
resolve(url);
});
}
// For videos, extract a frame thumbnail (first frame)
if(fileType.startsWith('video/')){
return new Promise((resolve) => {
const video = document.createElement('video');
video.preload = "metadata";
video.src = URL.createObjectURL(fileBlob);
video.muted = true;
video.playsInline = true;
video.onloadeddata = () => {
// draw frame to canvas
const canvas = document.createElement('canvas');
canvas.width = 120;
canvas.height = 90;
const ctx = canvas.getContext('2d');
try {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
resolve(url);
}, 'image/png');
} catch {
resolve(null);
} finally {
URL.revokeObjectURL(video.src);
}
};
video.onerror = () => {
resolve(null);
};
});
}
return null; // no thumbnail for other files
}
/*******************
* STORAGE USAGE CALCULATION
*******************/
// Calculate total used storage (sum of file sizes)
function computeUsedStorage() {
// Use BigInt for summation
let total = 0n;
for(const f of files){
if(typeof f.size === "string") {
total += BigInt(f.size); // fallback in case size stored as string
} else if(typeof f.size === "number"){
total += BigInt(f.size);
} else if(typeof f.size === "bigint") {
total += f.size;
}
}
return total;
}
/*******************
* UI RENDERING
*******************/
const categoryListEl = document.getElementById('category-list');
const filesListEl = document.getElementById('files-list');
const storageUsedBar = document.getElementById('storage-used-bar');
const storageText = document.getElementById('storage-text');
const renameCategoryBtn = document.getElementById('rename-category-btn');
const deleteCategoryBtn = document.getElementById('delete-category-btn');
const addCategoryBtn = document.getElementById('add-category-btn');
const searchFilesInput = document.getElementById('search-files');
const selectAllFilesBtn = document.getElementById('select-all-files-btn');
const deselectAllFilesBtn = document.getElementById('deselect-all-files-btn');
const deleteSelectedFilesBtn = document.getElementById('delete-selected-files-btn');
const downloadSelectedFilesBtn = document.getElementById('download-selected-files-btn');
const fileInput = document.getElementById('file-input');
const uploadArea = document.getElementById('upload-area');
const modalOverlay = document.getElementById('modal-overlay');
const modalTitle = document.getElementById('modal-title');
const modalDesc = document.getElementById('modal-desc');
const modalCancelBtn = document.getElementById('modal-cancel-btn');
const modalConfirmBtn = document.getElementById('modal-confirm-btn');
const clearAllStorageLink = document.getElementById('clear-all-storage');
// Helper: Render categories panel, highlighting selected category
function renderCategories() {
categoryListEl.innerHTML = '';
// Add a special 'All Files' category with id = null
const allFilesBtn = document.createElement('button');
allFilesBtn.textContent = 'All Files';
allFilesBtn.className = 'category-item' + (selectedCategoryId === null ? ' selected' : '');
allFilesBtn.setAttribute('role','listitem');
allFilesBtn.addEventListener('click', () => {
selectCategory(null);
});
allFilesBtn.title = 'Show all files';
categoryListEl.appendChild(allFilesBtn);
for(const cat of categories){
const btn = document.createElement('button');
btn.textContent = cat.name;
btn.className = 'category-item';
btn.setAttribute('role','listitem');
btn.dataset.id = cat.id;
if(selectedCategoryId === cat.id){
btn.classList.add('selected');
}
btn.title = 'Select category: '+cat.name;
btn.addEventListener('click', () => {
selectCategory(cat.id);
});
categoryListEl.appendChild(btn);
}
// Update category control buttons states
const catSelected = categories.find(c => c.id === selectedCategoryId);
renameCategoryBtn.disabled = !catSelected;
deleteCategoryBtn.disabled = !catSelected;
}
// Select category sets the state, clears selected files
function selectCategory(catId) {
selectedCategoryId = catId;
selectedFileIds.clear();
renderCategories();
renderFiles();
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
}
// Render files table based on selected category, search, sort
function renderFiles() {
const filteredFiles = files.filter(f => {
// Filter by category
if(selectedCategoryId && !f.categories.includes(selectedCategoryId))
return false;
// Search filter
if(searchQuery.trim() !== ''){
return f.name.toLowerCase().includes(searchQuery.toLowerCase());
}
return true;
});
// Sort
filteredFiles.sort((a,b)=>{
let valA, valB;
switch(sortField){
case 'name':
valA = a.name.toLowerCase();
valB = b.name.toLowerCase();
break;
case 'size':
valA = (typeof a.size === 'bigint') ? a.size : BigInt(a.size);
valB = (typeof b.size === 'bigint') ? b.size : BigInt(b.size);
break;
case 'uploadDate':
default:
valA = a.uploadDate;
valB = b.uploadDate;
}
if(valA < valB) return sortDirection === 'asc' ? -1 : 1;
if(valA > valB) return sortDirection === 'asc' ? 1 : -1;
return 0;
});
// Build table HTML
if(filteredFiles.length === 0){
filesListEl.innerHTML = '<p style="padding:1rem; color:#78909c;">No files found in this category.</p>';
return;
}
const table = document.createElement('table');
table.setAttribute('role','grid');
table.setAttribute('aria-label', 'List of files');
// Header row
const thead = document.createElement('thead');
const trHead = document.createElement('tr');
// Checkbox all select
const thSelect = document.createElement('th');
thSelect.scope = "col";
const checkboxAll = document.createElement('input');
checkboxAll.type = 'checkbox';
checkboxAll.title = 'Select/Deselect all visible files';
checkboxAll.ariaLabel = 'Select or deselect all visible files';
checkboxAll.addEventListener('change', e =>{
if(e.target.checked){
filteredFiles.forEach(f => selectedFileIds.add(f.id));
} else {
filteredFiles.forEach(f => selectedFileIds.delete(f.id));
}
renderFiles();
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
});
// If all filteredFiles are selected, checkbox checked
const allSelected = filteredFiles.length > 0 && filteredFiles.every(f => selectedFileIds.has(f.id));
checkboxAll.checked = allSelected;
thSelect.appendChild(checkboxAll);
trHead.appendChild(thSelect);
// Columns: Name, Size, Upload Date, Categories, Actions
const columns = [
{key:'name', label:'File Name', sortable:true},
{key:'size', label:'Size', sortable:true},
{key:'uploadDate', label:'Uploaded', sortable:true},
{key:'categories', label:'Categories', sortable:false},
{key:'actions', label:'Actions', sortable:false},
];
for(const col of columns){
const th = document.createElement('th');
th.scope = "col";
th.textContent = col.label;
if(col.sortable){
th.tabIndex = 0;
th.setAttribute('role','button');
th.ariaLabel = `Sort files by ${col.label}`;
th.style.userSelect = 'none';
th.addEventListener('click', () => {
if(sortField === col.key){
sortDirection = (sortDirection === 'asc') ? 'desc' : 'asc';
} else {
sortField = col.key;
sortDirection = 'asc';
}
renderFiles();
});
th.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' '){
e.preventDefault();
th.click();
}
});
if(sortField === col.key){
const arrow = document.createElement('span');
arrow.textContent = sortDirection === 'asc' ? ' ▲' : ' ▼';
arrow.setAttribute('aria-hidden','true');
th.appendChild(arrow);
}
}
trHead.appendChild(th);
}
thead.appendChild(trHead);
table.appendChild(thead);
// Body rows
const tbody = document.createElement('tbody');
for(const file of filteredFiles){
const tr = document.createElement('tr');
tr.tabIndex = 0;
// First cell: selectable checkbox
const tdSelect = document.createElement('td');
const fileCheckbox = document.createElement('input');
fileCheckbox.type = 'checkbox';
fileCheckbox.checked = selectedFileIds.has(file.id);
fileCheckbox.title = `Select file "${file.name}"`;
fileCheckbox.ariaLabel = `Select file ${file.name}`;
fileCheckbox.addEventListener('click', e=>{
e.stopPropagation();
});
fileCheckbox.addEventListener('change', e => {
if(e.target.checked){
selectedFileIds.add(file.id);
} else {
selectedFileIds.delete(file.id);
}
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
renderFiles();
});
tdSelect.appendChild(fileCheckbox);
tr.appendChild(tdSelect);
// File Name with optional thumbnail
const tdName = document.createElement('td');
tdName.className = 'file-name-cell';
if(file.thumbnailUrl){
const img = document.createElement('img');
img.src = file.thumbnailUrl;
img.alt = `Thumbnail of ${file.name}`;
img.className = 'thumbnail';
img.loading = "lazy";
tdName.appendChild(img);
} else {
// use an icon depending on file type
const iconSpan = document.createElement('span');
iconSpan.style.fontSize = '1.4rem';
iconSpan.style.color = '#90a4ae';
switch(file.type){
case 'video/mp4':
case file.type.startsWith('video/') && file.type:
iconSpan.textContent = '🎥';
break;
case 'audio/mp3':
case file.type.startsWith('audio/') && file.type:
iconSpan.textContent = '🎵';
break;
case 'application/x-iso' || file.name.endsWith('.iso'):
iconSpan.textContent = '📦';
break;
default:
iconSpan.textContent = '📄';
}
tdName.appendChild(iconSpan);
}
const nameSpan = document.createElement('span');
nameSpan.textContent = file.name;
nameSpan.title = file.name;
tdName.appendChild(nameSpan);
tr.appendChild(tdName);
// Size
const tdSize = document.createElement('td');
tdSize.textContent = formatBytes(file.size);
tr.appendChild(tdSize);
// Upload date
const tdDate = document.createElement('td');
tdDate.textContent = formatDate(file.uploadDate);
tr.appendChild(tdDate);
// Categories
const tdCats = document.createElement('td');
if(file.categories.length === 0) {
tdCats.textContent = '(None)';
tdCats.style.color = '#999';
} else {
let catNames = file.categories
.map(cid => {
const cat = categories.find(c => c.id === cid);
return cat ? cat.name : null;
})
.filter(Boolean);
tdCats.textContent = catNames.join(', ');
}
tr.appendChild(tdCats);
// Actions
const tdActions = document.createElement('td');
// Download button
const dlBtn = document.createElement('button');
dlBtn.innerHTML = '⬇️';
dlBtn.className = 'file-action-btn';
dlBtn.title = `Download file "${file.name}"`;
dlBtn.ariaLabel = `Download file ${file.name}`;
dlBtn.type = 'button';
dlBtn.addEventListener('click', async e => {
e.stopPropagation();
await downloadSingleFile(file);
});
tdActions.appendChild(dlBtn);
// Delete button
const delBtn = document.createElement('button');
delBtn.innerHTML = '🗑️';
delBtn.className = 'file-action-btn';
delBtn.title = `Delete file "${file.name}"`;
delBtn.ariaLabel = `Delete file ${file.name}`;
delBtn.type = 'button';
delBtn.addEventListener('click', e => {
e.stopPropagation();
confirmDeletion(`Are you sure you want to delete the file "${file.name}"?`, async () => {
await deleteSingleFile(file.id);
});
});
tdActions.appendChild(delBtn);
tr.appendChild(tdActions);
// Click row toggles selection
tr.addEventListener('click', () => {
if(selectedFileIds.has(file.id)){
selectedFileIds.delete(file.id);
} else {
selectedFileIds.add(file.id);
}
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
renderFiles();
});
tbody.appendChild(tr);
}
table.appendChild(tbody);
filesListEl.innerHTML = '';
filesListEl.appendChild(table);
}
// Update storage usage UI
function updateStorageUsageUI(){
const used = computeUsedStorage();
let usedPercent = 0;
if(used > 0 && MAX_TOTAL_STORAGE > 0) {
usedPercent = Number((used * 10000n) / MAX_TOTAL_STORAGE)/100; // percentage with 2 decimals
}
storageUsedBar.style.width = usedPercent + '%';
storageUsedBar.parentNode.setAttribute('aria-valuenow', usedPercent.toFixed(2).toString());
storageText.textContent = `Used: ${formatBytes(used)} / ${formatBytes(MAX_TOTAL_STORAGE)}`;
}
// Update Delete Selected button enabled state
function updateDeleteSelectedBtn(){
deleteSelectedFilesBtn.disabled = selectedFileIds.size === 0;
}
// Update Download Selected button enabled state
function updateDownloadSelectedBtn(){
downloadSelectedFilesBtn.disabled = selectedFileIds.size === 0;
}
/*******************
* FILE UPLOAD HANDLING
*******************/
// Check if a file can be uploaded (size and total capacity)
function canUploadFile(fileSize) {
const used = computeUsedStorage();
const newTotal = used + BigInt(fileSize);
if(fileSize > MAX_FILE_SIZE) return {ok:false, error: `File size exceeds 10GB limit.`};
if(newTotal > MAX_TOTAL_STORAGE) return {ok:false, error: `Insufficient storage space available.`};
return {ok:true};
}
// Save uploaded files into IndexedDB and update UI
async function handleFileUpload(fileList) {
if(!fileList || fileList.length === 0) return;
const tooLargeFiles = [];
const tooMuchStorage = [];
for(let f of fileList){
const check = canUploadFile(f.size);
if(!check.ok){
if(check.error.includes('10GB')) tooLargeFiles.push(f.name);
else if(check.error.includes('Insufficient')) tooMuchStorage.push(f.name);
continue;
}
// Read file data as Blob and create thumbnail if possible
let thumbnailUrl = null;
try {
thumbnailUrl = await createThumbnail(f, f.type);
} catch {
thumbnailUrl = null;
}
// Save file data in IndexedDB
const id = generateUUID();
const fileObj = {
id,
name: f.name,
size: BigInt(f.size),
uploadDate: Date.now(),
categories: selectedCategoryId ? [selectedCategoryId] : [],
type: f.type || '',
data: f, // Blob object saved directly
thumbnailUrl,
};
await saveFile(fileObj);
files.push(fileObj);
// Update UI after each file upload so progress appears smoother
updateStorageUsageUI();
renderFiles();
}
if(tooLargeFiles.length > 0){
alert(`Some files were skipped because they exceed 10GB limit:\n- ${tooLargeFiles.join('\n- ')}`);
}
if(tooMuchStorage.length > 0){
alert(`Some files were skipped because uploading them would exceed the 100TB storage limit:\n- ${tooMuchStorage.join('\n- ')}`);
}
}
/*******************
* FILE DOWNLOAD
*******************/
async function downloadSingleFile(file) {
try {
const data = await getFileData(file.id);
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = file.name;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 100);
} catch (e) {
alert('Error downloading file: ' + e.message);
}
}
// Download multiple files as ZIP archive
async function downloadMultipleFilesZip(fileIds) {
if(fileIds.size === 0) return;
downloadSelectedFilesBtn.disabled = true;
downloadSelectedFilesBtn.textContent = 'Preparing ZIP...';
try {
const zip = new JSZip();
let count = 0;
let total = fileIds.size;
for(const fileId of fileIds){
const file = files.find(f=>f.id === fileId);
if(!file) continue;
const data = await getFileData(fileId);
// Add file to zip
zip.file(file.name, data);
count++;
}
const zipBlob = await zip.generateAsync({type:'blob'}, (metadata) => {
// We could update progress here if needed
});
const url = URL.createObjectURL(zipBlob);
const a = document.createElement('a');
a.href = url;
let zipName = 'files.zip';
if(selectedCategoryId){
const cat = categories.find(c=>c.id===selectedCategoryId);
if(cat) zipName = cat.name.replace(/\W+/g,'_') + '.zip';
}
a.download = zipName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
a.remove();
}, 100);
} catch (e) {
alert('Failed to create ZIP archive: ' + e.message);
} finally {
downloadSelectedFilesBtn.disabled = false;
downloadSelectedFilesBtn.textContent = 'Download Selected';
}
}
/*******************
* FILE DELETE
*******************/
async function deleteSingleFile(fileId) {
await deleteFile(fileId);
files = files.filter(f => f.id !== fileId);
selectedFileIds.delete(fileId);
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
updateStorageUsageUI();
renderFiles();
}
async function deleteMultipleFiles(fileIds) {
for(const fid of fileIds) {
await deleteFile(fid);
selectedFileIds.delete(fid);
files = files.filter(f => f.id !== fid);
}
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
updateStorageUsageUI();
renderFiles();
}
/*******************
* CATEGORY MANAGEMENT
*******************/
async function addCategory() {
let name = prompt('Enter new category name:');
if(!name) return;
name = name.trim();
if(name.length === 0){
alert('Category name cannot be empty.');
return;
}
if(categories.some(c => c.name.toLowerCase() === name.toLowerCase())){
alert('Category name already exists.');
return;
}
const newCat = {id: generateUUID(), name};
await saveCategory(newCat);
categories.push(newCat);
selectCategory(newCat.id);
}
async function renameCategory() {
if(!selectedCategoryId) return;
const cat = categories.find(c => c.id === selectedCategoryId);
if(!cat) return;
let newName = prompt('Rename category:', cat.name);
if(!newName) return;
newName = newName.trim();
if(newName.length === 0){
alert('Category name cannot be empty.');
return;
}
if(newName.toLowerCase() === cat.name.toLowerCase()) return; // no change
if(categories.some(c => c.name.toLowerCase() === newName.toLowerCase() && c.id !== cat.id)){
alert('Category name already exists.');
return;
}
cat.name = newName;
await saveCategory(cat);
renderCategories();
renderFiles();
}
async function deleteCategoryHandler() {
if(!selectedCategoryId) return;
const cat = categories.find(c => c.id === selectedCategoryId);
if(!cat) return;
confirmDeletion(
`Are you sure you want to delete the category "${cat.name}"? This will remove this category from all files.`,
async () => {
await deleteCategory(cat.id);
categories = categories.filter(c => c.id !== cat.id);
selectCategory(null);
renderCategories();
renderFiles();
}
);
}
/*******************
* SEARCH, SELECT ALL/DESELECT ALL, DELETE SELECTED
*******************/
function onSearchFilesInput() {
searchQuery = searchFilesInput.value;
renderFiles();
}
function selectAllFilesVisible() {
const filteredFiles = files.filter(f => {
if(selectedCategoryId && !f.categories.includes(selectedCategoryId))
return false;
if(searchQuery.trim() !== ''){
return f.name.toLowerCase().includes(searchQuery.toLowerCase());
}
return true;
});
filteredFiles.forEach(f => selectedFileIds.add(f.id));
renderFiles();
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
}
function deselectAllFiles() {
selectedFileIds.clear();
renderFiles();
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
}
async function deleteSelectedFiles() {
if(selectedFileIds.size === 0) return;
confirmDeletion(`Are you sure you want to delete the ${selectedFileIds.size} selected file(s)?`, async () => {
await deleteMultipleFiles(selectedFileIds);
});
}
/*******************
* DRAG & DROP UPLOAD SUPPORT
*******************/
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight() {
uploadArea.classList.add('dragover');
}
function unhighlight() {
uploadArea.classList.remove('dragover');
}
uploadArea.addEventListener('dragenter', e => {
preventDefaults(e);
highlight();
});
uploadArea.addEventListener('dragover', e => {
preventDefaults(e);
highlight();
});
uploadArea.addEventListener('dragleave', e => {
preventDefaults(e);
unhighlight();
});
uploadArea.addEventListener('drop', async e => {
preventDefaults(e);
unhighlight();
const dt = e.dataTransfer;
if(dt && dt.files.length > 0){
await handleFileUpload(dt.files);
}
});
// Upload area click opens file input
uploadArea.addEventListener('click', () => {
fileInput.click();
});
uploadArea.addEventListener('keydown', e => {
if(e.key === 'Enter' || e.key === ' '){
e.preventDefault();
fileInput.click();
}
});
fileInput.addEventListener('change', async () => {
if(fileInput.files.length > 0){
await handleFileUpload(fileInput.files);
fileInput.value = ''; // reset input for next uploads
}
});
/*******************
* MODAL CONFIRMATION MANAGEMENT
*******************/
let currentConfirmCallback = null;
function confirmDeletion(message, onConfirm) {
modalTitle.textContent = 'Confirm Deletion';
modalDesc.textContent = message;
modalOverlay.hidden = false;
modalConfirmBtn.focus();
currentConfirmCallback = onConfirm;
}
modalCancelBtn.addEventListener('click', () => {
modalOverlay.hidden = true;
currentConfirmCallback = null;
});
modalConfirmBtn.addEventListener('click', async () => {
if(currentConfirmCallback){
await currentConfirmCallback();
}
modalOverlay.hidden = true;
currentConfirmCallback = null;
});
// Close modal on Escape key
window.addEventListener('keydown', (e) => {
if(modalOverlay.hidden) return;
if(e.key === 'Escape'){
modalOverlay.hidden = true;
currentConfirmCallback = null;
}
});
/*******************
* CLEAR ALL STORAGE (footer link)
*******************/
clearAllStorageLink.addEventListener('click', async (e) => {
e.preventDefault();
confirmDeletion('This will clear all files and categories permanently. Are you sure?', async () => {
await clearAllData();
});
});
async function clearAllData() {
const tx1 = db.transaction(FILES_STORE, 'readwrite');
const tx2 = db.transaction(CATEGORIES_STORE, 'readwrite');
await Promise.all([
new Promise((res,rej)=>{
const store = tx1.objectStore(FILES_STORE);
const req = store.clear();
req.onsuccess = () => res();
req.onerror = () => rej(req.error);
}),
new Promise((res,rej)=>{
const store = tx2.objectStore(CATEGORIES_STORE);
const req = store.clear();
req.onsuccess = () => res();
req.onerror = () => rej(req.error);
}),
]);
files = [];
categories = [];
selectedCategoryId = null;
selectedFileIds.clear();
updateDeleteSelectedBtn();
updateDownloadSelectedBtn();
updateStorageUsageUI();
renderCategories();
renderFiles();
}
/*******************
* INITIAL LOAD
*******************/
async function init() {
try {
await openDatabase();
categories = await getAllCategories();
files = await getAllFiles();
// We must load thumbnailUrls for files that lack it (in case older data)
for(const file of files){
if(file.thumbnailUrl === undefined || file.thumbnailUrl === null){
try {
const thumbnailUrl = await createThumbnail(file.data, file.type);
file.thumbnailUrl = thumbnailUrl;
await saveFile(file);
} catch(e){}
}
}
selectCategory(null);
renderCategories();
renderFiles();
updateStorageUsageUI();
} catch (e){
alert('Failed to initialize: '+ e.message);
}
}
init();
/*******************
* BUTTON EVENT LISTENERS
*******************/
addCategoryBtn.addEventListener('click', async () => {
await addCategory();
});
renameCategoryBtn.addEventListener('click', async () => {
await renameCategory();
});
deleteCategoryBtn.addEventListener('click', async () => {
await deleteCategoryHandler();
});
searchFilesInput.addEventListener('input', () => {
onSearchFilesInput();
});
selectAllFilesBtn.addEventListener('click', () => {
selectAllFilesVisible();
});
deselectAllFilesBtn.addEventListener('click', () => {
deselectAllFiles();
});
deleteSelectedFilesBtn.addEventListener('click', async () => {
await deleteSelectedFiles();
});
downloadSelectedFilesBtn.addEventListener('click', async () => {
await downloadMultipleFilesZip(selectedFileIds);
});
})();
</script>
</body>
</html>