GCStream's picture
Add tools/dataview/static/app.js
be88e83 verified
Raw
History Blame Contribute Delete
21.4 kB
(() => {
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 = '<span class="breadcrumb-item" data-path="/">/</span>';
let acc = '';
parts.forEach((p) => {
acc += '/' + p;
h += '<span class="breadcrumb-sep">/</span>';
h += '<span class="breadcrumb-item" data-path="' + esc(acc) + '">' + esc(p) + '</span>';
});
$('#breadcrumb').innerHTML = h;
$$('.breadcrumb-item').forEach((el) => el.addEventListener('click', () => loadFolder(el.dataset.path)));
}
function renderFolderList(data) {
let h = '';
if (data.parent) {
h += '<div class="folder-entry is-parent" data-path="' + esc(data.parent) + '"><span class="fe-icon">..</span><span class="fe-name">Up</span></div>';
}
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 += '<div class="folder-entry ' + cls + '" data-path="' + esc(e.path) + '" data-dir="' + e.is_dir + '" data-ds="' + e.is_dataset + '">';
h += '<span class="fe-icon">' + icon + '</span>';
h += '<span class="fe-name">' + esc(e.name) + '</span>';
if (!e.is_dir) h += '<span class="fe-meta">' + fmtSize(e.size) + '</span>';
h += '</div>';
});
if (!data.entries.length) h = '<div style="padding:24px;text-align:center;color:var(--text-tertiary);font-size:12px">Empty directory</div>';
$('#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) => '<option value="' + c.name + '">' + c.name + '</option>').join('');
$('#sel-txt-col').innerHTML = '<option value="">None</option>' + textCols.map((c) => '<option value="' + c.name + '">' + c.name + '</option>').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 += '<div class="card' + (sel ? ' selected' : '') + (isOpen ? ' card-open' : '') + '" data-row="' + rowIdx + '">';
h += '<span class="card-row">#' + (rowIdx + 1) + '</span>';
h += '<span class="card-check">&#10003;</span>';
h += '<img class="card-img" src="' + imgSrc(fid, rowIdx, imgCol) + '" loading="lazy" data-row="' + rowIdx + '" data-col="' + imgCol + '">';
if (w && hm) h += '<span class="card-dims">' + w + '&times;' + hm + '</span>';
if (caption) h += '<div class="card-caption">' + esc(trunc(caption, 140)) + '</div>';
h += '</div>';
});
if (!data.data.length) {
h = '<p style="color:var(--text-tertiary);padding:48px;text-align:center;grid-column:1/-1">No matching rows</p>';
}
$('#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 += '<div class="compare-card">';
h += '<div class="cc-head"><span class="cc-label">' + label + ' &middot; Row ' + (rowIdx + 1) + '</span>';
h += '<button class="cc-remove" data-row="' + rowIdx + '">&times;</button></div>';
h += '<img src="' + item.src + '" alt="Row ' + (rowIdx + 1) + '">';
if (txtCol && dataCache) {
const row = dataCache.data.find((_, ri) => dataCache.offset + ri === rowIdx);
if (row && row[txtCol]) {
h += '<div class="cc-prompt">' + esc(row[txtCol]) + '</div>';
}
}
h += '<div class="cc-meta">';
currentFile.columns.forEach((col) => {
if (col.is_image) return;
const row = dataCache?.data?.find((_, ri) => dataCache.offset + ri === rowIdx);
const val = row ? row[col.name] : null;
if (val === null || val === undefined) return;
const s = String(val);
if (s.length > 200) return;
h += '<div class="cc-meta-row"><span class="cc-meta-key">' + esc(col.name) + '</span><span class="cc-meta-val">' + esc(s) + '</span></div>';
});
h += '</div></div>';
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 = '<table><thead><tr><th style="width:36px">#</th>';
cols.forEach((c) => { h += '<th>' + esc(c) + '</th>'; });
h += '</tr></thead><tbody>';
data.data.forEach((row, ri) => {
const rowIdx = data.offset + ri;
h += '<tr><td class="row-num">' + (rowIdx + 1) + '</td>';
cols.forEach((col) => {
const val = row[col];
if (val === null || val === undefined) {
h += '<td class="cell-null">—</td>';
} else if (typeof val === 'object' && val._type === 'image') {
if (imgCols.includes(col)) {
h += '<td><img class="cell-thumb" src="' + imgSrc(fid, rowIdx, col) + '" loading="lazy" data-row="' + rowIdx + '" data-col="' + col + '"></td>';
} else {
h += '<td class="cell-null">' + fmtSize(val.size) + '</td>';
}
} else if (typeof val === 'string' && val.length > 120) {
h += '<td title="' + esc(val) + '">' + esc(trunc(val, 120)) + '</td>';
} else {
h += '<td>' + esc(String(val)) + '</td>';
}
});
h += '</tr>';
});
h += '</tbody></table>';
$('#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 += '<div class="drawer-meta-row"><span class="drawer-meta-key">' + esc(col.name) + '</span><span class="drawer-meta-val">' + esc(String(val)) + '</span></div>';
});
$('#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);
}
})();