@adamchanadam/agent-handoff-kit 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/bin/agent-handoff-kit.mjs +7107 -7047
- package/bin/commands.mjs +134 -134
- package/bin/handoff-read.mjs +88 -88
- package/bin/installed-file-contract.mjs +154 -90
- package/bin/migration-baselines/official-origin-catalog.json +280 -1
- package/bin/official-origin-catalog.mjs +294 -294
- package/bin/progress/ICON-LICENSE.txt +21 -21
- package/bin/progress/assets.mjs +6 -6
- package/bin/progress/dashboard.mjs +134 -134
- package/bin/progress/icons.svg +36 -36
- package/bin/progress/index.html +31 -31
- package/bin/progress/launch.mjs +40 -40
- package/bin/progress/open.mjs +43 -43
- package/bin/progress/project-version.mjs +121 -121
- package/bin/progress/projection.mjs +144 -144
- package/bin/progress/renderer.js +152 -152
- package/bin/progress/server.mjs +78 -78
- package/bin/progress/styles.css +31 -31
- package/bin/prompt-mirror-core.mjs +84 -84
- package/bin/upgrade-inventory.mjs +243 -243
- package/bin/user-rules-router.mjs +4 -4
- package/docs/commands.md +2 -2
- package/docs/progress.md +73 -73
- package/package.json +22 -22
- package/packs/agent-governance.md +120 -120
- package/packs/closeout.md +91 -91
- package/packs/coding.md +28 -28
- package/packs/integrations.md +19 -19
- package/packs/knowledge.md +3 -3
- package/packs/onboarding.md +45 -45
- package/packs/research.md +30 -30
- package/packs/safety.md +2 -2
- package/runtime-core/AGENTS.core.md +161 -161
- package/runtime-core/CLAUDE.md +13 -13
- package/runtime-core/DOC_SYNC_REGISTRY.md +24 -24
- package/runtime-core/GEMINI.md +17 -17
- package/runtime-core/PROJECT_DECISIONS.md +43 -43
- package/runtime-core/PROJECT_INDEX.md +16 -16
- package/runtime-core/RULE_PACKS.md +1 -1
- package/runtime-core/SESSION_HANDOFF.md +180 -180
- package/runtime-core/SESSION_LOG.md +37 -37
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
- package/runtime-core/USER_RULES_ENTRY.md +5 -5
package/bin/progress/renderer.js
CHANGED
|
@@ -1,152 +1,152 @@
|
|
|
1
|
-
// Fixed, bilingual UI. No model requests or project-specific content.
|
|
2
|
-
'use strict';
|
|
3
|
-
(()=>{
|
|
4
|
-
const $=s=>document.querySelector(s),dict={
|
|
5
|
-
creatorRole:['作者|AI 生活策展人','Creator · AI Lifestyle Curator'],
|
|
6
|
-
handoffSaved:['交接保存:{date}','Handoff saved: {date}'],recordedCurrent:['交接記錄的目前工作','Current work recorded in handoff'],legacyWork:['尚未分類;以下直接顯示交接紀錄。','Not classified yet. Showing the handoff records below.'],morePending:['另有 {n} 項,查看全部工作','{n} more items · View all work'],moreLegacy:['另有 {n} 項,查看交接原文','{n} more items · Read the handoff'],coreScope:['圖中顯示 {n} 份 Kit 核心文件;清單另列已登記的專案文件。','The map shows {n} Kit core documents. The list includes other registered project files.'],listScope:['已列出 {n} 份文件;只讀已登記路徑,不掃描整個專案。','{n} listed files; only registered paths are read, without scanning the whole project.'],
|
|
7
|
-
retryNow:['立即重連','Reconnect now'],reopenPrompt:['開啟專案進度頁','Open the project dashboard'],reopenCopy:['複製重開口令','Copy reopen prompt'],reconnectNote:['連線暫時中斷,保留上次資料並自動重連。若服務已停止,請在此專案的 AI 輸入重開口令。','Connection interrupted. Keeping the last data and reconnecting automatically. If the service stopped, use the reopen prompt in this project’s AI.'],projectKit:['專案 Kit','Project Kit'],viewerKit:['頁面工具','Dashboard tool'],versionUnknown:['版本未核實','Version unverified'],versionDifference:['版本不同','Versions differ'],versionDifferenceNote:['專案與頁面工具版本不同;開啟頁面不會升級專案。','Project and dashboard tool versions differ. Opening this page does not upgrade the project.'],versionSource:['專案版本讀自 PROJECT_INDEX.md 的 Stack;頁面工具版本讀自啟動套件。','Project version comes from PROJECT_INDEX.md Stack; dashboard tool version comes from the running package.'],
|
|
8
|
-
workRetained:['更新暫停,這裏顯示上次有效紀錄。','Updates paused. Showing the last valid record.'],eventSnapshot:['這則為開啟時的紀錄;來源已變,請從歷程重新選取。','This is the record opened earlier. Its source changed; reselect it in History.'],allWorkstreams:['所有工作線','All workstreams'],selectMap:['點選節點,突出顯示相關文件。','Select a node to highlight related documents.'],skip:['跳到內容','Skip to content'],overview:['總覽','Overview'],history:['歷程','History'],documents:['文件地圖','Document map'],project:['專案工作總覽','PROJECT DASHBOARD'],workstreams:['本專案工作','Project work'],recent:['最近變更','Recent changes'],viewHistory:['查看歷程','View history'],outstanding:['待辦事項','Outstanding work'],allWork:['全部工作','All work'],results:['成果與參考','Results & references'],documentRelations:['文件關係','Document connections'],documentIntro:['從目前交接,找回紀錄與依據。','Find the records and sources behind your handoff.'],viewMap:['查看地圖','View map'],projectHistory:['專案歷程','Project history'],historyIntro:['找回每次改變與交接的脈絡。','Follow the changes and the context behind each handoff.'],last7:['近7日','7 days'],last30:['近30日','30 days'],allDates:['全部日期','All dates'],from:['由','From'],to:['至','To'],search:['查找紀錄','Search records'],apply:['查看','Show'],loadMore:['繼續查閱紀錄','Continue reading'],dateBoundary:['日期只篩選歷程,目前未完事項不受影響。','Dates filter recorded events, not current outstanding work.'],documentsHeading:['專案文件導覽','Project documents'],documentsIntro:['核心文件看關係,其他已登記文件看清單。','Explore core document relationships or browse the registered file list.'],map:['核心關係','Core map'],list:['文件清單','File list'],mapBoundary:['連線表示已記錄的文件角色或關係;不代表已驗收。','Connections show declared roles and relationships, not acceptance.'],boundary:['依已保存紀錄更新;未保存的工作不會出現在這裏。','Updates from saved records. Unsaved work is not shown.'],sources:['資料依據','Sources'],empty:['尚未讀到交接紀錄。','No handoff records available yet.'],missing:['尚未記錄','Not recorded'],connected:['已連線','Connected'],offlineLabel:['連線中斷','Disconnected'],waiting:['連接中','Connecting'],interrupted:['更新待恢復','Updates paused'],close:['關閉','Close'],saved:['最後保存:{date}','Last saved: {date}'],focus:['正在查看','Viewing'],viewWork:['查看這項工作','View this work'],moreWork:['另有 {n} 條工作線','{n} more workstreams'],noWork:['尚未整理工作主線;可先查看目前交接。','Workstreams are not recorded yet. Read the current handoff.'],unknownState:['狀態未記錄','State not recorded'],noOutstanding:['未有明確記錄的未完項目;不代表全部完成。','No explicit outstanding items are recorded. This does not imply completion.'],noResults:['尚未登記成果入口。','No result links are registered yet.'],noEvents:['所選期間未找到紀錄。','No records found in this date range.'],noRecent:['尚未讀到近期紀錄。','No recent records loaded yet.'],showSource:['查看來源','Read source'],showDocument:['查看文件','Read document'],copied:['已複製','Copied'],copyPath:['複製路徑','Copy path'],copyFailed:['未能自動複製,請選取上方路徑。','Select the path above to copy it manually.'],sourceText:['原始紀錄','Source record'],purpose:['用途','Purpose'],parent:['所屬工作','Parent work'],children:['相關子項目','Related work'],relationships:['文件關係','Document relationships'],available:['檔案存在','File present'],notAvailable:['檔案未找到','File not found'],fileUnknown:['此格式可從專案檔案開啟;這裏不執行文件。','Open this format from the project. This page does not execute files.'],sourceChanged:['來源已更新,內容已同步。','Source updated. This view is current.'],loading:['正在讀取…','Loading…'],unavailable:['暫未能讀取,保留已顯示的內容。','Could not read this record. Existing content is retained.'],offline:['連接暫時中斷,保留上次資料,恢復後自動更新。','Connection interrupted. Last valid data is retained and will update on reconnection.'],upgrade:['Kit 正在升級,暫停讀取。','Kit upgrade in progress. Reading is paused.'],invalid:['部分紀錄暫未能完整讀取;保留上一次有效內容。','Some records cannot be read completely. Last valid data is retained.'],workInvalid:['工作項目格式有問題;暫不更新工作狀態。','Work records are invalid. Work state updates are paused.'],legacy:['此處顯示既有原文;尚未整理工作項目。','Existing source text is shown. Structured work items are not recorded.'],coverage:['這是已保存紀錄的導覽,不是 AI 完整接收交接或獨立驗收的證明。','Saved-record navigation does not prove full AI handoff reception or independent acceptance.'],readScope:['首頁讀現況;歷程按需讀主紀錄與封存。程式不寫回來源,也不呼叫 AI。','Current state loads first. History reads logs and archives on demand, without source writes or model calls.'],historyWindow:['已顯示 {n} 則;查閱 {files} / {total} 份相關紀錄檔。','Showing {n} events; checked {files} of {total} relevant files.'],historyMore:['尚有紀錄待查閱。','More records remain to be read.'],historyWarning:['部分歷史未能核實,不能把這個結果視作完整歷史。','Some history could not be verified. Results are not a complete history.'],historyChanged:['紀錄正在變動,請重新查看所選日期。','History changed while reading. Apply the date range again.'],dateError:['請選擇有效的起訖日期。','Choose a valid date range.'],archived:['封存紀錄','Archived record'],recentRecord:['近期紀錄','Recent record'],updated:['紀錄已更新','Records updated'],unclassified:['未分組','Ungrouped'],summary:['摘要','Summary'],done:['完成紀錄','Recorded work'],qc:['驗收紀錄','Checks'],pending:['尚未完成','Outstanding'],risks:['限制與風險','Constraints'],changed:['改變了甚麼','What changed'],reason:['原因','Reason'],boundaryField:['範圍','Scope'],focusFallback:['目前工作','Current work'],unknownGoal:['專案目標尚未記錄;目前任務請看下方。','The project goal is not recorded. Current work is shown below.'],profileFallback:['交接中的任務目標','Task goal from handoff'],sourceDate:['紀錄日期','Record date'],readTime:['最後成功讀取','Last successful read'],noMatches:['沒有符合條件的項目。','No matching items.'],continueSearch:['繼續查閱','Continue search'],allWorkTitle:['工作與交接狀態','Work and handoff state'],state:['狀態','Status'],notAStage:['工作線,並非完成順序','Workstreams, not a completion sequence'],linksEmpty:['未記錄其他關係。','No other relationships recorded.'],recordFields:['當次紀錄','Recorded details']
|
|
9
|
-
};
|
|
10
|
-
const roles={handoff:['目前交接','Current handoff'],log:['工作紀錄','Session log'],archive:['歷史封存','Archive index'],index:['文件索引','Project index'],rules:['工作規則','Working rules'],packs:['規則入口','Rule router'],decisions:['重要決定','Decisions'],sync:['同步關係','Sync registry'],document:['參考文件','Reference'],artifact:['成果','Result']};
|
|
11
|
-
const statuses={planned:['待完成','Planned'],active:['進行中','In progress'],waiting:['等待','Waiting'],review:['待驗收','Awaiting review'],done:['已完成','Done'],paused:['已暫停','Paused'],dropped:['已停止','Stopped']};
|
|
12
|
-
const incomingText={routes:['由此文件指向','routed from'],governs:['依循','governed by'],archives:['收錄自','archived from'],references:['被參考於','referenced by'],mirrors:['同步鏡像','mirrored by'],checks:['檢查由此觸發','checked with']};
|
|
13
|
-
const relationText={routes:['指向','routes to'],governs:['規範','governs'],archives:['封存至','archives to'],references:['參考','references'],mirrors:['同步鏡像','mirrors'],checks:['需一併檢查','also checks']};
|
|
14
|
-
const purposes={handoff:['保存目前目標、未完事項與接續位置。','Stores the current goal, outstanding work and resume point.'],log:['記錄每次工作發生過甚麼;不取代目前狀態。','Records what happened in each session, not current state.'],archive:['定位較早的工作紀錄,按需查閱。','Locates earlier records for on-demand reading.'],index:['指出文件位置、用途與必要來源。','Maps document locations, roles and sources.'],rules:['定義本專案的工作邊界與基本流程。','Defines project boundaries and working procedures.'],packs:['按任務選取需要的規則。','Routes tasks to the relevant rules.'],decisions:['保留重要選擇及其理由。','Preserves important decisions and rationale.'],sync:['記錄變更時哪些文件需要一併檢查或同步。','Records which documents need checks or synchronization.']};
|
|
15
|
-
let lang='zh-Hant';try{const v=localStorage.getItem('ahk-ui-language');if(['zh-Hant','en'].includes(v))lang=v;}catch{}const requested=new URLSearchParams(location.search).get('lang');if(['zh-Hant','en'].includes(requested))lang=requested;
|
|
16
|
-
const tr=(k,v={})=>(dict[k]?.[lang==='en'?1:0]||k).replace(/\{(\w+)\}/g,(_,x)=>String(v[x]??'')),pick=p=>p?.[lang==='en'?1:0]||'',esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
17
|
-
const icon=name=>`<svg aria-hidden="true"><use href="icons.svg#${name}"></use></svg>`;
|
|
18
|
-
const title=w=>lang==='zh-Hant'&&w.titleZh||w.title,summary=w=>lang==='zh-Hant'&&w.summaryZh||w.summary;
|
|
19
|
-
const short=(s,n=140)=>{s=String(s||'').replace(/\s+/g,' ').trim();return s.length>n?s.slice(0,n)+'…':s;};
|
|
20
|
-
const pill=s=>`<span class="pill ${esc(s)}">${esc(pick(statuses[s])||tr('unknownState'))}</span>`;
|
|
21
|
-
const cite=r=>r?.source?`<p class="citation">${esc(r.source.file)} · ${lang==='en'?'line':'第'} ${r.source.line}${lang==='en'?'':' 行'}</p>`:'';
|
|
22
|
-
function date(s,brief=false){if(!s)return tr('missing');const d=new Date(/^\d{4}-\d{2}-\d{2}$/.test(s)?s+'T12:00:00':s);if(Number.isNaN(d.getTime()))return s;return new Intl.DateTimeFormat(lang==='en'?'en-GB':'zh-Hant',{...(!brief||d.getFullYear()!==new Date().getFullYear()?{year:'numeric'}:{}),month:'short',day:'numeric',...(!brief&&s.includes('T')?{hour:'2-digit',minute:'2-digit'}:{})}).format(d);}
|
|
23
|
-
const reduced=matchMedia('(prefers-reduced-motion: reduce)');
|
|
24
|
-
function motion(el,keyframes,options={}){if(el&&!reduced.matches)el.animate(keyframes,{duration:260,easing:'cubic-bezier(.22,.8,.3,1)',...options});}
|
|
25
|
-
function reveal(el){motion(el,[{opacity:.3,transform:'translateY(8px)'},{opacity:1,transform:'translateY(0)'}]);}
|
|
26
|
-
function updated(el){motion(el,[{backgroundColor:'#e2edff'},{backgroundColor:'transparent'}],{duration:1800});}
|
|
27
|
-
const relationLabel=(link,id)=>pick((link.from===id?relationText:incomingText)[link.type]);
|
|
28
|
-
const eventTitle=r=>lang==='zh-Hant'&&(r.titleZh||r.fields?.['title zh-hant'])||r.title;
|
|
29
|
-
const eventSummary=r=>lang==='zh-Hant'&&(r.summaryZh||r.fields?.['summary zh-hant'])||r.summary;
|
|
30
|
-
let data=null,online=false,session='',sequence=-1,selected=null,view='overview',lastRead=null,drawerState=null,drawerRequest=0,returnTo=null,returnSelector=null,historyItems=[],historyNext=null,historyMeta=null,historyRequest=0,historyLoaded=false,historyDirty=false,historyQuery=null,mapMode='map',mapSelected='handoff';
|
|
31
|
-
const drawer=$('#drawer');const work=()=>data?.dashboard?.work?.items||[],documents=()=>data?.dashboard?.documents||[];
|
|
32
|
-
const docName=d=>pick(roles[d.role])+(d.role==='document'||d.role==='artifact'?': '+(lang==='zh-Hant'&&d.titleZh||d.title||d.file):'');
|
|
33
|
-
const docByFile=file=>documents().find(d=>d.file===file);
|
|
34
|
-
let stream=null,reconnectTimer=null,reconnectAttempts=0,connectionPaused=false;
|
|
35
|
-
function route(){const name=location.hash.slice(1).split('/')[0];const previousView=view;view=['overview','history','documents'].includes(name)?name:'overview';for(const v of ['overview','history','documents'])$('#'+v+'-view').hidden=view!==v;document.querySelectorAll('[data-view]').forEach(a=>{if(a.dataset.view===view)a.setAttribute('aria-current','page');else a.removeAttribute('aria-current');});if(view==='history'&&data&&online&&(!historyLoaded||historyDirty))loadHistory(false,historyDirty);if(view==='documents')renderDocuments();if(previousView!==view)reveal($('#'+view+'-view'));}
|
|
36
|
-
function versionInfo(){const project=data?.dashboard?.projectKitVersion||null,raw=data?.kitVersion,tool=typeof raw==='string'&&/^\d+\.\d+\.\d+$/.test(raw)?raw:null;const different=!!(project&&tool&&project!==tool);return{project,tool,different,label:project?'v'+project+(different?' · '+tr('versionDifference'):''):tr('versionUnknown'),description:tr('projectKit')+': '+(project?'v'+project:tr('versionUnknown'))+' · '+tr('viewerKit')+': '+(tool?'v'+tool:tr('versionUnknown'))+(different?' — '+tr('versionDifferenceNote'):'')};}
|
|
37
|
-
function render(){
|
|
38
|
-
document.documentElement.lang=lang;$('#language').value=lang;document.querySelectorAll('[data-i18n]').forEach(e=>e.textContent=tr(e.dataset.i18n));document.querySelectorAll('[data-placeholder]').forEach(e=>e.placeholder=tr(e.dataset.placeholder));$('#close').ariaLabel=tr('close');
|
|
39
|
-
const version=versionInfo(),badge=$('#kit-version');badge.textContent=version.label;badge.title=version.description;badge.setAttribute('aria-label',version.description);badge.dataset.state=!version.project?'unverified':version.different?'different':'matched';
|
|
40
|
-
const errors={...(data?.errors||{}),...(data?.dashboard?.errors||{})};const hasErrors=Object.keys(errors).length>0;document.body.dataset.live=String(online&&!hasErrors);$('#sync').textContent=tr(!online?(data?'offlineLabel':'waiting'):hasErrors?'interrupted':'connected');
|
|
41
|
-
const warning=!online&&(data||reconnectAttempts)?'offline':errors.lock?'upgrade':errors.work?'workInvalid':hasErrors?'invalid':null;$('#warning').hidden=!warning;$('#warning').innerHTML=warning==='offline'?esc(tr('reconnectNote'))+' <button class="text-link" data-action="retry">'+tr('retryNow')+'</button> <button class="text-link" data-copy="'+esc(tr('reopenPrompt'))+'">'+tr('reopenCopy')+'</button>':warning?esc(tr(warning)):'';
|
|
42
|
-
const p=data?.dashboard?.profile||{};const name=(lang==='zh-Hant'&&p.nameZh)||p.name||data?.project?.name||tr('missing');$('#project-title').textContent=name;$('#history-project').textContent=name;$('#documents-project').textContent=name;document.title=name+' · Agent Handoff Kit';
|
|
43
|
-
const saved=data?.sources?.find(s=>s.file.includes('HANDOFF'))?.updated;$('#freshness').innerHTML=icon('calendar')+esc(tr('handoffSaved',{date:date(saved||data?.recordDate)}));$('#empty').hidden=!!data?.available;
|
|
44
|
-
const current=data?.project?.current?.text;$('#recorded-current').textContent=tr('recordedCurrent')+':'+short(current||tr('missing'),150);$('#recorded-current').title=current||tr('missing');
|
|
45
|
-
const workValue=$('#history-work').value;$('#history-work').innerHTML='<option value="">'+tr('allWorkstreams')+'</option>'+work().map(w=>'<option value="'+esc(w.id)+'">'+esc(title(w))+'</option>').join('');$('#history-work').value=workValue;renderWork();renderRecent();renderStrip();if(view==='documents')renderDocuments();if(view==='history')renderHistory();route();
|
|
46
|
-
}
|
|
47
|
-
function legacyWorkHTML(){
|
|
48
|
-
const collections=['pending','risks'].map(kind=>({kind,items:data?.sections?.[kind]?.items||[],total:data?.sections?.[kind]?.total||0}));
|
|
49
|
-
const visible=collections.reduce((n,c)=>n+c.items.length,0),total=collections.reduce((n,c)=>n+c.total,0);
|
|
50
|
-
const warning=data?.errors?.handoff||data?.errors?.lock;
|
|
51
|
-
let html=warning?`<p class="scope-note">${tr(data?.available?'workRetained':'unavailable')}</p>`:'';
|
|
52
|
-
if(visible){html+=`<p class="scope-note">${tr('legacyWork')}</p>`+collections.filter(c=>c.items.length).map(c=>`<h3 class="legacy-label">${tr(c.kind)}</h3>`+c.items.map(r=>`<button class="work-row" data-document="handoff"><span>${esc(short(r.text,180))}</span></button>`).join('')).join('');
|
|
53
|
-
if(total>visible)html+=`<button class="text-link" data-document="handoff">${tr('moreLegacy',{n:total-visible})}</button>`;
|
|
54
|
-
}else html+=`<p class="empty">${tr(data?.available?'noOutstanding':'unavailable')}</p>`;
|
|
55
|
-
return html+`<button class="text-link" data-document="handoff">${tr('showSource')}</button>`;
|
|
56
|
-
}
|
|
57
|
-
function renderWork(){
|
|
58
|
-
const items=work(),roots=items.filter(x=>!x.parent);if(!items.some(x=>x.id===selected))selected=items.find(x=>x.status==='active')?.id||roots[0]?.id||null;
|
|
59
|
-
const selectedWork=items.find(x=>x.id===selected);let selectedRoot=selected;for(let w=selectedWork;w?.parent;w=items.find(x=>x.id===w.parent))selectedRoot=w.parent;
|
|
60
|
-
$('#work-route').innerHTML=roots.length?roots.slice(0,5).map((w,i)=>`<button class="route-node" data-work-select="${esc(w.id)}" aria-pressed="${w.id===selectedRoot}"><span class="node-circle">${icon(i===2?'grid':'document')}</span><strong>${esc(title(w))}</strong><span class="description">${esc(short(summary(w),100))}</span><span class="relation">${esc(pick(statuses[w.status]))}</span></button>`).join(''):`<p class="empty">${tr('noWork')}</p>`;
|
|
61
|
-
$('#work-route').ariaLabel=tr('notAStage');$('#work-scope').textContent=tr('notAStage');$('#work-scope').hidden=!roots.length;$('#more-work').hidden=roots.length<=5;$('#more-work').textContent=tr('moreWork',{n:roots.length-5});
|
|
62
|
-
if(selectedWork)$('#focus').innerHTML=`<h2>${tr('focus')}:${esc(title(selectedWork))}</h2>${pill(selectedWork.status)}<div class="focus-actions"><button class="primary" data-work="${esc(selectedWork.id)}">${tr('viewWork')}${icon('arrow')}</button></div>`;
|
|
63
|
-
else $('#focus').innerHTML=`<h2>${tr('focusFallback')}</h2><p class="focus-summary">${esc(short(data?.project?.current?.text||tr('missing'),240))}</p><div class="focus-actions"><button class="primary" data-document="handoff">${tr('showDocument')}</button></div>`;
|
|
64
|
-
const pending=items.filter(w=>!['done','dropped'].includes(w.status)&&(!items.some(c=>c.parent===w.id)||w.status!=='active'));
|
|
65
|
-
$('#pending-list').innerHTML=!items.length?legacyWorkHTML():pending.length?pending.slice(0,3).map(w=>`<button class="work-row" data-work="${esc(w.id)}">${pill(w.status)}<span><strong>${esc(title(w))}</strong><small>${esc(short(summary(w),80))}</small></span></button>`).join('')+(pending.length>3?`<button class="text-link" data-action="all-work">${tr('morePending',{n:pending.length-3})}</button>`:''):`<p class="empty">${tr('noOutstanding')}</p><button class="text-link" data-document="handoff">${tr('showDocument')}</button>`;
|
|
66
|
-
const results=items.filter(w=>w.artifact).slice(0,3);$('#result-list').innerHTML=results.length?results.map(w=>{const d=docByFile(w.artifact);return`<button class="result-row" data-document="${esc(d?.id||'handoff')}">${icon('document')}<span><strong>${esc(title(w))}</strong><small>${esc(w.artifact.split('/').pop())}</small></span></button>`;}).join(''):`<p class="empty">${tr('noResults')}</p>`;
|
|
67
|
-
}
|
|
68
|
-
function renderRecent(){const rows=data?.recent?.items||[];$('#recent-list').innerHTML=rows.length?rows.slice(0,3).map((r,i)=>`<button class="recent-row" data-recent="${i}"><time>${esc(date(r.title.slice(0,10),true))}</time><span><strong>${esc(eventTitle({...r,title:r.title.slice(10).replace(/^\s*[—–-]\s*/,'' )}))}</strong><small>${esc(short(eventSummary({...r,summary:r.summary?.text?.replace(/^Summary[::]\s*/i,'')}),95))}</small></span></button>`).join(''):`<p class="empty">${tr('noRecent')}</p>`;}
|
|
69
|
-
function renderStrip(){const ids=['handoff','log','archive','index'];$('#document-strip').innerHTML=ids.map(id=>documents().find(d=>d.id===id)).filter(Boolean).map(d=>`<button class="strip-node" data-document="${d.id}"><span class="mini-node">${icon(d.id==='archive'?'archive':d.id==='index'?'map':'document')}</span><span><strong>${esc(docName(d))}</strong><small>${esc(d.file.split('/').pop())}</small></span></button>`).join('');}
|
|
70
|
-
function renderDocuments(){const docs=documents(),links=data?.dashboard?.links||[];$('#document-status').textContent=data?.dashboard?.errors.documents?tr('invalid'):'';
|
|
71
|
-
$('#document-map').hidden=mapMode!=='map';$('#document-list').hidden=mapMode!=='list';$('#map-mode').setAttribute('aria-pressed',String(mapMode==='map'));$('#list-mode').setAttribute('aria-pressed',String(mapMode==='list'));
|
|
72
|
-
const order=['index','handoff','log','archive','packs','rules','decisions','sync'];const core=docs.filter(d=>order.includes(d.role)).sort((a,b)=>order.indexOf(a.role)-order.indexOf(b.role));const linked=new Set(links.filter(l=>l.from===mapSelected||l.to===mapSelected).flatMap(l=>[l.from,l.to]));linked.add(mapSelected);
|
|
73
|
-
const scope=tr(mapMode==='map'?'coreScope':'listScope',{n:mapMode==='map'?core.length:docs.length});$('#document-status').textContent=scope+(data?.dashboard?.errors.documents?' '+tr('invalid'):'');
|
|
74
|
-
$('#document-map').innerHTML='<svg class="map-lines" aria-hidden="true"></svg>'+core.map(d=>`<button class="doc-node ${d.available?'':'missing'} ${linked.has(d.id)?'related':'subdued'}" data-role="${d.role}" data-map="${d.id}" aria-pressed="${d.id===mapSelected}"><span class="node-circle">${icon(d.role==='archive'?'archive':d.role==='index'?'map':'document')}</span><strong>${esc(docName(d))}</strong><small>${esc(d.file.split('/').pop())}</small></button>`).join('');
|
|
75
|
-
const d=docs.find(x=>x.id===mapSelected);if(d){const related=links.filter(l=>l.from===d.id||l.to===d.id);$('#map-detail').innerHTML=`<div><h2>${esc(docName(d))}</h2><p>${esc(pick(purposes[d.role])||d.title||'')}</p></div><div class="map-relations">${related.map(l=>{const other=docs.find(x=>x.id===(l.from===d.id?l.to:l.from));return `<span>${esc(relationLabel(l,d.id))} <button class="text-link" ${core.some(x=>x.id===other.id)?'data-map':'data-document'}="${esc(other.id)}">${esc(docName(other))}</button></span>`;}).join('')||tr('linksEmpty')}</div><button class="primary" data-document="${esc(d.id)}">${tr('showDocument')}${icon('arrow')}</button>`;}
|
|
76
|
-
$('#map-detail').hidden=mapMode!=='map';$('#document-list').innerHTML=docs.map(d=>`<button data-document="${esc(d.id)}"><strong>${esc(docName(d))}</strong><small>${esc(d.file)}</small><small>${tr(d.available?'available':'notAvailable')}</small></button>`).join('');requestAnimationFrame(drawConnections);
|
|
77
|
-
}
|
|
78
|
-
function drawConnections(){if(view!=='documents'||mapMode!=='map')return;const box=$('#document-map'),svg=box.querySelector('svg'),bounds=box.getBoundingClientRect();if(!bounds.width)return;svg.setAttribute('viewBox',`0 0 ${bounds.width} ${bounds.height}`);svg.innerHTML='<defs><marker id="arrowhead" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto"><path d="M0 0 L7 3.5 L0 7" fill="currentColor" stroke="none"/></marker></defs>'+(data.dashboard.links||[]).map(l=>{const a=box.querySelector('[data-map="'+l.from+'"] .node-circle'),b=box.querySelector('[data-map="'+l.to+'"] .node-circle');if(!a||!b)return '';const ar=a.getBoundingClientRect(),br=b.getBoundingClientRect(),ax=ar.x+ar.width/2-bounds.x,ay=ar.y+ar.height/2-bounds.y,bx=br.x+br.width/2-bounds.x,by=br.y+br.height/2-bounds.y,dx=bx-ax,dy=by-ay,len=Math.hypot(dx,dy)||1,rad=43,x1=ax+dx/len*rad,y1=ay+dy/len*rad,x2=bx-dx/len*rad,y2=by-dy/len*rad;return `<path class="${l.from===mapSelected||l.to===mapSelected?'lit':''}" d="M${x1} ${y1} C${x1} ${(y1+y2)/2},${x2} ${(y1+y2)/2},${x2} ${y2}" marker-end="url(#arrowhead)"/>`;}).join('');}
|
|
79
|
-
new ResizeObserver(()=>requestAnimationFrame(drawConnections)).observe($('#document-map'));
|
|
80
|
-
function focusSelector(el){if(el?.id)return '#'+CSS.escape(el.id);for(const key of ['work','document','event','recent','workSelect','action'])if(el?.dataset?.[key]!==undefined)return 'main [data-'+key.replace(/[A-Z]/g,x=>'-'+x.toLowerCase())+'="'+CSS.escape(el.dataset[key])+'"]';return null;}
|
|
81
|
-
function openDrawer(state,titleText,body,kicker=''){if(!drawer.open){returnTo=document.activeElement;returnSelector=focusSelector(returnTo);}drawerState=state;$('#drawer-title').textContent=titleText;$('#drawer-kicker').textContent=kicker;$('#drawer-content').innerHTML=body;if(!drawer.open){drawer.showModal();motion(drawer,[{transform:'translateX(50px)',opacity:.4},{transform:'translateX(0)',opacity:1}],{duration:300});}}
|
|
82
|
-
function showWork(id,update=false){const w=work().find(x=>x.id===id);if(!w)return;const children=work().filter(x=>x.parent===id),parent=work().find(x=>x.id===w.parent);let body=pill(w.status)+`<p>${esc(summary(w)||tr('missing'))}</p>`;if(parent)body+=`<h3>${tr('parent')}</h3><button class="text-link" data-work="${esc(parent.id)}">${esc(title(parent))}</button>`;if(children.length)body+=`<h3>${tr('children')}</h3><div class="work-list">${children.map(c=>`<button class="work-row" data-work="${esc(c.id)}">${pill(c.status)}<span><strong>${esc(title(c))}</strong><small>${esc(summary(c))}</small></span></button>`).join('')}</div>`;body+=cite(w)+`<div class="drawer-actions"><button class="secondary" data-document="handoff">${tr('showSource')}</button>${w.artifact?`<button class="primary" data-document="${esc(docByFile(w.artifact)?.id||'handoff')}">${tr('showDocument')}</button>`:''}</div>`;if(update)body=`<p class="updated-note">${tr(data?.errors?.handoff||data?.errors?.lock||data?.dashboard?.errors?.work?'workRetained':'sourceChanged')}</p>`+body;openDrawer({kind:'work',id},title(w),body,tr('state'));}
|
|
83
|
-
async function showDocument(id,update=false){const previousBody=update?$('#drawer-content').innerHTML:null;const d=documents().find(x=>x.id===id);if(!d)return;const requestId=++drawerRequest,scroll=update?drawer.scrollTop:0;const relation=(data?.dashboard?.links||[]).filter(l=>l.from===id||l.to===id);const base=`<p>${esc(pick(purposes[d.role])||d.title||tr('missing'))}</p><p class="citation">${esc(d.file)}</p><div class="drawer-actions"><button class="secondary" data-copy="${esc(d.file)}">${icon('copy')}${tr('copyPath')}</button>${d.role==='log'||d.role==='archive'?`<button class="secondary" data-action="history">${tr('viewHistory')}</button>`:''}</div>${relation.length?`<h3>${tr('relationships')}</h3>${relation.map(l=>{const other=documents().find(x=>x.id===(l.from===id?l.to:l.from));return`<p>${esc(relationLabel(l,id))} <button class="text-link" data-document="${esc(other.id)}">${esc(docName(other))}</button></p>`;}).join('')}`:''}`;openDrawer({kind:'document',id},docName(d),base+`<p>${tr('loading')}</p>`,tr('sources'));try{const r=await fetch('/api/document?id='+encodeURIComponent(id));if(!r.ok)throw Error();const result=await r.json();if(requestId!==drawerRequest||!drawer.open)return;$('#drawer-content').innerHTML=(update?`<p class="updated-note">${tr('sourceChanged')}</p>`:'')+base+`<h3>${tr('sourceText')}</h3>`+(result.text!==null?`<pre tabindex="0">${esc(result.text)}</pre>`:`<p>${tr('fileUnknown')}</p>`);drawer.scrollTop=scroll;}catch{if(requestId===drawerRequest&&drawer.open)$('#drawer-content').innerHTML=(previousBody||base)+`<p class="warning">${tr(d.available?'unavailable':'notAvailable')}</p>`;}}
|
|
84
|
-
function showEvent(item){const map={summary:'summary',changed:'changed',done:'done',qc:'qc',pending:'pending',risks:'risks',reason:'reason',boundary:'boundaryField'};let body=`<p class="citation">${esc(date(item.date))}${item.work?' · '+esc(work().some(w=>w.id===item.work)?title(work().find(w=>w.id===item.work)):item.work):''}</p>`;const f=item.fields||{};let fields=Object.entries(map).filter(([k])=>f[k]);body+=fields.length?fields.map(([k,label])=>`<h3>${tr(label)}</h3><p>${esc(lang==='zh-Hant'&&f[k+' zh-hant']||f[k])}</p>`).join(''):`<p>${esc(item.summary||item.body||tr('missing'))}</p>`;body+=cite(item);if(item.body)body+=`<details><summary>${tr('sourceText')}</summary><pre>${esc(item.body)}</pre></details>`;openDrawer({kind:'event',item},eventTitle(item),body,tr(item.source?.file.includes('_archive/')?'archived':'recentRecord'));}
|
|
85
|
-
function showSources(){const version=versionInfo();const body=`<div class="source-row">${esc(version.description)}<small>${esc(tr('versionSource'))}</small></div>`+(data?.sources||[]).map(s=>`<div class="source-row">${esc(s.file)}<small>${esc(tr('saved',{date:date(s.updated)}))}</small></div>`).join('')+`<p class="citation">${tr('readTime')}:${esc(date(lastRead))}</p><p>${tr('readScope')}</p><p class="citation">${tr('coverage')}</p>`;openDrawer({kind:'sources'},tr('sources'),body);}
|
|
86
|
-
function showAllWork(){openDrawer({kind:'all'},tr('allWorkTitle'),work().length?`<div class="work-list">${work().map(w=>`<button class="work-row" data-work="${esc(w.id)}">${pill(w.status)}<span><strong>${esc(title(w))}</strong><small>${esc(summary(w))}</small></span></button>`).join('')}</div>`:legacyWorkHTML());}
|
|
87
|
-
function refreshDrawer(){if(!drawer.open)return;const s=drawerState,scroll=drawer.scrollTop;if(s?.kind==='work')showWork(s.id,true);else if(s?.kind==='document')showDocument(s.id,true);else if(s?.kind==='sources')showSources();else if(s?.kind==='all')showAllWork();else if(s?.kind==='event'){const recent=(data.recent?.items||[]).find(r=>r.id===s.item.id);const current=historyItems.find(r=>r.id===s.item.id);if(current||recent){showEvent(current||{...recent,date:recent.title.slice(0,10),title:recent.title.slice(10).replace(/^\s*[—–-]\s*/,''),summary:recent.summary?.text});}else if(!$('#event-update'))$('#drawer-content').insertAdjacentHTML('afterbegin',`<p id="event-update" class="updated-note">${tr('eventSnapshot')}</p>`);}drawer.scrollTop=scroll;}
|
|
88
|
-
function localDay(d){return [d.getFullYear(),String(d.getMonth()+1).padStart(2,'0'),String(d.getDate()).padStart(2,'0')].join('-');}
|
|
89
|
-
function setRange(days){const now=new Date();$('#to').value=days==='all'?'':localDay(now);const start=new Date(now);start.setDate(start.getDate()-Number(days||30)+1);$('#from').value=days==='all'?'':localDay(start);document.querySelectorAll('[data-days]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.days===String(days))));}
|
|
90
|
-
async function loadHistory(more=false,automatic=false){if(!data)return;const from=automatic&&historyQuery?historyQuery.from:$('#from').value,to=automatic&&historyQuery?historyQuery.to:$('#to').value;if(from&&to&&from>to){$('#history-status').textContent=tr('dateError');return;}const requestId=++historyRequest;const q={from,to,search:automatic&&historyQuery?historyQuery.search:$('#search').value,work:automatic&&historyQuery?historyQuery.work:$('#history-work').value};if(more&&historyNext)q.cursor=historyNext;const oldItems=historyItems,oldCount=historyItems.length;const anchor=[...document.querySelectorAll('[data-event]')].find(e=>e.getBoundingClientRect().top>=0);const anchorId=anchor?.dataset.event,anchorY=anchor?.getBoundingClientRect().top;historyLoaded=true;historyDirty=false;$('#history-status').textContent=tr('loading');$('#history-more').disabled=true;$('#history-list').setAttribute('aria-busy','true');
|
|
91
|
-
try{let combined=more?[...historyItems]:[],result,pages=0;do{const r=await fetch('/api/history?'+new URLSearchParams(q));if(!r.ok)throw Error();result=await r.json();if(requestId!==historyRequest)return;const ids=new Set(combined.map(x=>x.id));combined.push(...result.items.filter(x=>!ids.has(x.id)));q.cursor=result.next;pages++;}while(automatic&&result.next&&combined.length<oldCount&&pages<5);
|
|
92
|
-
historyQuery={from,to,search:q.search,work:q.work};historyItems=combined;historyNext=result.next;historyMeta=result;historyDirty=false;renderHistory();if(automatic&&anchorId){const nextAnchor=$('[data-event="'+anchorId+'"]');if(nextAnchor)window.scrollBy(0,nextAnchor.getBoundingClientRect().top-anchorY);}else reveal($('#history-list'));if(automatic){const oldById=new Map(oldItems.map(x=>[x.id,x.fingerprint]));document.querySelectorAll('[data-event]').forEach(el=>{const entry=combined.find(x=>x.id===el.dataset.event);if(entry&&oldById.get(entry.id)!==entry.fingerprint)updated(el);});}if(drawerState?.kind==='event')refreshDrawer();
|
|
93
|
-
}catch{if(requestId===historyRequest){historyDirty=true;$('#history-status').textContent=tr(more?'historyChanged':'unavailable');}}finally{if(requestId===historyRequest){$('#history-more').disabled=false;$('#history-list').removeAttribute('aria-busy');}}}
|
|
94
|
-
function renderHistory(){if(!historyLoaded)return;const groups=new Map();for(const item of [...historyItems].sort((a,b)=>b.date.localeCompare(a.date))){if(!groups.has(item.date))groups.set(item.date,[]);groups.get(item.date).push(item);}
|
|
95
|
-
$('#history-list').innerHTML=groups.size?[...groups].map(([day,rows])=>`<section class="day"><h2>${esc(date(day))}</h2><div class="day-events">${rows.map(r=>`<button class="event" data-event="${esc(r.id)}"><strong>${esc(eventTitle(r))}</strong><p>${esc(short(eventSummary(r),200))}</p><span class="event-meta">${esc(r.work?(work().some(w=>w.id===r.work)?title(work().find(w=>w.id===r.work)):r.work):tr('unclassified'))} · ${tr(r.source.file.includes('_archive/')?'archived':'recentRecord')}</span></button>`).join('')}</div></section>`).join(''):`<p class="empty">${tr(historyNext?'historyMore':'noEvents')}</p>`;
|
|
96
|
-
if(historyMeta)$('#history-status').textContent=tr('historyWindow',{n:historyItems.length,files:historyMeta.filesChecked,total:historyMeta.totalFiles})+' '+(historyMeta.warnings.length?tr('historyWarning'):'')+' '+(historyNext?tr('historyMore'):'')+(historyDirty?' '+tr('updated'):'');$('#history-more').hidden=!historyNext;
|
|
97
|
-
}
|
|
98
|
-
$('#close').onclick=()=>drawer.close();drawer.onclose=()=>{drawerRequest++;drawerState=null;const target=returnTo?.isConnected?returnTo:returnSelector?$(returnSelector):null;(target||document.querySelector('nav [aria-current=page]'))?.focus({preventScroll:true});};
|
|
99
|
-
document.addEventListener('click',async e=>{const b=e.target.closest('button');if(!b||b.disabled)return;
|
|
100
|
-
if(b.dataset.workSelect){selected=b.dataset.workSelect;renderWork();reveal($('#focus'));motion($('[data-work-select="'+selected+'"] .node-circle'),[{transform:'scale(.95)'},{transform:'scale(1.12)'},{transform:'scale(1.08)'}],{duration:350});$(`[data-work-select="${selected}"]`)?.focus({preventScroll:true});}
|
|
101
|
-
else if(b.dataset.map){mapSelected=b.dataset.map;renderDocuments();reveal($('#map-detail'));$('#document-map [data-map="'+mapSelected+'"]')?.focus({preventScroll:true});}
|
|
102
|
-
else if(b.dataset.work)showWork(b.dataset.work);
|
|
103
|
-
else if(b.dataset.document)showDocument(b.dataset.document);
|
|
104
|
-
else if(b.dataset.recent!==undefined){const r=data.recent.items[Number(b.dataset.recent)];showEvent({...r,title:r.title.slice(10).replace(/^\s*[—–-]\s*/,''),date:r.title.slice(0,10),summary:r.summary?.text||'',fields:r.fields,body:r.body,source:r.source});}
|
|
105
|
-
else if(b.dataset.event){const item=historyItems.find(x=>x.id===b.dataset.event);if(item)showEvent(item);}
|
|
106
|
-
else if(b.dataset.copy){try{await navigator.clipboard.writeText(b.dataset.copy);b.textContent=tr('copied');}catch{b.textContent=b.dataset.copy===tr('reopenPrompt')?b.dataset.copy:tr('copyFailed');}}
|
|
107
|
-
else if(b.dataset.days){setRange(b.dataset.days);loadHistory();}
|
|
108
|
-
else if(b.dataset.action==='retry')connect();else if(b.dataset.action==='sources')showSources();else if(b.dataset.action==='all-work')showAllWork();else if(b.dataset.action==='history'){drawer.close();location.hash='history';}
|
|
109
|
-
});
|
|
110
|
-
$('#language').onchange=e=>{lang=e.target.value;try{localStorage.setItem('ahk-ui-language',lang);}catch{}render();refreshDrawer();};$('#history-filter').onsubmit=e=>{e.preventDefault();document.querySelectorAll('[data-days]').forEach(b=>b.setAttribute('aria-pressed','false'));loadHistory();};$('#history-more').onclick=()=>loadHistory(true);$('#map-mode').onclick=()=>{mapMode='map';renderDocuments();};$('#list-mode').onclick=()=>{mapMode='list';renderDocuments();};window.addEventListener('hashchange',route);setRange(30);
|
|
111
|
-
function disconnect(current){
|
|
112
|
-
if(stream!==current)return;
|
|
113
|
-
current.close();stream=null;online=false;
|
|
114
|
-
if(!connectionPaused&&reconnectTimer===null){
|
|
115
|
-
const delay=Math.min(30000,1000*2**Math.min(reconnectAttempts++,5));
|
|
116
|
-
reconnectTimer=setTimeout(()=>{reconnectTimer=null;connect();},delay);
|
|
117
|
-
}
|
|
118
|
-
render();
|
|
119
|
-
}
|
|
120
|
-
function connect(){
|
|
121
|
-
if(connectionPaused||location.protocol!=='http:'||location.hostname!=='127.0.0.1'||!window.EventSource)return;
|
|
122
|
-
clearTimeout(reconnectTimer);reconnectTimer=null;
|
|
123
|
-
if(stream){if(online)return;stream.close();}
|
|
124
|
-
const current=new EventSource('/events');stream=current;
|
|
125
|
-
current.onmessage=e=>{
|
|
126
|
-
if(stream!==current)return;
|
|
127
|
-
try{
|
|
128
|
-
const next=JSON.parse(e.data);if(next.schemaVersion!==2||!next.dashboard||typeof next.session!=='string')throw Error();
|
|
129
|
-
if(next.session===session&&next.version<sequence)return;
|
|
130
|
-
const oldData=data,hadData=!!data,resumed=hadData&&!online,restarted=hadData&&next.session!==session;
|
|
131
|
-
const changed=hadData&&(resumed||restarted||next.version!==data.version||next.dashboard.revision!==data.dashboard.revision);
|
|
132
|
-
if(hadData&&(resumed||restarted||next.dashboard.historyRevision!==data.dashboard.historyRevision))historyDirty=true;
|
|
133
|
-
if(resumed||restarted){historyNext=null;historyRequest++;drawerRequest++;}
|
|
134
|
-
session=next.session;sequence=next.version;data=next;online=true;reconnectAttempts=0;lastRead=new Date().toISOString();
|
|
135
|
-
const active=document.activeElement,focusKey=active?.dataset.workSelect;render();
|
|
136
|
-
if(!hadData){document.querySelectorAll('.route-node,.overview-grid .panel').forEach((el,i)=>motion(el,[{opacity:0,transform:'translateY(12px)'},{opacity:1,transform:'none'}],{delay:i*60,duration:380}));}
|
|
137
|
-
else{for(const w of work()){const old=oldData.dashboard.work.items.find(x=>x.id===w.id);if(JSON.stringify(old)!==JSON.stringify(w))updated($('[data-work-select="'+w.id+'"]'));}}
|
|
138
|
-
if(focusKey)$('[data-work-select="'+focusKey+'"]')?.focus({preventScroll:true});
|
|
139
|
-
if(changed){refreshDrawer();$('#announcement').textContent=tr('updated');}
|
|
140
|
-
document.body.dataset.version=String(data.version);
|
|
141
|
-
}catch{disconnect(current);}
|
|
142
|
-
};
|
|
143
|
-
current.onerror=()=>disconnect(current);
|
|
144
|
-
}
|
|
145
|
-
const wake=()=>{if(!online&&!stream&&!connectionPaused)connect();};
|
|
146
|
-
window.addEventListener('online',wake);window.addEventListener('focus',wake);
|
|
147
|
-
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')wake();});
|
|
148
|
-
window.addEventListener('pagehide',()=>{connectionPaused=true;clearTimeout(reconnectTimer);reconnectTimer=null;stream?.close();stream=null;online=false;});
|
|
149
|
-
window.addEventListener('pageshow',()=>{connectionPaused=false;wake();});
|
|
150
|
-
connect();
|
|
151
|
-
render();
|
|
152
|
-
})();
|
|
1
|
+
// Fixed, bilingual UI. No model requests or project-specific content.
|
|
2
|
+
'use strict';
|
|
3
|
+
(()=>{
|
|
4
|
+
const $=s=>document.querySelector(s),dict={
|
|
5
|
+
creatorRole:['作者|AI 生活策展人','Creator · AI Lifestyle Curator'],
|
|
6
|
+
handoffSaved:['交接保存:{date}','Handoff saved: {date}'],recordedCurrent:['交接記錄的目前工作','Current work recorded in handoff'],legacyWork:['尚未分類;以下直接顯示交接紀錄。','Not classified yet. Showing the handoff records below.'],morePending:['另有 {n} 項,查看全部工作','{n} more items · View all work'],moreLegacy:['另有 {n} 項,查看交接原文','{n} more items · Read the handoff'],coreScope:['圖中顯示 {n} 份 Kit 核心文件;清單另列已登記的專案文件。','The map shows {n} Kit core documents. The list includes other registered project files.'],listScope:['已列出 {n} 份文件;只讀已登記路徑,不掃描整個專案。','{n} listed files; only registered paths are read, without scanning the whole project.'],
|
|
7
|
+
retryNow:['立即重連','Reconnect now'],reopenPrompt:['開啟專案進度頁','Open the project dashboard'],reopenCopy:['複製重開口令','Copy reopen prompt'],reconnectNote:['連線暫時中斷,保留上次資料並自動重連。若服務已停止,請在此專案的 AI 輸入重開口令。','Connection interrupted. Keeping the last data and reconnecting automatically. If the service stopped, use the reopen prompt in this project’s AI.'],projectKit:['專案 Kit','Project Kit'],viewerKit:['頁面工具','Dashboard tool'],versionUnknown:['版本未核實','Version unverified'],versionDifference:['版本不同','Versions differ'],versionDifferenceNote:['專案與頁面工具版本不同;開啟頁面不會升級專案。','Project and dashboard tool versions differ. Opening this page does not upgrade the project.'],versionSource:['專案版本讀自 PROJECT_INDEX.md 的 Stack;頁面工具版本讀自啟動套件。','Project version comes from PROJECT_INDEX.md Stack; dashboard tool version comes from the running package.'],
|
|
8
|
+
workRetained:['更新暫停,這裏顯示上次有效紀錄。','Updates paused. Showing the last valid record.'],eventSnapshot:['這則為開啟時的紀錄;來源已變,請從歷程重新選取。','This is the record opened earlier. Its source changed; reselect it in History.'],allWorkstreams:['所有工作線','All workstreams'],selectMap:['點選節點,突出顯示相關文件。','Select a node to highlight related documents.'],skip:['跳到內容','Skip to content'],overview:['總覽','Overview'],history:['歷程','History'],documents:['文件地圖','Document map'],project:['專案工作總覽','PROJECT DASHBOARD'],workstreams:['本專案工作','Project work'],recent:['最近變更','Recent changes'],viewHistory:['查看歷程','View history'],outstanding:['待辦事項','Outstanding work'],allWork:['全部工作','All work'],results:['成果與參考','Results & references'],documentRelations:['文件關係','Document connections'],documentIntro:['從目前交接,找回紀錄與依據。','Find the records and sources behind your handoff.'],viewMap:['查看地圖','View map'],projectHistory:['專案歷程','Project history'],historyIntro:['找回每次改變與交接的脈絡。','Follow the changes and the context behind each handoff.'],last7:['近7日','7 days'],last30:['近30日','30 days'],allDates:['全部日期','All dates'],from:['由','From'],to:['至','To'],search:['查找紀錄','Search records'],apply:['查看','Show'],loadMore:['繼續查閱紀錄','Continue reading'],dateBoundary:['日期只篩選歷程,目前未完事項不受影響。','Dates filter recorded events, not current outstanding work.'],documentsHeading:['專案文件導覽','Project documents'],documentsIntro:['核心文件看關係,其他已登記文件看清單。','Explore core document relationships or browse the registered file list.'],map:['核心關係','Core map'],list:['文件清單','File list'],mapBoundary:['連線表示已記錄的文件角色或關係;不代表已驗收。','Connections show declared roles and relationships, not acceptance.'],boundary:['依已保存紀錄更新;未保存的工作不會出現在這裏。','Updates from saved records. Unsaved work is not shown.'],sources:['資料依據','Sources'],empty:['尚未讀到交接紀錄。','No handoff records available yet.'],missing:['尚未記錄','Not recorded'],connected:['已連線','Connected'],offlineLabel:['連線中斷','Disconnected'],waiting:['連接中','Connecting'],interrupted:['更新待恢復','Updates paused'],close:['關閉','Close'],saved:['最後保存:{date}','Last saved: {date}'],focus:['正在查看','Viewing'],viewWork:['查看這項工作','View this work'],moreWork:['另有 {n} 條工作線','{n} more workstreams'],noWork:['尚未整理工作主線;可先查看目前交接。','Workstreams are not recorded yet. Read the current handoff.'],unknownState:['狀態未記錄','State not recorded'],noOutstanding:['未有明確記錄的未完項目;不代表全部完成。','No explicit outstanding items are recorded. This does not imply completion.'],noResults:['尚未登記成果入口。','No result links are registered yet.'],noEvents:['所選期間未找到紀錄。','No records found in this date range.'],noRecent:['尚未讀到近期紀錄。','No recent records loaded yet.'],showSource:['查看來源','Read source'],showDocument:['查看文件','Read document'],copied:['已複製','Copied'],copyPath:['複製路徑','Copy path'],copyFailed:['未能自動複製,請選取上方路徑。','Select the path above to copy it manually.'],sourceText:['原始紀錄','Source record'],purpose:['用途','Purpose'],parent:['所屬工作','Parent work'],children:['相關子項目','Related work'],relationships:['文件關係','Document relationships'],available:['檔案存在','File present'],notAvailable:['檔案未找到','File not found'],fileUnknown:['此格式可從專案檔案開啟;這裏不執行文件。','Open this format from the project. This page does not execute files.'],sourceChanged:['來源已更新,內容已同步。','Source updated. This view is current.'],loading:['正在讀取…','Loading…'],unavailable:['暫未能讀取,保留已顯示的內容。','Could not read this record. Existing content is retained.'],offline:['連接暫時中斷,保留上次資料,恢復後自動更新。','Connection interrupted. Last valid data is retained and will update on reconnection.'],upgrade:['Kit 正在升級,暫停讀取。','Kit upgrade in progress. Reading is paused.'],invalid:['部分紀錄暫未能完整讀取;保留上一次有效內容。','Some records cannot be read completely. Last valid data is retained.'],workInvalid:['工作項目格式有問題;暫不更新工作狀態。','Work records are invalid. Work state updates are paused.'],legacy:['此處顯示既有原文;尚未整理工作項目。','Existing source text is shown. Structured work items are not recorded.'],coverage:['這是已保存紀錄的導覽,不是 AI 完整接收交接或獨立驗收的證明。','Saved-record navigation does not prove full AI handoff reception or independent acceptance.'],readScope:['首頁讀現況;歷程按需讀主紀錄與封存。程式不寫回來源,也不呼叫 AI。','Current state loads first. History reads logs and archives on demand, without source writes or model calls.'],historyWindow:['已顯示 {n} 則;查閱 {files} / {total} 份相關紀錄檔。','Showing {n} events; checked {files} of {total} relevant files.'],historyMore:['尚有紀錄待查閱。','More records remain to be read.'],historyWarning:['部分歷史未能核實,不能把這個結果視作完整歷史。','Some history could not be verified. Results are not a complete history.'],historyChanged:['紀錄正在變動,請重新查看所選日期。','History changed while reading. Apply the date range again.'],dateError:['請選擇有效的起訖日期。','Choose a valid date range.'],archived:['封存紀錄','Archived record'],recentRecord:['近期紀錄','Recent record'],updated:['紀錄已更新','Records updated'],unclassified:['未分組','Ungrouped'],summary:['摘要','Summary'],done:['完成紀錄','Recorded work'],qc:['驗收紀錄','Checks'],pending:['尚未完成','Outstanding'],risks:['限制與風險','Constraints'],changed:['改變了甚麼','What changed'],reason:['原因','Reason'],boundaryField:['範圍','Scope'],focusFallback:['目前工作','Current work'],unknownGoal:['專案目標尚未記錄;目前任務請看下方。','The project goal is not recorded. Current work is shown below.'],profileFallback:['交接中的任務目標','Task goal from handoff'],sourceDate:['紀錄日期','Record date'],readTime:['最後成功讀取','Last successful read'],noMatches:['沒有符合條件的項目。','No matching items.'],continueSearch:['繼續查閱','Continue search'],allWorkTitle:['工作與交接狀態','Work and handoff state'],state:['狀態','Status'],notAStage:['工作線,並非完成順序','Workstreams, not a completion sequence'],linksEmpty:['未記錄其他關係。','No other relationships recorded.'],recordFields:['當次紀錄','Recorded details']
|
|
9
|
+
};
|
|
10
|
+
const roles={handoff:['目前交接','Current handoff'],log:['工作紀錄','Session log'],archive:['歷史封存','Archive index'],index:['文件索引','Project index'],rules:['工作規則','Working rules'],packs:['規則入口','Rule router'],decisions:['重要決定','Decisions'],sync:['同步關係','Sync registry'],document:['參考文件','Reference'],artifact:['成果','Result']};
|
|
11
|
+
const statuses={planned:['待完成','Planned'],active:['進行中','In progress'],waiting:['等待','Waiting'],review:['待驗收','Awaiting review'],done:['已完成','Done'],paused:['已暫停','Paused'],dropped:['已停止','Stopped']};
|
|
12
|
+
const incomingText={routes:['由此文件指向','routed from'],governs:['依循','governed by'],archives:['收錄自','archived from'],references:['被參考於','referenced by'],mirrors:['同步鏡像','mirrored by'],checks:['檢查由此觸發','checked with']};
|
|
13
|
+
const relationText={routes:['指向','routes to'],governs:['規範','governs'],archives:['封存至','archives to'],references:['參考','references'],mirrors:['同步鏡像','mirrors'],checks:['需一併檢查','also checks']};
|
|
14
|
+
const purposes={handoff:['保存目前目標、未完事項與接續位置。','Stores the current goal, outstanding work and resume point.'],log:['記錄每次工作發生過甚麼;不取代目前狀態。','Records what happened in each session, not current state.'],archive:['定位較早的工作紀錄,按需查閱。','Locates earlier records for on-demand reading.'],index:['指出文件位置、用途與必要來源。','Maps document locations, roles and sources.'],rules:['定義本專案的工作邊界與基本流程。','Defines project boundaries and working procedures.'],packs:['按任務選取需要的規則。','Routes tasks to the relevant rules.'],decisions:['保留重要選擇及其理由。','Preserves important decisions and rationale.'],sync:['記錄變更時哪些文件需要一併檢查或同步。','Records which documents need checks or synchronization.']};
|
|
15
|
+
let lang='zh-Hant';try{const v=localStorage.getItem('ahk-ui-language');if(['zh-Hant','en'].includes(v))lang=v;}catch{}const requested=new URLSearchParams(location.search).get('lang');if(['zh-Hant','en'].includes(requested))lang=requested;
|
|
16
|
+
const tr=(k,v={})=>(dict[k]?.[lang==='en'?1:0]||k).replace(/\{(\w+)\}/g,(_,x)=>String(v[x]??'')),pick=p=>p?.[lang==='en'?1:0]||'',esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
17
|
+
const icon=name=>`<svg aria-hidden="true"><use href="icons.svg#${name}"></use></svg>`;
|
|
18
|
+
const title=w=>lang==='zh-Hant'&&w.titleZh||w.title,summary=w=>lang==='zh-Hant'&&w.summaryZh||w.summary;
|
|
19
|
+
const short=(s,n=140)=>{s=String(s||'').replace(/\s+/g,' ').trim();return s.length>n?s.slice(0,n)+'…':s;};
|
|
20
|
+
const pill=s=>`<span class="pill ${esc(s)}">${esc(pick(statuses[s])||tr('unknownState'))}</span>`;
|
|
21
|
+
const cite=r=>r?.source?`<p class="citation">${esc(r.source.file)} · ${lang==='en'?'line':'第'} ${r.source.line}${lang==='en'?'':' 行'}</p>`:'';
|
|
22
|
+
function date(s,brief=false){if(!s)return tr('missing');const d=new Date(/^\d{4}-\d{2}-\d{2}$/.test(s)?s+'T12:00:00':s);if(Number.isNaN(d.getTime()))return s;return new Intl.DateTimeFormat(lang==='en'?'en-GB':'zh-Hant',{...(!brief||d.getFullYear()!==new Date().getFullYear()?{year:'numeric'}:{}),month:'short',day:'numeric',...(!brief&&s.includes('T')?{hour:'2-digit',minute:'2-digit'}:{})}).format(d);}
|
|
23
|
+
const reduced=matchMedia('(prefers-reduced-motion: reduce)');
|
|
24
|
+
function motion(el,keyframes,options={}){if(el&&!reduced.matches)el.animate(keyframes,{duration:260,easing:'cubic-bezier(.22,.8,.3,1)',...options});}
|
|
25
|
+
function reveal(el){motion(el,[{opacity:.3,transform:'translateY(8px)'},{opacity:1,transform:'translateY(0)'}]);}
|
|
26
|
+
function updated(el){motion(el,[{backgroundColor:'#e2edff'},{backgroundColor:'transparent'}],{duration:1800});}
|
|
27
|
+
const relationLabel=(link,id)=>pick((link.from===id?relationText:incomingText)[link.type]);
|
|
28
|
+
const eventTitle=r=>lang==='zh-Hant'&&(r.titleZh||r.fields?.['title zh-hant'])||r.title;
|
|
29
|
+
const eventSummary=r=>lang==='zh-Hant'&&(r.summaryZh||r.fields?.['summary zh-hant'])||r.summary;
|
|
30
|
+
let data=null,online=false,session='',sequence=-1,selected=null,view='overview',lastRead=null,drawerState=null,drawerRequest=0,returnTo=null,returnSelector=null,historyItems=[],historyNext=null,historyMeta=null,historyRequest=0,historyLoaded=false,historyDirty=false,historyQuery=null,mapMode='map',mapSelected='handoff';
|
|
31
|
+
const drawer=$('#drawer');const work=()=>data?.dashboard?.work?.items||[],documents=()=>data?.dashboard?.documents||[];
|
|
32
|
+
const docName=d=>pick(roles[d.role])+(d.role==='document'||d.role==='artifact'?': '+(lang==='zh-Hant'&&d.titleZh||d.title||d.file):'');
|
|
33
|
+
const docByFile=file=>documents().find(d=>d.file===file);
|
|
34
|
+
let stream=null,reconnectTimer=null,reconnectAttempts=0,connectionPaused=false;
|
|
35
|
+
function route(){const name=location.hash.slice(1).split('/')[0];const previousView=view;view=['overview','history','documents'].includes(name)?name:'overview';for(const v of ['overview','history','documents'])$('#'+v+'-view').hidden=view!==v;document.querySelectorAll('[data-view]').forEach(a=>{if(a.dataset.view===view)a.setAttribute('aria-current','page');else a.removeAttribute('aria-current');});if(view==='history'&&data&&online&&(!historyLoaded||historyDirty))loadHistory(false,historyDirty);if(view==='documents')renderDocuments();if(previousView!==view)reveal($('#'+view+'-view'));}
|
|
36
|
+
function versionInfo(){const project=data?.dashboard?.projectKitVersion||null,raw=data?.kitVersion,tool=typeof raw==='string'&&/^\d+\.\d+\.\d+$/.test(raw)?raw:null;const different=!!(project&&tool&&project!==tool);return{project,tool,different,label:project?'v'+project+(different?' · '+tr('versionDifference'):''):tr('versionUnknown'),description:tr('projectKit')+': '+(project?'v'+project:tr('versionUnknown'))+' · '+tr('viewerKit')+': '+(tool?'v'+tool:tr('versionUnknown'))+(different?' — '+tr('versionDifferenceNote'):'')};}
|
|
37
|
+
function render(){
|
|
38
|
+
document.documentElement.lang=lang;$('#language').value=lang;document.querySelectorAll('[data-i18n]').forEach(e=>e.textContent=tr(e.dataset.i18n));document.querySelectorAll('[data-placeholder]').forEach(e=>e.placeholder=tr(e.dataset.placeholder));$('#close').ariaLabel=tr('close');
|
|
39
|
+
const version=versionInfo(),badge=$('#kit-version');badge.textContent=version.label;badge.title=version.description;badge.setAttribute('aria-label',version.description);badge.dataset.state=!version.project?'unverified':version.different?'different':'matched';
|
|
40
|
+
const errors={...(data?.errors||{}),...(data?.dashboard?.errors||{})};const hasErrors=Object.keys(errors).length>0;document.body.dataset.live=String(online&&!hasErrors);$('#sync').textContent=tr(!online?(data?'offlineLabel':'waiting'):hasErrors?'interrupted':'connected');
|
|
41
|
+
const warning=!online&&(data||reconnectAttempts)?'offline':errors.lock?'upgrade':errors.work?'workInvalid':hasErrors?'invalid':null;$('#warning').hidden=!warning;$('#warning').innerHTML=warning==='offline'?esc(tr('reconnectNote'))+' <button class="text-link" data-action="retry">'+tr('retryNow')+'</button> <button class="text-link" data-copy="'+esc(tr('reopenPrompt'))+'">'+tr('reopenCopy')+'</button>':warning?esc(tr(warning)):'';
|
|
42
|
+
const p=data?.dashboard?.profile||{};const name=(lang==='zh-Hant'&&p.nameZh)||p.name||data?.project?.name||tr('missing');$('#project-title').textContent=name;$('#history-project').textContent=name;$('#documents-project').textContent=name;document.title=name+' · Agent Handoff Kit';
|
|
43
|
+
const saved=data?.sources?.find(s=>s.file.includes('HANDOFF'))?.updated;$('#freshness').innerHTML=icon('calendar')+esc(tr('handoffSaved',{date:date(saved||data?.recordDate)}));$('#empty').hidden=!!data?.available;
|
|
44
|
+
const current=data?.project?.current?.text;$('#recorded-current').textContent=tr('recordedCurrent')+':'+short(current||tr('missing'),150);$('#recorded-current').title=current||tr('missing');
|
|
45
|
+
const workValue=$('#history-work').value;$('#history-work').innerHTML='<option value="">'+tr('allWorkstreams')+'</option>'+work().map(w=>'<option value="'+esc(w.id)+'">'+esc(title(w))+'</option>').join('');$('#history-work').value=workValue;renderWork();renderRecent();renderStrip();if(view==='documents')renderDocuments();if(view==='history')renderHistory();route();
|
|
46
|
+
}
|
|
47
|
+
function legacyWorkHTML(){
|
|
48
|
+
const collections=['pending','risks'].map(kind=>({kind,items:data?.sections?.[kind]?.items||[],total:data?.sections?.[kind]?.total||0}));
|
|
49
|
+
const visible=collections.reduce((n,c)=>n+c.items.length,0),total=collections.reduce((n,c)=>n+c.total,0);
|
|
50
|
+
const warning=data?.errors?.handoff||data?.errors?.lock;
|
|
51
|
+
let html=warning?`<p class="scope-note">${tr(data?.available?'workRetained':'unavailable')}</p>`:'';
|
|
52
|
+
if(visible){html+=`<p class="scope-note">${tr('legacyWork')}</p>`+collections.filter(c=>c.items.length).map(c=>`<h3 class="legacy-label">${tr(c.kind)}</h3>`+c.items.map(r=>`<button class="work-row" data-document="handoff"><span>${esc(short(r.text,180))}</span></button>`).join('')).join('');
|
|
53
|
+
if(total>visible)html+=`<button class="text-link" data-document="handoff">${tr('moreLegacy',{n:total-visible})}</button>`;
|
|
54
|
+
}else html+=`<p class="empty">${tr(data?.available?'noOutstanding':'unavailable')}</p>`;
|
|
55
|
+
return html+`<button class="text-link" data-document="handoff">${tr('showSource')}</button>`;
|
|
56
|
+
}
|
|
57
|
+
function renderWork(){
|
|
58
|
+
const items=work(),roots=items.filter(x=>!x.parent);if(!items.some(x=>x.id===selected))selected=items.find(x=>x.status==='active')?.id||roots[0]?.id||null;
|
|
59
|
+
const selectedWork=items.find(x=>x.id===selected);let selectedRoot=selected;for(let w=selectedWork;w?.parent;w=items.find(x=>x.id===w.parent))selectedRoot=w.parent;
|
|
60
|
+
$('#work-route').innerHTML=roots.length?roots.slice(0,5).map((w,i)=>`<button class="route-node" data-work-select="${esc(w.id)}" aria-pressed="${w.id===selectedRoot}"><span class="node-circle">${icon(i===2?'grid':'document')}</span><strong>${esc(title(w))}</strong><span class="description">${esc(short(summary(w),100))}</span><span class="relation">${esc(pick(statuses[w.status]))}</span></button>`).join(''):`<p class="empty">${tr('noWork')}</p>`;
|
|
61
|
+
$('#work-route').ariaLabel=tr('notAStage');$('#work-scope').textContent=tr('notAStage');$('#work-scope').hidden=!roots.length;$('#more-work').hidden=roots.length<=5;$('#more-work').textContent=tr('moreWork',{n:roots.length-5});
|
|
62
|
+
if(selectedWork)$('#focus').innerHTML=`<h2>${tr('focus')}:${esc(title(selectedWork))}</h2>${pill(selectedWork.status)}<div class="focus-actions"><button class="primary" data-work="${esc(selectedWork.id)}">${tr('viewWork')}${icon('arrow')}</button></div>`;
|
|
63
|
+
else $('#focus').innerHTML=`<h2>${tr('focusFallback')}</h2><p class="focus-summary">${esc(short(data?.project?.current?.text||tr('missing'),240))}</p><div class="focus-actions"><button class="primary" data-document="handoff">${tr('showDocument')}</button></div>`;
|
|
64
|
+
const pending=items.filter(w=>!['done','dropped'].includes(w.status)&&(!items.some(c=>c.parent===w.id)||w.status!=='active'));
|
|
65
|
+
$('#pending-list').innerHTML=!items.length?legacyWorkHTML():pending.length?pending.slice(0,3).map(w=>`<button class="work-row" data-work="${esc(w.id)}">${pill(w.status)}<span><strong>${esc(title(w))}</strong><small>${esc(short(summary(w),80))}</small></span></button>`).join('')+(pending.length>3?`<button class="text-link" data-action="all-work">${tr('morePending',{n:pending.length-3})}</button>`:''):`<p class="empty">${tr('noOutstanding')}</p><button class="text-link" data-document="handoff">${tr('showDocument')}</button>`;
|
|
66
|
+
const results=items.filter(w=>w.artifact).slice(0,3);$('#result-list').innerHTML=results.length?results.map(w=>{const d=docByFile(w.artifact);return`<button class="result-row" data-document="${esc(d?.id||'handoff')}">${icon('document')}<span><strong>${esc(title(w))}</strong><small>${esc(w.artifact.split('/').pop())}</small></span></button>`;}).join(''):`<p class="empty">${tr('noResults')}</p>`;
|
|
67
|
+
}
|
|
68
|
+
function renderRecent(){const rows=data?.recent?.items||[];$('#recent-list').innerHTML=rows.length?rows.slice(0,3).map((r,i)=>`<button class="recent-row" data-recent="${i}"><time>${esc(date(r.title.slice(0,10),true))}</time><span><strong>${esc(eventTitle({...r,title:r.title.slice(10).replace(/^\s*[—–-]\s*/,'' )}))}</strong><small>${esc(short(eventSummary({...r,summary:r.summary?.text?.replace(/^Summary[::]\s*/i,'')}),95))}</small></span></button>`).join(''):`<p class="empty">${tr('noRecent')}</p>`;}
|
|
69
|
+
function renderStrip(){const ids=['handoff','log','archive','index'];$('#document-strip').innerHTML=ids.map(id=>documents().find(d=>d.id===id)).filter(Boolean).map(d=>`<button class="strip-node" data-document="${d.id}"><span class="mini-node">${icon(d.id==='archive'?'archive':d.id==='index'?'map':'document')}</span><span><strong>${esc(docName(d))}</strong><small>${esc(d.file.split('/').pop())}</small></span></button>`).join('');}
|
|
70
|
+
function renderDocuments(){const docs=documents(),links=data?.dashboard?.links||[];$('#document-status').textContent=data?.dashboard?.errors.documents?tr('invalid'):'';
|
|
71
|
+
$('#document-map').hidden=mapMode!=='map';$('#document-list').hidden=mapMode!=='list';$('#map-mode').setAttribute('aria-pressed',String(mapMode==='map'));$('#list-mode').setAttribute('aria-pressed',String(mapMode==='list'));
|
|
72
|
+
const order=['index','handoff','log','archive','packs','rules','decisions','sync'];const core=docs.filter(d=>order.includes(d.role)).sort((a,b)=>order.indexOf(a.role)-order.indexOf(b.role));const linked=new Set(links.filter(l=>l.from===mapSelected||l.to===mapSelected).flatMap(l=>[l.from,l.to]));linked.add(mapSelected);
|
|
73
|
+
const scope=tr(mapMode==='map'?'coreScope':'listScope',{n:mapMode==='map'?core.length:docs.length});$('#document-status').textContent=scope+(data?.dashboard?.errors.documents?' '+tr('invalid'):'');
|
|
74
|
+
$('#document-map').innerHTML='<svg class="map-lines" aria-hidden="true"></svg>'+core.map(d=>`<button class="doc-node ${d.available?'':'missing'} ${linked.has(d.id)?'related':'subdued'}" data-role="${d.role}" data-map="${d.id}" aria-pressed="${d.id===mapSelected}"><span class="node-circle">${icon(d.role==='archive'?'archive':d.role==='index'?'map':'document')}</span><strong>${esc(docName(d))}</strong><small>${esc(d.file.split('/').pop())}</small></button>`).join('');
|
|
75
|
+
const d=docs.find(x=>x.id===mapSelected);if(d){const related=links.filter(l=>l.from===d.id||l.to===d.id);$('#map-detail').innerHTML=`<div><h2>${esc(docName(d))}</h2><p>${esc(pick(purposes[d.role])||d.title||'')}</p></div><div class="map-relations">${related.map(l=>{const other=docs.find(x=>x.id===(l.from===d.id?l.to:l.from));return `<span>${esc(relationLabel(l,d.id))} <button class="text-link" ${core.some(x=>x.id===other.id)?'data-map':'data-document'}="${esc(other.id)}">${esc(docName(other))}</button></span>`;}).join('')||tr('linksEmpty')}</div><button class="primary" data-document="${esc(d.id)}">${tr('showDocument')}${icon('arrow')}</button>`;}
|
|
76
|
+
$('#map-detail').hidden=mapMode!=='map';$('#document-list').innerHTML=docs.map(d=>`<button data-document="${esc(d.id)}"><strong>${esc(docName(d))}</strong><small>${esc(d.file)}</small><small>${tr(d.available?'available':'notAvailable')}</small></button>`).join('');requestAnimationFrame(drawConnections);
|
|
77
|
+
}
|
|
78
|
+
function drawConnections(){if(view!=='documents'||mapMode!=='map')return;const box=$('#document-map'),svg=box.querySelector('svg'),bounds=box.getBoundingClientRect();if(!bounds.width)return;svg.setAttribute('viewBox',`0 0 ${bounds.width} ${bounds.height}`);svg.innerHTML='<defs><marker id="arrowhead" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto"><path d="M0 0 L7 3.5 L0 7" fill="currentColor" stroke="none"/></marker></defs>'+(data.dashboard.links||[]).map(l=>{const a=box.querySelector('[data-map="'+l.from+'"] .node-circle'),b=box.querySelector('[data-map="'+l.to+'"] .node-circle');if(!a||!b)return '';const ar=a.getBoundingClientRect(),br=b.getBoundingClientRect(),ax=ar.x+ar.width/2-bounds.x,ay=ar.y+ar.height/2-bounds.y,bx=br.x+br.width/2-bounds.x,by=br.y+br.height/2-bounds.y,dx=bx-ax,dy=by-ay,len=Math.hypot(dx,dy)||1,rad=43,x1=ax+dx/len*rad,y1=ay+dy/len*rad,x2=bx-dx/len*rad,y2=by-dy/len*rad;return `<path class="${l.from===mapSelected||l.to===mapSelected?'lit':''}" d="M${x1} ${y1} C${x1} ${(y1+y2)/2},${x2} ${(y1+y2)/2},${x2} ${y2}" marker-end="url(#arrowhead)"/>`;}).join('');}
|
|
79
|
+
new ResizeObserver(()=>requestAnimationFrame(drawConnections)).observe($('#document-map'));
|
|
80
|
+
function focusSelector(el){if(el?.id)return '#'+CSS.escape(el.id);for(const key of ['work','document','event','recent','workSelect','action'])if(el?.dataset?.[key]!==undefined)return 'main [data-'+key.replace(/[A-Z]/g,x=>'-'+x.toLowerCase())+'="'+CSS.escape(el.dataset[key])+'"]';return null;}
|
|
81
|
+
function openDrawer(state,titleText,body,kicker=''){if(!drawer.open){returnTo=document.activeElement;returnSelector=focusSelector(returnTo);}drawerState=state;$('#drawer-title').textContent=titleText;$('#drawer-kicker').textContent=kicker;$('#drawer-content').innerHTML=body;if(!drawer.open){drawer.showModal();motion(drawer,[{transform:'translateX(50px)',opacity:.4},{transform:'translateX(0)',opacity:1}],{duration:300});}}
|
|
82
|
+
function showWork(id,update=false){const w=work().find(x=>x.id===id);if(!w)return;const children=work().filter(x=>x.parent===id),parent=work().find(x=>x.id===w.parent);let body=pill(w.status)+`<p>${esc(summary(w)||tr('missing'))}</p>`;if(parent)body+=`<h3>${tr('parent')}</h3><button class="text-link" data-work="${esc(parent.id)}">${esc(title(parent))}</button>`;if(children.length)body+=`<h3>${tr('children')}</h3><div class="work-list">${children.map(c=>`<button class="work-row" data-work="${esc(c.id)}">${pill(c.status)}<span><strong>${esc(title(c))}</strong><small>${esc(summary(c))}</small></span></button>`).join('')}</div>`;body+=cite(w)+`<div class="drawer-actions"><button class="secondary" data-document="handoff">${tr('showSource')}</button>${w.artifact?`<button class="primary" data-document="${esc(docByFile(w.artifact)?.id||'handoff')}">${tr('showDocument')}</button>`:''}</div>`;if(update)body=`<p class="updated-note">${tr(data?.errors?.handoff||data?.errors?.lock||data?.dashboard?.errors?.work?'workRetained':'sourceChanged')}</p>`+body;openDrawer({kind:'work',id},title(w),body,tr('state'));}
|
|
83
|
+
async function showDocument(id,update=false){const previousBody=update?$('#drawer-content').innerHTML:null;const d=documents().find(x=>x.id===id);if(!d)return;const requestId=++drawerRequest,scroll=update?drawer.scrollTop:0;const relation=(data?.dashboard?.links||[]).filter(l=>l.from===id||l.to===id);const base=`<p>${esc(pick(purposes[d.role])||d.title||tr('missing'))}</p><p class="citation">${esc(d.file)}</p><div class="drawer-actions"><button class="secondary" data-copy="${esc(d.file)}">${icon('copy')}${tr('copyPath')}</button>${d.role==='log'||d.role==='archive'?`<button class="secondary" data-action="history">${tr('viewHistory')}</button>`:''}</div>${relation.length?`<h3>${tr('relationships')}</h3>${relation.map(l=>{const other=documents().find(x=>x.id===(l.from===id?l.to:l.from));return`<p>${esc(relationLabel(l,id))} <button class="text-link" data-document="${esc(other.id)}">${esc(docName(other))}</button></p>`;}).join('')}`:''}`;openDrawer({kind:'document',id},docName(d),base+`<p>${tr('loading')}</p>`,tr('sources'));try{const r=await fetch('/api/document?id='+encodeURIComponent(id));if(!r.ok)throw Error();const result=await r.json();if(requestId!==drawerRequest||!drawer.open)return;$('#drawer-content').innerHTML=(update?`<p class="updated-note">${tr('sourceChanged')}</p>`:'')+base+`<h3>${tr('sourceText')}</h3>`+(result.text!==null?`<pre tabindex="0">${esc(result.text)}</pre>`:`<p>${tr('fileUnknown')}</p>`);drawer.scrollTop=scroll;}catch{if(requestId===drawerRequest&&drawer.open)$('#drawer-content').innerHTML=(previousBody||base)+`<p class="warning">${tr(d.available?'unavailable':'notAvailable')}</p>`;}}
|
|
84
|
+
function showEvent(item){const map={summary:'summary',changed:'changed',done:'done',qc:'qc',pending:'pending',risks:'risks',reason:'reason',boundary:'boundaryField'};let body=`<p class="citation">${esc(date(item.date))}${item.work?' · '+esc(work().some(w=>w.id===item.work)?title(work().find(w=>w.id===item.work)):item.work):''}</p>`;const f=item.fields||{};let fields=Object.entries(map).filter(([k])=>f[k]);body+=fields.length?fields.map(([k,label])=>`<h3>${tr(label)}</h3><p>${esc(lang==='zh-Hant'&&f[k+' zh-hant']||f[k])}</p>`).join(''):`<p>${esc(item.summary||item.body||tr('missing'))}</p>`;body+=cite(item);if(item.body)body+=`<details><summary>${tr('sourceText')}</summary><pre>${esc(item.body)}</pre></details>`;openDrawer({kind:'event',item},eventTitle(item),body,tr(item.source?.file.includes('_archive/')?'archived':'recentRecord'));}
|
|
85
|
+
function showSources(){const version=versionInfo();const body=`<div class="source-row">${esc(version.description)}<small>${esc(tr('versionSource'))}</small></div>`+(data?.sources||[]).map(s=>`<div class="source-row">${esc(s.file)}<small>${esc(tr('saved',{date:date(s.updated)}))}</small></div>`).join('')+`<p class="citation">${tr('readTime')}:${esc(date(lastRead))}</p><p>${tr('readScope')}</p><p class="citation">${tr('coverage')}</p>`;openDrawer({kind:'sources'},tr('sources'),body);}
|
|
86
|
+
function showAllWork(){openDrawer({kind:'all'},tr('allWorkTitle'),work().length?`<div class="work-list">${work().map(w=>`<button class="work-row" data-work="${esc(w.id)}">${pill(w.status)}<span><strong>${esc(title(w))}</strong><small>${esc(summary(w))}</small></span></button>`).join('')}</div>`:legacyWorkHTML());}
|
|
87
|
+
function refreshDrawer(){if(!drawer.open)return;const s=drawerState,scroll=drawer.scrollTop;if(s?.kind==='work')showWork(s.id,true);else if(s?.kind==='document')showDocument(s.id,true);else if(s?.kind==='sources')showSources();else if(s?.kind==='all')showAllWork();else if(s?.kind==='event'){const recent=(data.recent?.items||[]).find(r=>r.id===s.item.id);const current=historyItems.find(r=>r.id===s.item.id);if(current||recent){showEvent(current||{...recent,date:recent.title.slice(0,10),title:recent.title.slice(10).replace(/^\s*[—–-]\s*/,''),summary:recent.summary?.text});}else if(!$('#event-update'))$('#drawer-content').insertAdjacentHTML('afterbegin',`<p id="event-update" class="updated-note">${tr('eventSnapshot')}</p>`);}drawer.scrollTop=scroll;}
|
|
88
|
+
function localDay(d){return [d.getFullYear(),String(d.getMonth()+1).padStart(2,'0'),String(d.getDate()).padStart(2,'0')].join('-');}
|
|
89
|
+
function setRange(days){const now=new Date();$('#to').value=days==='all'?'':localDay(now);const start=new Date(now);start.setDate(start.getDate()-Number(days||30)+1);$('#from').value=days==='all'?'':localDay(start);document.querySelectorAll('[data-days]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.days===String(days))));}
|
|
90
|
+
async function loadHistory(more=false,automatic=false){if(!data)return;const from=automatic&&historyQuery?historyQuery.from:$('#from').value,to=automatic&&historyQuery?historyQuery.to:$('#to').value;if(from&&to&&from>to){$('#history-status').textContent=tr('dateError');return;}const requestId=++historyRequest;const q={from,to,search:automatic&&historyQuery?historyQuery.search:$('#search').value,work:automatic&&historyQuery?historyQuery.work:$('#history-work').value};if(more&&historyNext)q.cursor=historyNext;const oldItems=historyItems,oldCount=historyItems.length;const anchor=[...document.querySelectorAll('[data-event]')].find(e=>e.getBoundingClientRect().top>=0);const anchorId=anchor?.dataset.event,anchorY=anchor?.getBoundingClientRect().top;historyLoaded=true;historyDirty=false;$('#history-status').textContent=tr('loading');$('#history-more').disabled=true;$('#history-list').setAttribute('aria-busy','true');
|
|
91
|
+
try{let combined=more?[...historyItems]:[],result,pages=0;do{const r=await fetch('/api/history?'+new URLSearchParams(q));if(!r.ok)throw Error();result=await r.json();if(requestId!==historyRequest)return;const ids=new Set(combined.map(x=>x.id));combined.push(...result.items.filter(x=>!ids.has(x.id)));q.cursor=result.next;pages++;}while(automatic&&result.next&&combined.length<oldCount&&pages<5);
|
|
92
|
+
historyQuery={from,to,search:q.search,work:q.work};historyItems=combined;historyNext=result.next;historyMeta=result;historyDirty=false;renderHistory();if(automatic&&anchorId){const nextAnchor=$('[data-event="'+anchorId+'"]');if(nextAnchor)window.scrollBy(0,nextAnchor.getBoundingClientRect().top-anchorY);}else reveal($('#history-list'));if(automatic){const oldById=new Map(oldItems.map(x=>[x.id,x.fingerprint]));document.querySelectorAll('[data-event]').forEach(el=>{const entry=combined.find(x=>x.id===el.dataset.event);if(entry&&oldById.get(entry.id)!==entry.fingerprint)updated(el);});}if(drawerState?.kind==='event')refreshDrawer();
|
|
93
|
+
}catch{if(requestId===historyRequest){historyDirty=true;$('#history-status').textContent=tr(more?'historyChanged':'unavailable');}}finally{if(requestId===historyRequest){$('#history-more').disabled=false;$('#history-list').removeAttribute('aria-busy');}}}
|
|
94
|
+
function renderHistory(){if(!historyLoaded)return;const groups=new Map();for(const item of [...historyItems].sort((a,b)=>b.date.localeCompare(a.date))){if(!groups.has(item.date))groups.set(item.date,[]);groups.get(item.date).push(item);}
|
|
95
|
+
$('#history-list').innerHTML=groups.size?[...groups].map(([day,rows])=>`<section class="day"><h2>${esc(date(day))}</h2><div class="day-events">${rows.map(r=>`<button class="event" data-event="${esc(r.id)}"><strong>${esc(eventTitle(r))}</strong><p>${esc(short(eventSummary(r),200))}</p><span class="event-meta">${esc(r.work?(work().some(w=>w.id===r.work)?title(work().find(w=>w.id===r.work)):r.work):tr('unclassified'))} · ${tr(r.source.file.includes('_archive/')?'archived':'recentRecord')}</span></button>`).join('')}</div></section>`).join(''):`<p class="empty">${tr(historyNext?'historyMore':'noEvents')}</p>`;
|
|
96
|
+
if(historyMeta)$('#history-status').textContent=tr('historyWindow',{n:historyItems.length,files:historyMeta.filesChecked,total:historyMeta.totalFiles})+' '+(historyMeta.warnings.length?tr('historyWarning'):'')+' '+(historyNext?tr('historyMore'):'')+(historyDirty?' '+tr('updated'):'');$('#history-more').hidden=!historyNext;
|
|
97
|
+
}
|
|
98
|
+
$('#close').onclick=()=>drawer.close();drawer.onclose=()=>{drawerRequest++;drawerState=null;const target=returnTo?.isConnected?returnTo:returnSelector?$(returnSelector):null;(target||document.querySelector('nav [aria-current=page]'))?.focus({preventScroll:true});};
|
|
99
|
+
document.addEventListener('click',async e=>{const b=e.target.closest('button');if(!b||b.disabled)return;
|
|
100
|
+
if(b.dataset.workSelect){selected=b.dataset.workSelect;renderWork();reveal($('#focus'));motion($('[data-work-select="'+selected+'"] .node-circle'),[{transform:'scale(.95)'},{transform:'scale(1.12)'},{transform:'scale(1.08)'}],{duration:350});$(`[data-work-select="${selected}"]`)?.focus({preventScroll:true});}
|
|
101
|
+
else if(b.dataset.map){mapSelected=b.dataset.map;renderDocuments();reveal($('#map-detail'));$('#document-map [data-map="'+mapSelected+'"]')?.focus({preventScroll:true});}
|
|
102
|
+
else if(b.dataset.work)showWork(b.dataset.work);
|
|
103
|
+
else if(b.dataset.document)showDocument(b.dataset.document);
|
|
104
|
+
else if(b.dataset.recent!==undefined){const r=data.recent.items[Number(b.dataset.recent)];showEvent({...r,title:r.title.slice(10).replace(/^\s*[—–-]\s*/,''),date:r.title.slice(0,10),summary:r.summary?.text||'',fields:r.fields,body:r.body,source:r.source});}
|
|
105
|
+
else if(b.dataset.event){const item=historyItems.find(x=>x.id===b.dataset.event);if(item)showEvent(item);}
|
|
106
|
+
else if(b.dataset.copy){try{await navigator.clipboard.writeText(b.dataset.copy);b.textContent=tr('copied');}catch{b.textContent=b.dataset.copy===tr('reopenPrompt')?b.dataset.copy:tr('copyFailed');}}
|
|
107
|
+
else if(b.dataset.days){setRange(b.dataset.days);loadHistory();}
|
|
108
|
+
else if(b.dataset.action==='retry')connect();else if(b.dataset.action==='sources')showSources();else if(b.dataset.action==='all-work')showAllWork();else if(b.dataset.action==='history'){drawer.close();location.hash='history';}
|
|
109
|
+
});
|
|
110
|
+
$('#language').onchange=e=>{lang=e.target.value;try{localStorage.setItem('ahk-ui-language',lang);}catch{}render();refreshDrawer();};$('#history-filter').onsubmit=e=>{e.preventDefault();document.querySelectorAll('[data-days]').forEach(b=>b.setAttribute('aria-pressed','false'));loadHistory();};$('#history-more').onclick=()=>loadHistory(true);$('#map-mode').onclick=()=>{mapMode='map';renderDocuments();};$('#list-mode').onclick=()=>{mapMode='list';renderDocuments();};window.addEventListener('hashchange',route);setRange(30);
|
|
111
|
+
function disconnect(current){
|
|
112
|
+
if(stream!==current)return;
|
|
113
|
+
current.close();stream=null;online=false;
|
|
114
|
+
if(!connectionPaused&&reconnectTimer===null){
|
|
115
|
+
const delay=Math.min(30000,1000*2**Math.min(reconnectAttempts++,5));
|
|
116
|
+
reconnectTimer=setTimeout(()=>{reconnectTimer=null;connect();},delay);
|
|
117
|
+
}
|
|
118
|
+
render();
|
|
119
|
+
}
|
|
120
|
+
function connect(){
|
|
121
|
+
if(connectionPaused||location.protocol!=='http:'||location.hostname!=='127.0.0.1'||!window.EventSource)return;
|
|
122
|
+
clearTimeout(reconnectTimer);reconnectTimer=null;
|
|
123
|
+
if(stream){if(online)return;stream.close();}
|
|
124
|
+
const current=new EventSource('/events');stream=current;
|
|
125
|
+
current.onmessage=e=>{
|
|
126
|
+
if(stream!==current)return;
|
|
127
|
+
try{
|
|
128
|
+
const next=JSON.parse(e.data);if(next.schemaVersion!==2||!next.dashboard||typeof next.session!=='string')throw Error();
|
|
129
|
+
if(next.session===session&&next.version<sequence)return;
|
|
130
|
+
const oldData=data,hadData=!!data,resumed=hadData&&!online,restarted=hadData&&next.session!==session;
|
|
131
|
+
const changed=hadData&&(resumed||restarted||next.version!==data.version||next.dashboard.revision!==data.dashboard.revision);
|
|
132
|
+
if(hadData&&(resumed||restarted||next.dashboard.historyRevision!==data.dashboard.historyRevision))historyDirty=true;
|
|
133
|
+
if(resumed||restarted){historyNext=null;historyRequest++;drawerRequest++;}
|
|
134
|
+
session=next.session;sequence=next.version;data=next;online=true;reconnectAttempts=0;lastRead=new Date().toISOString();
|
|
135
|
+
const active=document.activeElement,focusKey=active?.dataset.workSelect;render();
|
|
136
|
+
if(!hadData){document.querySelectorAll('.route-node,.overview-grid .panel').forEach((el,i)=>motion(el,[{opacity:0,transform:'translateY(12px)'},{opacity:1,transform:'none'}],{delay:i*60,duration:380}));}
|
|
137
|
+
else{for(const w of work()){const old=oldData.dashboard.work.items.find(x=>x.id===w.id);if(JSON.stringify(old)!==JSON.stringify(w))updated($('[data-work-select="'+w.id+'"]'));}}
|
|
138
|
+
if(focusKey)$('[data-work-select="'+focusKey+'"]')?.focus({preventScroll:true});
|
|
139
|
+
if(changed){refreshDrawer();$('#announcement').textContent=tr('updated');}
|
|
140
|
+
document.body.dataset.version=String(data.version);
|
|
141
|
+
}catch{disconnect(current);}
|
|
142
|
+
};
|
|
143
|
+
current.onerror=()=>disconnect(current);
|
|
144
|
+
}
|
|
145
|
+
const wake=()=>{if(!online&&!stream&&!connectionPaused)connect();};
|
|
146
|
+
window.addEventListener('online',wake);window.addEventListener('focus',wake);
|
|
147
|
+
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')wake();});
|
|
148
|
+
window.addEventListener('pagehide',()=>{connectionPaused=true;clearTimeout(reconnectTimer);reconnectTimer=null;stream?.close();stream=null;online=false;});
|
|
149
|
+
window.addEventListener('pageshow',()=>{connectionPaused=false;wake();});
|
|
150
|
+
connect();
|
|
151
|
+
render();
|
|
152
|
+
})();
|