tech-trans-rag / static /chunks.html
phaethon-order's picture
Refactor code structure for improved readability and maintainability
7a064ce
Raw History Blame Contribute Delete
27.2 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>Chunks Viewer</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,'SF Pro Rounded','SF Pro Display',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;background:#001122;color:#fff;min-height:100vh;padding:28px;display:flex;flex-direction:column;align-items:center;gap:28px}
.shell{width:100%;max-width:1400px;display:flex;flex-direction:column;gap:26px}
.panel{background:#333;border-radius:20px;padding:26px 32px;box-shadow:0 18px 50px rgba(0,0,0,.5);display:flex;flex-direction:column;gap:20px}
.header-title {
color: #fff;
font-size: 2.5rem;
font-weight: 500;
text-decoration: underline;
text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
text-align: center;
margin: 10px;
}
.header-subtitle {
color: #ccc;
font-size: 0.85rem;
font-weight: 400;
font-style: italic;
margin: 5px;
}
p.sub{font-size:.8rem;color:#ccc;font-style:italic;line-height:1.5;margin:0}
a{color:#87CEFA;text-decoration:none}a:hover{text-decoration:underline}
form.query{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-end}
form.query>div{display:flex;flex-direction:column;gap:6px}
label{font-size:.7rem;text-transform:uppercase;letter-spacing:1px;color:#ccc}
input[type=number],input[type=text]{background:#222;border:2px solid #555;border-radius:10px;padding:10px 14px;color:#fff;font-family:inherit;min-width:140px}
input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
button{background:#7ec8ff;color:#001122;border:none;padding:10px 18px;border-radius:10px;font-weight:600;cursor:pointer;font-size:.85rem;letter-spacing:1px;transition:.25s;box-shadow:0 8px 18px rgba(126,200,255,.25)}
button:hover{background:#6bb8ff;transform:translateY(-2px)}
button:active{transform:translateY(0)}
button.secondary{background:rgba(255,102,102,.45);color:#fff;box-shadow:none}
button.secondary:hover{background:rgba(255,102,102,.6)}
.status{font-size:.75rem;color:#ccc;min-height:18px}
.results{display:flex;flex-direction:column;gap:22px}
.summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px}
.kv{background:#222;border:2px solid #555;border-radius:12px;padding:10px 12px;display:flex;flex-direction:column;gap:4px}
.kv span.k{font-size:.6rem;text-transform:uppercase;letter-spacing:1px;color:#999}
.kv span.v{font-size:.8rem;word-break:break-word}
.table-wrapper{background:#222;border:2px solid #555;border-radius:16px;padding:14px 18px;max-height:60vh;overflow:auto;overflow-x:auto}
table.data-table{width:auto;min-width:1900px;border-collapse:collapse;font-size:.65rem;table-layout:fixed}
table.data-table th,table.data-table td{padding:6px 8px;text-align:left;border:1px solid #444;vertical-align:top;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
table.data-table th{position:sticky;top:0;background:#2d3f4d;z-index:2;font-weight:600;letter-spacing:.5px}
table.data-table tbody tr:nth-child(even){background:#1e2a33}
.truncate{max-width:unset;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
/* Wider, fixed column widths for better readability and horizontal scrolling */
table.data-table th:nth-child(1),
table.data-table td:nth-child(1){width:90px}
table.data-table th:nth-child(2),
table.data-table td:nth-child(2){width:90px}
table.data-table th:nth-child(3),
table.data-table td:nth-child(3){width:900px} /* text */
table.data-table th:nth-child(4),
table.data-table td:nth-child(4){width:120px}
table.data-table th:nth-child(5),
table.data-table td:nth-child(5){width:320px}
table.data-table th:nth-child(6),
table.data-table td:nth-child(6){width:180px}
table.data-table th:nth-child(7),
table.data-table td:nth-child(7){width:240px}
table.data-table th:nth-child(8),
table.data-table td:nth-child(8){width:140px}
.toolbar{display:flex;flex-wrap:wrap;gap:10px}
.toolbar input{background:#222;border:2px solid #555;border-radius:10px;padding:8px 10px;color:#fff;font-size:.75rem;min-width:220px}
.toolbar input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
.pagination{display:flex;align-items:center;gap:12px;font-size:.7rem;flex-wrap:wrap}
.pagination button{padding:6px 12px;font-size:.65rem}
.empty{text-align:center;font-style:italic;color:#ccc}
.spinner{width:18px;height:18px;border:3px solid rgba(255,255,255,.2);border-top-color:#7ec8ff;border-radius:50%;animation:spin 1s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
@media (max-width:900px){.panel{padding:22px 20px}h1{font-size:1.7rem}}
/* Edit mode styles */
tr.editing { background:#283745 !important; }
td.editable { cursor:text; }
td.editable:hover { background:#203240; }
.row-actions { display:flex; gap:6px; }
.row-actions button { padding:4px 10px; font-size:.6rem; background:#355064; color:#cfe9ff; }
.row-actions button.confirm { background:#4caf50; color:#fff; }
.row-actions button.cancel { background:#d9534f; color:#fff; }
th.sortable { cursor:pointer; user-select:none; }
th.sortable:hover { background:#355064; }
th.sortable .indicator { font-size:.55rem; margin-left:4px; opacity:.8; }
</style>
</head>
<body>
<div class="shell">
<div class="panel">
<h1 class="header-title">Chunks Explorer</h1>
<p class="header-subtitle">Paginated table view of chunks data with inline editing capabilities. Chunk embeddings are stored in Neon using pgvector.</p>
<form id="queryForm" class="query" autocomplete="off">
<div>
<label for="docId">Document ID</label>
<input type="number" id="docId" min="1" placeholder="e.g., 12" />
</div>
<div>
<label for="filter">Text Filter</label>
<input type="text" id="filter" placeholder="filter text..." />
</div>
<div>
<label for="pageSize">Page Size</label>
<input type="number" id="pageSize" min="5" max="200" value="25" />
</div>
<div style="display:flex;gap:8px;">
<button type="submit" id="fetchBtn">Fetch by Doc ID</button>
</div>
</form>
<div class="toolbar">
<input type="text" id="sectionFilter" placeholder="filter by section title" />
<input type="text" id="clauseFilter" placeholder="filter by clause type" />
<div style="display:flex;gap:8px;">
<button type="button" class="secondary" id="clearBtn">Clear</button>
</div>
</div>
<div class="status" id="status"></div>
</div>
<div class="panel results" id="resultsPanel">
<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:6px;">
<h2 style="font-size:1.2rem;margin:0;">Chunks Data</h2>
<button type="button" id="globalMode" class="secondary" style="margin-left:auto;">Show All Chunks</button>
<div style="font-size:.65rem;letter-spacing:1px;color:#ccc;">Total: <span id="rowCount">0</span></div>
</div>
<div class="summary" id="summary"></div>
<div class="table-wrapper" id="tableWrapper"></div>
<div class="pagination" id="pagination"></div>
</div>
</div>
<div style="text-align: center; margin-top: 20px;">
<a href="/" style="color: #87CEFA; text-decoration: none; font-size: 1rem; padding: 10px 20px; border: 1px solid #87CEFA; border-radius: 10px; transition: all 0.3s ease;" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">
← Back to Home
</a>
</div>
<script>
const form = document.getElementById('queryForm');
const docIdInput = document.getElementById('docId');
const filterInput = document.getElementById('filter');
const sectionFilter = document.getElementById('sectionFilter');
const clauseFilter = document.getElementById('clauseFilter');
const pageSizeInput = document.getElementById('pageSize');
const statusEl = document.getElementById('status');
const summaryEl = document.getElementById('summary');
const tableWrapper = document.getElementById('tableWrapper');
const paginationEl = document.getElementById('pagination');
const clearBtn = document.getElementById('clearBtn');
const resultsPanel = document.getElementById('resultsPanel');
const globalModeBtn = document.getElementById('globalMode');
const rowCountEl = document.getElementById('rowCount');
let rawChunks = [];
let currentPage = 1;
let sortCol = 'chunk_id';
let sortDir = 'asc';
let editing = { rowChunkId: null, col: null };
const PAGE_SIZE = 25;
function esc(v) {
return String(v ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function setStatus(msg, isErr=false) {
statusEl.innerHTML = msg ? `<span style="${isErr ? 'color:#ff7b7b;font-weight:600;' : ''}">${esc(msg)}</span>` : '';
}
function spinner() {
setStatus(`Loading...`);
}
function fetchChunks(docId) {
spinner();
fetch(`/api/chunks?doc_id=${encodeURIComponent(docId)}`)
.then(r => r.json())
.then(data => {
if (data.error) {
setStatus(data.error, true);
resultsPanel.style.display = 'none';
return;
}
rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s).` : 'No chunks.');
buildSummary(data);
currentPage = 1;
render();
resultsPanel.style.display = 'block';
})
.catch(err => {
setStatus('Failed to load chunks: ' + err.message, true);
resultsPanel.style.display = 'none';
});
}
function fetchAllChunks() {
setStatus('');
summaryEl.innerHTML = '';
spinner();
// Prefer JSONL source so we can show all records
fetch(`/api/chunks/jsonl`)
.then(r => r.json())
.then(data => {
if (data && data.chunks) {
rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
} else if (Array.isArray(data)) {
rawChunks = data; // tolerate direct array response
} else {
rawChunks = [];
}
// If JSONL missing/empty, fall back to DB list with max limit
if (!rawChunks.length) {
return fetch(`/api/chunks/all?limit=500&offset=0`).then(r => r.json());
}
return { chunks: rawChunks };
})
.then(data => {
if (data && data.chunks && !rawChunks.length) {
rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
}
setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s).` : 'No chunks.');
currentPage = 1;
render();
resultsPanel.style.display = 'block';
})
.catch(err => {
setStatus('Failed to load global chunks: ' + err.message, true);
});
}
function buildSummary(apiData) {
summaryEl.innerHTML = '';
if (!rawChunks.length) return;
const last = rawChunks[rawChunks.length - 1];
const meta = {
doc_id: apiData.doc_id || 'Global',
total_chunks: rawChunks.length,
first_chunk_id: rawChunks[0]?.chunk_id,
last_chunk_id: last?.chunk_id,
token_version: last?.tok_ver,
segment_version: last?.seg_ver
};
Object.entries(meta).forEach(([k, v]) => {
summaryEl.insertAdjacentHTML('beforeend',
`<div class="kv"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></div>`);
});
}
function applyFilters(list) {
const t = filterInput.value.trim().toLowerCase();
const s = sectionFilter.value.trim().toLowerCase();
const c = clauseFilter.value.trim().toLowerCase();
return list.filter(chunk => {
if (t && !JSON.stringify(chunk).toLowerCase().includes(t)) return false;
if (s && !(chunk.section_title || '').toLowerCase().includes(s)) return false;
if (c && !(chunk.clause_type || '').toLowerCase().includes(c)) return false;
return true;
});
}
function compareValues(a, b) {
const an = parseFloat(a);
const bn = parseFloat(b);
const aNum = !isNaN(an) && String(an) === String(a).trim();
const bNum = !isNaN(bn) && String(bn) === String(b).trim();
if (aNum && bNum) {
if (an < bn) return -1;
if (an > bn) return 1;
return 0;
}
const as = String(a).toLowerCase();
const bs = String(b).toLowerCase();
if (as < bs) return -1;
if (as > bs) return 1;
return 0;
}
function sortRows(rows) {
if (!sortCol) return rows;
return [...rows].sort((r1, r2) => {
const v1 = r1[sortCol] ?? '';
const v2 = r2[sortCol] ?? '';
const cmp = compareValues(v1, v2);
return sortDir === 'asc' ? cmp : -cmp;
});
}
function setSort(col) {
if (sortCol === col) {
sortDir = sortDir === 'asc' ? 'desc' : 'asc';
} else {
sortCol = col;
sortDir = 'asc';
}
currentPage = 1;
render();
}
function buildHeader(cols) {
return cols.map(c => {
const active = c === sortCol;
const indicator = active ? (sortDir === 'asc' ? '▲' : '▼') : '';
return `<th class="sortable" data-col="${esc(c)}">${esc(c)}<span class="indicator">${indicator}</span></th>`;
}).join('');
}
function paginate(rows) {
const pageSize = parseInt(pageSizeInput.value, 10) || PAGE_SIZE;
const pageCount = Math.max(1, Math.ceil(rows.length / pageSize));
if (currentPage > pageCount) currentPage = pageCount;
const start = (currentPage - 1) * pageSize;
const slice = rows.slice(start, start + pageSize);
updatePagination(currentPage, pageCount, slice.length, rows.length);
return slice;
}
function updatePagination(current, total, visible, totalRows) {
paginationEl.innerHTML = `
<button id="firstPage" ${current === 1 ? 'disabled' : ''} title="First">⏮</button>
<button id="prevPage" ${current === 1 ? 'disabled' : ''} title="Previous">◀</button>
<span>Page ${current} / ${total}</span>
<button id="nextPage" ${current === total ? 'disabled' : ''} title="Next">▶</button>
<button id="lastPage" ${current === total ? 'disabled' : ''} title="Last">⏭</button>
<span>| Rows: ${visible} / ${totalRows}</span>
`;
// Attach pagination event handlers
const firstBtn = document.getElementById('firstPage');
const prevBtn = document.getElementById('prevPage');
const nextBtn = document.getElementById('nextPage');
const lastBtn = document.getElementById('lastPage');
firstBtn?.addEventListener('click', () => { currentPage = 1; render(); });
prevBtn?.addEventListener('click', () => { if (currentPage > 1) { currentPage--; render(); } });
nextBtn?.addEventListener('click', () => { currentPage++; render(); });
lastBtn?.addEventListener('click', () => { currentPage = total; render(); });
paginationEl.style.display = totalRows ? 'flex' : 'none';
}
function render() {
const filtered = applyFilters(rawChunks);
const rows = sortRows(filtered);
rowCountEl.textContent = rows.length;
if (!rows.length) {
tableWrapper.innerHTML = '<div class="empty">No chunks match filters.</div>';
paginationEl.style.display = 'none';
return;
}
const pageRows = paginate(rows);
renderTable(pageRows);
}
function renderTable(pageRows) {
const cols = ["chunk_id", "doc_id", "text", "section_number", "section_title", "clause_type", "definition_terms", "embedding_count"];
let html = '<table class="data-table"><thead><tr>' + buildHeader(cols) + '</tr></thead><tbody>';
html += pageRows.map(r => {
const rid = esc(r.chunk_id);
let tds = cols.map(c => {
let val = r[c];
if (val == null) val = '';
let full = String(val);
let display = full;
const nonEditable = (c === 'chunk_id' || c === 'doc_id' || c === 'embedding_count');
if (c === 'text') {
// Truncate text to 350 characters unless editing
if (editing.rowChunkId === String(r.chunk_id) && editing.col === c) {
display = full; // Show full text when editing
} else {
display = full.length > 350 ? full.slice(0, 350) + '…' : full;
}
} else if (display.length > 160) {
display = display.slice(0, 160) + '…';
}
const cls = [
display !== full ? 'truncate' : '',
nonEditable ? '' : 'editable'
].filter(Boolean).join(' ');
let content = esc(display);
if (editing.rowChunkId === String(r.chunk_id) && editing.col === c && !nonEditable) {
if (c === 'text') {
content = `<textarea style="width:100%;height:80px;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;resize:vertical;" placeholder="Enter text...">${esc(full)}</textarea>`;
} else {
content = `<input type="text" style="width:100%;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;" value="${esc(full)}" />`;
}
}
return `<td data-col="${esc(c)}" data-chunk="${rid}" class="${cls}" title="${esc(full)}">${content}</td>`;
}).join('');
// Add action buttons if this row is being edited
const actionTd = editing.rowChunkId === String(r.chunk_id) ?
`<td class="row-actions"><button class="confirm">Save</button><button class="cancel">Cancel</button></td>` :
`<td></td>`;
const rowClass = editing.rowChunkId === String(r.chunk_id) ? 'editing' : '';
return `<tr data-chunk="${rid}" class="${rowClass}">${tds}${actionTd}</tr>`;
}).join('');
html += '</tbody></table>';
tableWrapper.innerHTML = html;
// Header sort handlers
tableWrapper.querySelectorAll('th.sortable').forEach(th => {
th.addEventListener('click', () => {
const col = th.getAttribute('data-col');
if (col) setSort(col);
});
});
attachEditHandlers();
focusEditingCell();
}
function attachEditHandlers() {
// Attach direct click handlers to editable cells
tableWrapper.querySelectorAll('td.editable').forEach(td => {
td.addEventListener('click', () => beginCellEdit(td));
});
// Save/cancel handlers if visible
tableWrapper.querySelectorAll('tr').forEach(tr => {
const chunkId = tr.getAttribute('data-chunk');
if (!chunkId) return;
const confirmBtn = tr.querySelector('button.confirm');
const cancelBtn = tr.querySelector('button.cancel');
if (confirmBtn) confirmBtn.addEventListener('click', () => confirmCellEdit(chunkId));
if (cancelBtn) cancelBtn.addEventListener('click', cancelCellEdit);
});
}
function focusEditingCell() {
if (!editing.rowChunkId || !editing.col) return;
const row = tableWrapper.querySelector(`tr[data-chunk="${CSS.escape(editing.rowChunkId)}"]`);
if (!row) return;
const field = row.querySelector(`td[data-col="${CSS.escape(editing.col)}"] input, td[data-col="${CSS.escape(editing.col)}"] textarea`);
if (field) {
// Focus and place caret at the end
field.focus();
if (field.setSelectionRange && typeof field.value === 'string') {
const len = field.value.length;
try { field.setSelectionRange(len, len); } catch {}
}
// Keyboard shortcuts: Enter to save (except Shift+Enter for textarea), Esc to cancel
field.addEventListener('keydown', (ev) => {
if (ev.key === 'Escape') { ev.preventDefault(); cancelCellEdit(); }
else if (ev.key === 'Enter') {
const isTextarea = field.tagName.toLowerCase() === 'textarea';
if (!isTextarea || (isTextarea && !ev.shiftKey)) {
ev.preventDefault();
confirmCellEdit(editing.rowChunkId);
}
}
}, { once: true });
}
}
function beginCellEdit(td) {
const tr = td.closest('tr');
const chunkId = tr.getAttribute('data-chunk');
const col = td.getAttribute('data-col');
if (!col || col === 'chunk_id' || col === 'doc_id' || col === 'embedding_count') return;
// Only one cell at a time
editing = { rowChunkId: String(chunkId), col };
render();
}
function cancelCellEdit() {
editing = { rowChunkId: null, col: null };
render();
}
function confirmCellEdit(chunkId) {
const row = tableWrapper.querySelector(`tr[data-chunk="${CSS.escape(chunkId)}"]`);
if (!row) return;
const cell = row.querySelector(`td[data-col="${CSS.escape(editing.col)}"] input, td[data-col="${CSS.escape(editing.col)}"] textarea`);
if (!cell) {
cancelCellEdit();
return;
}
const newVal = cell.value.trim();
const updates = { [editing.col]: newVal };
setStatus('Saving…');
fetch('/api/chunks', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chunk_id: parseInt(chunkId), updates })
})
.then(r => r.json().then(j => ({ ok: r.ok, data: j })))
.then(res => {
if (!res.ok) {
setStatus(res.data.error || 'Save failed', true);
return;
}
// Update local data
const chunk = rawChunks.find(c => String(c.chunk_id) === String(chunkId));
if (chunk) {
chunk[editing.col] = newVal;
}
setStatus('Saved.');
cancelCellEdit();
})
.catch(err => setStatus('Save error: ' + err.message, true));
}
// Event listeners
form.addEventListener('submit', e => {
e.preventDefault();
const id = docIdInput.value.trim();
if (!id) {
setStatus('Document ID required', true);
return;
}
fetchChunks(id);
});
clearBtn.addEventListener('click', () => {
docIdInput.value = '';
filterInput.value = '';
sectionFilter.value = '';
clauseFilter.value = '';
rawChunks = [];
resultsPanel.style.display = 'none';
setStatus('');
});
[filterInput, sectionFilter, clauseFilter, pageSizeInput].forEach(inp =>
inp.addEventListener('input', () => { currentPage = 1; render(); })
);
globalModeBtn.addEventListener('click', () => {
fetchAllChunks();
});
// Initial load
const params = new URLSearchParams(window.location.search);
const qsId = params.get('doc_id');
if (qsId) {
docIdInput.value = qsId;
fetchChunks(qsId);
} else {
fetchAllChunks();
}
</script>
</body>
</html>