Files
pages/static/js/public-navigation.js
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

137 lines
9.9 KiB
JavaScript

(() => {
'use strict';
const ja = document.documentElement.lang.startsWith('ja');
const text = {loading: ja ? '読み込み中…' : 'Loading…', failed: ja ? '一覧を取得できませんでした。' : 'Could not load this listing.', retry: ja ? '再試行' : 'Retry', views: ja ? '表示形式' : 'View mode'};
// Persist presentation only, never content, names or authorization.
let preferred = 'list';
try { const v = sessionStorage.getItem('public-navigation-view'); if (['list', 'detail', 'icon'].includes(v)) preferred = v; } catch (_) {}
const sections = new Set(), queue = [];
let active = 0;
function pump() {
while (active < 3 && queue.length) {
const job = queue.shift();
if (job.signal.aborted) { job.reject(new DOMException('Aborted', 'AbortError')); continue; }
active++;
job.run().then(job.resolve, job.reject).finally(() => { active--; pump(); });
}
}
const scheduled = (signal, run) => new Promise((resolve, reject) => { queue.push({signal, run, resolve, reject}); pump(); });
const observer = 'IntersectionObserver' in window ? new IntersectionObserver(entries => {
for (const entry of entries) if (entry.isIntersecting) {
observer.unobserve(entry.target);
const state = entry.target.closest('[data-children-src]')?._publicChildren;
if (state) load(state, entry.target.dataset.childrenNext, entry.target);
}
}, {rootMargin: '160px'}) : null;
function watch(state) {
state.body.querySelectorAll('[data-children-next]').forEach(target => {
if (observer) observer.observe(target);
else {
const link = document.createElement('a'); link.href = target.dataset.childrenNext; link.textContent = ja ? '次の項目' : 'Next items';
link.addEventListener('click', event => { event.preventDefault(); load(state, link.href, target); }); target.replaceChildren(link);
}
});
}
function status(target, message) { const p = document.createElement('p'); p.setAttribute('role', 'status'); p.textContent = message; target.replaceChildren(p); }
async function load(state, source, appendTarget = null) {
const generation = state.generation, signal = state.controller.signal, target = appendTarget || state.body;
const current = () => !signal.aborted && state.generation === generation && target.isConnected;
if (!current()) return;
status(target, text.loading); state.section.setAttribute('aria-busy', 'true');
try {
const url = new URL(source, location.origin);
if (url.origin !== location.origin || url.pathname !== '/v/children') throw new Error('Invalid navigation endpoint');
const body = await scheduled(signal, async () => {
const request = new AbortController(), abort = () => request.abort();
signal.addEventListener('abort', abort, {once: true});
const timeout = setTimeout(abort, 15000);
try {
const response = await fetch(url, {signal: request.signal, cache: 'no-store', headers: {Accept: 'text/html'}});
if (!response.ok || response.redirected || !response.headers.get('Content-Type')?.includes('text/html')) throw new Error('Navigation unavailable');
return await response.text();
} finally { clearTimeout(timeout); signal.removeEventListener('abort', abort); }
});
if (!current()) return;
const fragment = document.createElement('template'); fragment.innerHTML = body;
if (appendTarget) appendTarget.replaceWith(fragment.content); else target.replaceChildren(fragment.content);
watch(state);
} catch (error) {
if (!current()) return;
status(target, text.failed);
const retry = document.createElement('button'); retry.type = 'button'; retry.textContent = text.retry;
retry.addEventListener('click', () => load(state, source, appendTarget)); target.append(retry);
} finally { if (state.generation === generation) state.section.removeAttribute('aria-busy'); }
}
document.querySelectorAll('[data-children-src]').forEach(section => {
const views = document.createElement('nav'); views.className = 'public-children-views'; views.setAttribute('aria-label', text.views);
const body = document.createElement('div'); body.dataset.publicChildrenBody = '';
const ready = section.hasAttribute('data-public-children-ready');
if (ready) while (section.firstChild) body.append(section.firstChild);
section.replaceChildren(views, body);
const state = {section, body, generation: 0, controller: new AbortController()};
section._publicChildren = state; sections.add(state);
const buttons = [];
const choose = (view, initial = false) => {
state.controller.abort(); state.controller = new AbortController(); state.generation++;
buttons.forEach(button => button.setAttribute('aria-pressed', String(button.dataset.view === view)));
if (!initial) try { sessionStorage.setItem('public-navigation-view', view); } catch (_) {}
if (ready && initial && view === 'list') { watch(state); return; }
const url = new URL(section.dataset.childrenSrc, location.origin); url.searchParams.set('view', view); load(state, url);
};
for (const [view, icon, name] of [['icon', '▦', ja ? '縮小版表示' : 'Thumbnail view'], ['detail', '☷', ja ? '詳細表示' : 'Detail view'], ['list', '≡', ja ? '通常表示' : 'List view']]) {
const button = document.createElement('button'); button.type = 'button'; button.textContent = icon; button.dataset.view = view;
button.title = name; button.setAttribute('aria-label', name);
button.addEventListener('click', () => choose(view)); views.append(button); buttons.push(button);
}
choose(preferred, true);
});
const tree = document.querySelector('[data-public-tree]');
if (tree) {
const rows = [...tree.querySelectorAll('[data-public-tree-path]')], filter = document.querySelector('[data-public-tree-filter]');
const collapsed = new Set(), byPath = new Map(rows.map(row => [row.dataset.publicTreePath, row]));
const parent = path => path.slice(0, path.lastIndexOf('/')) || '/';
function update() {
const query = filter.value.trim().toLocaleLowerCase(), matches = new Set();
if (query) for (const row of rows) if (row.dataset.publicTreePath.toLocaleLowerCase().includes(query)) {
for (let at = row.dataset.publicTreePath; byPath.has(at); at = parent(at)) matches.add(at);
}
let visible = 0;
const ancestors = [];
for (const row of rows) {
const path = row.dataset.publicTreePath, depth = Number(row.dataset.depth);
while (ancestors.length && ancestors.at(-1).depth >= depth) ancestors.pop();
row.hidden = query ? !matches.has(path) : !!ancestors.at(-1)?.hidden;
ancestors.push({depth, hidden: row.hidden || collapsed.has(path)});
const toggle = row.querySelector('[data-public-tree-toggle]');
if (toggle) { toggle.hidden = false; toggle.disabled = !!query; toggle.setAttribute('aria-expanded', String(!!query || !collapsed.has(path))); toggle.textContent = query || !collapsed.has(path) ? '▾' : '▸'; }
if (!row.hidden) visible++;
}
document.querySelector('[data-public-tree-no-match]').hidden = visible > 0 || !query;
}
tree.addEventListener('click', event => {
const toggle = event.target.closest('[data-public-tree-toggle]'); if (!toggle) return;
const path = toggle.closest('[data-public-tree-path]').dataset.publicTreePath;
collapsed.has(path) ? collapsed.delete(path) : collapsed.add(path); update();
});
tree.addEventListener('keydown', event => {
if (event.altKey || event.ctrlKey || event.metaKey || !['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
const row = event.target.closest('[data-public-tree-path]'); if (!row) return;
const visible = rows.filter(item => !item.hidden), at = visible.indexOf(row), path = row.dataset.publicTreePath;
let next;
if (event.key === 'ArrowDown') next = visible[Math.min(at + 1, visible.length - 1)];
if (event.key === 'ArrowUp') next = visible[Math.max(at - 1, 0)];
if (event.key === 'Home') next = visible[0];
if (event.key === 'End') next = visible.at(-1);
if (event.key === 'ArrowLeft') { if (!filter.value.trim() && row.querySelector('[data-public-tree-toggle]') && !collapsed.has(path)) collapsed.add(path); else next = byPath.get(parent(path)); }
if (event.key === 'ArrowRight') { if (collapsed.has(path)) collapsed.delete(path); else if (visible[at + 1]?.dataset.publicTreePath.startsWith(path + '/')) next = visible[at + 1]; }
event.preventDefault(); update(); next?.querySelector('.public-tree-name').focus();
});
filter.addEventListener('input', update);
document.querySelector('[data-public-expand]').addEventListener('click', () => { filter.value = ''; collapsed.clear(); update(); });
document.querySelector('[data-public-collapse]').addEventListener('click', () => { filter.value = ''; rows.forEach(row => collapsed.add(row.dataset.publicTreePath)); update(); });
document.querySelector('[data-public-tree-tools]').hidden = false; update();
}
window.addEventListener('pagehide', () => { observer?.disconnect(); for (const state of sections) state.controller.abort(); });
window.addEventListener('pageshow', event => { if (event.persisted) location.reload(); });
})();