let browserSelectionAnchor = null; let activeNavigatorLink = null; function browserRows() { return Array.from(document.querySelectorAll('.browser-row')); } function selectedEntries() { return browserRows().filter(row => row.classList.contains('selected')); } function markEntrySelected(row, selected) { row.classList.toggle('selected', selected); row.setAttribute('aria-selected', String(selected)); } function clearBrowserSelection() { browserRows().forEach(row => markEntrySelected(row, false)); selectedEntry = null; updateSelectionStatus(); } function updateSelectionStatus() { const count = selectedEntries().length; const status = document.getElementById('browser-selection-status'); if (status) status.textContent = count ? `${count} selected` : ''; const rename = document.getElementById('browser-context-rename'); if (rename) rename.disabled = count !== 1; } function selectEntry(el, event) { const modifier = Boolean(event && (event.ctrlKey || event.metaKey)); const range = Boolean(event && event.shiftKey && browserSelectionAnchor); if (range) { const rows = browserRows(); const from = rows.indexOf(browserSelectionAnchor); const to = rows.indexOf(el); if (!modifier) rows.forEach(row => markEntrySelected(row, false)); if (from >= 0 && to >= 0) { const [start, end] = from < to ? [from, to] : [to, from]; rows.slice(start, end + 1).forEach(row => markEntrySelected(row, true)); } } else if (modifier) { markEntrySelected(el, !el.classList.contains('selected')); browserSelectionAnchor = el; } else { browserRows().forEach(row => markEntrySelected(row, row === el)); browserSelectionAnchor = el; } const selected = selectedEntries(); selectedEntry = el.classList.contains('selected') ? el : (selected.at(-1) || null); if (selectedEntry) updatePreview(selectedEntry); updateSelectionStatus(); } function openContextMenu(ev, el) { ev.preventDefault(); ev.stopPropagation(); if (!el.classList.contains('selected')) selectEntry(el); selectedEntry = el; const menu = document.getElementById('context-menu'); const rename = menu.querySelector('button:nth-child(3)'); if (rename) { rename.id = 'browser-context-rename'; rename.disabled = selectedEntries().length !== 1; } placeContextMenu(menu, ev.clientX, ev.clientY); loadContextAdapters(el.dataset.path); } function placeContextMenu(menu, x, y) { menu.style.display = 'block'; menu.style.left = `${x}px`; menu.style.top = `${y}px`; const bounds = menu.getBoundingClientRect(); menu.style.left = `${Math.max(8, Math.min(x, innerWidth - bounds.width - 8))}px`; menu.style.top = `${Math.max(8, Math.min(y, innerHeight - bounds.height - 8))}px`; } function selectionMarquee() { const grid = document.getElementById('browser-grid'); const box = document.getElementById('selection-marquee'); if (!grid || !box) return; grid.addEventListener('pointerdown', event => { if (event.button !== 0 || event.target.closest('.browser-row,button,a,input')) return; const startX = event.clientX; const startY = event.clientY; const additive = event.ctrlKey || event.metaKey; const initial = new Set(additive ? selectedEntries() : []); let active = false; try { grid.setPointerCapture?.(event.pointerId); } catch (_) {} const move = current => { if (!active && Math.hypot(current.clientX - startX, current.clientY - startY) < 4) return; active = true; current.preventDefault(); const left = Math.min(startX, current.clientX); const top = Math.min(startY, current.clientY); const right = Math.max(startX, current.clientX); const bottom = Math.max(startY, current.clientY); Object.assign(box.style, { display: 'block', left: `${left}px`, top: `${top}px`, width: `${right - left}px`, height: `${bottom - top}px` }); for (const row of browserRows()) { const rect = row.getBoundingClientRect(); const hit = rect.left < right && rect.right > left && rect.top < bottom && rect.bottom > top; markEntrySelected(row, initial.has(row) || hit); } const selected = selectedEntries(); selectedEntry = selected.at(-1) || null; updateSelectionStatus(); const edge = 44; const main = grid.closest('.browser-main'); if (main && current.clientY > innerHeight - edge) main.scrollTop += 18; if (main && current.clientY < grid.getBoundingClientRect().top + edge) main.scrollTop -= 18; }; const finish = current => { grid.removeEventListener('pointermove', move); grid.removeEventListener('pointerup', finish); grid.removeEventListener('pointercancel', finish); try { grid.releasePointerCapture?.(current.pointerId); } catch (_) {} box.style.display = 'none'; if (!active && !additive) clearBrowserSelection(); if (selectedEntry) updatePreview(selectedEntry); }; grid.addEventListener('pointermove', move); grid.addEventListener('pointerup', finish); grid.addEventListener('pointercancel', finish); }); } function draggedItems(event) { let raw = ''; try { raw = event.dataTransfer.getData('application/x-pageswiki-paths'); } catch (_) {} if (raw) { try { const items = JSON.parse(raw); if (Array.isArray(items)) return items.filter(item => item && typeof item.path === 'string'); } catch (_) {} } const path = event.dataTransfer.getData('text/plain') || draggedPath; if (!path) return []; const row = browserRows().find(item => item.dataset.path === path); return [{path, name: row?.dataset.name || path.split('/').pop(), is_directory: row?.dataset.isDir === 'true'}]; } function dragStart(ev, el) { if (!el.classList.contains('selected')) selectEntry(el); const items = selectedEntries().map(row => ({ path: row.dataset.path, name: row.dataset.name, is_directory: row.dataset.isDir === 'true' })); draggedPath = el.dataset.path; ev.dataTransfer.effectAllowed = 'copyMove'; ev.dataTransfer.setData('application/x-pageswiki-paths', JSON.stringify(items)); ev.dataTransfer.setData('text/plain', items.map(item => item.path).join('\n')); } function dragOver(ev, el) { if (el.dataset.isDir === 'true') { ev.preventDefault(); ev.dataTransfer.dropEffect = 'move'; } } async function dropEntry(ev, el) { ev.preventDefault(); ev.stopPropagation(); if (el.dataset.isDir !== 'true') return; const targetDir = el.dataset.path.replace(/\/$/, ''); const items = draggedItems(ev).filter(item => item.path !== targetDir); if (!items.length) return; const moves = items.map(item => ({ ...item, destination: `${targetDir}/${item.path.replace(/\/+$/, '').split('/').pop()}` })).filter(item => item.destination !== item.path); if (!moves.length) return; if (!confirm(`${moves.length} item(s)\nā ${targetDir}`)) return; await runMoveQueue(moves); location.reload(); } async function ctxRename() { const entries = selectedEntries(); if (entries.length !== 1) return; const entry = entries[0]; const oldPath = entry.dataset.path; const newPath = prompt('Rename path:', oldPath); if (!newPath || newPath === oldPath) return; await renamePath(oldPath, newPath, entry.dataset.isDir === 'true'); location.reload(); } function ctxCopy() { const paths = selectedEntries().map(row => row.dataset.path); if (!paths.length) return; localStorage.setItem('pageswiki.fileClipboard', JSON.stringify({ operation: 'copy', paths, created_at: Date.now() })); } function ctxCopyPath() { const paths = selectedEntries().map(row => row.dataset.path); if (paths.length) navigator.clipboard.writeText(paths.join('\n')); } async function renamePath(oldPath, newPath, recursive = false, operation = null, range = {start: 0, end: 100}) { const ownOperation = !operation; operation ||= startBrowserOperation('Renaming', oldPath, true); const request = {old_path: oldPath, new_path: newPath, recursive}; try { const preview = await fetch('/_/api/v1/path/rename?preview=1', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(request) }); if (!preview.ok) throw new Error((await preview.text()).trim() || 'rename preview failed'); const estimate = await preview.json(); const count = Number(estimate.count || 1); updateBrowserOperation(operation, range.start + (range.end - range.start) * .2, `${count} path${count === 1 ? '' : 's'} Ā· ${newPath}`); const response = await fetch('/_/api/v1/path/rename', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(request) }); if (!response.ok) throw new Error((await response.text()).trim() || 'rename failed'); const result = await response.json().catch(() => ({count})); updateBrowserOperation(operation, range.end, `${result.count || count} path${(result.count || count) === 1 ? '' : 's'}`); if (ownOperation) finishBrowserOperation(operation); return result.count || count; } catch (error) { failBrowserOperation(operation, error.message); throw error; } } async function runMoveQueue(moves) { const operation = startBrowserOperation('Moving items', `0 / ${moves.length}`, true); for (let index = 0; index < moves.length; index += 1) { const move = moves[index]; await renamePath(move.path, move.destination, Boolean(move.is_directory), operation, { start: index / moves.length * 100, end: (index + 1) / moves.length * 100 }); updateBrowserOperation(operation, (index + 1) / moves.length * 100, `${index + 1} / ${moves.length}`); } finishBrowserOperation(operation); } function startBrowserOperation(title, detail, indeterminate = false) { const operation = document.createElement('div'); operation.className = `browser-operation${indeterminate ? ' indeterminate' : ''}`; operation.style.setProperty('--operation-progress', '4'); operation.innerHTML = '