(() => {
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);
let currentFile = null;
let galleryOffset = 0;
let tableOffset = 0;
const PER_PAGE = 60;
let compareSet = new Map();
let searchText = '';
let dataCache = null;
let drawerRowIdx = null;
let drawerNavList = [];
function showLoading() { $('#loading').classList.remove('hidden'); }
function hideLoading() { $('#loading').classList.add('hidden'); }
function fmtSize(b) {
if (!b) return '—';
if (b < 1024) return b + ' B';
if (b < 1048576) return (b / 1024).toFixed(1) + ' KB';
if (b < 1073741824) return (b / 1048576).toFixed(1) + ' MB';
return (b / 1073741824).toFixed(2) + ' GB';
}
function fmtNum(n) {
if (n == null) return '—';
return Number.isInteger(n) ? n.toLocaleString() : n.toLocaleString(undefined, { maximumFractionDigits: 2 });
}
function esc(s) {
const d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
function trunc(s, len) {
if (!s) return '';
return s.length > len ? s.slice(0, len) + '…' : s;
}
function imgSrc(fid, rowIdx, col) {
return `/api/image/${fid}/${rowIdx}/${col}`;
}
// ── Folder browser ───────────────────────────────────────────────
function openSidebar(path) {
$('#sidebar').classList.add('open');
$('#sidebar-backdrop').classList.add('open');
loadFolder(path || '');
}
function closeSidebar() {
$('#sidebar').classList.remove('open');
$('#sidebar-backdrop').classList.remove('open');
}
async function loadFolder(path) {
try {
const res = await fetch(`/api/browse?path=${encodeURIComponent(path)}`);
if (!res.ok) throw new Error();
const data = await res.json();
renderBreadcrumb(data.path);
renderFolderList(data);
} catch (e) { console.error(e); }
}
function renderBreadcrumb(path) {
const parts = path.split('/').filter(Boolean);
let h = '/';
let acc = '';
parts.forEach((p) => {
acc += '/' + p;
h += '/';
h += '' + esc(p) + '';
});
$('#breadcrumb').innerHTML = h;
$$('.breadcrumb-item').forEach((el) => el.addEventListener('click', () => loadFolder(el.dataset.path)));
}
function renderFolderList(data) {
let h = '';
if (data.parent) {
h += '
..Up
';
}
data.entries.forEach((e) => {
let icon = '📄', cls = 'is-file';
if (e.is_dir) { icon = '📁'; cls = 'is-dir'; }
else if (e.is_dataset) { icon = '◉'; cls = 'is-dataset'; }
h += '';
h += '' + icon + '';
h += '' + esc(e.name) + '';
if (!e.is_dir) h += '' + fmtSize(e.size) + '';
h += '
';
});
if (!data.entries.length) h = 'Empty directory
';
$('#folder-list').innerHTML = h;
$$('.folder-entry').forEach((el) => el.addEventListener('click', () => {
if (el.dataset.dir === 'true') loadFolder(el.dataset.path);
else if (el.dataset.ds === 'true') {
$('#file-path').value = el.dataset.path;
closeSidebar();
openFile(el.dataset.path);
}
}));
}
$('#btn-browse').addEventListener('click', () => openSidebar(''));
$('#btn-close-sidebar').addEventListener('click', closeSidebar);
$('#sidebar-backdrop').addEventListener('click', closeSidebar);
// ── Open file ────────────────────────────────────────────────────
async function openFile(path) {
showLoading();
try {
const res = await fetch('/api/open', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path }),
});
if (!res.ok) { const e = await res.json(); alert(e.detail || 'Failed to open file'); return; }
currentFile = await res.json();
renderInfoBar();
renderColumnSelects();
galleryOffset = 0;
tableOffset = 0;
compareSet.clear();
updateCompareBadge();
closeDrawer();
$('#main').classList.remove('hidden');
$('#welcome').classList.add('hidden');
switchView('gallery');
} finally { hideLoading(); }
}
function renderInfoBar() {
$('#pill-file').textContent = currentFile.path.split('/').pop();
$('#pill-rows').textContent = fmtNum(currentFile.num_rows) + ' rows';
$('#pill-cols').textContent = currentFile.columns.length + ' cols';
}
function renderColumnSelects() {
const imgCols = currentFile.columns.filter((c) => c.is_image);
const textCols = currentFile.columns.filter((c) => !c.is_image);
$('#sel-img-col').innerHTML = imgCols.map((c) => '').join('');
$('#sel-txt-col').innerHTML = '' + textCols.map((c) => '').join('');
const prefer = textCols.find((c) => c.name === 'text') || textCols[0];
if (prefer) {
const sel = $('#sel-txt-col');
for (let i = 0; i < sel.options.length; i++) {
if (sel.options[i].value === prefer.name) { sel.selectedIndex = i; break; }
}
}
}
// ── View switching ───────────────────────────────────────────────
function switchView(name) {
$$('.vs-btn').forEach((b) => b.classList.toggle('active', b.dataset.view === name));
$$('.view').forEach((v) => v.classList.add('hidden'));
$('#view-' + name).classList.remove('hidden');
if (name === 'gallery') loadGallery();
else if (name === 'table') loadTable();
else if (name === 'compare') renderCompare();
}
$$('.vs-btn').forEach((b) => b.addEventListener('click', () => switchView(b.dataset.view)));
// ── Search ───────────────────────────────────────────────────────
let searchTimer;
$('#search-input').addEventListener('input', (e) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
searchText = e.target.value.trim().toLowerCase();
galleryOffset = 0;
tableOffset = 0;
const active = $('.vs-btn.active');
if (active) {
const v = active.dataset.view;
if (v === 'gallery') loadGallery();
else if (v === 'table') loadTable();
}
}, 200);
});
// ── Gallery ──────────────────────────────────────────────────────
async function loadGallery() {
if (!currentFile) return;
showLoading();
try {
const imgCol = $('#sel-img-col').value;
const txtCol = $('#sel-txt-col').value;
if (!imgCol) { hideLoading(); return; }
const cols = [imgCol];
if (txtCol) cols.push(txtCol);
const res = await fetch('/api/data/' + currentFile.id + '?offset=' + galleryOffset + '&limit=' + PER_PAGE + '&columns=' + cols.join(','));
if (!res.ok) throw new Error();
const data = await res.json();
dataCache = data;
drawerNavList = data.data.map((_, ri) => data.offset + ri);
renderGallery(data, imgCol, txtCol);
} finally { hideLoading(); }
}
function renderGallery(data, imgCol, txtCol) {
const totalPages = Math.ceil(data.total / PER_PAGE);
const page = Math.floor(data.offset / PER_PAGE) + 1;
$('#gallery-page').textContent = page + '/' + totalPages + ' (' + fmtNum(data.total) + ')';
$('#gallery-prev').disabled = data.offset === 0;
$('#gallery-next').disabled = data.offset + PER_PAGE >= data.total;
const fid = currentFile.id;
let h = '';
data.data.forEach((row, ri) => {
const rowIdx = data.offset + ri;
const caption = txtCol ? (row[txtCol] || '') : '';
const w = row.width || '';
const hm = row.height || '';
const sel = compareSet.has(rowIdx);
const isOpen = drawerRowIdx === rowIdx;
h += '';
h += '
#' + (rowIdx + 1) + '';
h += '
✓';
h += '
 + ')
';
if (w && hm) h += '
' + w + '×' + hm + '';
if (caption) h += '
' + esc(trunc(caption, 140)) + '
';
h += '
';
});
if (!data.data.length) {
h = 'No matching rows
';
}
$('#gallery-grid').innerHTML = h;
}
// Gallery event delegation
$('#gallery-grid').addEventListener('click', (e) => {
const img = e.target.closest('.card-img');
const card = e.target.closest('.card');
if (!card) return;
const rowIdx = parseInt(card.dataset.row);
if (e.shiftKey || e.metaKey || e.ctrlKey) {
toggleCompare(rowIdx);
return;
}
if (img) openDrawer(rowIdx);
});
$('#sel-img-col').addEventListener('change', () => { galleryOffset = 0; loadGallery(); });
$('#sel-txt-col').addEventListener('change', () => { galleryOffset = 0; loadGallery(); });
$('#sel-thumb-size').addEventListener('change', (e) => {
$('#gallery-grid').style.gridTemplateColumns = 'repeat(auto-fill, minmax(' + e.target.value + 'px, 1fr))';
});
$('#gallery-prev').addEventListener('click', () => { galleryOffset = Math.max(0, galleryOffset - PER_PAGE); loadGallery(); });
$('#gallery-next').addEventListener('click', () => { galleryOffset += PER_PAGE; loadGallery(); });
// ── Compare ──────────────────────────────────────────────────────
function toggleCompare(rowIdx) {
const imgCol = $('#sel-img-col').value;
if (compareSet.has(rowIdx)) {
compareSet.delete(rowIdx);
} else {
if (compareSet.size >= 4) {
const oldest = compareSet.keys().next().value;
compareSet.delete(oldest);
const oldCard = document.querySelector('.card[data-row="' + oldest + '"]');
if (oldCard) oldCard.classList.remove('selected');
}
compareSet.set(rowIdx, { src: imgSrc(currentFile.id, rowIdx, imgCol), rowIdx });
}
updateCompareBadge();
const card = document.querySelector('.card[data-row="' + rowIdx + '"]');
if (card) card.classList.toggle('selected', compareSet.has(rowIdx));
}
function updateCompareBadge() {
const badge = $('#compare-badge');
const n = compareSet.size;
badge.textContent = n;
badge.classList.toggle('hidden', n === 0);
}
function renderCompare() {
const content = $('#compare-content');
const empty = $('#compare-empty');
if (compareSet.size < 2) {
content.classList.add('hidden');
empty.classList.remove('hidden');
return;
}
content.classList.remove('hidden');
empty.classList.add('hidden');
const txtCol = $('#sel-txt-col').value;
let h = '';
let idx = 0;
for (const [rowIdx, item] of compareSet) {
const label = String.fromCharCode(65 + idx);
h += '';
h += '
' + label + ' · Row ' + (rowIdx + 1) + '';
h += '
';
h += '

';
if (txtCol && dataCache) {
const row = dataCache.data.find((_, ri) => dataCache.offset + ri === rowIdx);
if (row && row[txtCol]) {
h += '
' + esc(row[txtCol]) + '
';
}
}
h += '
';
idx++;
}
content.innerHTML = h;
content.querySelectorAll('.cc-remove').forEach((btn) => {
btn.addEventListener('click', () => {
const r = parseInt(btn.dataset.row);
compareSet.delete(r);
updateCompareBadge();
renderCompare();
const card = document.querySelector('.card[data-row="' + r + '"]');
if (card) card.classList.remove('selected');
});
});
}
// ── Table ────────────────────────────────────────────────────────
async function loadTable() {
if (!currentFile) return;
showLoading();
try {
const limit = parseInt($('#sel-page-size').value);
const res = await fetch('/api/data/' + currentFile.id + '?offset=' + tableOffset + '&limit=' + limit);
if (!res.ok) throw new Error();
const data = await res.json();
renderTable(data);
} finally { hideLoading(); }
}
function renderTable(data) {
const limit = parseInt($('#sel-page-size').value);
const totalPages = Math.ceil(data.total / limit);
const page = Math.floor(data.offset / limit) + 1;
$('#table-page').textContent = page + '/' + totalPages + ' (' + fmtNum(data.total) + ')';
$('#table-prev').disabled = data.offset === 0;
$('#table-next').disabled = data.offset + limit >= data.total;
const imgCols = currentFile.columns.filter((c) => c.is_image).map((c) => c.name);
const cols = currentFile.columns.map((c) => c.name);
const fid = currentFile.id;
let h = '| # | ';
cols.forEach((c) => { h += '' + esc(c) + ' | '; });
h += '
';
data.data.forEach((row, ri) => {
const rowIdx = data.offset + ri;
h += '| ' + (rowIdx + 1) + ' | ';
cols.forEach((col) => {
const val = row[col];
if (val === null || val === undefined) {
h += '— | ';
} else if (typeof val === 'object' && val._type === 'image') {
if (imgCols.includes(col)) {
h += ' + ') | ';
} else {
h += '' + fmtSize(val.size) + ' | ';
}
} else if (typeof val === 'string' && val.length > 120) {
h += '' + esc(trunc(val, 120)) + ' | ';
} else {
h += '' + esc(String(val)) + ' | ';
}
});
h += '
';
});
h += '
';
$('#table-container').innerHTML = h;
$('#table-container').querySelectorAll('.cell-thumb').forEach((img) => {
img.addEventListener('click', () => {
const rowIdx = parseInt(img.dataset.row);
openDrawer(rowIdx);
});
});
}
$('#sel-page-size').addEventListener('change', () => { tableOffset = 0; loadTable(); });
$('#table-prev').addEventListener('click', () => { tableOffset = Math.max(0, tableOffset - parseInt($('#sel-page-size').value)); loadTable(); });
$('#table-next').addEventListener('click', () => { tableOffset += parseInt($('#sel-page-size').value); loadTable(); });
// ── Drawer ───────────────────────────────────────────────────────
function openDrawer(rowIdx) {
if (!currentFile || !dataCache) return;
const row = dataCache.data.find((_, ri) => dataCache.offset + ri === rowIdx);
if (!row) return;
drawerRowIdx = rowIdx;
const imgCol = $('#sel-img-col').value;
const txtCol = $('#sel-txt-col').value;
const fid = currentFile.id;
$('#drawer-title').textContent = 'Row ' + (rowIdx + 1);
$('#drawer-img').src = imgSrc(fid, rowIdx, imgCol);
const prompt = txtCol ? (row[txtCol] || '') : '';
$('#drawer-prompt').textContent = prompt || 'No prompt text';
let meta = '';
currentFile.columns.forEach((col) => {
if (col.is_image) return;
const val = row[col.name];
if (val === null || val === undefined) return;
meta += '' + esc(col.name) + '' + esc(String(val)) + '
';
});
$('#drawer-meta').innerHTML = meta;
$('#drawer-meta-section').classList.toggle('hidden', !meta);
updateDrawerNav();
$('#drawer').classList.add('open');
$('#drawer-backdrop').classList.add('open');
highlightOpenCard();
}
function closeDrawer() {
drawerRowIdx = null;
$('#drawer').classList.remove('open');
$('#drawer-backdrop').classList.remove('open');
$$('.card.card-open').forEach((c) => c.classList.remove('card-open'));
}
function highlightOpenCard() {
$$('.card.card-open').forEach((c) => c.classList.remove('card-open'));
if (drawerRowIdx != null) {
const card = document.querySelector('.card[data-row="' + drawerRowIdx + '"]');
if (card) card.classList.add('card-open');
}
}
function updateDrawerNav() {
if (drawerRowIdx == null) return;
const idx = drawerNavList.indexOf(drawerRowIdx);
$('#drawer-prev').disabled = idx <= 0;
$('#drawer-next').disabled = idx < 0 || idx >= drawerNavList.length - 1;
}
function drawerNavigate(dir) {
if (drawerRowIdx == null) return;
const idx = drawerNavList.indexOf(drawerRowIdx);
const newIdx = idx + dir;
if (newIdx < 0 || newIdx >= drawerNavList.length) return;
openDrawer(drawerNavList[newIdx]);
}
$('#btn-close-drawer').addEventListener('click', closeDrawer);
$('#drawer-backdrop').addEventListener('click', closeDrawer);
$('#drawer-prev').addEventListener('click', () => drawerNavigate(-1));
$('#drawer-next').addEventListener('click', () => drawerNavigate(1));
$('#drawer-zoom').addEventListener('click', () => {
if (drawerRowIdx == null) return;
const imgCol = $('#sel-img-col').value;
openLightbox(imgSrc(currentFile.id, drawerRowIdx, imgCol));
});
$('#drawer-img').addEventListener('click', () => {
if (drawerRowIdx == null) return;
const imgCol = $('#sel-img-col').value;
openLightbox(imgSrc(currentFile.id, drawerRowIdx, imgCol));
});
// ── Lightbox ─────────────────────────────────────────────────────
const lightbox = $('#lightbox');
const lbImg = $('#lb-img');
function openLightbox(src) {
lbImg.src = src;
lightbox.classList.add('active');
}
function closeLightbox() {
lightbox.classList.remove('active');
}
lightbox.addEventListener('click', (e) => {
if (e.target === lightbox || e.target.classList.contains('lb-close')) closeLightbox();
});
// ── Keyboard shortcuts ───────────────────────────────────────────
document.addEventListener('keydown', (e) => {
if (lightbox.classList.contains('active')) {
if (e.key === 'Escape') closeLightbox();
return;
}
if ($('#drawer').classList.contains('open')) {
if (e.key === 'Escape') closeDrawer();
if (e.key === 'ArrowLeft') drawerNavigate(-1);
if (e.key === 'ArrowRight') drawerNavigate(1);
return;
}
});
// ── Init ─────────────────────────────────────────────────────────
$('#btn-open').addEventListener('click', () => {
const path = $('#file-path').value.trim();
if (path) openFile(path);
});
$('#file-path').addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const path = $('#file-path').value.trim();
if (path) openFile(path);
}
});
if (window.location.hash) {
const path = decodeURIComponent(window.location.hash.slice(1));
$('#file-path').value = path;
openFile(path);
}
})();