@tacktext/widget 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.baseUrl=e,this.projectId=t}setAuthToken(e){this.authToken=e}setOnUnauthorized(e){this.onUnauthorized=e}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async handleResponse(e){return e.status===401&&this.onUnauthorized?.(),e}async getComments(){let e=await fetch(`${this.baseUrl}/projects/${this.projectId}/comments?path=${encodeURIComponent(window.location.pathname)}`,{headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to fetch comments");return e.json()}async createComment(e){let t=await fetch(`${this.baseUrl}/comments`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({project_id:this.projectId,...e})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to create comment");return t.json()}async updateComment(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(t)});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to update comment");return i.json()}async deleteComment(e){let t=await fetch(`${this.baseUrl}/comments/${e}`,{method:"DELETE",headers:this.getHeaders()});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to delete comment")}async uploadScreenshot(e){let t=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({image:e,project_id:this.projectId})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to upload screenshot");let{url:i}=await t.json();return i}};var b=class{constructor(e){this.sessionToken=null;this.user=null;this.onAuthChange=null;this.apiUrl=e}async init(){let e=localStorage.getItem("tack_session");if(e)try{let t=await fetch(`${this.apiUrl}/auth/widget-session`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){localStorage.removeItem("tack_session");return}let{user:i}=await t.json();this.sessionToken=e,this.user={id:i.user_id,name:i.user_name,email:i.user_email,avatar_url:i.user_avatar_url},this.onAuthChange?.(this.user)}catch{localStorage.removeItem("tack_session")}}signIn(){return new Promise((e,t)=>{let i=this.apiUrl.replace(/\/api$/,""),n=window.open(`${i}/auth/widget`,"tack-auth","width=500,height=600,popup=yes");if(!n){t(new Error("Popup blocked"));return}let r=new URL(this.apiUrl).origin,a=o=>{if(o.data?.type!=="tack:auth"||o.origin!==r)return;window.removeEventListener("message",a),clearInterval(s);let{token:c,user:d}=o.data;this.sessionToken=c,this.user={id:d.user_id,name:d.user_name,email:d.user_email,avatar_url:d.user_avatar_url},localStorage.setItem("tack_session",c),this.onAuthChange?.(this.user),e(this.user)};window.addEventListener("message",a);let s=setInterval(()=>{n.closed&&(clearInterval(s),window.removeEventListener("message",a),this.user||t(new Error("Auth popup closed")))},500)})}signOut(){this.sessionToken&&fetch(`${this.apiUrl}/auth/widget-session`,{method:"DELETE",headers:{Authorization:`Bearer ${this.sessionToken}`}}).catch(()=>{}),this.sessionToken=null,this.user=null,localStorage.removeItem("tack_session"),this.onAuthChange?.(null)}getUser(){return this.user}getSessionToken(){return this.sessionToken}isAuthenticated(){return this.user!==null}setOnAuthChange(e){this.onAuthChange=e}};function H(){return`
1
+ var b=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.baseUrl=e,this.projectId=t}setAuthToken(e){this.authToken=e}setOnUnauthorized(e){this.onUnauthorized=e}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async handleResponse(e){return e.status===401&&this.onUnauthorized?.(),e}async getComments(){let e=await fetch(`${this.baseUrl}/projects/${this.projectId}/comments?path=${encodeURIComponent(window.location.pathname)}`,{headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to fetch comments");return e.json()}async createComment(e){let t=await fetch(`${this.baseUrl}/comments`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({project_id:this.projectId,...e})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to create comment");return t.json()}async updateComment(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(t)});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to update comment");return i.json()}async deleteComment(e){let t=await fetch(`${this.baseUrl}/comments/${e}`,{method:"DELETE",headers:this.getHeaders()});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to delete comment")}async uploadScreenshot(e){let t=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({image:e,project_id:this.projectId})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to upload screenshot");let{url:i}=await t.json();return i}};var x=class{constructor(e){this.sessionToken=null;this.user=null;this.onAuthChange=null;this.apiUrl=e}async init(){let e=localStorage.getItem("tack_session");if(e)try{let t=await fetch(`${this.apiUrl}/auth/widget-session`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){localStorage.removeItem("tack_session");return}let{user:i}=await t.json();this.sessionToken=e,this.user={id:i.user_id,name:i.user_name,email:i.user_email,avatar_url:i.user_avatar_url},this.onAuthChange?.(this.user)}catch{localStorage.removeItem("tack_session")}}signIn(){return new Promise((e,t)=>{let i=this.apiUrl.replace(/\/api$/,""),n=window.open(`${i}/auth/widget`,"tack-auth","width=500,height=600,popup=yes");if(!n){t(new Error("Popup blocked"));return}let r=new URL(this.apiUrl).origin,a=o=>{if(o.data?.type!=="tack:auth"||o.origin!==r)return;window.removeEventListener("message",a),clearInterval(s);let{token:c,user:d}=o.data;this.sessionToken=c,this.user={id:d.user_id,name:d.user_name,email:d.user_email,avatar_url:d.user_avatar_url},localStorage.setItem("tack_session",c),this.onAuthChange?.(this.user),e(this.user)};window.addEventListener("message",a);let s=setInterval(()=>{n.closed&&(clearInterval(s),window.removeEventListener("message",a),this.user||t(new Error("Auth popup closed")))},500)})}signOut(){this.sessionToken&&fetch(`${this.apiUrl}/auth/widget-session`,{method:"DELETE",headers:{Authorization:`Bearer ${this.sessionToken}`}}).catch(()=>{}),this.sessionToken=null,this.user=null,localStorage.removeItem("tack_session"),this.onAuthChange?.(null)}getUser(){return this.user}getSessionToken(){return this.sessionToken}isAuthenticated(){return this.user!==null}setOnAuthChange(e){this.onAuthChange=e}};function I(){return`
2
2
  * {
3
3
  box-sizing: border-box;
4
4
  }
@@ -1581,7 +1581,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1581
1581
  transform: translateY(0);
1582
1582
  }
1583
1583
  }
1584
- `}var x=class{constructor(e){this.enabled=!1;this.highlightedElement=null;this.highlight=null;this.scrim=null;this.cursor=null;this.styleElement=null;this.cursorRAF=null;this.cursorX=0;this.cursorY=0;this.targetX=0;this.targetY=0;this.settleTimer=null;this.pendingTarget=null;this.callback=e,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.onClick=this.onClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.animateCursor=this.animateCursor.bind(this)}enable(){this.enabled||(this.enabled=!0,document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mousedown",this.onMouseDown,!0),document.addEventListener("click",this.onClick,!0),document.addEventListener("keydown",this.onKeyDown),this.scrim=document.createElement("div"),this.scrim.style.cssText=`
1584
+ `}var w=class{constructor(e){this.enabled=!1;this.highlightedElement=null;this.highlight=null;this.scrim=null;this.cursor=null;this.styleElement=null;this.cursorRAF=null;this.cursorX=0;this.cursorY=0;this.targetX=0;this.targetY=0;this.settleTimer=null;this.pendingTarget=null;this.callback=e,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.onClick=this.onClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.animateCursor=this.animateCursor.bind(this)}enable(){this.enabled||(this.enabled=!0,document.addEventListener("mousemove",this.onMouseMove),document.addEventListener("mousedown",this.onMouseDown,!0),document.addEventListener("click",this.onClick,!0),document.addEventListener("keydown",this.onKeyDown),this.scrim=document.createElement("div"),this.scrim.style.cssText=`
1585
1585
  position: fixed;
1586
1586
  inset: 0;
1587
1587
  background: rgba(0, 0, 0, 0.03);
@@ -1620,7 +1620,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1620
1620
  `,this.cursor.textContent="+",document.body.appendChild(this.cursor),requestAnimationFrame(()=>{this.cursor&&(this.cursor.style.opacity="1")}),this.styleElement=document.createElement("style"),this.styleElement.textContent=`
1621
1621
  body, body *:not(#tack-widget) { cursor: none !important; }
1622
1622
  #tack-widget, #tack-widget * { cursor: default !important; }
1623
- `,document.head.appendChild(this.styleElement),this.cursorRAF=requestAnimationFrame(this.animateCursor))}disable(){this.enabled&&(this.enabled=!1,document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mousedown",this.onMouseDown,!0),document.removeEventListener("click",this.onClick,!0),document.removeEventListener("keydown",this.onKeyDown),this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.highlight&&(this.highlight.remove(),this.highlight=null),this.scrim&&(this.scrim.remove(),this.scrim=null),this.cursor&&(this.cursor.remove(),this.cursor=null),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.cursorRAF&&(cancelAnimationFrame(this.cursorRAF),this.cursorRAF=null),this.highlightedElement=null,this.pendingTarget=null)}animateCursor(){this.cursorX+=(this.targetX-this.cursorX)*.2,this.cursorY+=(this.targetY-this.cursorY)*.2,this.cursor&&(this.cursor.style.left=`${this.cursorX}px`,this.cursor.style.top=`${this.cursorY}px`),this.cursorRAF=requestAnimationFrame(this.animateCursor)}onMouseDown(e){e.target.closest("#tack-widget")||(e.preventDefault(),e.stopPropagation())}onMouseMove(e){this.targetX=e.clientX,this.targetY=e.clientY;let t=e.target;if(t.closest("#tack-widget")){this.clearHighlight(),this.cursor&&(this.cursor.style.opacity="0");return}this.cursor&&this.cursor.style.opacity==="0"&&(this.cursor.style.opacity="1"),t!==this.pendingTarget&&t!==this.highlightedElement&&(this.pendingTarget=t,this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.pendingTarget&&this.pendingTarget!==this.highlightedElement&&this.showHighlight(this.pendingTarget),this.pendingTarget=null},150))}showHighlight(e){if(this.highlightedElement=e,this.highlight){let t=e.getBoundingClientRect(),i=3;this.highlight.style.left=`${t.left-i}px`,this.highlight.style.top=`${t.top-i}px`,this.highlight.style.width=`${t.width+i*2}px`,this.highlight.style.height=`${t.height+i*2}px`,this.highlight.style.opacity="1";let r=window.getComputedStyle(e).borderRadius;this.highlight.style.borderRadius=r&&r!=="0px"?r:"6px"}}onClick(e){if(e.target.closest("#tack-widget"))return;e.preventDefault(),e.stopPropagation();let t=e.target,i=t.getBoundingClientRect(),n=(e.clientX-i.left)/i.width,r=(e.clientY-i.top)/i.height,a=this.generateAnchor(t,n,r);this.callback({element:t,anchor:a}),this.clearHighlight()}onKeyDown(e){e.key==="Escape"&&this.disable()}clearHighlight(){this.highlightedElement=null,this.pendingTarget=null,this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.highlight&&(this.highlight.style.opacity="0")}generateAnchor(e,t,i){return{cssSelector:this.generateCssSelector(e),xpath:this.generateXPath(e),textQuote:this.generateTextQuote(e),contentHash:this.generateContentHash(e),relativeX:t,relativeY:i,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight}}generateCssSelector(e){if(e.id&&!this.isDynamicId(e.id))return`#${CSS.escape(e.id)}`;let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase();if(i.className&&typeof i.className=="string"){let o=i.className.trim().split(/\s+/).filter(c=>!this.isDynamicClass(c));o.length>0&&(n+="."+o.slice(0,2).map(c=>CSS.escape(c)).join("."))}let r=i.getAttribute("data-testid")||i.getAttribute("data-test-id");r&&(n+=`[data-testid="${CSS.escape(r)}"]`);let a=i.parentElement;if(a){let o=Array.from(a.children).filter(c=>c.tagName===i.tagName);if(o.length>1){let c=o.indexOf(i)+1;n+=`:nth-child(${c})`}}t.unshift(n);let s=t.join(" > ");try{if(document.querySelectorAll(s).length===1)return s}catch{}i=a}return t.join(" > ")}generateXPath(e){let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase(),r=i.parentElement;if(r){let a=Array.from(r.children).filter(s=>s.tagName===i.tagName);if(a.length>1){let s=a.indexOf(i)+1;n+=`[${s}]`}}t.unshift(n),i=r}return"//"+t.join("/")}generateTextQuote(e){let t=e.textContent?.trim();if(!t||t.length===0||t.length>500)return null;let i=e.parentElement,n="",r="";if(i){let a=i.textContent||"",s=a.indexOf(t);s>0&&(n=a.slice(Math.max(0,s-32),s).trim());let o=s+t.length;o<a.length&&(r=a.slice(o,o+32).trim())}return{prefix:n,exact:t.slice(0,200),suffix:r}}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}isDynamicId(e){return/^[:_]/.test(e)||/[0-9]{5,}/.test(e)||/^(ember|react|vue|ng-|_)[0-9]+/.test(e)||/^[a-f0-9]{8,}$/i.test(e)}isDynamicClass(e){return e.startsWith("tack-")||/^css-[a-z0-9]+$/i.test(e)||/^sc-[a-z]+$/i.test(e)||/^emotion-[0-9]+$/i.test(e)||/^_[a-zA-Z0-9]{5,}$/.test(e)||/^[a-z]{1,3}[A-Z][a-zA-Z0-9]{10,}$/.test(e)}};async function _(l,e,t){let i=(await import("html2canvas")).default;try{if(l){let c=document.querySelector(l);if(c){let d=c.getBoundingClientRect(),h=20;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,x:Math.max(0,d.left+window.scrollX-h),y:Math.max(0,d.top+window.scrollY-h),width:Math.min(d.width+h*2,600),height:Math.min(d.height+h*2,400)})).toDataURL("image/png",.8)}}let n=e/100*document.documentElement.scrollWidth,r=t/100*document.documentElement.scrollHeight,a=400,s=300;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,x:Math.max(0,n-a/2),y:Math.max(0,r-s/2),width:a,height:s})).toDataURL("image/png",.8)}catch(n){console.warn("Tack: Screenshot capture failed",n);return}}var w=class{constructor(e,t){this.onHide=null;this.onSignIn=null;this.currentTarget=null;this.isSubmitting=!1;this.capturedScreenshot=void 0;this.highlightElement=null;this.isVisible=!1;this.currentUser=null;this.container=e,this.onSubmit=t,this.form=this.createForm(),this.container.appendChild(this.form),this.highlightElement=document.createElement("div"),this.highlightElement.className="tack-form-highlight",this.highlightElement.style.cssText=`
1623
+ `,document.head.appendChild(this.styleElement),this.cursorRAF=requestAnimationFrame(this.animateCursor))}disable(){this.enabled&&(this.enabled=!1,document.removeEventListener("mousemove",this.onMouseMove),document.removeEventListener("mousedown",this.onMouseDown,!0),document.removeEventListener("click",this.onClick,!0),document.removeEventListener("keydown",this.onKeyDown),this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.highlight&&(this.highlight.remove(),this.highlight=null),this.scrim&&(this.scrim.remove(),this.scrim=null),this.cursor&&(this.cursor.remove(),this.cursor=null),this.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.cursorRAF&&(cancelAnimationFrame(this.cursorRAF),this.cursorRAF=null),this.highlightedElement=null,this.pendingTarget=null)}animateCursor(){this.cursorX+=(this.targetX-this.cursorX)*.2,this.cursorY+=(this.targetY-this.cursorY)*.2,this.cursor&&(this.cursor.style.left=`${this.cursorX}px`,this.cursor.style.top=`${this.cursorY}px`),this.cursorRAF=requestAnimationFrame(this.animateCursor)}onMouseDown(e){e.target.closest("#tack-widget")||(e.preventDefault(),e.stopPropagation())}onMouseMove(e){this.targetX=e.clientX,this.targetY=e.clientY;let t=e.target;if(t.closest("#tack-widget")){this.clearHighlight(),this.cursor&&(this.cursor.style.opacity="0");return}this.cursor&&this.cursor.style.opacity==="0"&&(this.cursor.style.opacity="1"),t!==this.pendingTarget&&t!==this.highlightedElement&&(this.pendingTarget=t,this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.pendingTarget&&this.pendingTarget!==this.highlightedElement&&this.showHighlight(this.pendingTarget),this.pendingTarget=null},150))}showHighlight(e){if(this.highlightedElement=e,this.highlight){let t=e.getBoundingClientRect(),i=3;this.highlight.style.left=`${t.left-i}px`,this.highlight.style.top=`${t.top-i}px`,this.highlight.style.width=`${t.width+i*2}px`,this.highlight.style.height=`${t.height+i*2}px`,this.highlight.style.opacity="1";let r=window.getComputedStyle(e).borderRadius;this.highlight.style.borderRadius=r&&r!=="0px"?r:"6px"}}onClick(e){if(e.target.closest("#tack-widget"))return;e.preventDefault(),e.stopPropagation();let t=e.target,i=t.getBoundingClientRect(),n=(e.clientX-i.left)/i.width,r=(e.clientY-i.top)/i.height,a=this.generateAnchor(t,n,r);this.callback({element:t,anchor:a}),this.clearHighlight()}onKeyDown(e){e.key==="Escape"&&this.disable()}clearHighlight(){this.highlightedElement=null,this.pendingTarget=null,this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.highlight&&(this.highlight.style.opacity="0")}generateAnchor(e,t,i){return{cssSelector:this.generateCssSelector(e),xpath:this.generateXPath(e),textQuote:this.generateTextQuote(e),contentHash:this.generateContentHash(e),relativeX:t,relativeY:i,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight}}generateCssSelector(e){if(e.id&&!this.isDynamicId(e.id))return`#${CSS.escape(e.id)}`;let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase();if(i.className&&typeof i.className=="string"){let o=i.className.trim().split(/\s+/).filter(c=>!this.isDynamicClass(c));o.length>0&&(n+="."+o.slice(0,2).map(c=>CSS.escape(c)).join("."))}let r=i.getAttribute("data-testid")||i.getAttribute("data-test-id");r&&(n+=`[data-testid="${CSS.escape(r)}"]`);let a=i.parentElement;if(a){let o=Array.from(a.children).filter(c=>c.tagName===i.tagName);if(o.length>1){let c=o.indexOf(i)+1;n+=`:nth-child(${c})`}}t.unshift(n);let s=t.join(" > ");try{if(document.querySelectorAll(s).length===1)return s}catch{}i=a}return t.join(" > ")}generateXPath(e){let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase(),r=i.parentElement;if(r){let a=Array.from(r.children).filter(s=>s.tagName===i.tagName);if(a.length>1){let s=a.indexOf(i)+1;n+=`[${s}]`}}t.unshift(n),i=r}return"//"+t.join("/")}generateTextQuote(e){let t=e.textContent?.trim();if(!t||t.length===0||t.length>500)return null;let i=e.parentElement,n="",r="";if(i){let a=i.textContent||"",s=a.indexOf(t);s>0&&(n=a.slice(Math.max(0,s-32),s).trim());let o=s+t.length;o<a.length&&(r=a.slice(o,o+32).trim())}return{prefix:n,exact:t.slice(0,200),suffix:r}}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}isDynamicId(e){return/^[:_]/.test(e)||/[0-9]{5,}/.test(e)||/^(ember|react|vue|ng-|_)[0-9]+/.test(e)||/^[a-f0-9]{8,}$/i.test(e)}isDynamicClass(e){return e.startsWith("tack-")||/^css-[a-z0-9]+$/i.test(e)||/^sc-[a-z]+$/i.test(e)||/^emotion-[0-9]+$/i.test(e)||/^_[a-zA-Z0-9]{5,}$/.test(e)||/^[a-z]{1,3}[A-Z][a-zA-Z0-9]{10,}$/.test(e)}};function W(l){return l.id==="tack-widget"||l.classList?.contains("tack-form-highlight")}async function U(l,e,t){let i=(await import("html2canvas")).default;try{if(l){let c=document.querySelector(l);if(c){let d=c.getBoundingClientRect(),p=20;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,x:Math.max(0,d.left+window.scrollX-p),y:Math.max(0,d.top+window.scrollY-p),width:Math.min(d.width+p*2,600),height:Math.min(d.height+p*2,400)})).toDataURL("image/png",.8)}}let n=e/100*document.documentElement.scrollWidth,r=t/100*document.documentElement.scrollHeight,a=400,s=300;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,ignoreElements:W,x:Math.max(0,n-a/2),y:Math.max(0,r-s/2),width:a,height:s})).toDataURL("image/png",.8)}catch(n){console.warn("Tack: Screenshot capture failed",n);return}}var y=class{constructor(e,t){this.onHide=null;this.onSignIn=null;this.currentTarget=null;this.isSubmitting=!1;this.capturedScreenshot=void 0;this.highlightElement=null;this.isVisible=!1;this.currentUser=null;this.container=e,this.onSubmit=t,this.form=this.createForm(),this.container.appendChild(this.form),this.highlightElement=document.createElement("div"),this.highlightElement.className="tack-form-highlight",this.highlightElement.style.cssText=`
1624
1624
  position: fixed;
1625
1625
  pointer-events: none;
1626
1626
  border: 2px solid #14B8A6;
@@ -1651,19 +1651,19 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1651
1651
  Sign in
1652
1652
  </button>
1653
1653
  </div>
1654
- `,this.attachFormListeners(e)}attachFormListeners(e){e.addEventListener("mousedown",i=>i.stopPropagation()),e.addEventListener("click",i=>i.stopPropagation()),e.querySelector(".tack-sign-in-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.onSignIn?.()}),e.querySelector(".tack-form-pill-send")?.addEventListener("click",i=>{i.stopPropagation(),this.handleSubmit()});let t=e.querySelector("#tack-comment-content");t&&(t.addEventListener("input",()=>{this.autoExpandTextarea(t);let i=e.querySelector(".tack-form-pill-send");i&&i.classList.toggle("active",t.value.trim().length>0)}),t.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSubmit())})),e.addEventListener("keydown",i=>{let n=i;n.key==="Escape"&&(n.preventDefault(),this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await _(e.anchor.cssSelector,e.anchor.relativeX*100,e.anchor.relativeY*100),e.element&&this.highlightElement){let o=e.element.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.left=`${o.left-4}px`,this.highlightElement.style.top=`${o.top-4}px`,this.highlightElement.style.width=`${o.width+8}px`,this.highlightElement.style.height=`${o.height+8}px`}let t,i;if(e.element){let o=e.element.getBoundingClientRect();t=o.right+12,i=o.top;let c=300;t+c>window.innerWidth-380&&(t=o.left-c-12)}else t=e.anchor.relativeX*window.innerWidth+20,i=e.anchor.relativeY*window.innerHeight;let n=300,r=52,a=Math.min(t,window.innerWidth-n-380),s=Math.min(i,window.innerHeight-r-20);a=Math.max(20,a),s=Math.max(20,s),this.form.style.left=`${a}px`,this.form.style.top=`${s}px`,this.form.classList.add("visible"),setTimeout(()=>{this.form.querySelector("#tack-comment-content")?.focus()},50)}hide(){if(!this.isVisible)return;this.isVisible=!1,this.form.classList.remove("visible"),this.currentTarget=null,this.capturedScreenshot=void 0;let e=this.form.querySelector("#tack-comment-content");e&&(e.value="",e.style.height="28px",e.style.overflowY="hidden");let t=this.form.querySelector(".tack-form-pill-send");t&&t.classList.remove("active"),this.highlightElement&&(this.highlightElement.style.display="none"),this.onHide?.()}isFormVisible(){return this.isVisible}autoExpandTextarea(e){e.style.height="auto";let t=120;e.style.height=`${Math.min(e.scrollHeight,t)}px`,e.style.overflowY=e.scrollHeight>t?"auto":"hidden"}async handleSubmit(){if(this.isSubmitting||!this.currentTarget)return;let e=this.form.querySelector("#tack-comment-content")?.value.trim();if(!e)return;let t;if(this.currentUser)t=this.currentUser.name;else if(t=this.form.querySelector("#tack-author-name")?.value.trim()||"",!t)return;this.isSubmitting=!0;let i=this.form.querySelector(".tack-form-pill-send");i&&i.classList.add("sending");try{this.currentUser||localStorage.setItem("tack_author_name",t);let n={content:e,authorName:t,anchor:this.currentTarget.anchor,screenshot:this.capturedScreenshot};this.hide(),await this.onSubmit(n)}catch(n){console.error("[Tack] Submit failed:",n)}finally{this.isSubmitting=!1,i&&i.classList.remove("sending")}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var M=[["#818CF8","#6366F1"],["#A78BFA","#7C3AED"],["#F472B6","#EC4899"],["#FBBF24","#F59E0B"],["#34D399","#10B981"],["#60A5FA","#3B82F6"],["#F87171","#EF4444"],["#2DD4BF","#14B8A6"]],I=M.map(([,l])=>l);function D(l){let e=0;for(let t=0;t<l.length;t++)e=l.charCodeAt(t)+((e<<5)-e);return Math.abs(e)}function U(l){return I[D(l)%I.length]}function P(l){let[e,t]=M[D(l)%M.length];return`linear-gradient(135deg, ${e} 0%, ${t} 100%)`}function p(l){let e=l.trim().split(/\s+/);return e.length>=2?(e[0][0]+e[e.length-1][0]).toUpperCase():l.slice(0,2).toUpperCase()}function u(l,e,t,i=""){let n=Math.round(t*.38),r=i?` ${i}`:"";return e?`<img
1655
- src="${e}"
1656
- alt="${p(l)}"
1654
+ `,this.attachFormListeners(e)}attachFormListeners(e){e.addEventListener("mousedown",i=>i.stopPropagation()),e.addEventListener("click",i=>i.stopPropagation()),e.querySelector(".tack-sign-in-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.onSignIn?.()}),e.querySelector(".tack-form-pill-send")?.addEventListener("click",i=>{i.stopPropagation(),this.handleSubmit()});let t=e.querySelector("#tack-comment-content");t&&(t.addEventListener("input",()=>{this.autoExpandTextarea(t);let i=e.querySelector(".tack-form-pill-send");i&&i.classList.toggle("active",t.value.trim().length>0)}),t.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSubmit())})),e.addEventListener("keydown",i=>{let n=i;n.key==="Escape"&&(n.preventDefault(),this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await U(e.anchor.cssSelector,e.anchor.relativeX*100,e.anchor.relativeY*100),e.element&&this.highlightElement){let o=e.element.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.left=`${o.left-4}px`,this.highlightElement.style.top=`${o.top-4}px`,this.highlightElement.style.width=`${o.width+8}px`,this.highlightElement.style.height=`${o.height+8}px`}let t,i;if(e.element){let o=e.element.getBoundingClientRect();t=o.right+12,i=o.top;let c=300;t+c>window.innerWidth-380&&(t=o.left-c-12)}else t=e.anchor.relativeX*window.innerWidth+20,i=e.anchor.relativeY*window.innerHeight;let n=300,r=52,a=Math.min(t,window.innerWidth-n-380),s=Math.min(i,window.innerHeight-r-20);a=Math.max(20,a),s=Math.max(20,s),this.form.style.left=`${a}px`,this.form.style.top=`${s}px`,this.form.classList.add("visible"),setTimeout(()=>{this.form.querySelector("#tack-comment-content")?.focus()},50)}hide(){if(!this.isVisible)return;this.isVisible=!1,this.form.classList.remove("visible"),this.currentTarget=null,this.capturedScreenshot=void 0;let e=this.form.querySelector("#tack-comment-content");e&&(e.value="",e.style.height="28px",e.style.overflowY="hidden");let t=this.form.querySelector(".tack-form-pill-send");t&&t.classList.remove("active"),this.highlightElement&&(this.highlightElement.style.display="none"),this.onHide?.()}isFormVisible(){return this.isVisible}autoExpandTextarea(e){e.style.height="auto";let t=120;e.style.height=`${Math.min(e.scrollHeight,t)}px`,e.style.overflowY=e.scrollHeight>t?"auto":"hidden"}async handleSubmit(){if(this.isSubmitting||!this.currentTarget)return;let e=this.form.querySelector("#tack-comment-content")?.value.trim();if(!e)return;let t;if(this.currentUser)t=this.currentUser.name;else if(t=this.form.querySelector("#tack-author-name")?.value.trim()||"",!t)return;this.isSubmitting=!0;let i=this.form.querySelector(".tack-form-pill-send");i&&i.classList.add("sending");try{this.currentUser||localStorage.setItem("tack_author_name",t);let n={content:e,authorName:t,anchor:this.currentTarget.anchor,screenshot:this.capturedScreenshot};this.hide(),await this.onSubmit(n)}catch(n){console.error("[Tack] Submit failed:",n)}finally{this.isSubmitting=!1,i&&i.classList.remove("sending")}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var M=class{constructor(){this.cache=new Map;this.pending=new Map}get(e){return this.cache.get(e)||e}async preload(e){let t=[...new Set(e.filter(i=>!!i&&!this.cache.has(i)))];t.length!==0&&await Promise.all(t.map(i=>this.resolve(i)))}resolve(e){if(this.cache.has(e))return Promise.resolve(this.cache.get(e));if(this.pending.has(e))return this.pending.get(e);let t=fetch(e,{mode:"cors"}).then(i=>{if(!i.ok)throw new Error(`${i.status}`);return i.blob()}).then(i=>{let n=URL.createObjectURL(i);return this.cache.set(e,n),this.pending.delete(e),n}).catch(()=>(this.pending.delete(e),e));return this.pending.set(e,t),t}destroy(){this.cache.forEach(e=>URL.revokeObjectURL(e)),this.cache.clear(),this.pending.clear()}},h=new M;var R=[["#818CF8","#6366F1"],["#A78BFA","#7C3AED"],["#F472B6","#EC4899"],["#FBBF24","#F59E0B"],["#34D399","#10B981"],["#60A5FA","#3B82F6"],["#F87171","#EF4444"],["#2DD4BF","#14B8A6"]],D=R.map(([,l])=>l);function z(l){let e=0;for(let t=0;t<l.length;t++)e=l.charCodeAt(t)+((e<<5)-e);return Math.abs(e)}function O(l){return D[z(l)%D.length]}function $(l){let[e,t]=R[z(l)%R.length];return`linear-gradient(135deg, ${e} 0%, ${t} 100%)`}function u(l){let e=l.trim().split(/\s+/);return e.length>=2?(e[0][0]+e[e.length-1][0]).toUpperCase():l.slice(0,2).toUpperCase()}function m(l,e,t,i=""){let n=Math.round(t*.38),r=i?` ${i}`:"";return e?`<img
1655
+ src="${h.get(e)}"
1656
+ alt="${u(l)}"
1657
1657
  class="tack-avatar-img${r}"
1658
1658
  style="width:${t}px;height:${t}px;border-radius:50%;object-fit:cover;"
1659
1659
  onerror="this.style.display='none';this.nextElementSibling.style.display='flex'"
1660
1660
  /><div
1661
1661
  class="tack-avatar-fallback${r}"
1662
- style="display:none;width:${t}px;height:${t}px;border-radius:50%;background:${U(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
1663
- >${p(l)}</div>`:`<div
1662
+ style="display:none;width:${t}px;height:${t}px;border-radius:50%;background:${O(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
1663
+ >${u(l)}</div>`:`<div
1664
1664
  class="tack-avatar-fallback${r}"
1665
- style="display:flex;width:${t}px;height:${t}px;border-radius:50%;background:${U(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
1666
- >${p(l)}</div>`}var z="tack_panel_filters";function q(){try{let l=localStorage.getItem(z);if(l){let e=JSON.parse(l);return{sort:e.sort||"date",showResolved:e.showResolved??!1,onlyYourThreads:e.onlyYourThreads??!1,onlyCurrentPage:e.onlyCurrentPage??!1}}}catch{}return{sort:"date",showResolved:!1,onlyYourThreads:!1,onlyCurrentPage:!1}}function O(l){try{localStorage.setItem(z,JSON.stringify(l))}catch{}}var y=class{constructor(e,t){this.comments=[];this.searchQuery="";this.searchTimer=null;this.highlightedId=null;this.filterDropdownOpen=!1;this.moreDropdownOpen=!1;this.currentUser=null;this.projectId="";this.container=e,this.callbacks=t,this.filters=q(),this.readCommentIds=this.loadReadIds(),this.strip=this.createPanelStrip(),this.panel=this.strip.querySelector(".tack-panel"),this.container.appendChild(this.strip)}setUser(e){this.currentUser=e}setProjectId(e){this.projectId=e,this.readCommentIds=this.loadReadIds()}loadReadIds(){try{let e=`tack_read_${this.projectId}`,t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}saveReadIds(){try{let e=`tack_read_${this.projectId}`;localStorage.setItem(e,JSON.stringify([...this.readCommentIds]))}catch{}}markAsRead(e){this.readCommentIds.has(e)||(this.readCommentIds.add(e),this.saveReadIds())}markVisibleAsRead(){if(!this.isOpen())return;let e=this.getFilteredComments(),t=!1;for(let i of e)this.readCommentIds.has(i.id)||(this.readCommentIds.add(i.id),t=!0);t&&this.saveReadIds()}isRead(e){return this.readCommentIds.has(e)}createPanelStrip(){let e=document.createElement("div");e.className="tack-panel-strip",e.innerHTML=`
1665
+ style="display:flex;width:${t}px;height:${t}px;border-radius:50%;background:${O(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
1666
+ >${u(l)}</div>`}var B="tack_panel_filters";function V(){try{let l=localStorage.getItem(B);if(l){let e=JSON.parse(l);return{sort:e.sort||"date",showResolved:e.showResolved??!1,onlyYourThreads:e.onlyYourThreads??!1,onlyCurrentPage:e.onlyCurrentPage??!1}}}catch{}return{sort:"date",showResolved:!1,onlyYourThreads:!1,onlyCurrentPage:!1}}function j(l){try{localStorage.setItem(B,JSON.stringify(l))}catch{}}var C=class{constructor(e,t){this.comments=[];this.searchQuery="";this.searchTimer=null;this.highlightedId=null;this.filterDropdownOpen=!1;this.moreDropdownOpen=!1;this.currentUser=null;this.projectId="";this.container=e,this.callbacks=t,this.filters=V(),this.readCommentIds=this.loadReadIds(),this.strip=this.createPanelStrip(),this.panel=this.strip.querySelector(".tack-panel"),this.container.appendChild(this.strip)}setUser(e){this.currentUser=e}setProjectId(e){this.projectId=e,this.readCommentIds=this.loadReadIds()}loadReadIds(){try{let e=`tack_read_${this.projectId}`,t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}saveReadIds(){try{let e=`tack_read_${this.projectId}`;localStorage.setItem(e,JSON.stringify([...this.readCommentIds]))}catch{}}markAsRead(e){this.readCommentIds.has(e)||(this.readCommentIds.add(e),this.saveReadIds())}markVisibleAsRead(){if(!this.isOpen())return;let e=this.getFilteredComments(),t=!1;for(let i of e)this.readCommentIds.has(i.id)||(this.readCommentIds.add(i.id),t=!0);t&&this.saveReadIds()}isRead(e){return this.readCommentIds.has(e)}createPanelStrip(){let e=document.createElement("div");e.className="tack-panel-strip",e.innerHTML=`
1667
1667
  <div class="tack-panel" role="complementary" aria-label="Comments panel">
1668
1668
  <div class="tack-panel-header">
1669
1669
  <button class="tack-panel-close" aria-label="Close comments panel">
@@ -1744,7 +1744,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1744
1744
  <span>Only current page</span>
1745
1745
  <span class="tack-dropdown-toggle-switch ${t.onlyCurrentPage?"on":""}"><span class="tack-dropdown-toggle-knob"></span></span>
1746
1746
  </button>
1747
- `,e.setAttribute("data-state","open"),e.querySelectorAll(".tack-dropdown-item").forEach(r=>{r.addEventListener("click",a=>{a.stopPropagation();let s=r.dataset.action;s.startsWith("sort-")?this.filters.sort=s.replace("sort-",""):s==="showResolved"?this.filters.showResolved=!this.filters.showResolved:s==="onlyYourThreads"?this.filters.onlyYourThreads=!this.filters.onlyYourThreads:s==="onlyCurrentPage"&&(this.filters.onlyCurrentPage=!this.filters.onlyCurrentPage),O(this.filters),this.updateFilterBadge(),this.renderFilterDropdown(),this.renderComments()})})}renderMoreDropdown(){let e=this.strip.querySelector(".tack-panel-more-dropdown");if(!this.moreDropdownOpen){e.setAttribute("data-state","closed"),e.innerHTML="";return}e.innerHTML=`
1747
+ `,e.setAttribute("data-state","open"),e.querySelectorAll(".tack-dropdown-item").forEach(r=>{r.addEventListener("click",a=>{a.stopPropagation();let s=r.dataset.action;s.startsWith("sort-")?this.filters.sort=s.replace("sort-",""):s==="showResolved"?this.filters.showResolved=!this.filters.showResolved:s==="onlyYourThreads"?this.filters.onlyYourThreads=!this.filters.onlyYourThreads:s==="onlyCurrentPage"&&(this.filters.onlyCurrentPage=!this.filters.onlyCurrentPage),j(this.filters),this.updateFilterBadge(),this.renderFilterDropdown(),this.renderComments()})})}renderMoreDropdown(){let e=this.strip.querySelector(".tack-panel-more-dropdown");if(!this.moreDropdownOpen){e.setAttribute("data-state","closed"),e.innerHTML="";return}e.innerHTML=`
1748
1748
  <button class="tack-dropdown-item" data-action="share">
1749
1749
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1750
1750
  <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"></path>
@@ -1753,7 +1753,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1753
1753
  </svg>
1754
1754
  <span>Copy share link</span>
1755
1755
  </button>
1756
- `,e.setAttribute("data-state","open"),e.querySelector('[data-action="share"]').addEventListener("click",t=>{t.stopPropagation(),this.moreDropdownOpen=!1,this.renderMoreDropdown(),this.callbacks.onShare?.()})}updateFilterBadge(){let e=this.strip.querySelector(".tack-panel-filter-badge"),t=this.strip.querySelector(".tack-panel-filter-btn"),i=0;this.filters.showResolved&&i++,this.filters.onlyYourThreads&&i++,this.filters.onlyCurrentPage&&i++,i>0?(e.textContent=String(i),e.style.display="flex",t.classList.add("filter-active")):(e.style.display="none",t.classList.remove("filter-active"))}show(){this.strip.classList.add("open"),this.updateFilterBadge(),setTimeout(()=>this.markVisibleAsRead(),1500)}hide(){this.strip.classList.remove("open"),this.filterDropdownOpen=!1,this.moreDropdownOpen=!1,this.renderFilterDropdown(),this.renderMoreDropdown()}toggle(){this.strip.classList.contains("open")?this.hide():this.show()}isOpen(){return this.strip.classList.contains("open")}render(e){this.comments=e,this.renderComments(),this.isOpen()&&setTimeout(()=>this.markVisibleAsRead(),1500)}renderPresence(e){let t=this.panel.querySelector(".tack-presence-bar");if(!t){t=document.createElement("div"),t.className="tack-presence-bar";let s=this.panel.querySelector(".tack-panel-header");s&&s.parentNode?.insertBefore(t,s.nextSibling)}if(e.length===0){t.style.display="none";return}t.style.display="flex";let i=5,n=e.slice(0,i),r=e.length-i,a='<div class="tack-presence-avatars">';n.forEach(s=>{a+=`<div class="tack-presence-avatar" title="${this.escapeHtml(s.name)}">${u(s.name,s.avatar_url,24)}</div>`}),r>0&&(a+=`<div class="tack-presence-overflow">+${r}</div>`),a+="</div>",a+=`<span class="tack-presence-label">${e.length} viewing</span>`,t.innerHTML=a}renderComments(){let e=this.panel.querySelector(".tack-panel-content"),t=this.getFilteredComments();if(t.length===0){if(this.searchQuery){let i=(this.filters.showResolved?1:0)+(this.filters.onlyYourThreads?1:0)+(this.filters.onlyCurrentPage?1:0);e.innerHTML=`
1756
+ `,e.setAttribute("data-state","open"),e.querySelector('[data-action="share"]').addEventListener("click",t=>{t.stopPropagation(),this.moreDropdownOpen=!1,this.renderMoreDropdown(),this.callbacks.onShare?.()})}updateFilterBadge(){let e=this.strip.querySelector(".tack-panel-filter-badge"),t=this.strip.querySelector(".tack-panel-filter-btn"),i=0;this.filters.showResolved&&i++,this.filters.onlyYourThreads&&i++,this.filters.onlyCurrentPage&&i++,i>0?(e.textContent=String(i),e.style.display="flex",t.classList.add("filter-active")):(e.style.display="none",t.classList.remove("filter-active"))}show(){this.strip.classList.add("open"),this.updateFilterBadge(),setTimeout(()=>this.markVisibleAsRead(),1500)}hide(){this.strip.classList.remove("open"),this.filterDropdownOpen=!1,this.moreDropdownOpen=!1,this.renderFilterDropdown(),this.renderMoreDropdown()}toggle(){this.strip.classList.contains("open")?this.hide():this.show()}isOpen(){return this.strip.classList.contains("open")}render(e){this.comments=e,this.renderComments(),this.isOpen()&&setTimeout(()=>this.markVisibleAsRead(),1500)}renderPresence(e){let t=this.panel.querySelector(".tack-presence-bar");if(!t){t=document.createElement("div"),t.className="tack-presence-bar";let s=this.panel.querySelector(".tack-panel-header");s&&s.parentNode?.insertBefore(t,s.nextSibling)}if(e.length===0){t.style.display="none";return}t.style.display="flex";let i=5,n=e.slice(0,i),r=e.length-i,a='<div class="tack-presence-avatars">';n.forEach(s=>{a+=`<div class="tack-presence-avatar" title="${this.escapeHtml(s.name)}">${m(s.name,s.avatar_url,24)}</div>`}),r>0&&(a+=`<div class="tack-presence-overflow">+${r}</div>`),a+="</div>",a+=`<span class="tack-presence-label">${e.length} viewing</span>`,t.innerHTML=a}renderComments(){let e=this.panel.querySelector(".tack-panel-content"),t=this.getFilteredComments();if(t.length===0){if(this.searchQuery){let i=(this.filters.showResolved?1:0)+(this.filters.onlyYourThreads?1:0)+(this.filters.onlyCurrentPage?1:0);e.innerHTML=`
1757
1757
  <div class="tack-empty">
1758
1758
  <div class="tack-empty-icon">
1759
1759
  <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
@@ -1788,7 +1788,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1788
1788
  <p class="tack-empty-title">No comments yet</p>
1789
1789
  <p class="tack-empty-subtitle">Click anywhere on the page to add feedback</p>
1790
1790
  </div>
1791
- `;e.querySelector(".tack-empty-reset")?.addEventListener("click",()=>{this.resetFilters()});return}e.innerHTML=t.map(i=>this.renderCommentRow(i)).join(""),e.querySelectorAll(".tack-comment-row").forEach(i=>{let n=i.dataset.id;i.addEventListener("click",()=>{this.markAsRead(n);let s=i.querySelector(".tack-unread-dot");s&&s.remove();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)});let r=i.querySelector(".tack-comment-row-resolve");r&&r.addEventListener("click",s=>{s.stopPropagation();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onResolve(n,!o.resolved)});let a=i.querySelector(".tack-comment-row-more");a&&a.addEventListener("click",s=>{s.stopPropagation();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)})})}hasActiveFilters(){return this.filters.showResolved||this.filters.onlyYourThreads||this.filters.onlyCurrentPage}describeActiveFilters(){let e=[];return this.filters.onlyYourThreads&&e.push("only your threads"),this.filters.onlyCurrentPage&&e.push("only current page"),this.filters.showResolved||e.push("resolved comments hidden"),e.length>0?e.join(", ").replace(/^./,t=>t.toUpperCase()):""}resetFilters(){this.filters={sort:"date",showResolved:!1,onlyYourThreads:!1,onlyCurrentPage:!1},this.searchQuery="";let e=this.strip.querySelector(".tack-panel-search");e&&(e.value="");let t=this.strip.querySelector(".tack-panel-search-clear");t&&(t.style.display="none"),O(this.filters),this.updateFilterBadge(),this.renderComments()}getCurrentPagePath(){return window.location.pathname+window.location.search}formatPagePath(e){if(!e||e==="/")return"Home";let t=e.split("?")[0].slice(1);return t.charAt(0).toUpperCase()+t.slice(1)}renderCommentRow(e){let t=e.id===this.highlightedId,i=this.formatTimeAgo(new Date(e.created_at)),n=this.getCurrentPagePath(),r=e.page_path===n,a=this.formatPagePath(e.page_path),s=!!e.screenshot_url,o=!this.isRead(e.id);return`
1791
+ `;e.querySelector(".tack-empty-reset")?.addEventListener("click",()=>{this.resetFilters()});return}e.innerHTML=t.map(i=>this.renderCommentRow(i)).join(""),e.querySelectorAll(".tack-comment-row").forEach(i=>{let n=i.dataset.id;i.addEventListener("click",()=>{this.markAsRead(n);let s=i.querySelector(".tack-unread-dot");s&&s.remove();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)});let r=i.querySelector(".tack-comment-row-resolve");r&&r.addEventListener("click",s=>{s.stopPropagation();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onResolve(n,!o.resolved)});let a=i.querySelector(".tack-comment-row-more");a&&a.addEventListener("click",s=>{s.stopPropagation();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)})})}hasActiveFilters(){return this.filters.showResolved||this.filters.onlyYourThreads||this.filters.onlyCurrentPage}describeActiveFilters(){let e=[];return this.filters.onlyYourThreads&&e.push("only your threads"),this.filters.onlyCurrentPage&&e.push("only current page"),this.filters.showResolved||e.push("resolved comments hidden"),e.length>0?e.join(", ").replace(/^./,t=>t.toUpperCase()):""}resetFilters(){this.filters={sort:"date",showResolved:!1,onlyYourThreads:!1,onlyCurrentPage:!1},this.searchQuery="";let e=this.strip.querySelector(".tack-panel-search");e&&(e.value="");let t=this.strip.querySelector(".tack-panel-search-clear");t&&(t.style.display="none"),j(this.filters),this.updateFilterBadge(),this.renderComments()}getCurrentPagePath(){return window.location.pathname}formatPagePath(e){if(!e||e==="/")return"Home";let t=e.split("?")[0].slice(1);return t.charAt(0).toUpperCase()+t.slice(1)}renderCommentRow(e){let t=e.id===this.highlightedId,i=this.formatTimeAgo(new Date(e.created_at)),n=this.getCurrentPagePath(),r=e.page_path===n,a=this.formatPagePath(e.page_path),s=!!e.screenshot_url,o=!this.isRead(e.id);return`
1792
1792
  <div class="tack-comment-row ${t?"highlighted":""}" data-id="${e.id}">
1793
1793
  <div class="tack-comment-row-actions">
1794
1794
  <button class="tack-comment-row-more" data-action="more" data-id="${e.id}" title="More actions">
@@ -1799,7 +1799,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1799
1799
  </button>
1800
1800
  </div>
1801
1801
  <div class="tack-comment-row-top">
1802
- ${u(e.author_name,e.author_avatar_url,32,"tack-comment-avatar")}
1802
+ ${m(e.author_name,e.author_avatar_url,32,"tack-comment-avatar")}
1803
1803
  ${o?'<span class="tack-unread-dot"></span>':""}
1804
1804
  </div>
1805
1805
  <div class="tack-comment-meta">
@@ -1813,7 +1813,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1813
1813
  <div class="tack-comment-content">${this.escapeHtml(e.content)}</div>
1814
1814
  </div>
1815
1815
  </div>
1816
- `}getFilteredComments(){let e=this.comments.filter(t=>!t.parent_id);if(this.filters.showResolved||(e=e.filter(t=>!t.resolved)),this.filters.onlyYourThreads&&this.currentUser){let t=this.currentUser.id,i=this.currentUser.name;e=e.filter(n=>!!(n.user_id===t||n.author_name===i||n.replies?.some(r=>r.user_id===t||r.author_name===i)))}if(this.filters.onlyCurrentPage){let t=this.getCurrentPagePath();e=e.filter(i=>i.page_path===t)}if(this.searchQuery){let t=this.searchQuery;e=e.filter(i=>!!(i.author_name.toLowerCase().includes(t)||i.content.toLowerCase().includes(t)||i.replies?.some(n=>n.content.toLowerCase().includes(t)||n.author_name.toLowerCase().includes(t))))}switch(this.filters.sort){case"unread":e.sort((t,i)=>{let n=this.isRead(t.id)?1:0,r=this.isRead(i.id)?1:0;return n!==r?n-r:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;case"replies":e.sort((t,i)=>{let n=t.replies?.length||0,r=i.replies?.length||0;return r!==n?r-n:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;default:e.sort((t,i)=>new Date(i.created_at).getTime()-new Date(t.created_at).getTime());break}return e}scrollToComment(e){this.highlightedId=e,this.renderComments(),this.panel.querySelector(`[data-id="${e}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.highlightedId=null,this.renderComments()},2e3)}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var C=class{resolve(e){if(!e)return{element:null,confidence:"none",method:"none"};if(e.cssSelector){let t=this.tryCssSelector(e);if(t.element)return t}if(e.xpath){let t=this.tryXPath(e);if(t.element)return t}if(e.textQuote){let t=this.tryTextQuote(e.textQuote);if(t.element)return t}if(e.textQuote){let t=this.tryFuzzySearch(e.textQuote);if(t.element)return t}return{element:null,confidence:"none",method:"none"}}calculatePinPosition(e,t){let i=e.getBoundingClientRect(),n=i.left+t.relativeX*i.width+window.scrollX,r=i.top+t.relativeY*i.height+window.scrollY;return{x:n,y:r}}tryCssSelector(e){try{let t=document.querySelector(e.cssSelector);return t?e.contentHash?this.generateContentHash(t)===e.contentHash?{element:t,confidence:"high",method:"css"}:{element:t,confidence:"medium",method:"css"}:{element:t,confidence:"high",method:"css"}:{element:null,confidence:"none",method:"css"}}catch{return{element:null,confidence:"none",method:"css"}}}tryXPath(e){try{let i=document.evaluate(e.xpath,document.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return i?e.contentHash?this.generateContentHash(i)===e.contentHash?{element:i,confidence:"high",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:null,confidence:"none",method:"xpath"}}catch{return{element:null,confidence:"none",method:"xpath"}}}tryTextQuote(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=t.nextNode();for(;i;){let n=i,r=n.textContent?.trim();if(r&&r.includes(e.exact)&&this.verifyContext(n,e))return{element:n,confidence:"high",method:"textQuote"};i=t.nextNode()}return{element:null,confidence:"none",method:"textQuote"}}tryFuzzySearch(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=null,n=e.exact.toLowerCase(),r=t.nextNode();for(;r;){let a=r,s=a.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let o=this.similarityScore(s,n);o>.7&&(!i||o>i.score)&&(i={element:a,score:o})}r=t.nextNode()}return i?{element:i.element,confidence:i.score>.9?"medium":"low",method:"fuzzy"}:{element:null,confidence:"none",method:"fuzzy"}}verifyContext(e,t){if(!t.prefix&&!t.suffix)return!0;let i=e.parentElement;if(!i)return!0;let n=i.textContent||"",r=e.textContent||"",a=n.indexOf(r);if(a===-1)return!0;if(t.prefix&&!n.slice(Math.max(0,a-50),a).trim().includes(t.prefix.slice(-20)))return!1;if(t.suffix){let s=a+r.length;if(!n.slice(s,s+50).trim().includes(t.suffix.slice(0,20)))return!1}return!0}similarityScore(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let i=new Set,n=new Set;for(let a=0;a<e.length-1;a++)i.add(e.slice(a,a+2));for(let a=0;a<t.length-1;a++)n.add(t.slice(a,a+2));let r=0;return i.forEach(a=>{n.has(a)&&r++}),2*r/(i.size+n.size)}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}};var E=class{constructor(e,t){this.highlightedId=null;this.activeId=null;this.pins=new Map;this.resizeObserver=null;this.repositionRAF=null;this.hoverTimers=new Map;this.leaveTimers=new Map;this.currentlyExpanded=null;this.container=e,this.onClick=t,this.anchoring=new C,this.boundScheduleReposition=this.scheduleReposition.bind(this),this.pinsContainer=document.createElement("div"),this.pinsContainer.className="tack-pins-container",this.container.appendChild(this.pinsContainer),this.setupResizeObserver(),window.addEventListener("scroll",this.boundScheduleReposition,{passive:!0}),window.addEventListener("resize",this.boundScheduleReposition,{passive:!0})}setupResizeObserver(){this.resizeObserver=new ResizeObserver(()=>{this.scheduleReposition()}),this.resizeObserver.observe(document.body)}scheduleReposition(){this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),this.repositionRAF=requestAnimationFrame(()=>{this.repositionAllPins()})}repositionAllPins(){this.pins.forEach((e,t)=>{e.targetElement&&!document.contains(e.targetElement)&&(e.anchorResult=this.anchoring.resolve(e.comment.anchor),e.targetElement=e.anchorResult.element),this.positionPin(e)})}getCurrentPagePath(){return window.location.pathname+window.location.search}render(e){this.hoverTimers.forEach(n=>clearTimeout(n)),this.hoverTimers.clear(),this.leaveTimers.forEach(n=>clearTimeout(n)),this.leaveTimers.clear(),this.currentlyExpanded=null,this.pinsContainer.innerHTML="",this.pins.clear();let t=this.getCurrentPagePath();e.filter(n=>!n.parent_id&&n.page_path===t).forEach(n=>{let r=this.createPin(n);r&&(this.pins.set(n.id,r),this.pinsContainer.appendChild(r.element))})}getUniqueAuthors(e){let t=new Set,i=[],n=e.user_id||e.author_name;if(t.add(n),i.push({name:e.author_name,avatar_url:e.author_avatar_url}),e.replies)for(let r of e.replies){let a=r.user_id||r.author_name;t.has(a)||(t.add(a),i.push({name:r.author_name,avatar_url:r.author_avatar_url}))}return i}renderInsetAvatar(e,t){let i=p(e.name),n=P(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${e.avatar_url}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}renderStackedAvatar(e,t){let i=p(e.name),n=P(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${e.avatar_url}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}createPin(e){let t={element:null,confidence:"none",method:"none"},i=null;e.anchor?(t=this.anchoring.resolve(e.anchor),i=t.element):e.element_selector&&(i=document.querySelector(e.element_selector),i&&(t={element:i,confidence:"medium",method:"css"}));let n=document.createElement("div"),r=e.id===this.activeId,a=e.id===this.highlightedId,s=this.getUniqueAuthors(e),o=s.length>1;n.className=`tack-pin${e.resolved?" resolved":""}${r?" active":""}${a?" highlighted":""}${o?" multi-author":""}`,n.dataset.id=e.id,t.confidence==="low"&&n.classList.add("low-confidence");let c=s[0],d=this.formatTimeAgo(new Date(e.created_at)),h=this.escapeHtml(e.content),m=e.replies?.length||0,R=`<div class="tack-pin-preview">
1816
+ `}getFilteredComments(){let e=this.comments.filter(t=>!t.parent_id);if(this.filters.showResolved||(e=e.filter(t=>!t.resolved)),this.filters.onlyYourThreads&&this.currentUser){let t=this.currentUser.id,i=this.currentUser.name;e=e.filter(n=>!!(n.user_id===t||n.author_name===i||n.replies?.some(r=>r.user_id===t||r.author_name===i)))}if(this.filters.onlyCurrentPage){let t=this.getCurrentPagePath();e=e.filter(i=>i.page_path===t)}if(this.searchQuery){let t=this.searchQuery;e=e.filter(i=>!!(i.author_name.toLowerCase().includes(t)||i.content.toLowerCase().includes(t)||i.replies?.some(n=>n.content.toLowerCase().includes(t)||n.author_name.toLowerCase().includes(t))))}switch(this.filters.sort){case"unread":e.sort((t,i)=>{let n=this.isRead(t.id)?1:0,r=this.isRead(i.id)?1:0;return n!==r?n-r:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;case"replies":e.sort((t,i)=>{let n=t.replies?.length||0,r=i.replies?.length||0;return r!==n?r-n:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;default:e.sort((t,i)=>new Date(i.created_at).getTime()-new Date(t.created_at).getTime());break}return e}scrollToComment(e){this.highlightedId=e,this.renderComments(),this.panel.querySelector(`[data-id="${e}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.highlightedId=null,this.renderComments()},2e3)}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var E=class{resolve(e){if(!e)return{element:null,confidence:"none",method:"none"};if(e.cssSelector){let t=this.tryCssSelector(e);if(t.element)return t}if(e.xpath){let t=this.tryXPath(e);if(t.element)return t}if(e.textQuote){let t=this.tryTextQuote(e.textQuote);if(t.element)return t}if(e.textQuote){let t=this.tryFuzzySearch(e.textQuote);if(t.element)return t}return{element:null,confidence:"none",method:"none"}}calculatePinPosition(e,t){let i=e.getBoundingClientRect(),n=i.left+t.relativeX*i.width+window.scrollX,r=i.top+t.relativeY*i.height+window.scrollY;return{x:n,y:r}}tryCssSelector(e){try{let t=document.querySelector(e.cssSelector);return t?e.contentHash?this.generateContentHash(t)===e.contentHash?{element:t,confidence:"high",method:"css"}:{element:t,confidence:"medium",method:"css"}:{element:t,confidence:"high",method:"css"}:{element:null,confidence:"none",method:"css"}}catch{return{element:null,confidence:"none",method:"css"}}}tryXPath(e){try{let i=document.evaluate(e.xpath,document.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return i?e.contentHash?this.generateContentHash(i)===e.contentHash?{element:i,confidence:"high",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:null,confidence:"none",method:"xpath"}}catch{return{element:null,confidence:"none",method:"xpath"}}}tryTextQuote(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=t.nextNode();for(;i;){let n=i,r=n.textContent?.trim();if(r&&r.includes(e.exact)&&this.verifyContext(n,e))return{element:n,confidence:"high",method:"textQuote"};i=t.nextNode()}return{element:null,confidence:"none",method:"textQuote"}}tryFuzzySearch(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=null,n=e.exact.toLowerCase(),r=t.nextNode();for(;r;){let a=r,s=a.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let o=this.similarityScore(s,n);o>.7&&(!i||o>i.score)&&(i={element:a,score:o})}r=t.nextNode()}return i?{element:i.element,confidence:i.score>.9?"medium":"low",method:"fuzzy"}:{element:null,confidence:"none",method:"fuzzy"}}verifyContext(e,t){if(!t.prefix&&!t.suffix)return!0;let i=e.parentElement;if(!i)return!0;let n=i.textContent||"",r=e.textContent||"",a=n.indexOf(r);if(a===-1)return!0;if(t.prefix&&!n.slice(Math.max(0,a-50),a).trim().includes(t.prefix.slice(-20)))return!1;if(t.suffix){let s=a+r.length;if(!n.slice(s,s+50).trim().includes(t.suffix.slice(0,20)))return!1}return!0}similarityScore(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let i=new Set,n=new Set;for(let a=0;a<e.length-1;a++)i.add(e.slice(a,a+2));for(let a=0;a<t.length-1;a++)n.add(t.slice(a,a+2));let r=0;return i.forEach(a=>{n.has(a)&&r++}),2*r/(i.size+n.size)}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}};function K(l){return l.map(e=>`${e.id}:${e.resolved}:${e.content}:${e.replies?.length||0}`).join("|")}var T=class{constructor(e,t){this.highlightedId=null;this.activeId=null;this.pins=new Map;this.resizeObserver=null;this.repositionRAF=null;this.hoverTimers=new Map;this.leaveTimers=new Map;this.currentlyExpanded=null;this.lastFingerprint="";this.container=e,this.onClick=t,this.anchoring=new E,this.boundScheduleReposition=this.scheduleReposition.bind(this),this.pinsContainer=document.createElement("div"),this.pinsContainer.className="tack-pins-container",this.container.appendChild(this.pinsContainer),this.setupResizeObserver(),window.addEventListener("scroll",this.boundScheduleReposition,{passive:!0}),window.addEventListener("resize",this.boundScheduleReposition,{passive:!0})}setupResizeObserver(){this.resizeObserver=new ResizeObserver(()=>{this.scheduleReposition()}),this.resizeObserver.observe(document.body)}scheduleReposition(){this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),this.repositionRAF=requestAnimationFrame(()=>{this.repositionAllPins()})}repositionAllPins(){this.pins.forEach((e,t)=>{e.targetElement&&!document.contains(e.targetElement)&&(e.anchorResult=this.anchoring.resolve(e.comment.anchor),e.targetElement=e.anchorResult.element),this.positionPin(e)})}getCurrentPagePath(){return window.location.pathname}render(e){let t=this.getCurrentPagePath(),i=t+"::"+K(e);if(i===this.lastFingerprint)return;this.lastFingerprint=i,this.hoverTimers.forEach(r=>clearTimeout(r)),this.hoverTimers.clear(),this.leaveTimers.forEach(r=>clearTimeout(r)),this.leaveTimers.clear(),this.currentlyExpanded=null,this.pinsContainer.innerHTML="",this.pins.clear(),e.filter(r=>!r.parent_id&&r.page_path===t).forEach(r=>{let a=this.createPin(r);a&&(this.pins.set(r.id,a),this.pinsContainer.appendChild(a.element))})}getUniqueAuthors(e){let t=new Set,i=[],n=e.user_id||e.author_name;if(t.add(n),i.push({name:e.author_name,avatar_url:e.author_avatar_url}),e.replies)for(let r of e.replies){let a=r.user_id||r.author_name;t.has(a)||(t.add(a),i.push({name:r.author_name,avatar_url:r.author_avatar_url}))}return i}renderInsetAvatar(e,t){let i=u(e.name),n=$(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${h.get(e.avatar_url)}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}renderStackedAvatar(e,t){let i=u(e.name),n=$(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${h.get(e.avatar_url)}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}createPin(e){let t={element:null,confidence:"none",method:"none"},i=null;e.anchor?(t=this.anchoring.resolve(e.anchor),i=t.element):e.element_selector&&(i=document.querySelector(e.element_selector),i&&(t={element:i,confidence:"medium",method:"css"}));let n=document.createElement("div"),r=e.id===this.activeId,a=e.id===this.highlightedId,s=this.getUniqueAuthors(e),o=s.length>1;n.className=`tack-pin${e.resolved?" resolved":""}${r?" active":""}${a?" highlighted":""}${o?" multi-author":""}`,n.dataset.id=e.id,t.confidence==="low"&&n.classList.add("low-confidence");let c=s[0],d=this.formatTimeAgo(new Date(e.created_at)),p=this.escapeHtml(e.content),g=e.replies?.length||0,F=`<div class="tack-pin-preview">
1817
1817
  <div class="tack-pin-preview-header">
1818
1818
  <div class="tack-pin-preview-avatar">${this.renderInsetAvatar(c,28)}</div>
1819
1819
  <div class="tack-pin-preview-meta">
@@ -1821,9 +1821,9 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1821
1821
  <span class="tack-pin-preview-time">${d}</span>
1822
1822
  </div>
1823
1823
  </div>
1824
- <p class="tack-pin-preview-text">${h}</p>
1825
- ${m>0?`<span class="tack-pin-preview-replies">${m} ${m===1?"reply":"replies"}</span>`:""}
1826
- </div>`,g;if(o){let j=s.slice(0,3),F=s.length-3,f='<div class="tack-pin-shell"><div class="tack-pin-avatars">';j.forEach((B,N)=>{f+=`<div class="tack-pin-avatar-stacked" style="z-index:${N+1}">${this.renderStackedAvatar(B,24)}</div>`}),F>0&&(f+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:4">+${F}</div>`),f+=`</div>${R}</div>`,g=f}else{let v=s[0];g=`<div class="tack-pin-shell">${this.renderInsetAvatar(v,32)}${R}</div>`}e.resolved&&(g+='<div class="tack-pin-check"></div>'),n.innerHTML=g,n.addEventListener("click",v=>{v.stopPropagation(),this.collapsePin(e.id,n),this.onClick(e.id,n)}),this.setupHoverListeners(n,e);let $={comment:e,element:n,targetElement:i,anchorResult:t};return this.positionPin($),n.style.left===""&&n.style.top===""?null:$}positionPin(e){let{comment:t,element:i,targetElement:n}=e,r=7,a=45;if(t.anchor&&n){let s=this.anchoring.calculatePinPosition(n,t.anchor);i.style.left=`${s.x-r}px`,i.style.top=`${s.y-a}px`;return}if(n){let s=n.getBoundingClientRect();i.style.left=`${s.left+window.scrollX-r}px`,i.style.top=`${s.top+window.scrollY-a}px`;return}if(t.x_percent!==null&&t.y_percent!==null){let s=t.x_percent/100*document.documentElement.scrollWidth,o=t.y_percent/100*document.documentElement.scrollHeight;i.style.left=`${s-r}px`,i.style.top=`${o-a}px`;return}i.style.display="none"}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}setupHoverListeners(e,t){e.addEventListener("mouseenter",()=>{let i=this.leaveTimers.get(t.id);i&&(clearTimeout(i),this.leaveTimers.delete(t.id));let n=window.setTimeout(()=>{this.expandPin(t.id,e),this.hoverTimers.delete(t.id)},150);this.hoverTimers.set(t.id,n)}),e.addEventListener("mouseleave",()=>{let i=this.hoverTimers.get(t.id);i&&(clearTimeout(i),this.hoverTimers.delete(t.id));let n=window.setTimeout(()=>{this.collapsePin(t.id,e),this.leaveTimers.delete(t.id)},120);this.leaveTimers.set(t.id,n)})}expandPin(e,t){if(t.classList.contains("active"))return;if(this.currentlyExpanded&&this.currentlyExpanded!==e){let n=this.pins.get(this.currentlyExpanded);n&&n.element.classList.remove("expanded","expand-left")}this.currentlyExpanded=e;let i=t.getBoundingClientRect();window.innerWidth-i.left<300?t.classList.add("expand-left"):t.classList.remove("expand-left"),t.classList.add("expanded")}collapsePin(e,t){t.classList.remove("expanded","expand-left"),this.currentlyExpanded===e&&(this.currentlyExpanded=null)}setActive(e){this.activeId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("active",i===e)})}highlight(e){this.highlightedId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("highlighted",i===e)}),setTimeout(()=>{this.highlightedId=null,this.pins.forEach(t=>{t.element.classList.remove("highlighted")})},2e3)}show(){this.pinsContainer.classList.add("visible")}hide(){this.pinsContainer.classList.remove("visible")}destroy(){this.hoverTimers.forEach(e=>clearTimeout(e)),this.leaveTimers.forEach(e=>clearTimeout(e)),this.resizeObserver&&this.resizeObserver.disconnect(),this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),window.removeEventListener("scroll",this.boundScheduleReposition),window.removeEventListener("resize",this.boundScheduleReposition)}};var T=class{constructor(e,t){this.currentComment=null;this.currentUser=null;this.visible=!1;this.editing=!1;this.dropdownOpen=!1;this.container=e,this.callbacks=t,this.card=document.createElement("div"),this.card.className="tack-card",this.card.setAttribute("role","dialog"),this.card.setAttribute("aria-label","Comment details"),this.container.appendChild(this.card),this.card.addEventListener("mousedown",i=>i.stopPropagation()),this.card.addEventListener("click",i=>i.stopPropagation()),this.boundOnMouseDown=this.onDocumentMouseDown.bind(this),this.boundOnKeyDown=this.onKeyDown.bind(this)}setUser(e){this.currentUser=e}show(e,t){if(this.visible&&this.currentComment?.id===e.id){this.hide();return}this.currentComment=e,this.visible=!0,this.editing=!1,this.dropdownOpen=!1,this.renderCard(e),this.positionNear(t),this.card.classList.add("visible"),this.attachListeners(),document.addEventListener("mousedown",this.boundOnMouseDown,!0),document.addEventListener("keydown",this.boundOnKeyDown)}hide(){this.visible&&(this.visible=!1,this.currentComment=null,this.editing=!1,this.dropdownOpen=!1,this.card.classList.remove("visible"),document.removeEventListener("mousedown",this.boundOnMouseDown,!0),document.removeEventListener("keydown",this.boundOnKeyDown),this.callbacks.onClose())}isVisible(){return this.visible}updateComment(e){!this.visible||this.currentComment?.id!==e.id||(this.currentComment=e,this.renderCard(e),this.attachListeners())}onDocumentMouseDown(e){this.card.contains(e.target)||e.composedPath().includes(this.card)||this.hide()}onKeyDown(e){if(e.key==="Escape"){if(this.dropdownOpen){this.dropdownOpen=!1,this.renderCard(this.currentComment),this.attachListeners();return}if(this.editing){this.editing=!1,this.renderCard(this.currentComment),this.attachListeners();return}e.preventDefault(),this.hide()}}positionNear(e){let t=e.getBoundingClientRect(),i=320,n=8,r=document.body.classList.contains("tack-panel-open")?360:0,a=window.innerWidth-r-16,s=t.right+n+window.scrollX;s+i>a+window.scrollX&&(s=t.left-i-n+window.scrollX),s=Math.max(16,s);let o=t.top+window.scrollY,c=window.innerHeight+window.scrollY-16,d=300;o+d>c&&(o=c-d),o=Math.max(16+window.scrollY,o),this.card.style.left=`${s}px`,this.card.style.top=`${o}px`}isOwnComment(e){return this.currentUser?.id&&e.user_id?this.currentUser.id===e.user_id:(localStorage.getItem("tack_author_name")||"")===e.author_name}renderCard(e){let t=e.replies||[],i=localStorage.getItem("tack_author_name")||"Anonymous",n=`
1824
+ <p class="tack-pin-preview-text">${p}</p>
1825
+ ${g>0?`<span class="tack-pin-preview-replies">${g} ${g===1?"reply":"replies"}</span>`:""}
1826
+ </div>`,v;if(o){let N=s.slice(0,3),_=s.length-3,k='<div class="tack-pin-shell"><div class="tack-pin-avatars">';N.forEach((q,Y)=>{k+=`<div class="tack-pin-avatar-stacked" style="z-index:${Y+1}">${this.renderStackedAvatar(q,24)}</div>`}),_>0&&(k+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:4">+${_}</div>`),k+=`</div>${F}</div>`,v=k}else{let f=s[0];v=`<div class="tack-pin-shell">${this.renderInsetAvatar(f,32)}${F}</div>`}e.resolved&&(v+='<div class="tack-pin-check"></div>'),n.innerHTML=v,n.addEventListener("click",f=>{f.stopPropagation(),this.collapsePin(e.id,n),this.onClick(e.id,n)}),this.setupHoverListeners(n,e);let H={comment:e,element:n,targetElement:i,anchorResult:t};return this.positionPin(H),n.style.left===""&&n.style.top===""?null:H}positionPin(e){let{comment:t,element:i,targetElement:n}=e,r=7,a=45;if(t.anchor&&n){let s=this.anchoring.calculatePinPosition(n,t.anchor);i.style.left=`${s.x-r}px`,i.style.top=`${s.y-a}px`;return}if(n){let s=n.getBoundingClientRect();i.style.left=`${s.left+window.scrollX-r}px`,i.style.top=`${s.top+window.scrollY-a}px`;return}if(t.x_percent!==null&&t.y_percent!==null){let s=t.x_percent/100*document.documentElement.scrollWidth,o=t.y_percent/100*document.documentElement.scrollHeight;i.style.left=`${s-r}px`,i.style.top=`${o-a}px`;return}i.style.display="none"}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}setupHoverListeners(e,t){e.addEventListener("mouseenter",()=>{let i=this.leaveTimers.get(t.id);i&&(clearTimeout(i),this.leaveTimers.delete(t.id));let n=window.setTimeout(()=>{this.expandPin(t.id,e),this.hoverTimers.delete(t.id)},150);this.hoverTimers.set(t.id,n)}),e.addEventListener("mouseleave",()=>{let i=this.hoverTimers.get(t.id);i&&(clearTimeout(i),this.hoverTimers.delete(t.id));let n=window.setTimeout(()=>{this.collapsePin(t.id,e),this.leaveTimers.delete(t.id)},120);this.leaveTimers.set(t.id,n)})}expandPin(e,t){if(t.classList.contains("active"))return;if(this.currentlyExpanded&&this.currentlyExpanded!==e){let n=this.pins.get(this.currentlyExpanded);n&&n.element.classList.remove("expanded","expand-left")}this.currentlyExpanded=e;let i=t.getBoundingClientRect();window.innerWidth-i.left<300?t.classList.add("expand-left"):t.classList.remove("expand-left"),t.classList.add("expanded")}collapsePin(e,t){t.classList.remove("expanded","expand-left"),this.currentlyExpanded===e&&(this.currentlyExpanded=null)}setActive(e){this.activeId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("active",i===e)})}highlight(e){this.highlightedId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("highlighted",i===e)}),setTimeout(()=>{this.highlightedId=null,this.pins.forEach(t=>{t.element.classList.remove("highlighted")})},2e3)}show(){this.pinsContainer.classList.add("visible")}hide(){this.pinsContainer.classList.remove("visible")}destroy(){this.hoverTimers.forEach(e=>clearTimeout(e)),this.leaveTimers.forEach(e=>clearTimeout(e)),this.resizeObserver&&this.resizeObserver.disconnect(),this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),window.removeEventListener("scroll",this.boundScheduleReposition),window.removeEventListener("resize",this.boundScheduleReposition)}};var S=class{constructor(e,t){this.currentComment=null;this.currentUser=null;this.visible=!1;this.editing=!1;this.dropdownOpen=!1;this.container=e,this.callbacks=t,this.card=document.createElement("div"),this.card.className="tack-card",this.card.setAttribute("role","dialog"),this.card.setAttribute("aria-label","Comment details"),this.container.appendChild(this.card),this.card.addEventListener("mousedown",i=>i.stopPropagation()),this.card.addEventListener("click",i=>i.stopPropagation()),this.boundOnMouseDown=this.onDocumentMouseDown.bind(this),this.boundOnKeyDown=this.onKeyDown.bind(this)}setUser(e){this.currentUser=e}show(e,t){if(this.visible&&this.currentComment?.id===e.id){this.hide();return}this.currentComment=e,this.visible=!0,this.editing=!1,this.dropdownOpen=!1,this.renderCard(e),this.positionNear(t),this.card.classList.add("visible"),this.attachListeners(),document.addEventListener("mousedown",this.boundOnMouseDown,!0),document.addEventListener("keydown",this.boundOnKeyDown)}hide(){this.visible&&(this.visible=!1,this.currentComment=null,this.editing=!1,this.dropdownOpen=!1,this.card.classList.remove("visible"),document.removeEventListener("mousedown",this.boundOnMouseDown,!0),document.removeEventListener("keydown",this.boundOnKeyDown),this.callbacks.onClose())}isVisible(){return this.visible}updateComment(e){!this.visible||this.currentComment?.id!==e.id||(this.currentComment=e,this.renderCard(e),this.attachListeners())}onDocumentMouseDown(e){this.card.contains(e.target)||e.composedPath().includes(this.card)||this.hide()}onKeyDown(e){if(e.key==="Escape"){if(this.dropdownOpen){this.dropdownOpen=!1,this.renderCard(this.currentComment),this.attachListeners();return}if(this.editing){this.editing=!1,this.renderCard(this.currentComment),this.attachListeners();return}e.preventDefault(),this.hide()}}positionNear(e){let t=e.getBoundingClientRect(),i=320,n=8,r=document.body.classList.contains("tack-panel-open")?360:0,a=window.innerWidth-r-16,s=t.right+n+window.scrollX;s+i>a+window.scrollX&&(s=t.left-i-n+window.scrollX),s=Math.max(16,s);let o=t.top+window.scrollY,c=window.innerHeight+window.scrollY-16,d=300;o+d>c&&(o=c-d),o=Math.max(16+window.scrollY,o),this.card.style.left=`${s}px`,this.card.style.top=`${o}px`}isOwnComment(e){return this.currentUser?.id&&e.user_id?this.currentUser.id===e.user_id:(localStorage.getItem("tack_author_name")||"")===e.author_name}renderCard(e){let t=e.replies||[],i=localStorage.getItem("tack_author_name")||"Anonymous",n=`
1827
1827
  <div class="tack-card-title-bar">
1828
1828
  <span class="tack-card-title">Comment</span>
1829
1829
  <div class="tack-card-title-actions">
@@ -1848,7 +1848,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1848
1848
  Resolved by ${this.escapeHtml(e.author_name)}
1849
1849
  </div>`),n+=this.renderCommentRow(e,!0),n+='<div class="tack-card-divider"></div>',t.length>0&&(t.forEach((r,a)=>{n+=this.renderCommentRow(r,!1),a<t.length-1&&(n+='<div class="tack-card-divider"></div>')}),n+='<div class="tack-card-divider"></div>'),n+=`
1850
1850
  <div class="tack-card-reply-bar">
1851
- <div class="tack-card-reply-bar-avatar-wrap">${u(i,this.currentUser?.avatar_url||null,24)}</div>
1851
+ <div class="tack-card-reply-bar-avatar-wrap">${m(i,this.currentUser?.avatar_url||null,24)}</div>
1852
1852
  <div class="tack-card-reply-bar-input-wrap">
1853
1853
  <input type="text" class="tack-card-reply-bar-input" placeholder="Reply\u2026" data-parent-id="${e.id}" />
1854
1854
  <button class="tack-card-reply-bar-send" data-parent-id="${e.id}">
@@ -1860,7 +1860,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1860
1860
  </div>
1861
1861
  </div>`,this.card.innerHTML=n}renderCommentRow(e,t){let i=this.formatTimeAgo(new Date(e.created_at)),n=t&&this.isOwnComment(e),r=`<div class="tack-card-row${t?" main":""}" data-comment-id="${e.id}">`;return r+=`
1862
1862
  <div class="tack-card-row-header">
1863
- <div class="tack-card-row-avatar-wrap">${u(e.author_name,e.author_avatar_url,28)}</div>
1863
+ <div class="tack-card-row-avatar-wrap">${m(e.author_name,e.author_avatar_url,28)}</div>
1864
1864
  <div class="tack-card-row-meta">
1865
1865
  <span class="tack-card-row-author">${this.escapeHtml(e.author_name)}</span>
1866
1866
  ${this.editing&&t?'<span class="tack-card-editing-badge">Editing</span>':""}
@@ -1882,7 +1882,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1882
1882
  <button class="tack-card-edit-cancel">Cancel</button>
1883
1883
  <button class="tack-card-edit-save">Save</button>
1884
1884
  </div>
1885
- </div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,r+="</div>",r}attachListeners(){this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",t=>{t.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelector(".tack-card-more-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.dropdownOpen=!this.dropdownOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-card-dropdown-item").forEach(t=>{t.addEventListener("click",i=>{i.stopPropagation();let n=t.dataset.action;if(n==="edit"){this.dropdownOpen=!1,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let r=this.card.querySelector(".tack-card-edit-textarea");r?.focus(),r?.setSelectionRange(r.value.length,r.value.length)}else n==="delete"&&(this.dropdownOpen=!1,this.currentComment&&(this.callbacks.onDelete(this.currentComment.id),this.hide()))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",t=>{t.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",t=>{t.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),this.saveEdit())}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",t=>{t.stopPropagation(),this.submitReply()})}saveEdit(){if(!this.currentComment)return;let t=this.card.querySelector(".tack-card-edit-textarea")?.value.trim();t&&(this.editing=!1,this.callbacks.onEdit(this.currentComment.id,t))}submitReply(){if(!this.currentComment)return;let e=this.card.querySelector(".tack-card-reply-bar-input"),t=e?.value.trim();t&&(this.callbacks.onReply(this.currentComment.id,t),e.value="")}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var S=class{constructor(e,t,i,n){this.ws=null;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.heartbeatInterval=null;this.supabaseUrl=e,this.supabaseKey=t,this.versionId=i,this.callback=n}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.subscribe()},this.ws.onmessage=i=>{let n=JSON.parse(i.data);this.handleMessage(n)},this.ws.onclose=()=>{this.attemptReconnect()},this.ws.onerror=i=>{console.error("[Tack] Realtime error:",i)}}subscribe(){if(!this.ws)return;let e={topic:"realtime:public:comments",event:"phx_join",payload:{config:{postgres_changes:[{event:"*",schema:"public",table:"comments",filter:`version_id=eq.${this.versionId}`}]}},ref:"1"};this.ws.send(JSON.stringify(e)),this.startHeartbeat()}handleMessage(e){if(e.event==="postgres_changes"&&e.payload?.data){let{type:t,record:i}=e.payload.data,n=t.toUpperCase();this.callback(n,i)}}startHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.heartbeatInterval=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:Date.now().toString()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[Tack] Max reconnect attempts reached");return}this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{console.log(`[Tack] Reconnecting... (attempt ${this.reconnectAttempts})`),this.connect()},e)}disconnect(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.ws&&(this.ws.close(),this.ws=null)}};var A=class{constructor(e,t,i){this.ws=null;this.currentUser=null;this.pagePath="";this.users=new Map;this.onPresenceChange=null;this.heartbeatTimer=null;this.reconnectAttempts=0;this.joined=!1;this.ref=1;this.supabaseUrl=e,this.supabaseKey=t,this.projectId=i}join(e){this.currentUser=e,this.connect()}leave(){this.joined=!1,this.currentUser=null,this.users.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.ws&&(this.ws.close(),this.ws=null)}updatePagePath(e){this.pagePath=e,this.joined&&this.ws?.readyState===WebSocket.OPEN&&this.trackPresence()}setOnPresenceChange(e){this.onPresenceChange=e}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.joinChannel()},this.ws.onmessage=i=>{try{let n=JSON.parse(i.data);this.handleMessage(n)}catch{}},this.ws.onclose=()=>{this.currentUser&&this.attemptReconnect()},this.ws.onerror=()=>{}}nextRef(){return(this.ref++).toString()}joinChannel(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"phx_join",payload:{config:{presence:{key:this.currentUser.id}}},ref:this.nextRef()})),this.startHeartbeat(),setTimeout(()=>{this.joined=!0,this.trackPresence()},200)}trackPresence(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.currentUser)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"presence",payload:{type:"presence",event:"track",payload:{user_id:this.currentUser.id,name:this.currentUser.name,avatar_url:this.currentUser.avatar_url,page_path:this.pagePath,online_at:Date.now()}},ref:this.nextRef()}))}handleMessage(e){if(e.event==="presence_state"){this.users.clear();let t=e.payload||{};for(let i of Object.keys(t)){let n=t[i]?.metas;if(n?.length>0){let r=n[0];this.users.set(i,{id:r.user_id||i,name:r.name||"Unknown",avatar_url:r.avatar_url||null})}}this.notifyChange()}else if(e.event==="presence_diff"){let{joins:t,leaves:i}=e.payload||{};if(t)for(let n of Object.keys(t)){let r=t[n]?.metas;if(r?.length>0){let a=r[0];this.users.set(n,{id:a.user_id||n,name:a.name||"Unknown",avatar_url:a.avatar_url||null})}}if(i)for(let n of Object.keys(i))this.users.delete(n);this.notifyChange()}}notifyChange(){let e=Array.from(this.users.values());this.onPresenceChange?.(e)}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:this.nextRef()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=5)return;this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{this.currentUser&&this.connect()},e)}};var L=class{constructor(e){this.container=null;this.shadowRoot=null;this.selector=null;this.form=null;this.panel=null;this.pins=null;this.card=null;this.realtime=null;this.presence=null;this.commentMode=!1;this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.config={apiUrl:"https://tacktext.vercel.app/api",supabaseUrl:"https://etpavqvnpupqdxdptkhc.supabase.co",supabaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0cGF2cXZucHVwcWR4ZHB0a2hjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4MzU4MzgsImV4cCI6MjA5MDQxMTgzOH0.GMSIuPmMaEkNhss_laSm_NchihN_KF9VyyEh5YH4Ru0",...e},this.api=new k(this.config.apiUrl,this.config.projectId),this.auth=new b(this.config.apiUrl)}async mount(){this.container=document.createElement("div"),this.container.id="tack-widget",this.shadowRoot=this.container.attachShadow({mode:"open"});let e=document.createElement("style");e.textContent=H(),this.shadowRoot.appendChild(e),this.injectPageStyles();let t=document.createElement("div");if(t.className="tack-wrapper",this.shadowRoot.appendChild(t),this.auth.setOnAuthChange(i=>{this.api.setAuthToken(i?this.auth.getSessionToken():null),this.form?.setUser(i),this.card?.setUser(i),this.panel?.setUser(i),i?this.joinPresence(i):(this.presence?.leave(),this.presence=null)}),await this.auth.init(),this.auth.isAuthenticated()&&this.api.setAuthToken(this.auth.getSessionToken()),this.api.setOnUnauthorized(()=>{this.auth.signOut(),this.showToast("Session expired. Please sign in again.")}),this.selector=new x(this.onElementSelected.bind(this)),this.form=new w(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.panel?.isOpen()&&this.enableCommentMode()}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new y(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:this.onPanelClose.bind(this),onAddComment:this.enableCommentMode.bind(this),onShare:this.onShare.bind(this)}),this.card=new T(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new E(t,this.onPinClick.bind(this)),this.createToggleButton(t),document.body.appendChild(this.container),await this.loadComments(),this.handleDeepLink(),this.subscribeToRealtime(),this.setupUrlChangeDetection(),this.auth.isAuthenticated()){let i=this.auth.getUser();this.joinPresence(i)}}joinPresence(e){!this.config.supabaseUrl||!this.config.supabaseKey||(this.presence?.leave(),this.presence=new A(this.config.supabaseUrl,this.config.supabaseKey,this.config.projectId),this.presence.setOnPresenceChange(t=>{this.panel?.renderPresence(t)}),this.presence.join(e),this.presence.updatePagePath(this.getPagePath()))}async signIn(){try{await this.auth.signIn()}catch(e){console.error("[Tack] Sign in failed:",e)}}getPagePath(){return window.location.pathname+window.location.search}setupUrlChangeDetection(){this.currentPagePath=this.getPagePath(),this.boundOnUrlChange=this.onUrlChange.bind(this),window.addEventListener("popstate",this.boundOnUrlChange),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState(...e),this.onUrlChange()},history.replaceState=(...e)=>{this.originalReplaceState(...e),this.onUrlChange()}}onUrlChange(){let e=this.getPagePath();e!==this.currentPagePath&&(this.currentPagePath=e,this.presence?.updatePagePath(e),setTimeout(()=>{console.log("[Tack] URL changed, re-rendering pins after DOM settle"),this.pins?.render(this.comments),this.panel?.render(this.comments)},100))}createToggleButton(e){let t=document.createElement("button");t.className="tack-toggle",t.setAttribute("aria-label","Toggle comments"),t.setAttribute("aria-expanded","false"),t.innerHTML=`
1885
+ </div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,r+="</div>",r}attachListeners(){this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",t=>{t.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelector(".tack-card-more-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.dropdownOpen=!this.dropdownOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-card-dropdown-item").forEach(t=>{t.addEventListener("click",i=>{i.stopPropagation();let n=t.dataset.action;if(n==="edit"){this.dropdownOpen=!1,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let r=this.card.querySelector(".tack-card-edit-textarea");r?.focus(),r?.setSelectionRange(r.value.length,r.value.length)}else n==="delete"&&(this.dropdownOpen=!1,this.currentComment&&(this.callbacks.onDelete(this.currentComment.id),this.hide()))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",t=>{t.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",t=>{t.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),this.saveEdit())}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",t=>{t.stopPropagation(),this.submitReply()})}saveEdit(){if(!this.currentComment)return;let t=this.card.querySelector(".tack-card-edit-textarea")?.value.trim();t&&(this.editing=!1,this.callbacks.onEdit(this.currentComment.id,t))}submitReply(){if(!this.currentComment)return;let e=this.card.querySelector(".tack-card-reply-bar-input"),t=e?.value.trim();t&&(this.callbacks.onReply(this.currentComment.id,t),e.value="")}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var A=class{constructor(e,t,i,n){this.ws=null;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.heartbeatInterval=null;this.supabaseUrl=e,this.supabaseKey=t,this.versionId=i,this.callback=n}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.subscribe()},this.ws.onmessage=i=>{let n=JSON.parse(i.data);this.handleMessage(n)},this.ws.onclose=()=>{this.attemptReconnect()},this.ws.onerror=i=>{console.error("[Tack] Realtime error:",i)}}subscribe(){if(!this.ws)return;let e={topic:"realtime:public:comments",event:"phx_join",payload:{config:{postgres_changes:[{event:"*",schema:"public",table:"comments",filter:`version_id=eq.${this.versionId}`}]}},ref:"1"};this.ws.send(JSON.stringify(e)),this.startHeartbeat()}handleMessage(e){if(e.event==="postgres_changes"&&e.payload?.data){let{type:t,record:i}=e.payload.data,n=t.toUpperCase();this.callback(n,i)}}startHeartbeat(){this.heartbeatInterval&&clearInterval(this.heartbeatInterval),this.heartbeatInterval=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:Date.now().toString()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[Tack] Max reconnect attempts reached");return}this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{console.log(`[Tack] Reconnecting... (attempt ${this.reconnectAttempts})`),this.connect()},e)}disconnect(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.ws&&(this.ws.close(),this.ws=null)}};var L=class{constructor(e,t,i){this.ws=null;this.currentUser=null;this.pagePath="";this.users=new Map;this.onPresenceChange=null;this.heartbeatTimer=null;this.reconnectAttempts=0;this.joined=!1;this.ref=1;this.supabaseUrl=e,this.supabaseKey=t,this.projectId=i}join(e){this.currentUser=e,this.connect()}leave(){this.joined=!1,this.currentUser=null,this.users.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.ws&&(this.ws.close(),this.ws=null)}updatePagePath(e){this.pagePath=e,this.joined&&this.ws?.readyState===WebSocket.OPEN&&this.trackPresence()}setOnPresenceChange(e){this.onPresenceChange=e}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.joinChannel()},this.ws.onmessage=i=>{try{let n=JSON.parse(i.data);this.handleMessage(n)}catch{}},this.ws.onclose=()=>{this.currentUser&&this.attemptReconnect()},this.ws.onerror=()=>{}}nextRef(){return(this.ref++).toString()}joinChannel(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"phx_join",payload:{config:{presence:{key:this.currentUser.id}}},ref:this.nextRef()})),this.startHeartbeat(),setTimeout(()=>{this.joined=!0,this.trackPresence()},200)}trackPresence(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.currentUser)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"presence",payload:{type:"presence",event:"track",payload:{user_id:this.currentUser.id,name:this.currentUser.name,avatar_url:this.currentUser.avatar_url,page_path:this.pagePath,online_at:Date.now()}},ref:this.nextRef()}))}handleMessage(e){if(e.event==="presence_state"){this.users.clear();let t=e.payload||{};for(let i of Object.keys(t)){let n=t[i]?.metas;if(n?.length>0){let r=n[0];this.users.set(i,{id:r.user_id||i,name:r.name||"Unknown",avatar_url:r.avatar_url||null})}}this.notifyChange()}else if(e.event==="presence_diff"){let{joins:t,leaves:i}=e.payload||{};if(t)for(let n of Object.keys(t)){let r=t[n]?.metas;if(r?.length>0){let a=r[0];this.users.set(n,{id:a.user_id||n,name:a.name||"Unknown",avatar_url:a.avatar_url||null})}}if(i)for(let n of Object.keys(i))this.users.delete(n);this.notifyChange()}}notifyChange(){let e=Array.from(this.users.values());this.onPresenceChange?.(e)}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:this.nextRef()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=5)return;this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{this.currentUser&&this.connect()},e)}};var P=class{constructor(e){this.container=null;this.shadowRoot=null;this.selector=null;this.form=null;this.panel=null;this.pins=null;this.card=null;this.realtime=null;this.presence=null;this.commentMode=!1;this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.config={apiUrl:"https://tacktext.vercel.app/api",supabaseUrl:"https://etpavqvnpupqdxdptkhc.supabase.co",supabaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0cGF2cXZucHVwcWR4ZHB0a2hjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4MzU4MzgsImV4cCI6MjA5MDQxMTgzOH0.GMSIuPmMaEkNhss_laSm_NchihN_KF9VyyEh5YH4Ru0",...e},this.api=new b(this.config.apiUrl,this.config.projectId),this.auth=new x(this.config.apiUrl)}async mount(){this.container=document.createElement("div"),this.container.id="tack-widget",this.shadowRoot=this.container.attachShadow({mode:"open"});let e=document.createElement("style");e.textContent=I(),this.shadowRoot.appendChild(e),this.injectPageStyles();let t=document.createElement("div");if(t.className="tack-wrapper",this.shadowRoot.appendChild(t),this.auth.setOnAuthChange(i=>{this.api.setAuthToken(i?this.auth.getSessionToken():null),this.form?.setUser(i),this.card?.setUser(i),this.panel?.setUser(i),i?this.joinPresence(i):(this.presence?.leave(),this.presence=null)}),await this.auth.init(),this.auth.isAuthenticated()&&this.api.setAuthToken(this.auth.getSessionToken()),this.api.setOnUnauthorized(()=>{this.auth.signOut(),this.showToast("Session expired. Please sign in again.")}),this.selector=new w(this.onElementSelected.bind(this)),this.form=new y(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.panel?.isOpen()&&this.enableCommentMode()}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new C(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:this.onPanelClose.bind(this),onAddComment:this.enableCommentMode.bind(this),onShare:this.onShare.bind(this)}),this.card=new S(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new T(t,this.onPinClick.bind(this)),this.createToggleButton(t),document.body.appendChild(this.container),await this.loadComments(),this.handleDeepLink(),this.subscribeToRealtime(),this.setupUrlChangeDetection(),this.auth.isAuthenticated()){let i=this.auth.getUser();this.joinPresence(i)}}joinPresence(e){!this.config.supabaseUrl||!this.config.supabaseKey||(this.presence?.leave(),this.presence=new L(this.config.supabaseUrl,this.config.supabaseKey,this.config.projectId),this.presence.setOnPresenceChange(t=>{this.panel?.renderPresence(t)}),this.presence.join(e),this.presence.updatePagePath(this.getPagePath()))}async signIn(){try{await this.auth.signIn()}catch(e){console.error("[Tack] Sign in failed:",e)}}getPagePath(){return window.location.pathname}setupUrlChangeDetection(){this.currentPagePath=this.getPagePath(),this.boundOnUrlChange=this.onUrlChange.bind(this),window.addEventListener("popstate",this.boundOnUrlChange),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState(...e),this.onUrlChange()},history.replaceState=(...e)=>{this.originalReplaceState(...e),this.onUrlChange()}}onUrlChange(){let e=this.getPagePath();e!==this.currentPagePath&&(this.currentPagePath=e,this.presence?.updatePagePath(e),setTimeout(()=>{this.loadComments()},100))}createToggleButton(e){let t=document.createElement("button");t.className="tack-toggle",t.setAttribute("aria-label","Toggle comments"),t.setAttribute("aria-expanded","false"),t.innerHTML=`
1886
1886
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1887
1887
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
1888
1888
  </svg>
@@ -1894,7 +1894,7 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1894
1894
  body {
1895
1895
  transition: margin-right 250ms cubic-bezier(0.16, 1, 0.3, 1);
1896
1896
  }
1897
- `,document.head.appendChild(t)}setPanelOpen(e){e?document.body.classList.add("tack-panel-open"):document.body.classList.remove("tack-panel-open")}updateToggleAria(e){let t=this.shadowRoot?.querySelector(".tack-toggle");t&&t.setAttribute("aria-expanded",String(e))}async loadComments(){try{let e=await this.api.getComments();this.comments=e.comments,this.currentVersion=e.version,this.pins?.render(this.comments),this.panel?.render(this.comments)}catch(e){console.error("[Tack] Failed to load comments:",e)}}onElementSelected(e){this.form?.isFormVisible()||(this.selector?.disable(),this.form?.show(e))}async onCommentSubmit(e){try{let t={content:e.content,element_selector:e.anchor.cssSelector,x_percent:e.anchor.relativeX*100,y_percent:e.anchor.relativeY*100,anchor:e.anchor,page_path:window.location.pathname+window.location.search,screenshot_data:e.screenshot};this.auth.isAuthenticated()||(t.author_name=e.authorName,t.author_email=e.authorEmail);let i=await this.api.createComment(t),n={...i,screenshot_url:i.screenshot_url||e.screenshot||null};this.comments.push(n),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.panel?.isOpen()&&this.enableCommentMode()}catch(t){console.error("[Tack] Failed to submit comment:",t),this.showToast("Failed to add comment")}}onCommentClick(e){this.pins?.highlight(e.id),this.scrollToComment(e)}onPinClick(e,t){let i=this.comments.find(n=>n.id===e);i&&(this.card?.show(i,t),this.pins?.setActive(e),this.pins?.highlight(e),this.panel?.isOpen()&&this.panel.scrollToComment(e))}onCardClose(){this.pins?.setActive(null)}async onResolve(e,t){try{await this.api.updateComment(e,{resolved:t});let i=this.comments.find(n=>n.id===e);i&&(i.resolved=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to update comment:",i)}}async onReply(e,t){try{let i={content:t,parent_id:e,page_path:window.location.pathname+window.location.search};this.auth.isAuthenticated()||(i.author_name=localStorage.getItem("tack_author_name")||"Anonymous");let n=await this.api.createComment(i),r=this.comments.find(a=>a.id===e);r&&(r.replies=r.replies||[],r.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(r))}catch(i){console.error("[Tack] Failed to submit reply:",i)}}async onEdit(e,t){try{await this.api.updateComment(e,{content:t});let i=this.comments.find(n=>n.id===e);i&&(i.content=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to edit comment:",i),this.showToast("Failed to edit comment")}}async onDelete(e){try{await this.api.deleteComment(e),this.comments=this.comments.filter(t=>t.id!==e),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}scrollToComment(e){if(e.element_selector)document.querySelector(e.element_selector)?.scrollIntoView({behavior:"smooth",block:"center"});else if(e.x_percent!==null&&e.y_percent!==null){let t=e.x_percent/100*document.documentElement.scrollWidth,i=e.y_percent/100*document.documentElement.scrollHeight;window.scrollTo({left:t-window.innerWidth/2,top:i-window.innerHeight/2,behavior:"smooth"})}}handleDeepLink(){let e=new URLSearchParams(window.location.search);e.get("tack_open")==="true"&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0));let i=e.get("tack_comment");if(i){let n=this.comments.find(r=>r.id===i);n&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0),this.panel?.scrollToComment(i),this.pins?.highlight(i),this.scrollToComment(n))}}subscribeToRealtime(){if(!this.currentVersion||!this.config.supabaseUrl||!this.config.supabaseKey){this.pollingInterval=setInterval(()=>this.loadComments(),3e4);return}this.realtime=new S(this.config.supabaseUrl,this.config.supabaseKey,this.currentVersion.id,(e,t)=>{this.handleRealtimeEvent(e,t)}),this.realtime.connect()}handleRealtimeEvent(e,t){switch(e){case"INSERT":if(this.comments.some(r=>r.id===t.id)||this.comments.some(r=>r.replies?.some(a=>a.id===t.id)))return;if(t.parent_id){let r=this.comments.find(a=>a.id===t.parent_id);r&&(r.replies=r.replies||[],r.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":let n=this.comments.find(r=>r.id===t.id);n&&Object.assign(n,t);break;case"DELETE":this.comments=this.comments.filter(r=>r.id!==t.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments)}showToast(e){if(!this.shadowRoot)return;let t=document.createElement("div");t.className="tack-toast",t.textContent=e,t.style.cssText=`
1897
+ `,document.head.appendChild(t)}setPanelOpen(e){e?document.body.classList.add("tack-panel-open"):document.body.classList.remove("tack-panel-open")}updateToggleAria(e){let t=this.shadowRoot?.querySelector(".tack-toggle");t&&t.setAttribute("aria-expanded",String(e))}async loadComments(){try{let e=await this.api.getComments();this.comments=e.comments,this.currentVersion=e.version;let t=this.comments.flatMap(i=>[i.author_avatar_url,...i.replies?.map(n=>n.author_avatar_url)||[]]);await h.preload(t),this.pins?.render(this.comments),this.panel?.render(this.comments)}catch(e){console.error("[Tack] Failed to load comments:",e)}}onElementSelected(e){this.form?.isFormVisible()||(this.selector?.disable(),this.form?.show(e))}async onCommentSubmit(e){try{let t={content:e.content,element_selector:e.anchor.cssSelector,x_percent:e.anchor.relativeX*100,y_percent:e.anchor.relativeY*100,anchor:e.anchor,page_path:this.getPagePath(),screenshot_data:e.screenshot};this.auth.isAuthenticated()||(t.author_name=e.authorName,t.author_email=e.authorEmail);let i=await this.api.createComment(t),n={...i,screenshot_url:i.screenshot_url||e.screenshot||null};this.comments.push(n),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.panel?.isOpen()&&this.enableCommentMode()}catch(t){console.error("[Tack] Failed to submit comment:",t),this.showToast("Failed to add comment")}}onCommentClick(e){this.pins?.highlight(e.id),this.scrollToComment(e)}onPinClick(e,t){let i=this.comments.find(n=>n.id===e);i&&(this.card?.show(i,t),this.pins?.setActive(e),this.pins?.highlight(e),this.panel?.isOpen()&&this.panel.scrollToComment(e))}onCardClose(){this.pins?.setActive(null)}async onResolve(e,t){try{await this.api.updateComment(e,{resolved:t});let i=this.comments.find(n=>n.id===e);i&&(i.resolved=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to update comment:",i)}}async onReply(e,t){try{let i={content:t,parent_id:e,page_path:this.getPagePath()};this.auth.isAuthenticated()||(i.author_name=localStorage.getItem("tack_author_name")||"Anonymous");let n=await this.api.createComment(i),r=this.comments.find(a=>a.id===e);r&&(r.replies=r.replies||[],r.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(r))}catch(i){console.error("[Tack] Failed to submit reply:",i)}}async onEdit(e,t){try{await this.api.updateComment(e,{content:t});let i=this.comments.find(n=>n.id===e);i&&(i.content=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to edit comment:",i),this.showToast("Failed to edit comment")}}async onDelete(e){try{await this.api.deleteComment(e),this.comments=this.comments.filter(t=>t.id!==e),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}scrollToComment(e){if(e.element_selector)document.querySelector(e.element_selector)?.scrollIntoView({behavior:"smooth",block:"center"});else if(e.x_percent!==null&&e.y_percent!==null){let t=e.x_percent/100*document.documentElement.scrollWidth,i=e.y_percent/100*document.documentElement.scrollHeight;window.scrollTo({left:t-window.innerWidth/2,top:i-window.innerHeight/2,behavior:"smooth"})}}handleDeepLink(){let e=new URLSearchParams(window.location.search);e.get("tack_open")==="true"&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0));let i=e.get("tack_comment");if(i){let n=this.comments.find(r=>r.id===i);n&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0),this.panel?.scrollToComment(i),this.pins?.highlight(i),this.scrollToComment(n))}}subscribeToRealtime(){if(!this.currentVersion||!this.config.supabaseUrl||!this.config.supabaseKey){this.pollingInterval=setInterval(()=>this.loadComments(),3e4);return}this.realtime=new A(this.config.supabaseUrl,this.config.supabaseKey,this.currentVersion.id,(e,t)=>{this.handleRealtimeEvent(e,t)}),this.realtime.connect()}handleRealtimeEvent(e,t){switch(e){case"INSERT":if(this.comments.some(r=>r.id===t.id)||this.comments.some(r=>r.replies?.some(a=>a.id===t.id)))return;if(t.parent_id){let r=this.comments.find(a=>a.id===t.parent_id);r&&(r.replies=r.replies||[],r.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":let n=this.comments.find(r=>r.id===t.id);n&&Object.assign(n,t);break;case"DELETE":this.comments=this.comments.filter(r=>r.id!==t.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments)}showToast(e){if(!this.shadowRoot)return;let t=document.createElement("div");t.className="tack-toast",t.textContent=e,t.style.cssText=`
1898
1898
  position: fixed;
1899
1899
  bottom: 80px;
1900
1900
  right: 20px;
@@ -1905,5 +1905,5 @@ var k=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.b
1905
1905
  font-size: 14px;
1906
1906
  z-index: 10002;
1907
1907
  animation: tack-toast-in 0.3s ease;
1908
- `,this.shadowRoot.appendChild(t),setTimeout(()=>{t.remove()},3e3)}destroy(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.selector?.disable(),this.realtime?.disconnect(),this.presence?.leave(),this.pins?.destroy(),this.boundOnUrlChange&&(window.removeEventListener("popstate",this.boundOnUrlChange),this.boundOnUrlChange=null),this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),document.getElementById("tack-page-styles")?.remove(),document.body.classList.remove("tack-panel-open"),this.container?.remove()}};var Me={init(l){let e=new L(l);return e.mount(),e}};export{Me as Tack,L as TackWidget};
1908
+ `,this.shadowRoot.appendChild(t),setTimeout(()=>{t.remove()},3e3)}destroy(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.selector?.disable(),this.realtime?.disconnect(),this.presence?.leave(),this.pins?.destroy(),h.destroy(),this.boundOnUrlChange&&(window.removeEventListener("popstate",this.boundOnUrlChange),this.boundOnUrlChange=null),this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),document.getElementById("tack-page-styles")?.remove(),document.body.classList.remove("tack-panel-open"),this.container?.remove()}};var Ue={init(l){let e=new P(l);return e.mount(),e}};export{Ue as Tack,P as TackWidget};
1909
1909
  //# sourceMappingURL=index.mjs.map