diff options
Diffstat (limited to 'web/static/app.mjs')
| -rw-r--r-- | web/static/app.mjs | 100 |
1 files changed, 32 insertions, 68 deletions
diff --git a/web/static/app.mjs b/web/static/app.mjs index f18a103..33d5a08 100644 --- a/web/static/app.mjs +++ b/web/static/app.mjs @@ -21,7 +21,7 @@ function locationView() { return configuration?.catalog && ['sites', 'services'].includes(view) ? view : 'files'; } function viewURL(view, path = currentPath) { - return pathURL(path) + (view === 'files' ? '' : `?view=${view}`); + return pathURL(path) + (view === 'files' ? (current?.stream && path === currentPath ? '?follow=1' : '') : `?view=${view}`); } function showView(view) { activeView = view; @@ -43,7 +43,7 @@ function status(message, error = false) { function controls() { for (const id of ['go', 'reload', 'newfile', 'newdir', 'upload']) $(id).disabled = busy; $('save').disabled = busy || !current || current.stat.directory || $('editor').hidden || !dirty; - $('download').disabled = busy || !current || current.stat.directory; + $('download').disabled = busy || !current || current.stat.directory || current.stream; $('follow').disabled = busy || !current || current.stat.directory; $('rename').disabled = busy || currentPath === '/'; $('delete').disabled = busy || currentPath === '/'; @@ -66,14 +66,14 @@ async function connectedClient() { catch { throw new Error('Unable to reach the file server. Reload to try again.'); } return client; } -async function readPath(path) { +async function readPath(path, metadataOnly = false) { const active = await connectedClient(); - try { return await active.readPath(path); } + try { return await active.readPath(path, metadataOnly); } catch (error) { // A timed-out/closed transport has lost its fids. Retry reads once on a // fresh session. Writes are never replayed after an uncertain result. if (!active.closed) throw error; - return (await connectedClient()).readPath(path); + return (await connectedClient()).readPath(path, metadataOnly); } } function normalizePath(path) { @@ -131,16 +131,16 @@ function breadcrumbs(path) { $('up').href = pathURL(parent); $('up').dataset.path = parent; } -async function navigate(path, historyMode = 'push') { +async function navigate(path, historyMode = 'push', follow = false) { path = normalizePath(path); showView('files'); stopFollow(); status('Loading…'); - const result = await readPath(path); + const result = await readPath(path, follow); current = result; currentPath = path; dirty = false; for (const view of ['files', 'sites', 'services']) $(`view-${view}`).href = viewURL(view); $('path').value = path; - const url = pathURL(path); + const url = pathURL(path) + (follow ? '?follow=1' : ''); if (historyMode === 'push' && location.pathname + location.search + location.hash !== url) history.pushState(null, '', url); document.title = `${path} — 9web`; breadcrumbs(path); @@ -154,6 +154,11 @@ async function navigate(path, historyMode = 'push') { const permissions = document.createElement('td'), name = document.createElement('td'), size = document.createElement('td'); permissions.className = 'mode'; permissions.textContent = mode(entry); name.append(pathLink(entry.name + (entry.directory ? '/' : ''), child(path, entry.name), 'entry' + (entry.directory ? ' directory' : ''))); + if (!entry.directory) { + const followLink = pathLink('follow', child(path, entry.name), 'follow-link'); + followLink.dataset.follow = 'true'; followLink.href += '?follow=1'; + name.append(followLink); + } size.className = 'size'; size.textContent = entry.directory ? '—' : entry.length.toLocaleString(); row.append(permissions, name, size); rows.append(row); } @@ -163,7 +168,7 @@ async function navigate(path, historyMode = 'push') { } else { $('filename').textContent = result.stat.name; $('file-mode').textContent = mode(result.stat); - $('file-size').textContent = `${result.bytes.length.toLocaleString()} bytes`; + $('file-size').textContent = result.stream ? 'stream' : `${result.bytes.length.toLocaleString()} bytes`; let editable = true; try { if (result.bytes.includes(0)) throw new Error('Binary'); @@ -175,7 +180,7 @@ async function navigate(path, historyMode = 'push') { status('File loaded.'); } updateStat(result); - markTree(path); + if (follow && !result.stat.directory) startFollow(); } function mayLeave() { return !dirty || window.confirm('Discard unsaved changes?'); } document.addEventListener('click', event => { @@ -187,19 +192,19 @@ document.addEventListener('click', event => { if (view === activeView) return; history.pushState(null, '', viewURL(view)); showView(view); - if (view === 'files' && !current) action(() => navigate(currentPath, 'none')).then(loadTree); + if (view === 'files' && !current) action(() => navigate(currentPath, 'none')); return; } const link = event.target.closest('a[data-path]'); if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; event.preventDefault(); - if (!busy && mayLeave()) action(() => navigate(link.dataset.path)); + if (!busy && mayLeave()) action(() => navigate(link.dataset.path, 'push', link.dataset.follow === 'true')); }); $('path-form').onsubmit = event => { event.preventDefault(); if (mayLeave()) action(() => navigate($('path').value)); }; -$('reload').onclick = () => { if (mayLeave()) action(() => navigate(current ? currentPath : locationPath(), 'none')); }; +$('reload').onclick = () => { if (mayLeave()) action(() => navigate(current ? currentPath : locationPath(), 'none', Boolean(current?.stream))); }; $('editor').oninput = () => { dirty = true; controls(); }; $('save').onclick = () => action(async () => { const bytes = new TextEncoder().encode($('editor').value); @@ -224,26 +229,20 @@ window.addEventListener('popstate', () => { const view = locationView(), path = locationPath(); if (busy || (view === 'files' && path !== currentPath && !mayLeave())) { history.pushState(null, '', viewURL(activeView)); return; } showView(view); - if (view === 'files' && (!current || path !== currentPath)) action(() => navigate(path, 'none')).then(loadTree); + const follow = new URLSearchParams(location.search).get('follow') === '1'; + if (view === 'files' && (!current || path !== currentPath || Boolean(current.stream) !== follow)) action(() => navigate(path, 'none', follow)); }); window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } }); -// ---- HTTP /fs view: tree, stat panel, create/rename/delete/upload, follow ---- +// ---- HTTP /fs view: stat panel, create/rename/delete/upload, follow ---- // These operate over the gateway's HTTP mapping of the same 9P tree, so they // stay independent of the WebSocket editing session above. function fsURL(path) { return '/fs' + path.split('/').map(encodeURIComponent).join('/'); } function parentOf(path) { return path.replace(/\/[^/]+$/, '') || '/'; } function baseName(path) { return path.split('/').filter(Boolean).pop() || ''; } function dirContext() { return current && current.stat.directory ? currentPath : parentOf(currentPath); } -function sortEntries(a, b) { return Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name); } - -async function fetchDir(path) { - const response = await fetch(fsURL(path) + (path.endsWith('/') ? '' : '/'), { headers: { accept: 'application/json' } }); - if (!response.ok) throw new Error(`list failed: ${response.status}`); - return response.json(); -} function renderStat(rows) { const dl = $('stat'); @@ -276,72 +275,37 @@ function updateStat(result) { }).catch(() => {}); } -function treeItem(entry, path) { - const li = document.createElement('li'); - const node = document.createElement('span'); - node.className = 'node' + (entry.dir ? ' dir' : ''); - node.dataset.node = path; - const twist = document.createElement('span'); - twist.className = 'twist'; - twist.textContent = entry.dir ? '▸' : ' '; - node.append(twist, document.createTextNode(entry.name)); - li.append(node); - node.onclick = () => { - if (entry.dir) toggleTree(li, path, twist); - else if (!busy && mayLeave()) action(() => navigate(path)); - }; - return li; -} -async function toggleTree(li, path, twist) { - const open = li.querySelector(':scope > ul'); - if (open) { open.remove(); twist.textContent = '▸'; return; } - twist.textContent = '▾'; - const ul = document.createElement('ul'); - li.append(ul); - try { - for (const entry of (await fetchDir(path)).sort(sortEntries)) ul.append(treeItem(entry, child(path, entry.name))); - } catch (error) { ul.textContent = '(unavailable)'; } -} -async function loadTree() { - const root = $('filetree'); - try { - const entries = (await fetchDir('/')).sort(sortEntries); - root.replaceChildren(...entries.map(entry => treeItem(entry, '/' + entry.name))); - } catch { /* upstream not ready; leave the last tree in place */ } -} -function markTree(path) { - for (const node of $('filetree').querySelectorAll('.node.current')) node.classList.remove('current'); - const match = $('filetree').querySelector(`.node[data-node="${CSS.escape(path)}"]`); - if (match) match.classList.add('current'); -} let stream = null; -function stopFollow() { +function stopFollow(clear = true) { if (stream) { stream.close(); stream = null; } $('follow').classList.remove('active'); - $('stream').hidden = true; - $('stream').textContent = ''; + if (clear) { $('stream').hidden = true; $('stream').textContent = ''; } } function startFollow() { if (!current || current.stat.directory) return; + current.stream = true; + history.replaceState(null, '', viewURL('files')); + controls(); $('editor').hidden = true; $('binary').hidden = true; $('edit-actions').hidden = true; const view = $('stream'); view.hidden = false; view.textContent = ''; $('follow').classList.add('active'); + status('Following stream…'); stream = new EventSource(fsURL(currentPath) + '?follow=1'); stream.onmessage = event => { view.textContent += event.data + '\n'; view.scrollTop = view.scrollHeight; }; - stream.addEventListener('eof', stopFollow); - stream.onerror = () => { status('Stream ended.'); stopFollow(); }; + stream.addEventListener('eof', () => { stopFollow(false); status('End of stream.'); }); + stream.onerror = () => { status('Stream ended.'); stopFollow(false); }; } $('follow').onclick = () => { - if ($('follow').classList.contains('active')) { stopFollow(); action(() => navigate(currentPath, 'none')); } + if ($('follow').classList.contains('active')) { stopFollow(false); status('Stream stopped.'); } else startFollow(); }; async function mutate(fn, done) { if (busy) return; busy = true; controls(); - try { await fn(); await loadTree(); status(done); } + try { await fn(); status(done); } catch (error) { status(error.message, true); } finally { busy = false; controls(); } } @@ -406,7 +370,7 @@ async function start() { currentPath = locationPath(); const view = locationView(); showView(view); - if (view === 'files') await action(() => navigate(currentPath, 'none')).then(loadTree); + if (view === 'files') await action(() => navigate(currentPath, 'none', new URLSearchParams(location.search).get('follow') === '1')); } catch (error) { status(error.message, true); } } start(); |
