@tacktext/widget 0.1.9 → 0.1.11
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.js +61 -30
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +61 -30
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var oe=Object.create;var E=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty;var he=(o,e)=>{for(var t in e)E(o,t,{get:e[t],enumerable:!0})},W=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ce(e))!pe.call(o,n)&&n!==t&&E(o,n,{get:()=>e[n],enumerable:!(i=le(e,n))||i.enumerable});return o};var ue=(o,e,t)=>(t=o!=null?oe(de(o)):{},W(e||!o||!o.__esModule?E(t,"default",{value:o,enumerable:!0}):t,o)),me=o=>W(E({},"__esModule",{value:!0}),o);var ye={};he(ye,{Tack:()=>xe,TackWidget:()=>b});module.exports=me(ye);var C=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 addReaction(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}/reactions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({emoji:t})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to add reaction")}async removeReaction(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}/reactions`,{method:"DELETE",headers:this.getHeaders(),body:JSON.stringify({emoji:t})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to remove reaction")}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 T=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 a=new URL(this.apiUrl).origin,r=l=>{if(l.data?.type!=="tack:auth"||l.origin!==a)return;window.removeEventListener("message",r),clearInterval(s);let{token:c,user:d}=l.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",r);let s=setInterval(()=>{n.closed&&(clearInterval(s),window.removeEventListener("message",r),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 K(){return`
|
|
2
2
|
* {
|
|
3
3
|
box-sizing: border-box;
|
|
4
4
|
}
|
|
@@ -244,10 +244,11 @@
|
|
|
244
244
|
grid-area: 1 / 1;
|
|
245
245
|
}
|
|
246
246
|
|
|
247
|
-
/* Multi-author shell becomes pill-shaped \u2014 width set via
|
|
247
|
+
/* Multi-author shell becomes pill-shaped \u2014 collapsed width set via --pin-w custom property */
|
|
248
248
|
.tack-pin.multi-author .tack-pin-shell {
|
|
249
249
|
border-radius: 17px;
|
|
250
250
|
padding: 3px;
|
|
251
|
+
width: var(--pin-w, 74px);
|
|
251
252
|
max-height: 34px;
|
|
252
253
|
}
|
|
253
254
|
|
|
@@ -366,9 +367,9 @@
|
|
|
366
367
|
}
|
|
367
368
|
|
|
368
369
|
.tack-pin.expanded.multi-author .tack-pin-shell {
|
|
370
|
+
--pin-w: 256px;
|
|
369
371
|
border-radius: 14px;
|
|
370
|
-
|
|
371
|
-
max-height: 130px;
|
|
372
|
+
max-height: 160px;
|
|
372
373
|
}
|
|
373
374
|
|
|
374
375
|
/* Fade avatar/stacked avatars when expanded (not display:none) */
|
|
@@ -471,6 +472,28 @@
|
|
|
471
472
|
transform 120ms cubic-bezier(0.4, 0, 0.2, 1) 140ms;
|
|
472
473
|
}
|
|
473
474
|
|
|
475
|
+
/* Multi-author preview: avatar stack row at top */
|
|
476
|
+
.tack-pin-preview-avatars {
|
|
477
|
+
display: flex;
|
|
478
|
+
align-items: center;
|
|
479
|
+
margin-bottom: 6px;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
.tack-pin-preview-avatars .tack-pin-avatar-stacked {
|
|
483
|
+
width: 24px;
|
|
484
|
+
height: 24px;
|
|
485
|
+
border-radius: 50%;
|
|
486
|
+
margin-left: -6px;
|
|
487
|
+
position: relative;
|
|
488
|
+
flex-shrink: 0;
|
|
489
|
+
overflow: hidden;
|
|
490
|
+
border: 2px solid #FFFFFF;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
.tack-pin-preview-avatars .tack-pin-avatar-stacked:first-child {
|
|
494
|
+
margin-left: 0;
|
|
495
|
+
}
|
|
496
|
+
|
|
474
497
|
/* Reply count badge */
|
|
475
498
|
.tack-pin-preview-replies {
|
|
476
499
|
font-size: 11px;
|
|
@@ -2194,7 +2217,7 @@
|
|
|
2194
2217
|
transform: translateY(0);
|
|
2195
2218
|
}
|
|
2196
2219
|
}
|
|
2197
|
-
`}var
|
|
2220
|
+
`}var S=class{constructor(e,t){this.enabled=!1;this.highlightedElement=null;this.highlight=null;this.scrim=null;this.styleElement=null;this.settleTimer=null;this.pendingTarget=null;this.enabledAt=0;this.callback=e,this.onEscape=t,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.onClick=this.onClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this)}enable(){this.enabled||(this.enabled=!0,this.enabledAt=Date.now(),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=`
|
|
2198
2221
|
position: fixed;
|
|
2199
2222
|
inset: 0;
|
|
2200
2223
|
background: rgba(0, 0, 0, 0.03);
|
|
@@ -2213,7 +2236,7 @@
|
|
|
2213
2236
|
`,document.body.appendChild(this.highlight),this.styleElement=document.createElement("style"),this.styleElement.textContent=`
|
|
2214
2237
|
body, body * { cursor: crosshair !important; }
|
|
2215
2238
|
#tack-widget, #tack-widget * { cursor: default !important; }
|
|
2216
|
-
`,document.head.appendChild(this.styleElement))}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.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.highlightedElement=null,this.pendingTarget=null)}inCooldown(){return Date.now()-this.enabledAt<150}onMouseDown(e){e.target.closest("#tack-widget")||this.inCooldown()||(e.preventDefault(),e.stopPropagation())}onMouseMove(e){if(this.inCooldown())return;let t=e.target;if(t.closest("#tack-widget")){this.clearHighlight();return}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 a=window.getComputedStyle(e).borderRadius;this.highlight.style.borderRadius=a&&a!=="0px"?a:"6px"}}onClick(e){if(e.target.closest("#tack-widget")||this.inCooldown())return;e.preventDefault(),e.stopPropagation();let t=e.target,i=t.getBoundingClientRect(),n=(e.clientX-i.left)/i.width,a=(e.clientY-i.top)/i.height,r=e.clientX/window.innerWidth,s=e.clientY/window.innerHeight,l=this.generateAnchor(t,n,a,r,s);this.callback({element:t,anchor:l}),this.clearHighlight()}onKeyDown(e){e.key==="Escape"&&(this.disable(),this.onEscape?.())}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,n,a){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,viewportRelativeX:n,viewportRelativeY:a}}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 l=i.className.trim().split(/\s+/).filter(c=>!this.isDynamicClass(c));l.length>0&&(n+="."+l.slice(0,2).map(c=>CSS.escape(c)).join("."))}let a=i.getAttribute("data-testid")||i.getAttribute("data-test-id");a&&(n+=`[data-testid="${CSS.escape(a)}"]`);let r=i.parentElement;if(r){let l=Array.from(r.children).filter(c=>c.tagName===i.tagName);if(l.length>1){let c=l.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=r}return t.join(" > ")}generateXPath(e){let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase(),a=i.parentElement;if(a){let r=Array.from(a.children).filter(s=>s.tagName===i.tagName);if(r.length>1){let s=r.indexOf(i)+1;n+=`[${s}]`}}t.unshift(n),i=a}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="",a="";if(i){let r=i.textContent||"",s=r.indexOf(t);s>0&&(n=r.slice(Math.max(0,s-32),s).trim());let l=s+t.length;l<r.length&&(a=r.slice(l,l+32).trim())}return{prefix:n,exact:t.slice(0,200),suffix:a}}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",a=`${i}:${n}:${t}`,r=5381;for(let s=0;s<a.length;s++)r=(r<<5)+r+a.charCodeAt(s);return(r>>>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
|
|
2239
|
+
`,document.head.appendChild(this.styleElement))}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.styleElement&&(this.styleElement.remove(),this.styleElement=null),this.highlightedElement=null,this.pendingTarget=null)}inCooldown(){return Date.now()-this.enabledAt<150}onMouseDown(e){e.target.closest("#tack-widget")||this.inCooldown()||(e.preventDefault(),e.stopPropagation())}onMouseMove(e){if(this.inCooldown())return;let t=e.target;if(t.closest("#tack-widget")){this.clearHighlight();return}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 a=window.getComputedStyle(e).borderRadius;this.highlight.style.borderRadius=a&&a!=="0px"?a:"6px"}}onClick(e){if(e.target.closest("#tack-widget")||this.inCooldown())return;e.preventDefault(),e.stopPropagation();let t=e.target,i=t.getBoundingClientRect(),n=(e.clientX-i.left)/i.width,a=(e.clientY-i.top)/i.height,r=e.clientX/window.innerWidth,s=e.clientY/window.innerHeight,l=this.generateAnchor(t,n,a,r,s);this.callback({element:t,anchor:l}),this.clearHighlight()}onKeyDown(e){e.key==="Escape"&&(this.disable(),this.onEscape?.())}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,n,a){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,viewportRelativeX:n,viewportRelativeY:a}}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 l=i.className.trim().split(/\s+/).filter(c=>!this.isDynamicClass(c));l.length>0&&(n+="."+l.slice(0,2).map(c=>CSS.escape(c)).join("."))}let a=i.getAttribute("data-testid")||i.getAttribute("data-test-id");a&&(n+=`[data-testid="${CSS.escape(a)}"]`);let r=i.parentElement;if(r){let l=Array.from(r.children).filter(c=>c.tagName===i.tagName);if(l.length>1){let c=l.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=r}return t.join(" > ")}generateXPath(e){let t=[],i=e;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase(),a=i.parentElement;if(a){let r=Array.from(a.children).filter(s=>s.tagName===i.tagName);if(r.length>1){let s=r.indexOf(i)+1;n+=`[${s}]`}}t.unshift(n),i=a}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="",a="";if(i){let r=i.textContent||"",s=r.indexOf(t);s>0&&(n=r.slice(Math.max(0,s-32),s).trim());let l=s+t.length;l<r.length&&(a=r.slice(l,l+32).trim())}return{prefix:n,exact:t.slice(0,200),suffix:a}}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",a=`${i}:${n}:${t}`,r=5381;for(let s=0;s<a.length;s++)r=(r<<5)+r+a.charCodeAt(s);return(r>>>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 ge(o){return o.id==="tack-widget"||o.classList?.contains("tack-form-highlight")}async function V(o,e,t){let i=(await import("html2canvas")).default;try{if(o){let c=document.querySelector(o);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,a=t/100*document.documentElement.scrollHeight,r=400,s=300;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,ignoreElements:ge,x:Math.max(0,n-r/2),y:Math.max(0,a-s/2),width:r,height:s})).toDataURL("image/png",.8)}catch(n){console.warn("Tack: Screenshot capture failed",n);return}}var g=class g{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.boundOnOutsideClick=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=`
|
|
2217
2240
|
position: fixed;
|
|
2218
2241
|
pointer-events: none;
|
|
2219
2242
|
border: 2px solid #14B8A6;
|
|
@@ -2255,10 +2278,10 @@
|
|
|
2255
2278
|
Sign in
|
|
2256
2279
|
</button>
|
|
2257
2280
|
</div>
|
|
2258
|
-
`,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-inspect-toggle")?.addEventListener("click",i=>{i.stopPropagation();let n=e.querySelector(".tack-form-inspect");n&&n.classList.toggle("expanded")}),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.hasContent()?this.jitter():this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await
|
|
2259
|
-
`)),t.classList.remove("expanded"),t.style.display=a.length>0?"":"none"}getElementLabel(e,t){if(e.id)return`#${e.id}`;let i=Array.from(e.classList).find(a=>!a.startsWith("tack-")&&a.length>1&&a.length<40);if(i)return`.${i}`;let n=(a,r)=>a.length>r?a.slice(0,r)+"...":a;switch(t){case"button":{let a=(e.textContent||"").trim();return a?`Button "${n(a,24)}"`:"<button>"}case"link":{let a=e.getAttribute("href")||"";if(a)try{let s=new URL(a,window.location.origin);return`Link "${n(s.pathname,28)}"`}catch{return`Link "${n(a,28)}"`}let r=(e.textContent||"").trim();return r?`Link "${n(r,24)}"`:"<a>"}case"image":{let a=e.getAttribute("alt");if(a)return`Image "${n(a,28)}"`;let r=e.getAttribute("src");if(r){let l=r.split("/").pop()?.split("?")[0]||"";if(l)return`Image "${n(l,28)}"`}let s=e.getAttribute("aria-label");return s?`Image "${n(s,28)}"`:e.matches("svg")||e.closest("svg")?"<svg>":"<img>"}case"input":{let a=e.tagName.toLowerCase();if(a==="textarea"){let l=e.getAttribute("name")||e.getAttribute("placeholder")||"";return l?`Textarea "${n(l,24)}"`:"<textarea>"}if(a==="select"){let l=e.getAttribute("name")||"";return l?`Select "${n(l,24)}"`:"<select>"}let r=e.getAttribute("type")||"text",s=e.getAttribute("name")||e.getAttribute("placeholder")||"";return s?`Input ${r} "${n(s,20)}"`:`<input ${r}>`}case"toggle":{let a=e.checked??e.getAttribute("aria-checked")==="true";return`${e.matches('[role="switch"]')?"Switch":e.matches('input[type="radio"], [role="radio"]')?"Radio":"Checkbox"} (${a?"on":"off"})`}case"layout":{let a=window.getComputedStyle(e).display;return`<${e.tagName.toLowerCase()}> ${a}`}default:{let a=e.tagName.toLowerCase(),r=(e.textContent||"").trim();return r.length>0?`<${a}> "${n(r,24)}"`:`<${a}>`}}}getRelevantStyles(e,t){let i=window.getComputedStyle(e),n=
|
|
2281
|
+
`,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-inspect-toggle")?.addEventListener("click",i=>{i.stopPropagation();let n=e.querySelector(".tack-form-inspect");n&&n.classList.toggle("expanded")}),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.hasContent()?this.jitter():this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await V(e.anchor.cssSelector,e.anchor.relativeX*100,e.anchor.relativeY*100),e.element&&this.highlightElement){let c=e.element.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.left=`${c.left-4}px`,this.highlightElement.style.top=`${c.top-4}px`,this.highlightElement.style.width=`${c.width+8}px`,this.highlightElement.style.height=`${c.height+8}px`}let t,i;if(e.element){let c=e.element.getBoundingClientRect();t=c.left+e.anchor.relativeX*c.width+12,i=c.top+e.anchor.relativeY*c.height}else e.anchor.viewportRelativeX!=null&&e.anchor.viewportRelativeY!=null?(t=e.anchor.viewportRelativeX*window.innerWidth+12,i=e.anchor.viewportRelativeY*window.innerHeight):(t=e.anchor.relativeX*window.innerWidth+20,i=e.anchor.relativeY*window.innerHeight);let n=300;t+n>window.innerWidth-20&&(t=Math.max(20,t-n-24));let a=300,r=52,s=Math.min(t,window.innerWidth-a-380),l=Math.min(i,window.innerHeight-r-20);s=Math.max(20,s),l=Math.max(20,l),this.form.style.left=`${s}px`,this.form.style.top=`${l}px`,this.form.classList.add("visible"),this.populateInspect(e.element),this.boundOnOutsideClick=c=>{this.hasContent()?this.jitter():this.hide()},setTimeout(()=>{this.boundOnOutsideClick&&document.addEventListener("mousedown",this.boundOnOutsideClick)},0),setTimeout(()=>{this.form.querySelector("#tack-comment-content")?.focus()},50)}hide(){if(!this.isVisible)return;this.isVisible=!1,this.form.classList.remove("visible"),this.form.classList.remove("jitter"),this.boundOnOutsideClick&&(document.removeEventListener("mousedown",this.boundOnOutsideClick),this.boundOnOutsideClick=null),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");let i=this.form.querySelector(".tack-form-inspect");i&&(i.classList.remove("expanded"),i.style.display="none"),this.onHide?.()}isFormVisible(){return this.isVisible}hasContent(){let e=this.form.querySelector("#tack-comment-content");return!!e&&e.value.trim().length>0}jitter(){this.form.classList.remove("jitter"),this.form.offsetWidth,this.form.classList.add("jitter"),this.form.querySelector("#tack-comment-content")?.focus();let t=()=>{this.form.classList.remove("jitter"),this.form.removeEventListener("animationend",t)};this.form.addEventListener("animationend",t)}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")}}classifyElement(e){if(e.matches('input[type="checkbox"], input[type="radio"], [role="switch"], [role="checkbox"], [role="radio"]'))return"toggle";if(e.matches('button, [role="button"], input[type="submit"], input[type="reset"], input[type="button"]'))return"button";if(e.matches("a[href]"))return"link";if(e.matches("img, picture, video, canvas")||e.closest("svg"))return"image";if(e.matches('input, textarea, select, [contenteditable="true"]'))return"input";if(e.matches('td, th, [role="cell"], [role="columnheader"], [role="rowheader"]'))return"table-cell";if(e.matches("h1, h2, h3, h4, h5, h6, p, span, label, blockquote, li, code, pre, em, strong, small"))return"text";if(e.matches("div, section, main, aside, article, nav, header, footer, ul, ol")&&e.children.length>0){let t=window.getComputedStyle(e).display;if(t.includes("flex")||t.includes("grid"))return"layout"}return"generic"}populateInspect(e){let t=this.form.querySelector(".tack-form-inspect");if(!t)return;if(!e){t.style.display="none";return}let i=this.classifyElement(e),n=this.getElementLabel(e,i),a=this.getRelevantStyles(e,i),r=t.querySelector(".tack-form-inspect-label");r&&(r.textContent=n);let s=t.querySelector(".tack-form-inspect-props");s&&(s.innerHTML=a.map(([l,c])=>`<span class="tack-inspect-prop"><span class="tack-inspect-key">${this.escapeHtml(l)}</span>: <span class="tack-inspect-val">${this.escapeHtml(c)}</span>;</span>`).join(`
|
|
2282
|
+
`)),t.classList.remove("expanded"),t.style.display=a.length>0?"":"none"}getElementLabel(e,t){if(e.id)return`#${e.id}`;let i=Array.from(e.classList).find(a=>!a.startsWith("tack-")&&a.length>1&&a.length<40);if(i)return`.${i}`;let n=(a,r)=>a.length>r?a.slice(0,r)+"...":a;switch(t){case"button":{let a=(e.textContent||"").trim();return a?`Button "${n(a,24)}"`:"<button>"}case"link":{let a=e.getAttribute("href")||"";if(a)try{let s=new URL(a,window.location.origin);return`Link "${n(s.pathname,28)}"`}catch{return`Link "${n(a,28)}"`}let r=(e.textContent||"").trim();return r?`Link "${n(r,24)}"`:"<a>"}case"image":{let a=e.getAttribute("alt");if(a)return`Image "${n(a,28)}"`;let r=e.getAttribute("src");if(r){let l=r.split("/").pop()?.split("?")[0]||"";if(l)return`Image "${n(l,28)}"`}let s=e.getAttribute("aria-label");return s?`Image "${n(s,28)}"`:e.matches("svg")||e.closest("svg")?"<svg>":"<img>"}case"input":{let a=e.tagName.toLowerCase();if(a==="textarea"){let l=e.getAttribute("name")||e.getAttribute("placeholder")||"";return l?`Textarea "${n(l,24)}"`:"<textarea>"}if(a==="select"){let l=e.getAttribute("name")||"";return l?`Select "${n(l,24)}"`:"<select>"}let r=e.getAttribute("type")||"text",s=e.getAttribute("name")||e.getAttribute("placeholder")||"";return s?`Input ${r} "${n(s,20)}"`:`<input ${r}>`}case"toggle":{let a=e.checked??e.getAttribute("aria-checked")==="true";return`${e.matches('[role="switch"]')?"Switch":e.matches('input[type="radio"], [role="radio"]')?"Radio":"Checkbox"} (${a?"on":"off"})`}case"layout":{let a=window.getComputedStyle(e).display;return`<${e.tagName.toLowerCase()}> ${a}`}default:{let a=e.tagName.toLowerCase(),r=(e.textContent||"").trim();return r.length>0?`<${a}> "${n(r,24)}"`:`<${a}>`}}}getRelevantStyles(e,t){let i=window.getComputedStyle(e),n=g.CATEGORY_PROPS[t]||g.CATEGORY_PROPS.generic,a=[];for(let r of n)if(r.startsWith("@")){let s=this.resolveCustomProp(r,e,i);s&&a.push(s)}else{let s=i.getPropertyValue(r);s&&a.push([r,s])}return a.filter(([r,s])=>!(r==="background-color"&&(s==="rgba(0, 0, 0, 0)"||s==="transparent")||r==="text-decoration"&&s.startsWith("none")||r==="object-fit"&&s==="fill"||r==="text-align"&&s==="start"||r==="vertical-align"&&s==="middle"||r==="align-items"&&s==="normal")).map(([r,s])=>{if(r==="font-family"){let l=s.split(",")[0].trim().replace(/^["']|["']$/g,"");return[r,l]}return[r,s]})}resolveCustomProp(e,t,i){switch(e){case"@dimensions":{let n=t.getBoundingClientRect(),a=Math.round(n.width),r=Math.round(n.height);return a===0&&r===0?null:["size",`${a} \xD7 ${r}px`]}case"@state":return["state",t.checked??t.getAttribute("aria-checked")==="true"?"checked":"unchecked"];case"@padding":{let n=i.getPropertyValue("padding-top"),a=i.getPropertyValue("padding-right"),r=i.getPropertyValue("padding-bottom"),s=i.getPropertyValue("padding-left");return n?n===a&&a===r&&r===s?["padding",n]:n===r&&a===s?["padding",`${n} ${a}`]:["padding",`${n} ${a} ${r} ${s}`]:null}case"@layout-direction":{let n=i.display;if(n.includes("flex")){let a=i.getPropertyValue("flex-direction");return a?["flex-direction",a]:null}if(n.includes("grid")){let a=i.getPropertyValue("grid-template-columns");return a&&a.length>40&&(a=a.slice(0,37)+"..."),a?["grid-columns",a]:null}return null}default:return null}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};g.CATEGORY_PROPS={text:["font-size","font-weight","line-height","color","font-family"],button:["font-size","color","background-color","border-radius","@padding"],link:["font-size","color","text-decoration","font-weight"],image:["@dimensions","object-fit","border-radius"],input:["@dimensions","font-size","@padding","border-radius"],toggle:["@state","@dimensions","background-color","border-radius"],"table-cell":["text-align","vertical-align","@padding","font-size","background-color"],layout:["display","@layout-direction","gap","@padding","align-items"],generic:["color","font-size","font-weight","background-color"]};var L=g;var N=[["#818CF8","#6366F1"],["#A78BFA","#7C3AED"],["#F472B6","#EC4899"],["#FBBF24","#F59E0B"],["#34D399","#10B981"],["#60A5FA","#3B82F6"],["#F87171","#EF4444"],["#2DD4BF","#14B8A6"]],J=N.map(([,o])=>o);function G(o){let e=0;for(let t=0;t<o.length;t++)e=o.charCodeAt(t)+((e<<5)-e);return Math.abs(e)}function Q(o){return J[G(o)%J.length]}function P(o){let[e,t]=N[G(o)%N.length];return`linear-gradient(135deg, ${e} 0%, ${t} 100%)`}function u(o){let e=o.trim().split(/\s+/);return e.length>=2?(e[0][0]+e[e.length-1][0]).toUpperCase():o.slice(0,2).toUpperCase()}function f(o,e,t,i=""){let n=Math.round(t*.38),a=i?` ${i}`:"";return e?`<img
|
|
2260
2283
|
src="${e}"
|
|
2261
|
-
alt="${
|
|
2284
|
+
alt="${u(o)}"
|
|
2262
2285
|
referrerpolicy="no-referrer"
|
|
2263
2286
|
crossorigin="anonymous"
|
|
2264
2287
|
class="tack-avatar-img${a}"
|
|
@@ -2266,18 +2289,18 @@
|
|
|
2266
2289
|
onerror="this.style.display='none';this.nextElementSibling.style.display='flex'"
|
|
2267
2290
|
/><div
|
|
2268
2291
|
class="tack-avatar-fallback${a}"
|
|
2269
|
-
style="display:none;width:${t}px;height:${t}px;border-radius:50%;background:${
|
|
2270
|
-
>${
|
|
2292
|
+
style="display:none;width:${t}px;height:${t}px;border-radius:50%;background:${Q(o)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
|
|
2293
|
+
>${u(o)}</div>`:`<div
|
|
2271
2294
|
class="tack-avatar-fallback${a}"
|
|
2272
|
-
style="display:flex;width:${t}px;height:${t}px;border-radius:50%;background:${
|
|
2273
|
-
>${
|
|
2295
|
+
style="display:flex;width:${t}px;height:${t}px;border-radius:50%;background:${Q(o)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
|
|
2296
|
+
>${u(o)}</div>`}var fe="tack-fab-pos-";function Z(){return`${fe}${location.origin}`}function ee(){try{let o=localStorage.getItem(Z());if(!o)return null;let e=JSON.parse(o);return e&&(e.edge==="left"||e.edge==="right")&&typeof e.y=="number"?e:null}catch{return null}}function q(o){try{localStorage.setItem(Z(),JSON.stringify(o))}catch{}}function R(o){let e=document.createElement("div");return e.style.cssText=`
|
|
2274
2297
|
position: fixed;
|
|
2275
2298
|
inset: 0;
|
|
2276
2299
|
z-index: ${o.zIndex};
|
|
2277
2300
|
cursor: ${o.cursor};
|
|
2278
2301
|
background: transparent;
|
|
2279
2302
|
touch-action: none;
|
|
2280
|
-
`,document.body.appendChild(e),e}function
|
|
2303
|
+
`,document.body.appendChild(e),e}function v(o){o&&o.parentNode&&o.parentNode.removeChild(o)}function H(o,e){let i=window.innerHeight-e-20;return Math.max(20,Math.min(o,i))}function $(o,e,t,i,n=5){let a=t-o,r=i-e;return Math.sqrt(a*a+r*r)>n}var ve="tack-panel-side-";function te(){return`${ve}${location.origin}`}function ie(){try{let o=localStorage.getItem(te());if(o==="left"||o==="right")return o}catch{}return"right"}function ne(o){try{localStorage.setItem(te(),o)}catch{}}var re="tack_panel_filters";function be(){try{let o=localStorage.getItem(re);if(o){let e=JSON.parse(o);return{sort:e.sort||"date",showResolved:e.showResolved??!1,onlyYourThreads:e.onlyYourThreads??!1,onlyCurrentPage:e.onlyCurrentPage??!1}}}catch{}return{sort:"date",showResolved:!0,onlyYourThreads:!1,onlyCurrentPage:!1}}function ae(o){try{localStorage.setItem(re,JSON.stringify(o))}catch{}}var A=class{constructor(e,t){this.comments=[];this.searchQuery="";this.searchTimer=null;this.highlightedId=null;this.filterDropdownOpen=!1;this.currentUser=null;this.projectId="";this.dragState="idle";this.dragStartPointer={x:0,y:0};this.dragStartRect=null;this.dragOverlay=null;this.snapHint=null;this.container=e,this.callbacks=t,this.filters=be(),this.readCommentIds=this.loadReadIds(),this.side=ie(),this.strip=this.createPanelStrip(),this.panel=this.strip.querySelector(".tack-panel"),this.applySide(),this.setupHeaderDrag(),this.container.appendChild(this.strip)}getSide(){return this.side}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=`
|
|
2281
2304
|
<div class="tack-panel" role="complementary" aria-label="Comments panel">
|
|
2282
2305
|
<div class="tack-panel-header">
|
|
2283
2306
|
<span class="tack-panel-title">Comments</span>
|
|
@@ -2342,7 +2365,7 @@
|
|
|
2342
2365
|
<span>Only current page</span>
|
|
2343
2366
|
<span class="tack-dropdown-toggle-switch ${t.onlyCurrentPage?"on":""}"><span class="tack-dropdown-toggle-knob"></span></span>
|
|
2344
2367
|
</button>
|
|
2345
|
-
`,e.setAttribute("data-state","open"),e.querySelectorAll(".tack-dropdown-item").forEach(a=>{a.addEventListener("click",r=>{r.stopPropagation();let s=a.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),
|
|
2368
|
+
`,e.setAttribute("data-state","open"),e.querySelectorAll(".tack-dropdown-item").forEach(a=>{a.addEventListener("click",r=>{r.stopPropagation();let s=a.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),ae(this.filters),this.updateFilterBadge(),this.renderFilterDropdown(),this.renderComments()})})}renderMoreDropdown(){}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"))}applySide(){this.side==="left"?this.strip.classList.add("tack-panel-left"):this.strip.classList.remove("tack-panel-left")}switchSide(e){if(e===this.side)return;let t=this.isOpen();this.strip.style.transition="none",this.strip.classList.remove("open"),this.strip.offsetHeight,this.side=e,ne(e),this.applySide(),this.strip.offsetHeight,this.strip.style.transition="",t&&requestAnimationFrame(()=>{this.strip.classList.add("tack-panel-snapping"),this.strip.classList.add("open"),setTimeout(()=>{this.strip.classList.remove("tack-panel-snapping")},350)}),this.callbacks.onSideChange?.(e)}setupHeaderDrag(){let e=this.strip.querySelector(".tack-panel-header");e&&e.addEventListener("pointerdown",t=>{let i=t.target;if(i.closest("button")||i.closest("input")||t.button!==0)return;t.preventDefault(),this.dragState="pending",this.dragStartPointer={x:t.clientX,y:t.clientY},this.dragStartRect=this.strip.getBoundingClientRect();let n=r=>{if(this.dragState==="pending"){if(!$(this.dragStartPointer.x,this.dragStartPointer.y,r.clientX,r.clientY,5))return;this.enterPanelDrag()}this.dragState==="dragging"&&this.updatePanelDrag(r)},a=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",a),this.dragState==="dragging"&&this.finalizePanelDrop(),this.dragState="idle",e.classList.remove("tack-dragging")};window.addEventListener("pointermove",n),window.addEventListener("pointerup",a),window.addEventListener("pointercancel",a)})}enterPanelDrag(){this.dragState="dragging";let e=this.strip.querySelector(".tack-panel-header");e&&e.classList.add("tack-dragging"),this.dragOverlay=R({zIndex:10005,cursor:"grabbing"}),this.strip.classList.add("tack-panel-dragging"),this.dragStartRect&&(this.strip.style.left=`${this.dragStartRect.left}px`,this.strip.style.top=`${this.dragStartRect.top}px`,this.strip.style.right="auto",this.strip.style.transform="none",this.strip.classList.remove("tack-panel-left")),this.createSnapHint()}updatePanelDrag(e){if(!this.dragStartRect)return;let t=e.clientX-this.dragStartPointer.x,i=this.dragStartRect.left+t;this.strip.style.left=`${i}px`;let n=i+this.dragStartRect.width/2,a=window.innerWidth/2,r=n<a?"left":"right";this.updateSnapHint(r)}finalizePanelDrop(){v(this.dragOverlay),this.dragOverlay=null,this.removeSnapHint(),this.strip.classList.remove("tack-panel-dragging");let e=this.strip.getBoundingClientRect(),t=e.left+e.width/2,i=window.innerWidth/2,n=t<i?"left":"right";this.strip.style.left="",this.strip.style.top="",this.strip.style.right="",this.strip.style.transform="",n!==this.side?this.switchSide(n):(this.applySide(),this.isOpen()&&this.strip.classList.add("open"))}createSnapHint(){this.snapHint||(this.snapHint=document.createElement("div"),this.snapHint.style.cssText=`
|
|
2346
2369
|
position: fixed;
|
|
2347
2370
|
top: 0;
|
|
2348
2371
|
bottom: 0;
|
|
@@ -2387,7 +2410,7 @@
|
|
|
2387
2410
|
<p class="tack-empty-title">No comments yet</p>
|
|
2388
2411
|
<p class="tack-empty-subtitle">Click anywhere on the page to add feedback</p>
|
|
2389
2412
|
</div>
|
|
2390
|
-
`;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 l=this.comments.find(c=>c.id===n);l&&this.callbacks.onCommentClick(l)}),i.addEventListener("mouseenter",()=>{this.callbacks.onRowHover?.(n)}),i.addEventListener("mouseleave",()=>{this.callbacks.onRowHoverEnd?.(n)});let a=i.querySelector(".tack-comment-row-resolve");a&&a.addEventListener("click",s=>{s.stopPropagation();let l=this.comments.find(c=>c.id===n);l&&this.callbacks.onResolve(n,!l.resolved)});let r=i.querySelector(".tack-comment-row-more");r&&r.addEventListener("click",s=>{s.stopPropagation();let l=this.comments.find(c=>c.id===n);l&&this.callbacks.onCommentClick(l)})})}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"),
|
|
2413
|
+
`;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 l=this.comments.find(c=>c.id===n);l&&this.callbacks.onCommentClick(l)}),i.addEventListener("mouseenter",()=>{this.callbacks.onRowHover?.(n)}),i.addEventListener("mouseleave",()=>{this.callbacks.onRowHoverEnd?.(n)});let a=i.querySelector(".tack-comment-row-resolve");a&&a.addEventListener("click",s=>{s.stopPropagation();let l=this.comments.find(c=>c.id===n);l&&this.callbacks.onResolve(n,!l.resolved)});let r=i.querySelector(".tack-comment-row-more");r&&r.addEventListener("click",s=>{s.stopPropagation();let l=this.comments.find(c=>c.id===n);l&&this.callbacks.onCommentClick(l)})})}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"),ae(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(),a=e.page_path===n,r=this.formatPagePath(e.page_path),s=!this.isRead(e.id);return`
|
|
2391
2414
|
<div class="tack-comment-row ${t?"highlighted":""}" data-id="${e.id}">
|
|
2392
2415
|
<div class="tack-comment-row-actions">
|
|
2393
2416
|
<button class="tack-comment-row-more" data-action="more" data-id="${e.id}" title="More actions">
|
|
@@ -2398,7 +2421,7 @@
|
|
|
2398
2421
|
</button>
|
|
2399
2422
|
</div>
|
|
2400
2423
|
<div class="tack-comment-row-top">
|
|
2401
|
-
${
|
|
2424
|
+
${f(e.author_name,e.author_avatar_url,32,"tack-comment-avatar")}
|
|
2402
2425
|
${s?'<span class="tack-unread-dot"></span>':""}
|
|
2403
2426
|
</div>
|
|
2404
2427
|
<div class="tack-comment-meta">
|
|
@@ -2411,17 +2434,25 @@
|
|
|
2411
2434
|
<div class="tack-comment-content">${this.escapeHtml(e.content)}</div>
|
|
2412
2435
|
</div>
|
|
2413
2436
|
</div>
|
|
2414
|
-
`}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(a=>a.user_id===t||a.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,a=this.isRead(i.id)?1:0;return n!==a?n-a: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,a=i.replies?.length||0;return a!==n?a-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}getFilteredCommentIds(){return this.getFilteredComments().map(e=>e.id)}highlightRow(e){let t=this.panel.querySelector(`.tack-comment-row[data-id="${e}"]`);t&&t.classList.add("pin-hover")}clearRowHighlight(e){let t=this.panel.querySelector(`.tack-comment-row[data-id="${e}"]`);t&&t.classList.remove("pin-hover")}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
|
|
2415
|
-
|
|
2416
|
-
<div class="tack-pin-preview-
|
|
2417
|
-
<div class="tack-pin-preview-meta">
|
|
2437
|
+
`}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(a=>a.user_id===t||a.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,a=this.isRead(i.id)?1:0;return n!==a?n-a: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,a=i.replies?.length||0;return a!==n?a-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}getFilteredCommentIds(){return this.getFilteredComments().map(e=>e.id)}highlightRow(e){let t=this.panel.querySelector(`.tack-comment-row[data-id="${e}"]`);t&&t.classList.add("pin-hover")}clearRowHighlight(e){let t=this.panel.querySelector(`.tack-comment-row[data-id="${e}"]`);t&&t.classList.remove("pin-hover")}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 F=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,a=i.top+t.relativeY*i.height+window.scrollY;return{x:n,y:a}}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,a=n.textContent?.trim();if(a&&a.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(),a=t.nextNode();for(;a;){let r=a,s=r.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let l=this.similarityScore(s,n);l>.7&&(!i||l>i.score)&&(i={element:r,score:l})}a=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||"",a=e.textContent||"",r=n.indexOf(a);if(r===-1)return!0;if(t.prefix&&!n.slice(Math.max(0,r-50),r).trim().includes(t.prefix.slice(-20)))return!1;if(t.suffix){let s=r+a.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 r=0;r<e.length-1;r++)i.add(e.slice(r,r+2));for(let r=0;r<t.length-1;r++)n.add(t.slice(r,r+2));let a=0;return i.forEach(r=>{n.has(r)&&a++}),2*a/(i.size+n.size)}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",a=`${i}:${n}:${t}`,r=5381;for(let s=0;s<a.length;s++)r=(r<<5)+r+a.charCodeAt(s);return(r>>>0).toString(16)}};function ke(o){return o.map(e=>`${e.id}:${e.resolved}:${e.content}:${e.replies?.length||0}`).join("|")}var M=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.loadingPin=null;this.onHover=null;this.onHoverEnd=null;this.container=e,this.onClick=t,this.anchoring=new F,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+"::"+ke(e);if(i===this.lastFingerprint)return;this.lastFingerprint=i,this.removeLoadingPin(),this.hoverTimers.forEach(a=>clearTimeout(a)),this.hoverTimers.clear(),this.leaveTimers.forEach(a=>clearTimeout(a)),this.leaveTimers.clear(),this.currentlyExpanded=null,this.pinsContainer.innerHTML="",this.pins.clear(),e.filter(a=>!a.parent_id&&a.page_path===t).forEach(a=>{let r=this.createPin(a);r&&(this.pins.set(a.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 a of e.replies){let r=a.user_id||a.author_name;t.has(r)||(t.add(r),i.push({name:a.author_name,avatar_url:a.author_avatar_url}))}return i}renderInsetAvatar(e,t){let i=u(e.name),n=P(e.name),a=Math.round(t*.38);return e.avatar_url?`<img src="${e.avatar_url}" alt="${i}" referrerpolicy="no-referrer" crossorigin="anonymous" 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:${a}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${a}px;">${i}</div>`}renderStackedAvatar(e,t){let i=u(e.name),n=P(e.name),a=Math.round(t*.38);return e.avatar_url?`<img src="${e.avatar_url}" alt="${i}" referrerpolicy="no-referrer" crossorigin="anonymous" 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:${a}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${a}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"),a=e.id===this.activeId,r=e.id===this.highlightedId,s=this.getUniqueAuthors(e),l=s.length>1;n.className=`tack-pin${e.resolved?" resolved":""}${a?" active":""}${r?" highlighted":""}${l?" 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),h=e.replies?.length||0,k;if(l){let y=s.slice(0,3),U=s.length-3,m=`<div class="tack-pin-shell" style="--pin-w:${28+(y.length+(U>0?1:0)-1)*20+6}px"><div class="tack-pin-avatars">`;y.forEach((j,B)=>{m+=`<div class="tack-pin-avatar-stacked" style="z-index:${B+1}">${this.renderStackedAvatar(j,24)}</div>`}),U>0&&(m+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:4">+${U}</div>`),m+="</div>";let w='<div class="tack-pin-preview-avatars">';s.slice(0,4).forEach((j,B)=>{w+=`<div class="tack-pin-avatar-stacked" style="z-index:${B+1}">${this.renderStackedAvatar(j,20)}</div>`}),s.length>4&&(w+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:5;width:24px;height:24px;font-size:8px">+${s.length-4}</div>`),w+="</div>";let se=`<div class="tack-pin-preview">
|
|
2438
|
+
${w}
|
|
2439
|
+
<div class="tack-pin-preview-meta" style="margin-bottom:4px">
|
|
2418
2440
|
<span class="tack-pin-preview-name">${this.escapeHtml(c.name)}</span>
|
|
2419
2441
|
<span class="tack-pin-preview-time">${d}</span>
|
|
2420
2442
|
</div>
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2443
|
+
<p class="tack-pin-preview-text">${p}</p>
|
|
2444
|
+
${h>0?`<span class="tack-pin-preview-replies">${h} ${h===1?"reply":"replies"}</span>`:""}
|
|
2445
|
+
</div>`;m+=`${se}</div>`,k=m}else{let x=s[0],y=`<div class="tack-pin-preview">
|
|
2446
|
+
<div class="tack-pin-preview-header">
|
|
2447
|
+
<div class="tack-pin-preview-avatar">${this.renderInsetAvatar(c,28)}</div>
|
|
2448
|
+
<div class="tack-pin-preview-meta">
|
|
2449
|
+
<span class="tack-pin-preview-name">${this.escapeHtml(c.name)}</span>
|
|
2450
|
+
<span class="tack-pin-preview-time">${d}</span>
|
|
2451
|
+
</div>
|
|
2452
|
+
</div>
|
|
2453
|
+
<p class="tack-pin-preview-text">${p}</p>
|
|
2454
|
+
${h>0?`<span class="tack-pin-preview-replies">${h} ${h===1?"reply":"replies"}</span>`:""}
|
|
2455
|
+
</div>`;k=`<div class="tack-pin-shell">${this.renderInsetAvatar(x,32)}${y}</div>`}e.resolved&&(k+='<div class="tack-pin-check"></div>'),n.innerHTML=k,n.addEventListener("click",x=>{x.stopPropagation(),this.collapsePin(e.id,n),this.onClick(e.id,n)}),this.setupHoverListeners(n,e);let Y={comment:e,element:n,targetElement:i,anchorResult:t};return this.positionPin(Y),n.style.left===""&&n.style.top===""?null:Y}positionPin(e){let{comment:t,element:i,targetElement:n}=e,a=7,r=45;if(t.anchor&&n){let s=this.anchoring.calculatePinPosition(n,t.anchor);i.style.left=`${s.x-a}px`,i.style.top=`${s.y-r}px`;return}if(n){let s=n.getBoundingClientRect();i.style.left=`${s.left+window.scrollX-a}px`,i.style.top=`${s.top+window.scrollY-r}px`;return}if(t.anchor?.viewportRelativeX!=null&&t.anchor?.viewportRelativeY!=null){let s=t.anchor.viewportRelativeX*window.innerWidth+window.scrollX,l=t.anchor.viewportRelativeY*window.innerHeight+window.scrollY;i.style.left=`${s-a}px`,i.style.top=`${l-r}px`;return}if(t.x_percent!==null&&t.y_percent!==null){let s=t.x_percent/100*document.documentElement.scrollWidth,l=t.y_percent/100*document.documentElement.scrollHeight;i.style.left=`${s-a}px`,i.style.top=`${l-r}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.onHover?.(t.id),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.onHoverEnd?.(t.id),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")}setHoverCallbacks(e,t){this.onHover=e,this.onHoverEnd=t}setHoverLinked(e){this.pins.forEach((t,i)=>{t.element.classList.toggle("hover-linked",i===e)})}beacon(e){let t=this.pins.get(e);t&&(t.element.classList.add("beacon"),setTimeout(()=>{t.element.classList.remove("beacon")},700))}getPinElement(e){return this.pins.get(e)?.element||null}showLoadingPin(e,t){this.removeLoadingPin();let i=document.createElement("div");i.className="tack-pin tack-pin-loading";let n=u(t.name),a=P(t.name),r;t.avatar_url?r=`<img src="${t.avatar_url}" alt="${n}" referrerpolicy="no-referrer" crossorigin="anonymous" class="tack-pin-avatar-img" style="width:32px;height:32px;" />`:r=`<div class="tack-pin-avatar-fallback" style="width:32px;height:32px;background:${a};font-size:12px;">${n}</div>`,i.innerHTML=`<div class="tack-pin-shell">${r}<svg class="tack-pin-loading-ring" viewBox="0 0 36 36"><circle cx="18" cy="18" r="16" /></svg></div>`;let s=this.anchoring.resolve(e),l=7,c=45;if(s.element){let d=this.anchoring.calculatePinPosition(s.element,e);i.style.left=`${d.x-l}px`,i.style.top=`${d.y-c}px`}else if(e.relativeX!==void 0&&e.relativeY!==void 0){let d=e.relativeX*document.documentElement.scrollWidth,p=e.relativeY*document.documentElement.scrollHeight;i.style.left=`${d-l}px`,i.style.top=`${p-c}px`}this.loadingPin=i,this.pinsContainer.appendChild(i)}resolveLoadingPin(){if(!this.loadingPin)return;let e=this.loadingPin;e.classList.remove("tack-pin-loading"),e.classList.add("tack-pin-settle"),e.querySelector(".tack-pin-loading-ring")?.remove();let i=e.querySelector(".tack-pin-avatar-img, .tack-pin-avatar-fallback");i&&(i.style.opacity="1",i.style.filter="none"),setTimeout(()=>{e.classList.remove("tack-pin-settle")},350)}failLoadingPin(e){if(!this.loadingPin)return;let t=this.loadingPin;t.classList.remove("tack-pin-loading"),t.classList.add("tack-pin-failed");let i=document.createElement("div");i.className="tack-pin-failed-tooltip",i.textContent="Failed to save. Click to retry.",t.appendChild(i),t.addEventListener("click",n=>{n.stopPropagation(),this.removeLoadingPin(),e()})}removeLoadingPin(){this.loadingPin&&(this.loadingPin.remove(),this.loadingPin=null)}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 I=class{constructor(e,t){this.currentComment=null;this.currentUser=null;this.visible=!1;this.editing=!1;this.dropdownOpen=!1;this.pickerOpen=!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.pickerOpen=!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,a=t.right+n;a+i>window.innerWidth-16&&(a=t.left-i-n),a=Math.max(16,a);let r=t.top,s=300;r+s>window.innerHeight-16&&(r=window.innerHeight-16-s),r=Math.max(16,r),this.card.style.left=`${a}px`,this.card.style.top=`${r}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=`
|
|
2425
2456
|
<div class="tack-card-title-bar">
|
|
2426
2457
|
<span class="tack-card-title">Comment</span>
|
|
2427
2458
|
<div class="tack-card-title-actions">
|
|
@@ -2446,7 +2477,7 @@
|
|
|
2446
2477
|
Resolved by ${this.escapeHtml(e.author_name)}
|
|
2447
2478
|
</div>`),n+=this.renderCommentRow(e,!0),n+='<div class="tack-card-divider"></div>',t.length>0&&(t.forEach((a,r)=>{n+=this.renderCommentRow(a,!1),r<t.length-1&&(n+='<div class="tack-card-divider"></div>')}),n+='<div class="tack-card-divider"></div>'),n+=`
|
|
2448
2479
|
<div class="tack-card-reply-bar">
|
|
2449
|
-
<div class="tack-card-reply-bar-avatar-wrap">${
|
|
2480
|
+
<div class="tack-card-reply-bar-avatar-wrap">${f(i,this.currentUser?.avatar_url||null,24)}</div>
|
|
2450
2481
|
<div class="tack-card-reply-bar-input-wrap">
|
|
2451
2482
|
<input type="text" class="tack-card-reply-bar-input" placeholder="Reply\u2026" data-parent-id="${e.id}" />
|
|
2452
2483
|
<button class="tack-card-reply-bar-send" data-parent-id="${e.id}">
|
|
@@ -2458,7 +2489,7 @@
|
|
|
2458
2489
|
</div>
|
|
2459
2490
|
</div>`,this.card.innerHTML=n}renderCommentRow(e,t){let i=this.formatTimeAgo(new Date(e.created_at)),n=t&&this.isOwnComment(e),a=`<div class="tack-card-row${t?" main":""}" data-comment-id="${e.id}">`;return a+=`
|
|
2460
2491
|
<div class="tack-card-row-header">
|
|
2461
|
-
<div class="tack-card-row-avatar-wrap">${
|
|
2492
|
+
<div class="tack-card-row-avatar-wrap">${f(e.author_name,e.author_avatar_url,28)}</div>
|
|
2462
2493
|
<div class="tack-card-row-meta">
|
|
2463
2494
|
<span class="tack-card-row-author">${this.escapeHtml(e.author_name)}</span>
|
|
2464
2495
|
${this.editing&&t?'<span class="tack-card-editing-badge">Editing</span>':""}
|
|
@@ -2480,7 +2511,7 @@
|
|
|
2480
2511
|
<button class="tack-card-edit-cancel">Cancel</button>
|
|
2481
2512
|
<button class="tack-card-edit-save">Save</button>
|
|
2482
2513
|
</div>
|
|
2483
|
-
</div>`:a+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,t&&(a+=this.renderReactions(e)),a+="</div>",a}renderReactions(e){let t=e.reactions||[],i=this.currentUser?.id,n=new Map;for(let r of t){let s=n.get(r.emoji)||{count:0,userReacted:!1,users:[]};s.count++,s.users.push(r.user_name),r.user_id===i&&(s.userReacted=!0),n.set(r.emoji,s)}let a='<div class="tack-reaction-bar">';for(let[r,s]of n){let l=s.userReacted?" mine":"",c=s.users.join(", ");a+=`<button class="tack-reaction-pill${l}" data-emoji="${r}" title="${this.escapeHtml(c)}">${r} ${s.count}</button>`}if(a+='<button class="tack-reaction-add" title="Add reaction">+</button>',this.pickerOpen){let r=["\u{1F44D}","\u{1F44E}","\u2764\uFE0F","\u{1F389}","\u{1F440}","\u{1F680}"];a+='<div class="tack-reaction-picker">';for(let s of r){let l=n.get(s)?.userReacted?" mine":"";a+=`<button class="tack-reaction-picker-item${l}" data-picker-emoji="${s}">${s}</button>`}a+="</div>"}return a+="</div>",a}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 a=this.card.querySelector(".tack-card-edit-textarea");a?.focus(),a?.setSelectionRange(a.value.length,a.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.querySelectorAll(".tack-reaction-pill").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.emoji,a=t.classList.contains("mine");this.callbacks.onReaction(this.currentComment.id,n,!a)})}),this.card.querySelector(".tack-reaction-add")?.addEventListener("click",t=>{t.stopPropagation(),this.pickerOpen=!this.pickerOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-reaction-picker-item").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.pickerEmoji,a=t.classList.contains("mine");this.pickerOpen=!1,this.callbacks.onReaction(this.currentComment.id,n,!a)})}),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 M=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 I=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 a=n[0];this.users.set(i,{id:a.user_id||i,name:a.name||"Unknown",avatar_url:a.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 a=t[n]?.metas;if(a?.length>0){let r=a[0];this.users.set(n,{id:r.user_id||n,name:r.name||"Unknown",avatar_url:r.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 O=44,j=20,D=class{constructor(e,t){this.expanded=!1;this.dragState="idle";this.startPointerX=0;this.startPointerY=0;this.startFabX=0;this.startFabY=0;this.dragOverlay=null;this.snapHint=null;this.handledByPointer=!1;this.boundOnPointerMove=null;this.boundOnPointerUp=null;this.boundOnResize=null;this.callbacks=t;let i=G();this.position=i||{edge:"right",y:window.innerHeight-O-j},this.el=document.createElement("div"),this.el.className="tack-fab tack-fab--entering",this.position.edge==="left"&&this.el.classList.add("tack-fab--left"),this.panelToggleBtn=document.createElement("button"),this.panelToggleBtn.className="tack-fab-btn tack-fab-panel-toggle",this.panelToggleBtn.setAttribute("aria-label","Toggle panel"),this.panelToggleBtn.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="15" y1="3" x2="15" y2="21"></line></svg>',this.panelToggleBtn.addEventListener("click",n=>{n.stopPropagation(),!this.handledByPointer&&this.dragState!=="dragging"&&this.callbacks.onPanelToggle()}),this.mainBtn=document.createElement("button"),this.mainBtn.className="tack-fab-main",this.mainBtn.setAttribute("aria-label","Toggle comments"),this.commentIcon=document.createElement("span"),this.commentIcon.className="tack-fab-icon tack-fab-icon--comment",this.commentIcon.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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></svg>',this.closeIcon=document.createElement("span"),this.closeIcon.className="tack-fab-icon tack-fab-icon--close",this.closeIcon.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',this.mainBtn.appendChild(this.commentIcon),this.mainBtn.appendChild(this.closeIcon),this.badge=document.createElement("span"),this.badge.className="tack-fab-badge",this.el.appendChild(this.panelToggleBtn),this.el.appendChild(this.mainBtn),this.el.appendChild(this.badge),e.appendChild(this.el),this.applyPosition(),setTimeout(()=>{this.el.classList.remove("tack-fab--entering")},500),this.el.addEventListener("pointerdown",this.onPointerDown.bind(this)),this.boundOnResize=this.onResize.bind(this),window.addEventListener("resize",this.boundOnResize)}applyPosition(){let e=P(this.position.y,O);this.position.y=e,this.el.style.left="",this.el.style.right="",this.el.style.bottom="",this.position.edge==="left"?this.el.style.left=`${j}px`:this.el.style.right=`${j}px`,this.el.style.top=`${e}px`,this.el.classList.toggle("tack-fab--left",this.position.edge==="left")}onResize(){this.dragState==="idle"&&(this.position.y=P(this.position.y,O),this.applyPosition(),U(this.position))}onPointerDown(e){if(e.button!==0)return;this.dragState="pending",this.startPointerX=e.clientX,this.startPointerY=e.clientY;let t=this.el.getBoundingClientRect();this.startFabX=t.left,this.startFabY=t.top,this.boundOnPointerMove=this.onPointerMove.bind(this),this.boundOnPointerUp=this.onPointerUp.bind(this),window.addEventListener("pointermove",this.boundOnPointerMove),window.addEventListener("pointerup",this.boundOnPointerUp)}onPointerMove(e){if(this.dragState==="pending"){if(!R(this.startPointerX,this.startPointerY,e.clientX,e.clientY))return;this.enterDragState()}if(this.dragState!=="dragging")return;let t=e.clientX-this.startPointerX,i=e.clientY-this.startPointerY,n=this.startFabX+t,a=this.startFabY+i;this.el.style.left=`${n}px`,this.el.style.right="auto",this.el.style.top=`${a}px`,this.updateSnapHint(e.clientX)}onPointerUp(e){let t=this.dragState==="dragging";if(this.dragState==="pending"){this.cleanupDragListeners(),this.dragState="idle",this.handleFabClick(e);return}t&&this.exitDragState(e),this.cleanupDragListeners()}enterDragState(){this.dragState="dragging",this.expanded&&this.collapse(),this.dragOverlay=L({zIndex:10004,cursor:"grabbing"}),this.el.classList.add("tack-fab-dragging");let e=this.el.getBoundingClientRect();this.el.style.left=`${e.left}px`,this.el.style.right="auto",this.el.style.top=`${e.top}px`,document.body.style.userSelect="none"}exitDragState(e){this.dragState="idle",g(this.dragOverlay),this.dragOverlay=null,this.removeSnapHint(),this.el.classList.remove("tack-fab-dragging");let t=this.el.getBoundingClientRect(),n=t.left+t.width/2<window.innerWidth/2?"left":"right",a=P(t.top,O);this.position={edge:n,y:a},U(this.position),this.el.classList.add("tack-fab-snapping"),this.applyPosition();let r=()=>{this.el.classList.remove("tack-fab-snapping"),this.el.removeEventListener("transitionend",r),this.el.classList.add("tack-fab-settling"),setTimeout(()=>{this.el.classList.remove("tack-fab-settling")},350)};this.el.addEventListener("transitionend",r),setTimeout(()=>{this.el.classList.remove("tack-fab-snapping"),this.el.classList.remove("tack-fab-settling")},800),document.body.style.userSelect=""}handleFabClick(e){let i=e.composedPath().includes(this.panelToggleBtn);if(this.handledByPointer=!0,setTimeout(()=>{this.handledByPointer=!1},100),i){this.callbacks.onPanelToggle();return}this.expanded?this.callbacks.onExit():this.callbacks.onToggle()}cleanupDragListeners(){this.boundOnPointerMove&&(window.removeEventListener("pointermove",this.boundOnPointerMove),this.boundOnPointerMove=null),this.boundOnPointerUp&&(window.removeEventListener("pointerup",this.boundOnPointerUp),this.boundOnPointerUp=null)}updateSnapHint(e){let t=e<window.innerWidth/2?"left":"right";this.snapHint||(this.snapHint=document.createElement("div"),this.snapHint.style.cssText=`
|
|
2514
|
+
</div>`:a+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,t&&(a+=this.renderReactions(e)),a+="</div>",a}renderReactions(e){let t=e.reactions||[],i=this.currentUser?.id,n=new Map;for(let r of t){let s=n.get(r.emoji)||{count:0,userReacted:!1,users:[]};s.count++,s.users.push(r.user_name),r.user_id===i&&(s.userReacted=!0),n.set(r.emoji,s)}let a='<div class="tack-reaction-bar">';for(let[r,s]of n){let l=s.userReacted?" mine":"",c=s.users.join(", ");a+=`<button class="tack-reaction-pill${l}" data-emoji="${r}" title="${this.escapeHtml(c)}">${r} ${s.count}</button>`}if(a+='<button class="tack-reaction-add" title="Add reaction">+</button>',this.pickerOpen){let r=["\u{1F44D}","\u{1F44E}","\u2764\uFE0F","\u{1F389}","\u{1F440}","\u{1F680}"];a+='<div class="tack-reaction-picker">';for(let s of r){let l=n.get(s)?.userReacted?" mine":"";a+=`<button class="tack-reaction-picker-item${l}" data-picker-emoji="${s}">${s}</button>`}a+="</div>"}return a+="</div>",a}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 a=this.card.querySelector(".tack-card-edit-textarea");a?.focus(),a?.setSelectionRange(a.value.length,a.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.querySelectorAll(".tack-reaction-pill").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.emoji,a=t.classList.contains("mine");this.callbacks.onReaction(this.currentComment.id,n,!a)})}),this.card.querySelector(".tack-reaction-add")?.addEventListener("click",t=>{t.stopPropagation(),this.pickerOpen=!this.pickerOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-reaction-picker-item").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.pickerEmoji,a=t.classList.contains("mine");this.pickerOpen=!1,this.callbacks.onReaction(this.currentComment.id,n,!a)})}),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 O=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 D=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 a=n[0];this.users.set(i,{id:a.user_id||i,name:a.name||"Unknown",avatar_url:a.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 a=t[n]?.metas;if(a?.length>0){let r=a[0];this.users.set(n,{id:r.user_id||n,name:r.name||"Unknown",avatar_url:r.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 z=44,X=20,_=class{constructor(e,t){this.expanded=!1;this.dragState="idle";this.startPointerX=0;this.startPointerY=0;this.startFabX=0;this.startFabY=0;this.dragOverlay=null;this.snapHint=null;this.handledByPointer=!1;this.boundOnPointerMove=null;this.boundOnPointerUp=null;this.boundOnResize=null;this.callbacks=t;let i=ee();this.position=i||{edge:"right",y:window.innerHeight-z-X},this.el=document.createElement("div"),this.el.className="tack-fab tack-fab--entering",this.position.edge==="left"&&this.el.classList.add("tack-fab--left"),this.panelToggleBtn=document.createElement("button"),this.panelToggleBtn.className="tack-fab-btn tack-fab-panel-toggle",this.panelToggleBtn.setAttribute("aria-label","Toggle panel"),this.panelToggleBtn.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><line x1="15" y1="3" x2="15" y2="21"></line></svg>',this.panelToggleBtn.addEventListener("click",n=>{n.stopPropagation(),!this.handledByPointer&&this.dragState!=="dragging"&&this.callbacks.onPanelToggle()}),this.mainBtn=document.createElement("button"),this.mainBtn.className="tack-fab-main",this.mainBtn.setAttribute("aria-label","Toggle comments"),this.commentIcon=document.createElement("span"),this.commentIcon.className="tack-fab-icon tack-fab-icon--comment",this.commentIcon.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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></svg>',this.closeIcon=document.createElement("span"),this.closeIcon.className="tack-fab-icon tack-fab-icon--close",this.closeIcon.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>',this.mainBtn.appendChild(this.commentIcon),this.mainBtn.appendChild(this.closeIcon),this.badge=document.createElement("span"),this.badge.className="tack-fab-badge",this.el.appendChild(this.panelToggleBtn),this.el.appendChild(this.mainBtn),this.el.appendChild(this.badge),e.appendChild(this.el),this.applyPosition(),setTimeout(()=>{this.el.classList.remove("tack-fab--entering")},500),this.el.addEventListener("pointerdown",this.onPointerDown.bind(this)),this.boundOnResize=this.onResize.bind(this),window.addEventListener("resize",this.boundOnResize)}applyPosition(){let e=H(this.position.y,z);this.position.y=e,this.el.style.left="",this.el.style.right="",this.el.style.bottom="",this.position.edge==="left"?this.el.style.left=`${X}px`:this.el.style.right=`${X}px`,this.el.style.top=`${e}px`,this.el.classList.toggle("tack-fab--left",this.position.edge==="left")}onResize(){this.dragState==="idle"&&(this.position.y=H(this.position.y,z),this.applyPosition(),q(this.position))}onPointerDown(e){if(e.button!==0)return;this.dragState="pending",this.startPointerX=e.clientX,this.startPointerY=e.clientY;let t=this.el.getBoundingClientRect();this.startFabX=t.left,this.startFabY=t.top,this.boundOnPointerMove=this.onPointerMove.bind(this),this.boundOnPointerUp=this.onPointerUp.bind(this),window.addEventListener("pointermove",this.boundOnPointerMove),window.addEventListener("pointerup",this.boundOnPointerUp)}onPointerMove(e){if(this.dragState==="pending"){if(!$(this.startPointerX,this.startPointerY,e.clientX,e.clientY))return;this.enterDragState()}if(this.dragState!=="dragging")return;let t=e.clientX-this.startPointerX,i=e.clientY-this.startPointerY,n=this.startFabX+t,a=this.startFabY+i;this.el.style.left=`${n}px`,this.el.style.right="auto",this.el.style.top=`${a}px`,this.updateSnapHint(e.clientX)}onPointerUp(e){let t=this.dragState==="dragging";if(this.dragState==="pending"){this.cleanupDragListeners(),this.dragState="idle",this.handleFabClick(e);return}t&&this.exitDragState(e),this.cleanupDragListeners()}enterDragState(){this.dragState="dragging",this.expanded&&this.collapse(),this.dragOverlay=R({zIndex:10004,cursor:"grabbing"}),this.el.classList.add("tack-fab-dragging");let e=this.el.getBoundingClientRect();this.el.style.left=`${e.left}px`,this.el.style.right="auto",this.el.style.top=`${e.top}px`,document.body.style.userSelect="none"}exitDragState(e){this.dragState="idle",v(this.dragOverlay),this.dragOverlay=null,this.removeSnapHint(),this.el.classList.remove("tack-fab-dragging");let t=this.el.getBoundingClientRect(),n=t.left+t.width/2<window.innerWidth/2?"left":"right",a=H(t.top,z);this.position={edge:n,y:a},q(this.position),this.el.classList.add("tack-fab-snapping"),this.applyPosition();let r=()=>{this.el.classList.remove("tack-fab-snapping"),this.el.removeEventListener("transitionend",r),this.el.classList.add("tack-fab-settling"),setTimeout(()=>{this.el.classList.remove("tack-fab-settling")},350)};this.el.addEventListener("transitionend",r),setTimeout(()=>{this.el.classList.remove("tack-fab-snapping"),this.el.classList.remove("tack-fab-settling")},800),document.body.style.userSelect=""}handleFabClick(e){let i=e.composedPath().includes(this.panelToggleBtn);if(this.handledByPointer=!0,setTimeout(()=>{this.handledByPointer=!1},100),i){this.callbacks.onPanelToggle();return}this.expanded?this.callbacks.onExit():this.callbacks.onToggle()}cleanupDragListeners(){this.boundOnPointerMove&&(window.removeEventListener("pointermove",this.boundOnPointerMove),this.boundOnPointerMove=null),this.boundOnPointerUp&&(window.removeEventListener("pointerup",this.boundOnPointerUp),this.boundOnPointerUp=null)}updateSnapHint(e){let t=e<window.innerWidth/2?"left":"right";this.snapHint||(this.snapHint=document.createElement("div"),this.snapHint.style.cssText=`
|
|
2484
2515
|
position: fixed;
|
|
2485
2516
|
top: 0;
|
|
2486
2517
|
width: 3px;
|
|
@@ -2489,7 +2520,7 @@
|
|
|
2489
2520
|
z-index: 10003;
|
|
2490
2521
|
pointer-events: none;
|
|
2491
2522
|
transition: left 150ms ease, right 150ms ease, opacity 150ms ease;
|
|
2492
|
-
`,document.body.appendChild(this.snapHint)),t==="left"?(this.snapHint.style.left="0px",this.snapHint.style.right="auto"):(this.snapHint.style.left="auto",this.snapHint.style.right="0px"),this.snapHint.style.opacity="1"}removeSnapHint(){if(this.snapHint){this.snapHint.style.opacity="0";let e=this.snapHint;this.snapHint=null,setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},150)}}expand(){this.expanded||(this.expanded=!0,this.el.classList.add("tack-fab--expanded"),this.badge.classList.remove("visible"))}collapse(){this.expanded&&(this.expanded=!1,this.el.classList.remove("tack-fab--expanded"),setTimeout(()=>{!this.expanded&&parseInt(this.badge.textContent||"0",10)>0&&this.badge.classList.add("visible")},200))}isExpanded(){return this.expanded}getEdge(){return this.position.edge}setPanelToggleActive(e){this.panelToggleBtn.classList.toggle("tack-fab-btn--active",e)}setBadgeCount(e){this.badge.textContent=e>99?"99+":String(e),!this.expanded&&e>0?this.badge.classList.add("visible"):this.badge.classList.remove("visible")}destroy(){this.cleanupDragListeners(),g(this.dragOverlay),this.removeSnapHint(),document.body.style.userSelect="",this.boundOnResize&&(window.removeEventListener("resize",this.boundOnResize),this.boundOnResize=null),this.el.remove()}};var f=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.fab=null;this.state="idle";this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.boundOnKeyDown=null;this.navigationIndex=-1;this.pendingRetryData=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 w(this.config.apiUrl,this.config.projectId),this.auth=new E(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=q(),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 C(this.onElementSelected.bind(this),()=>this.transitionTo("idle")),this.form=new T(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.state==="active"&&setTimeout(()=>{this.state==="active"&&this.selector?.enable()},100)}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new H(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:()=>this.transitionTo("active"),onAddComment:()=>this.transitionTo("active"),onShare:this.onShare.bind(this),onRowHover:i=>{this.pins?.setHoverLinked(i)},onRowHoverEnd:()=>{this.pins?.setHoverLinked(null)},onSideChange:()=>{this.state==="active-panel"&&(this.fab&&this.panel?.setFabOffset(this.fab.getEdge()),this.setPanelOpen(!0))}}),this.card=new $(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onReaction:this.onReaction.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 F(t,this.onPinClick.bind(this)),this.pins.setHoverCallbacks(i=>{this.panel?.highlightRow(i)},i=>{this.panel?.clearRowHighlight(i)}),this.fab=new D(t,{onToggle:()=>{this.state==="idle"&&this.transitionTo("active")},onPanelToggle:()=>{this.state==="active"?this.transitionTo("active-panel"):this.state==="active-panel"&&this.transitionTo("active")},onExit:()=>{this.transitionTo("idle")}}),document.body.appendChild(this.container),await this.loadComments(),this.handleDeepLink(),this.subscribeToRealtime(),this.setupKeyboardShortcuts(),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 I(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))}transitionTo(e){let t=this.state;if(e==="idle"){if(this.form?.isFormVisible()&&this.form.hasContent()){this.form.jitter();return}this.selector?.disable(),this.form?.hide(),this.pins?.hide(),t==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),this.fab?.collapse(),this.container?.classList.remove("tack-active"),this.fab?.setPanelToggleActive(!1),this.updateFabBadge()}else e==="active"?(this.selector?.enable(),this.pins?.show(),t==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),t==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!1)):e==="active-panel"&&(this.selector?.disable(),this.pins?.show(),this.fab&&this.panel?.setFabOffset(this.fab.getEdge()),this.panel?.show(),this.setPanelOpen(!0),t==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!0));this.state=e}updateFabBadge(){let e=this.comments.filter(t=>!t.resolved&&!t.parent_id).length;this.fab?.setBadgeCount(e)}onShare(){let e=new URL(window.location.href);e.searchParams.set("tack_open","true"),navigator.clipboard.writeText(e.toString()).then(()=>{this.showToast("Link copied to clipboard")}).catch(()=>{this.showToast("Failed to copy link")})}injectPageStyles(){}setPanelOpen(e){}setupKeyboardShortcuts(){this.boundOnKeyDown=this.handleKeyDown.bind(this),document.addEventListener("keydown",this.boundOnKeyDown)}handleKeyDown(e){if(e.metaKey||e.ctrlKey||e.altKey)return;let t=e.key.toLowerCase();if(t!=="c"&&t!=="n"&&t!=="p")return;let i=document.activeElement;if(i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))return;let n=this.shadowRoot?.activeElement;if(!(n&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))&&!(this.form?.isFormVisible()||this.card?.isVisible())){if(t==="c"){e.preventDefault(),this.state==="idle"?this.transitionTo("active"):this.state==="active-panel"?this.transitionTo("active"):this.transitionTo("idle");return}this.state==="active-panel"&&(t==="n"?(e.preventDefault(),this.navigateComments("next")):t==="p"&&(e.preventDefault(),this.navigateComments("prev")))}}navigateComments(e){let t=this.panel?.getFilteredCommentIds()||[];if(t.length===0)return;e==="next"?this.navigationIndex=this.navigationIndex<t.length-1?this.navigationIndex+1:0:this.navigationIndex=this.navigationIndex>0?this.navigationIndex-1:t.length-1;let i=t[this.navigationIndex],n=this.comments.find(a=>a.id===i);n&&(this.pins?.highlight(i),this.panel?.scrollToComment(i),this.scrollToComment(n))}async loadComments(){try{let e=await this.api.getComments();this.comments=e.comments,this.currentVersion=e.version,this.navigationIndex=-1,this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}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){let t=!1,i=window.setTimeout(()=>{let n=this.auth.getUser();this.pins?.showLoadingPin(e.anchor,{name:n?.name||e.authorName,avatar_url:n?.avatar_url||null}),t=!0},150);try{let n={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()||(n.author_name=e.authorName,n.author_email=e.authorEmail);let a=await this.api.createComment(n);clearTimeout(i),t&&this.pins?.resolveLoadingPin();let r={...a,screenshot_url:a.screenshot_url||e.screenshot||null};this.comments.push(r),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.pendingRetryData=null,this.updateFabBadge(),this.state==="active"&&this.selector?.enable()}catch(n){clearTimeout(i),console.error("[Tack] Failed to submit comment:",n),t?(this.pendingRetryData=e,this.pins?.failLoadingPin(()=>this.retryFailedComment())):this.showToast("Failed to add comment")}}retryFailedComment(){if(!this.pendingRetryData)return;let e=this.pendingRetryData;this.pendingRetryData=null,this.onCommentSubmit(e)}onCommentClick(e){this.scrollToComment(e),setTimeout(()=>{let t=this.pins?.getPinElement(e.id);t&&(this.card?.show(e,t),this.pins?.setActive(e.id),this.pins?.beacon(e.id))},300)}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),this.updateFabBadge())}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),a=this.comments.find(r=>r.id===e);a&&(a.replies=a.replies||[],a.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(a))}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.updateFabBadge(),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}async onReaction(e,t,i){if(!this.auth.isAuthenticated())return;let n=this.comments.find(r=>r.id===e);if(!n)return;let a=this.auth.getUser();n.reactions=n.reactions||[],i?n.reactions.push({emoji:t,user_id:a.id,user_name:a.name}):n.reactions=n.reactions.filter(r=>!(r.emoji===t&&r.user_id===a.id)),this.card?.updateComment(n);try{i?await this.api.addReaction(e,t):await this.api.removeReaction(e,t)}catch(r){console.error("[Tack] Failed to update reaction:",r),await this.loadComments()}}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.transitionTo("active-panel");let i=e.get("tack_comment");if(i){let n=this.comments.find(a=>a.id===i);n&&(this.transitionTo("active-panel"),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 M(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(a=>a.id===t.id)||this.comments.some(a=>a.replies?.some(r=>r.id===t.id)))return;if(t.parent_id){let a=this.comments.find(r=>r.id===t.parent_id);a&&(a.replies=a.replies||[],a.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":let n=this.comments.find(a=>a.id===t.id);n&&Object.assign(n,t);break;case"DELETE":this.comments=this.comments.filter(a=>a.id!==t.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}showToast(e){if(!this.shadowRoot)return;let t=document.createElement("div");t.className="tack-toast",t.textContent=e,t.style.cssText=`
|
|
2523
|
+
`,document.body.appendChild(this.snapHint)),t==="left"?(this.snapHint.style.left="0px",this.snapHint.style.right="auto"):(this.snapHint.style.left="auto",this.snapHint.style.right="0px"),this.snapHint.style.opacity="1"}removeSnapHint(){if(this.snapHint){this.snapHint.style.opacity="0";let e=this.snapHint;this.snapHint=null,setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},150)}}expand(){this.expanded||(this.expanded=!0,this.el.classList.add("tack-fab--expanded"),this.badge.classList.remove("visible"))}collapse(){this.expanded&&(this.expanded=!1,this.el.classList.remove("tack-fab--expanded"),setTimeout(()=>{!this.expanded&&parseInt(this.badge.textContent||"0",10)>0&&this.badge.classList.add("visible")},200))}isExpanded(){return this.expanded}getEdge(){return this.position.edge}setPanelToggleActive(e){this.panelToggleBtn.classList.toggle("tack-fab-btn--active",e)}setBadgeCount(e){this.badge.textContent=e>99?"99+":String(e),!this.expanded&&e>0?this.badge.classList.add("visible"):this.badge.classList.remove("visible")}destroy(){this.cleanupDragListeners(),v(this.dragOverlay),this.removeSnapHint(),document.body.style.userSelect="",this.boundOnResize&&(window.removeEventListener("resize",this.boundOnResize),this.boundOnResize=null),this.el.remove()}};var b=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.fab=null;this.state="idle";this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.boundOnKeyDown=null;this.navigationIndex=-1;this.pendingRetryData=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 C(this.config.apiUrl,this.config.projectId),this.auth=new T(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=K(),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 S(this.onElementSelected.bind(this),()=>this.transitionTo("idle")),this.form=new L(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.state==="active"&&setTimeout(()=>{this.state==="active"&&this.selector?.enable()},100)}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new A(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:()=>this.transitionTo("active"),onAddComment:()=>this.transitionTo("active"),onShare:this.onShare.bind(this),onRowHover:i=>{this.pins?.setHoverLinked(i)},onRowHoverEnd:()=>{this.pins?.setHoverLinked(null)},onSideChange:()=>{this.state==="active-panel"&&(this.fab&&this.panel?.setFabOffset(this.fab.getEdge()),this.setPanelOpen(!0))}}),this.card=new I(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onReaction:this.onReaction.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 M(t,this.onPinClick.bind(this)),this.pins.setHoverCallbacks(i=>{this.panel?.highlightRow(i)},i=>{this.panel?.clearRowHighlight(i)}),this.fab=new _(t,{onToggle:()=>{this.state==="idle"&&this.transitionTo("active")},onPanelToggle:()=>{this.state==="active"?this.transitionTo("active-panel"):this.state==="active-panel"&&this.transitionTo("active")},onExit:()=>{this.transitionTo("idle")}}),document.body.appendChild(this.container),await this.loadComments(),this.handleDeepLink(),this.subscribeToRealtime(),this.setupKeyboardShortcuts(),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 D(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))}transitionTo(e){let t=this.state;if(e==="idle"){if(this.form?.isFormVisible()&&this.form.hasContent()){this.form.jitter();return}this.selector?.disable(),this.form?.hide(),this.pins?.hide(),t==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),this.fab?.collapse(),this.container?.classList.remove("tack-active"),this.fab?.setPanelToggleActive(!1),this.updateFabBadge()}else e==="active"?(this.selector?.enable(),this.pins?.show(),t==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),t==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!1)):e==="active-panel"&&(this.selector?.disable(),this.pins?.show(),this.fab&&this.panel?.setFabOffset(this.fab.getEdge()),this.panel?.show(),this.setPanelOpen(!0),t==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!0));this.state=e}updateFabBadge(){let e=this.comments.filter(t=>!t.resolved&&!t.parent_id).length;this.fab?.setBadgeCount(e)}onShare(){let e=new URL(window.location.href);e.searchParams.set("tack_open","true"),navigator.clipboard.writeText(e.toString()).then(()=>{this.showToast("Link copied to clipboard")}).catch(()=>{this.showToast("Failed to copy link")})}injectPageStyles(){}setPanelOpen(e){}setupKeyboardShortcuts(){this.boundOnKeyDown=this.handleKeyDown.bind(this),document.addEventListener("keydown",this.boundOnKeyDown)}handleKeyDown(e){if(e.metaKey||e.ctrlKey||e.altKey)return;let t=e.key.toLowerCase();if(t!=="c"&&t!=="n"&&t!=="p")return;let i=document.activeElement;if(i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.isContentEditable))return;let n=this.shadowRoot?.activeElement;if(!(n&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))&&!(this.form?.isFormVisible()||this.card?.isVisible())){if(t==="c"){e.preventDefault(),this.state==="idle"?this.transitionTo("active"):this.state==="active-panel"?this.transitionTo("active"):this.transitionTo("idle");return}this.state==="active-panel"&&(t==="n"?(e.preventDefault(),this.navigateComments("next")):t==="p"&&(e.preventDefault(),this.navigateComments("prev")))}}navigateComments(e){let t=this.panel?.getFilteredCommentIds()||[];if(t.length===0)return;e==="next"?this.navigationIndex=this.navigationIndex<t.length-1?this.navigationIndex+1:0:this.navigationIndex=this.navigationIndex>0?this.navigationIndex-1:t.length-1;let i=t[this.navigationIndex],n=this.comments.find(a=>a.id===i);n&&(this.pins?.highlight(i),this.panel?.scrollToComment(i),this.scrollToComment(n))}async loadComments(){try{let e=await this.api.getComments();this.comments=e.comments,this.currentVersion=e.version,this.navigationIndex=-1,this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}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){let t=!1,i=window.setTimeout(()=>{let n=this.auth.getUser();this.pins?.showLoadingPin(e.anchor,{name:n?.name||e.authorName,avatar_url:n?.avatar_url||null}),t=!0},150);try{let n={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()||(n.author_name=e.authorName,n.author_email=e.authorEmail);let a=await this.api.createComment(n);clearTimeout(i),t&&this.pins?.resolveLoadingPin();let r={...a,screenshot_url:a.screenshot_url||e.screenshot||null};this.comments.push(r),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.pendingRetryData=null,this.updateFabBadge(),this.state==="active"&&this.selector?.enable()}catch(n){clearTimeout(i),console.error("[Tack] Failed to submit comment:",n),t?(this.pendingRetryData=e,this.pins?.failLoadingPin(()=>this.retryFailedComment())):this.showToast("Failed to add comment")}}retryFailedComment(){if(!this.pendingRetryData)return;let e=this.pendingRetryData;this.pendingRetryData=null,this.onCommentSubmit(e)}onCommentClick(e){this.scrollToComment(e),setTimeout(()=>{let t=this.pins?.getPinElement(e.id);t&&(this.card?.show(e,t),this.pins?.setActive(e.id),this.pins?.beacon(e.id))},300)}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),this.updateFabBadge())}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),a=this.comments.find(r=>r.id===e);a&&(a.replies=a.replies||[],a.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(a))}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.updateFabBadge(),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}async onReaction(e,t,i){if(!this.auth.isAuthenticated())return;let n=this.comments.find(r=>r.id===e);if(!n)return;let a=this.auth.getUser();n.reactions=n.reactions||[],i?n.reactions.push({emoji:t,user_id:a.id,user_name:a.name}):n.reactions=n.reactions.filter(r=>!(r.emoji===t&&r.user_id===a.id)),this.card?.updateComment(n);try{i?await this.api.addReaction(e,t):await this.api.removeReaction(e,t)}catch(r){console.error("[Tack] Failed to update reaction:",r),await this.loadComments()}}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.transitionTo("active-panel");let i=e.get("tack_comment");if(i){let n=this.comments.find(a=>a.id===i);n&&(this.transitionTo("active-panel"),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 O(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(a=>a.id===t.id)||this.comments.some(a=>a.replies?.some(r=>r.id===t.id)))return;if(t.parent_id){let a=this.comments.find(r=>r.id===t.parent_id);a&&(a.replies=a.replies||[],a.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":let n=this.comments.find(a=>a.id===t.id);n&&Object.assign(n,t);break;case"DELETE":this.comments=this.comments.filter(a=>a.id!==t.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}showToast(e){if(!this.shadowRoot)return;let t=document.createElement("div");t.className="tack-toast",t.textContent=e,t.style.cssText=`
|
|
2493
2524
|
position: fixed;
|
|
2494
2525
|
bottom: 80px;
|
|
2495
2526
|
right: 20px;
|
|
@@ -2500,5 +2531,5 @@
|
|
|
2500
2531
|
font-size: 14px;
|
|
2501
2532
|
z-index: 10002;
|
|
2502
2533
|
animation: tack-toast-in 0.3s ease;
|
|
2503
|
-
`,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.fab?.destroy(),this.boundOnKeyDown&&(document.removeEventListener("keydown",this.boundOnKeyDown),this.boundOnKeyDown=null),this.boundOnUrlChange&&(window.removeEventListener("popstate",this.boundOnUrlChange),this.boundOnUrlChange=null),this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.container?.remove()}};var
|
|
2534
|
+
`,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.fab?.destroy(),this.boundOnKeyDown&&(document.removeEventListener("keydown",this.boundOnKeyDown),this.boundOnKeyDown=null),this.boundOnUrlChange&&(window.removeEventListener("popstate",this.boundOnUrlChange),this.boundOnUrlChange=null),this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.container?.remove()}};var xe={init(o){let e=new b(o);return e.mount(),e}};0&&(module.exports={Tack,TackWidget});
|
|
2504
2535
|
//# sourceMappingURL=index.js.map
|