Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
executable file
·19 lines (18 loc) · 26.9 KB
/
Copy pathmain.js
File metadata and controls
executable file
·19 lines (18 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"use strict";var U=Object.create;var w=Object.defineProperty;var B=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var G=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var H=(p,e)=>{for(var t in e)w(p,t,{get:e[t],enumerable:!0})},R=(p,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!X.call(p,n)&&n!==t&&w(p,n,{get:()=>e[n],enumerable:!(i=B(e,n))||i.enumerable});return p};var Y=(p,e,t)=>(t=p!=null?U(G(p)):{},R(e||!p||!p.__esModule?w(t,"default",{value:p,enumerable:!0}):t,p)),J=p=>R(w({},"__esModule",{value:!0}),p);var ce={};H(ce,{default:()=>I});module.exports=J(ce);var k=require("obsidian");var T=class extends Error{constructor(t,i,n){super(n);this.status=t;this.apiError=i;this.name="VikunjaRequestError"}},v=class{baseUrl;token;constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.token=t}url(e){return`${this.baseUrl}/api/v1${e}`}get headers(){return{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"}}async request(e,t={}){let i=new AbortController,n=window.setTimeout(()=>i.abort(),2e4),s;try{s=await fetch(this.url(e),{...t,signal:i.signal,headers:{...this.headers,...t.headers??{}}})}catch(a){throw a.name==="AbortError"?new T(0,null,`Request timed out: ${e}`):a}finally{window.clearTimeout(n)}if(!s.ok){let a=null;try{a=await s.json()}catch{}throw new T(s.status,a,a?.message??`HTTP ${s.status} on ${e}`)}return s.status===204?{}:s.json()}async testConnection(){try{return await this.request("/user"),{success:!0}}catch(e){return e instanceof T?{success:!1,error:e.message}:{success:!1,error:String(e)}}}async getProjects(){return this.request("/projects?per_page=500")}async getProject(e){return this.request(`/projects/${e}`)}async getProjectTasks(e){let t=[],i=1;for(;;){let n=await this.request(`/projects/${e}/tasks?per_page=50&page=${i}`);if(t.push(...n),n.length<50)break;i++}return t}async getAllTasks(){let e=await this.getProjects(),t=[];for(let i of e)if(!i.is_archived)try{let n=await this.getProjectTasks(i.id);t.push(...n)}catch(n){console.warn(`Failed to fetch tasks for project ${i.id}:`,n)}return t}async getTask(e){return this.request(`/tasks/${e}`)}async createTask(e,t){return this.request(`/projects/${e}/tasks`,{method:"PUT",body:JSON.stringify(t)})}async updateTask(e,t){return this.request(`/tasks/${e}`,{method:"POST",body:JSON.stringify(t)})}async setTaskDone(e,t){return this.updateTask(e,{done:t})}async deleteTask(e){await this.request(`/tasks/${e}`,{method:"DELETE"})}async getLabels(){return this.request("/labels?per_page=500")}async createLabel(e){return this.request("/labels",{method:"PUT",body:JSON.stringify(e)})}async addLabelToTask(e,t,i){await this.request(`/projects/${e}/tasks/${t}/labels`,{method:"PUT",body:JSON.stringify({label_id:i})})}async removeLabelFromTask(e,t,i){await this.request(`/projects/${e}/tasks/${t}/labels/${i}`,{method:"DELETE"})}};var D={apiUrl:"",apiToken:"",syncIntervalSeconds:300,syncOnSave:!0,defaultProjectId:null,showRibbonIcon:!0,syncCompletedTasks:!0,excludedFolders:[],autoCreateProjectFiles:!1,projectsFolder:"Vikunja"},b="0001-01-01T00:00:00Z",C={"\u{1F53A}":5,"\u23EB":4,"\u{1F53C}":3,"\u{1F53D}":2,"\u23EC":1},L={5:"\u{1F53A}",4:"\u23EB",3:"\u{1F53C}",2:"\u{1F53D}",1:"\u23EC"};var $=/^(\s*)[-*]\s+\[([x ])\]\s+(.+)$/i,x=/#([\w-]+)/g,K=/%%vikunja:(\d+)%%|<!--vikunja:(\d+)-->/,W=/📅\s*(\d{4}-\d{2}-\d{2})/,z=/🛫\s*(\d{4}-\d{2}-\d{2})/,Z=/⏳\s*(\d{4}-\d{2}-\d{2})/,Q=/🔁\s*([^🔺⏫🔼🔽⏬📅🛫⏳➕✅❌🆔⛔🏁@<]+)/,F=/@project:([^@<📅🛫⏳🔺⏫🔼🔽⏬➕✅❌🆔⛔🏁%]+)/,ee=Object.keys(C),te=/[📅🛫⏳]\s*\d{4}-\d{2}-\d{2}/gu,ne=/🔁\s*[^🔺⏫🔼🔽⏬📅🛫⏳➕✅❌🆔⛔🏁@<]*/gu,ie=/➕\s*\d{4}-\d{2}-\d{2}/gu,se=/✅\s*\d{4}-\d{2}-\d{2}/gu,ae=/❌\s*\d{4}-\d{2}-\d{2}/gu,re=/🆔\s*\S*/gu,oe=/⛔\s*\S*/gu,le=/🏁\s*\S*/gu,m=class p{static parseFile(e,t){return e.split(`
`).map((i,n)=>p.parseLine(i,n,t)).filter(i=>i!==null)}static parseLine(e,t,i){let n=e.match($);if(!n)return null;let[,,s,a]=n,r=s.toLowerCase()==="x",o=a.match(K),l=o?parseInt(o[1]??o[2],10):null,c=a.match(W),g=a.match(z),h=a.match(Z),d=0;for(let[V,M]of Object.entries(C))if(a.includes(V)){d=M;break}let u=a.match(Q),y=u?u[1].trim():null,j=a.match(F),N=j?j[1].trim():null,_=Array.from(a.matchAll(x)).map(V=>V[1]),O=p.cleanTitle(a);return{rawLine:e,lineNumber:t,filePath:i,title:O,done:r,dueDate:c?c[1]:null,startDate:g?g[1]:null,scheduledDate:h?h[1]:null,priority:d,recurrence:y,vikunjaId:l,projectId:null,projectName:N,labels:[],tagNames:_.length>0?_:void 0}}static cleanTitle(e){let t=e;t=t.replace(/%%vikunja:\d+%%/g,""),t=t.replace(/<!--vikunja:\d+-->/g,""),t=t.replace(te,""),t=t.replace(ne,""),t=t.replace(F,"");for(let i of ee)t=t.replaceAll(i,"");return t=t.replace(x,""),t=t.replace(ie,""),t=t.replace(se,""),t=t.replace(ae,""),t=t.replace(re,""),t=t.replace(oe,""),t=t.replace(le,""),t.trim().replace(/\s+/g," ")}static serialise(e){let t=e.rawLine.match(/^(\s*)/),i=t?t[1]:"",n=e.done?"x":" ",s=`${i}- [${n}] ${e.title}`;if(e.projectName&&(s+=` @project:${e.projectName}`),e.recurrence&&(s+=` \u{1F501} ${e.recurrence}`),e.priority>0&&L[e.priority]&&(s+=` ${L[e.priority]}`),e.startDate&&(s+=` \u{1F6EB} ${e.startDate}`),e.scheduledDate&&(s+=` \u23F3 ${e.scheduledDate}`),e.dueDate&&(s+=` \u{1F4C5} ${e.dueDate}`),e.labels&&e.labels.length>0){let a=e.labels.map(r=>`#${p.sanitizeTagToSlug(r.title)}`).join(" ");s+=` ${a}`}return e.vikunjaId!==null&&(s+=` %%vikunja:${e.vikunjaId}%%`),s}static replaceLine(e,t,i){let n=e.split(`
`);return n[t]=i,n.join(`
`)}static isTaskLine(e){return $.test(e)}static parseRepeatAfter(e){if(!e)return;let t=e.toLowerCase().trim(),n=86400*1,s=7*n,a=30*n,r=365*n;if(t==="every day"||t==="daily")return n;if(t==="every week"||t==="weekly")return s;if(t==="every month"||t==="monthly")return a;if(t==="every year"||t==="yearly")return r;if(t==="every other day")return 2*n;let o=t.match(/^every (\d+) (day|week|month|year)s?$/);if(o)return parseInt(o[1],10)*{day:n,week:s,month:a,year:r}[o[2]]}static formatRepeatAfter(e){if(!e||e<=0)return null;let t=86400,i=7*t,n=30*t,s=365*t;if(e%s===0)return e===s?"every year":`every ${e/s} years`;if(e%n===0)return e===n?"every month":`every ${e/n} months`;if(e%i===0)return e===i?"every week":`every ${e/i} weeks`;if(e%t===0)return e===t?"every day":`every ${e/t} days`;let a=Math.round(e/t);return a===1?"every day":`every ${a} days`}static sanitizeTagToSlug(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w-]/g,"")}static slugToLabel(e){return e.split("-").map(t=>t.length>0?t.charAt(0).toUpperCase()+t.slice(1):"").join(" ").trim()}static generateRandomColor(){let e=["#FF6B6B","#4ECDC4","#45B7D1","#FFA07A","#98D8C8","#F7DC6F","#BB8FCE","#85C1E2","#F8B88B","#ABEBC6"];return e[Math.floor(Math.random()*e.length)]}};var P=class p{app;client;settings;lastSyncTime=null;cachedProjects=null;cachedLabels=null;constructor(e,t,i){this.app=e,this.client=t,this.settings=i}async sync(){let e={created:0,updated:0,completed:0,errors:[],timestamp:new Date};this.cachedProjects=null,this.cachedLabels=null;try{let t=await this.ensureProjectFiles(),{tasks:i,fileProjectMap:n}=await this.scanVault();for(let[s,a]of t)n.has(s)||n.set(s,a);await this.pullRemoteChanges(i,n,e),await this.pushNewTasks(i,e),await this.pushTaskUpdates(i,e)}catch(t){e.errors.push(String(t))}return this.lastSyncTime=new Date,e}async syncFile(e){let t={created:0,updated:0,completed:0,errors:[],timestamp:new Date};if(this.isExcluded(e.path))return t;this.cachedProjects=null;try{let i=await this.app.vault.read(e),n=m.parseFile(i,e.path),s=await this.getExplicitProjectId(e),a=s??this.settings.defaultProjectId;for(let r of n)r.projectId=a;if(await this.pushNewTasks(n,t),await this.pushTaskUpdates(n,t),s!==null){let r=new Map([[e.path,s]]);await this.pullRemoteChanges(n,r,t)}}catch(i){t.errors.push(`Error syncing ${e.path}: ${String(i)}`)}return t}async handleCheckboxToggle(e,t,i){let n=await this.app.vault.read(e),a=n.split(`
`)[t];if(!m.isTaskLine(a))return;let r=m.parseLine(a,t,e.path);if(!r)return;r.done=i,r.vikunjaId!==null&&await this.client.setTaskDone(r.vikunjaId,i);let o=m.replaceLine(n,t,m.serialise(r));await this.app.vault.modify(e,o)}async ensureProjectFiles(){let e=new Map;if(!this.settings.autoCreateProjectFiles)return e;let t=this.settings.projectsFolder.trim().replace(/\/+$/,"");if(!t)return e;if(!this.app.vault.getAbstractFileByPath(t))try{await this.app.vault.createFolder(t)}catch{}let i=await this.getCachedProjects();for(let n of i){if(n.is_archived)continue;let s=n.title.replace(/[\\/:*?"<>|#^[\]]/g,"-").trim();if(!s)continue;let a=`${t}/${s}.md`;if(this.app.vault.getAbstractFileByPath(a))continue;let r=`---
vikunja_project_id: ${n.id}
---
`;try{await this.app.vault.create(a,r),e.set(a,n.id),console.log(`[Vikunja] Created project file: ${a}`)}catch(o){console.error(`[Vikunja] Failed to create project file ${a}:`,o)}}return e}async scanVault(){let e=[],t=new Map,i=this.app.vault.getMarkdownFiles();for(let n of i)if(!this.isExcluded(n.path))try{let s=await this.app.vault.read(n),a=m.parseFile(s,n.path),r=await this.getExplicitProjectId(n),o=r??this.settings.defaultProjectId;for(let l of a)l.projectId=o;r!==null&&t.set(n.path,r),e.push(...a)}catch(s){console.error(`[Vikunja] Error scanning ${n.path}:`,s)}return{tasks:e,fileProjectMap:t}}async pushNewTasks(e,t){let i=e.filter(n=>n.vikunjaId===null);for(let n of i){let s=n.projectId??this.settings.defaultProjectId;if(n.projectName){let r=(await this.getCachedProjects()).find(o=>o.title.toLowerCase().trim()===n.projectName.toLowerCase().trim());if(r)s=r.id;else{t.errors.push(`Unknown project "@project:${n.projectName}" on task "${n.title}" in ${n.filePath}. Check the name matches a project in Vikunja exactly.`);continue}}if(!s){t.errors.push(`Skipped "${n.title}" in ${n.filePath} \u2014 no project assigned. Add vikunja_project_id to the note's frontmatter, use @project:Name on the task line, or set a Default Project in plugin settings.`);continue}try{let a=await this.client.createTask(s,{title:n.title,done:n.done,due_date:n.dueDate?new Date(n.dueDate).toISOString():void 0,start_date:n.startDate?new Date(n.startDate).toISOString():void 0,priority:n.priority>0?n.priority:void 0,repeat_after:m.parseRepeatAfter(n.recurrence)});if(n.vikunjaId=a.id,await this.writeTaskToFile(n),n.tagNames&&n.tagNames.length>0)try{let r=await this.resolveOrCreateLabels(n.tagNames);for(let o of r)await this.client.addLabelToTask(s,a.id,o.id);n.labels=r,await this.writeTaskToFile(n)}catch(r){t.errors.push(`Failed to sync labels for "${n.title}": ${String(r)}`)}t.created++}catch(a){t.errors.push(`Failed to create task "${n.title}": ${String(a)}`)}}}async pushTaskUpdates(e,t){let i=e.filter(s=>s.vikunjaId!==null);if(i.length===0)return;let n=new Map;try{let s=await this.client.getAllTasks();n=new Map(s.map(a=>[a.id,a]))}catch(s){t.errors.push(`Could not fetch remote tasks for update comparison: ${String(s)}`);return}for(let s of i){let a=n.get(s.vikunjaId);if(!a)continue;if(s.title.includes("\uFFFD")){console.warn(`[Vikunja] Skipping update for task ${s.vikunjaId}: title contains corruption (replacement characters). Title: "${s.title}". This task may need manual repair.`),t.errors.push(`Skipped corrupted task ${s.vikunjaId}: title contains replacement characters. Please check this task in both Obsidian and Vikunja.`);continue}let r=m.parseRepeatAfter(s.recurrence)??0,o=s.dueDate?new Date(s.dueDate).toISOString():null,l=s.startDate?new Date(s.startDate).toISOString():null,c=s.tagNames&&s.tagNames.length>0?await this.resolveOrCreateLabels(s.tagNames):[];if(!(s.title===a.title&&s.done===a.done&&s.priority===a.priority&&r===(a.repeat_after??0)&&(o??b)===(a.due_date??b)&&(l??b)===(a.start_date??b)&&this.labelArraysEqual(c,a.labels||[]))){try{let h=this.app.vault.getAbstractFileByPath(s.filePath);if(h&&"stat"in h&&"mtime"in h.stat){let d=new Date(h.stat.mtime),u=new Date(a.updated);if(u>d){console.log(`[Vikunja] Skipping push for task ${s.vikunjaId}: remote updated (${u.toISOString()}) is newer than local file modified (${d.toISOString()})`);continue}}}catch{}try{await this.client.updateTask(s.vikunjaId,{title:s.title,done:s.done,due_date:o??void 0,start_date:l??void 0,priority:s.priority>0?s.priority:void 0,repeat_after:r||void 0});let h=a.labels||[];if(!this.labelArraysEqual(c,h))try{for(let d of h)c.find(u=>u.id===d.id)||await this.client.removeLabelFromTask(s.projectId,s.vikunjaId,d.id);for(let d of c)h.find(u=>u.id===d.id)||await this.client.addLabelToTask(s.projectId,s.vikunjaId,d.id)}catch(d){t.errors.push(`Failed to sync labels for task "${s.title}": ${String(d)}`)}t.updated++}catch(h){t.errors.push(`Failed to update task "${s.title}": ${String(h)}`)}}}}async pullRemoteChanges(e,t,i){let n=new Map(e.filter(l=>l.vikunjaId!==null).map(l=>[l.vikunjaId,l])),s=new Set,a=new Map;for(let[l,c]of t){let g=a.get(c)??[];g.push(l),a.set(c,g)}for(let[l,c]of a){let g=[];try{g=await this.client.getProjectTasks(l)}catch(d){i.errors.push(`Failed to fetch tasks for project ${l}: ${String(d)}`);continue}let h=[];for(let d of g){s.add(d.id);let u=n.get(d.id);if(u){let y=!1;d.done!==u.done&&(u.done=d.done,y=!0,i.completed++),d.title!==u.title&&(u.title=d.title,y=!0,i.updated++);let j=d.labels||[];(j.length!==u.labels.length||!this.labelArraysEqual(j,u.labels))&&(u.labels=j,y=!0),y&&await this.writeTaskToFile(u)}else(!d.done||this.settings.syncCompletedTasks)&&h.push(d)}h.length>0&&await this.appendTasksToFile(c[0],h,i)}if(e.filter(l=>l.vikunjaId!==null&&!s.has(l.vikunjaId)).length===0)return;let o=[];try{o=await this.client.getAllTasks()}catch(l){i.errors.push(`Failed to fetch remote tasks: ${String(l)}`);return}for(let l of o){if(s.has(l.id))continue;let c=n.get(l.id);if(!c)continue;let g=!1;l.done!==c.done&&(c.done=l.done,g=!0,i.completed++),l.title!==c.title&&(c.title=l.title,g=!0,i.updated++);let h=l.labels||[];(h.length!==c.labels.length||!this.labelArraysEqual(h,c.labels))&&(c.labels=h,g=!0),g&&await this.writeTaskToFile(c)}}async deleteOrphanedTasks(e,t){if(!this.settings.autoCreateProjectFiles)return;let i=this.settings.projectsFolder.trim().replace(/\/+$/,"");if(!i)return;let n=await this.getCachedProjects();for(let s of n){if(s.is_archived)continue;let a=s.title.replace(/[\\/:*?"<>|#^[\]]/g,"-").trim();if(!a)continue;let r=`${i}/${a}.md`,o=this.app.vault.getAbstractFileByPath(r);if(!(!o||!("extension"in o)))try{let l=await this.app.vault.read(o),c=m.parseFile(l,r),g=new Set(c.filter(u=>u.vikunjaId!==null).map(u=>u.vikunjaId));if(c.length===0){console.log(`[Vikunja] Skipping orphan check for ${r} (file is empty, likely not yet populated)`);continue}let h=await this.client.getProjectTasks(s.id),d=h.filter(u=>!g.has(u.id)).length;if(d>h.length*.5){console.warn(`[Vikunja] Skipping deletion for ${s.title}: ${d} orphaned tasks (>50%), likely a sync issue`),t.errors.push(`Skipped deletion for project "${s.title}": too many orphaned tasks (${d}/${h.length}). Please check your sync state.`);continue}for(let u of h)if(!g.has(u.id))try{await this.client.deleteTask(u.id),t.deleted=(t.deleted??0)+1,console.log(`[Vikunja] Deleted orphaned task ${u.id} (was removed from Obsidian)`)}catch(y){console.error(`[Vikunja] Failed to delete orphaned task ${u.id}:`,y)}}catch(l){console.error(`[Vikunja] Failed to check orphaned tasks in project ${s.id}:`,l)}}}async writeTaskToFile(e){let t=this.app.vault.getAbstractFileByPath(e.filePath);if(!t||!("extension"in t))throw new Error(`File not found: ${e.filePath}`);let i=await this.app.vault.read(t),n=m.serialise(e),s=m.replaceLine(i,e.lineNumber,n);await this.app.vault.modify(t,s)}async appendTasksToFile(e,t,i){let n=this.app.vault.getAbstractFileByPath(e);if(!n||!("extension"in n))return;let s=await this.app.vault.read(n),a=t.map(o=>{let l={rawLine:"",lineNumber:-1,filePath:e,title:o.title,done:o.done,dueDate:p.formatDate(o.due_date),startDate:p.formatDate(o.start_date),scheduledDate:null,priority:o.priority,recurrence:m.formatRepeatAfter(o.repeat_after),vikunjaId:o.id,projectId:o.project_id,projectName:null,labels:o.labels||[]};return m.serialise(l)}),r=s.trimEnd()+`
`+a.join(`
`)+`
`;await this.app.vault.modify(n,r),i.created+=t.length}async getCachedProjects(){return this.cachedProjects||(this.cachedProjects=await this.client.getProjects()),this.cachedProjects}async getCachedLabels(){return this.cachedLabels||(this.cachedLabels=await this.client.getLabels()),this.cachedLabels}async getExplicitProjectId(e){let t=this.app.metadataCache.getFileCache(e)?.frontmatter;if(t?.vikunja_project_id)return Number(t.vikunja_project_id);if(t?.vikunja_project){let i=String(t.vikunja_project).toLowerCase().trim(),s=(await this.getCachedProjects()).find(a=>a.title.toLowerCase().trim()===i);if(s)return s.id;console.warn(`[Vikunja] No project found with name "${t.vikunja_project}" in ${e.path}`)}return null}async resolveProjectId(e){return await this.getExplicitProjectId(e)??this.settings.defaultProjectId}isExcluded(e){return this.settings.excludedFolders.some(t=>e.startsWith(t.trim()+"/"))}async resolveOrCreateLabels(e){if(!e||e.length===0)return[];let t=await this.getCachedLabels(),i=[];for(let n of e){let s=t.find(a=>a.title.toLowerCase()===n.toLowerCase());if(s)i.push(s);else{let a=await this.client.createLabel({title:m.slugToLabel(n),hex_color:m.generateRandomColor(),description:""});i.push(a),this.cachedLabels.push(a)}}return i}labelArraysEqual(e,t){if(e.length!==t.length)return!1;let i=e.map(s=>s.id).sort((s,a)=>s-a),n=t.map(s=>s.id).sort((s,a)=>s-a);return i.every((s,a)=>s===n[a])}static formatDate(e){return!e||e===b?null:e.split("T")[0]}};var f=require("obsidian"),E=class extends f.PluginSettingTab{plugin;constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"Vikunja Connection"}),new f.Setting(e).setName("Vikunja URL").setDesc("Base URL of your Vikunja instance, e.g. https://vikunja.example.com").addText(i=>i.setPlaceholder("https://vikunja.example.com").setValue(this.plugin.settings.apiUrl).onChange(async n=>{this.plugin.settings.apiUrl=n.trim().replace(/\/$/,""),await this.plugin.saveSettings()})),new f.Setting(e).setName("API Token").setDesc("Personal access token from Vikunja \u2192 Account Settings \u2192 API Tokens. Generate a token with full access.").addText(i=>{i.setPlaceholder("Paste your token here").setValue(this.plugin.settings.apiToken).onChange(async n=>{this.plugin.settings.apiToken=n.trim(),await this.plugin.saveSettings()}),i.inputEl.type="password"}),new f.Setting(e).setName("Test Connection").setDesc("Verify your URL and token are correct.").addButton(i=>i.setButtonText("Test").setCta().onClick(async()=>{i.setButtonText("Testing\u2026"),i.setDisabled(!0);let n=await this.plugin.testConnection();n.success?(new f.Notice("\u2705 Connected to Vikunja successfully!"),this.display()):(new f.Notice(`\u274C Connection failed: ${n.error}`),i.setButtonText("Test"),i.setDisabled(!1))})),e.createEl("h2",{text:"Default Project"}),new f.Setting(e).setName("Default Project").setDesc("Tasks created in notes without a vikunja_project_id frontmatter property will be added to this project.").addDropdown(async i=>{i.addOption("","\u2014 Select a project \u2014");try{let n=await this.plugin.client?.getProjects()??[];for(let s of n)i.addOption(String(s.id),s.title)}catch{i.addOption("","Could not load projects \u2014 check connection")}i.setValue(String(this.plugin.settings.defaultProjectId??"")).onChange(async n=>{this.plugin.settings.defaultProjectId=n?parseInt(n,10):null,await this.plugin.saveSettings()})}),e.createEl("h2",{text:"Project Files"}),new f.Setting(e).setName("Auto-create project files").setDesc("Automatically create one markdown file per Vikunja project in the folder below. Each file is pre-configured with the correct project ID and acts as the task list for that project. Files are only created \u2014 never deleted or renamed \u2014 so renaming a project in Vikunja won't affect existing files.").addToggle(i=>i.setValue(this.plugin.settings.autoCreateProjectFiles).onChange(async n=>{this.plugin.settings.autoCreateProjectFiles=n,await this.plugin.saveSettings(),t.settingEl.toggle(n)}));let t=new f.Setting(e).setName("Projects folder").setDesc("Vault-relative folder where project files are created. The folder is created automatically if it doesn't exist. Example: Vikunja, Tasks/Projects").addText(i=>i.setPlaceholder("Vikunja").setValue(this.plugin.settings.projectsFolder).onChange(async n=>{this.plugin.settings.projectsFolder=n.trim().replace(/\/+$/,""),await this.plugin.saveSettings()}));t.settingEl.toggle(this.plugin.settings.autoCreateProjectFiles),e.createEl("h2",{text:"Sync Behaviour"}),new f.Setting(e).setName("Sync on save").setDesc("Automatically sync tasks when you save a markdown file.").addToggle(i=>i.setValue(this.plugin.settings.syncOnSave).onChange(async n=>{this.plugin.settings.syncOnSave=n,await this.plugin.saveSettings()})),new f.Setting(e).setName("Sync interval (seconds)").setDesc("How often to poll Vikunja for remote changes. Set to 0 to disable polling (sync on save only).").addSlider(i=>i.setLimits(0,3600,30).setValue(this.plugin.settings.syncIntervalSeconds).setDynamicTooltip().onChange(async n=>{this.plugin.settings.syncIntervalSeconds=n,await this.plugin.saveSettings(),this.plugin.restartSyncInterval()})),new f.Setting(e).setName("Sync completed tasks").setDesc("Pull tasks completed remotely (e.g. by collaborators) back to Obsidian and mark them as [x].").addToggle(i=>i.setValue(this.plugin.settings.syncCompletedTasks).onChange(async n=>{this.plugin.settings.syncCompletedTasks=n,await this.plugin.saveSettings()})),e.createEl("h2",{text:"Exclusions"}),new f.Setting(e).setName("Excluded folders").setDesc("Folders to exclude from task scanning, one per line. Tasks in these folders will not be synced to Vikunja. Example: Templates, Archive").addTextArea(i=>i.setPlaceholder(`Templates
Archive
.trash`).setValue(this.plugin.settings.excludedFolders.join(`
`)).onChange(async n=>{this.plugin.settings.excludedFolders=n.split(`
`).map(s=>s.trim()).filter(Boolean),await this.plugin.saveSettings()})),e.createEl("h2",{text:"Interface"}),new f.Setting(e).setName("Show ribbon icon").setDesc("Show the Vikunja sync button in the left sidebar ribbon.").addToggle(i=>i.setValue(this.plugin.settings.showRibbonIcon).onChange(async n=>{this.plugin.settings.showRibbonIcon=n,await this.plugin.saveSettings(),new f.Notice("Reload Obsidian to apply ribbon changes.")}))}};var A=require("obsidian"),S=class extends A.EditorSuggest{getLabels;constructor(e,t){super(e),this.getLabels=t}onTrigger(e,t,i){let n=t.getLine(e.line);if(!n.match(/^\s*[-*]\s+\[.\]\s+/))return null;let s=n.substring(0,e.ch),a=s.lastIndexOf("#");if(a===-1||a>0&&!/\s/.test(n[a-1]))return null;let r=a+1,o=s.substring(r).trim();return s.substring(r).includes(" ")&&o.length>0?null:{start:{line:e.line,ch:r},end:e,query:o.toLowerCase()}}getSuggestions(e){let t=this.getLabels(),i=e.query.toLowerCase();return t.filter(n=>n.title.toLowerCase().startsWith(i)||n.title.toLowerCase().includes(i)).slice(0,10).map(n=>({label:n,displayText:this.labelToTag(n.title)}))}renderSuggestion(e,t){t.createEl("div",{text:`#${e.displayText}`,cls:"vikunja-label-suggest"})}selectSuggestion(e,t){let i=this.context?.editor;if(!i||!this.context)return;let n=this.context.start,s=this.context.end,a=this.labelToTag(e.label.title);i.replaceRange(a,n,s);let r={line:n.line,ch:n.ch+a.length};i.setCursor(r)}labelToTag(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^\w-]/g,"")}};var I=class extends k.Plugin{settings;client=null;syncEngine=null;syncIntervalHandle=null;isSyncing=!1;cachedLabels=[];async onload(){console.log("[Vikunja] Plugin loading\u2026"),await this.loadSettings(),this.initClient(),this.addSettingTab(new E(this.app,this)),this.settings.showRibbonIcon&&this.addRibbonIcon("refresh-cw","Sync Vikunja tasks",async()=>{await this.runFullSync()}),this.addCommand({id:"sync-all",name:"Sync all tasks with Vikunja",callback:async()=>{await this.runFullSync()}}),this.addCommand({id:"sync-current-file",name:"Sync current file with Vikunja",editorCallback:async(e,t)=>{t.file&&await this.syncFile(t.file)}}),this.registerEvent(this.app.vault.on("modify",async e=>{this.settings.syncOnSave&&this.syncEngine&&e instanceof k.TFile&&e.extension==="md"&&await this.syncFile(e)})),this.registerDomEvent(document,"click",async e=>{await this.handleEditorClick(e)}),this.registerEditorSuggest(new S(this.app,()=>this.cachedLabels)),this.startSyncInterval(),console.log("[Vikunja] Plugin loaded.")}onunload(){this.stopSyncInterval(),console.log("[Vikunja] Plugin unloaded.")}async loadSettings(){this.settings=Object.assign({},D,await this.loadData())}async saveSettings(){await this.saveData(this.settings),this.initClient()}initClient(){if(!this.settings.apiUrl||!this.settings.apiToken){this.client=null,this.syncEngine=null;return}this.client=new v(this.settings.apiUrl,this.settings.apiToken),this.syncEngine=new P(this.app,this.client,this.settings)}async testConnection(){return this.client?this.client.testConnection():{success:!1,error:"No URL or token configured."}}async runFullSync(){if(!this.syncEngine){new k.Notice("\u26A0\uFE0F Vikunja: Please configure your API URL and token in settings.");return}if(this.isSyncing){new k.Notice("\u23F3 Vikunja: Sync already in progress.");return}this.isSyncing=!0;let e=new k.Notice("\u{1F504} Vikunja: Syncing\u2026",0);try{let t=await this.syncEngine.sync();try{this.client&&(this.cachedLabels=await this.client.getLabels())}catch(n){console.warn("[Vikunja] Failed to fetch labels for autocomplete:",n)}e.hide();let i=[t.created>0?`${t.created} created`:null,t.updated>0?`${t.updated} updated`:null,t.completed>0?`${t.completed} completed`:null,t.deleted&&t.deleted>0?`${t.deleted} deleted`:null].filter(Boolean).join(", ");t.errors.length>0?new k.Notice(`\u26A0\uFE0F Vikunja sync finished with errors:
${t.errors.join(`
`)}`,8e3):i?new k.Notice(`\u2705 Vikunja: ${i}`):new k.Notice("\u2705 Vikunja: Everything up to date.")}catch(t){e.hide(),new k.Notice(`\u274C Vikunja sync failed: ${String(t)}`,8e3)}finally{this.isSyncing=!1}}async syncFile(e){if(this.syncEngine)try{let t=await this.syncEngine.syncFile(e);t.errors.length>0&&console.error("[Vikunja] Sync errors:",t.errors);try{this.client&&(this.cachedLabels=await this.client.getLabels())}catch(i){console.warn("[Vikunja] Failed to fetch labels for autocomplete:",i)}}catch(t){console.error("[Vikunja] File sync error:",t)}}startSyncInterval(){this.stopSyncInterval(),!(this.settings.syncIntervalSeconds<=0)&&(this.syncIntervalHandle=window.setInterval(async()=>{this.syncEngine&&await this.runFullSync()},this.settings.syncIntervalSeconds*1e3))}stopSyncInterval(){this.syncIntervalHandle!==null&&(window.clearInterval(this.syncIntervalHandle),this.syncIntervalHandle=null)}restartSyncInterval(){this.startSyncInterval()}async handleEditorClick(e){let t=e.target;if(t.tagName!=="INPUT"||t.type!=="checkbox"||!t.closest("li.task-list-item")||!this.syncEngine)return;let i=this.app.workspace.getActiveViewOfType((await import("obsidian")).MarkdownView);if(!i?.file)return;let n=t.closest("li");if(!n)return;let a=(await this.app.vault.read(i.file)).split(`
`),r=t.checked,o=n.textContent?.trim()??"",l=a.findIndex(c=>{if(!c.includes("[")||!c.includes("]"))return!1;let g=c.replace(/^[\s\-*]+\[[x ]\]\s*/i,"").trim();return o.startsWith(g.slice(0,30))});l!==-1&&await this.syncEngine.handleCheckboxToggle(i.file,l,r)}};