Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1 lines (1 loc) · 32.9 KB
/
Copy pathmain.js
File metadata and controls
1 lines (1 loc) · 32.9 KB
1
"use strict";var U=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var ee=Object.prototype.hasOwnProperty;var te=(p,t)=>{for(var n in t)U(p,n,{get:t[n],enumerable:!0})},ne=(p,t,n,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Z(t))!ee.call(p,r)&&r!==n&&U(p,r,{get:()=>t[r],enumerable:!(e=X(t,r))||e.enumerable});return p};var se=p=>ne(U({},"__esModule",{value:!0}),p);var pe={};te(pe,{default:()=>L});module.exports=se(pe);var v=require("obsidian");var G=require("obsidian"),N="tasknotes-pm-gantt",re=24*60*60*1e3,_=7*re,ae=72,$=class extends G.ItemView{constructor(n,e){super(n);this.plugin=e}selectedProject="all";getViewType(){return N}getDisplayText(){return"Tasknotes-PM Gantt"}getIcon(){return"chart-gantt"}async onOpen(){await this.render()}async render(){let n=this.contentEl;n.empty(),n.addClass("tasknotes-pm-gantt-view");let e=n.createDiv({cls:"tasknotes-pm-gantt-toolbar"});e.createEl("h2",{text:"Project timeline"});let r=e.createDiv({cls:"tasknotes-pm-gantt-controls"}),s=r.createEl("select",{attr:{"aria-label":"Choose project"}}),a=r.createEl("button",{attr:{"aria-label":"Refresh Gantt chart"}});(0,G.setIcon)(a,"refresh-cw");let o;try{o=await this.plugin.getGanttProjects()}catch(c){n.createDiv({cls:"tasknotes-pm-gantt-empty",text:`Unable to load projects: ${this.plugin.describeError(c)}`});return}s.createEl("option",{text:"All open projects",value:"all"});for(let c of o)s.createEl("option",{text:c.name,value:c.path});this.selectedProject!=="all"&&!o.some(c=>c.path===this.selectedProject)&&(this.selectedProject="all"),s.value=this.selectedProject,s.addEventListener("change",()=>{this.selectedProject=s.value,this.drawProjects(i,o)}),a.addEventListener("click",()=>void this.render());let i=n.createDiv({cls:"tasknotes-pm-gantt-chart"});this.drawProjects(i,o)}drawProjects(n,e){n.empty();let r=this.selectedProject==="all"?e:e.filter(l=>l.path===this.selectedProject);if(!r.length){n.createDiv({cls:"tasknotes-pm-gantt-empty",text:"No open projects with scheduled children."});return}let s=r.flatMap(l=>l.tasks),a=Math.min(...s.map(l=>l.startMs)),o=Math.max(...s.map(l=>l.endMs)),i=this.startOfWeek(a),c=Math.max(1,Math.ceil((o-i)/_)),d=c*_;n.style.setProperty("--tasknotes-pm-gantt-week-count",String(c)),n.style.setProperty("--tasknotes-pm-gantt-timeline-width",`${Math.max(500,c*ae)}px`),this.drawAxis(n,i,d,c);for(let l of r){let u=n.createDiv({cls:"tasknotes-pm-gantt-project"}),h=u.createDiv({cls:"tasknotes-pm-gantt-project-heading"});h.createSpan({cls:"tasknotes-pm-gantt-swatch"}).style.setProperty("--tasknotes-pm-project-color",l.color),this.createTaskLink(h,l.path,l.name,"tasknotes-pm-gantt-project-link");for(let m of l.tasks)this.drawTask(u,m,i,d)}}drawAxis(n,e,r,s){let a=n.createDiv({cls:"tasknotes-pm-gantt-axis"});a.createDiv({cls:"tasknotes-pm-gantt-axis-label",text:"Task"});let o=a.createDiv({cls:"tasknotes-pm-gantt-axis-ticks"});for(let i=0;i<=s;i++){let c=new Date(e+i*_),d=o.createDiv({cls:"tasknotes-pm-gantt-week-tick"});d.style.left=`${i/s*100}%`;let l=d.createSpan({text:c.toLocaleDateString(void 0,{month:"short",day:"numeric"})});i===s&&l.addClass("is-end")}}drawTask(n,e,r,s){let a=n.createDiv({cls:"tasknotes-pm-gantt-row"}),o=a.createDiv({cls:"tasknotes-pm-gantt-label"});o.style.paddingInlineStart=`${8+e.depth*14}px`,e.isProject&&o.addClass("is-project"),this.createTaskLink(o,e.path,e.name,"tasknotes-pm-gantt-task-link");let i=a.createDiv({cls:"tasknotes-pm-gantt-track"}),c=this.createTaskLink(i,e.path,"",`tasknotes-pm-gantt-bar${e.isProject?" is-project":""}`);c.style.left=`${Math.max(0,(e.startMs-r)/s*100)}%`,c.style.width=`${Math.max(.8,(e.endMs-e.startMs)/s*100)}%`,c.style.setProperty("--tasknotes-pm-project-color",e.color),c.setAttribute("aria-label",`${e.name}: ${this.dateText(e.startMs)} to ${this.dateText(e.endMs)}`),c.setAttribute("data-tooltip-position","top")}createTaskLink(n,e,r,s){let a=n.createEl("a",{cls:s,text:r,attr:{href:e,"data-href":e}});return a.addEventListener("click",o=>{o.preventDefault(),this.app.workspace.openLinkText(e,"",o.metaKey||o.ctrlKey)}),a}startOfWeek(n){let e=new Date(n);e.setHours(0,0,0,0);let r=(e.getDay()+6)%7;return e.setDate(e.getDate()-r),e.getTime()}dateText(n){return new Date(n).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}};var x=["#AF1C0D","#00B8A9","#FFCA3A","#7B61FF","#2DC653","#FF7A00","#1982C4","#F15BB5","#96AFC9","#A65F38"];function A(p){if(typeof p!="string")return null;let t=p.trim().toUpperCase();return/^#[0-9A-F]{6}$/.test(t)?t:null}function B(p){let t=[...p].map(s=>A(s)).filter(s=>s!==null),n=new Set(t),e=x.find(s=>!n.has(s));if(e)return e;let r=ie().filter(s=>!n.has(s));if(!r.length)throw new Error("No distinct project colors remain available");return r.reduce((s,a)=>{let o=K(a,t),i=K(s,t);return o>i||o===i&&a<s?a:s})}function J(p){let t=[];for(;t.length<p;)t.push(B(t));return t}function oe(p,t){let n=Y(p),e=Y(t);return Math.hypot(n.l-e.l,n.a-e.a,n.b-e.b)}function K(p,t){return t.length?Math.min(...t.map(n=>oe(p,n))):Number.POSITIVE_INFINITY}var H=null;function ie(){if(H)return H;let p=new Set,t=[.42,.5,.58,.66,.74,.82],n=[.04,.08,.12,.16,.2,.24];for(let e of t)for(let r of n)for(let s=0;s<360;s+=15){let a=le(e,r,s);a&&p.add(a)}for(let e of x)p.delete(e);return H=[...p].sort(),H}function Y(p){let t=A(p);if(!t)throw new Error(`Invalid project color: ${p}`);let n=W(Number.parseInt(t.slice(1,3),16)/255),e=W(Number.parseInt(t.slice(3,5),16)/255),r=W(Number.parseInt(t.slice(5,7),16)/255),s=Math.cbrt(.4122214708*n+.5363325363*e+.0514459929*r),a=Math.cbrt(.2119034982*n+.6806995451*e+.1073969566*r),o=Math.cbrt(.0883024619*n+.2817188376*e+.6299787005*r);return{l:.2104542553*s+.793617785*a-.0040720468*o,a:1.9779984951*s-2.428592205*a+.4505937099*o,b:.0259040371*s+.7827717662*a-.808675766*o}}function le(p,t,n){let e=n*Math.PI/180,r=t*Math.cos(e),s=t*Math.sin(e),a=p+.3963377774*r+.2158037573*s,o=p-.1055613458*r-.0638541728*s,i=p-.0894841775*r-1.291485548*s,c=a**3,d=o**3,l=i**3,u=[4.0767416621*c-3.3077115913*d+.2309699292*l,-1.2684380046*c+2.6097574011*d-.3413193965*l,-.0041960863*c-.7034186147*d+1.707614701*l];return u.some(h=>h<0||h>1)?null:`#${u.map(h=>Math.round(ce(h)*255).toString(16).padStart(2,"0")).join("")}`.toUpperCase()}function W(p){return p<=.04045?p/12.92:((p+.055)/1.055)**2.4}function ce(p){return p<=.0031308?12.92*p:1.055*p**(1/2.4)-.055}function Q(p){let{currentCompletionMs:t,desiredCompletionMs:n,activeChildCount:e,hasUnresolvedActiveChild:r}=p;return e>0&&!r&&n!==null?n:n===null?t:t===null?n:Math.max(t,n)}var M=require("obsidian"),q={durationProperty:"duration",completionProperty:"tasknotesPmCompletion",hardDeadlineProperty:"hardDeadline",projectColorProperty:"tasknotesPmProjectColor",projectColorSchemeVersion:0,defaultDurationHours:24,dependencyGapHours:24,projectBufferHours:24,hardDeadlineConflictPolicy:"ignore",updateOnStartup:!0,syncGoogleCalendarOnStartup:!0,syncGoogleCalendarOnUpdate:!0,highlightProjectCards:!0},F=class extends M.PluginSettingTab{constructor(n,e){super(n,e);this.plugin=e}display(){let{containerEl:n}=this;n.empty(),new M.Setting(n).setName("Project scheduling").setHeading().setDesc("Ordinary dependencies extend dates; project rollups and hard deadlines are exact. Precise timestamps are retained while TaskNotes displays a date."),this.addTextSetting(n,"Duration property","Frontmatter property measured in hours.","durationProperty"),this.addTextSetting(n,"Completion timestamp property","Plugin-owned ISO timestamp used to retain hour-level precision.","completionProperty"),this.addTextSetting(n,"Hard deadline property","A date in this frontmatter property schedules children backward from the parent deadline.","hardDeadlineProperty"),this.addTextSetting(n,"Project color property","A persisted hex color shared by each project and its direct children.","projectColorProperty"),this.addNumberSetting(n,"Default duration","Hours used when no valid duration exists.","defaultDurationHours"),this.addNumberSetting(n,"Dependency gap","Hours between a predecessor finishing and a successor starting.","dependencyGapHours"),new M.Setting(n).setName("Hard deadline conflict").setDesc("Choose what happens when backward scheduling would begin before today.").addDropdown(e=>e.addOption("ignore","Honor deadline and create overdue tasks").addOption("move-deadline","Move parent due date and deadline").setValue(this.plugin.settings.hardDeadlineConflictPolicy).onChange(async r=>{this.plugin.settings.hardDeadlineConflictPolicy=r,await this.plugin.saveSettings()})),new M.Setting(n).setName("Update project dates on startup").setDesc("Run the same project rollup and deadline update after TaskNotes is ready.").addToggle(e=>e.setValue(this.plugin.settings.updateOnStartup).onChange(async r=>{this.plugin.settings.updateOnStartup=r,await this.plugin.saveSettings()})),new M.Setting(n).setName("Sync Google Calendar on startup").setDesc("After TaskNotes is ready, run its built-in Sync all tasks action. TaskNotes decides which dated, open tasks are eligible for export.").addToggle(e=>e.setValue(this.plugin.settings.syncGoogleCalendarOnStartup).onChange(async r=>{this.plugin.settings.syncGoogleCalendarOnStartup=r,await this.plugin.saveSettings()})),new M.Setting(n).setName("Sync Google Calendar after project updates").setDesc("After the Update Project Dates command finishes, run TaskNotes' built-in Sync all tasks action.").addToggle(e=>e.setValue(this.plugin.settings.syncGoogleCalendarOnUpdate).onChange(async r=>{this.plugin.settings.syncGoogleCalendarOnUpdate=r,await this.plugin.saveSettings()})),new M.Setting(n).setName("Highlight project cards").setDesc("Use each project's persisted, high-contrast color for the project and its direct child cards in TaskNotes Kanban views.").addToggle(e=>e.setValue(this.plugin.settings.highlightProjectCards).onChange(async r=>{this.plugin.settings.highlightProjectCards=r,await this.plugin.saveSettings(),this.plugin.refreshProjectCardStyles()}))}addTextSetting(n,e,r,s){new M.Setting(n).setName(e).setDesc(r).addText(a=>a.setValue(this.plugin.settings[s]).onChange(async o=>{let i=o.trim();i&&(this.plugin.settings[s]=i,await this.plugin.saveSettings())}))}addNumberSetting(n,e,r,s){new M.Setting(n).setName(e).setDesc(r).addText(a=>a.setPlaceholder("24").setValue(String(this.plugin.settings[s])).onChange(async o=>{let i=Number(o);!Number.isFinite(i)||i<=0||(this.plugin.settings[s]=i,await this.plugin.saveSettings())}))}};var O=60*60*1e3,E=24*O,de="tasknotes-pm",R=2,L=class extends v.Plugin{settings=q;updateInProgress=!1;calendarSyncInProgress=!1;projectColors=new Map;cardObserver=null;async onload(){await this.loadSettings(),this.addSettingTab(new F(this.app,this)),this.addCommand({id:"update-project-dates",name:"Update Project Dates",callback:()=>void this.updateProjectDates(!1)}),this.addCommand({id:"sync-open-tasks-to-google-calendar",name:"Sync Open Tasks to Google Calendar",callback:()=>void this.syncOpenTasksToGoogleCalendar(!1,!0)}),this.registerView(N,t=>new $(t,this)),this.addCommand({id:"open-gantt-view",name:"Open Gantt View",callback:()=>void this.openGanttView()}),this.installKanbanObserver(),this.app.workspace.onLayoutReady(()=>{this.settings.updateOnStartup?this.updateProjectDates(!0):(this.hydrateProjectColorStyles(),this.settings.syncGoogleCalendarOnStartup&&this.syncOpenTasksToGoogleCalendar(!0,!1))})}onunload(){this.cardObserver?.disconnect(),this.app.workspace.detachLeavesOfType(N)}async loadSettings(){this.settings={...q,...this.validSettings(await this.loadData())}}async saveSettings(){await this.saveData(this.settings)}validSettings(t){if(!this.isRecord(t))return{};let n=k=>{let b=t[k];return typeof b=="number"&&Number.isFinite(b)&&b>0?b:void 0},e=k=>typeof t[k]=="boolean"?t[k]:void 0,r=k=>typeof t[k]=="string"&&t[k].trim()?t[k].trim():void 0,s={},a=r("durationProperty"),o=r("completionProperty"),i=r("hardDeadlineProperty"),c=r("projectColorProperty"),d=n("projectColorSchemeVersion"),l=n("defaultDurationHours"),u=n("dependencyGapHours"),h=n("projectBufferHours"),f=e("updateOnStartup"),m=e("syncGoogleCalendarOnStartup"),y=e("syncGoogleCalendarOnUpdate"),D=e("highlightProjectCards"),S=t.hardDeadlineConflictPolicy==="ignore"||t.hardDeadlineConflictPolicy==="move-deadline"?t.hardDeadlineConflictPolicy:void 0;return a!==void 0&&(s.durationProperty=a),o!==void 0&&(s.completionProperty=o),i!==void 0&&(s.hardDeadlineProperty=i),c!==void 0&&(s.projectColorProperty=c),d!==void 0&&(s.projectColorSchemeVersion=d),l!==void 0&&(s.defaultDurationHours=l),u!==void 0&&(s.dependencyGapHours=u),h!==void 0&&(s.projectBufferHours=h),f!==void 0&&(s.updateOnStartup=f),m!==void 0&&(s.syncGoogleCalendarOnStartup=m),y!==void 0&&(s.syncGoogleCalendarOnUpdate=y),D!==void 0&&(s.highlightProjectCards=D),S!==void 0&&(s.hardDeadlineConflictPolicy=S),s}isRecord(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async updateProjectDates(t){if(this.updateInProgress){t||new v.Notice("Tasknotes-PM: An update is already running.");return}let n=await this.getTaskNotesApi();if(!n){t||new v.Notice("Tasknotes-PM requires TaskNotes runtime API v1 with task and relationship access.");return}this.updateInProgress=!0;let e={scanned:0,openTasks:0,dependenciesAdded:0,datesChanged:0,defaultsAdded:0,colorsAssigned:0,colorsCleared:0,parentDurationsChanged:0,deadlinesMoved:0,deadlineWarnings:[],calendarSync:"not-run",invalidDurations:[],unscheduled:[],cycles:[],errors:[]};try{await n.lifecycle.ready();let s=await n.tasks.list();e.scanned=s.length;let a=this.completedStatuses(n);e.openTasks=this.openTasks(s,a).length;let o=await this.createTaskStates(s,e,a),i=await this.loadChildren(n,s,e);await this.writeDurationDefaults(o,e),await this.syncProjectColors(s,i,e),await this.ensureParentDependencies(n,i,e);let c=await this.loadDependencies(n,s,e);this.updateParentDurationsInMemory(o,i,this.recordedCompletions(o));let d=await this.scheduleHardDeadlines(o,i,e),l=this.calculateDates(o,i,c,d,e),u=this.updateParentDurationsInMemory(o,i,l);await this.writeParentDurations(u,e),await this.writeCalculatedDates(n,o,l,new Set(i.keys()),d,e),this.refreshProjectCardStyles();for(let f of this.app.workspace.getLeavesOfType(N)){let m=f.view;m instanceof $&&m.render()}let h=await this.runGoogleCalendarSync(s,a,t,!1);e.calendarSync=h.status,(h.status==="failed"||h.status==="unavailable")&&e.errors.push(h.detail??"Google Calendar sync was unavailable.")}catch(s){console.error("Tasknotes-PM update failed",s),e.errors.push(this.errorMessage(s))}finally{this.updateInProgress=!1}let r=[`${e.scanned} scanned`,`${e.openTasks} open`,`${e.dependenciesAdded} prerequisite${e.dependenciesAdded===1?"":"s"} added`,`${e.datesChanged} date${e.datesChanged===1?"":"s"} updated`,e.parentDurationsChanged?`${e.parentDurationsChanged} parent duration${e.parentDurationsChanged===1?"":"s"} updated`:"",e.deadlinesMoved?`${e.deadlinesMoved} deadline${e.deadlinesMoved===1?"":"s"} moved`:"",e.deadlineWarnings.length?`${e.deadlineWarnings.length} deadline warning${e.deadlineWarnings.length===1?"":"s"}`:"",e.colorsAssigned?`${e.colorsAssigned} color${e.colorsAssigned===1?"":"s"} assigned`:"",e.colorsCleared?`${e.colorsCleared} stale color${e.colorsCleared===1?"":"s"} cleared`:"",e.calendarSync==="synced"?"Google Calendar synced":"",e.calendarSync==="skipped"?"Google Calendar sync skipped":"",e.calendarSync==="unavailable"?"Google Calendar sync unavailable":"",e.unscheduled.length?`${e.unscheduled.length} unscheduled`:"",e.cycles.length?`${e.cycles.length} cycle${e.cycles.length===1?"":"s"}`:"",e.errors.length?`${e.errors.length} error${e.errors.length===1?"":"s"}`:""].filter(Boolean).join(" \xB7 ");new v.Notice(`Tasknotes-PM: ${r}`,7e3),e.deadlineWarnings.length&&(console.warn("Tasknotes-PM hard deadline warnings",e.deadlineWarnings),new v.Notice(`Tasknotes-PM: ${e.deadlineWarnings.join(" \xB7 ")}`,12e3))}async syncOpenTasksToGoogleCalendar(t,n){let e=await this.getTaskNotesApi();if(!e){t||new v.Notice("Tasknotes-PM requires TaskNotes before it can sync Google Calendar.");return}try{await e.lifecycle.ready();let r=await e.tasks.list(),s=await this.runGoogleCalendarSync(r,this.completedStatuses(e),t,n);(!t||s.status!=="synced")&&new v.Notice(this.calendarSyncNotice(s),7e3)}catch(r){console.error("Tasknotes-PM Google Calendar sync failed",r),t||new v.Notice(`Tasknotes-PM: Google Calendar sync failed (${this.errorMessage(r)}).`,7e3)}}async runGoogleCalendarSync(t,n,e,r){let s=this.openTasks(t,n),a=e?this.settings.syncGoogleCalendarOnStartup:this.settings.syncGoogleCalendarOnUpdate;if(!r&&!a)return{status:"skipped",openTasks:s.length};if(this.calendarSyncInProgress)return{status:"busy",openTasks:s.length};let o=this.taskNotesCalendarSyncCommand();if(!o)return{status:"unavailable",openTasks:s.length,detail:"TaskNotes' Sync all tasks command was not found. Update TaskNotes and enable Google Calendar task export in TaskNotes settings."};this.calendarSyncInProgress=!0;try{return await Promise.resolve(this.commandRegistry()?.executeCommandById(o.id))===!1?{status:"failed",openTasks:s.length,detail:"TaskNotes did not accept the Google Calendar sync command."}:{status:"synced",openTasks:s.length}}catch(i){return{status:"failed",openTasks:s.length,detail:this.errorMessage(i)}}finally{this.calendarSyncInProgress=!1}}commandRegistry(){return this.app.commands??null}taskNotesCalendarSyncCommand(){let t=this.commandRegistry()?.commands??{};return Object.values(t).find(n=>{if(!n.id.startsWith("tasknotes:"))return!1;let e=`${n.id} ${n.name}`.toLowerCase();return/sync.*all.*tasks|all.*tasks.*sync/.test(e)})??null}openTasks(t,n){return t.filter(e=>!e.archived&&!e.completed&&!n.has(e.status??""))}calendarSyncNotice(t){let n=`${t.openTasks} open task${t.openTasks===1?"":"s"}`;switch(t.status){case"synced":return`Tasknotes-PM: asked TaskNotes to sync ${n} with Google Calendar.`;case"skipped":return"Tasknotes-PM: Google Calendar sync is disabled in Tasknotes-PM settings.";case"busy":return"Tasknotes-PM: A Google Calendar sync is already running.";case"unavailable":return`Tasknotes-PM: ${t.detail}`;case"failed":return`Tasknotes-PM: Google Calendar sync failed (${t.detail}).`;default:return"Tasknotes-PM: Google Calendar sync did not run."}}refreshProjectCardStyles(){let t=document.querySelectorAll(".task-card");for(let n of t)this.styleProjectCard(n)}async hydrateProjectColorStyles(){let t=await this.getTaskNotesApi();if(!t){this.projectColors.clear(),this.refreshProjectCardStyles();return}try{await t.lifecycle.ready();let n=await t.tasks.list(),e={scanned:n.length,openTasks:0,dependenciesAdded:0,datesChanged:0,defaultsAdded:0,colorsAssigned:0,colorsCleared:0,parentDurationsChanged:0,deadlineWarnings:[],deadlinesMoved:0,calendarSync:"not-run",invalidDurations:[],unscheduled:[],cycles:[],errors:[]},r=await this.loadChildren(t,n,e),s=[...r.keys()],a=this.settings.projectColorSchemeVersion<R?this.rebalancedProjectColors(s):this.persistedProjectColors(s);this.projectColors=this.projectGroupColors(n,r,a)}catch(n){console.error("Tasknotes-PM project-color hydration failed",n),this.projectColors.clear()}this.refreshProjectCardStyles()}async openGanttView(){let t=this.app.workspace.getLeavesOfType(N)[0];t||(t=this.app.workspace.getLeaf("tab"),await t.setViewState({type:N,active:!0})),await this.app.workspace.revealLeaf(t)}async getGanttProjects(){let t=await this.getTaskNotesApi();if(!t)throw new Error("TaskNotes runtime API v1 is unavailable");await t.lifecycle.ready();let n=await t.tasks.list(),e={scanned:n.length,openTasks:0,dependenciesAdded:0,datesChanged:0,defaultsAdded:0,colorsAssigned:0,colorsCleared:0,parentDurationsChanged:0,deadlineWarnings:[],deadlinesMoved:0,calendarSync:"not-run",invalidDurations:[],unscheduled:[],cycles:[],errors:[]},r=await this.createTaskStates(n,e,this.completedStatuses(t)),s=await this.loadChildren(t,n,e);this.updateParentDurationsInMemory(r,s,this.recordedCompletions(r));let a=[];for(let[o]of s){let i=r.get(o);if(!i||i.isCompletedOrArchived)continue;let c=[];if(this.collectGanttTasks(o,o,0,r,s,c,new Set),c.length<2)continue;let d=this.projectColorFor(o);a.push({path:o,name:this.taskName(o),color:d,tasks:c})}return a.sort((o,i)=>o.name.localeCompare(i.name))}describeError(t){return this.errorMessage(t)}collectGanttTasks(t,n,e,r,s,a,o){if(o.has(t))return;o.add(t);let i=r.get(t);if(!i||i.completionMs===null)return;let c=s.get(t)??new Set,d=[...c].map(m=>{let y=r.get(m);return y?.completionMs===null||!y?null:{start:y.completionMs-y.durationHours*O,end:y.completionMs}}).filter(m=>m!==null),l=c.size>0,u=l&&d.length?Math.min(...d.map(m=>m.start)):i.completionMs-i.durationHours*O,h=l&&d.length?Math.max(i.completionMs,...d.map(m=>m.end)):i.completionMs;a.push({path:t,name:this.taskName(t),startMs:u,endMs:h,color:this.projectColorFor(t,n),isProject:l,depth:e});let f=[...c].sort((m,y)=>{let D=r.get(m)?.completionMs??Number.POSITIVE_INFINITY,S=r.get(y)?.completionMs??Number.POSITIVE_INFINITY;return D-S||m.localeCompare(y)});for(let m of f)this.collectGanttTasks(m,n,e+1,r,s,a,o)}projectColorFor(t,n=t){return this.projectColors.get(t)??A(this.frontmatterFor(t)[this.settings.projectColorProperty])??this.projectColors.get(n)??A(this.frontmatterFor(n)[this.settings.projectColorProperty])??x[this.projectHash(n)%x.length]}taskName(t){return t.split("/").pop()?.replace(/\.md$/i,"")??t}async getTaskNotesApi(){let e=this.app.plugins.getPlugin("tasknotes")?.api;return!e||e.apiVersion!==1?null:["tasks.read","tasks.write","relationships.read"].every(s=>e.hasCapability(s))?e:null}async createTaskStates(t,n,e){let r=new Map;for(let s of t){let a=this.frontmatterFor(s.path),o=a[this.settings.durationProperty],i=this.readDuration(o);i.invalid&&n.invalidDurations.push(s.path);let c=a[this.settings.hardDeadlineProperty],d=this.parseCompletion(c);c!=null&&c!==""&&d===null&&n.errors.push(`${s.path}: invalid ${this.settings.hardDeadlineProperty} date`);let l=this.parseCompletion(a[this.settings.completionProperty]),u=this.parseCompletion(s.due),h=l!==null&&this.calendarDate(s.due)===this.formatDueDate(l);r.set(s.path,{durationHours:i.value,completionMs:h?l:u,hardDeadlineMs:d,isCompletedOrArchived:!!(s.archived||s.completed||e.has(s.status??""))})}return r}async loadChildren(t,n,e){let r=new Map;for(let s of n)try{let a=await t.relationships.subtasks(s.path);a.length&&r.set(s.path,new Set(a.map(o=>o.path)))}catch(a){e.errors.push(`${s.path}: unable to read subtasks (${this.errorMessage(a)})`)}return r}async loadDependencies(t,n,e){let r=new Map;for(let s of n)try{r.set(s.path,await t.relationships.dependencies(s.path))}catch(a){e.errors.push(`${s.path}: unable to read dependencies (${this.errorMessage(a)})`)}for(let s of n)try{let a=await t.relationships.blocking(s.path);for(let o of a){let i=r.get(o.path)??[];i.some(c=>c.path===s.path)||i.push({dependency:{uid:`[[${s.path.replace(/\.md$/i,"")}]]`,reltype:"FINISHTOSTART"},task:s,path:s.path}),r.set(o.path,i)}}catch(a){e.errors.push(`${s.path}: unable to read blocking tasks (${this.errorMessage(a)})`)}return r}async writeDurationDefaults(t,n){for(let[e]of t){let r=this.frontmatterFor(e),s=r[this.settings.durationProperty]===void 0||r[this.settings.durationProperty]===null||r[this.settings.durationProperty]==="";if(s)try{await this.app.fileManager.processFrontMatter(this.fileFor(e),a=>{let o=a;s&&(o[this.settings.durationProperty]=this.settings.defaultDurationHours)}),s&&n.defaultsAdded++}catch(a){n.errors.push(`${e}: unable to update project metadata (${this.errorMessage(a)})`)}}}async syncProjectColors(t,n,e){let r=[...n.keys()],s=this.settings.projectColorSchemeVersion<R?this.rebalancedProjectColors(r):this.persistedProjectColors(r),a=this.projectGroupColors(t,n,s);this.projectColors=a;for(let[o,i]of a)if(A(this.frontmatterFor(o)[this.settings.projectColorProperty])!==i)try{await this.app.fileManager.processFrontMatter(this.fileFor(o),d=>{let l=d;l[this.settings.projectColorProperty]=i}),e.colorsAssigned++}catch(d){e.errors.push(`${o}: unable to save project color (${this.errorMessage(d)})`)}for(let o of t){if(a.has(o.path))continue;let i=this.frontmatterFor(o.path)[this.settings.projectColorProperty];if(!(i==null||i===""))try{await this.app.fileManager.processFrontMatter(this.fileFor(o.path),c=>{let d=c;delete d[this.settings.projectColorProperty]}),e.colorsCleared++}catch(c){e.errors.push(`${o.path}: unable to clear stale project color (${this.errorMessage(c)})`)}}this.settings.projectColorSchemeVersion<R&&(this.settings.projectColorSchemeVersion=R,await this.saveSettings())}projectGroupColors(t,n,e){let r=new Map;for(let[a,o]of n)for(let i of o){let c=r.get(i)??[];c.push(a),r.set(i,c)}let s=new Map;for(let a of t){if(n.has(a.path)){let c=e.get(a.path);c!==void 0&&s.set(a.path,c);continue}let o=r.get(a.path)?.sort((c,d)=>c.localeCompare(d))[0],i=o?e.get(o):void 0;i!==void 0&&s.set(a.path,i)}return s}async ensureParentDependencies(t,n,e){let r=this.context("Synchronize subtask prerequisites");for(let[s,a]of n){let o;try{o=await t.relationships.dependencies(s)}catch(c){e.errors.push(`${s}: unable to inspect prerequisites (${this.errorMessage(c)})`);continue}let i=new Set(o.map(c=>c.path).filter(c=>!!c));for(let c of a)if(!i.has(c))try{await t.tasks.addDependency(s,{uid:`[[${c.replace(/\.md$/i,"")}]]`,reltype:"FINISHTOSTART"},r),e.dependenciesAdded++}catch(d){e.errors.push(`${s}: unable to add ${c} as prerequisite (${this.errorMessage(d)})`)}}}recordedCompletions(t){let n=new Map;for(let[e,r]of t)r.completionMs!==null&&n.set(e,r.completionMs);return n}updateParentDurationsInMemory(t,n,e){let r=new Map,s=new Set,a=o=>{if(r.has(o))return r.get(o)??null;if(s.has(o))return null;s.add(o);let i=[...n.get(o)??[]],c=[];for(let u of i){n.has(u)&&a(u);let h=t.get(u),f=e.get(u);!h||f===void 0||!Number.isFinite(f)||c.push({start:f-h.durationHours*O,end:f})}if(s.delete(o),!i.length||c.length!==i.length)return null;let d=(Math.max(...c.map(u=>u.end))-Math.min(...c.map(u=>u.start)))/O;if(!Number.isFinite(d)||d<=0)return null;r.set(o,d);let l=t.get(o);return l&&(l.durationHours=d),d};for(let o of n.keys())a(o);return r}async writeParentDurations(t,n){for(let[e,r]of t){let s=this.readDuration(this.frontmatterFor(e)[this.settings.durationProperty]);if(!(!s.invalid&&Math.abs(s.value-r)<.001))try{await this.app.fileManager.processFrontMatter(this.fileFor(e),a=>{let o=a;o[this.settings.durationProperty]=Number(r.toFixed(2))}),n.parentDurationsChanged++}catch(a){n.errors.push(`${e}: unable to update parent duration (${this.errorMessage(a)})`)}}}async scheduleHardDeadlines(t,n,e){let r=new Map,s=new Map,a=new Map,o=new Set,i=new Date;i.setHours(0,0,0,0);let c=(l,u,h,f=!1)=>{let m=s.get(l);if(m!==void 0&&m<=u||o.has(l))return;let y=[...n.get(l)??[]].filter(g=>t.get(g)?.isCompletedOrArchived!==!0);if(!y.length){s.set(l,u);return}o.add(l);let D=y.sort((g,P)=>{let j=r.get(g)??t.get(g)?.completionMs??Number.POSITIVE_INFINITY,T=r.get(P)??t.get(P)?.completionMs??Number.POSITIVE_INFINITY;return j-T||g.localeCompare(P)}),S=u,k=S-E,b=new Map;for(let g=D.length-1;g>=0;g--){let P=D[g];b.set(P,k),k-=(t.get(P)?.durationHours??this.settings.defaultDurationHours)*O}let C=h&&k<i.getTime(),w=!1;if(C)if(this.settings.hardDeadlineConflictPolicy==="move-deadline"){let g=Math.ceil((i.getTime()-k)/E),P=g*E;S+=P;for(let[T,I]of b)b.set(T,I+P);let j=t.get(l);j&&(j.hardDeadlineMs=S),a.set(l,S),w=!0,e.deadlinesMoved++,e.deadlineWarnings.push(`${this.taskName(l)} moved ${g} day${g===1?"":"s"} so work can begin today.`)}else e.deadlineWarnings.push(`${this.taskName(l)} begins before today; the deadline was honored and overdue tasks were allowed.`);s.set(l,S);for(let g of D){let P=b.get(g),j=t.get(g),T=r.get(g)??j?.completionMs,I=f||w;if(j?.isCompletedOrArchived){T==null?e.deadlineWarnings.push(`${this.taskName(g)} is completed without a due date and was not changed by ${this.taskName(l)}'s hard deadline.`):T>P&&e.deadlineWarnings.push(`${this.taskName(g)} is already completed after ${this.taskName(l)}'s allowable child date and was not changed.`);continue}if(I||T===null||T===void 0||T>P){let z=r.get(g);r.set(g,z===void 0?P:Math.min(z,P))}let V=r.get(g)??T;V!=null&&n.has(g)&&c(g,V,!1,I)}o.delete(l)},d=[...n.keys()].filter(l=>t.get(l)?.hardDeadlineMs!=null).sort((l,u)=>l.localeCompare(u));for(let l of d)c(l,t.get(l)?.hardDeadlineMs,!0);for(let[l,u]of a)try{await this.app.fileManager.processFrontMatter(this.fileFor(l),h=>{let f=h;f[this.settings.hardDeadlineProperty]=this.formatDueDate(u)})}catch(h){e.errors.push(`${l}: unable to move hard deadline (${this.errorMessage(h)})`)}return{forcedCompletions:r,parentDeadlines:s}}calculateDates(t,n,e,r,s){let a=new Map,o=new Set,i=new Set,c=[],d=l=>{let u=t.get(l);if(!u)return null;if(a.has(l)){let C=a.get(l);return C!==void 0&&Number.isFinite(C)?C:null}if(o.has(l)){let C=c.indexOf(l),w=[...c.slice(C),l];return w.forEach(g=>i.add(g)),s.cycles.push(w),null}o.add(l),c.push(l);let h=[],f=n.get(l)??new Set,m=new Set,y=!1;for(let C of f){let w=t.get(C);if(!w){y=!0;continue}if(w.isCompletedOrArchived)continue;m.add(C);let g=d(C);g!==null?h.push(g+E):y=!0}for(let C of e.get(l)??[]){if(!C.path||f.has(C.path)||C.dependency.reltype&&C.dependency.reltype!=="FINISHTOSTART")continue;let w=d(C.path);w!==null&&h.push(w+(this.settings.dependencyGapHours+u.durationHours)*O)}if(c.pop(),o.delete(l),i.has(l))return null;let D=h.length?Math.max(...h):null,S=r.parentDeadlines.get(l),k=r.forcedCompletions.get(l),b;return S!==void 0?b=S:k!==void 0?b=k:b=Q({currentCompletionMs:u.completionMs,desiredCompletionMs:D,activeChildCount:m.size,hasUnresolvedActiveChild:y}),a.set(l,b??NaN),(b===null&&(m.size||(e.get(l)?.length??0)>0)||y)&&(s.unscheduled.includes(l)||s.unscheduled.push(l)),b};for(let l of t.keys())d(l);for(let l of i)a.delete(l);return a}async writeCalculatedDates(t,n,e,r,s,a){let o=this.context("Update project dates");for(let[i,c]of e){let d=n.get(i);if(!d||d.isCompletedOrArchived||!Number.isFinite(c))continue;let l=r.has(i)||s.forcedCompletions.has(i)||s.parentDeadlines.has(i);if(!(d.completionMs!==null&&(l&&Math.abs(c-d.completionMs)<1e3||!l&&c<=d.completionMs)))try{await t.tasks.setDue(i,this.formatDueDate(c),o),await this.app.fileManager.processFrontMatter(this.fileFor(i),u=>{let h=u;h[this.settings.completionProperty]=new Date(c).toISOString()}),a.datesChanged++,d.completionMs=c}catch(u){a.errors.push(`${i}: unable to set due date (${this.errorMessage(u)})`)}}}frontmatterFor(t){return this.app.metadataCache.getFileCache(this.fileFor(t))?.frontmatter??{}}fileFor(t){let n=this.app.vault.getAbstractFileByPath((0,v.normalizePath)(t));if(!(n instanceof v.TFile))throw new Error("Task file is no longer available");return n}readDuration(t){if(t==null||t==="")return{value:this.settings.defaultDurationHours,invalid:!1};let n=typeof t=="number"?t:Number(t);return Number.isFinite(n)&&n>0?{value:n,invalid:!1}:{value:this.settings.defaultDurationHours,invalid:!0}}projectHash(t){let n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)>>>0;return n}rebalancedProjectColors(t){let n=[...t].sort((r,s)=>this.projectHash(r)-this.projectHash(s)||r.localeCompare(s)),e=J(n.length);return new Map(n.map((r,s)=>[r,e[s]]))}persistedProjectColors(t){let n=new Map,e=new Set,r=[...t].sort((s,a)=>this.projectHash(s)-this.projectHash(a)||s.localeCompare(a));for(let s of r){let a=A(this.frontmatterFor(s)[this.settings.projectColorProperty]);a===null||e.has(a)||(n.set(s,a),e.add(a))}for(let s of r.filter(a=>!n.has(a))){let a=B(e);n.set(s,a),e.add(a)}return n}parseCompletion(t){if(typeof t!="string"||!t.trim())return null;let r=(/^\d{4}-\d{2}-\d{2}$/.test(t)?new Date(`${t}T23:59:59.999`):new Date(t)).getTime();return Number.isFinite(r)?r:null}formatDueDate(t){let n=new Date(t),e=n.getFullYear(),r=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0");return`${e}-${r}-${s}`}calendarDate(t){return t?t.match(/^\d{4}-\d{2}-\d{2}/)?.[0]??null:null}context(t){return{source:de,correlationId:crypto.randomUUID(),reason:t}}completedStatuses(t){let n=t.catalog?.statuses()??[];return new Set(n.filter(e=>e.isCompleted===!0||e.completed===!0).map(e=>e.value??e.id??e.name).filter(e=>!!e))}installKanbanObserver(){this.cardObserver=new MutationObserver(t=>{if(this.settings.highlightProjectCards)for(let n of t)n.addedNodes.forEach(e=>{e.instanceOf(HTMLElement)&&(e.matches(".task-card")&&this.styleProjectCard(e),e.querySelectorAll?.(".task-card").forEach(r=>this.styleProjectCard(r)))})}),this.cardObserver.observe(document.body,{childList:!0,subtree:!0})}styleProjectCard(t){if(!this.settings.highlightProjectCards||!this.isInsideKanban(t)){t.removeClass("tasknotes-pm-project-card"),t.style.removeProperty("--tasknotes-pm-project-color");return}let n=this.pathForCard(t),e=n?this.projectColors.get(n):void 0;t.toggleClass("tasknotes-pm-project-card",e!==void 0),e===void 0?t.style.removeProperty("--tasknotes-pm-project-color"):t.style.setProperty("--tasknotes-pm-project-color",e)}isInsideKanban(t){for(let n=t;n;n=n.parentElement)if(typeof n.className=="string"&&/kanban/i.test(n.className)||n.getAttribute("data-view-type")==="tasknotesKanban")return!0;return!1}pathForCard(t){let n=t.getAttribute("data-task-path")??t.getAttribute("data-path")??t.getAttribute("data-file-path");if(n)return n;let e=t.textContent?.match(/file\s*name:\s*(.+?\.md)(?:\s|$)/i)?.[1];if(e)return this.app.metadataCache.getFirstLinkpathDest(e,"")?.path??null;let r=t.querySelector("[data-href], a.internal-link"),s=r?.getAttribute("data-href")??r?.getAttribute("href");return s?this.app.metadataCache.getFirstLinkpathDest(s,"")?.path??null:null}errorMessage(t){return t instanceof Error?t.message:String(t)}};