(() => { 'use strict'; const app=document.getElementById('tasks-app');if(!app)return; const ja=document.documentElement.lang.startsWith('ja'), text=(en,jp)=>ja?jp:en; const root='/_/api/v1/extension/organizer.tasks/', writable=app.dataset.writable==='true'; const el=(tag,value)=>{const n=document.createElement(tag);if(value!==undefined)n.textContent=value;return n;}; const dialog=el('dialog');dialog.id='tasks-plan-dialog';dialog.setAttribute('aria-labelledby','tasks-plan-title'); const header=el('header');header.className='tasks-toolbar';const title=el('h2',text('Calendar time blocks','カレンダーの時間枠'));title.id='tasks-plan-title'; const close=el('button','×');close.type='button';close.ariaLabel=text('Close','閉じる');header.append(title,close); const help=el('p',text('Private local calendars only. Event titles include the task title; sharing this calendar later exposes that title. Notes are not copied. Unlink keeps the event.','自分専用・非公開のローカルカレンダーのみ。予定名にタスクの件名を含めます。後からカレンダーを公開・共有すると件名も見えます。メモはコピーせず、関連を解除しても予定は残ります。'));help.className='tasks-muted'; const form=el('form'), inputs={}, fields=el('div');fields.className='task-plan-fields'; function field(name,label,type){const wrap=el('label',label),input=el(type==='select'?'select':'input');if(type!=='select')input.type=type;input.name=name;input.required=true;inputs[name]=input;wrap.append(input);fields.append(wrap);return input;} const select=field('calendar_uuid',text('Calendar','カレンダー'),'select'); const start=field('start',text('Start','開始'),'datetime-local'),end=field('end',text('End','終了'),'datetime-local');start.step=end.step=60; const zone=el('small'),save=el('button',text('Add time block','時間枠を追加'));save.type='submit';form.append(fields,zone,save); const status=el('p');status.role='status';status.setAttribute('aria-live','polite'); const list=el('div');list.id='tasks-plan-list';const more=el('button',text('Load more','続きを表示'));more.type='button';more.hidden=true; const refresh=el('button','↻');refresh.type='button';refresh.ariaLabel=refresh.title=text('Refresh','更新');header.append(refresh); dialog.append(header,help,form,status,list,more);app.append(dialog); let task,ticket=0,busy=false,mutating=false,controller=null,draft=null,items=[],offset=0,timezone=app.dataset.timezone; const message=code=>({conflict:text('Changed elsewhere, or this request was unlinked. Reopen the task to review it.','別の画面で変更されたか、関連付けが解除されています。タスクを開き直してください。'),forbidden:text('This calendar must be private, local and owned by you.','自分所有の非公開・ローカルカレンダーのみ利用できます。'),not_found:text('Unavailable. Check the calendar and extension settings.','利用できません。カレンダーや拡張機能の設定を確認してください。'),invalid:text('Check dates (up to 24 hours), task status and timezone.','日時(24時間以内)・タスクの状態・タイムゾーンを確認してください。')}[code]||text('Request failed. Retry using the same request, or reopen this dialog to inspect pending blocks.','処理に失敗しました。同じ要求を再試行するか、画面を開き直して未完了の関連付けを確認してください。')); async function request(path,options={}){ const res=await fetch(root+path,{credentials:'same-origin',signal:AbortSignal.any([controller.signal,AbortSignal.timeout(15000)]),...options,headers:{'Content-Type':'application/json',...options.headers}}); if(res.status===204)return{};const data=await res.json().catch(()=>({}));if(!res.ok||res.redirected)throw new Error(message(data.error||(res.status===404?'not_found':'')));return data; } function localValue(date){const p=new Intl.DateTimeFormat('en-CA',{timeZone:timezone,year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(date);const get=k=>p.find(v=>v.type===k).value;return `${get('year')}-${get('month')}-${get('day')}T${get('hour')}:${get('minute')}`;} function display(date){return new Intl.DateTimeFormat(ja?'ja-JP':'en-GB',{timeZone:timezone,month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}).format(new Date(date));} function lock(value){busy=value;close.disabled=value&&mutating;refresh.disabled=more.disabled=value;save.disabled=value;Object.values(inputs).forEach(n=>n.disabled=value||!!draft);list.querySelectorAll('button').forEach(n=>n.disabled=value||!writable);} function dismiss(){if(mutating)return;ticket++;controller?.abort();dialog.close();draft=null;} close.addEventListener('click',dismiss);dialog.addEventListener('cancel',e=>{e.preventDefault();dismiss();}); async function appendRows(gen){ const batch=items.slice(offset,offset+10);offset+=batch.length;more.hidden=offset>=items.length; for(const b of batch){ if(gen!==ticket||!dialog.open)return; const row=el('section');row.className='task-plan-row';row.dataset.uuid=b.uuid;const summary=el('span',display(b.start)+' – '+display(b.end));row.append(summary);list.append(row); try{ const current=await request('blocks/'+b.uuid);if(gen!==ticket)return; if(current.available){const a=el('a',display(current.start)+' – '+display(current.end));a.href=current.href;summary.replaceWith(a);} else summary.textContent=text('Event unavailable (removed, shared, or calendar unavailable)','予定を参照できません(削除・共有・カレンダー利用不可)'); if(b.state==='pending')row.append(el('small',text('Pending request','未完了の連携要求'))); }catch(e){summary.textContent=e.message;} if(!writable)continue; const actions=el('div');actions.className='tasks-actions'; if(b.state==='pending'){const retry=el('button',text('Retry','再試行'));retry.type='button';retry.addEventListener('click',()=>mutate(()=>request('blocks',{method:'POST',body:JSON.stringify({uuid:b.uuid,task_uuid:task.uuid,task_version:task.version,calendar_uuid:b.calendar_uuid,start:b.start,end:b.end})})));actions.append(retry);} const unlink=el('button',text('Unlink','関連を解除'));unlink.type='button';unlink.addEventListener('click',()=>{if(confirm(text('Unlink? The calendar event will be kept.','関連を解除しますか? カレンダーの予定は残ります。')))mutate(()=>request('blocks/'+b.uuid,{method:'DELETE'}));});actions.append(unlink);row.append(actions); } } async function reload(){const gen=++ticket;status.textContent=text('Loading…','読み込み中…');const data=await request('blocks?task_uuid='+encodeURIComponent(task.uuid));if(gen!==ticket)return;items=data.items;offset=0;list.replaceChildren();await appendRows(gen);if(gen===ticket)status.textContent=items.length?'':text('No time blocks yet.','時間枠はまだありません。');} async function mutate(fn){if(busy)return;mutating=true;lock(true);status.textContent='';try{await fn();app.dispatchEvent(new Event('task-today-refresh'));mutating=false;lock(true);await reload();}catch(e){status.textContent=e.message;}finally{mutating=false;lock(false);}} more.addEventListener('click',async()=>{if(busy)return;lock(true);try{await appendRows(ticket);}finally{lock(false);}}); refresh.addEventListener('click',()=>mutate(async()=>{})); form.addEventListener('submit',e=>{e.preventDefault();if(busy||!task)return; if(!draft)draft={uuid:crypto.randomUUID(),task_uuid:task.uuid,task_version:task.version,calendar_uuid:select.value,start:start.value,end:end.value,timezone}; mutate(async()=>{await request('blocks',{method:'POST',body:JSON.stringify(draft)});draft=null;}); }); app.addEventListener('task-plan',async e=>{ if(dialog.open||busy)return;controller=new AbortController();task=e.detail;draft=null;list.replaceChildren();more.hidden=true;form.hidden=true;status.textContent=text('Loading…','読み込み中…');dialog.showModal();const gen=++ticket;lock(true); try{const data=await request('calendars');if(gen!==ticket)return;timezone=data.timezone;zone.textContent=timezone;select.replaceChildren();data.items.forEach(c=>{const o=el('option',c.name+' ('+c.pretty_name+')');o.value=c.id;select.append(o);}); const now=new Date(Math.ceil(Date.now()/300000)*300000);start.value=localValue(now);end.value=localValue(new Date(now.getTime()+Math.min(1440,task.estimate_minutes||25)*60000)); const plannedDate=app.dataset.view==='day'?app.dataset.selectedDate:task.planned_on; if(/^\d{4}-\d{2}-\d{2}$/.test(plannedDate||'')){ start.value=plannedDate+start.value.slice(10); const wallTime=new Date(start.value+':00Z');wallTime.setUTCMinutes(wallTime.getUTCMinutes()+Math.min(1440,task.estimate_minutes||25));end.value=wallTime.toISOString().slice(0,16); } form.hidden=!writable||task.archived||['done','cancelled'].includes(task.status)||!data.items.length; await reload();if(!data.items.length)status.textContent=text('Create a private local calendar in Calendar settings first.','カレンダーの設定で、自分専用の非公開ローカルカレンダーを作成してください。'); }catch(err){status.textContent=err.message;}finally{lock(false);} }); })();