Files
Anya Tokugawa 667776e43f
Build and publish container images / images (push) Successful in 9m29s
Release container images / release (push) Successful in 18s
feat(tasks): add keyboard index and productivity dashboard improvements
2026-11-10 07:12:15 +09:00

93 lines
15 KiB
JavaScript
Raw Permalink 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.
(() => {
'use strict';
window.PagesTaskIndex={mount({app,open,setProject}){
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en;
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
const $=id=>document.getElementById('tasks-'+id),api='/_/api/v1/extension/organizer.tasks/items',writable=app.dataset.writable==='true';
const list=$('list'),status=$('status'),sidebar=$('nav');
let items=[],selected='',project='',projects=[],next='',projectNext='',loading=false,mutating=false,generation=0,projectGeneration=0,controller,projectController;
let applied='~active',sortKey='due',order='asc',validResult=false;
const initial=new URLSearchParams(location.search);if(initial.has('filter'))applied=initial.get('filter');if(initial.has('project'))project=initial.get('project');
const sorts={due:t('Due date','期限'),planned:t('Planned date','取り組む日'),title:t('Subject','件名'),status:t('Status','状態'),priority:t('Priority','優先度'),created:t('Created','作成日時'),updated:t('Updated','更新日時')};
if(initial.has('sort')&&sorts[initial.get('sort')])sortKey=initial.get('sort');if(initial.get('order')==='desc')order='desc';
const states={todo:t('To do','未着手'),doing:t('Doing','着手中'),done:t('Done','完了'),cancelled:t('Cancelled','取りやめ')};
const marks={todo:'○',doing:'◐',done:'✓',cancelled:'−'};
function button(label,text,fn){const b=el('button',text);b.type='button';b.title=b.ariaLabel=label;b.onclick=fn;return b;}
async function request(url,options={}){
const r=await fetch(url,{credentials:'same-origin',signal:AbortSignal.timeout(15000),...options,headers:{'Content-Type':'application/json',...options.headers}}),data=await r.json().catch(()=>({}));
if(r.redirected||r.status===401)throw Error(t('Sign in again.','再度ログインしてください。'));
if(!r.ok)throw Error(r.status===412?t('Changed elsewhere. Refresh before retrying.','別の画面で更新されました。再読込してから操作してください。'):r.status===422?t('Invalid filter or sort. See ? for syntax.','絞り込み式またはソートが不正です。? で書式を確認してください。'):t('Request failed. Check permissions and try again.','操作に失敗しました。権限を確認して再度お試しください。'));
return data;
}
$('heading').textContent=t('Task index','タスク一覧');$('help').hidden=$('capture').hidden=true;$('search').closest('label').hidden=true;
const filterForm=el('form',undefined,'task-index-filter'),filter=el('input'),sort=el('select'),reverse=button(t('Reverse sort (O)','逆ソート (O)'),'↑',()=>{order=order==='asc'?'desc':'asc';reload();});
filter.name='filter';filter.value=applied;filter.maxLength=1000;filter.autocomplete='off';filter.ariaLabel=t('Limit tasks (l)','タスクを絞り込む (l)');filter.placeholder='~s "release" ~overdue';
const apply=el('button',t('Apply','適用'));apply.type='submit';
for(const[key,label]of Object.entries(sorts)){const o=el('option',label);o.value=key;sort.append(o);}sort.value=sortKey;sort.ariaLabel=t('Sort (o)','ソート (o)');sort.onchange=()=>{sortKey=sort.value;reload();};
filterForm.append(filter,apply,sort,reverse);$('status').before(filterForm);
filterForm.onsubmit=e=>{e.preventDefault();applied=filter.value;reload().then(()=>grid.focus());};
const actions=el('div',undefined,'task-index-actions'),help=el('dialog',undefined,'task-index-help');
help.ariaLabel=t('Task index shortcuts','タスク一覧のショートカット');
const helpTitle=el('h2',help.ariaLabel),helpClose=button(t('Close','閉じる'),'×',()=>help.close()),helpTable=el('dl');
for(const[key,label]of [['j / k / ↓ / ↑',t('Select next / previous task','次/前のタスクを選択')],['Ctrl+j / Ctrl+k',t('Next / previous project','次/前のプロジェクト')],['o / O',t('Choose sort / reverse order','ソート選択/順序反転')],['l / Esc',t('Focus filter / return to list','絞り込みへ/一覧へ戻る')],['d',t('Mark done (not delete)','完了にする(削除ではありません)')],['s',t('Start Pomodoro (25 minutes)','Pomodoro開始(25分)')],['c',t('Create in current project','現在のプロジェクトに新規作成')],['m / Enter',t('Edit selected task','選択タスクを編集')],['w',t('Open linked Wiki page','関連Wikiページを開く')],['?',t('Show this help','このヘルプを表示')]]){helpTable.append(el('dt',key),el('dd',label));}
help.append(helpClose,helpTitle,helpTable,el('h3',t('Filters (AND; ! negates)','絞り込み(AND結合、! で否定)')),el('pre','~s "release notes"\n~active / ~todo / ~doing / ~done / ~cancelled\n~overdue / ~archived / ~wiki / ~attachment\n~due <=today / ~planned tomorrow / ~start >=2026-01-01\n~review <today / ~due none\n~bucket inbox / ~bucket backlog / ~bucket someday\n~priority 3 / !~done\n\n~s "release" ~doing !~overdue'));
app.append(help);const showHelp=()=>help.showModal();help.addEventListener('close',()=>grid.focus());
const done=button(t('Done (d)','完了 (d)'),'✓',()=>act('done')),focus=button(t('Pomodoro (s)','Pomodoro (s)'),'◷',()=>act('focus')),edit=button(t('Edit (m)','編集 (m)'),'✎',()=>act('edit')),wiki=button(t('Wiki (w)','Wiki (w)'),'▣',()=>act('wiki'));
actions.append(done,focus,edit,wiki,button(t('Shortcuts (?)','ショートカット (?)'),'? ',showHelp));filterForm.after(actions);
const grid=el('table',undefined,'task-index-grid'),head=el('thead'),header=el('tr'),body=el('tbody');grid.tabIndex=0;grid.setAttribute('role','grid');grid.ariaLabel=t('Tasks','タスク');
for(const text of [t('Status','状態'),t('Subject','件名'),t('Due','期限'),t('Planned','取り組む日'),t('Priority','優先度'),'▣']){const th=el('th',text);th.scope='col';if(text==='▣')th.ariaLabel=t('Linked Wiki','関連Wiki');header.append(th);}head.append(header);grid.append(head,body);list.replaceChildren(grid);list.removeAttribute('role');
$('dialog').addEventListener('close',()=>grid.focus());
const projectTitle=el('h2',t('Projects','プロジェクト')),projectSearch=el('input'),projectList=el('div',undefined,'task-index-projects'),projectMore=button(t('More projects','続きのプロジェクト'),'…',()=>loadProjects(true));
projectSearch.type='search';projectSearch.ariaLabel=projectSearch.placeholder=t('Find project','プロジェクト検索');
sidebar.replaceChildren(projectTitle,projectSearch,projectList,projectMore);const inline=el('a',t('Inline editing ↗','インライン編集 ↗'));inline.href='/v/plan/tasks';sidebar.append(inline);
let projectTimer;projectSearch.oninput=()=>{clearTimeout(projectTimer);projectTimer=setTimeout(()=>loadProjects(),200);};
function projectChoices(){return [{uuid:'',title:t('All projects','すべて')},{uuid:'none',title:t('No project','プロジェクトなし')},...projects];}
function paintProjects(){projectList.replaceChildren();for(const p of projectChoices()){const b=button(p.title,p.title,()=>chooseProject(p.uuid));window.PagesTaskPresentation.render(b,p.title,false);b.dataset.project=p.uuid;b.setAttribute('aria-current',p.uuid===project?'true':'false');projectList.append(b);}projectMore.hidden=!projectNext;}
async function loadProjects(append=false){const ticket=++projectGeneration;projectController?.abort();projectController=new AbortController();projectMore.disabled=true;
try{const q=new URLSearchParams({kind:'project',view:'all',q:projectSearch.value,limit:'50'});if(append&&projectNext)q.set('before',projectNext);const data=await request(api+'?'+q,{signal:AbortSignal.any([projectController.signal,AbortSignal.timeout(15000)])});if(ticket!==projectGeneration)return;if(!append)projects=[];for(const p of data.items)if(!projects.some(x=>x.uuid===p.uuid))projects.push(p);projectNext=data.next;paintProjects();}
catch(e){if(e.name!=='AbortError')status.textContent=e.message;}finally{if(ticket===projectGeneration)projectMore.disabled=false;}
}
function chooseProject(id){project=id;setProject(project);selected='';paintProjects();reload();}
async function moveProject(delta){let choices=projectChoices(),index=choices.findIndex(x=>x.uuid===project);if(index<0)index=0;if(delta>0&&index===choices.length-1&&projectNext&&!projectMore.disabled){await loadProjects(true);choices=projectChoices();}const p=choices[Math.max(0,Math.min(choices.length-1,index+delta))];if(p)chooseProject(p.uuid);}
function syncURL(){const q=new URLSearchParams();if(project)q.set('project',project);if(applied!=='~active')q.set('filter',applied);if(sortKey!=='due')q.set('sort',sortKey);if(order!=='asc')q.set('order',order);history.replaceState(history.state,'',location.pathname+(q.size?'?'+q:''));}
function paint(){body.replaceChildren();for(const item of items){const row=el('tr');row.id='task-index-'+item.uuid;row.dataset.task=item.uuid;row.setAttribute('aria-selected',String(item.uuid===selected));row.onclick=()=>select(item.uuid);row.ondblclick=()=>act('edit');
const state=el('td',marks[item.status]+' '+states[item.status]),subject=el('td',undefined,'task-index-subject'),due=el('td',item.due_on||'—'),planned=el('td',item.planned_on||'—'),priority=el('td',['↓','·','!','!!'][item.priority]||'·'),note=el('td',item.page_uuid?'▣':'');
window.PagesTaskPresentation.render(subject,item.title,false);subject.title=item.title;if(item.parent_uuid)subject.prepend(el('span','↳ '));state.title=states[item.status];note.title=item.page_uuid?t('Linked Wiki page (w)','関連Wikiページ (w)'):'';
if(item.due_on&&item.due_on<app.dataset.today&&!['done','cancelled'].includes(item.status))due.className='task-index-overdue';row.append(state,subject,due,planned,priority,note);body.append(row);
}selection();}
function selection(scroll=false){for(const row of body.children)row.setAttribute('aria-selected',String(row.dataset.task===selected));if(selected){grid.setAttribute('aria-activedescendant','task-index-'+selected);if(scroll)document.getElementById('task-index-'+selected)?.scrollIntoView({block:'nearest'});}else grid.removeAttribute('aria-activedescendant');const item=items.find(x=>x.uuid===selected);done.disabled=focus.disabled=!writable||!item||loading||mutating||!validResult||item.archived;done.disabled||=item?.status==='done';focus.disabled||=['done','cancelled'].includes(item?.status);edit.disabled=wiki.disabled=!selected||loading||mutating||!validResult;}
function select(id){selected=id;selection(true);grid.focus({preventScroll:true});}
async function move(delta){if(loading)return;let i=items.findIndex(x=>x.uuid===selected);if(delta>0&&i===items.length-1&&next){const keep=i;await reload(true);if(items[keep+1])select(items[keep+1].uuid);return;}i=Math.max(0,Math.min(items.length-1,i+delta));if(items[i])select(items[i].uuid);}
async function reload(append=false){
const ticket=++generation;controller?.abort();controller=new AbortController();loading=true;validResult=false;selection();$('more').disabled=true;status.textContent=t('Loading…','読み込み中…');grid.setAttribute('aria-busy','true');const oldIndex=Math.max(0,items.findIndex(x=>x.uuid===selected));
try{const q=new URLSearchParams({kind:'task',view:'index',filter:applied,sort:sortKey,order,project,limit:'100'});if(append&&next)q.set('before',next);const data=await request(api+'?'+q,{signal:AbortSignal.any([controller.signal,AbortSignal.timeout(15000)])});if(ticket!==generation)return;
if(!append)items=[];for(const item of data.items)if(!items.some(x=>x.uuid===item.uuid))items.push(item);next=data.next;app.dataset.today=data.today;validResult=true;
if(!items.some(x=>x.uuid===selected))selected=items[Math.min(oldIndex,items.length-1)]?.uuid||'';paint();reverse.textContent=order==='asc'?'↑':'↓';sort.value=sortKey;syncURL();status.textContent=items.length?`${items.length}${next?'+':''}`:t('No matching tasks.','該当するタスクはありません。');$('more').hidden=!next;
}catch(e){if(e.name!=='AbortError'&&ticket===generation)status.textContent=e.message;}finally{if(ticket===generation){loading=false;selection();$('more').disabled=!validResult;grid.removeAttribute('aria-busy');}}
}
async function act(action){const item=items.find(x=>x.uuid===selected);if(!item||loading||mutating||!validResult)return;
if(action==='edit'){open(item.uuid);return;}
if(action==='focus'){if(writable&&!item.archived&&!['done','cancelled'].includes(item.status))app.dispatchEvent(new CustomEvent('task-focus',{detail:item}));return;}
if(action==='wiki'&&!item.page_uuid){status.textContent=t('No linked Wiki page. Use task details to link one.','関連Wikiページはありません。タスク詳細から関連付けてください。');return;}
if(action==='done'&&(!writable||item.archived||item.status==='done'))return;
mutating=true;selection();try{
if(action==='wiki'){const note=await request(api+'/'+item.uuid+'/note');if(note.linked)location.assign(note.url);else status.textContent=t('No linked Wiki page. Use task details to link or create one.','関連Wikiページはありません。タスク詳細から関連付けてください。');}
else{const fresh=await request(api+'/'+item.uuid);await request(api+'/'+item.uuid,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify({...fresh.item,status:'done'})});app.dispatchEvent(new Event('task-today-refresh'));await reload();}
}catch(e){status.textContent=e.message;}finally{mutating=false;selection();}
}
document.addEventListener('keydown',e=>{
if(e.defaultPrevented||e.isComposing||e.keyCode===229||e.altKey||e.metaKey||document.querySelector('dialog[open]'))return;
if(e.key==='Escape'&&(filterForm.contains(e.target)||e.target===projectSearch)){e.preventDefault();filter.value=applied;grid.focus();return;}
if(e.target.closest?.('input,textarea,select,[contenteditable=true]'))return;
if(e.ctrlKey){if(e.key==='j'||e.key==='k'){e.preventDefault();moveProject(e.key==='j'?1:-1);}return;}
if(['j','k','ArrowDown','ArrowUp'].includes(e.key)){e.preventDefault();move(['j','ArrowDown'].includes(e.key)?1:-1);return;}
if(e.repeat)return;
if(e.key==='Enter'&&e.target!==grid&&e.target!==document.body)return;
const commands={o:()=>sort.focus(),O:()=>reverse.click(),l:()=>{filter.focus();filter.select();},d:()=>act('done'),s:()=>act('focus'),c:()=>{if(writable&&!mutating)open('');},m:()=>act('edit'),Enter:()=>{if(e.target===grid||e.target===document.body)act('edit');},w:()=>act('wiki'),'?':showHelp};
if(commands[e.key]){e.preventDefault();commands[e.key]();}
});
setProject(project);paintProjects();loadProjects();reload();grid.focus();
return {reload};
}};
})();