Files
2026-07-23 14:20:36 -04:00

29 lines
86 KiB
JavaScript

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";var ne=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var bt=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var wt=(o,r)=>{for(var e in r)ne(o,e,{get:r[e],enumerable:!0})},yt=(o,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of bt(r))!vt.call(o,s)&&s!==e&&ne(o,s,{get:()=>r[s],enumerable:!(t=ft(r,s))||t.enumerable});return o};var Ct=o=>yt(ne({},"__esModule",{value:!0}),o);var kt={};wt(kt,{COMMENTS_MAX_PREVIEW:()=>Ie,CoalescingCache:()=>$,DEFAULT_ACCENT_COLOR:()=>Be,DEFAULT_SETTINGS:()=>H,GRAPH_DIRECTIONS:()=>ot,IssueCache:()=>X,MAX_BACKOFF_MS:()=>Fe,MIN_REFRESH_SECONDS:()=>Y,SEARCH_DEFAULT_LIMIT:()=>W,SEARCH_LAYOUTS:()=>Ze,SEARCH_MAX_LIMIT:()=>T,assignGraphLayers:()=>pt,attachmentMarkdown:()=>$e,buildGraphBlock:()=>Me,buildGraphQuerySource:()=>ut,buildInlineChipReference:()=>Ye,buildIssueCardBlock:()=>Je,buildIssueUrl:()=>j,buildMilestoneUrl:()=>oe,buildMultipart:()=>qe,buildRepoUrl:()=>ie,buildSearchBlock:()=>Pe,buildSearchQuerySource:()=>st,default:()=>Z,defaultImageName:()=>Te,escapeRegExp:()=>te,formatRelativeTime:()=>de,graphNodeId:()=>le,graphQueryKey:()=>ct,graphSubtitle:()=>Pt,graphTitle:()=>dt,initialsFromLogin:()=>ue,insertAtCursor:()=>je,insertGraphBlock:()=>ht,insertIssueCard:()=>Ae,insertIssueReference:()=>Re,insertSearchBlock:()=>nt,isCloudflareBaseUrl:()=>Ke,isImageAsset:()=>Se,labelTextColor:()=>K,milestoneProgressPercent:()=>at,milestoneQueryKey:()=>rt,parseBlockedByLabel:()=>he,parseGraphQuery:()=>lt,parseIssueBlock:()=>Qe,parseIssueRef:()=>Ve,parseIssueUrl:()=>We,parseMilestoneQuery:()=>it,parseSearchQuery:()=>et,resolveImageSrc:()=>re,searchQueryKey:()=>tt,splitRepo:()=>A,stripMarkdown:()=>gt,truncate:()=>ce});module.exports=Ct(kt);var d=require("obsidian"),Ne=require("@codemirror/language"),He=require("@codemirror/state"),F=require("@codemirror/view"),Y=30,Fe=30*60*1e3,_t=0,N={pat:"gitea-cards-gitea-pat",cfClientId:"gitea-cards-cf-access-client-id",cfClientSecret:"gitea-cards-cf-access-client-secret"},Be="#4c8dff",H={baseUrl:"",keyword:"GITEA",refreshIntervalSeconds:60,truncationLength:160,commentPreviewCount:3,showCommentImages:!1,showAttachments:!1,defaultRepo:"",lastRepo:"",insertFormat:"card",repoAccents:{},inProgressLabel:"",secrets:{}},L=class extends Error{constructor(r){super(r),this.name="GiteaRequestError"}},$=class{constructor(r,e){this.keyOf=r;this.fetcher=e;this.entries=new Map}ensure(r){let e=this.entries.get(r);return e||(e={value:null,fetchedAt:0,inFlight:null,failureCount:0,nextRetryAt:0,lastError:null},this.entries.set(r,e)),e}invalidate(r){this.entries.delete(this.keyOf(r))}async load(r,e){let t=this.ensure(this.keyOf(r)),s=Date.now(),n=Math.max(0,e*.8);return t.value!==null&&s-t.fetchedAt<n?{value:t.value,stale:!1,error:null}:s<t.nextRetryAt?t.value!==null?{value:t.value,stale:!0,error:t.lastError}:{value:null,stale:!1,error:t.lastError}:(t.inFlight||(t.inFlight=this.runFetch(r,t,e)),t.inFlight)}async runFetch(r,e,t){try{let s=await this.fetcher(r);return e.value=s,e.fetchedAt=Date.now(),e.failureCount=0,e.nextRetryAt=0,e.lastError=null,{value:s,stale:!1,error:null}}catch(s){let n=s instanceof Error?s:new Error("Failed to load.");e.failureCount+=1,e.lastError=n;let i=Math.min(Fe,t*Math.pow(2,e.failureCount-1));return e.nextRetryAt=Date.now()+i,e.value!==null?{value:e.value,stale:!0,error:n}:{value:null,stale:!1,error:n}}finally{e.inFlight=null}}},X=class extends ${constructor(r){super(e=>`${e.owner}/${e.repo}#${e.index}`,r)}};function z(o){if(!o.isConnected)return!1;let r=o;return typeof r.isShown=="function"?r.isShown():o.offsetParent!==null}var xt=/^([^/\s]+)\/([^#\s]+)#(\d+)$/;function Ve(o){let r=xt.exec(o.trim());return r?{owner:r[1],repo:r[2],index:Number.parseInt(r[3],10)}:null}var Ie=20;function Qe(o){let r=null,e=null;for(let t of o.split(/\r?\n/)){let s=t.trim();if(s.length===0)continue;let n=Ve(s);if(n){r=n;continue}let i=s.indexOf(":");if(i===-1)return{block:null,error:`Expected owner/repo#index or "key: value"; got "${s}".`};let a=s.slice(0,i).trim().toLowerCase(),l=s.slice(i+1).trim();switch(a){case"comments":{let c=Number.parseInt(l,10);e=Number.isFinite(c)&&c>0?Math.min(c,Ie):0;break}default:return{block:null,error:`Unknown field "${a}".`}}}return r?{block:{ref:r,comments:e},error:null}:{block:null,error:"Expected a single reference in owner/repo#index form."}}function j(o,r){return`${o.replace(/\/+$/,"")}/${r.owner}/${r.repo}/issues/${r.index}`}function ie(o,r,e){return`${o.replace(/\/+$/,"")}/${r}/${e}`}var Et=/\/attachments\/[^/]+/i;function re(o,r){let e=r.trim();if(!e||/^(data|blob):/i.test(e))return{url:e,authed:!1};let t;try{t=new URL(o)}catch(n){return{url:e,authed:!1}}let s=null;try{s=new URL(e)}catch(n){s=null}if(!s)try{let n=o.replace(/\/+$/,"")+"/";return{url:new URL(e,n).href,authed:!0}}catch(n){return{url:e,authed:!1}}if(s.host.toLowerCase()===t.host.toLowerCase())return{url:s.href,authed:!0};if(Et.test(s.pathname)){let n=new URL(t.origin);return n.pathname=s.pathname,n.search=s.search,{url:n.href,authed:!0}}return{url:e,authed:!1}}var It=/\.(png|jpe?g|gif|webp|svg|bmp|avif|ico|tiff?)$/i;function Se(o){return It.test(o.trim())}function $e(o){let r=o.name.replace(/[\r\n\]]/g," ").trim()||"attachment",e=`/attachments/${o.uuid}`;return Se(o.name)?`![${r}](${e})`:`[${r}](${e})`}function Te(o){var e,t;return`pasted-image.${((t=(e=o.split("/")[1])==null?void 0:e.split(";")[0])==null?void 0:t.trim())||"png"}`}function je(o,r){var c,u;let e=(c=o.selectionStart)!=null?c:o.value.length,t=(u=o.selectionEnd)!=null?u:o.value.length,s=o.value.slice(0,e),n=o.value.slice(t),a=`${s&&!s.endsWith(`
`)?`
`:""}${r}
`;o.value=`${s}${a}${n}`;let l=s.length+a.length;o.setSelectionRange(l,l)}var St=0;function qe(o,r,e,t){let s=`----GiteaCards${(St++).toString(36)}${Date.now().toString(36)}`,n=r.replace(/[\r\n"]/g,"_"),i=new TextEncoder,a=i.encode(`--${s}\r
Content-Disposition: form-data; name="${o}"; filename="${n}"\r
Content-Type: ${e}\r
\r
`),l=i.encode(`\r
--${s}--\r
`),c=new Uint8Array(t),u=new Uint8Array(a.length+c.length+l.length);return u.set(a,0),u.set(c,a.length),u.set(l,a.length+c.length),{body:u.buffer,contentType:`multipart/form-data; boundary=${s}`}}var $t=/^\/([^/\s]+)\/([^/\s]+)\/issues\/(\d+)\/?$/;function We(o,r){let e,t;try{e=new URL(r.trim()),t=new URL(o)}catch(i){return null}if(e.host.toLowerCase()!==t.host.toLowerCase())return null;let s=t.pathname.replace(/\/+$/,"");if(s&&!e.pathname.startsWith(`${s}/`))return null;let n=$t.exec(e.pathname.slice(s.length));return n?{owner:n[1],repo:n[2],index:Number.parseInt(n[3],10)}:null}function Tt(o){return new RegExp(`^${te(o)}:([^\\s:/]+)/([^\\s:/]+):#(\\d+)$`)}function Lt(o){return new RegExp("`"+te(o)+":([^\\s:/`]+)/([^\\s:/`]+):#(\\d+)`","g")}function ze(o,r,e){let t=createEl("a",{cls:"gitea-chip",href:j(o,r)});return t.setAttr("target","_blank"),t.setAttr("rel","noopener"),t.setAttr("aria-label",`${r.owner}/${r.repo}#${r.index}`),e&&(t.addClass("gitea-chip--accented"),t.style.setProperty("--gitea-accent",e)),t.createSpan({cls:"gitea-chip__dot"}),t.createSpan({cls:"gitea-chip__number",text:`#${r.index}`}),t.createSpan({cls:"gitea-chip__title"}),t.createSpan({cls:"gitea-chip__state"}),t}function ae(o,r){let e=r.trim().toLowerCase();return e?o.labels.some(t=>t.name.trim().toLowerCase()===e):!1}function Le(o,r,e){var c;o.setAttr("aria-label",`#${r.number} \u2014 ${r.title}`);let t=r.state==="closed",s=!t&&ae(r,e);o.toggleClass("gitea-chip--closed",t);let n=t?"closed":s?"in-progress":"open",i=s?"in progress":n,a=o.querySelector(".gitea-chip__dot");a&&(a.removeClass("gitea-chip__dot--open","gitea-chip__dot--closed","gitea-chip__dot--in-progress"),a.addClass(`gitea-chip__dot--${n}`)),(c=o.querySelector(".gitea-chip__title"))==null||c.setText(r.title);let l=o.querySelector(".gitea-chip__state");l&&(l.removeClass("gitea-chip__state--open","gitea-chip__state--closed","gitea-chip__state--in-progress"),l.addClass(`gitea-chip__state--${n}`),l.setText(i))}function At(o){let r=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(o);if(!r)return!1;let e=Number.parseInt(r[1],10),t=Number.parseInt(r[2],10);return e===0||e===10||e===127||e===192&&t===168||e===172&&t>=16&&t<=31||e===169&&t===254||e===100&&t>=64&&t<=127}function Ke(o){let r;try{r=new URL(o).hostname.toLowerCase()}catch(e){return!1}return r=r.replace(/^\[/,"").replace(/\]$/,""),!(r.length===0||r==="localhost"||r.endsWith(".localhost")||/\.(local|lan|internal|home|ts\.net)$/.test(r)||At(r)||r==="::1"||/^f[cd]/.test(r)||r.startsWith("fe80:"))}function J(o,r){var s,n;let e=(s=o.headers)!=null?s:{},t=r.toLowerCase();for(let i of Object.keys(e))if(i.toLowerCase()===t)return(n=e[i])!=null?n:"";return""}function te(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Rt=/^([^/\s]+)\/([^/\s]+)$/;function A(o){let r=Rt.exec(o.trim());return r?{owner:r[1],repo:r[2]}:null}function Je(o){return["```gitea-issue",`${o.owner}/${o.repo}#${o.index}`,"```",""].join(`
`)}function Ye(o,r){return`\`${o}:${r.owner}/${r.repo}:#${r.index}\``}function Ae(o,r){let e=o.getCursor("from"),s=o.getLine(e.line).slice(0,e.ch).trim().length>0?`
`:"";o.replaceSelection(s+Je(r))}function Re(o,r,e,t){e!=="none"&&(e==="inline"?o.replaceSelection(Ye(t,r)):Ae(o,r))}var W=10,T=50,Xe=["open","closed","all"],Ze=["table","cards"];function D(o){return o.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function et(o){let r={repo:null,state:"open",labels:[],milestones:[],q:null,limit:W,layout:"table"};for(let e of o.split(/\r?\n/)){let t=e.trim();if(t.length===0)continue;let s=t.indexOf(":");if(s===-1)return{query:null,error:`Expected "key: value" lines; got "${t}".`};let n=t.slice(0,s).trim().toLowerCase(),i=t.slice(s+1).trim();switch(n){case"repo":r.repo=i.length>0?i:null;break;case"state":{let a=i.toLowerCase();if(!Xe.includes(a))return{query:null,error:`Unknown state "${i}" \u2014 use open, closed, or all.`};r.state=a;break}case"label":case"labels":r.labels=D(i);break;case"milestone":case"milestones":r.milestones=D(i);break;case"q":case"query":r.q=i.length>0?i:null;break;case"limit":{let a=Number.parseInt(i,10);Number.isFinite(a)&&a>0&&(r.limit=Math.min(a,T));break}case"layout":case"view":{let a=i.toLowerCase(),l=a==="card"?"cards":a;if(!Ze.includes(l))return{query:null,error:`Unknown layout "${i}" \u2014 use table or cards.`};r.layout=l;break}default:return{query:null,error:`Unknown field "${n}".`}}}return r.repo&&!/^[^/\s]+\/[^/\s]+$/.test(r.repo)?{query:null,error:`Invalid repo "${r.repo}" \u2014 use owner/repo.`}:{query:r,error:null}}function tt(o){return JSON.stringify({repo:o.repo,state:o.state,labels:[...o.labels].sort(),milestones:[...o.milestones].sort(),q:o.q,limit:o.limit})}function st(o){let r=[];return o.repo&&r.push(`repo: ${o.repo}`),o.state!=="open"&&r.push(`state: ${o.state}`),o.labels.length>0&&r.push(`labels: ${o.labels.join(", ")}`),o.milestones.length>0&&r.push(`milestones: ${o.milestones.join(", ")}`),o.q&&r.push(`query: ${o.q}`),o.limit!==W&&r.push(`limit: ${o.limit}`),o.layout!=="table"&&r.push(`layout: ${o.layout}`),r.join(`
`)}function Pe(o){let r=st(o);return"```gitea-search"+(r.length>0?`
${r}`:"")+"\n```\n"}function nt(o,r){let e=o.getCursor("from"),s=o.getLine(e.line).slice(0,e.ch).trim().length>0?`
`:"";o.replaceSelection(s+Pe(r))}function it(o){let r="",e="";for(let t of o.split(/\r?\n/)){let s=t.trim();if(s.length===0)continue;let n=s.indexOf(":");if(n===-1)return{query:null,error:`Expected "key: value" lines; got "${s}".`};let i=s.slice(0,n).trim().toLowerCase(),a=s.slice(n+1).trim();switch(i){case"repo":r=a;break;case"milestone":e=a;break;default:return{query:null,error:`Unknown field "${i}".`}}}return r?/^[^/\s]+\/[^/\s]+$/.test(r)?e?{query:{repo:r,milestone:e},error:null}:{query:null,error:"Missing milestone \u2014 add a milestone: name line."}:{query:null,error:`Invalid repo "${r}" \u2014 use owner/repo.`}:{query:null,error:"Missing repo \u2014 add a repo: owner/repo line."}}function rt(o){return`${o.repo}!milestone:${o.milestone}`}function at(o,r){let e=o+r;return e<=0?0:Math.round(r/e*100)}function oe(o,r,e){return`${o.replace(/\/+$/,"")}/${r}/milestone/${e}`}var ot=["TB","LR"];function le(o){return`${o.owner}/${o.repo}#${o.index}`}function lt(o){let r={repo:null,state:"all",labels:[],milestones:[],q:null,limit:T,direction:"TB"};for(let e of o.split(/\r?\n/)){let t=e.trim();if(t.length===0)continue;let s=t.indexOf(":");if(s===-1)return{query:null,error:`Expected "key: value" lines; got "${t}".`};let n=t.slice(0,s).trim().toLowerCase(),i=t.slice(s+1).trim();switch(n){case"repo":r.repo=i.length>0?i:null;break;case"state":{let a=i.toLowerCase();if(!Xe.includes(a))return{query:null,error:`Unknown state "${i}" \u2014 use open, closed, or all.`};r.state=a;break}case"label":case"labels":r.labels=D(i);break;case"milestone":case"milestones":r.milestones=D(i);break;case"q":case"query":r.q=i.length>0?i:null;break;case"limit":{let a=Number.parseInt(i,10);Number.isFinite(a)&&a>0&&(r.limit=Math.min(a,T));break}case"direction":case"dir":{let a=i.toUpperCase()==="TD"?"TB":i.toUpperCase();if(!ot.includes(a))return{query:null,error:`Unknown direction "${i}" \u2014 use TB or LR.`};r.direction=a;break}default:return{query:null,error:`Unknown field "${n}".`}}}return r.repo&&!/^[^/\s]+\/[^/\s]+$/.test(r.repo)?{query:null,error:`Invalid repo "${r.repo}" \u2014 use owner/repo.`}:{query:r,error:null}}function ct(o){return"graph!"+JSON.stringify({repo:o.repo,state:o.state,labels:[...o.labels].sort(),milestones:[...o.milestones].sort(),q:o.q,limit:o.limit})}function dt(o,r){var t;let e=(t=o.repo)!=null?t:r.length>0?r:null;return e!=null?e:"All repositories"}function Pt(o){return o.milestones.length===0?"":`${o.milestones.length===1?"milestone":"milestones"} ${o.milestones.join(", ")}`}function ut(o){let r=[];return o.repo&&r.push(`repo: ${o.repo}`),o.state!=="all"&&r.push(`state: ${o.state}`),o.labels.length>0&&r.push(`labels: ${o.labels.join(", ")}`),o.milestones.length>0&&r.push(`milestones: ${o.milestones.join(", ")}`),o.q&&r.push(`query: ${o.q}`),o.limit!==T&&r.push(`limit: ${o.limit}`),o.direction!=="TB"&&r.push(`direction: ${o.direction}`),r.join(`
`)}function Me(o){let r=ut(o);return"```gitea-graph"+(r.length>0?`
${r}`:"")+"\n```\n"}function ht(o,r){let e=o.getCursor("from"),s=o.getLine(e.line).slice(0,e.ch).trim().length>0?`
`:"";o.replaceSelection(s+Me(r))}function pt(o,r){var a;let e=new Set(o.map(l=>l.id)),t=new Map;for(let l of o)t.set(l.id,[]);for(let l of r)e.has(l.from)&&e.has(l.to)&&((a=t.get(l.to))==null||a.push(l.from));let s=new Map,n=new Set,i=l=>{var h;let c=s.get(l);if(c!==void 0)return c;if(n.has(l))return 0;n.add(l);let u=0;for(let p of(h=t.get(l))!=null?h:[])u=Math.max(u,i(p)+1);return n.delete(l),s.set(l,u),u};for(let l of o)i(l.id);return s}function gt(o){var e;return((e=o.split(/\r?\n/,1)[0])!=null?e:"").replace(/^\s{0,3}(#{1,6}\s+|>\s+|[-*+]\s+)/,"").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/`([^`]*)`/g,"$1").replace(/[*_~]/g,"").replace(/\s+/g," ").trim()}function ce(o,r){return r<=0||o.length<=r?o:`${o.slice(0,r).trimEnd()}\u2026`}function de(o,r=Date.now()){let e=Date.parse(o);if(Number.isNaN(e))return"";let t=Math.max(0,Math.round((r-e)/1e3));if(t<45)return"just now";let s=Math.round(t/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);if(i<7)return`${i}d ago`;let a=Math.round(i/7);if(a<5)return`${a}w ago`;let l=Math.round(i/30);return l<12?`${l}mo ago`:`${Math.round(i/365)}y ago`}function ue(o){let r=o.split(/[\s._-]+/).filter(Boolean);return r.length===0?"?":r.length===1?r[0].slice(0,2).toUpperCase():`${r[0][0]}${r[1][0]}`.toUpperCase()}function he(o){let r=/^blocked-by:#(\d+)$/.exec(o.trim());return r?Number.parseInt(r[1],10):null}function K(o){let r=o.replace(/^#/,"");if(r.length!==6)return"#ffffff";let e=Number.parseInt(r.slice(0,2),16),t=Number.parseInt(r.slice(2,4),16),s=Number.parseInt(r.slice(4,6),16);return(.299*e+.587*t+.114*s)/255>.6?"#000000":"#ffffff"}var Z=class extends d.Plugin{constructor(){super(...arguments);this.settings=H;this.cache=new X(e=>this.fetchIssue(e));this.commentsCache=new $(e=>`${e.owner}/${e.repo}#${e.index}`,e=>this.fetchComments(e));this.searchCache=new $(tt,e=>this.fetchSearchIssues(e));this.milestoneCache=new $(rt,e=>this.fetchMilestone(e));this.graphCache=new $(ct,e=>this.fetchGraph(e));this.repoListCache=new $(()=>"user-repos",()=>this.fetchRepos());this.inlineIssueCache=new $(e=>e,e=>this.fetchInlineIssues(e));this.repoWriteCache=new $(e=>e,e=>this.fetchRepoCanWrite(e));this.imageCache=new $(e=>`img:${e}`,e=>this.fetchAuthedImage(e));this.assetsCache=new $(e=>`assets:${e.owner}/${e.repo}#${e.index}`,e=>this.fetchIssueAssets(e))}async onload(){await this.loadSettings(),this.addSettingTab(new Ee(this.app,this)),this.registerMarkdownCodeBlockProcessor("gitea-issue",(e,t,s)=>{t.empty();let{block:n,error:i}=Qe(e);if(!n){this.renderError(t,i!=null?i:"Expected a single reference in owner/repo#index form.");return}s.addChild(new pe(t,this,n.ref,s.sourcePath,n.comments))}),this.registerMarkdownCodeBlockProcessor("gitea-search",(e,t,s)=>{t.empty();let{query:n,error:i}=et(e);if(!n){this.renderError(t,i!=null?i:"Invalid search query.");return}s.addChild(new ge(t,this,n))}),this.registerMarkdownCodeBlockProcessor("gitea-milestone",(e,t,s)=>{t.empty();let{query:n,error:i}=it(e);if(!n){this.renderError(t,i!=null?i:"Invalid milestone query.");return}s.addChild(new me(t,this,n))}),this.registerMarkdownCodeBlockProcessor("gitea-graph",(e,t,s)=>{t.empty();let{query:n,error:i}=lt(e);if(!n){this.renderError(t,i!=null?i:"Invalid graph query.");return}s.addChild(new fe(t,this,n))}),this.addCommand({id:"new-issue",name:"New issue",callback:()=>{var t,s;let e=(s=(t=this.app.workspace.getActiveViewOfType(d.MarkdownView))==null?void 0:t.editor)!=null?s:null;new q(this,{editor:e}).open()}}),this.addCommand({id:"convert-selection-to-issue",name:"Convert selection to issue",editorCallback:e=>{new q(this,{editor:e,body:e.getSelection()}).open()}}),this.addCommand({id:"insert-existing-issue",name:"Insert existing issue",editorCallback:e=>{new ye(this,e).open()}}),this.addCommand({id:"build-search-query",name:"Build search query",editorCallback:e=>{new Ce(this,e).open()}}),this.addCommand({id:"build-graph-view",name:"Build graph view",editorCallback:e=>{new _e(this,e).open()}}),this.registerEditorSuggest(new we(this)),this.registerMarkdownPostProcessor((e,t)=>{this.processInlineChips(e,t)}),this.registerEditorExtension(Mt(this)),this.registerEvent(this.app.workspace.on("editor-paste",(e,t)=>{var i;if(e.defaultPrevented)return;let s=(i=e.clipboardData)==null?void 0:i.getData("text/plain");if(!s)return;let n=We(this.settings.baseUrl,s);n&&(e.preventDefault(),Ae(t,n))}))}async loadSettings(){var t,s;let e=await this.loadData();this.settings=Object.assign({},H,e!=null?e:{}),this.settings.secrets={...(t=e==null?void 0:e.secrets)!=null?t:{}},this.settings.repoAccents={...(s=e==null?void 0:e.repoAccents)!=null?s:{}}}async saveSettings(){await this.saveData(this.settings)}get refreshIntervalMs(){return Math.max(Y,this.settings.refreshIntervalSeconds)*1e3}async getSecret(e){var t;return(t=this.settings.secrets[e])!=null?t:null}async setSecret(e,t){t.length===0?delete this.settings.secrets[e]:this.settings.secrets[e]=t,await this.saveSettings()}async buildAuthHeaders(){let e={Accept:"application/json"},t=await this.getSecret(N.pat);if(t&&(e.Authorization=`token ${t}`),Ke(this.settings.baseUrl)){let s=await this.getSecret(N.cfClientId),n=await this.getSecret(N.cfClientSecret);s&&n&&(e["CF-Access-Client-Id"]=s,e["CF-Access-Client-Secret"]=n)}return e}ensureGiteaStatusOk(e,t){if(e.status>=300&&e.status<400)throw J(e,"location").includes("cloudflareaccess.com")?new L("Cloudflare Access rejected the service token."):new L(`Unexpected redirect (HTTP ${e.status}).`);if(e.status===401||e.status===403)throw J(e,"content-type").toLowerCase().includes("application/json")?new L("Gitea token invalid or insufficient scope."):new L("Cloudflare Access rejected the service token.");if(e.status===404)throw new L(t);if(e.status>=400)throw new L(`Gitea returned HTTP ${e.status}.`)}ensureGiteaOk(e,t){this.ensureGiteaStatusOk(e,t);let s=J(e,"content-type").toLowerCase();if(s&&!s.includes("json"))throw new L("Gitea returned a non-JSON response \u2014 check the base URL points at your Gitea server, not a login or proxy page.")}async testConnection(){var c,u,h,p;let e=this.settings.baseUrl.replace(/\/+$/,"");if(!e)throw new L("Set the Gitea base URL first.");let t=await this.buildAuthHeaders(),s=await(0,d.requestUrl)({url:`${e}/api/v1/version`,method:"GET",headers:t,throw:!1});this.ensureGiteaOk(s,"No Gitea API found at this base URL.");let n=(u=(c=s.json)==null?void 0:c.version)!=null?u:"unknown";if(!!!await this.getSecret(N.pat))return`Reached Gitea ${n}, but no API token is set.`;let a=await(0,d.requestUrl)({url:`${e}/api/v1/user`,method:"GET",headers:t,throw:!1});this.ensureGiteaOk(a,"Could not look up the token's user.");let l=(p=(h=a.json)==null?void 0:h.login)!=null?p:"unknown";return`Connected to Gitea ${n} as ${l}.`}async fetchIssue(e){let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}/issues/${e.index}`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Issue not found."),i.json}async fetchComments(e){var a;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/comments`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Issue not found."),(a=i.json)!=null?a:[]}async fetchIssueAssets(e){var a;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/assets`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Issue not found."),(a=i.json)!=null?a:[]}async fetchAuthedImage(e){let t=await this.buildAuthHeaders(),s=await(0,d.requestUrl)({url:e,method:"GET",headers:t,throw:!1});return this.ensureGiteaStatusOk(s,"Image not found."),{data:s.arrayBuffer,contentType:J(s,"content-type")||"application/octet-stream"}}async loadAuthedImage(e,t){var a;let s=await this.imageCache.load(e,this.refreshIntervalMs);if(!s.value)throw(a=s.error)!=null?a:new L("Image could not be loaded.");let n=new Blob([s.value.data],{type:s.value.contentType}),i=URL.createObjectURL(n);return t.register(()=>URL.revokeObjectURL(i)),i}buildSearchParams(e){let t=new URLSearchParams;return t.set("type","issues"),t.set("state",e.state),t.set("limit",String(e.limit)),t.set("page","1"),e.labels.length>0&&t.set("labels",e.labels.join(",")),e.milestones.length>0&&t.set("milestones",e.milestones.join(",")),e.q&&t.set("q",e.q),t.toString()}refForResult(e,t){var i,a,l;let s=(l=(a=e.repo)!=null?a:(i=t.repository)==null?void 0:i.full_name)!=null?l:"",n=s.indexOf("/");return n<=0||n===s.length-1?null:{owner:s.slice(0,n),repo:s.slice(n+1),index:t.number}}async fetchSearchIssues(e){var u;let t=this.settings.baseUrl.replace(/\/+$/,""),s=this.buildSearchParams(e),n=e.repo?`${t}/api/v1/repos/${e.repo.split("/").map(encodeURIComponent).join("/")}/issues?${s}`:`${t}/api/v1/repos/issues/search?${s}`,i=await this.buildAuthHeaders(),a=await(0,d.requestUrl)({url:n,method:"GET",headers:i,throw:!1});this.ensureGiteaOk(a,e.repo?"Repository not found.":"Search endpoint not found.");let l=(u=a.json)!=null?u:[],c=[];for(let h of l){if(h.pull_request!=null)continue;let p=this.refForResult(e,h);p&&c.push({ref:p,issue:h})}return c}async fetchMilestone(e){let t=this.settings.baseUrl.replace(/\/+$/,""),s=e.repo.split("/").map(encodeURIComponent).join("/"),n=`${t}/api/v1/repos/${s}/milestones/${encodeURIComponent(e.milestone)}`,i=await this.buildAuthHeaders(),a=await(0,d.requestUrl)({url:n,method:"GET",headers:i,throw:!1});return this.ensureGiteaOk(a,"Milestone not found."),a.json}graphRepo(e){var t;return(t=e.repo)!=null?t:this.settings.defaultRepo||null}graphToSearchQuery(e){return{repo:this.graphRepo(e),state:e.state,labels:e.labels,milestones:e.milestones,q:e.q,limit:e.limit,layout:"table"}}async assertMilestonesExist(e,t){let s=this.settings.baseUrl.replace(/\/+$/,""),n=this.repoPath(e),i=await this.buildAuthHeaders(),a=[];if(await Promise.all(t.map(async l=>{let c=`${s}/api/v1/repos/${n}/milestones/${encodeURIComponent(l)}`,u=await(0,d.requestUrl)({url:c,method:"GET",headers:i,throw:!1});if(u.status===404){a.push(l);return}this.ensureGiteaOk(u,`Milestone "${l}" not found.`)})),a.length>0){let l=a.length===1?"Milestone":"Milestones",c=a.map(u=>`"${u}"`).join(", ");throw new L(`${l} ${c} not found in ${e} \u2014 check the milestone name.`)}}async fetchIssueDependencies(e){var a;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/dependencies`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Issue not found."),(a=i.json)!=null?a:[]}async fetchGraph(e){let t=this.graphRepo(e);e.milestones.length>0&&t&&await this.assertMilestonesExist(t,e.milestones);let s=await this.fetchSearchIssues(this.graphToSearchQuery(e)),n=new Map;for(let p of s)n.set(le(p.ref),p);let i=await Promise.all(s.map(p=>this.fetchIssueDependencies(p.ref))),a=[],l=[],c={},u=new Set,h=(p,b)=>{if(p===b||!n.has(p)||!n.has(b))return;let g=`${p}->${b}`;u.has(g)||(u.add(g),l.push({from:p,to:b}))};return s.forEach((p,b)=>{var G,R;let{ref:g,issue:v}=p,y=le(g),x=v.state==="closed",w=!x&&ae(v,this.settings.inProgressLabel),M=!1;for(let m of i[b]){if(m.pull_request!=null)continue;let P=`${(R=(G=m.repository)==null?void 0:G.full_name)!=null?R:`${g.owner}/${g.repo}`}#${m.number}`;h(P,y),!x&&m.state==="open"&&(M=!0)}for(let m of v.labels){let S=he(m.name);if(S==null)continue;let P=`${g.owner}/${g.repo}#${S}`;h(P,y);let O=n.get(P);!x&&O&&O.issue.state==="open"&&(M=!0)}v.milestone&&typeof v.milestone.id=="number"&&(c[v.milestone.title]=v.milestone.id),a.push({id:y,ref:g,number:v.number,title:v.title,state:x?"closed":"open",inProgress:w,blocked:M})}),{nodes:a,edges:l,milestoneIds:c}}repoPath(e){return e.split("/").map(encodeURIComponent).join("/")}async fetchRepos(){var a;let t=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/user/repos?limit=50`,s=await this.buildAuthHeaders(),n=await(0,d.requestUrl)({url:t,method:"GET",headers:s,throw:!1});return this.ensureGiteaOk(n,"Could not list repositories."),((a=n.json)!=null?a:[]).map(l=>l.full_name).filter(l=>typeof l=="string"&&l.length>0)}async fetchInlineIssues(e){var l;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}/issues?type=issues&state=all&limit=50`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Repository not found."),((l=i.json)!=null?l:[]).filter(c=>c.pull_request==null).map(c=>({index:c.number,title:c.title,state:c.state}))}async loadRepoList(){var t;return(t=(await this.repoListCache.load(null,this.refreshIntervalMs)).value)!=null?t:[]}async loadInlineIssues(e){var s;return(s=(await this.inlineIssueCache.load(e,this.refreshIntervalMs)).value)!=null?s:[]}async fetchLabels(e){var a;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}/labels?limit=50`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Repository not found."),(a=i.json)!=null?a:[]}async fetchMilestones(e){var a;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}/milestones?state=open&limit=50`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});return this.ensureGiteaOk(i,"Repository not found."),(a=i.json)!=null?a:[]}async createIssue(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}/issues`,i=await this.buildAuthHeaders();i["Content-Type"]="application/json";let a=await(0,d.requestUrl)({url:n,method:"POST",headers:i,body:JSON.stringify(t),throw:!1});return this.ensureGiteaOk(a,"Repository not found."),a.json}issuePath(e){return`${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}/issues/${e.index}`}async giteaMutate(e,t,s){let n=await this.buildAuthHeaders();s!==void 0&&(n["Content-Type"]="application/json");let i=await(0,d.requestUrl)({url:e,method:t,headers:n,body:s!==void 0?JSON.stringify(s):void 0,throw:!1});return this.ensureGiteaOk(i,"Issue not found."),i}async fetchRepoCanWrite(e){var l,c;let s=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}`,n=await this.buildAuthHeaders(),i=await(0,d.requestUrl)({url:s,method:"GET",headers:n,throw:!1});this.ensureGiteaOk(i,"Repository not found.");let a=i.json;return!!((l=a.permissions)!=null&&l.push||(c=a.permissions)!=null&&c.admin)}async loadCanWriteIssues(e){return this.loadRepoCanWrite(`${e.owner}/${e.repo}`)}async loadRepoCanWrite(e){var s;return(s=(await this.repoWriteCache.load(e,this.refreshIntervalMs)).value)!=null?s:!1}async setIssueState(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}`;await this.giteaMutate(n,"PATCH",{state:t})}async addIssueComment(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/comments`;await this.giteaMutate(n,"POST",{body:t})}async editIssueBody(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}`;await this.giteaMutate(n,"PATCH",{body:t})}async uploadAsset(e,t,s,n){let i=await this.buildAuthHeaders(),{body:a,contentType:l}=qe("attachment",t,s,n);i["Content-Type"]=l;let c=await(0,d.requestUrl)({url:e,method:"POST",headers:i,body:a,throw:!1});return this.ensureGiteaOk(c,"Issue not found."),c.json}async uploadIssueAsset(e,t,s,n){let a=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/assets`;return this.uploadAsset(a,t,s,n)}async uploadCommentAsset(e,t,s,n,i){let l=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.repoPath(e)}/issues/comments/${t}/assets`;return this.uploadAsset(l,s,n,i)}async addIssueLabels(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/labels`;await this.giteaMutate(n,"POST",{labels:t})}async removeIssueLabel(e,t){let n=`${this.settings.baseUrl.replace(/\/+$/,"")}/api/v1/repos/${this.issuePath(e)}/labels/${t}`;await this.giteaMutate(n,"DELETE")}renderCardResult(e,t,s,n,i){var a,l;if(e.empty(),s.value){this.renderIssueCard(e,t,s.value,s.stale,n,i);return}this.renderError(e,(l=(a=s.error)==null?void 0:a.message)!=null?l:"Failed to load issue.")}renderSearchResult(e,t,s,n){var a,l;if(e.empty(),!s.value){this.renderError(e,(l=(a=s.error)==null?void 0:a.message)!=null?l:"Failed to load issues.");return}let i=e.createDiv({cls:"gitea-search"});if(s.stale&&i.createDiv({cls:"gitea-search__notice"}).setText("Gitea is unreachable \u2014 showing last-known results."),n&&this.renderCornerRefresh(i,"Refresh results now",n),this.renderSearchToolbar(i,t),s.value.length===0){i.createDiv({cls:"gitea-card gitea-card--empty",text:"No issues match this query."});return}if(t.layout==="table"){this.renderSearchTable(i,t,s.value);return}for(let c of s.value)this.renderIssueCard(i,c.ref,c.issue,!1)}renderSearchToolbar(e,t){let s=e.createDiv({cls:"gitea-search__toolbar"});new d.ButtonComponent(s).setIcon("plus").setButtonText("Add issue").setTooltip("Create an issue prefilled from this search").onClick(()=>{var a,l,c;let n=(l=(a=this.app.workspace.getActiveViewOfType(d.MarkdownView))==null?void 0:a.editor)!=null?l:null,i=t.repo!==null;new q(this,{editor:n,repo:(c=t.repo)!=null?c:void 0,labels:i?t.labels:void 0,milestone:i&&t.milestones.length===1?t.milestones[0]:void 0,defaultInsertFormat:"none"}).open()})}renderSearchTable(e,t,s){let n=t.repo===null,a=e.createEl("table",{cls:"gitea-search-table"}).createEl("tbody");for(let{ref:l,issue:c}of s){let u=c.state==="closed",h=!u&&ae(c,this.settings.inProgressLabel),p=u?"closed":h?"in-progress":"open",b=h?"in progress":p,g=a.createEl("tr",{cls:"gitea-search-table__row"});u&&g.addClass("gitea-search-table__row--closed");let v=this.settings.repoAccents[`${l.owner}/${l.repo}`];v&&(g.addClass("gitea-search-table__row--accented"),g.style.setProperty("--gitea-accent",v)),g.createEl("td",{cls:"gitea-search-table__cell gitea-search-table__cell--dot"}).createSpan({cls:`gitea-search-table__dot gitea-search-table__dot--${p}`});let w=g.createEl("td",{cls:"gitea-search-table__cell gitea-search-table__cell--number"}).createEl("a",{cls:"gitea-search-table__number",text:`#${c.number}`,href:j(this.settings.baseUrl,l)});w.setAttr("target","_blank"),w.setAttr("rel","noopener"),n&&g.createEl("td",{cls:"gitea-search-table__cell gitea-search-table__cell--repo",text:`${l.owner}/${l.repo}`}),g.createEl("td",{cls:"gitea-search-table__cell gitea-search-table__cell--title",text:c.title}),g.createEl("td",{cls:"gitea-search-table__cell gitea-search-table__cell--state"}).createSpan({cls:`gitea-search-table__state gitea-search-table__state--${p}`,text:b})}}renderMilestoneResult(e,t,s){var n,i;if(e.empty(),!s.value){this.renderError(e,(i=(n=s.error)==null?void 0:n.message)!=null?i:"Failed to load milestone.");return}this.renderMilestoneCard(e,t,s.value,s.stale)}renderMilestoneCard(e,t,s,n=!1){var x,w;let i=(x=s.open_issues)!=null?x:0,a=(w=s.closed_issues)!=null?w:0,l=i+a,c=at(i,a),u=s.state==="closed",h=e.createDiv({cls:"gitea-card gitea-milestone"});this.applyRepoAccent(h,t.repo),u&&h.addClass("gitea-card--closed"),n&&h.addClass("gitea-card--stale");let p=h.createDiv({cls:"gitea-milestone__header"}),b=p.createEl("a",{cls:"gitea-milestone__title",text:s.title,href:oe(this.settings.baseUrl,t.repo,s.id)});b.setAttr("target","_blank"),b.setAttr("rel","noopener"),n&&p.createSpan({cls:"gitea-card__stale-badge",text:"stale"}).setAttr("aria-label","Showing last-known data \u2014 Gitea is currently unreachable"),p.createSpan({cls:"gitea-milestone__percent",text:`${c}%`});let g=h.createDiv({cls:"gitea-milestone__bar"});g.setAttr("role","progressbar"),g.setAttr("aria-valuemin","0"),g.setAttr("aria-valuemax","100"),g.setAttr("aria-valuenow",String(c)),g.createDiv({cls:"gitea-milestone__bar-fill"}).style.setProperty("--gitea-progress",`${c}%`);let y=h.createDiv({cls:"gitea-milestone__stats"});y.createSpan({cls:"gitea-milestone__stat",text:l===0?"No issues in this milestone":`${a} of ${l} closed`}),i>0&&y.createSpan({cls:"gitea-milestone__stat",text:`${i} open`})}renderGraphResult(e,t,s,n){var i,a;if(e.empty(),!s.value){this.renderError(e,(a=(i=s.error)==null?void 0:i.message)!=null?a:"Failed to load graph.");return}this.renderGraph(e,t,s.value,s.stale,n)}renderGraph(e,t,s,n=!1,i){var De,Oe,Ue;let a=e.createDiv({cls:"gitea-card gitea-graph"});n&&(a.addClass("gitea-card--stale"),a.createSpan({cls:"gitea-card__stale-badge gitea-graph__stale-badge",text:"stale"}).setAttr("aria-label","Showing last-known data \u2014 Gitea is currently unreachable")),i&&this.renderCornerRefresh(a,"Refresh graph now",i);let c=a.createDiv({cls:"gitea-graph__header"}).createDiv({cls:"gitea-graph__heading"}),u=(De=t.repo)!=null?De:this.settings.defaultRepo.length>0?this.settings.defaultRepo:null,h=u?A(u):null,p=dt(t,this.settings.defaultRepo);if(h){let f=c.createEl("a",{cls:"gitea-graph__title",text:p,href:ie(this.settings.baseUrl,h.owner,h.repo)});f.setAttr("target","_blank"),f.setAttr("rel","noopener")}else c.createDiv({cls:"gitea-graph__title",text:p});if(t.milestones.length>0){let f=c.createDiv({cls:"gitea-graph__subtitle"}),C=t.milestones.length===1?"milestone":"milestones";f.createSpan({text:`${C} `}),t.milestones.forEach((_,k)=>{var E;k>0&&f.createSpan({text:", "});let I=(E=s.milestoneIds)==null?void 0:E[_];if(u&&typeof I=="number"){let U=f.createEl("a",{cls:"gitea-graph__milestone-link",text:_,href:oe(this.settings.baseUrl,u,I)});U.setAttr("target","_blank"),U.setAttr("rel","noopener")}else f.createSpan({text:_})})}if(s.nodes.length===0){a.addClass("gitea-card--empty"),a.createSpan({text:"No issues match this query."});return}let b=200,g=48,v=60,y=18,x=10,w=t.direction==="LR",M=pt(s.nodes,s.edges),G=new Map,R=0;for(let f of s.nodes){let C=(Oe=M.get(f.id))!=null?Oe:0;R=Math.max(R,C);let _=G.get(C);_?_.push(f):G.set(C,[f])}let m=new Map,S=1;for(let f=0;f<=R;f++){let C=(Ue=G.get(f))!=null?Ue:[];S=Math.max(S,C.length),C.forEach((_,k)=>{let I=x+f*((w?b:g)+v),E=x+k*((w?g:b)+y);m.set(_.id,{x:w?I:E,y:w?E:I})})}let P=x*2+(R+1)*(w?b:g)+R*v,O=x*2+S*(w?g:b)+(S-1)*y,B=w?P:O,ke=w?O:P,se=a.createSvg("svg",{cls:"gitea-graph__svg",attr:{viewBox:`0 0 ${B} ${ke}`,width:B,height:ke,preserveAspectRatio:"xMinYMin meet",role:"img","aria-label":`Dependency graph of ${s.nodes.length} issues`}}),Ge=`gitea-graph-arrow-${_t++}`;se.createSvg("defs").createSvg("marker",{attr:{id:Ge,markerWidth:8,markerHeight:8,refX:7,refY:3,orient:"auto",markerUnits:"strokeWidth"}}).createSvg("path",{cls:"gitea-graph__arrow",attr:{d:"M0,0 L7,3 L0,6 Z"}});for(let f of s.edges){let C=m.get(f.from),_=m.get(f.to);if(!C||!_)continue;let k;if(w){let I=C.x+b,E=C.y+g/2,U=_.x,V=_.y+g/2,Q=(I+U)/2;k=`M${I},${E} C${Q},${E} ${Q},${V} ${U},${V}`}else{let I=C.x+b/2,E=C.y+g,U=_.x+b/2,V=_.y,Q=(E+V)/2;k=`M${I},${E} C${I},${Q} ${U},${Q} ${U},${V}`}se.createSvg("path",{cls:"gitea-graph__edge",attr:{d:k,"marker-end":`url(#${Ge})`}})}for(let f of s.nodes){let C=m.get(f.id);if(!C)continue;let _=f.state==="closed"?"closed":f.inProgress?"in-progress":"open",k=["gitea-graph__node",`gitea-graph__node--${_}`];f.blocked&&k.push("gitea-graph__node--blocked");let I=se.createSvg("a",{cls:k,attr:{href:j(this.settings.baseUrl,f.ref),target:"_blank",rel:"noopener"}});I.createSvg("title").textContent=`#${f.number} ${f.title}`;let E=I.createSvg("g",{attr:{transform:`translate(${C.x},${C.y})`}});E.createSvg("rect",{cls:"gitea-graph__node-rect",attr:{x:0,y:0,width:b,height:g,rx:6,ry:6}}),E.createSvg("circle",{cls:["gitea-graph__node-dot",`gitea-graph__node-dot--${_}`],attr:{cx:16,cy:g/2,r:5}}),E.createSvg("text",{cls:"gitea-graph__node-number",attr:{x:30,y:20}}).textContent=`#${f.number}`,E.createSvg("text",{cls:"gitea-graph__node-title",attr:{x:30,y:36}}).textContent=ce(f.title,24)}}processInlineChips(e,t){var a;let s=this.settings.keyword;if(!s)return;let n=`${s}:`,i=Tt(s);for(let l of e.findAll("code")){if(l.closest("pre, a, .gitea-chip"))continue;let c=((a=l.textContent)!=null?a:"").trim();if(!c.includes(n))continue;let u=i.exec(c);if(!u)continue;let h={owner:u[1],repo:u[2],index:Number.parseInt(u[3],10)};l.replaceWith(this.createInlineChip(h,t))}}createInlineChip(e,t){let s=ze(this.settings.baseUrl,e,this.settings.repoAccents[`${e.owner}/${e.repo}`]);return t.addChild(new be(s,this,e)),s}renderError(e,t){e.createDiv({cls:"gitea-card gitea-card--error"}).createSpan({cls:"gitea-card__error",text:t})}applyRepoAccent(e,t){let s=this.settings.repoAccents[t];s&&(e.addClass("gitea-card--accented"),e.style.setProperty("--gitea-accent",s))}renderIssueCard(e,t,s,n=!1,i,a){var G,R;let l=s.state==="closed",c=e.createDiv({cls:"gitea-card"});this.applyRepoAccent(c,`${t.owner}/${t.repo}`),l&&c.addClass("gitea-card--closed"),n&&c.addClass("gitea-card--stale");let u=c.createDiv({cls:"gitea-card__header"}),h=u.createEl("a",{cls:"gitea-card__number",text:`#${s.number}`,href:j(this.settings.baseUrl,t)});h.setAttr("target","_blank"),h.setAttr("rel","noopener"),u.createSpan({cls:"gitea-card__title",text:s.title}),n&&u.createSpan({cls:"gitea-card__stale-badge",text:"stale"}).setAttr("aria-label","Showing last-known data \u2014 Gitea is currently unreachable");let p=ce(gt((G=s.body)!=null?G:""),this.settings.truncationLength);if(p&&c.createDiv({cls:"gitea-card__body",text:p}),a&&this.settings.showAttachments&&!n){let m=c.createDiv({cls:"gitea-card__attachments"});this.renderAttachmentStrip(m,t,a.component)}let b=c.createDiv({cls:"gitea-card__meta"});if((R=s.labels)!=null&&R.length){let m=b.createDiv({cls:"gitea-card__labels"});for(let S of s.labels){let P=he(S.name);if(P===null){let B=m.createSpan({cls:"gitea-card__label",text:S.name});B.style.setProperty("--gitea-label-bg",`#${S.color}`),B.style.setProperty("--gitea-label-fg",K(S.color));continue}let O=m.createSpan({cls:"gitea-card__label gitea-card__label--blocked-by"});O.createSpan({cls:"gitea-card__label-name",text:`Blocked by #${P}`}),this.renderBlockerState(O,{owner:t.owner,repo:t.repo,index:P})}}let g=b.createDiv({cls:"gitea-card__author"});if(g.createSpan({cls:"gitea-card__avatar",text:ue(s.user.login)}),g.createSpan({cls:"gitea-card__author-name",text:s.user.login}),s.milestone){let m=b.createDiv({cls:"gitea-card__milestone"});m.createSpan({cls:"gitea-card__milestone-icon",text:"\u{1F3AF}"}),m.createSpan({text:s.milestone.title})}let v=c.createDiv({cls:"gitea-card__status"}),y=v.createEl("a",{cls:"gitea-card__repo-name",href:ie(this.settings.baseUrl,t.owner,t.repo)});y.setAttr("target","_blank"),y.setAttr("rel","noopener"),y.setAttr("aria-label",`Repository ${t.owner}/${t.repo}`),y.createSpan({cls:"gitea-card__repo-icon",text:"\u{1F4E6}"}),y.createSpan({text:`${t.owner}/${t.repo}`});let x=a!==void 0&&s.comments>0;if(x){let m=v.createEl("button",{cls:"gitea-card__comments gitea-card__comments--toggle"});m.setAttr("aria-expanded",String(a.expanded)),m.setAttr("aria-label",a.expanded?"Hide comments":"Show recent comments"),m.createSpan({cls:"gitea-card__comments-icon",text:"\u{1F4AC}"}),m.createSpan({text:String(s.comments)}),m.createSpan({cls:"gitea-card__comments-caret",text:a.expanded?"\u25BE":"\u25B8"}),m.addEventListener("click",()=>a.onToggle())}else{let m=v.createSpan({cls:"gitea-card__comments"});m.createSpan({cls:"gitea-card__comments-icon",text:"\u{1F4AC}"}),m.createSpan({text:String(s.comments)})}let w=v.createSpan({cls:"gitea-card__state"});w.createSpan({cls:l?"gitea-card__dot gitea-card__dot--closed":"gitea-card__dot gitea-card__dot--open"}),w.createSpan({text:l?"closed":"open"});let M=de(s.updated_at);if(M){let m=v.createSpan({cls:"gitea-card__updated"});m.createSpan({cls:"gitea-card__updated-icon",text:"\u27F3"}),m.createSpan({text:`updated ${M}`})}if(x&&a.expanded){let m=c.createDiv({cls:"gitea-card__comments-thread"});this.renderCommentThread(m,t,a)}if(i){let m=c.createDiv({cls:"gitea-card__actions"});this.renderRefreshAction(m,i),n||this.renderQuickActions(m,t,s,i)}}async renderCommentThread(e,t,s){var l,c;e.createDiv({cls:"gitea-card__comments-loading",text:"Loading comments\u2026"});let n=await this.commentsCache.load(t,this.refreshIntervalMs);if(!e.isConnected)return;e.empty();let i=n.value;if(!i){e.createDiv({cls:"gitea-card__comments-message",text:(c=(l=n.error)==null?void 0:l.message)!=null?c:"Failed to load comments."});return}if(n.stale&&e.createDiv({cls:"gitea-card__comments-message",text:"Gitea is unreachable \u2014 showing last-known comments."}),i.length===0){e.createDiv({cls:"gitea-card__comments-message",text:"No comments yet."});return}let a=s.count>0?i.slice(-s.count):i;i.length>a.length&&e.createDiv({cls:"gitea-card__comments-message",text:`Showing the latest ${a.length} of ${i.length} comments.`});for(let u of a)this.renderComment(e,u,s)}renderComment(e,t,s){var c;let n=e.createDiv({cls:"gitea-card__comment"}),i=n.createDiv({cls:"gitea-card__comment-header"});i.createSpan({cls:"gitea-card__avatar",text:ue(t.user.login)}),i.createSpan({cls:"gitea-card__comment-author",text:t.user.login});let a=de(t.created_at);a&&i.createSpan({cls:"gitea-card__comment-time",text:a});let l=n.createDiv({cls:"gitea-card__comment-body"});this.renderCommentBody(l,(c=t.body)!=null?c:"",s)}async renderCommentBody(e,t,s){var i;if(await d.MarkdownRenderer.render(this.app,t,e,s.sourcePath,s.component),!this.settings.showCommentImages||!e.isConnected)return;let n=e.querySelectorAll("img");for(let a=0;a<n.length;a++){let l=n[a],c=re(this.settings.baseUrl,(i=l.getAttribute("src"))!=null?i:"");c.authed&&this.loadCommentImage(l,c.url,s.component)}}loadCommentImage(e,t,s){var i;let n=(i=e.getAttribute("alt"))!=null?i:"";e.removeAttribute("src"),e.addClass("gitea-card__comment-image"),e.addClass("gitea-card__comment-image--loading"),this.loadAuthedImage(t,s).then(a=>{e.isConnected&&(e.setAttr("src",a),e.removeClass("gitea-card__comment-image--loading"),e.addClass("gitea-card__comment-image--loaded"),e.setAttr("aria-label",n?`View image: ${n}`:"View image"),s.registerDomEvent(e,"click",()=>{new ee(this,t,n).open()}))}).catch(a=>{if(!e.isConnected)return;let l=a instanceof Error?a.message:"Image could not be loaded.";e.replaceWith(createSpan({cls:"gitea-card__comment-image-error",text:`\u{1F512} ${l}`}))})}async renderAttachmentStrip(e,t,s){var a;let n=await this.assetsCache.load(t,this.refreshIntervalMs);if(!e.isConnected)return;let i=(a=n.value)!=null?a:[];if(i.length===0){e.remove();return}for(let l of i){let c=re(this.settings.baseUrl,l.browser_download_url);Se(l.name)?this.renderAttachmentThumbnail(e,l,c.url,s):this.renderAttachmentFileChip(e,l,c.url)}}renderAttachmentThumbnail(e,t,s,n){let i=e.createEl("img",{cls:"gitea-card__attachment-thumb gitea-card__attachment-thumb--loading"});i.setAttr("alt",t.name),this.loadAuthedImage(s,n).then(a=>{i.isConnected&&(i.setAttr("src",a),i.removeClass("gitea-card__attachment-thumb--loading"),i.addClass("gitea-card__attachment-thumb--loaded"),i.setAttr("aria-label",`View image: ${t.name}`),n.registerDomEvent(i,"click",()=>{new ee(this,s,t.name).open()}))}).catch(a=>{if(!i.isConnected)return;let l=a instanceof Error?a.message:"Image could not be loaded.";i.replaceWith(createSpan({cls:"gitea-card__attachment-error",text:`\u{1F512} ${l}`}))})}renderAttachmentFileChip(e,t,s){let n=e.createEl("a",{cls:"gitea-card__attachment-file",href:s});n.setAttr("target","_blank"),n.setAttr("rel","noopener"),n.setAttr("aria-label",`Download ${t.name}`),n.createSpan({cls:"gitea-card__attachment-file-icon",text:"\u{1F4CE}"}),n.createSpan({cls:"gitea-card__attachment-file-name",text:t.name})}async renderBlockerState(e,t){let s=e.createSpan({cls:"gitea-card__blocker-dot"});e.setAttr("aria-label",`Blocked by #${t.index}`);let n=await this.cache.load(t,this.refreshIntervalMs);if(!e.isConnected)return;let i=n.value;if(!i)return;let a=i.state==="closed";s.addClass(a?"gitea-card__blocker-dot--closed":"gitea-card__blocker-dot--open"),a&&e.addClass("gitea-card__label--resolved"),e.setAttr("aria-label",`Blocked by #${t.index} \u2014 ${a?"closed":"still open"}`)}renderRefreshButton(e,t,s){let n=new d.ExtraButtonComponent(e).setIcon("refresh-cw").setTooltip(t).onClick(()=>{n.extraSettingsEl.addClass("gitea-refresh-button--spinning"),s()});return n.extraSettingsEl.addClass("gitea-refresh-button"),n}renderCornerRefresh(e,t,s){this.renderRefreshButton(e,t,()=>s()).extraSettingsEl.addClass("gitea-refresh-button--corner")}renderRefreshAction(e,t){let s=this.renderRefreshButton(e,"Refresh this card now",()=>{s.setDisabled(!0),t.onChanged()});s.extraSettingsEl.addClass("gitea-card__action--refresh")}async renderQuickActions(e,t,s,n){let i;try{i=await this.loadCanWriteIssues(t)}catch(p){i=!1}if(!i||!e.isConnected)return;let a=s.state==="closed",l=e.createEl("button",{cls:"gitea-card__action",text:"Comment"});l.setAttr("aria-label","Add a comment");let c=e.createEl("button",{cls:"gitea-card__action",text:a?"Reopen":"Close"});c.setAttr("aria-label",a?"Reopen this issue":"Close this issue"),c.addEventListener("click",()=>{this.runCardAction(c,()=>this.setIssueState(t,a?"open":"closed"),n,a?"Reopened issue.":"Closed issue.")});let u=e.createEl("button",{cls:"gitea-card__action",text:"Labels"});u.setAttr("aria-label","Add or remove labels"),u.addEventListener("click",p=>{this.openLabelMenu(p,t,s,n)});let h=e.createDiv({cls:"gitea-card__comment-form gitea-card__comment-form--hidden"});l.addEventListener("click",()=>{h.hasClass("gitea-card__comment-form--hidden")?this.openCommentForm(h,t,n):this.closeCommentForm(h,n)})}openCommentForm(e,t,s){e.empty(),e.removeClass("gitea-card__comment-form--hidden"),s.setSuspended(!0);let n=e.createEl("textarea",{cls:"gitea-card__comment-input"});n.setAttr("placeholder","Leave a comment\u2026"),n.rows=3,n.focus();let i=e.createDiv({cls:"gitea-card__comment-buttons"}),a=i.createEl("button",{cls:"gitea-card__action mod-cta",text:"Send"}),l=i.createEl("button",{cls:"gitea-card__action",text:"Cancel"});if(this.settings.showCommentImages){let c=i.createEl("input",{cls:"gitea-card__comment-file"});c.type="file",c.accept="image/*",c.setAttr("aria-label","Attach an image"),c.addEventListener("change",()=>{var h,p;let u=(p=(h=c.files)==null?void 0:h[0])!=null?p:null;c.value="",u&&this.attachCommentImage(t,u,n,a,c)}),n.addEventListener("paste",u=>{var b,g,v;let h=Array.from((g=(b=u.clipboardData)==null?void 0:b.items)!=null?g:[]).find(y=>y.kind==="file"&&y.type.startsWith("image/")),p=(v=h==null?void 0:h.getAsFile())!=null?v:null;p&&(u.preventDefault(),this.attachCommentImage(t,p,n,a,c))})}l.addEventListener("click",()=>this.closeCommentForm(e,s)),a.addEventListener("click",()=>{let c=n.value.trim();if(!c){new d.Notice("Enter a comment first.");return}this.runCardAction(a,()=>this.addIssueComment(t,c),s,"Comment posted.")})}async attachCommentImage(e,t,s,n,i){if(!t.type.startsWith("image/")){new d.Notice("Only images can be attached.");return}let a=n.disabled;n.disabled=!0,i.disabled=!0;let l=new d.Notice("Uploading image\u2026",0);try{let c=await t.arrayBuffer(),u=t.name&&t.name.trim()?t.name:Te(t.type),h=await this.uploadIssueAsset(e,u,t.type,c);je(s,$e(h)),new d.Notice("Image attached.")}catch(c){new d.Notice(c instanceof Error?c.message:"Image upload failed.")}finally{l.hide(),n.disabled=a,i.disabled=!1,s.focus()}}closeCommentForm(e,t){e.empty(),e.addClass("gitea-card__comment-form--hidden"),t.setSuspended(!1)}async openLabelMenu(e,t,s,n){var c;let i;try{i=await this.fetchLabels(`${t.owner}/${t.repo}`)}catch(u){new d.Notice(u instanceof Error?u.message:"Could not load labels.");return}if(i.length===0){new d.Notice("This repository has no labels.");return}let a=new Set((c=s.labels)==null?void 0:c.map(u=>u.id)),l=new d.Menu;for(let u of i){let h=a.has(u.id);l.addItem(p=>{p.setTitle(u.name).setChecked(h).onClick(()=>{this.runCardAction(null,()=>h?this.removeIssueLabel(t,u.id):this.addIssueLabels(t,[u.id]),n,h?`Removed \u201C${u.name}\u201D.`:`Added \u201C${u.name}\u201D.`)})})}l.showAtMouseEvent(e)}async runCardAction(e,t,s,n){e&&(e.disabled=!0);try{await t(),new d.Notice(n),s.onChanged()}catch(i){new d.Notice(i instanceof Error?i.message:"Action failed."),e&&(e.disabled=!1)}}},pe=class extends d.MarkdownRenderChild{constructor(e,t,s,n,i){super(e);this.plugin=t;this.ref=s;this.sourcePath=n;this.suspended=!1;this.commentsExpanded=i!==null,this.commentCount=i&&i>0?i:t.settings.commentPreviewCount}onload(){this.containerEl.empty(),this.containerEl.createDiv({cls:"gitea-card gitea-card--loading",text:"Loading issue\u2026"}),this.refresh(),this.registerInterval(window.setInterval(()=>{this.suspended||!z(this.containerEl)||this.refresh()},this.plugin.refreshIntervalMs))}async refresh(){let e=await this.plugin.cache.load(this.ref,this.plugin.refreshIntervalMs);this.containerEl.isConnected&&this.plugin.renderCardResult(this.containerEl,this.ref,e,{onChanged:()=>{this.suspended=!1,this.plugin.cache.invalidate(this.ref),this.plugin.commentsCache.invalidate(this.ref),this.plugin.assetsCache.invalidate(this.ref),this.refresh()},setSuspended:t=>{this.suspended=t}},{count:this.commentCount,expanded:this.commentsExpanded,component:this,sourcePath:this.sourcePath,onToggle:()=>{this.commentsExpanded=!this.commentsExpanded,this.refresh()}})}},ge=class extends d.MarkdownRenderChild{constructor(e,t,s){super(e);this.plugin=t;this.query=s}onload(){this.containerEl.empty(),this.containerEl.createDiv({cls:"gitea-card gitea-card--loading",text:"Loading issues\u2026"}),this.refresh(),this.registerInterval(window.setInterval(()=>{z(this.containerEl)&&this.refresh()},this.plugin.refreshIntervalMs))}async refresh(){let e=await this.plugin.searchCache.load(this.query,this.plugin.refreshIntervalMs);this.containerEl.isConnected&&this.plugin.renderSearchResult(this.containerEl,this.query,e,()=>void this.refreshNow())}async refreshNow(){this.plugin.searchCache.invalidate(this.query),await this.refresh()}},me=class extends d.MarkdownRenderChild{constructor(e,t,s){super(e);this.plugin=t;this.query=s}onload(){this.containerEl.empty(),this.containerEl.createDiv({cls:"gitea-card gitea-card--loading",text:"Loading milestone\u2026"}),this.refresh(),this.registerInterval(window.setInterval(()=>{z(this.containerEl)&&this.refresh()},this.plugin.refreshIntervalMs))}async refresh(){let e=await this.plugin.milestoneCache.load(this.query,this.plugin.refreshIntervalMs);this.containerEl.isConnected&&this.plugin.renderMilestoneResult(this.containerEl,this.query,e)}},fe=class extends d.MarkdownRenderChild{constructor(e,t,s){super(e);this.plugin=t;this.query=s}onload(){this.containerEl.empty(),this.containerEl.createDiv({cls:"gitea-card gitea-card--loading",text:"Loading graph\u2026"}),this.refresh(),this.registerInterval(window.setInterval(()=>{z(this.containerEl)&&this.refresh()},this.plugin.refreshIntervalMs))}async refresh(){let e=await this.plugin.graphCache.load(this.query,this.plugin.refreshIntervalMs);this.containerEl.isConnected&&this.plugin.renderGraphResult(this.containerEl,this.query,e,()=>void this.refreshNow())}async refreshNow(){this.plugin.graphCache.invalidate(this.query),await this.refresh()}},be=class extends d.MarkdownRenderChild{constructor(e,t,s){super(e);this.plugin=t;this.ref=s}onload(){this.loadIssue(),this.registerInterval(window.setInterval(()=>{z(this.containerEl)&&this.loadIssue()},this.plugin.refreshIntervalMs))}async loadIssue(){let e=await this.plugin.cache.load(this.ref,this.plugin.refreshIntervalMs);if(!this.containerEl.isConnected)return;let t=e.value;t&&Le(this.containerEl,t,this.plugin.settings.inProgressLabel)}},mt=new WeakMap,ve=class extends F.WidgetType{constructor(e,t){super();this.plugin=e;this.ref=t}eq(e){return e.ref.owner===this.ref.owner&&e.ref.repo===this.ref.repo&&e.ref.index===this.ref.index}toDOM(){let e=ze(this.plugin.settings.baseUrl,this.ref,this.plugin.settings.repoAccents[`${this.ref.owner}/${this.ref.repo}`]);return mt.set(e,this.ref),this.plugin.cache.load(this.ref,this.plugin.refreshIntervalMs).then(t=>{e.isConnected&&t.value&&Le(e,t.value,this.plugin.settings.inProgressLabel)}),e}ignoreEvent(){return!0}};function Mt(o){return F.ViewPlugin.fromClass(class{constructor(r){this.view=r;this.decorations=this.build(r),this.refreshTimer=window.setInterval(()=>{this.refreshChips()},o.refreshIntervalMs)}update(r){(r.docChanged||r.viewportChanged||r.selectionSet)&&(this.decorations=this.build(r.view))}destroy(){window.clearInterval(this.refreshTimer)}refreshChips(){this.view.dom.querySelectorAll(".gitea-chip").forEach(e=>{let t=mt.get(e);t&&o.cache.load(t,o.refreshIntervalMs).then(s=>{e.isConnected&&s.value&&Le(e,s.value,o.settings.inProgressLabel)})})}build(r){let e=new He.RangeSetBuilder;if(!r.state.field(d.editorLivePreviewField)||!o.settings.keyword)return e.finish();let t=(0,Ne.syntaxTree)(r.state),s=r.state.selection;for(let{from:n,to:i}of r.visibleRanges){let a=r.state.doc.sliceString(n,i),l=Lt(o.settings.keyword);for(let c=l.exec(a);c!==null;c=l.exec(a)){let u=n+c.index,h=u+c[0].length;if(s.ranges.some(v=>v.from<=h&&v.to>=u))continue;let b=t.resolveInner(u+1,1).type.name;if(!/inline.?code/i.test(b))continue;let g={owner:c[1],repo:c[2],index:Number.parseInt(c[3],10)};e.add(u,h,F.Decoration.replace({widget:new ve(o,g)}))}}return e.finish()}},{decorations:r=>r.decorations})}var we=class extends d.EditorSuggest{constructor(e){super(e.app);this.plugin=e;this.stage="repo";this.repoSlug="";this.referenceStart=0}onTrigger(e,t,s){let n=this.plugin.settings.keyword;if(!n)return null;let i=t.getLine(e.line).slice(0,e.ch);if(!i.includes(`${n}:`))return null;let l=new RegExp(`${te(n)}:([^\\s:]*)(?::([^\\s:]*))?$`).exec(i);if(!l)return null;let c=l[1],u=l[2];if(u===void 0)return this.stage="repo",this.repoSlug="",{start:{line:e.line,ch:e.ch-c.length},end:e,query:c};let h=A(c);return h?(this.stage="issue",this.repoSlug=`${h.owner}/${h.repo}`,this.referenceStart=l.index,{start:{line:e.line,ch:e.ch-u.length},end:e,query:u}):null}async getSuggestions(e){let t=e.query.toLowerCase();try{if(this.stage==="repo")return(await this.plugin.loadRepoList()).filter(a=>a.toLowerCase().includes(t)).slice(0,20).map(a=>({kind:"repo",repo:a}));let s=t.replace(/^#/,"");return(await this.plugin.loadInlineIssues(this.repoSlug)).filter(i=>String(i.index).includes(s)||i.title.toLowerCase().includes(s)).slice(0,20).map(i=>({kind:"issue",index:i.index,title:i.title,state:i.state}))}catch(s){return[]}}renderSuggestion(e,t){if(t.addClass("gitea-suggestion"),e.kind==="repo"){t.createSpan({cls:"gitea-suggestion__repo",text:e.repo});return}t.createSpan({cls:"gitea-suggestion__number",text:`#${e.index}`}),t.createSpan({cls:"gitea-suggestion__title",text:`\u2014 ${e.title}`})}selectSuggestion(e){let t=this.context;if(!t)return;if(e.kind==="repo"){let l=`${e.repo}:`;t.editor.replaceRange(l,t.start,t.end),t.editor.setCursor({line:t.start.line,ch:t.start.ch+l.length});return}let s=t.editor.getLine(t.start.line),n=this.referenceStart;n>0&&s.charAt(n-1)==="`"&&(n-=1);let i=t.end.ch;s.charAt(i)==="`"&&(i+=1);let a=`\`${this.plugin.settings.keyword}:${this.repoSlug}:#${e.index}\``;t.editor.replaceRange(a,{line:t.start.line,ch:n},{line:t.end.line,ch:i}),t.editor.setCursor({line:t.start.line,ch:n+a.length})}},ee=class extends d.Modal{constructor(e,t,s){super(e.app);this.plugin=e;this.url=t;this.alt=s;this.owner=new d.Component}async onOpen(){this.owner.load();let{contentEl:e,modalEl:t}=this;t.addClass("gitea-lightbox-modal"),e.empty(),e.addClass("gitea-lightbox");let s=e.createDiv({cls:"gitea-lightbox__status",text:"Loading image\u2026"});try{let n=await this.plugin.loadAuthedImage(this.url,this.owner);if(!e.isConnected)return;s.remove();let i=e.createEl("img",{cls:"gitea-lightbox__image"});i.setAttr("src",n),this.alt&&i.setAttr("alt",this.alt)}catch(n){if(!e.isConnected)return;s.setText(n instanceof Error?n.message:"Image could not be loaded.")}}onClose(){this.owner.unload(),this.contentEl.empty()}},ye=class extends d.Modal{constructor(e,t){super(e.app);this.plugin=e;this.editor=t;this.issues=[];this.selectedIndex=null;this.repoSetting=null;this.issueEl=null;this.insertButton=null;this.repo=e.settings.defaultRepo,this.insertFormat=e.settings.insertFormat==="none"?"card":e.settings.insertFormat}async onOpen(){this.titleEl.setText("Insert existing issue");let{contentEl:e}=this;e.empty(),e.addClass("gitea-insert-issue"),this.repoSetting=new d.Setting(e).setName("Repository"),this.issueEl=e.createDiv(),new d.Setting(e).setName("Insert as").setDesc("Drop a full card or a compact inline status into the note.").addDropdown(t=>{t.addOption("card","Card"),t.addOption("inline","Inline status"),t.setValue(this.insertFormat),t.onChange(s=>{this.insertFormat=s,this.plugin.settings.insertFormat=this.insertFormat,this.plugin.saveSettings()})}),new d.Setting(e).addButton(t=>{this.insertButton=t,t.setButtonText("Insert").setCta().onClick(()=>this.submit())}),await this.renderRepoControl(),await this.renderIssues()}onClose(){this.contentEl.empty()}async renderRepoControl(){let e=this.repoSetting;if(e)try{let t=await this.plugin.fetchRepos(),s=[...new Set([this.repo,...t].filter(n=>n.length>0))];!this.repo&&s.length>0&&(this.repo=s[0]),e.setDesc("Repository to insert an issue from."),e.addDropdown(n=>{for(let i of s)n.addOption(i,i);n.setValue(this.repo),n.onChange(i=>{this.repo=i,this.renderIssues()})})}catch(t){e.setDesc("Repository in owner/repo form."),e.addText(s=>{s.setValue(this.repo).onChange(n=>{this.repo=n.trim()})}),e.addExtraButton(s=>{s.setIcon("refresh-cw").setTooltip("Load issues").onClick(()=>void this.renderIssues())})}}async renderIssues(){let e=this.issueEl;if(!e)return;if(this.selectedIndex=null,this.issues=[],e.empty(),!A(this.repo)){e.createDiv({cls:"gitea-insert-issue__notice",text:"Enter a repository in owner/repo form."});return}let s=this.repo;e.createDiv({cls:"gitea-insert-issue__notice",text:"Loading issues\u2026"});let n;try{n=await this.plugin.fetchInlineIssues(this.repo)}catch(i){if(this.repo!==s)return;e.empty(),e.createDiv({cls:"gitea-insert-issue__notice",text:i instanceof Error?i.message:"Could not load issues."});return}if(this.repo===s){if(this.issues=n,e.empty(),n.length===0){e.createDiv({cls:"gitea-insert-issue__notice",text:"This repository has no issues."});return}this.selectedIndex=n[0].index,new d.Setting(e).setName("Issue").addDropdown(i=>{for(let a of n){let l=a.state==="closed"?" (closed)":"";i.addOption(String(a.index),`#${a.index} \u2014 ${a.title}${l}`)}i.setValue(String(this.selectedIndex)),i.onChange(a=>{this.selectedIndex=Number.parseInt(a,10)})})}}submit(){let e=A(this.repo);if(!e){new d.Notice("Enter a repository in owner/repo form.");return}if(this.selectedIndex===null){new d.Notice("Choose an issue to insert.");return}let t={owner:e.owner,repo:e.repo,index:this.selectedIndex};Re(this.editor,t,this.insertFormat,this.plugin.settings.keyword),this.close()}},q=class extends d.Modal{constructor(e,t){var s,n;super(e.app);this.plugin=e;this.options=t;this.title="";this.selectedLabelIds=new Set;this.milestoneId=null;this.assignees="";this.labels=[];this.milestones=[];this.repoSetting=null;this.metaEl=null;this.attachEl=null;this.submitButton=null;this.submitting=!1;this.pendingFiles=[];this.previewUrls=[];this.previewsEl=null;this.attachEnabled=!1;this.repo=t.repo||e.settings.lastRepo||e.settings.defaultRepo,this.body=(s=t.body)!=null?s:"",this.insertFormat=(n=t.defaultInsertFormat)!=null?n:e.settings.insertFormat}async onOpen(){this.titleEl.setText("New issue");let{contentEl:e}=this;e.empty(),e.addClass("gitea-new-issue"),this.repoSetting=new d.Setting(e).setName("Repository"),new d.Setting(e).setName("Title").addText(t=>{t.setPlaceholder("Issue title").onChange(s=>{this.title=s})}),new d.Setting(e).setName("Description").addTextArea(t=>{t.setValue(this.body).onChange(s=>{this.body=s}),t.inputEl.rows=6,t.inputEl.addClass("gitea-new-issue__body"),t.inputEl.addEventListener("paste",s=>{this.handleBodyPaste(s)})}),this.metaEl=e.createDiv(),this.attachEl=e.createDiv(),this.options.editor&&new d.Setting(e).setName("Insert as").setDesc("Drop a full card, a compact inline status, or nothing into the note.").addDropdown(t=>{t.addOption("card","Card"),t.addOption("inline","Inline status"),t.addOption("none","None"),t.setValue(this.insertFormat),t.onChange(s=>{this.insertFormat=s,this.plugin.settings.insertFormat=this.insertFormat,this.plugin.saveSettings()})}),new d.Setting(e).addButton(t=>{this.submitButton=t,t.setButtonText("Create issue").setCta().onClick(()=>void this.submit())}),this.scope.register(["Mod"],"Enter",t=>(t.preventDefault(),this.submit(),!1)),await this.renderRepoControl(),await this.renderMetadata(),await this.renderAttachSection()}onClose(){this.clearPreviewUrls(),this.contentEl.empty()}async renderRepoControl(){let e=this.repoSetting;if(e)try{let t=await this.plugin.fetchRepos(),s=[...new Set([this.repo,...t].filter(n=>n.length>0))];!this.repo&&s.length>0&&(this.repo=s[0]),e.setDesc("Repository to create the issue in."),e.addDropdown(n=>{for(let i of s)n.addOption(i,i);n.setValue(this.repo),n.onChange(i=>{this.repo=i,this.renderMetadata(),this.renderAttachSection()})})}catch(t){e.setDesc("Repository in owner/repo form."),e.addText(s=>{s.setValue(this.repo).onChange(n=>{this.repo=n.trim()})}),e.addExtraButton(s=>{s.setIcon("refresh-cw").setTooltip("Load labels and milestones").onClick(()=>{this.renderMetadata(),this.renderAttachSection()})})}}async renderMetadata(){let e=this.metaEl;if(!e)return;if(this.selectedLabelIds.clear(),this.milestoneId=null,e.empty(),!A(this.repo)){e.createDiv({cls:"gitea-new-issue__notice",text:"Enter a repository in owner/repo form."});return}let s=this.repo;e.createDiv({cls:"gitea-new-issue__notice",text:"Loading labels and milestones\u2026"});let n,i;try{[n,i]=await Promise.all([this.plugin.fetchLabels(this.repo),this.plugin.fetchMilestones(this.repo)])}catch(a){if(this.repo!==s)return;e.empty(),e.createDiv({cls:"gitea-new-issue__notice",text:a instanceof Error?a.message:"Could not load repository metadata."});return}this.repo===s&&(this.labels=n,this.milestones=i.filter(a=>a.state!=="closed"),this.options.repo&&this.repo===this.options.repo&&this.applyPrefill(),e.empty(),this.renderLabelOptions(e),this.renderMilestoneOption(e),this.renderAssigneesOption(e))}applyPrefill(){var s,n;let e=new Set(((s=this.options.labels)!=null?s:[]).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0));if(e.size>0)for(let i of this.labels)e.has(i.name.trim().toLowerCase())&&this.selectedLabelIds.add(i.id);let t=(n=this.options.milestone)==null?void 0:n.trim().toLowerCase();if(t){let i=this.milestones.find(a=>a.title.trim().toLowerCase()===t);i&&(this.milestoneId=i.id)}}renderLabelOptions(e){if(new d.Setting(e).setName("Labels").setHeading(),this.labels.length===0){e.createDiv({cls:"gitea-new-issue__notice",text:"This repository has no labels."});return}let t=e.createDiv({cls:"gitea-new-issue__labels"});for(let s of this.labels){let n=t.createEl("button",{cls:"gitea-new-issue__label",text:s.name});n.type="button",n.style.setProperty("--gitea-label-bg",`#${s.color}`),n.style.setProperty("--gitea-label-fg",K(s.color));let i=()=>{let a=this.selectedLabelIds.has(s.id);n.toggleClass("is-selected",a),n.setAttr("aria-pressed",a?"true":"false")};i(),n.addEventListener("click",()=>{this.selectedLabelIds.has(s.id)?this.selectedLabelIds.delete(s.id):this.selectedLabelIds.add(s.id),i()})}}renderMilestoneOption(e){new d.Setting(e).setName("Milestone").addDropdown(t=>{t.addOption("","None");for(let s of this.milestones)t.addOption(String(s.id),s.title);t.setValue(this.milestoneId!==null?String(this.milestoneId):""),t.onChange(s=>{this.milestoneId=s?Number.parseInt(s,10):null})})}renderAssigneesOption(e){new d.Setting(e).setName("Assignees").setDesc("Comma-separated usernames.").addText(t=>{t.setValue(this.assignees).onChange(s=>{this.assignees=s})})}async renderAttachSection(){let e=this.attachEl;if(!e)return;if(e.empty(),this.clearPreviewUrls(),this.previewsEl=null,this.attachEnabled=!1,!this.plugin.settings.showCommentImages){this.pendingFiles=[];return}let t=this.repo,s=!1;try{s=await this.plugin.loadRepoCanWrite(this.repo)}catch(a){s=!1}if(this.repo!==t)return;if(!s){this.pendingFiles=[];return}new d.Setting(e).setName("Images").setHeading();let n=e.createEl("input",{cls:"gitea-new-issue__file"});n.type="file",n.accept="image/*",n.multiple=!0,n.setAttr("aria-label","Attach images");let i=e.createDiv({cls:"gitea-new-issue__previews"});this.previewsEl=i,this.attachEnabled=!0,n.addEventListener("change",()=>{var l;let a=Array.from((l=n.files)!=null?l:[]).filter(c=>c.type.startsWith("image/"));n.value="",a.length>0&&(this.pendingFiles.push(...a),this.renderPreviews(i))}),this.renderPreviews(i)}handleBodyPaste(e){var s,n;if(!this.attachEnabled||!this.previewsEl)return;let t=Array.from((n=(s=e.clipboardData)==null?void 0:s.items)!=null?n:[]).filter(i=>i.kind==="file"&&i.type.startsWith("image/")).map(i=>i.getAsFile()).filter(i=>i!==null);t.length!==0&&(e.preventDefault(),this.pendingFiles.push(...t),this.renderPreviews(this.previewsEl),new d.Notice(t.length===1?"Image queued.":`${t.length} images queued.`))}renderPreviews(e){e.empty(),this.clearPreviewUrls(),this.pendingFiles.forEach((t,s)=>{let n=e.createDiv({cls:"gitea-new-issue__preview"}),i=URL.createObjectURL(t);this.previewUrls.push(i);let a=n.createEl("img",{cls:"gitea-new-issue__preview-img"});a.src=i,a.alt=t.name;let l=n.createEl("button",{cls:"gitea-new-issue__preview-remove",text:"\xD7"});l.type="button",l.setAttr("aria-label",`Remove ${t.name}`),l.addEventListener("click",()=>{this.pendingFiles.splice(s,1),this.renderPreviews(e)})})}clearPreviewUrls(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[]}async submit(){var a,l,c;if(this.submitting)return;let e=this.title.trim();if(!e){new d.Notice("Enter a title for the issue.");return}let t=A(this.repo);if(!t){new d.Notice("Enter a repository in owner/repo form.");return}this.submitting=!0,(a=this.submitButton)==null||a.setDisabled(!0).setButtonText("Creating\u2026");let s={title:e,body:this.body,labels:[...this.selectedLabelIds],assignees:D(this.assignees)};this.milestoneId!==null&&(s.milestone=this.milestoneId);let n;try{n=await this.plugin.createIssue(this.repo,s)}catch(u){new d.Notice(u instanceof Error?u.message:"Could not create the issue."),this.submitting=!1,(l=this.submitButton)==null||l.setDisabled(!1).setButtonText("Create issue");return}let i={owner:t.owner,repo:t.repo,index:n.number};this.pendingFiles.length>0&&((c=this.submitButton)==null||c.setButtonText("Uploading images\u2026"),await this.attachPendingImages(i,n.number)),this.options.editor&&Re(this.options.editor,i,this.insertFormat,this.plugin.settings.keyword),this.plugin.settings.lastRepo!==this.repo&&(this.plugin.settings.lastRepo=this.repo,this.plugin.saveSettings()),new d.Notice(`Created issue #${n.number}.`),this.close()}async attachPendingImages(e,t){let s=[],n=null;for(let i of this.pendingFiles)try{let a=i.name&&i.name.trim()?i.name:Te(i.type),l=await i.arrayBuffer(),c=await this.plugin.uploadIssueAsset(e,a,i.type,l);s.push($e(c))}catch(a){n=a instanceof Error?a:new Error("Image upload failed.");break}if(s.length>0){let i=s.join(`
`),a=this.body.trim().length>0?`${this.body.replace(/\s+$/,"")}
${i}`:i;try{await this.plugin.editIssueBody(e,a)}catch(l){n=l instanceof Error?l:new Error("Could not update the issue body.")}}n&&new d.Notice(`Created issue #${t}, but not all images were attached: ${n.message}`)}},Ce=class extends d.Modal{constructor(e,t){super(e.app);this.plugin=e;this.editor=t;this.state="open";this.selectedLabels=new Set;this.labelsText="";this.milestone="";this.milestonesText="";this.q="";this.limit=W;this.layout="table";this.labels=[];this.milestones=[];this.repoSetting=null;this.metaEl=null;this.previewEl=null;this.repo=e.settings.lastRepo||e.settings.defaultRepo}async onOpen(){this.titleEl.setText("Build search query");let{contentEl:e}=this;e.empty(),e.addClass("gitea-search-wizard"),this.repoSetting=new d.Setting(e).setName("Repository"),new d.Setting(e).setName("State").setDesc("Which issues to include.").addDropdown(t=>{t.addOption("open","Open"),t.addOption("closed","Closed"),t.addOption("all","All"),t.setValue(this.state),t.onChange(s=>{this.state=s,this.updatePreview()})}),this.metaEl=e.createDiv(),new d.Setting(e).setName("Keyword").setDesc("Free-text match on issue title and body.").addText(t=>{t.setPlaceholder("Optional").onChange(s=>{this.q=s,this.updatePreview()})}),new d.Setting(e).setName("Limit").setDesc(`How many results to render (max ${T}).`).addText(t=>{t.inputEl.type="number",t.inputEl.min="1",t.inputEl.max=String(T),t.setValue(String(this.limit)).onChange(s=>{let n=Number.parseInt(s,10);this.limit=Number.isFinite(n)&&n>0?Math.min(n,T):W,this.updatePreview()})}),new d.Setting(e).setName("Layout").setDesc("Compact table of rows or a list of full cards.").addDropdown(t=>{t.addOption("table","Table"),t.addOption("cards","Cards"),t.setValue(this.layout),t.onChange(s=>{this.layout=s,this.updatePreview()})}),new d.Setting(e).setName("Preview").setHeading(),this.previewEl=e.createEl("pre",{cls:"gitea-search-wizard__preview"}),new d.Setting(e).addButton(t=>{t.setButtonText("Insert").setCta().onClick(()=>this.submit())}),this.scope.register(["Mod"],"Enter",t=>(t.preventDefault(),this.submit(),!1)),await this.renderRepoControl(),await this.renderMetadata()}onClose(){this.contentEl.empty()}currentQuery(){let e=A(this.repo)!==null;return{repo:this.repo.trim()||null,state:this.state,labels:e?[...this.selectedLabels]:D(this.labelsText),milestones:e?this.milestone?[this.milestone]:[]:D(this.milestonesText),q:this.q.trim()||null,limit:this.limit,layout:this.layout}}updatePreview(){var e;(e=this.previewEl)==null||e.setText(Pe(this.currentQuery()).trimEnd())}async renderRepoControl(){let e=this.repoSetting;if(e)try{let t=await this.plugin.fetchRepos(),s=[...new Set([this.repo,...t].filter(n=>n.length>0))];e.setDesc("Repository to search, or all repositories."),e.addDropdown(n=>{n.addOption("","All repositories (global)");for(let i of s)n.addOption(i,i);n.setValue(this.repo),n.onChange(i=>{this.repo=i,this.renderMetadata()})})}catch(t){e.setDesc("Repository in owner/repo form, or blank for all."),e.addText(s=>{s.setValue(this.repo).onChange(n=>{this.repo=n.trim(),this.updatePreview()})}),e.addExtraButton(s=>{s.setIcon("refresh-cw").setTooltip("Load labels and milestones").onClick(()=>void this.renderMetadata())})}}async renderMetadata(){let e=this.metaEl;if(!e)return;if(this.selectedLabels.clear(),this.milestone="",e.empty(),!A(this.repo)){this.renderLabelTextOption(e),this.renderMilestoneTextOption(e),this.updatePreview();return}let s=this.repo;e.createDiv({cls:"gitea-search-wizard__notice",text:"Loading labels and milestones\u2026"});let n,i;try{[n,i]=await Promise.all([this.plugin.fetchLabels(this.repo),this.plugin.fetchMilestones(this.repo)])}catch(a){if(this.repo!==s)return;e.empty(),this.renderLabelTextOption(e),this.renderMilestoneTextOption(e),this.updatePreview();return}this.repo===s&&(this.labels=n,this.milestones=i,e.empty(),this.renderLabelChips(e),this.renderMilestoneDropdown(e),this.updatePreview())}renderLabelChips(e){if(new d.Setting(e).setName("Labels").setHeading(),this.labels.length===0){e.createDiv({cls:"gitea-search-wizard__notice",text:"This repository has no labels."});return}let t=e.createDiv({cls:"gitea-new-issue__labels"});for(let s of this.labels){let n=t.createEl("button",{cls:"gitea-new-issue__label",text:s.name});n.type="button",n.style.setProperty("--gitea-label-bg",`#${s.color}`),n.style.setProperty("--gitea-label-fg",K(s.color));let i=()=>{let a=this.selectedLabels.has(s.name);n.toggleClass("is-selected",a),n.setAttr("aria-pressed",a?"true":"false")};i(),n.addEventListener("click",()=>{this.selectedLabels.has(s.name)?this.selectedLabels.delete(s.name):this.selectedLabels.add(s.name),i(),this.updatePreview()})}}renderMilestoneDropdown(e){new d.Setting(e).setName("Milestone").addDropdown(t=>{t.addOption("","None");for(let s of this.milestones)t.addOption(s.title,s.title);t.setValue(""),t.onChange(s=>{this.milestone=s,this.updatePreview()})})}renderLabelTextOption(e){new d.Setting(e).setName("Labels").setDesc("Comma-separated label names.").addText(t=>{t.setValue(this.labelsText).onChange(s=>{this.labelsText=s,this.updatePreview()})})}renderMilestoneTextOption(e){new d.Setting(e).setName("Milestones").setDesc("Comma-separated milestone names.").addText(t=>{t.setValue(this.milestonesText).onChange(s=>{this.milestonesText=s,this.updatePreview()})})}submit(){nt(this.editor,this.currentQuery()),this.close()}},_e=class extends d.Modal{constructor(e,t){super(e.app);this.plugin=e;this.editor=t;this.state="all";this.selectedLabels=new Set;this.labelsText="";this.selectedMilestones=new Set;this.milestonesText="";this.q="";this.limit=T;this.direction="TB";this.labels=[];this.milestones=[];this.repoSetting=null;this.metaEl=null;this.previewEl=null;this.repo=e.settings.lastRepo||e.settings.defaultRepo}async onOpen(){this.titleEl.setText("Build graph view");let{contentEl:e}=this;e.empty(),e.addClass("gitea-search-wizard"),this.repoSetting=new d.Setting(e).setName("Repository"),this.metaEl=e.createDiv(),new d.Setting(e).setName("State").setDesc("Which issues to include. All keeps completed blockers visible.").addDropdown(t=>{t.addOption("open","Open"),t.addOption("closed","Closed"),t.addOption("all","All"),t.setValue(this.state),t.onChange(s=>{this.state=s,this.updatePreview()})}),new d.Setting(e).setName("Keyword").setDesc("Free-text match on issue title and body.").addText(t=>{t.setPlaceholder("Optional").onChange(s=>{this.q=s,this.updatePreview()})}),new d.Setting(e).setName("Limit").setDesc(`Maximum number of nodes (max ${T}).`).addText(t=>{t.inputEl.type="number",t.inputEl.min="1",t.inputEl.max=String(T),t.setValue(String(this.limit)).onChange(s=>{let n=Number.parseInt(s,10);this.limit=Number.isFinite(n)&&n>0?Math.min(n,T):T,this.updatePreview()})}),new d.Setting(e).setName("Direction").setDesc("Orientation of the dependency layers.").addDropdown(t=>{t.addOption("TB","Top to bottom"),t.addOption("LR","Left to right"),t.setValue(this.direction),t.onChange(s=>{this.direction=s,this.updatePreview()})}),new d.Setting(e).setName("Preview").setHeading(),this.previewEl=e.createEl("pre",{cls:"gitea-search-wizard__preview"}),new d.Setting(e).addButton(t=>{t.setButtonText("Insert").setCta().onClick(()=>this.submit())}),this.scope.register(["Mod"],"Enter",t=>(t.preventDefault(),this.submit(),!1)),await this.renderRepoControl(),await this.renderMetadata()}onClose(){this.contentEl.empty()}currentQuery(){let e=A(this.repo)!==null;return{repo:this.repo.trim()||null,state:this.state,labels:e?[...this.selectedLabels]:D(this.labelsText),milestones:e?[...this.selectedMilestones]:D(this.milestonesText),q:this.q.trim()||null,limit:this.limit,direction:this.direction}}updatePreview(){var e;(e=this.previewEl)==null||e.setText(Me(this.currentQuery()).trimEnd())}async renderRepoControl(){let e=this.repoSetting;if(e)try{let t=await this.plugin.fetchRepos(),s=[...new Set([this.repo,...t].filter(n=>n.length>0))];e.setDesc("Repository to graph, or all repositories."),e.addDropdown(n=>{n.addOption("","All repositories (global)");for(let i of s)n.addOption(i,i);n.setValue(this.repo),n.onChange(i=>{this.repo=i,this.renderMetadata()})})}catch(t){e.setDesc("Repository in owner/repo form, or blank for all."),e.addText(s=>{s.setValue(this.repo).onChange(n=>{this.repo=n.trim(),this.updatePreview()})}),e.addExtraButton(s=>{s.setIcon("refresh-cw").setTooltip("Load milestones and labels").onClick(()=>void this.renderMetadata())})}}async renderMetadata(){let e=this.metaEl;if(!e)return;if(this.selectedLabels.clear(),this.selectedMilestones.clear(),e.empty(),!A(this.repo)){this.renderMilestoneTextOption(e),this.renderLabelTextOption(e),this.updatePreview();return}let s=this.repo;e.createDiv({cls:"gitea-search-wizard__notice",text:"Loading milestones and labels\u2026"});let n,i;try{[n,i]=await Promise.all([this.plugin.fetchLabels(this.repo),this.plugin.fetchMilestones(this.repo)])}catch(a){if(this.repo!==s)return;e.empty(),this.renderMilestoneTextOption(e),this.renderLabelTextOption(e),this.updatePreview();return}this.repo===s&&(this.labels=n,this.milestones=i,e.empty(),this.renderMilestonePicker(e),this.renderLabelChips(e),this.updatePreview())}renderMilestonePicker(e){if(new d.Setting(e).setName("Milestones").setHeading(),this.milestones.length===0){e.createDiv({cls:"gitea-search-wizard__notice",text:"This repository has no milestones."});return}this.renderMilestoneControls(e.createDiv())}renderMilestoneControls(e){e.empty();let t=this.milestones.filter(n=>!this.selectedMilestones.has(n.title));if(new d.Setting(e).setName("Add milestone").setDesc("Pick a milestone to add. A graph can span several.").addDropdown(n=>{n.addOption("",t.length>0?"Choose a milestone\u2026":"All milestones added");for(let i of t)n.addOption(i.title,i.title);n.setValue(""),n.setDisabled(t.length===0),n.onChange(i=>{i&&(this.selectedMilestones.add(i),this.renderMilestoneControls(e),this.updatePreview())})}),this.selectedMilestones.size===0)return;let s=e.createDiv({cls:"gitea-new-issue__labels"});for(let n of this.selectedMilestones){let i=s.createEl("button",{cls:"gitea-new-issue__label is-selected"});i.type="button",i.setAttr("aria-label",`Remove ${n}`),i.createSpan({text:n}),i.createSpan({cls:"gitea-new-issue__label-remove",text:"\u2715"}),i.addEventListener("click",()=>{this.selectedMilestones.delete(n),this.renderMilestoneControls(e),this.updatePreview()})}}renderLabelChips(e){if(new d.Setting(e).setName("Labels").setHeading(),this.labels.length===0){e.createDiv({cls:"gitea-search-wizard__notice",text:"This repository has no labels."});return}let t=e.createDiv({cls:"gitea-new-issue__labels"});for(let s of this.labels){let n=t.createEl("button",{cls:"gitea-new-issue__label",text:s.name});n.type="button",n.style.setProperty("--gitea-label-bg",`#${s.color}`),n.style.setProperty("--gitea-label-fg",K(s.color));let i=()=>{let a=this.selectedLabels.has(s.name);n.toggleClass("is-selected",a),n.setAttr("aria-pressed",a?"true":"false")};i(),n.addEventListener("click",()=>{this.selectedLabels.has(s.name)?this.selectedLabels.delete(s.name):this.selectedLabels.add(s.name),i(),this.updatePreview()})}}renderMilestoneTextOption(e){new d.Setting(e).setName("Milestones").setDesc("Comma-separated milestone names.").addText(t=>{t.setValue(this.milestonesText).onChange(s=>{this.milestonesText=s,this.updatePreview()})})}renderLabelTextOption(e){new d.Setting(e).setName("Labels").setDesc("Comma-separated label names.").addText(t=>{t.setValue(this.labelsText).onChange(s=>{this.labelsText=s,this.updatePreview()})})}submit(){ht(this.editor,this.currentQuery()),this.close()}},xe=class extends d.AbstractInputSuggest{constructor(e,t,s,n){super(e,t);this.plugin=s;this.taken=n}async getSuggestions(e){let t=this.taken(),s=e.trim().toLowerCase();return(await this.plugin.loadRepoList()).filter(i=>!t[i]).filter(i=>i.toLowerCase().includes(s))}renderSuggestion(e,t){t.setText(e)}},Ee=class extends d.PluginSettingTab{constructor(r,e){super(r,e),this.plugin=e}display(){let{containerEl:r}=this;r.empty(),new d.Setting(r).setName("Gitea base URL").setDesc("Public, globally reachable URL. A local-network or remote address is a manual fallback. Card links are built from this URL.").addText(e=>e.setPlaceholder("https://gitea.example.com").setValue(this.plugin.settings.baseUrl).onChange(async t=>{this.plugin.settings.baseUrl=t.trim(),await this.plugin.saveSettings()})),new d.Setting(r).setName("Default repository").setDesc("Used by the new-issue flow and bare references, in owner/repo form.").addText(e=>e.setValue(this.plugin.settings.defaultRepo).onChange(async t=>{this.plugin.settings.defaultRepo=t.trim(),await this.plugin.saveSettings()})),new d.Setting(r).setName("Inline keyword").setDesc("Trigger word for the inline reference syntax, placed before owner/repo:#123.").addText(e=>e.setPlaceholder("GITEA").setValue(this.plugin.settings.keyword).onChange(async t=>{this.plugin.settings.keyword=t.trim()||H.keyword,await this.plugin.saveSettings()})),new d.Setting(r).setName("In-progress label").setDesc("Label name that marks an issue as in progress. An open issue carrying it shows an amber dot and badge on its inline chip. Leave empty to disable.").addText(e=>e.setPlaceholder("In-progress").setValue(this.plugin.settings.inProgressLabel).onChange(async t=>{this.plugin.settings.inProgressLabel=t.trim(),await this.plugin.saveSettings()})),new d.Setting(r).setName("Refresh interval").setDesc(`How often visible cards refresh, in seconds. Floored at ${Y} seconds.`).addText(e=>e.setPlaceholder("60").setValue(String(this.plugin.settings.refreshIntervalSeconds)).onChange(async t=>{let s=Number.parseInt(t,10);this.plugin.settings.refreshIntervalSeconds=Number.isFinite(s)?Math.max(Y,s):H.refreshIntervalSeconds,await this.plugin.saveSettings()})),new d.Setting(r).setName("Description truncation length").setDesc("Maximum characters of issue body shown on a card.").addText(e=>e.setPlaceholder("160").setValue(String(this.plugin.settings.truncationLength)).onChange(async t=>{let s=Number.parseInt(t,10);this.plugin.settings.truncationLength=Number.isFinite(s)&&s>0?s:H.truncationLength,await this.plugin.saveSettings()})),new d.Setting(r).setName("Comment preview count").setDesc("Number of recent comments shown when a card's comment thread is expanded.").addText(e=>e.setPlaceholder("3").setValue(String(this.plugin.settings.commentPreviewCount)).onChange(async t=>{let s=Number.parseInt(t,10);this.plugin.settings.commentPreviewCount=Number.isFinite(s)&&s>0?Math.min(s,Ie):H.commentPreviewCount,await this.plugin.saveSettings()})),new d.Setting(r).setName("Show images in comments").setDesc("Load images pasted into comments inline in expanded threads. Off by default \u2014 when off, comments stay text-only. Images are fetched with your token, so private and access-gated attachments load; click one to open it full size.").addToggle(e=>e.setValue(this.plugin.settings.showCommentImages).onChange(async t=>{this.plugin.settings.showCommentImages=t,await this.plugin.saveSettings()})),new d.Setting(r).setName("Show attachments").setDesc("Show an attachment strip \u2014 image thumbnails and file chips \u2014 under single issue cards. Off by default. When on, each single issue card makes one extra request for its attachments; list blocks are unaffected and stay one request per card. Click a thumbnail to open it full size.").addToggle(e=>e.setValue(this.plugin.settings.showAttachments).onChange(async t=>{this.plugin.settings.showAttachments=t,await this.plugin.saveSettings()})),this.renderAccentSettings(r),new d.Setting(r).setName("Credentials").setHeading(),this.addSecretSetting(r,"Gitea API token","Personal access token with write:issue and read:repository scope. Stored in plaintext in this vault's data.json.",N.pat),this.addSecretSetting(r,"Cloudflare Access client ID","Service-token client ID. Sent only when the base URL is a public host behind Cloudflare Access \u2014 ignored on LAN or Tailscale addresses.",N.cfClientId),this.addSecretSetting(r,"Cloudflare Access client secret","Service-token client secret. Shown only once at creation in Cloudflare Zero Trust.",N.cfClientSecret),new d.Setting(r).setName("Test connection").setDesc("Query the server with the settings above to confirm the base URL and token work.").addButton(e=>e.setButtonText("Test connection").onClick(async()=>{e.setDisabled(!0).setButtonText("Testing\u2026");try{let t=await this.plugin.testConnection();new d.Notice(t)}catch(t){let s=t instanceof Error?t.message:"Connection test failed.";new d.Notice(`Connection failed: ${s}`)}finally{e.setDisabled(!1).setButtonText("Test connection")}}))}renderAccentSettings(r){new d.Setting(r).setName("Repository accent colours").setHeading();let e=r.createDiv();this.renderAccentRows(e);let t="",s=null;new d.Setting(r).setName("Add repository").setDesc("Assign an accent colour to a repository, in owner/repo form.").addText(n=>{s=n,n.setPlaceholder("Owner/repo").onChange(a=>{t=a.trim()});let i=new xe(this.app,n.inputEl,this.plugin,()=>this.plugin.settings.repoAccents);i.onSelect(a=>{t=a,n.setValue(a),i.close()})}).addButton(n=>n.setButtonText("Add").onClick(async()=>{if(!A(t)){new d.Notice("Enter a repository in owner/repo form.");return}if(this.plugin.settings.repoAccents[t]){new d.Notice("That repository already has an accent colour.");return}this.plugin.settings.repoAccents[t]=Be,await this.plugin.saveSettings(),this.renderAccentRows(e),t="",s==null||s.setValue("")}))}renderAccentRows(r){r.empty();let e=this.plugin.settings.repoAccents,t=Object.keys(e).sort();if(t.length===0){new d.Setting(r).setDesc("No accent colours set. Add a repository below to tint its cards with a subtle coloured left border.");return}for(let s of t)new d.Setting(r).setName(s).addColorPicker(n=>n.setValue(e[s]).onChange(async i=>{this.plugin.settings.repoAccents[s]=i,await this.plugin.saveSettings()})).addExtraButton(n=>n.setIcon("trash").setTooltip("Remove accent colour").onClick(async()=>{delete this.plugin.settings.repoAccents[s],await this.plugin.saveSettings(),this.renderAccentRows(r)}))}addSecretSetting(r,e,t,s){new d.Setting(r).setName(e).setDesc(t).addText(i=>{i.inputEl.type="password",i.setPlaceholder("Stored in data.json"),this.plugin.getSecret(s).then(a=>{a&&i.setPlaceholder("\u2022\u2022\u2022\u2022\u2022\u2022 (stored)")}),i.onChange(async a=>{try{await this.plugin.setSecret(s,a.trim())}catch(l){let c=l instanceof Error?l.message:String(l);new d.Notice(`Could not save "${e}": ${c}`)}})})}};
/* nosourcemap */