77 lines
15 KiB
JavaScript
77 lines
15 KiB
JavaScript
(() => {
|
||
'use strict';
|
||
if(window.PagesWikiTaskRows)return;
|
||
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en,api='/_/api/v1/extension/organizer.tasks/items';
|
||
const el=(tag,value,cls)=>{const n=document.createElement(tag);if(value!==undefined)n.textContent=value;if(cls)n.className=cls;return n;};
|
||
const dirtyRows=new Set();
|
||
const expandedRows=new Set();
|
||
const labels={title:t('Title','件名'),status:t('Status','状態'),planned_on:t('Planned','取り組む日'),due_on:t('Due','期限'),review_on:t('Review','見直す日'),start_on:t('Work starts','工程開始'),end_on:t('Work ends','工程終了')};
|
||
const header=document.createElement('div');header.className='task-inline-header';header.setAttribute('aria-hidden','true');
|
||
['',...Object.values(labels),t('Actions','操作')].forEach(label=>header.append(el('span',label)));
|
||
document.getElementById('tasks-list')?.before(header);
|
||
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}});const data=await r.json().catch(()=>({}));if(!r.ok||r.redirected){const messages={note_setup:t('Set a project and its related Wiki page first (project settings → note subfolder).','先にプロジェクトを選び、その設定で関連Wikiページとメモのサブ階層を指定してください。'),note_exists:t('A page already exists here. Link it explicitly in task details, or change the title.','同じPathのページが既にあります。タスクの詳細から明示的に関連付けるか、件名を変更してください。')};throw Error(messages[data.error]||(r.status===412?t('Changed elsewhere. Input kept; reload to discard it.','別の画面で変更されています。入力は保持しています。「再読込」で破棄して最新版を取得できます。'):t('Unable to save. Check permissions, dates and reminder requirements.','保存できません。権限・日付の順序・通知に必要な日付を確認してください。')));}return data;}
|
||
function create(initial,options={}){
|
||
let item={...initial},draft={},saving=false,childDraft=null;const writable=options.writable!==false;
|
||
const row=el('article',undefined,'task-inline-row');row.dataset.taskId=item.uuid;row.setAttribute('role','listitem');
|
||
const line=el('div',undefined,'task-inline-main'), dates=el('div',undefined,'task-inline-dates'), actions=el('div',undefined,'tasks-actions'),status=el('span',undefined,'task-inline-status');status.role='status';
|
||
const inputs={};
|
||
function message(text,state='error'){status.textContent=text;status.dataset.state=state;}
|
||
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);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;}
|
||
const detail=el('a','⋯');detail.title=detail.ariaLabel=t('Details','詳細');detail.href='/v/plan/task/'+item.uuid;detail.dataset.action='detail';if(options.onDetail)detail.addEventListener('click',e=>{if(e.ctrlKey||e.metaKey||e.shiftKey||e.button)return;e.preventDefault();if(blocked())return;options.onDetail(item.uuid);});actions.append(detail);
|
||
function blocked(){if(saving||dirtyRows.has(row)){message(t('Save or reload this row first.','先にこの行の変更を保存するか再読込してください。'));return true;}return false;}
|
||
if(writable&&!item.archived)button(t('Start work recording','作業時間を記録開始'),'▶',()=>{if(!blocked())document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-work',{detail:item}));}).dataset.action='work';
|
||
button(t('Calendar time blocks','カレンダーへ時間枠を追加'),'▦',async()=>{if(blocked())return;try{const d=await request(api+'/'+item.uuid);document.getElementById('tasks-app')?.dispatchEvent(new CustomEvent('task-plan',{detail:d.item}));}catch(e){message(e.message);}}).dataset.action='plan';
|
||
const reset=button(t('Reload row (discard edits)','行を再読込(編集を破棄)'),'↻',async()=>{if(saving)return;if(dirtyRows.has(row)&&!confirm(t('Discard changes in this row?','この行の変更を破棄しますか?')))return;try{const d=await request(api+'/'+item.uuid);item=d.item;draft={};dirtyRows.delete(row);Object.keys(inputs).forEach(k=>inputs[k].value=item[k]||'');paint();message('','idle');}catch(e){message(e.message);}});reset.dataset.action='reload';
|
||
function buttonMore(cursor){const more=el('button',t('More subtasks','続きのサブタスク'));more.type='button';more.className='task-children-more';more.addEventListener('click',async()=>{if(dirtyRows.size)return;more.disabled=true;try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100,before:cursor}));if(dirtyRows.size)return;d.items.forEach(c=>more.before(create(c,{...options,initialChildren:[],context:false,nested:true})));if(d.next)more.replaceWith(buttonMore(d.next));else more.remove();}catch(e){message(e.message);}finally{more.disabled=false;}});return more;}
|
||
const children=el('div',undefined,'task-inline-children');children.hidden=true;children.role='list';children.ariaLabel=t('Subtasks','サブタスク');row.append(children);
|
||
let expand;function showChildren(show){children.hidden=!show;if(show)expandedRows.add(item.uuid);else expandedRows.delete(item.uuid);if(expand){expand.textContent=show?'▾':'▸';expand.setAttribute('aria-expanded',String(show));expand.title=expand.ariaLabel=show?t('Hide subtasks','サブタスクを閉じる'):t('Show subtasks','サブタスクを表示');}}
|
||
if(!item.parent_uuid){
|
||
let childRequest=0,loadAll;
|
||
async function loadChildren(){
|
||
if(blocked()||dirtyRows.size)return;
|
||
const ticket=++childRequest;showChildren(true);
|
||
try{const d=await request(api+'?'+new URLSearchParams({view:'family',parent:item.uuid,limit:100}));
|
||
if(ticket!==childRequest||dirtyRows.size||!row.isConnected)return;
|
||
children.replaceChildren();d.items.forEach(c=>children.append(create(c,{...options,initialChildren:[],context:false,nested:true})));
|
||
if(!d.items.length)children.append(el('small',t('No subtasks.','サブタスクはありません。')));
|
||
if(d.next)children.append(buttonMore(d.next));
|
||
if(loadAll)loadAll.hidden=true;
|
||
}catch(e){message(e.message);}
|
||
}
|
||
expand=button(t('Show subtasks','サブタスクを表示'),'▸',()=>{if(blocked()||dirtyRows.size)return;if(!children.hidden){childRequest++;showChildren(false);}else loadChildren();});expand.dataset.action='children';expand.setAttribute('aria-expanded','false');
|
||
if(options.initialChildren?.length){loadAll=button(t('Load all subtasks, including other dates','別の日付も含めてすべてのサブタスクを表示'),'⇊',loadChildren);loadAll.dataset.action='children-all';}
|
||
if(writable&&!item.archived){const add=el('form',undefined,'task-child-capture'),input=el('input'),submit=el('button','+');input.required=true;input.maxLength=300;input.placeholder=input.ariaLabel=t('New subtask','サブタスクを追加');submit.type='submit';submit.title=t('Add subtask','サブタスクを追加');add.append(input,submit);add.hidden=true;row.append(add);button(t('Add subtask','サブタスクを追加'),'+',()=>{if(blocked())return;add.hidden=!add.hidden;if(!add.hidden)input.focus();}).dataset.action='add-child';
|
||
input.addEventListener('input',()=>{if(input.value)dirtyRows.add(add);else dirtyRows.delete(add);});
|
||
add.addEventListener('submit',async e=>{e.preventDefault();if(submit.disabled||blocked())return;const title=input.value.trim();if(!title)return;submit.disabled=input.disabled=true;try{if(!childDraft||childDraft.title!==title){const preferences=await request('/_/api/v1/extension/organizer.tasks/preferences');childDraft={...preferences.defaults,uuid:crypto.randomUUID(),kind:'task',title,notes:'',parent_uuid:item.uuid,project_uuid:item.project_uuid,status:'todo',bucket:item.bucket,priority:item.priority,archived:false,version:0};}const d=await request(api,{method:'POST',body:JSON.stringify(childDraft)});childDraft=null;childRequest++;input.value='';dirtyRows.delete(add);showChildren(true);children.querySelector('small')?.remove();children.append(create(d.item,{...options,initialChildren:[],context:false,nested:true}));document.getElementById('tasks-app')?.dispatchEvent(new Event('task-today-refresh'));}catch(err){message(err.message);}finally{submit.disabled=input.disabled=false;input.focus();}});
|
||
}
|
||
}
|
||
if(options.context){row.dataset.context='true';const badge=el('small',t('Parent','親'),'task-context-badge');badge.title=t('Context only: this parent is outside the current filter.','親子関係を示すために表示しています。親自体は現在の条件の対象外です。');inputs.title.parentElement.append(badge);}
|
||
async function openNote(edit){if(blocked()||dirtyRows.size)return;try{let data=await request(api+'/'+item.uuid+'/note');if(!data.linked){
|
||
if(data.exists){message(t('A page already exists here. Link it in task details.','同じPathのページが既にあります。タスクの詳細から関連付けてください。'));return;}
|
||
if(!data.writable){message(t('No permission to create this Wiki note.','このWikiメモを作成する権限がありません。'));return;}
|
||
if(!confirm(t('Create a Wiki note at ','次のPathにWikiメモを作成します:')+data.path+'\n\n'+t('Its visibility follows the Wiki path, not this private task.','公開範囲は個人タスクではなく、WikiのPathの設定に従います。')))return;
|
||
data=await request(api+'/'+item.uuid+'/note',{method:'POST',headers:{'If-Match':'"'+item.version+'"'},body:JSON.stringify({path:data.path})});item=data.item;edit=true;
|
||
}
|
||
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);}}
|
||
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(){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);}
|
||
else if(expand&&restoreExpanded){queueMicrotask(()=>{if(row.isConnected)expand.click();});}
|
||
paint();return row;
|
||
}
|
||
window.addEventListener('beforeunload',e=>{if(dirtyRows.size){e.preventDefault();e.returnValue='';}});
|
||
window.PagesWikiTaskRows={create,request,hasDirty:()=>dirtyRows.size>0};
|
||
})();
|