feat(tasks): add keyboard index and productivity dashboard improvements
Build and publish container images / images (push) Successful in 9m29s
Release container images / release (push) Successful in 18s

This commit is contained in:
Anya Tokugawa committed 2026-11-10 07:12:15 +09:00
1 parent 02edb51b8a
commit 667776e43f
44 files changed
+1224 -138

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
(() => {
'use strict';
// Commands address exact UUIDs, never ambiguous titles. Mutations reuse the
// task API's ownership checks and revision CAS; this is not a shell.
window.PagesDashboardCommands=(body,{request,api,t,today,refresh,writable,signal})=>{
const form=document.createElement('form'),input=document.createElement('input'),submit=document.createElement('button'),help=document.createElement('details'),summary=document.createElement('summary'),examples=document.createElement('pre'),status=document.createElement('p');
form.className='dashboard-command';input.ariaLabel=t('Task command','タスクコマンド');input.placeholder='add task … / today UUID / tomorrow UUID';input.required=true;input.maxLength=500;submit.textContent='↵';submit.title=submit.ariaLabel=t('Run','実行');submit.disabled=input.disabled=!writable;status.role='status';summary.textContent='?';examples.textContent='add task 件名\ntoday UUID\ntomorrow UUID\ndue UUID YYYY-MM-DD\ndue UUID clear\ndone UUID\ndelete UUID';help.append(summary,examples);form.append(input,submit);body.replaceChildren(form,status,help);
const suggestions=document.createElement('datalist');suggestions.id='dashboard-command-tasks';input.setAttribute('list',suggestions.id);input.autocomplete='off';body.append(suggestions);
let pending=null,timer,lookup;
signal?.addEventListener('abort',()=>{clearTimeout(timer);lookup?.abort();},{once:true});
input.addEventListener('input',()=>{
clearTimeout(timer);lookup?.abort();suggestions.replaceChildren();
const match=/^(today|tomorrow|due|done|delete) (.*)$/.exec(input.value);
if(!match||/^[0-9a-f]{8}-/.test(match[2]))return;
const command=input.value;lookup=new AbortController();const requestSignal=lookup.signal;
timer=setTimeout(async()=>{
try {const data=await request(api+'items?'+new URLSearchParams({kind:'task',view:'all',limit:'10',q:match[2]}),{signal:AbortSignal.any([requestSignal,AbortSignal.timeout(10000)])});
if(input.value!==command||requestSignal.aborted||!body.isConnected)return;
for(const item of data.items){const option=document.createElement('option');option.value=match[1]+' '+item.uuid+(match[1]==='due'?' '+today:'');option.label=match[1]+' '+item.title;suggestions.append(option);}
}catch{/* Suggestions must never prevent command entry. */}
},250);
});
form.onsubmit=async e=>{
e.preventDefault();if(submit.disabled)return;
const command=input.value.trim(),tomorrow=new Date(today+'T12:00:00Z');tomorrow.setUTCDate(tomorrow.getUTCDate()+1);
submit.disabled=true;input.disabled=true;status.textContent='';
try{
let saved;
if(command.startsWith('add task ')){
const title=command.slice(9).trim();if(!title)throw Error(t('Enter a title.','件名を入力してください。'));
if(!pending||pending.command!==command){const preferences=await request(api+'preferences');pending={command,item:{...preferences.defaults,uuid:crypto.randomUUID(),kind:'task',title,notes:'',status:'todo',bucket:'inbox',priority:1,archived:false,version:0}};}
saved=await request(api+'items',{method:'POST',body:JSON.stringify(pending.item)});
}else{
const match=/^(today|tomorrow|due|done|delete) ([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?: (\d{4}-\d{2}-\d{2}|clear))?$/.exec(command);
if(!match||(match[1]==='due')!==!!match[3])throw Error(t('Unknown command. See ?.','コマンドを確認してください(?)。'));
const [,action,id,date]=match,{item}=await request(api+'items/'+id);
if(item.kind!=='task')throw Error(t('Select a task, not a project.','プロジェクトではなくタスクを指定してください。'));
if(action==='delete'){
if(!confirm(item.title+'\n'+t('Permanently delete this task?','このタスクを完全に削除しますか?')))return;
await request(api+'items/'+id,{method:'DELETE',headers:{'If-Match':'"'+item.version+'"'}});
}else{
if(action==='due'){item.due_on=date==='clear'?'':date;if(!item.due_on)item.notify_due=false;}
if(action==='today'||action==='tomorrow')item.planned_on=action==='today'?today:tomorrow.toISOString().slice(0,10);
if(action==='done')item.status='done';
saved=await request(api+'items/'+id,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify(item)});
}
}
pending=null;input.value='';status.textContent=t('Saved','保存しました');
if(saved?.item){const a=document.createElement('a');a.href='/v/plan/task/'+saved.item.uuid;a.textContent=' '+saved.item.title;status.append(a);}
refresh();
}catch(error){status.textContent=error.message;}finally{submit.disabled=input.disabled=!writable;input.focus();}
};
};
})();
+6 -1
View File
@@ -10,6 +10,7 @@
let saved = Number(input.value);
const paletteNames = ['home_palette_mode','home_palette_strength','home_palette_brightness'];
let savedPalette = paletteNames.map(name => form.elements[name]?.value);
let savedWallpaper = ['home_wallpaper_path','home_wallpaper_opacity'].map(name=>form.elements[name]?.value);
const palettePreview = () => {
const strength = Number(form.elements.home_palette_strength?.value ?? 35);
const label = form.querySelector('[data-palette-strength]');
@@ -24,6 +25,7 @@
palettePreview();
};
const restore = () => {
['home_wallpaper_path','home_wallpaper_opacity'].forEach((name,i)=>{if(form.elements[name])form.elements[name].value=savedWallpaper[i];});
input.value = String(saved);
paletteNames.forEach((name,i) => { if (form.elements[name]) form.elements[name].value=savedPalette[i]; });
preview(saved);
@@ -71,11 +73,14 @@
signal: AbortSignal.timeout(15000),
});
if (!response.ok) throw new Error((await response.text()).trim());
await response.json();
const result=await response.json();form.elements.version.value=String(result.version);
const wallpaper=['home_wallpaper_path','home_wallpaper_opacity'].map(name=>submitted.get(name));
const wallpaperChanged=wallpaper.some((value,i)=>value!==savedWallpaper[i]);savedWallpaper=wallpaper;
saved = Number(submitted.get('home_glass_transparency'));
savedPalette = paletteNames.map(name => submitted.get(name));
preview(saved);
status.textContent = form.dataset.saved;
if(wallpaperChanged){location.reload();return;}
window.setTimeout(() => dialog.open && dialog.close(), 350);
} catch (error) {
status.textContent = error.message;
+13 -10
View File
@@ -8,7 +8,8 @@
const names={progress:t('Today’s completion','本日の達成率'),today:t('Today’s tasks','本日のタスク'),tomorrow:t('Tomorrow’s tasks','明日のタスク'),tasks:t('Tasks','タスク'),schedule:t('Today’s schedule','本日のスケジュール'),activity:t('Activity report','達成度・作業レポート')};
const defaults=[['progress',4,3],['today',4,3],['tomorrow',4,3],['tasks',8,4],['schedule',4,4],['activity',12,5]].map(([id,width,height])=>({id,width,height,...(id==='tasks'?{tab:'inbox'}:{})}));
names.feeds=t('RSS · latest cached articles','RSS · 最近の取得記事');
const available=[...defaults,{id:'feeds',width:6,height:4}];
names['tomorrow-schedule']=t('Tomorrow’s schedule','明日のスケジュール');names.commands=t('Task commands','タスクコマンド');
const available=[...defaults,{id:'feeds',width:6,height:4},{id:'tomorrow-schedule',width:6,height:4},{id:'commands',width:6,height:3}];
const tabs={inbox:'Inbox',backlog:'Backlog',someday:'Someday',review:'Review',all:'Incomplete',done:'Done'};
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
function button(text,label,fn){const b=el('button',text);b.type='button';b.title=b.ariaLabel=label;b.onclick=fn;return b;}
@@ -36,7 +37,7 @@
const add=el('select');add.ariaLabel=t('Add widget','ウィジェットを追加');add.onchange=()=>{const item=available.find(w=>w.id===add.value);if(item){widgets.push({...item});render();changed();}};
const reset=button(t('Reset layout','初期配置'),t('Reset layout','初期配置'),()=>{if(confirm(t('Replace this layout with the default layout? Save to apply.','初期配置に戻しますか? 保存するまでは確定しません。'))){widgets=defaults.map(x=>({...x}));render();changed();}});
controls.append(refresh);if(writable)controls.append(edit,add,reset,save);
function updateControls(){save.disabled=!dirty||saving||!loaded;edit.disabled=add.disabled=reset.disabled=saving||!loaded;refresh.disabled=!loaded;root.classList.toggle('dashboard-saving',saving);for(const card of cards.values())card.querySelectorAll('.widget-arrange button,.widget-arrange select,.widget-drag,.widget-resize').forEach(n=>n.disabled=saving);add.replaceChildren();const option=el('option',t('+ Add widget','+ ウィジェットを追加'));option.value='';add.append(option);for(const [id,name] of Object.entries(names)){if(widgets.some(w=>w.id===id)||id==='schedule'&&root.dataset.calendar!=='true')continue;const o=el('option',name);o.value=id;add.append(o);}}
function updateControls(){save.disabled=!dirty||saving||!loaded;edit.disabled=add.disabled=reset.disabled=saving||!loaded;refresh.disabled=!loaded;root.classList.toggle('dashboard-saving',saving);for(const card of cards.values())card.querySelectorAll('.widget-arrange button,.widget-arrange select,.widget-drag,.widget-resize').forEach(n=>n.disabled=saving);add.replaceChildren();const option=el('option',t('+ Add widget','+ ウィジェットを追加'));option.value='';add.append(option);for(const [id,name] of Object.entries(names)){if(widgets.some(w=>w.id===id)||['schedule','tomorrow-schedule'].includes(id)&&root.dataset.calendar!=='true')continue;const o=el('option',name);o.value=id;add.append(o);}}
function changed(){dirty=true;status.textContent=t('Unsaved layout changes','配置は未保存です');updateControls();}
window.addEventListener('beforeunload',event=>{if(dirty){event.preventDefault();event.returnValue='';}});
function applySize(item,card){card.style.setProperty('--widget-width',String(item.width));card.style.setProperty('--widget-height',String(item.height));}
@@ -47,7 +48,7 @@
const card=el('section',undefined,'dashboard-widget');card.id=item.id;card.dataset.widget=item.id;applySize(item,card);
const header=el('header',undefined,'widget-header'),heading=el('h2',names[item.id]);heading.id='widget-title-'+item.id;card.setAttribute('aria-labelledby',heading.id);
header.append(heading);const destinations={progress:'/v/plan/today',today:'/v/plan/today',tomorrow:'/v/plan/tasks/tomorrow',tasks:'/v/plan/tasks',schedule:'/v/plan',activity:'/v/plan/dashboard#activity'};
destinations.feeds='/v/feeds';
destinations.feeds='/v/feeds';destinations['tomorrow-schedule']='/v/plan';destinations.commands='/v/plan/tasks';
const open=link('↗',destinations[item.id]);open.title=open.ariaLabel=t('Open ','開く: ')+names[item.id];header.append(open);
const arrange=el('div',undefined,'widget-arrange');
if(writable){
@@ -81,6 +82,7 @@
if(controller.signal.aborted||!card.isConnected)return;
const signal=AbortSignal.any([controller.signal,AbortSignal.timeout(15000)]);
try{
if(item.id==='commands'){window.PagesDashboardCommands(body,{request,api,t,today,writable,signal:controller.signal,refresh:()=>{for(const w of widgets){if(w.id!=='commands')loadWidget(w,cards.get(w.id));}}});return;}
if(item.id==='feeds'){
const data=await request('/_/api/v1/extension/organizer.feeds/items',{signal});if(controller.signal.aborted)return;
const list=el('ul',undefined,'dashboard-list');for(const item of data.items.slice(0,12)){const row=el('li');row.append(el('span',item.read?'○':'●'),link(item.title||t('(Untitled)','(無題)'),'/v/feeds?'+new URLSearchParams({source:item.source,id:item.id})));list.append(row);}
@@ -94,12 +96,13 @@
const ring=el('div',percentage===null?'—':percentage+'%','dashboard-progress');ring.style.setProperty('--progress',(percentage||0)+'%');
body.append(ring,el('p',data.done+' / '+data.total));return;
}
if(item.id==='schedule'){
if(item.id==='schedule'||item.id==='tomorrow-schedule'){
if(root.dataset.calendar!=='true'){body.replaceChildren(el('p',t('Calendar extension is disabled.','カレンダー拡張は無効です。')));return;}
const data=await request(calendarAPI+'upcoming?period=day',{signal});if(controller.signal.aborted)return;
const list=el('ul',undefined,'dashboard-list'),format=new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{hour:'2-digit',minute:'2-digit',timeZone:zone});
for(const event of data.events){const row=el('li'),a=link(event.summary||t('(Untitled)','(無題)'),event.href);row.append(el('time',event.all_day?t('All day','終日'):format.format(new Date(event.start))),a);list.append(row);}
body.replaceChildren(list);if(!data.events.length)body.append(el('p',t('No events today.','本日の予定はありません。')));body.append(link(t('Open calendar →','カレンダーで確認 →'),'/v/plan'));return;
const date=new Date(today+'T12:00:00Z');if(item.id==='tomorrow-schedule')date.setUTCDate(date.getUTCDate()+1);const day=date.toISOString().slice(0,10);
const data=await request(calendarAPI+'upcoming?period=day&date='+day,{signal});if(controller.signal.aborted)return;const dayURL='/v/plan/cal/'+day.replaceAll('-','/');card.querySelector('.widget-header a').href=dayURL;
const list=el('ul',undefined,'dashboard-list dashboard-agenda'),format=new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{hour:'2-digit',minute:'2-digit',timeZone:zone});
for(const event of data.events){const row=el('li'),a=link(event.summary||t('(Untitled)','(無題)'),event.href);const time=el('time',event.all_day?t('All day','終日'):format.format(new Date(event.start))+'–'+format.format(new Date(event.end)));time.dateTime=event.start;const detail=el('div',undefined,'agenda-event');detail.append(a,el('small',event.calendar));row.append(time,detail);row.dataset.allDay=String(!!event.all_day);if(Date.parse(event.start)<=Date.now()&&Date.parse(event.end)>Date.now())row.classList.add('is-current');list.append(row);}
body.replaceChildren(list);if(!data.events.length)body.append(el('p',t('No events.','予定はありません。')));body.append(link(t('Open calendar →','カレンダーで確認 →'),dayURL));return;
}
const tabbar=el('div',undefined,'widget-tabs');tabbar.setAttribute('role','tablist');tabbar.ariaLabel=names.tasks;
const list=el('div');list.id='widget-panel-'+item.id;list.setAttribute('role','tabpanel');list.tabIndex=0;
@@ -117,9 +120,9 @@
if(!append)list.replaceChildren();panel.querySelector('[data-more]')?.remove();
const ul=el('ul',undefined,'dashboard-list');
for(const task of data.items){const row=el('li');row.dataset.task=task.uuid;
const title=link(task.title,'/v/plan/task/'+encodeURIComponent(task.uuid));title.title=task.title;
const title=link(task.title,'/v/plan/task/'+encodeURIComponent(task.uuid));title.title=task.title;window.PagesTaskPresentation?.render(title,task.title,false);
row.append(el('span',task.status==='done'?'✓':task.status==='cancelled'?'−':task.status==='doing'?'◐':'○'),title);
if(task.due_on)row.append(el('time',task.due_on));ul.append(row);
if(task.page_uuid){const note=link('▣','/v/uuid:'+encodeURIComponent(task.page_uuid));note.title=note.ariaLabel=t('Open linked Wiki page','関連Wikiページを開く');note.className='dashboard-note';row.append(note);}if(task.due_on)row.append(el('time',task.due_on));ul.append(row);
}
list.append(ul);if(!data.items.length&&!append)list.append(el('p',t('No matching tasks.','該当するタスクはありません。')));
if(data.next){const more=button(t('Load more','続きを表示'),t('Load more','続きを表示'),()=>{more.disabled=true;tasks(tab,true,data.next).finally(()=>{more.disabled=false;});});more.dataset.more='true';panel.append(more);}
+92
View File
@@ -0,0 +1,92 @@
(() => {
'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};
}};
})();
+3 -3
View File
@@ -19,7 +19,7 @@
function field(key,type,container){const label=el('label'),n=el(type==='select'?'select':'input');label.append(el('span',labels[key]));if(type!=='select')n.type=type;else ['todo','doing','done','cancelled'].forEach((v,i)=>{const o=el('option',[t('To do','未着手'),t('Doing','進行中'),t('Done','完了'),t('Cancelled','取りやめ')][i]);o.value=v;n.append(o);});n.name=key;n.value=item[key]||'';n.disabled=!writable;n.ariaLabel=labels[key];if(key==='title'){n.required=true;n.maxLength=300;label.className='task-inline-title';}inputs[key]=n;label.append(n);container.append(label);
n.addEventListener('input',()=>{draft[key]=n.value;dirtyRows.add(row);});n.addEventListener('change',()=>{draft[key]=n.value;dirtyRows.add(row);flush();});
n.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();n.blur();}if(e.key==='Escape'){e.preventDefault();n.value=item[key]||'';draft[key]=n.value;flush();}});}
field('title','text',line);field('status','select',line);['planned_on','due_on','review_on','start_on','end_on'].forEach(k=>field(k,'date',dates));
field('title','text',line);const titlePreview=el('div',undefined,'task-title-preview');titlePreview.setAttribute('aria-hidden','true');inputs.title.after(titlePreview);inputs.title.addEventListener('input',()=>window.PagesTaskPresentation?.render(titlePreview,inputs.title.value,false));field('status','select',line);['planned_on','due_on','review_on','start_on','end_on'].forEach(k=>field(k,'date',dates));
const complete=el('button','○');complete.type='button';complete.title=complete.ariaLabel=t('Toggle completion','完了を切り替え');complete.disabled=!writable;complete.dataset.action='complete';complete.addEventListener('click',()=>{draft.status=item.status==='done'?'todo':'done';inputs.status.value=draft.status;dirtyRows.add(row);flush();});line.prepend(complete);
const parent=el('a','↳');parent.title=parent.ariaLabel=t('Parent task','親タスク');parent.hidden=!item.parent_uuid;if(item.parent_uuid){row.classList.add('task-is-child');parent.href='/v/plan/task/'+encodeURIComponent(item.parent_uuid);}row.append(parent,line,dates,actions,status);
function button(label,icon,fn){const b=el('button',icon);b.type='button';b.title=b.ariaLabel=label;b.addEventListener('click',fn);actions.append(b);return b;}
@@ -60,11 +60,11 @@
}
if(edit&&!data.writable){message(t('This Wiki note is read-only.','このWikiメモは読み取り専用です。'));return;}location.assign(edit?data.edit_url:data.url);
}catch(e){message(e.message);}}
button(t('View Wiki note (create if missing)','Wikiメモを表示(未作成なら新規作成)'),'▤',()=>openNote(false)).dataset.action='note-view';
const noteView=button(t('View Wiki note (create if missing)','Wikiメモを表示(未作成なら新規作成)'),'▤',()=>openNote(false));noteView.dataset.action='note-view';
const editNote=button(t('Edit / create Wiki note','Wikiメモを編集・新規作成'),'✎',()=>openNote(true));editNote.dataset.action='note-edit';editNote.disabled=!writable;
if(options.planDate&&writable){button(t('Schedule for ','取り組む日を変更:')+options.planDate,'→',()=>{if(blocked())return;draft.planned_on=options.planDate;inputs.planned_on.value=draft.planned_on;dirtyRows.add(row);flush();}).dataset.action='schedule-day';}
const estimate=el('small',undefined,'task-inline-estimate');actions.prepend(estimate);
function paint(){row.dataset.done=String(['done','cancelled'].includes(item.status));complete.textContent=item.status==='done'?'✓':'○';row.dataset.archived=String(item.archived);estimate.textContent=item.estimate_minutes?item.estimate_minutes+' min':'';}
function paint(){window.PagesTaskPresentation?.render(titlePreview,item.title,false);noteView.classList.toggle('has-wiki-note',!!item.page_uuid);noteView.textContent=item.page_uuid?'▣':'▤';noteView.title=noteView.ariaLabel=item.page_uuid?t('Open linked Wiki page','関連Wikiページを開く'):t('Create Wiki note','Wikiメモを作成');row.dataset.done=String(['done','cancelled'].includes(item.status));complete.textContent=item.status==='done'?'✓':'○';row.dataset.archived=String(item.archived);estimate.textContent=item.estimate_minutes?item.estimate_minutes+' min':'';}
async function flush(){if(saving||!writable||!Object.keys(draft).length)return;if(!inputs.title.reportValidity())return;saving=true;row.setAttribute('aria-busy','true');message(t('Saving…','保存中…'),'saving');try{while(Object.keys(draft).length){const patch={...draft};const fresh=await request(api+'/'+item.uuid);const saved=await request(api+'/'+item.uuid,{method:'PUT',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify({...fresh.item,...patch})});item=saved.item;for(const [k,v]of Object.entries(patch)){if(draft[k]===v)delete draft[k];}paint();}dirtyRows.delete(row);message(t('Saved','保存しました'),'saved');document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));options.onChanged?.(item,row);}catch(e){message(e.message);}finally{saving=false;row.removeAttribute('aria-busy');}}
const restoreExpanded=expandedRows.has(item.uuid);
if(options.initialChildren?.length){options.initialChildren.forEach(c=>children.append(create(c,{...options,initialChildren:[],context:false,nested:true})));showChildren(true);}
+29
View File
@@ -0,0 +1,29 @@
(() => {
'use strict';
// Small inline-only dialect: no HTML, images, macros or remote rendering.
function render(node, source, links = true, depth = 0) {
node.replaceChildren();
if (depth > 8) { node.textContent=source; return; }
const pattern=/\\([\\`*_\[\]~])|(`+)([^`]+)\2|\*\*(.+?)\*\*|__(.+?)__|~~(.+?)~~|\*([^*]+)\*|_([^_]+)_|\[([^\]]+)\]\(([^\s)]+)\)/g;
let offset=0;
for(const m of source.matchAll(pattern)) {
node.append(document.createTextNode(source.slice(offset,m.index)));
if(m[1]){node.append(document.createTextNode(m[1]));offset=m.index+m[0].length;continue;}
let tag,text;
if(m[2]) {tag='code';text=m[3];} else if(m[4]||m[5]) {tag='strong';text=m[4]||m[5];}
else if(m[6]) {tag='del';text=m[6];} else if(m[7]||m[8]) {tag='em';text=m[7]||m[8];}
else {tag='span';text=m[9];if(links&&safeReference(m[10]))tag='a';}
const child=document.createElement(tag);
if(tag==='a') {child.href=m[10];child.rel='noopener noreferrer';}
if(tag==='code')child.textContent=text;else render(child,text,false,depth+1);
node.append(child);offset=m.index+m[0].length;
}
node.append(document.createTextNode(source.slice(offset)));
}
function safeReference(ref) {
if(!ref||/[\\\s\x00-\x1f]/.test(ref))return false;
if(ref.startsWith('/')&&!ref.startsWith('//'))return true;
try {const u=new URL(ref);return ['http:','https:'].includes(u.protocol)&&!u.username&&!u.password;}catch{return false;}
}
window.PagesTaskPresentation={render,safeReference};
})();
+10 -5
View File
@@ -3,6 +3,7 @@
const app = document.getElementById('tasks-app'); if (!app) return;
const ja = document.documentElement.lang.startsWith('ja');
const words = {
index:['Keyboard task index','キーボード一覧'],
delete:['Delete','削除'],deleted:['This task has been deleted.','このタスクは削除されています。'],has_children:['Move or delete the subtasks first, including archived subtasks.','先にサブタスクを移動または削除してください(アーカイブ済みも含みます)。'],working:['Stop the running work timer or focus session before deleting this task.','作業時間の記録・集中セッションを停止してから削除してください。'],deleteConfirm:['Delete this task? This cannot be undone. Wiki notes, calendar events and recorded work time will remain. Unsaved changes will be discarded.','このタスクを削除しますか?復元できません。Wikiメモ、カレンダーの予定、記録済みの作業時間は残ります。未保存の変更は破棄されます。'],
carryover:['Carryover','持ち越し'],tomorrow:['Tomorrow','明日'],day:['Daily plan','日別の計画'],notes_subpath:['Wiki note subfolder (relative to the project Wiki page)','Wikiメモのサブ階層(プロジェクトの関連Wiki配下)'],
start_on:['Work starts','工程開始'],end_on:['Work ends','工程終了'],schedule:['Day schedule','日割り工程表'],
@@ -17,6 +18,7 @@
const view = app.dataset.view, projectID = view === 'project' ? app.dataset.id : '';
const writable = app.dataset.writable === 'true';
let today = app.dataset.today;
let indexBrowser, indexProject=null;
let selectedDate=app.dataset.selectedDate||today;
const loadedItems=new Map(),contextParents=new Map();
const nextDay=date=>{const d=new Date(date+'T12:00:00Z');d.setUTCDate(d.getUTCDate()+1);return d.toISOString().slice(0,10);};
@@ -32,7 +34,7 @@
}
const href = item => '/v/plan/' + item.kind + '/' + encodeURIComponent(item.uuid);
const routes = {today:'/v/plan/today',all:'/v/plan/tasks',projects:'/v/plan/projects'};
const icons = {carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
const icons = {index:'⌨',carryover:'↶',today:'☀',tomorrow:'⇢',inbox:'↓',backlog:'≡',someday:'◇',review:'↻',all:'☷',projects:'▱',done:'✓',archived:'▣'};
Object.keys(icons).forEach(key => { const a = el('a'); a.href = routes[key] || '/v/plan/tasks/' + key; a.append(el('span',icons[key]),el('span',t(key))); if(view===key||(key==='tomorrow'&&view==='day'&&selectedDate===nextDay(today)))a.setAttribute('aria-current','page'); $('nav').append(a); });
const schedule=el('a','▦ '+t('schedule'));schedule.href='/v/plan/tasks/schedule'+(projectID?'?project='+projectID:'');$('nav').append(schedule);const workHistory=el('a',ja?'◷ 作業記録':'◷ Work history');workHistory.href='/v/plan/tasks/work';$('nav').append(workHistory);
$('date').textContent = view==='day'?selectedDate:today; $('heading').textContent = t(view === 'project' ? 'project' : view === 'detail' || view === 'new' ? 'all' : view);
@@ -56,9 +58,10 @@
if(!writable)$('help').textContent+=' '+t('readonly');
let taskDefaults={},reminderDefaults={};
async function refreshDefaults(){const data=await request('/_/api/v1/extension/organizer.tasks/preferences');taskDefaults=data.defaults;reminderDefaults=data.preferences;}
function blank(kind='task') { const defaults=kind==='task'?taskDefaults:{};const item={ ...defaults,uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:defaults.estimate_minutes||0,project_uuid:kind==='task'?(projectID||defaults.project_uuid||''):'',page_uuid:'',due_on:defaults.due_on||'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):(defaults.planned_on||''),review_on:defaults.review_on||'',archived:false,version:0 };if(kind==='task'){item.notify_due=!!(reminderDefaults.notify_due&&item.due_on);item.notify_planned=!!(reminderDefaults.notify_planned&&item.planned_on);}return item; }
function blank(kind='task') { const defaults=kind==='task'?taskDefaults:{};const item={ ...defaults,uuid:crypto.randomUUID(),kind,title:'',notes:'',status:'todo',bucket:['inbox','backlog','someday'].includes(view)?view:'inbox',priority:1,estimate_minutes:defaults.estimate_minutes||0,project_uuid:kind==='task'?(view==='index'&&indexProject!==null?indexProject:(projectID||defaults.project_uuid||'')):'',page_uuid:'',due_on:defaults.due_on||'',planned_on:['today','day'].includes(view)&&kind==='task'?(view==='day'?selectedDate:today):(defaults.planned_on||''),review_on:defaults.review_on||'',archived:false,version:0 };if(kind==='task'){item.notify_due=!!(reminderDefaults.notify_due&&item.due_on);item.notify_planned=!!(reminderDefaults.notify_planned&&item.planned_on);}return item; }
function listView(){return ['project','detail','new'].includes(view)?'all':view;}
async function load(append=false) {
if(indexBrowser)return indexBrowser.reload(append);
if(window.PagesWikiTaskRows?.hasDirty()){$('status').textContent=ja?'編集中の行を保存または再読込してください。':'Save or reload edited rows first.';return;}
const ticket=++generation; listController?.abort();listController=new AbortController();$('status').textContent=t('loading');$('more').disabled=true;
const q=new URLSearchParams({kind:view==='projects'?'project':view==='archived'?$('kind').value:'task',view:listView(),q:$('search').value,project:projectID,hierarchy:'1'});if(view==='day')q.set('date',selectedDate);if(append&&next)q.set('before',next);
@@ -86,7 +89,7 @@
if(item.kind==='task'&&window.PagesWikiTaskRows){$('list').append(window.PagesWikiTaskRows.create(item,rowOptions()));return;}
const row=el('div',undefined,'task-row');row.role='listitem';row.dataset.done=String(item.status==='done'||item.status==='cancelled');
if(item.kind==='task'&&writable){const b=el('button',item.status==='done'?'✓':'○');b.type='button';b.title=b.ariaLabel=t(item.status==='done'?'reopen':'complete');b.addEventListener('click',async()=>{b.disabled=true;try{const {item:fresh}=await request(api+'/'+item.uuid);fresh.status=fresh.status==='done'?'todo':'done';await saveItem(fresh);await load();}catch(e){$('status').textContent=e.message;}finally{b.disabled=false;}});row.append(b);}
const main=el('div',undefined,'task-row-main'), a=el('a',item.title);a.href=href(item);if(item.kind==='task')a.addEventListener('click',e=>{if(e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;e.preventDefault();open(item.uuid);});main.append(a);
const main=el('div',undefined,'task-row-main'), a=el('a',item.title);window.PagesTaskPresentation?.render(a,item.title,false);a.href=href(item);if(item.kind==='task')a.addEventListener('click',e=>{if(e.button||e.ctrlKey||e.metaKey||e.shiftKey||e.altKey)return;e.preventDefault();open(item.uuid);});main.append(a);
const meta=el('div',undefined,'task-row-meta');meta.append(el('span',t(item.status)));if(item.kind==='task'){if(item.due_on)meta.append(el('span',t('due_on')+' '+item.due_on,item.due_on<today?'task-overdue':''));if(item.planned_on)meta.append(el('span',t('planned_on')+' '+item.planned_on));if(item.priority>=2)meta.append(el('span',t(item.priority===3?'urgent':'high')));if(item.estimate_minutes)meta.append(el('span',item.estimate_minutes+' min'));}main.append(meta);row.append(main);$('list').append(row);
}
const fields={};
@@ -147,6 +150,8 @@
if(!id)for(const [date,key] of [['due_on','notify_due'],['planned_on','notify_planned']]){let touched=false;fields[key].addEventListener('change',()=>{touched=true;});fields[date].addEventListener('input',()=>{if(!touched){fields[key].checked=!!(fields[date].value&&reminderDefaults[key]);requirements();}});}
}
if(editing.kind==='project'){const folder=field('notes_subpath',t('notes_subpath'),'text',editing.notes_subpath||'tasks',true);folder.maxLength=500;folder.placeholder='tasks';$('fields').append(el('small',ja?'例:関連Wikiが /projects/app、サブ階層が tasks → /projects/app/tasks/件名。Wikiの公開範囲に従います。':'Example: project Wiki /projects/app + subfolder tasks → /projects/app/tasks/title. Wiki permissions apply.','task-full'));}
const refs=field('references',ja?'URL / 添付Path(1行に1件)':'URLs / attachment Paths (one per line)','textarea',(editing.references||[]).join('\n'),true);refs.maxLength=81920;
const referenceLinks=el('div',undefined,'task-full');for(const ref of editing.references||[]){if(!window.PagesTaskPresentation.safeReference(ref))continue;const a=el('a',ref);a.href=ref;a.target='_blank';a.rel='noopener noreferrer';referenceLinks.append(a,el('br'));}$('fields').append(referenceLinks);
field('page_path',t('page'),'text',data.page_path,true).placeholder='/lab/project';
const updatePageLink=()=>{const a=$('page-open');a.hidden=!data.page_path||!editing.page_uuid||fields.page_path.value!==data.page_path;a.removeAttribute('href');if(!a.hidden)a.href='/'+data.page_path.replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');};
$('page-open').textContent=t('linked')+' ↗';$('page-open').title=ja?'関連ページを新しいタブで開く':'Open related page in a new tab';updatePageLink();
@@ -168,7 +173,7 @@
$('close').addEventListener('click',()=>closeDialog());$('dialog').addEventListener('cancel',e=>{e.preventDefault();closeDialog();});
$('form').addEventListener('input',()=>{dirty=true;});
$('form').addEventListener('invalid',event=>{const details=event.target.closest('details');if(details)details.open=true;},true);
function readForm(){const item={...editing};['title','notes','notes_subpath','status','bucket','project_uuid','assignee_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes','complexity'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
function readForm(){const item={...editing};if(fields.references)item.references=fields.references.value.split('\n').map(x=>x.trim()).filter(Boolean);['title','notes','notes_subpath','status','bucket','project_uuid','assignee_uuid','due_on','planned_on','review_on','start_on','end_on','reminder_time'].forEach(k=>{if(fields[k])item[k]=fields[k].value;});['notify_due','notify_planned'].forEach(k=>{if(fields[k])item[k]=fields[k].checked;});['priority','estimate_minutes','complexity'].forEach(k=>{if(fields[k])item[k]=Number(fields[k].value);});if(fields.page_path?.dataset.changed||(!item.page_uuid&&fields.page_path?.value))item.page_path=fields.page_path.value;return item;}
async function saveItem(item){const data=await request(api+(item.version?'/'+item.uuid:''),{method:item.version?'PUT':'POST',headers:item.version?{'If-Match':'"'+item.version+'"'}:{},body:JSON.stringify(item)});app.dispatchEvent(new Event('task-today-refresh'));return data;}
async function submit(archive=false){if(!editing||saving||!writable)return;if(!$('form').reportValidity())return;const item=readForm();if(archive)item.archived=!item.archived;saving=true;Object.values(fields).forEach(f=>f.disabled=true);$('save').disabled=$('archive').disabled=$('delete').disabled=true;$('error').textContent='';try{await saveItem(item);saving=false;closeDialog(true);await load();if(projectID)await loadProject();}catch(e){$('error').textContent=e.message;}finally{saving=false;Object.values(fields).forEach(f=>f.disabled=!writable);$('save').disabled=$('archive').disabled=$('delete').disabled=false;}}
$('delete').addEventListener('click',async()=>{
@@ -194,5 +199,5 @@
$('project-edit').addEventListener('click',()=>open(projectID));
window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&!$('dialog').open&&!capturing)load();});
load();if(projectID)loadProject();if(view==='detail')open(app.dataset.id);if(view==='new')open('');
if(view==='index')indexBrowser=window.PagesTaskIndex.mount({app,open,setProject:id=>{indexProject=id==='none'?'':id||null;}});else load();if(projectID)loadProject();if(view==='detail')open(app.dataset.id);if(view==='new')open('');
})();