atlus/frontend/js/apps/files.js
roberts f9743bb29a Initial commit — Atlus web desktop environment for SBCs
Full-stack implementation: FastAPI backend with PAM auth, WebSocket
stats/terminal, and vanilla JS frontend with tiling desktop shell.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 16:53:46 -05:00

353 lines
12 KiB
JavaScript

/* Atlus — File Manager app */
(function () {
'use strict';
let container = null;
let currentPath = '/';
let fileListEl = null;
let breadcrumbEl = null;
let sidebarEl = null;
let selectedFiles = new Set();
let contextMenuEl = null;
const FILE_ICONS = {
dir: '📁',
file: '📄',
image: '🖼',
video: '🎬',
audio: '🎵',
archive: '📦',
code: '📝',
text: '📝',
};
function getFileIcon(entry) {
if (entry.is_dir) return FILE_ICONS.dir;
const ext = entry.name.split('.').pop().toLowerCase();
if (['jpg','jpeg','png','gif','bmp','svg','webp','fits','fit'].includes(ext)) return FILE_ICONS.image;
if (['mp4','mkv','avi','mov','webm'].includes(ext)) return FILE_ICONS.video;
if (['mp3','flac','wav','ogg','aac'].includes(ext)) return FILE_ICONS.audio;
if (['zip','tar','gz','bz2','xz','7z','rar'].includes(ext)) return FILE_ICONS.archive;
if (['js','py','sh','css','html','json','yml','yaml','toml','rs','go','c','cpp','h'].includes(ext)) return FILE_ICONS.code;
return FILE_ICONS.file;
}
function formatSize(bytes) {
return Atlus.formatBytes(bytes);
}
function formatDate(ts) {
return new Date(ts * 1000).toLocaleString('en-US', {
month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false,
});
}
async function loadDirectory(path) {
currentPath = path;
selectedFiles.clear();
updateBreadcrumb();
try {
const res = await Atlus.apiFetch(`/api/files/list?path=${encodeURIComponent(path)}`);
if (!res.ok) throw new Error('Failed to load directory');
const entries = await res.json();
renderFileList(entries);
} catch (e) {
fileListEl.innerHTML = `<div style="padding:16px;color:var(--status-red);font-family:var(--font-mono);font-size:13px;">Error: ${e.message}</div>`;
}
// Update sidebar active
if (sidebarEl) {
sidebarEl.querySelectorAll('.sidebar-item').forEach(item => {
item.classList.toggle('active', item.dataset.path === path);
});
}
}
function renderFileList(entries) {
fileListEl.innerHTML = '';
// Parent directory entry
if (currentPath !== '/') {
const parentRow = document.createElement('div');
parentRow.className = 'file-row';
parentRow.innerHTML = `
<div class="file-name"><span class="file-icon dir">..</span><span>..</span></div>
<span class="file-size"></span>
<span class="file-modified"></span>
<span class="file-perms"></span>
`;
parentRow.addEventListener('click', () => {
const parent = currentPath.replace(/\/[^/]+\/?$/, '') || '/';
loadDirectory(parent);
});
fileListEl.appendChild(parentRow);
}
entries.forEach(entry => {
const row = document.createElement('div');
row.className = 'file-row';
row.dataset.path = entry.path;
const icon = getFileIcon(entry);
row.innerHTML = `
<div class="file-name">
<span class="file-icon ${entry.is_dir ? 'dir' : ''}">${icon}</span>
<span>${entry.name}</span>
</div>
<span class="file-size">${entry.is_dir ? '--' : formatSize(entry.size)}</span>
<span class="file-modified">${formatDate(entry.modified)}</span>
<span class="file-perms">${entry.permissions}</span>
`;
row.addEventListener('click', () => {
if (entry.is_dir) {
loadDirectory(entry.path);
} else {
// Toggle selection
row.classList.toggle('selected');
if (selectedFiles.has(entry.path)) {
selectedFiles.delete(entry.path);
} else {
selectedFiles.add(entry.path);
}
}
});
// Long-press for context menu
let pressTimer;
row.addEventListener('touchstart', (e) => {
pressTimer = setTimeout(() => showContextMenu(e, entry), 500);
});
row.addEventListener('touchend', () => clearTimeout(pressTimer));
row.addEventListener('touchmove', () => clearTimeout(pressTimer));
// Right-click fallback
row.addEventListener('contextmenu', (e) => {
e.preventDefault();
showContextMenu(e, entry);
});
fileListEl.appendChild(row);
});
}
function updateBreadcrumb() {
breadcrumbEl.innerHTML = '';
const parts = currentPath.split('/').filter(Boolean);
// Root
const root = document.createElement('button');
root.className = 'breadcrumb-segment';
root.textContent = '/';
root.addEventListener('click', () => loadDirectory('/'));
breadcrumbEl.appendChild(root);
let path = '';
parts.forEach((part, i) => {
path += '/' + part;
const sep = document.createElement('span');
sep.className = 'breadcrumb-sep';
sep.textContent = '/';
breadcrumbEl.appendChild(sep);
const seg = document.createElement('button');
seg.className = 'breadcrumb-segment';
seg.textContent = part;
const segPath = path;
seg.addEventListener('click', () => loadDirectory(segPath));
breadcrumbEl.appendChild(seg);
});
}
function showContextMenu(e, entry) {
hideContextMenu();
contextMenuEl = document.createElement('div');
contextMenuEl.className = 'file-context-menu';
const items = [
{ label: 'Open', action: () => entry.is_dir ? loadDirectory(entry.path) : previewFile(entry) },
{ label: 'Rename', action: () => renameFile(entry) },
{ label: 'Copy', action: () => { /* clipboard */ } },
{ label: 'Move', action: () => { /* clipboard */ } },
{ sep: true },
{ label: 'Delete', action: () => deleteFile(entry), danger: true },
];
items.forEach(item => {
if (item.sep) {
const sep = document.createElement('div');
sep.className = 'context-sep';
contextMenuEl.appendChild(sep);
return;
}
const btn = document.createElement('button');
btn.className = 'context-item' + (item.danger ? ' danger' : '');
btn.textContent = item.label;
btn.addEventListener('click', () => {
hideContextMenu();
item.action();
});
contextMenuEl.appendChild(btn);
});
// Position
const x = e.touches ? e.touches[0].clientX : e.clientX;
const y = e.touches ? e.touches[0].clientY : e.clientY;
contextMenuEl.style.left = x + 'px';
contextMenuEl.style.top = y + 'px';
document.body.appendChild(contextMenuEl);
// Close on outside click
setTimeout(() => {
document.addEventListener('click', hideContextMenu, { once: true });
}, 10);
}
function hideContextMenu() {
if (contextMenuEl) {
contextMenuEl.remove();
contextMenuEl = null;
}
}
async function deleteFile(entry) {
if (!confirm(`Delete "${entry.name}"?`)) return;
await Atlus.apiFetch('/api/files/delete', {
method: 'POST',
body: { path: entry.path },
});
loadDirectory(currentPath);
}
async function renameFile(entry) {
const newName = prompt('New name:', entry.name);
if (!newName || newName === entry.name) return;
await Atlus.apiFetch('/api/files/rename', {
method: 'POST',
body: { old_path: entry.path, new_name: newName },
});
loadDirectory(currentPath);
}
async function previewFile(entry) {
// Simple text preview
try {
const res = await Atlus.apiFetch(`/api/files/read?path=${encodeURIComponent(entry.path)}`);
if (res.ok) {
const data = await res.json();
alert(data.content.substring(0, 2000));
}
} catch (e) {}
}
async function loadMounts() {
try {
const res = await Atlus.apiFetch('/api/files/mounts');
if (!res.ok) return;
const mounts = await res.json();
// Add mount entries to sidebar
const heading = document.createElement('div');
heading.className = 'sidebar-heading';
heading.textContent = 'MOUNTS';
sidebarEl.appendChild(heading);
mounts.forEach(mount => {
if (mount.mountpoint === '/') return; // Already in sidebar
const item = document.createElement('button');
item.className = 'sidebar-item';
item.dataset.path = mount.mountpoint;
item.innerHTML = `<span class="sidebar-icon">💾</span>${mount.mountpoint.split('/').pop() || mount.mountpoint}`;
item.addEventListener('click', () => loadDirectory(mount.mountpoint));
sidebarEl.appendChild(item);
});
} catch (e) {}
}
Atlus.registerApp('files', {
title: 'Files',
init(el) {
container = el;
container.classList.add('app-files');
// Toolbar
const toolbar = document.createElement('div');
toolbar.className = 'files-toolbar';
breadcrumbEl = document.createElement('div');
breadcrumbEl.className = 'files-breadcrumb';
toolbar.appendChild(breadcrumbEl);
// Refresh button
const refreshBtn = document.createElement('button');
refreshBtn.className = 'files-action-btn';
refreshBtn.textContent = '↻';
refreshBtn.title = 'Refresh';
refreshBtn.addEventListener('click', () => loadDirectory(currentPath));
toolbar.appendChild(refreshBtn);
container.appendChild(toolbar);
// Body
const body = document.createElement('div');
body.className = 'files-body';
// Sidebar
sidebarEl = document.createElement('div');
sidebarEl.className = 'files-sidebar';
const homeHeading = document.createElement('div');
homeHeading.className = 'sidebar-heading';
homeHeading.textContent = 'PLACES';
sidebarEl.appendChild(homeHeading);
const places = [
{ icon: '🏠', label: 'Home', path: `/home/${Atlus.user}` },
{ icon: '/', label: 'Root', path: '/' },
{ icon: '📁', label: 'tmp', path: '/tmp' },
];
places.forEach(p => {
const item = document.createElement('button');
item.className = 'sidebar-item';
item.dataset.path = p.path;
item.innerHTML = `<span class="sidebar-icon">${p.icon}</span>${p.label}`;
item.addEventListener('click', () => loadDirectory(p.path));
sidebarEl.appendChild(item);
});
body.appendChild(sidebarEl);
// File list panel
const listPanel = document.createElement('div');
listPanel.className = 'files-list-panel';
const header = document.createElement('div');
header.className = 'files-list-header';
header.innerHTML = '<span>Name</span><span>Size</span><span>Modified</span><span>Perms</span>';
listPanel.appendChild(header);
fileListEl = document.createElement('div');
fileListEl.className = 'files-list';
listPanel.appendChild(fileListEl);
body.appendChild(listPanel);
container.appendChild(body);
// Load initial directory
loadDirectory(`/home/${Atlus.user}`);
loadMounts();
},
destroy() {
hideContextMenu();
container = null;
fileListEl = null;
breadcrumbEl = null;
sidebarEl = null;
currentPath = '/';
selectedFiles.clear();
},
});
})();