Files
pages/static/js/viewer-shortcuts.js
T
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

87 lines
7.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
const path = document.body?.dataset?.path || document.querySelector('.breadcrumb-bar')?.dataset?.path || location.pathname;
const isTyping = target => target?.matches?.('input,textarea,select,[contenteditable="true"]');
const openDialog = (title, content) => {
const dialog = document.createElement('dialog'); dialog.className = 'viewer-shortcut-dialog';
dialog.innerHTML = `<form method="dialog"><header><h2></h2><button value="cancel" aria-label="Close">×</button></header><div class="viewer-shortcut-content"></div></form>`;
dialog.querySelector('h2').textContent = title; dialog.querySelector('.viewer-shortcut-content').append(content); document.body.append(dialog);
dialog.addEventListener('close', () => dialog.remove()); dialog.showModal(); return dialog;
};
const formDialog = (title, action, fields) => {
const form = document.createElement('form'); form.method='get'; form.action=action;
for (const field of fields) { const label=document.createElement('label'); label.textContent=field.label; const input=document.createElement(field.tag||'input'); Object.assign(input,field.attrs||{}); label.append(input); form.append(label); }
const submit=document.createElement('button'); submit.type='submit'; submit.textContent='Open'; form.append(submit); openDialog(title,form);
};
const findDialog = () => {
const form=document.createElement('form'); form.method='get'; form.action='/v/search'; form.className='viewer-find-form';
const input=document.createElement('input'); input.type='search'; input.name='q'; input.autocomplete='off'; input.placeholder='Find…'; input.setAttribute('aria-label','Find');
const list=document.createElement('div'); list.className='viewer-find-suggestions';
const candidates=[...document.querySelectorAll('a[href]')].map(a=>({href:a.href,label:(a.textContent||'').trim()||a.getAttribute('href')})).filter(x=>x.label&&x.href.startsWith(location.origin)).slice(0,80);
const render=()=>{const q=input.value.toLowerCase();list.replaceChildren(...candidates.filter(x=>!q||x.label.toLowerCase().includes(q)).slice(0,12).map(x=>{const a=document.createElement('a');a.href=x.href;a.textContent=x.label;return a;}));};
input.addEventListener('input',render); form.append(input,list); const button=document.createElement('button');button.type='submit';button.textContent='Search';form.append(button);openDialog('Find',form);setTimeout(()=>input.focus(),0);
};
const shortcutSheet = () => {
const table=document.createElement('div'); table.className='viewer-shortcut-grid';
[['e','Edit'],['/','Find'],['v','Change view'],['c','Create child'],['u','Upload'],['s','Share'],['p','Permissions'],['Ctrl+↑','Parent'],['Ctrl+↓','Children'],['Ctrl+→','Previous'],['Ctrl+←','Next'],['?','This cheat sheet']].forEach(([key,label])=>{const k=document.createElement('kbd');k.textContent=key;const d=document.createElement('span');d.textContent=label;table.append(k,d);});
openDialog('Keyboard shortcuts',table);
};
const childrenDialog = async () => {
const content=document.createElement('div'); content.className='viewer-children-dialog-content'; content.textContent='Loading…';
const dialog=openDialog('Children',content);
try {
const response=await fetch(childrenURL(path),{headers:{'Accept':'text/html'}});
if(!response.ok) throw new Error('children request failed');
content.innerHTML=await response.text();
content.querySelectorAll('a[href]').forEach(link=>link.addEventListener('click',event=>{event.preventDefault();dialog.close();window.location.assign(new URL(link.getAttribute('href'),location.href).href);}));
} catch (_) { content.textContent='Unable to load children.'; }
};
const parentPath = value => { const clean=(value||'/').replace(/\/+$/,'')||'/'; const i=clean.lastIndexOf('/'); return i<=0?'/':clean.slice(0,i); };
const childrenURL = value => '/v/children?path='+encodeURIComponent(value||'/');
const focusView = () => { const buttons=[...document.querySelectorAll('[data-children-view]')]; if (!buttons.length) return; const active=buttons.findIndex(b=>b.classList.contains('active')); buttons[(active+1+buttons.length)%buttons.length].click(); };
const share = () => {
const url = new URL(location.href); url.hash=''; const wrap=document.createElement('div');
const input=document.createElement('input'); input.value=url.href; input.readOnly=true; input.select();
const copy=document.createElement('button'); copy.type='button'; copy.textContent='Copy link'; copy.onclick=async()=>{try{await navigator.clipboard.writeText(input.value);copy.textContent='Copied'}catch{input.select()}};
const pageTitle=document.querySelector('meta[property="og:title"]')?.content || document.title.split(' · ')[0] || location.pathname.split('/').filter(Boolean).pop() || '/';
const domainTitle=document.querySelector('meta[property="og:site_name"]')?.content || location.host;
const text=pageTitle+' - '+domainTitle;
const x=document.createElement('a'); x.href='https://twitter.com/intent/tweet?url='+encodeURIComponent(input.value)+'&text='+encodeURIComponent(text); x.target='_blank'; x.rel='noopener noreferrer'; x.dataset.shareX='true'; x.textContent='Share on X'; wrap.append(input,copy,x); openDialog('Share link',wrap);
};
document.addEventListener('click', event => {
const link = event.target.closest?.('a[data-share-x]');
if (!link || event.defaultPrevented) return;
event.preventDefault();
event.stopImmediatePropagation();
window.open(link.href, '_blank', 'noopener,noreferrer');
});
document.querySelector('[data-viewer-delete]')?.addEventListener('click', async event => {
const uuid = event.currentTarget.dataset.objectUuid;
if (!uuid || !window.confirm('Delete this object?')) return;
const response = await fetch('/_/api/v1/object/delete', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({object_uuid: uuid}),
});
if (!response.ok) { window.alert('Delete failed'); return; }
window.location.assign('/');
});
document.addEventListener('keydown', event => {
if (event.defaultPrevented || isTyping(event.target) || document.querySelector('dialog[open]')) return;
const key=event.key.toLowerCase();
if (event.ctrlKey || event.metaKey) {
if (key==='arrowup') { event.preventDefault(); location.href=parentPath(path); }
else if (key==='arrowdown') { event.preventDefault(); childrenDialog(); }
else if (key==='arrowright') { event.preventDefault(); history.forward(); }
else if (key==='arrowleft') { event.preventDefault(); history.back(); }
return;
}
if (key==='e') { event.preventDefault(); location.href='/e/-'+(path==='/'?'':path); }
else if (key==='/') { event.preventDefault(); findDialog(); }
else if (key==='v') { event.preventDefault(); focusView(); }
else if (key==='c') { event.preventDefault(); location.href='/:/new?path='+encodeURIComponent(path); }
else if (key==='u') { event.preventDefault(); location.href='/v/upload?path='+encodeURIComponent(path); }
else if (key==='s') { event.preventDefault(); share(); }
else if (key==='p') { event.preventDefault(); const trigger=document.querySelector('[data-governance-open]'); if(trigger) trigger.click(); else { const message=document.createElement('p'); message.textContent='Open the City governance dialog from the City view to manage permissions for this locality.'; openDialog('Permissions',message); } }
else if (key==='?') { event.preventDefault(); shortcutSheet(); }
});
})();