@tacktext/widget 0.1.18 → 0.1.19
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 +124 -66
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +122 -64
- 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 ct=Object.create;var S=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ut=(l,t)=>{for(var e in t)S(l,e,{get:t[e],enumerable:!0})},K=(l,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pt(t))!mt.call(l,n)&&n!==e&&S(l,n,{get:()=>t[n],enumerable:!(i=dt(t,n))||i.enumerable});return l};var gt=(l,t,e)=>(e=l!=null?ct(ht(l)):{},K(t||!l||!l.__esModule?S(e,"default",{value:l,enumerable:!0}):e,l)),ft=l=>K(S({},"__esModule",{value:!0}),l);var Ct={};ut(Ct,{Tack:()=>wt,TackWidget:()=>C});module.exports=ft(Ct);var L=class{constructor(t,e){this.authToken=null;this.onUnauthorized=null;this.baseUrl=t,this.projectId=e}setAuthToken(t){this.authToken=t}setOnUnauthorized(t){this.onUnauthorized=t}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}async handleResponse(t){return t.status===401&&this.onUnauthorized?.(),t}async getComments(){let t=await fetch(`${this.baseUrl}/projects/${this.projectId}/comments?path=${encodeURIComponent(window.location.pathname)}`,{headers:this.getHeaders()});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to fetch comments");return t.json()}async createComment(t){let e=await fetch(`${this.baseUrl}/comments`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({project_id:this.projectId,...t})});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to create comment");return e.json()}async updateComment(t,e){let i=await fetch(`${this.baseUrl}/comments/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(e)});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to update comment");return i.json()}async deleteComment(t){let e=await fetch(`${this.baseUrl}/comments/${t}`,{method:"DELETE",headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to delete comment")}async addReaction(t,e){let i=await fetch(`${this.baseUrl}/comments/${t}/reactions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({emoji:e})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to add reaction")}async removeReaction(t,e){let i=await fetch(`${this.baseUrl}/comments/${t}/reactions`,{method:"DELETE",headers:this.getHeaders(),body:JSON.stringify({emoji:e})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to remove reaction")}async markAsRead(t){let e=await fetch(`${this.baseUrl}/comments/${t}/reads`,{method:"POST",headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to mark as read")}async markAsUnread(t){let e=await fetch(`${this.baseUrl}/comments/${t}/reads`,{method:"DELETE",headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to mark as unread")}async batchMarkAsRead(t){let e=await fetch(`${this.baseUrl}/reads/batch`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({comment_ids:t})});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to batch mark as read")}async uploadScreenshot(t){let e=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({image:t,project_id:this.projectId})});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to upload screenshot");let{url:i}=await e.json();return i}};var P=class{constructor(t){this.sessionToken=null;this.user=null;this.onAuthChange=null;this.apiUrl=t}async init(){let t=localStorage.getItem("tack_session");if(t)try{let e=await fetch(`${this.apiUrl}/auth/widget-session`,{headers:{Authorization:`Bearer ${t}`}});if(!e.ok){localStorage.removeItem("tack_session");return}let{user:i}=await e.json();this.sessionToken=t,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((t,e)=>{let i=this.apiUrl.replace(/\/api$/,""),n=window.open(`${i}/auth/widget`,"tack-auth","width=500,height=600,popup=yes");if(!n){e(new Error("Popup blocked"));return}let a=new URL(this.apiUrl).origin,r=o=>{if(o.data?.type!=="tack:auth"||o.origin!==a)return;window.removeEventListener("message",r),clearInterval(s);let{token:c,user:d}=o.data;this.sessionToken=c,this.user={id:d.user_id,name:d.user_name,email:d.user_email,avatar_url:d.user_avatar_url},localStorage.setItem("tack_session",c),this.onAuthChange?.(this.user),t(this.user)};window.addEventListener("message",r);let s=setInterval(()=>{n.closed&&(clearInterval(s),window.removeEventListener("message",r),this.user||e(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(t){this.onAuthChange=t}};function V(){return`
|
|
2
2
|
* {
|
|
3
3
|
box-sizing: border-box;
|
|
4
4
|
}
|
|
@@ -1159,18 +1159,58 @@
|
|
|
1159
1159
|
}
|
|
1160
1160
|
|
|
1161
1161
|
.tack-comment-avatar {
|
|
1162
|
-
width:
|
|
1163
|
-
height:
|
|
1162
|
+
width: 24px;
|
|
1163
|
+
height: 24px;
|
|
1164
1164
|
border-radius: 50%;
|
|
1165
1165
|
display: flex;
|
|
1166
1166
|
align-items: center;
|
|
1167
1167
|
justify-content: center;
|
|
1168
1168
|
color: white;
|
|
1169
|
-
font-size:
|
|
1169
|
+
font-size: 10px;
|
|
1170
1170
|
font-weight: 600;
|
|
1171
1171
|
flex-shrink: 0;
|
|
1172
1172
|
line-height: 1;
|
|
1173
|
-
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/* Multi-author avatar row (no overlap) */
|
|
1176
|
+
.tack-comment-avatars {
|
|
1177
|
+
display: flex;
|
|
1178
|
+
align-items: center;
|
|
1179
|
+
gap: 4px;
|
|
1180
|
+
flex-shrink: 0;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
.tack-comment-avatar-item {
|
|
1184
|
+
width: 24px;
|
|
1185
|
+
height: 24px;
|
|
1186
|
+
border-radius: 50%;
|
|
1187
|
+
flex-shrink: 0;
|
|
1188
|
+
overflow: hidden;
|
|
1189
|
+
line-height: 1;
|
|
1190
|
+
display: flex;
|
|
1191
|
+
align-items: center;
|
|
1192
|
+
justify-content: center;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
.tack-comment-avatar-item img {
|
|
1196
|
+
display: block;
|
|
1197
|
+
width: 100%;
|
|
1198
|
+
height: 100%;
|
|
1199
|
+
object-fit: cover;
|
|
1200
|
+
border-radius: 50%;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
.tack-comment-avatar-item .tack-avatar-fallback {
|
|
1204
|
+
width: 100% !important;
|
|
1205
|
+
height: 100% !important;
|
|
1206
|
+
font-size: 9px !important;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
.tack-comment-avatar-overflow {
|
|
1210
|
+
background: #E4E4E7;
|
|
1211
|
+
color: #52525B;
|
|
1212
|
+
font-size: 9px;
|
|
1213
|
+
font-weight: 600;
|
|
1174
1214
|
}
|
|
1175
1215
|
|
|
1176
1216
|
.tack-comment-meta {
|
|
@@ -1236,6 +1276,23 @@
|
|
|
1236
1276
|
font-size: 13.5px;
|
|
1237
1277
|
color: #3f3f46;
|
|
1238
1278
|
line-height: 1.5;
|
|
1279
|
+
display: -webkit-box;
|
|
1280
|
+
-webkit-line-clamp: 2;
|
|
1281
|
+
-webkit-box-orient: vertical;
|
|
1282
|
+
overflow: hidden;
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
.tack-comment-replies {
|
|
1286
|
+
display: block;
|
|
1287
|
+
font-size: 12px;
|
|
1288
|
+
font-weight: 500;
|
|
1289
|
+
color: #2563EB;
|
|
1290
|
+
margin-top: 6px;
|
|
1291
|
+
line-height: 1;
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
.tack-comment-body.dimmed ~ .tack-comment-replies {
|
|
1295
|
+
opacity: 0.6;
|
|
1239
1296
|
}
|
|
1240
1297
|
|
|
1241
1298
|
/* New Comment Input */
|
|
@@ -2279,7 +2336,7 @@
|
|
|
2279
2336
|
transform: translateY(0);
|
|
2280
2337
|
}
|
|
2281
2338
|
}
|
|
2282
|
-
`}var R=class{constructor(e
|
|
2339
|
+
`}var R=class{constructor(t,e){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=t,this.onEscape=e,this.onMouseMove=this.onMouseMove.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.onClick=this.onClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this)}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=`
|
|
2283
2340
|
position: fixed;
|
|
2284
2341
|
inset: 0;
|
|
2285
2342
|
background: rgba(0, 0, 0, 0.03);
|
|
@@ -2298,7 +2355,7 @@
|
|
|
2298
2355
|
`,document.body.appendChild(this.highlight),this.styleElement=document.createElement("style"),this.styleElement.textContent=`
|
|
2299
2356
|
body, body * { cursor: crosshair !important; }
|
|
2300
2357
|
#tack-widget, #tack-widget * { cursor: default !important; }
|
|
2301
|
-
`,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(
|
|
2358
|
+
`,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(t){t.target.closest("#tack-widget")||this.inCooldown()||(t.preventDefault(),t.stopPropagation())}onMouseMove(t){if(this.inCooldown())return;let e=t.target;if(e.closest("#tack-widget")){this.clearHighlight();return}e!==this.pendingTarget&&e!==this.highlightedElement&&(this.pendingTarget=e,this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.pendingTarget&&this.pendingTarget!==this.highlightedElement&&this.showHighlight(this.pendingTarget),this.pendingTarget=null},150))}showHighlight(t){if(this.highlightedElement=t,this.highlight){let e=t.getBoundingClientRect(),i=3;this.highlight.style.left=`${e.left-i}px`,this.highlight.style.top=`${e.top-i}px`,this.highlight.style.width=`${e.width+i*2}px`,this.highlight.style.height=`${e.height+i*2}px`,this.highlight.style.opacity="1";let a=window.getComputedStyle(t).borderRadius;this.highlight.style.borderRadius=a&&a!=="0px"?a:"6px"}}onClick(t){if(t.target.closest("#tack-widget")||this.inCooldown())return;t.preventDefault(),t.stopPropagation();let e=t.target,i=e.getBoundingClientRect(),n=(t.clientX-i.left)/i.width,a=(t.clientY-i.top)/i.height,r=t.clientX/window.innerWidth,s=t.clientY/window.innerHeight,o=this.generateAnchor(e,n,a,r,s);this.callback({element:e,anchor:o}),this.clearHighlight()}onKeyDown(t){t.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(t,e,i,n,a){return{cssSelector:this.generateCssSelector(t),xpath:this.generateXPath(t),textQuote:this.generateTextQuote(t),contentHash:this.generateContentHash(t),relativeX:e,relativeY:i,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,viewportRelativeX:n,viewportRelativeY:a}}generateCssSelector(t){if(t.id&&!this.isDynamicId(t.id))return`#${CSS.escape(t.id)}`;let e=[],i=t;for(;i&&i!==document.body;){let n=i.tagName.toLowerCase();if(i.className&&typeof i.className=="string"){let o=i.className.trim().split(/\s+/).filter(c=>!this.isDynamicClass(c));o.length>0&&(n+="."+o.slice(0,2).map(c=>CSS.escape(c)).join("."))}let a=i.getAttribute("data-testid")||i.getAttribute("data-test-id");a&&(n+=`[data-testid="${CSS.escape(a)}"]`);let r=i.parentElement;if(r){let o=Array.from(r.children).filter(c=>c.tagName===i.tagName);if(o.length>1){let c=o.indexOf(i)+1;n+=`:nth-child(${c})`}}e.unshift(n);let s=e.join(" > ");try{if(document.querySelectorAll(s).length===1)return s}catch{}i=r}return e.join(" > ")}generateXPath(t){let e=[],i=t;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}]`}}e.unshift(n),i=a}return"//"+e.join("/")}generateTextQuote(t){let e=t.textContent?.trim();if(!e||e.length===0||e.length>500)return null;let i=t.parentElement,n="",a="";if(i){let r=i.textContent||"",s=r.indexOf(e);s>0&&(n=r.slice(Math.max(0,s-32),s).trim());let o=s+e.length;o<r.length&&(a=r.slice(o,o+32).trim())}return{prefix:n,exact:e.slice(0,200),suffix:a}}generateContentHash(t){let e=t.textContent?.trim().slice(0,500)||"",i=t.tagName.toLowerCase(),n=t.className?.toString()||"",a=`${i}:${n}:${e}`,r=5381;for(let s=0;s<a.length;s++)r=(r<<5)+r+a.charCodeAt(s);return(r>>>0).toString(16)}isDynamicId(t){return/^[:_]/.test(t)||/[0-9]{5,}/.test(t)||/^(ember|react|vue|ng-|_)[0-9]+/.test(t)||/^[a-f0-9]{8,}$/i.test(t)}isDynamicClass(t){return t.startsWith("tack-")||/^css-[a-z0-9]+$/i.test(t)||/^sc-[a-z]+$/i.test(t)||/^emotion-[0-9]+$/i.test(t)||/^_[a-zA-Z0-9]{5,}$/.test(t)||/^[a-z]{1,3}[A-Z][a-zA-Z0-9]{10,}$/.test(t)}};function vt(l){return l.id==="tack-widget"||l.classList?.contains("tack-form-highlight")}async function J(l,t,e){let i=(await import("html2canvas")).default;try{if(l){let c=document.querySelector(l);if(c){let d=c.getBoundingClientRect(),p=20;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,x:Math.max(0,d.left+window.scrollX-p),y:Math.max(0,d.top+window.scrollY-p),width:Math.min(d.width+p*2,600),height:Math.min(d.height+p*2,400)})).toDataURL("image/png",.8)}}let n=t/100*document.documentElement.scrollWidth,a=e/100*document.documentElement.scrollHeight,r=400,s=300;return(await i(document.body,{logging:!1,useCORS:!0,allowTaint:!0,scale:1,ignoreElements:vt,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 y=class y{constructor(t,e){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=t,this.onSubmit=e,this.form=this.createForm(),this.container.appendChild(this.form),this.highlightElement=document.createElement("div"),this.highlightElement.className="tack-form-highlight",this.highlightElement.style.cssText=`
|
|
2302
2359
|
position: fixed;
|
|
2303
2360
|
pointer-events: none;
|
|
2304
2361
|
border: 2px solid #14B8A6;
|
|
@@ -2307,7 +2364,7 @@
|
|
|
2307
2364
|
z-index: 10002;
|
|
2308
2365
|
display: none;
|
|
2309
2366
|
transition: all 0.15s ease;
|
|
2310
|
-
`,document.body.appendChild(this.highlightElement)}setOnHide(
|
|
2367
|
+
`,document.body.appendChild(this.highlightElement)}setOnHide(t){this.onHide=t}setOnSignIn(t){this.onSignIn=t}setUser(t){this.currentUser=t,this.rebuildFormContent()}createForm(){let t=document.createElement("div");return t.className="tack-form",this.buildFormInner(t),t}rebuildFormContent(){this.buildFormInner(this.form)}buildFormInner(t){this.currentUser?t.innerHTML=`
|
|
2311
2368
|
<div class="tack-form-pill">
|
|
2312
2369
|
<div class="tack-form-inspect" style="display:none;">
|
|
2313
2370
|
<button type="button" class="tack-form-inspect-toggle">
|
|
@@ -2327,7 +2384,7 @@
|
|
|
2327
2384
|
</button>
|
|
2328
2385
|
</div>
|
|
2329
2386
|
</div>
|
|
2330
|
-
`:
|
|
2387
|
+
`:t.innerHTML=`
|
|
2331
2388
|
<div class="tack-form-pill tack-form-pill-signin">
|
|
2332
2389
|
<span class="tack-sign-in-prompt-text">Sign in to leave feedback</span>
|
|
2333
2390
|
<button type="button" class="tack-sign-in-btn">
|
|
@@ -2340,29 +2397,29 @@
|
|
|
2340
2397
|
Sign in
|
|
2341
2398
|
</button>
|
|
2342
2399
|
</div>
|
|
2343
|
-
`,this.attachFormListeners(
|
|
2344
|
-
`)),
|
|
2345
|
-
src="${
|
|
2346
|
-
alt="${
|
|
2400
|
+
`,this.attachFormListeners(t)}attachFormListeners(t){t.addEventListener("mousedown",i=>i.stopPropagation()),t.addEventListener("click",i=>i.stopPropagation()),t.querySelector(".tack-sign-in-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.onSignIn?.()}),t.querySelector(".tack-form-inspect-toggle")?.addEventListener("click",i=>{i.stopPropagation();let n=t.querySelector(".tack-form-inspect");n&&n.classList.toggle("expanded")}),t.querySelector(".tack-form-pill-send")?.addEventListener("click",i=>{i.stopPropagation(),this.handleSubmit()});let e=t.querySelector("#tack-comment-content");e&&(e.addEventListener("input",()=>{this.autoExpandTextarea(e);let i=t.querySelector(".tack-form-pill-send");i&&i.classList.toggle("active",e.value.trim().length>0)}),e.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSubmit())})),t.addEventListener("keydown",i=>{let n=i;n.key==="Escape"&&(n.preventDefault(),this.hasContent()?this.jitter():this.hide())})}async show(t){if(this.isVisible)return;if(this.currentTarget=t,this.isVisible=!0,this.capturedScreenshot=await J(t.anchor.cssSelector,t.anchor.relativeX*100,t.anchor.relativeY*100),t.element&&this.highlightElement){let c=t.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 e,i;if(t.element){let c=t.element.getBoundingClientRect();e=c.left+t.anchor.relativeX*c.width+12,i=c.top+t.anchor.relativeY*c.height}else t.anchor.viewportRelativeX!=null&&t.anchor.viewportRelativeY!=null?(e=t.anchor.viewportRelativeX*window.innerWidth+12,i=t.anchor.viewportRelativeY*window.innerHeight):(e=t.anchor.relativeX*window.innerWidth+20,i=t.anchor.relativeY*window.innerHeight);let n=300;e+n>window.innerWidth-20&&(e=Math.max(20,e-n-24));let a=300,r=52,s=Math.min(e,window.innerWidth-a-380),o=Math.min(i,window.innerHeight-r-20);s=Math.max(20,s),o=Math.max(20,o),this.form.style.left=`${s}px`,this.form.style.top=`${o}px`,this.form.classList.add("visible"),this.populateInspect(t.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 t=this.form.querySelector("#tack-comment-content");t&&(t.value="",t.style.height="28px",t.style.overflowY="hidden");let e=this.form.querySelector(".tack-form-pill-send");e&&e.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 t=this.form.querySelector("#tack-comment-content");return!!t&&t.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 e=()=>{this.form.classList.remove("jitter"),this.form.removeEventListener("animationend",e)};this.form.addEventListener("animationend",e)}autoExpandTextarea(t){t.style.height="auto";let e=120;t.style.height=`${Math.min(t.scrollHeight,e)}px`,t.style.overflowY=t.scrollHeight>e?"auto":"hidden"}async handleSubmit(){if(this.isSubmitting||!this.currentTarget)return;let t=this.form.querySelector("#tack-comment-content")?.value.trim();if(!t)return;let e;if(this.currentUser)e=this.currentUser.name;else if(e=this.form.querySelector("#tack-author-name")?.value.trim()||"",!e)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",e);let n={content:t,authorName:e,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(t){if(t.matches('input[type="checkbox"], input[type="radio"], [role="switch"], [role="checkbox"], [role="radio"]'))return"toggle";if(t.matches('button, [role="button"], input[type="submit"], input[type="reset"], input[type="button"]'))return"button";if(t.matches("a[href]"))return"link";if(t.matches("img, picture, video, canvas")||t.closest("svg"))return"image";if(t.matches('input, textarea, select, [contenteditable="true"]'))return"input";if(t.matches('td, th, [role="cell"], [role="columnheader"], [role="rowheader"]'))return"table-cell";if(t.matches("h1, h2, h3, h4, h5, h6, p, span, label, blockquote, li, code, pre, em, strong, small"))return"text";if(t.matches("div, section, main, aside, article, nav, header, footer, ul, ol")&&t.children.length>0){let e=window.getComputedStyle(t).display;if(e.includes("flex")||e.includes("grid"))return"layout"}return"generic"}populateInspect(t){let e=this.form.querySelector(".tack-form-inspect");if(!e)return;if(!t){e.style.display="none";return}let i=this.classifyElement(t),n=this.getElementLabel(t,i),a=this.getRelevantStyles(t,i),r=e.querySelector(".tack-form-inspect-label");r&&(r.textContent=n);let s=e.querySelector(".tack-form-inspect-props");s&&(s.innerHTML=a.map(([o,c])=>`<span class="tack-inspect-prop"><span class="tack-inspect-key">${this.escapeHtml(o)}</span>: <span class="tack-inspect-val">${this.escapeHtml(c)}</span>;</span>`).join(`
|
|
2401
|
+
`)),e.classList.remove("expanded"),e.style.display=a.length>0?"":"none"}getElementLabel(t,e){if(t.id)return`#${t.id}`;let i=Array.from(t.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(e){case"button":{let a=(t.textContent||"").trim();return a?`Button "${n(a,24)}"`:"<button>"}case"link":{let a=t.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=(t.textContent||"").trim();return r?`Link "${n(r,24)}"`:"<a>"}case"image":{let a=t.getAttribute("alt");if(a)return`Image "${n(a,28)}"`;let r=t.getAttribute("src");if(r){let o=r.split("/").pop()?.split("?")[0]||"";if(o)return`Image "${n(o,28)}"`}let s=t.getAttribute("aria-label");return s?`Image "${n(s,28)}"`:t.matches("svg")||t.closest("svg")?"<svg>":"<img>"}case"input":{let a=t.tagName.toLowerCase();if(a==="textarea"){let o=t.getAttribute("name")||t.getAttribute("placeholder")||"";return o?`Textarea "${n(o,24)}"`:"<textarea>"}if(a==="select"){let o=t.getAttribute("name")||"";return o?`Select "${n(o,24)}"`:"<select>"}let r=t.getAttribute("type")||"text",s=t.getAttribute("name")||t.getAttribute("placeholder")||"";return s?`Input ${r} "${n(s,20)}"`:`<input ${r}>`}case"toggle":{let a=t.checked??t.getAttribute("aria-checked")==="true";return`${t.matches('[role="switch"]')?"Switch":t.matches('input[type="radio"], [role="radio"]')?"Radio":"Checkbox"} (${a?"on":"off"})`}case"layout":{let a=window.getComputedStyle(t).display;return`<${t.tagName.toLowerCase()}> ${a}`}default:{let a=t.tagName.toLowerCase(),r=(t.textContent||"").trim();return r.length>0?`<${a}> "${n(r,24)}"`:`<${a}>`}}}getRelevantStyles(t,e){let i=window.getComputedStyle(t),n=y.CATEGORY_PROPS[e]||y.CATEGORY_PROPS.generic,a=[];for(let r of n)if(r.startsWith("@")){let s=this.resolveCustomProp(r,t,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 o=s.split(",")[0].trim().replace(/^["']|["']$/g,"");return[r,o]}return[r,s]})}resolveCustomProp(t,e,i){switch(t){case"@dimensions":{let n=e.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",e.checked??e.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(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}};y.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 A=y;var X=[["#818CF8","#6366F1"],["#A78BFA","#7C3AED"],["#F472B6","#EC4899"],["#FBBF24","#F59E0B"],["#34D399","#10B981"],["#60A5FA","#3B82F6"],["#F87171","#EF4444"],["#2DD4BF","#14B8A6"]],Q=X.map(([,l])=>l);function Z(l){let t=0;for(let e=0;e<l.length;e++)t=l.charCodeAt(e)+((t<<5)-t);return Math.abs(t)}function G(l){return Q[Z(l)%Q.length]}function $(l){let[t,e]=X[Z(l)%X.length];return`linear-gradient(135deg, ${t} 0%, ${e} 100%)`}function f(l){let t=l.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():l.slice(0,2).toUpperCase()}function v(l,t,e,i=""){let n=Math.round(e*.38),a=i?` ${i}`:"";return t?`<img
|
|
2402
|
+
src="${t}"
|
|
2403
|
+
alt="${f(l)}"
|
|
2347
2404
|
referrerpolicy="no-referrer"
|
|
2348
2405
|
crossorigin="anonymous"
|
|
2349
2406
|
class="tack-avatar-img${a}"
|
|
2350
|
-
style="width:${
|
|
2407
|
+
style="width:${e}px;height:${e}px;border-radius:50%;object-fit:cover;"
|
|
2351
2408
|
onerror="this.style.display='none';this.nextElementSibling.style.display='flex'"
|
|
2352
2409
|
/><div
|
|
2353
2410
|
class="tack-avatar-fallback${a}"
|
|
2354
|
-
style="display:none;width:${
|
|
2355
|
-
>${
|
|
2411
|
+
style="display:none;width:${e}px;height:${e}px;border-radius:50%;background:${G(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
|
|
2412
|
+
>${f(l)}</div>`:`<div
|
|
2356
2413
|
class="tack-avatar-fallback${a}"
|
|
2357
|
-
style="display:flex;width:${
|
|
2358
|
-
>${
|
|
2414
|
+
style="display:flex;width:${e}px;height:${e}px;border-radius:50%;background:${G(l)};color:white;font-size:${n}px;font-weight:600;align-items:center;justify-content:center;line-height:1;flex-shrink:0"
|
|
2415
|
+
>${f(l)}</div>`}var bt="tack-fab-pos-";function tt(){return`${bt}${location.origin}`}function et(){try{let l=localStorage.getItem(tt());if(!l)return null;let t=JSON.parse(l);return t&&(t.edge==="left"||t.edge==="right")&&typeof t.y=="number"?t:null}catch{return null}}function Y(l){try{localStorage.setItem(tt(),JSON.stringify(l))}catch{}}function H(l){let t=document.createElement("div");return t.style.cssText=`
|
|
2359
2416
|
position: fixed;
|
|
2360
2417
|
inset: 0;
|
|
2361
|
-
z-index: ${
|
|
2362
|
-
cursor: ${
|
|
2418
|
+
z-index: ${l.zIndex};
|
|
2419
|
+
cursor: ${l.cursor};
|
|
2363
2420
|
background: transparent;
|
|
2364
2421
|
touch-action: none;
|
|
2365
|
-
`,document.body.appendChild(
|
|
2422
|
+
`,document.body.appendChild(t),t}function w(l){l&&l.parentNode&&l.parentNode.removeChild(l)}function F(l,t){let i=window.innerHeight-t-20;return Math.max(20,Math.min(l,i))}function M(l,t,e,i,n=5){let a=e-l,r=i-t;return Math.sqrt(a*a+r*r)>n}var kt="tack-panel-side-";function it(){return`${kt}${location.origin}`}function nt(){try{let l=localStorage.getItem(it());if(l==="left"||l==="right")return l}catch{}return"right"}function at(l){try{localStorage.setItem(it(),l)}catch{}}var st="tack_panel_filters";function xt(){try{let l=localStorage.getItem(st);if(l){let t=JSON.parse(l);return{sort:t.sort||"date",showResolved:t.showResolved??!1,onlyYourThreads:t.onlyYourThreads??!1,onlyCurrentPage:t.onlyCurrentPage??!1}}}catch{}return{sort:"date",showResolved:!0,onlyYourThreads:!1,onlyCurrentPage:!1}}function rt(l){try{localStorage.setItem(st,JSON.stringify(l))}catch{}}var I=class{constructor(t,e){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=t,this.callbacks=e,this.filters=xt(),this.readCommentIds=this.loadReadIds(),this.side=nt(),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(t){this.currentUser=t}setProjectId(t){this.projectId=t,this.readCommentIds=this.loadReadIds()}loadReadIds(){try{let t=`tack_read_${this.projectId}`,e=localStorage.getItem(t);if(e)return new Set(JSON.parse(e))}catch{}return new Set}saveReadIds(){try{let t=`tack_read_${this.projectId}`;localStorage.setItem(t,JSON.stringify([...this.readCommentIds]))}catch{}}syncReadIds(t){for(let e of t)this.readCommentIds.add(e);this.saveReadIds()}markAsRead(t){this.readCommentIds.has(t)||(this.readCommentIds.add(t),this.saveReadIds())}markAsUnread(t){this.readCommentIds.has(t)&&(this.readCommentIds.delete(t),this.saveReadIds())}markVisibleAsRead(){if(!this.isOpen())return;let t=this.getFilteredComments(),e=[];for(let i of t)this.readCommentIds.has(i.id)||(this.readCommentIds.add(i.id),e.push(i.id));e.length>0&&(this.saveReadIds(),this.callbacks.onBatchRead?.(e))}isRead(t){return this.currentUser?this.readCommentIds.has(t):!0}createPanelStrip(){let t=document.createElement("div");t.className="tack-panel-strip",t.innerHTML=`
|
|
2366
2423
|
<div class="tack-panel" role="complementary" aria-label="Comments panel">
|
|
2367
2424
|
<div class="tack-panel-header">
|
|
2368
2425
|
<span class="tack-panel-title">Comments</span>
|
|
@@ -2401,33 +2458,33 @@
|
|
|
2401
2458
|
</div>
|
|
2402
2459
|
<div class="tack-panel-content"></div>
|
|
2403
2460
|
</div>
|
|
2404
|
-
`,
|
|
2461
|
+
`,t.querySelector(".tack-panel-close").addEventListener("click",()=>{this.hide(),this.callbacks.onClose?.()});let e=t.querySelector(".tack-panel-search"),i=t.querySelector(".tack-panel-search-clear");return e.addEventListener("input",()=>{let n=e.value;i.style.display=n?"flex":"none",this.searchTimer&&clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>{this.searchQuery=n.trim().toLowerCase(),this.renderComments()},200)}),i.addEventListener("click",n=>{n.stopPropagation(),e.value="",i.style.display="none",this.searchQuery="",this.renderComments(),e.focus()}),t.querySelector(".tack-panel-filter-btn").addEventListener("click",n=>{n.stopPropagation(),this.filterDropdownOpen=!this.filterDropdownOpen,this.renderFilterDropdown()}),t.addEventListener("click",n=>{!n.target.closest(".tack-panel-filter-wrap")&&this.filterDropdownOpen&&(this.filterDropdownOpen=!1,this.renderFilterDropdown())}),t}renderFilterDropdown(){let t=this.strip.querySelector(".tack-panel-filter-dropdown");if(!this.filterDropdownOpen){t.setAttribute("data-state","closed"),t.innerHTML="";return}let e=this.filters,i='<svg class="tack-dropdown-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>',n='<span class="tack-dropdown-check-space"></span>';t.innerHTML=`
|
|
2405
2462
|
<button class="tack-dropdown-item" data-action="sort-date">
|
|
2406
|
-
${
|
|
2463
|
+
${e.sort==="date"?i:n}
|
|
2407
2464
|
<span>Sort by date</span>
|
|
2408
2465
|
</button>
|
|
2409
2466
|
<button class="tack-dropdown-item" data-action="sort-unread">
|
|
2410
|
-
${
|
|
2467
|
+
${e.sort==="unread"?i:n}
|
|
2411
2468
|
<span>Sort by unread</span>
|
|
2412
2469
|
</button>
|
|
2413
2470
|
<button class="tack-dropdown-item" data-action="sort-replies">
|
|
2414
|
-
${
|
|
2471
|
+
${e.sort==="replies"?i:n}
|
|
2415
2472
|
<span>Sort by most replies</span>
|
|
2416
2473
|
</button>
|
|
2417
2474
|
<div class="tack-dropdown-sep"></div>
|
|
2418
2475
|
<button class="tack-dropdown-item tack-dropdown-toggle" data-action="showResolved">
|
|
2419
2476
|
<span>Show resolved comments</span>
|
|
2420
|
-
<span class="tack-dropdown-toggle-switch ${
|
|
2477
|
+
<span class="tack-dropdown-toggle-switch ${e.showResolved?"on":""}"><span class="tack-dropdown-toggle-knob"></span></span>
|
|
2421
2478
|
</button>
|
|
2422
2479
|
<button class="tack-dropdown-item tack-dropdown-toggle" data-action="onlyYourThreads">
|
|
2423
2480
|
<span>Only your threads</span>
|
|
2424
|
-
<span class="tack-dropdown-toggle-switch ${
|
|
2481
|
+
<span class="tack-dropdown-toggle-switch ${e.onlyYourThreads?"on":""}"><span class="tack-dropdown-toggle-knob"></span></span>
|
|
2425
2482
|
</button>
|
|
2426
2483
|
<button class="tack-dropdown-item tack-dropdown-toggle" data-action="onlyCurrentPage">
|
|
2427
2484
|
<span>Only current page</span>
|
|
2428
|
-
<span class="tack-dropdown-toggle-switch ${
|
|
2485
|
+
<span class="tack-dropdown-toggle-switch ${e.onlyCurrentPage?"on":""}"><span class="tack-dropdown-toggle-knob"></span></span>
|
|
2429
2486
|
</button>
|
|
2430
|
-
`,
|
|
2487
|
+
`,t.setAttribute("data-state","open"),t.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),rt(this.filters),this.updateFilterBadge(),this.renderFilterDropdown(),this.renderComments()})})}renderMoreDropdown(){}updateFilterBadge(){let t=this.strip.querySelector(".tack-panel-filter-badge"),e=this.strip.querySelector(".tack-panel-filter-btn"),i=0;this.filters.showResolved&&i++,this.filters.onlyYourThreads&&i++,this.filters.onlyCurrentPage&&i++,i>0?(t.textContent=String(i),t.style.display="flex",e.classList.add("filter-active")):(t.style.display="none",e.classList.remove("filter-active"))}applySide(){this.side==="left"?this.strip.classList.add("tack-panel-left"):this.strip.classList.remove("tack-panel-left")}switchSide(t){if(t===this.side)return;let e=this.isOpen();this.strip.style.transition="none",this.strip.classList.remove("open"),this.strip.offsetHeight,this.side=t,at(t),this.applySide(),this.strip.offsetHeight,this.strip.style.transition="",e&&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?.(t)}setupHeaderDrag(){let t=this.strip.querySelector(".tack-panel-header");t&&t.addEventListener("pointerdown",e=>{let i=e.target;if(i.closest("button")||i.closest("input")||e.button!==0)return;e.preventDefault(),this.dragState="pending",this.dragStartPointer={x:e.clientX,y:e.clientY},this.dragStartRect=this.strip.getBoundingClientRect();let n=r=>{if(this.dragState==="pending"){if(!M(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",t.classList.remove("tack-dragging")};window.addEventListener("pointermove",n),window.addEventListener("pointerup",a),window.addEventListener("pointercancel",a)})}enterPanelDrag(){this.dragState="dragging";let t=this.strip.querySelector(".tack-panel-header");t&&t.classList.add("tack-dragging"),this.dragOverlay=H({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(t){if(!this.dragStartRect)return;let e=t.clientX-this.dragStartPointer.x,i=this.dragStartRect.left+e;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(){w(this.dragOverlay),this.dragOverlay=null,this.removeSnapHint(),this.strip.classList.remove("tack-panel-dragging");let t=this.strip.getBoundingClientRect(),e=t.left+t.width/2,i=window.innerWidth/2,n=e<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=`
|
|
2431
2488
|
position: fixed;
|
|
2432
2489
|
top: 0;
|
|
2433
2490
|
bottom: 0;
|
|
@@ -2437,7 +2494,7 @@
|
|
|
2437
2494
|
pointer-events: none;
|
|
2438
2495
|
opacity: 0;
|
|
2439
2496
|
transition: opacity 150ms ease;
|
|
2440
|
-
`,document.body.appendChild(this.snapHint))}updateSnapHint(
|
|
2497
|
+
`,document.body.appendChild(this.snapHint))}updateSnapHint(t){this.snapHint&&(t==="left"?(this.snapHint.style.left="0",this.snapHint.style.right="auto"):(this.snapHint.style.right="0",this.snapHint.style.left="auto"),this.snapHint.style.opacity="1")}removeSnapHint(){this.snapHint&&(this.snapHint.remove(),this.snapHint=null)}show(){this.strip.classList.add("open"),this.updateFilterBadge(),setTimeout(()=>this.markVisibleAsRead(),1500)}hide(){this.strip.classList.remove("open"),this.filterDropdownOpen=!1,this.renderFilterDropdown()}setFabOffset(t){let e=t===this.side;this.strip.classList.toggle("tack-panel-fab-offset",e),this.strip.style.left="",this.strip.style.right=""}toggle(){this.strip.classList.contains("open")?this.hide():this.show()}isOpen(){return this.strip.classList.contains("open")}render(t){this.comments=t,this.renderComments(),this.isOpen()&&setTimeout(()=>this.markVisibleAsRead(),1500)}renderPresence(t){}renderComments(){let t=this.panel.querySelector(".tack-panel-content"),e=this.getFilteredComments();if(e.length===0){if(this.searchQuery){let i=(this.filters.showResolved?1:0)+(this.filters.onlyYourThreads?1:0)+(this.filters.onlyCurrentPage?1:0);t.innerHTML=`
|
|
2441
2498
|
<div class="tack-empty">
|
|
2442
2499
|
<div class="tack-empty-icon">
|
|
2443
2500
|
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
|
@@ -2449,7 +2506,7 @@
|
|
|
2449
2506
|
<p class="tack-empty-subtitle">${i>0?"Try adjusting your search or filters":"Try a different search term"}</p>
|
|
2450
2507
|
${i>0?'<button class="tack-empty-reset">Reset filters</button>':""}
|
|
2451
2508
|
</div>
|
|
2452
|
-
`}else this.hasActiveFilters()?
|
|
2509
|
+
`}else this.hasActiveFilters()?t.innerHTML=`
|
|
2453
2510
|
<div class="tack-empty">
|
|
2454
2511
|
<div class="tack-empty-icon">
|
|
2455
2512
|
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
|
@@ -2462,7 +2519,7 @@
|
|
|
2462
2519
|
<p class="tack-empty-subtitle">${this.describeActiveFilters()}</p>
|
|
2463
2520
|
<button class="tack-empty-reset">Reset filters</button>
|
|
2464
2521
|
</div>
|
|
2465
|
-
`:
|
|
2522
|
+
`:t.innerHTML=`
|
|
2466
2523
|
<div class="tack-empty">
|
|
2467
2524
|
<div class="tack-empty-icon">
|
|
2468
2525
|
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
|
@@ -2472,39 +2529,40 @@
|
|
|
2472
2529
|
<p class="tack-empty-title">No comments yet</p>
|
|
2473
2530
|
<p class="tack-empty-subtitle">Click anywhere on the page to add feedback</p>
|
|
2474
2531
|
</div>
|
|
2475
|
-
`;
|
|
2476
|
-
<div class="tack-comment-row ${
|
|
2532
|
+
`;t.querySelector(".tack-empty-reset")?.addEventListener("click",()=>{this.resetFilters()});return}t.innerHTML=e.map(i=>this.renderCommentRow(i)).join(""),t.querySelectorAll(".tack-comment-row").forEach(i=>{let n=i.dataset.id;i.addEventListener("click",()=>{this.markAsRead(n);let s=i.querySelector(".tack-unread-dot");s&&s.remove();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)}),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 o=this.comments.find(c=>c.id===n);o&&this.callbacks.onResolve(n,!o.resolved)});let r=i.querySelector(".tack-comment-row-more");r&&r.addEventListener("click",s=>{s.stopPropagation();let o=this.comments.find(c=>c.id===n);o&&this.callbacks.onCommentClick(o)})})}hasActiveFilters(){return this.filters.showResolved||this.filters.onlyYourThreads||this.filters.onlyCurrentPage}describeActiveFilters(){let t=[];return this.filters.onlyYourThreads&&t.push("only your threads"),this.filters.onlyCurrentPage&&t.push("only current page"),this.filters.showResolved||t.push("resolved comments hidden"),t.length>0?t.join(", ").replace(/^./,e=>e.toUpperCase()):""}resetFilters(){this.filters={sort:"date",showResolved:!1,onlyYourThreads:!1,onlyCurrentPage:!1},this.searchQuery="";let t=this.strip.querySelector(".tack-panel-search");t&&(t.value="");let e=this.strip.querySelector(".tack-panel-search-clear");e&&(e.style.display="none"),rt(this.filters),this.updateFilterBadge(),this.renderComments()}getCurrentPagePath(){return window.location.pathname}formatPagePath(t){if(!t||t==="/")return"Home";let e=t.split("?")[0].slice(1);return e.charAt(0).toUpperCase()+e.slice(1)}getUniqueAuthors(t){let e=new Set,i=[],n=t.user_id||t.author_name;if(e.add(n),i.push({name:t.author_name,avatar_url:t.author_avatar_url}),t.replies)for(let a of t.replies){let r=a.user_id||a.author_name;e.has(r)||(e.add(r),i.push({name:a.author_name,avatar_url:a.author_avatar_url}))}return i}renderCommentRow(t){let e=t.id===this.highlightedId,i=this.formatTimeAgo(new Date(t.created_at)),n=this.getCurrentPagePath(),a=t.page_path===n,r=this.formatPagePath(t.page_path),s=!this.isRead(t.id),o=this.getUniqueAuthors(t),c=t.replies?.length||0,d,p=3;if(o.length>1){let h=o.slice(0,p),m=o.length-p;d='<div class="tack-comment-avatars">';for(let u of h)d+=`<div class="tack-comment-avatar-item">${v(u.name,u.avatar_url,24,"")}</div>`;m>0&&(d+=`<div class="tack-comment-avatar-item tack-comment-avatar-overflow">+${m}</div>`),d+="</div>"}else d=v(t.author_name,t.author_avatar_url,24,"tack-comment-avatar");return`
|
|
2533
|
+
<div class="tack-comment-row ${e?"highlighted":""}" data-id="${t.id}">
|
|
2477
2534
|
<div class="tack-comment-row-actions">
|
|
2478
|
-
<button class="tack-comment-row-more" data-action="more" data-id="${
|
|
2535
|
+
<button class="tack-comment-row-more" data-action="more" data-id="${t.id}" title="More actions">
|
|
2479
2536
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="3" cy="8" r="1.25" fill="currentColor"/><circle cx="8" cy="8" r="1.25" fill="currentColor"/><circle cx="13" cy="8" r="1.25" fill="currentColor"/></svg>
|
|
2480
2537
|
</button>
|
|
2481
|
-
<button class="tack-comment-row-resolve ${
|
|
2538
|
+
<button class="tack-comment-row-resolve ${t.resolved?"resolved":""}" data-action="resolve" data-id="${t.id}" title="${t.resolved?"Unresolve":"Resolve"}">
|
|
2482
2539
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
|
|
2483
2540
|
</button>
|
|
2484
2541
|
</div>
|
|
2485
2542
|
<div class="tack-comment-row-top">
|
|
2486
|
-
${
|
|
2543
|
+
${d}
|
|
2487
2544
|
${s?'<span class="tack-unread-dot"></span>':""}
|
|
2488
2545
|
</div>
|
|
2489
2546
|
<div class="tack-comment-meta">
|
|
2490
|
-
<span class="tack-comment-author">${this.escapeHtml(
|
|
2547
|
+
<span class="tack-comment-author">${this.escapeHtml(t.author_name)}</span>
|
|
2491
2548
|
<span class="tack-comment-time">${i}</span>
|
|
2492
|
-
${
|
|
2549
|
+
${t.resolved?'<span class="tack-comment-resolved-badge">Resolved</span>':""}
|
|
2493
2550
|
${a?"":`<span class="tack-comment-page-badge">${this.escapeHtml(r)}</span>`}
|
|
2494
2551
|
</div>
|
|
2495
|
-
<div class="tack-comment-body ${
|
|
2496
|
-
<div class="tack-comment-content">${this.escapeHtml(
|
|
2552
|
+
<div class="tack-comment-body ${t.resolved?"dimmed":""}">
|
|
2553
|
+
<div class="tack-comment-content">${this.escapeHtml(t.content)}</div>
|
|
2497
2554
|
</div>
|
|
2555
|
+
${c>0?`<span class="tack-comment-replies">${c} ${c===1?"reply":"replies"}</span>`:""}
|
|
2498
2556
|
</div>
|
|
2499
|
-
`}getFilteredComments(){let
|
|
2557
|
+
`}getFilteredComments(){let t=this.comments.filter(e=>!e.parent_id);if(this.filters.showResolved||(t=t.filter(e=>!e.resolved)),this.filters.onlyYourThreads&&this.currentUser){let e=this.currentUser.id,i=this.currentUser.name;t=t.filter(n=>!!(n.user_id===e||n.author_name===i||n.replies?.some(a=>a.user_id===e||a.author_name===i)))}if(this.filters.onlyCurrentPage){let e=this.getCurrentPagePath();t=t.filter(i=>i.page_path===e)}if(this.searchQuery){let e=this.searchQuery;t=t.filter(i=>!!(i.author_name.toLowerCase().includes(e)||i.content.toLowerCase().includes(e)||i.replies?.some(n=>n.content.toLowerCase().includes(e)||n.author_name.toLowerCase().includes(e))))}switch(this.filters.sort){case"unread":t.sort((e,i)=>{let n=this.isRead(e.id)?1:0,a=this.isRead(i.id)?1:0;return n!==a?n-a:new Date(i.created_at).getTime()-new Date(e.created_at).getTime()});break;case"replies":t.sort((e,i)=>{let n=e.replies?.length||0,a=i.replies?.length||0;return a!==n?a-n:new Date(i.created_at).getTime()-new Date(e.created_at).getTime()});break;default:t.sort((e,i)=>new Date(i.created_at).getTime()-new Date(e.created_at).getTime());break}return t}getFilteredCommentIds(){return this.getFilteredComments().map(t=>t.id)}highlightRow(t){let e=this.panel.querySelector(`.tack-comment-row[data-id="${t}"]`);e&&e.classList.add("pin-hover")}clearRowHighlight(t){let e=this.panel.querySelector(`.tack-comment-row[data-id="${t}"]`);e&&e.classList.remove("pin-hover")}scrollToComment(t){this.highlightedId=t,this.renderComments(),this.panel.querySelector(`[data-id="${t}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.highlightedId=null,this.renderComments()},2e3)}formatTimeAgo(t){let e=Math.floor((Date.now()-t.getTime())/1e3);return e<60?"just now":e<3600?`${Math.floor(e/60)}m ago`:e<86400?`${Math.floor(e/3600)}h ago`:e<604800?`${Math.floor(e/86400)}d ago`:t.toLocaleDateString()}escapeHtml(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}};var D=class{resolve(t){if(!t)return{element:null,confidence:"none",method:"none"};if(t.cssSelector){let e=this.tryCssSelector(t);if(e.element)return e}if(t.xpath){let e=this.tryXPath(t);if(e.element)return e}if(t.textQuote){let e=this.tryTextQuote(t.textQuote);if(e.element)return e}if(t.textQuote){let e=this.tryFuzzySearch(t.textQuote);if(e.element)return e}return{element:null,confidence:"none",method:"none"}}calculatePinPosition(t,e){let i=t.getBoundingClientRect(),n=i.left+e.relativeX*i.width+window.scrollX,a=i.top+e.relativeY*i.height+window.scrollY;return{x:n,y:a}}tryCssSelector(t){try{let e=document.querySelector(t.cssSelector);return e?t.contentHash?this.generateContentHash(e)===t.contentHash?{element:e,confidence:"high",method:"css"}:{element:e,confidence:"medium",method:"css"}:{element:e,confidence:"high",method:"css"}:{element:null,confidence:"none",method:"css"}}catch{return{element:null,confidence:"none",method:"css"}}}tryXPath(t){try{let i=document.evaluate(t.xpath,document.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return i?t.contentHash?this.generateContentHash(i)===t.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(t){let e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=e.nextNode();for(;i;){let n=i,a=n.textContent?.trim();if(a&&a.includes(t.exact)&&this.verifyContext(n,t))return{element:n,confidence:"high",method:"textQuote"};i=e.nextNode()}return{element:null,confidence:"none",method:"textQuote"}}tryFuzzySearch(t){let e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=null,n=t.exact.toLowerCase(),a=e.nextNode();for(;a;){let r=a,s=r.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let o=this.similarityScore(s,n);o>.7&&(!i||o>i.score)&&(i={element:r,score:o})}a=e.nextNode()}return i?{element:i.element,confidence:i.score>.9?"medium":"low",method:"fuzzy"}:{element:null,confidence:"none",method:"fuzzy"}}verifyContext(t,e){if(!e.prefix&&!e.suffix)return!0;let i=t.parentElement;if(!i)return!0;let n=i.textContent||"",a=t.textContent||"",r=n.indexOf(a);if(r===-1)return!0;if(e.prefix&&!n.slice(Math.max(0,r-50),r).trim().includes(e.prefix.slice(-20)))return!1;if(e.suffix){let s=r+a.length;if(!n.slice(s,s+50).trim().includes(e.suffix.slice(0,20)))return!1}return!0}similarityScore(t,e){if(t===e)return 1;if(t.length<2||e.length<2)return 0;let i=new Set,n=new Set;for(let r=0;r<t.length-1;r++)i.add(t.slice(r,r+2));for(let r=0;r<e.length-1;r++)n.add(e.slice(r,r+2));let a=0;return i.forEach(r=>{n.has(r)&&a++}),2*a/(i.size+n.size)}generateContentHash(t){let e=t.textContent?.trim().slice(0,500)||"",i=t.tagName.toLowerCase(),n=t.className?.toString()||"",a=`${i}:${n}:${e}`,r=5381;for(let s=0;s<a.length;s++)r=(r<<5)+r+a.charCodeAt(s);return(r>>>0).toString(16)}};function yt(l){return l.map(t=>`${t.id}:${t.resolved}:${t.content}:${t.replies?.length||0}`).join("|")}var _=class{constructor(t,e){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=t,this.onClick=e,this.anchoring=new D,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((t,e)=>{t.targetElement&&!document.contains(t.targetElement)&&(t.anchorResult=this.anchoring.resolve(t.comment.anchor),t.targetElement=t.anchorResult.element),this.positionPin(t)})}getCurrentPagePath(){return window.location.pathname}render(t){let e=this.getCurrentPagePath(),i=e+"::"+yt(t);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(),t.filter(a=>!a.parent_id&&a.page_path===e).forEach(a=>{let r=this.createPin(a);r&&(this.pins.set(a.id,r),this.pinsContainer.appendChild(r.element))})}getUniqueAuthors(t){let e=new Set,i=[],n=t.user_id||t.author_name;if(e.add(n),i.push({name:t.author_name,avatar_url:t.author_avatar_url}),t.replies)for(let a of t.replies){let r=a.user_id||a.author_name;e.has(r)||(e.add(r),i.push({name:a.author_name,avatar_url:a.author_avatar_url}))}return i}renderInsetAvatar(t,e){let i=f(t.name),n=$(t.name),a=Math.round(e*.38);return t.avatar_url?`<img src="${t.avatar_url}" alt="${i}" referrerpolicy="no-referrer" crossorigin="anonymous" class="tack-pin-avatar-img" style="width:${e}px;height:${e}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${e}px;height:${e}px;background:${n};font-size:${a}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${e}px;height:${e}px;background:${n};font-size:${a}px;">${i}</div>`}renderStackedAvatar(t,e){let i=f(t.name),n=$(t.name),a=Math.round(e*.38);return t.avatar_url?`<img src="${t.avatar_url}" alt="${i}" referrerpolicy="no-referrer" crossorigin="anonymous" class="tack-pin-avatar-img" style="width:${e}px;height:${e}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${e}px;height:${e}px;background:${n};font-size:${a}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${e}px;height:${e}px;background:${n};font-size:${a}px;">${i}</div>`}createPin(t){let e={element:null,confidence:"none",method:"none"},i=null;t.anchor?(e=this.anchoring.resolve(t.anchor),i=e.element):t.element_selector&&(i=document.querySelector(t.element_selector),i&&(e={element:i,confidence:"medium",method:"css"}));let n=document.createElement("div"),a=t.id===this.activeId,r=t.id===this.highlightedId,s=this.getUniqueAuthors(t),o=s.length>1;n.className=`tack-pin${t.resolved?" resolved":""}${a?" active":""}${r?" highlighted":""}${o?" multi-author":""}`,n.dataset.id=t.id,e.confidence==="low"&&n.classList.add("low-confidence");let c=s[0],d=this.formatTimeAgo(new Date(t.created_at)),p=this.escapeHtml(t.content),h=t.replies?.length||0,m;if(o){let b=s.slice(0,3),k=s.length-3,x=`<div class="tack-pin-shell" style="--pin-w:${28+(b.length+(k>0?1:0)-1)*20+6}px"><div class="tack-pin-avatars">`;b.forEach((N,q)=>{x+=`<div class="tack-pin-avatar-stacked" style="z-index:${q+1}">${this.renderStackedAvatar(N,24)}</div>`}),k>0&&(x+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:4">+${k}</div>`),x+="</div>";let T='<div class="tack-pin-preview-avatars">';s.slice(0,4).forEach((N,q)=>{T+=`<div class="tack-pin-avatar-stacked" style="z-index:${q+1}">${this.renderStackedAvatar(N,20)}</div>`}),s.length>4&&(T+=`<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>`),T+="</div>";let lt=`<div class="tack-pin-preview">
|
|
2500
2558
|
${T}
|
|
2501
2559
|
<div class="tack-pin-preview-meta" style="margin-bottom:4px">
|
|
2502
2560
|
<span class="tack-pin-preview-name">${this.escapeHtml(c.name)}</span>
|
|
2503
2561
|
<span class="tack-pin-preview-time">${d}</span>
|
|
2504
2562
|
</div>
|
|
2505
|
-
<p class="tack-pin-preview-text">${
|
|
2506
|
-
${
|
|
2507
|
-
</div>`;
|
|
2563
|
+
<p class="tack-pin-preview-text">${p}</p>
|
|
2564
|
+
${h>0?`<span class="tack-pin-preview-replies">${h} ${h===1?"reply":"replies"}</span>`:""}
|
|
2565
|
+
</div>`;x+=`${lt}</div>`,m=x}else{let g=s[0],b=`<div class="tack-pin-preview">
|
|
2508
2566
|
<div class="tack-pin-preview-header">
|
|
2509
2567
|
<div class="tack-pin-preview-avatar">${this.renderInsetAvatar(c,28)}</div>
|
|
2510
2568
|
<div class="tack-pin-preview-meta">
|
|
@@ -2512,13 +2570,13 @@
|
|
|
2512
2570
|
<span class="tack-pin-preview-time">${d}</span>
|
|
2513
2571
|
</div>
|
|
2514
2572
|
</div>
|
|
2515
|
-
<p class="tack-pin-preview-text">${
|
|
2516
|
-
${
|
|
2517
|
-
</div>`;
|
|
2573
|
+
<p class="tack-pin-preview-text">${p}</p>
|
|
2574
|
+
${h>0?`<span class="tack-pin-preview-replies">${h} ${h===1?"reply":"replies"}</span>`:""}
|
|
2575
|
+
</div>`;m=`<div class="tack-pin-shell">${this.renderInsetAvatar(g,32)}${b}</div>`}t.resolved&&(m+='<div class="tack-pin-check"></div>'),n.innerHTML=m,n.addEventListener("click",g=>{g.stopPropagation(),this.collapsePin(t.id,n),this.onClick(t.id,n)}),this.setupHoverListeners(n,t);let u={comment:t,element:n,targetElement:i,anchorResult:e};return this.positionPin(u),n.style.left===""&&n.style.top===""?null:u}positionPin(t){let{comment:e,element:i,targetElement:n}=t,a=7,r=45;if(e.anchor&&n){let s=this.anchoring.calculatePinPosition(n,e.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(e.anchor?.viewportRelativeX!=null&&e.anchor?.viewportRelativeY!=null){let s=e.anchor.viewportRelativeX*window.innerWidth+window.scrollX,o=e.anchor.viewportRelativeY*window.innerHeight+window.scrollY;i.style.left=`${s-a}px`,i.style.top=`${o-r}px`;return}if(e.x_percent!==null&&e.y_percent!==null){let s=e.x_percent/100*document.documentElement.scrollWidth,o=e.y_percent/100*document.documentElement.scrollHeight;i.style.left=`${s-a}px`,i.style.top=`${o-r}px`;return}i.style.display="none"}formatTimeAgo(t){let e=Math.floor((Date.now()-t.getTime())/1e3);return e<60?"just now":e<3600?`${Math.floor(e/60)}m ago`:e<86400?`${Math.floor(e/3600)}h ago`:e<604800?`${Math.floor(e/86400)}d ago`:t.toLocaleDateString()}escapeHtml(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}setupHoverListeners(t,e){t.addEventListener("mouseenter",()=>{let i=this.leaveTimers.get(e.id);i&&(clearTimeout(i),this.leaveTimers.delete(e.id));let n=window.setTimeout(()=>{this.expandPin(e.id,t),this.onHover?.(e.id),this.hoverTimers.delete(e.id)},150);this.hoverTimers.set(e.id,n)}),t.addEventListener("mouseleave",()=>{let i=this.hoverTimers.get(e.id);i&&(clearTimeout(i),this.hoverTimers.delete(e.id));let n=window.setTimeout(()=>{this.collapsePin(e.id,t),this.onHoverEnd?.(e.id),this.leaveTimers.delete(e.id)},120);this.leaveTimers.set(e.id,n)})}expandPin(t,e){if(e.classList.contains("active"))return;if(this.currentlyExpanded&&this.currentlyExpanded!==t){let n=this.pins.get(this.currentlyExpanded);n&&n.element.classList.remove("expanded","expand-left")}this.currentlyExpanded=t;let i=e.getBoundingClientRect();window.innerWidth-i.left<300?e.classList.add("expand-left"):e.classList.remove("expand-left"),e.classList.add("expanded")}collapsePin(t,e){e.classList.remove("expanded","expand-left"),this.currentlyExpanded===t&&(this.currentlyExpanded=null)}setActive(t){this.activeId=t,this.pins.forEach((e,i)=>{e.element.classList.toggle("active",i===t)})}highlight(t){this.highlightedId=t,this.pins.forEach((e,i)=>{e.element.classList.toggle("highlighted",i===t)}),setTimeout(()=>{this.highlightedId=null,this.pins.forEach(e=>{e.element.classList.remove("highlighted")})},2e3)}show(){this.pinsContainer.classList.add("visible")}hide(){this.pinsContainer.classList.remove("visible")}setHoverCallbacks(t,e){this.onHover=t,this.onHoverEnd=e}setHoverLinked(t){this.pins.forEach((e,i)=>{e.element.classList.toggle("hover-linked",i===t)})}beacon(t){let e=this.pins.get(t);e&&(e.element.classList.add("beacon"),setTimeout(()=>{e.element.classList.remove("beacon")},700))}getPinElement(t){return this.pins.get(t)?.element||null}showLoadingPin(t,e){this.removeLoadingPin();let i=document.createElement("div");i.className="tack-pin tack-pin-loading";let n=f(e.name),a=$(e.name),r;e.avatar_url?r=`<img src="${e.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(t),o=7,c=45;if(s.element){let d=this.anchoring.calculatePinPosition(s.element,t);i.style.left=`${d.x-o}px`,i.style.top=`${d.y-c}px`}else if(t.relativeX!==void 0&&t.relativeY!==void 0){let d=t.relativeX*document.documentElement.scrollWidth,p=t.relativeY*document.documentElement.scrollHeight;i.style.left=`${d-o}px`,i.style.top=`${p-c}px`}this.loadingPin=i,this.pinsContainer.appendChild(i)}resolveLoadingPin(){if(!this.loadingPin)return;let t=this.loadingPin;t.classList.remove("tack-pin-loading"),t.classList.add("tack-pin-settle"),t.querySelector(".tack-pin-loading-ring")?.remove();let i=t.querySelector(".tack-pin-avatar-img, .tack-pin-avatar-fallback");i&&(i.style.opacity="1",i.style.filter="none"),setTimeout(()=>{t.classList.remove("tack-pin-settle")},350)}failLoadingPin(t){if(!this.loadingPin)return;let e=this.loadingPin;e.classList.remove("tack-pin-loading"),e.classList.add("tack-pin-failed");let i=document.createElement("div");i.className="tack-pin-failed-tooltip",i.textContent="Failed to save. Click to retry.",e.appendChild(i),e.addEventListener("click",n=>{n.stopPropagation(),this.removeLoadingPin(),t()})}removeLoadingPin(){this.loadingPin&&(this.loadingPin.remove(),this.loadingPin=null)}destroy(){this.hoverTimers.forEach(t=>clearTimeout(t)),this.leaveTimers.forEach(t=>clearTimeout(t)),this.resizeObserver&&this.resizeObserver.disconnect(),this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),window.removeEventListener("scroll",this.boundScheduleReposition),window.removeEventListener("resize",this.boundScheduleReposition)}};var ot={"\u{1F44D}":"thumbs up","\u{1F44E}":"thumbs down","\u2764\uFE0F":"heart","\u{1F389}":"party","\u{1F440}":"eyes","\u{1F680}":"rocket"},z=class{constructor(t,e){this.currentComment=null;this.currentUser=null;this.visible=!1;this.editing=!1;this.activeDropdownId=null;this.activePickerId=null;this.lastAddedReaction=null;this.container=t,this.callbacks=e,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(t){this.currentUser=t}show(t,e){if(this.visible&&this.currentComment?.id===t.id){this.hide();return}this.currentComment=t,this.visible=!0,this.editing=!1,this.activeDropdownId=null,this.activePickerId=null,this.renderCard(t),this.positionNear(e),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.activeDropdownId=null,this.activePickerId=null,this.card.classList.remove("visible"),document.removeEventListener("mousedown",this.boundOnMouseDown,!0),document.removeEventListener("keydown",this.boundOnKeyDown),this.callbacks.onClose())}isVisible(){return this.visible}updateComment(t){!this.visible||this.currentComment?.id!==t.id||(this.currentComment=t,this.renderCard(t),this.attachListeners())}markReactionAdded(t,e){this.lastAddedReaction={commentId:t,emoji:e}}onDocumentMouseDown(t){this.card.contains(t.target)||t.composedPath().includes(this.card)||this.hide()}onKeyDown(t){if(t.key==="Escape"){if(this.activeDropdownId){let e=this.activeDropdownId;this.activeDropdownId=null,this.renderCard(this.currentComment),this.attachListeners(),this.card.querySelector(`.tack-action-more[data-pill-comment-id="${e}"]`)?.focus();return}if(this.activePickerId){let e=this.activePickerId;this.activePickerId=null,this.renderCard(this.currentComment),this.attachListeners(),this.card.querySelector(`.tack-action-emoji[data-pill-comment-id="${e}"]`)?.focus();return}if(this.editing){this.editing=!1,this.renderCard(this.currentComment),this.attachListeners();return}t.preventDefault(),this.hide()}}positionNear(t){let e=parseFloat(t.style.left)||0,i=parseFloat(t.style.top)||0,n=44,a=44,r=e-window.scrollX,s=i-window.scrollY,o=320,c=8,d=r+n+c;d+o>window.innerWidth-16&&(d=r-o-c),d=Math.max(16,d);let p=s,h=300;p+h>window.innerHeight-16&&(p=window.innerHeight-16-h),p=Math.max(16,p),this.card.style.left=`${d}px`,this.card.style.top=`${p}px`}isOwnComment(t){return this.currentUser?.id&&t.user_id?this.currentUser.id===t.user_id:(localStorage.getItem("tack_author_name")||"")===t.author_name}renderCard(t){let e=t.replies||[],i=localStorage.getItem("tack_author_name")||"Anonymous",n=`
|
|
2518
2576
|
<div class="tack-card-title-bar">
|
|
2519
2577
|
<span class="tack-card-title">Comment</span>
|
|
2520
2578
|
<div class="tack-card-title-actions">
|
|
2521
|
-
<button class="tack-card-resolve-icon ${
|
|
2579
|
+
<button class="tack-card-resolve-icon ${t.resolved?"resolved":""}" data-id="${t.id}" title="${t.resolved?"Unresolve":"Resolve"}" aria-label="${t.resolved?"Unresolve comment":"Resolve comment"}">
|
|
2522
2580
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2523
2581
|
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
|
|
2524
2582
|
<polyline points="22 4 12 14.01 9 11.01"/>
|
|
@@ -2531,49 +2589,49 @@
|
|
|
2531
2589
|
</svg>
|
|
2532
2590
|
</button>
|
|
2533
2591
|
</div>
|
|
2534
|
-
</div>`;
|
|
2592
|
+
</div>`;t.resolved&&(n+=`
|
|
2535
2593
|
<div class="tack-card-resolved-banner">
|
|
2536
2594
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
2537
2595
|
<polyline points="20 6 9 17 4 12"/>
|
|
2538
2596
|
</svg>
|
|
2539
|
-
Resolved by ${this.escapeHtml(
|
|
2540
|
-
</div>`),n+=this.renderCommentRow(
|
|
2597
|
+
Resolved by ${this.escapeHtml(t.author_name)}
|
|
2598
|
+
</div>`),n+=this.renderCommentRow(t,!0),n+='<div class="tack-card-divider"></div>',e.length>0&&(e.forEach((a,r)=>{n+=this.renderCommentRow(a,!1),r<e.length-1&&(n+='<div class="tack-card-divider"></div>')}),n+='<div class="tack-card-divider"></div>'),n+=`
|
|
2541
2599
|
<div class="tack-card-reply-bar">
|
|
2542
|
-
<div class="tack-card-reply-bar-avatar-wrap">${
|
|
2600
|
+
<div class="tack-card-reply-bar-avatar-wrap">${v(i,this.currentUser?.avatar_url||null,24)}</div>
|
|
2543
2601
|
<div class="tack-card-reply-bar-input-wrap">
|
|
2544
|
-
<input type="text" class="tack-card-reply-bar-input" placeholder="Reply\u2026" data-parent-id="${
|
|
2545
|
-
<button class="tack-card-reply-bar-send" data-parent-id="${
|
|
2602
|
+
<input type="text" class="tack-card-reply-bar-input" placeholder="Reply\u2026" data-parent-id="${t.id}" />
|
|
2603
|
+
<button class="tack-card-reply-bar-send" data-parent-id="${t.id}">
|
|
2546
2604
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
|
2547
2605
|
<line x1="12" y1="19" x2="12" y2="5"/>
|
|
2548
2606
|
<polyline points="5 12 12 5 19 12"/>
|
|
2549
2607
|
</svg>
|
|
2550
2608
|
</button>
|
|
2551
2609
|
</div>
|
|
2552
|
-
</div>`,this.card.innerHTML=n}renderCommentRow(e
|
|
2610
|
+
</div>`,this.card.innerHTML=n}renderCommentRow(t,e){let i=this.formatTimeAgo(new Date(t.created_at)),n=this.isOwnComment(t),a=this.activePickerId===t.id||this.activeDropdownId===t.id?" active":"",r=`<div class="tack-card-row${e?" main":""}" data-comment-id="${t.id}">`;if(r+=`
|
|
2553
2611
|
<div class="tack-card-row-header">
|
|
2554
|
-
<div class="tack-card-row-avatar-wrap">${
|
|
2612
|
+
<div class="tack-card-row-avatar-wrap">${v(t.author_name,t.author_avatar_url,28)}</div>
|
|
2555
2613
|
<div class="tack-card-row-meta">
|
|
2556
|
-
<span class="tack-card-row-author">${this.escapeHtml(
|
|
2557
|
-
${this.editing&&
|
|
2614
|
+
<span class="tack-card-row-author">${this.escapeHtml(t.author_name)}</span>
|
|
2615
|
+
${this.editing&&e?'<span class="tack-card-editing-badge">Editing</span>':""}
|
|
2558
2616
|
<span class="tack-card-row-time">\xB7 ${i}</span>
|
|
2559
2617
|
</div>
|
|
2560
|
-
</div>`,r+=`<div class="tack-card-action-pill${a}">`,r+=`<button class="tack-card-action-pill-btn tack-action-emoji" data-pill-comment-id="${
|
|
2618
|
+
</div>`,r+=`<div class="tack-card-action-pill${a}">`,r+=`<button class="tack-card-action-pill-btn tack-action-emoji" data-pill-comment-id="${t.id}" aria-label="Add reaction" aria-haspopup="true" aria-expanded="${this.activePickerId===t.id}">
|
|
2561
2619
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2562
2620
|
<circle cx="12" cy="12" r="10"/>
|
|
2563
2621
|
<path d="M8 14s1.5 2 4 2 4-2 4-2"/>
|
|
2564
2622
|
<line x1="9" y1="9" x2="9.01" y2="9"/>
|
|
2565
2623
|
<line x1="15" y1="9" x2="15.01" y2="9"/>
|
|
2566
2624
|
</svg>
|
|
2567
|
-
</button>`,r+='<div class="tack-card-action-pill-divider"></div>',r+=`<button class="tack-card-action-pill-btn tack-action-more" data-pill-comment-id="${
|
|
2625
|
+
</button>`,r+='<div class="tack-card-action-pill-divider"></div>',r+=`<button class="tack-card-action-pill-btn tack-action-more" data-pill-comment-id="${t.id}" data-is-main="${e}" data-is-own="${n}" title="More actions">
|
|
2568
2626
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="3" cy="8" r="1.25" fill="currentColor"/><circle cx="8" cy="8" r="1.25" fill="currentColor"/><circle cx="13" cy="8" r="1.25" fill="currentColor"/></svg>
|
|
2569
|
-
</button>`,r+="</div>",this.activeDropdownId===
|
|
2627
|
+
</button>`,r+="</div>",this.activeDropdownId===t.id&&(r+='<div class="tack-card-dropdown">',r+=`<button class="tack-card-dropdown-item" data-action="copy-link" data-comment-id="${t.id}" aria-label="Copy link">Copy link</button>`,e&&(r+=`<button class="tack-card-dropdown-item" data-action="mark-unread" data-comment-id="${t.id}" aria-label="Mark as unread">Mark as unread</button>`),n&&(r+='<div class="tack-card-dropdown-sep"></div>',e&&(r+=`<button class="tack-card-dropdown-item" data-action="edit" data-comment-id="${t.id}" aria-label="Edit comment">Edit</button>`),r+=`<button class="tack-card-dropdown-item delete" data-action="delete" data-comment-id="${t.id}" aria-label="Delete comment">Delete</button>`),r+="</div>"),this.activePickerId===t.id){let s=["\u{1F44D}","\u{1F44E}","\u2764\uFE0F","\u{1F389}","\u{1F440}","\u{1F680}"],o=t.reactions||[],c=this.currentUser?.id,d=new Set;for(let p of o)p.user_id===c&&d.add(p.emoji);r+='<div class="tack-reaction-picker" role="toolbar" aria-label="React with emoji">';for(let p=0;p<s.length;p++){let h=s[p],m=d.has(h),u=m?" mine":"",g=ot[h]||h;r+=`<button class="tack-reaction-picker-item${u}" data-picker-emoji="${h}" data-picker-for="${t.id}" aria-label="${g}" aria-pressed="${m}" tabindex="${p===0?"0":"-1"}">${h}</button>`}r+="</div>"}return this.editing&&e?r+=`
|
|
2570
2628
|
<div class="tack-card-edit-wrap">
|
|
2571
|
-
<textarea class="tack-card-edit-textarea">${this.escapeHtml(
|
|
2629
|
+
<textarea class="tack-card-edit-textarea">${this.escapeHtml(t.content)}</textarea>
|
|
2572
2630
|
<div class="tack-card-edit-actions">
|
|
2573
2631
|
<button class="tack-card-edit-cancel">Cancel</button>
|
|
2574
2632
|
<button class="tack-card-edit-save">Save</button>
|
|
2575
2633
|
</div>
|
|
2576
|
-
</div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,r+=this.renderReactions(e),r+="</div>",r}renderReactions(e){let t=e.reactions||[],i=this.currentUser?.id,n=new Map;for(let s of t){let l=n.get(s.emoji)||{count:0,userReacted:!1,users:[]};l.count++,l.users.push(s.user_name),s.user_id===i&&(l.userReacted=!0),n.set(s.emoji,l)}if(n.size===0)return"";let a=[...n.entries()].sort((s,l)=>l[1].count-s[1].count),r='<div class="tack-reaction-bar">';for(let[s,l]of a){let c=l.userReacted?" mine":"",d=this.lastAddedReaction?.commentId===e.id&&this.lastAddedReaction?.emoji===s?" just-added":"",h=oe[s]||s,p=[...l.users];if(l.userReacted&&i){let m=p.findIndex((v,b)=>t.find(E=>E.emoji===s&&E.user_id===i&&E.user_name===p[b]));m!==-1&&(p.splice(m,1),p.unshift("You"))}let u;p.length<=3?u=p.join(", "):u=`${p.slice(0,2).join(", ")}, and ${p.length-2} other${p.length-2>1?"s":""}`;let f=`${h}, ${l.count} reaction${l.count>1?"s":""}${l.userReacted?", you reacted":""}`;r+=`<button class="tack-reaction-pill${c}${d}" data-emoji="${s}" data-reaction-comment-id="${e.id}" aria-label="${this.escapeHtml(f)}" aria-pressed="${l.userReacted}"><span class="tack-reaction-tooltip">${this.escapeHtml(u)}</span>${s} ${l.count}</button>`}return r+="</div>",this.lastAddedReaction?.commentId===e.id&&setTimeout(()=>{this.lastAddedReaction=null},300),r}closePopovers(){(this.activePickerId||this.activeDropdownId)&&(this.activePickerId=null,this.activeDropdownId=null,this.renderCard(this.currentComment),this.attachListeners())}attachListeners(){this.card.addEventListener("click",i=>{let n=i.target;!n.closest(".tack-reaction-picker")&&!n.closest(".tack-card-dropdown")&&!n.closest(".tack-card-action-pill")&&this.closePopovers()}),this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",i=>{i.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelectorAll(".tack-action-emoji").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.pillCommentId;this.activeDropdownId=null;let r=this.activePickerId===a;this.activePickerId=r?null:a,this.renderCard(this.currentComment),this.attachListeners(),r||this.card.querySelector(".tack-reaction-picker")?.querySelector('[tabindex="0"]')?.focus()})}),this.card.querySelectorAll(".tack-action-more").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.pillCommentId;this.activePickerId=null,this.activeDropdownId=this.activeDropdownId===a?null:a,this.renderCard(this.currentComment),this.attachListeners()})});let e=this.card.querySelector(".tack-reaction-picker");if(e){let i=Array.from(e.querySelectorAll(".tack-reaction-picker-item"));i.forEach((n,a)=>{n.addEventListener("keydown",r=>{let s=-1;r.key==="ArrowRight"||r.key==="ArrowDown"?(r.preventDefault(),s=(a+1)%i.length):r.key==="ArrowLeft"||r.key==="ArrowUp"?(r.preventDefault(),s=(a-1+i.length)%i.length):r.key==="Home"?(r.preventDefault(),s=0):r.key==="End"&&(r.preventDefault(),s=i.length-1),s>=0&&(i[a].setAttribute("tabindex","-1"),i[s].setAttribute("tabindex","0"),i[s].focus())})})}this.card.querySelectorAll(".tack-card-dropdown-item").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.action,r=i.dataset.commentId;if(a==="copy-link"&&r)this.activeDropdownId=null,this.callbacks.onCopyLink(r),this.renderCard(this.currentComment),this.attachListeners();else if(a==="mark-unread"&&r)this.activeDropdownId=null,this.callbacks.onMarkAsUnread(r),this.renderCard(this.currentComment),this.attachListeners();else if(a==="edit"){this.activeDropdownId=null,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let s=this.card.querySelector(".tack-card-edit-textarea");s?.focus(),s?.setSelectionRange(s.value.length,s.value.length)}else a==="delete"&&r&&(this.activeDropdownId=null,r===this.currentComment?.id?(this.callbacks.onDelete(r),this.hide()):this.callbacks.onDelete(r))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",i=>{i.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",i=>{i.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),this.saveEdit())}),this.card.querySelectorAll(".tack-reaction-pill").forEach(i=>{i.addEventListener("click",n=>{if(n.stopPropagation(),!this.currentUser)return;let a=i.dataset.emoji,r=i.dataset.reactionCommentId,s=i.classList.contains("mine");this.callbacks.onReaction(r,a,!s)})}),this.card.querySelectorAll(".tack-reaction-picker-item").forEach(i=>{i.addEventListener("click",n=>{if(n.stopPropagation(),!this.currentUser)return;let a=i.dataset.pickerEmoji,r=i.dataset.pickerFor,s=i.classList.contains("mine");this.activePickerId=null,this.callbacks.onReaction(r,a,!s)})}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",i=>{i.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 U=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 j=44,W=20,B=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=te();this.position=i||{edge:"right",y:window.innerHeight-j-W},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=F(this.position.y,j);this.position.y=e,this.el.style.left="",this.el.style.right="",this.el.style.bottom="",this.position.edge==="left"?this.el.style.left=`${W}px`:this.el.style.right=`${W}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=F(this.position.y,j),this.applyPosition(),Y(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(!M(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=$({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",w(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=F(t.top,j);this.position={edge:n,y:a},Y(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=`
|
|
2634
|
+
</div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(t.content)}</div>`,r+=this.renderReactions(t),r+="</div>",r}renderReactions(t){let e=t.reactions||[],i=this.currentUser?.id,n=new Map;for(let s of e){let o=n.get(s.emoji)||{count:0,userReacted:!1,users:[]};o.count++,o.users.push(s.user_name),s.user_id===i&&(o.userReacted=!0),n.set(s.emoji,o)}if(n.size===0)return"";let a=[...n.entries()].sort((s,o)=>o[1].count-s[1].count),r='<div class="tack-reaction-bar">';for(let[s,o]of a){let c=o.userReacted?" mine":"",d=this.lastAddedReaction?.commentId===t.id&&this.lastAddedReaction?.emoji===s?" just-added":"",p=ot[s]||s,h=[...o.users];if(o.userReacted&&i){let g=h.findIndex((b,k)=>e.find(E=>E.emoji===s&&E.user_id===i&&E.user_name===h[k]));g!==-1&&(h.splice(g,1),h.unshift("You"))}let m;h.length<=3?m=h.join(", "):m=`${h.slice(0,2).join(", ")}, and ${h.length-2} other${h.length-2>1?"s":""}`;let u=`${p}, ${o.count} reaction${o.count>1?"s":""}${o.userReacted?", you reacted":""}`;r+=`<button class="tack-reaction-pill${c}${d}" data-emoji="${s}" data-reaction-comment-id="${t.id}" aria-label="${this.escapeHtml(u)}" aria-pressed="${o.userReacted}"><span class="tack-reaction-tooltip">${this.escapeHtml(m)}</span>${s} ${o.count}</button>`}return r+="</div>",this.lastAddedReaction?.commentId===t.id&&setTimeout(()=>{this.lastAddedReaction=null},300),r}closePopovers(){(this.activePickerId||this.activeDropdownId)&&(this.activePickerId=null,this.activeDropdownId=null,this.renderCard(this.currentComment),this.attachListeners())}attachListeners(){this.card.addEventListener("click",i=>{let n=i.target;!n.closest(".tack-reaction-picker")&&!n.closest(".tack-card-dropdown")&&!n.closest(".tack-card-action-pill")&&this.closePopovers()}),this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",i=>{i.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelectorAll(".tack-action-emoji").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.pillCommentId;this.activeDropdownId=null;let r=this.activePickerId===a;this.activePickerId=r?null:a,this.renderCard(this.currentComment),this.attachListeners(),r||this.card.querySelector(".tack-reaction-picker")?.querySelector('[tabindex="0"]')?.focus()})}),this.card.querySelectorAll(".tack-action-more").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.pillCommentId;this.activePickerId=null,this.activeDropdownId=this.activeDropdownId===a?null:a,this.renderCard(this.currentComment),this.attachListeners()})});let t=this.card.querySelector(".tack-reaction-picker");if(t){let i=Array.from(t.querySelectorAll(".tack-reaction-picker-item"));i.forEach((n,a)=>{n.addEventListener("keydown",r=>{let s=-1;r.key==="ArrowRight"||r.key==="ArrowDown"?(r.preventDefault(),s=(a+1)%i.length):r.key==="ArrowLeft"||r.key==="ArrowUp"?(r.preventDefault(),s=(a-1+i.length)%i.length):r.key==="Home"?(r.preventDefault(),s=0):r.key==="End"&&(r.preventDefault(),s=i.length-1),s>=0&&(i[a].setAttribute("tabindex","-1"),i[s].setAttribute("tabindex","0"),i[s].focus())})})}this.card.querySelectorAll(".tack-card-dropdown-item").forEach(i=>{i.addEventListener("click",n=>{n.stopPropagation();let a=i.dataset.action,r=i.dataset.commentId;if(a==="copy-link"&&r)this.activeDropdownId=null,this.callbacks.onCopyLink(r),this.renderCard(this.currentComment),this.attachListeners();else if(a==="mark-unread"&&r)this.activeDropdownId=null,this.callbacks.onMarkAsUnread(r),this.renderCard(this.currentComment),this.attachListeners();else if(a==="edit"){this.activeDropdownId=null,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let s=this.card.querySelector(".tack-card-edit-textarea");s?.focus(),s?.setSelectionRange(s.value.length,s.value.length)}else a==="delete"&&r&&(this.activeDropdownId=null,r===this.currentComment?.id?(this.callbacks.onDelete(r),this.hide()):this.callbacks.onDelete(r))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",i=>{i.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",i=>{i.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),this.saveEdit())}),this.card.querySelectorAll(".tack-reaction-pill").forEach(i=>{i.addEventListener("click",n=>{if(n.stopPropagation(),!this.currentUser)return;let a=i.dataset.emoji,r=i.dataset.reactionCommentId,s=i.classList.contains("mine");this.callbacks.onReaction(r,a,!s)})}),this.card.querySelectorAll(".tack-reaction-picker-item").forEach(i=>{i.addEventListener("click",n=>{if(n.stopPropagation(),!this.currentUser)return;let a=i.dataset.pickerEmoji,r=i.dataset.pickerFor,s=i.classList.contains("mine");this.activePickerId=null,this.callbacks.onReaction(r,a,!s)})}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",i=>{i.stopPropagation(),this.submitReply()})}saveEdit(){if(!this.currentComment)return;let e=this.card.querySelector(".tack-card-edit-textarea")?.value.trim();e&&(this.editing=!1,this.callbacks.onEdit(this.currentComment.id,e))}submitReply(){if(!this.currentComment)return;let t=this.card.querySelector(".tack-card-reply-bar-input"),e=t?.value.trim();e&&(this.callbacks.onReply(this.currentComment.id,e),t.value="")}formatTimeAgo(t){let e=Math.floor((Date.now()-t.getTime())/1e3);return e<60?"just now":e<3600?`${Math.floor(e/60)}m ago`:e<86400?`${Math.floor(e/3600)}h ago`:e<604800?`${Math.floor(e/86400)}d ago`:t.toLocaleDateString()}escapeHtml(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}};var O=class{constructor(t,e,i,n){this.ws=null;this.reconnectAttempts=0;this.maxReconnectAttempts=5;this.heartbeatInterval=null;this.supabaseUrl=t,this.supabaseKey=e,this.versionId=i,this.callback=n}connect(){let t=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",e=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${t}?${e}`),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 t={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(t)),this.startHeartbeat()}handleMessage(t){if(t.event==="postgres_changes"&&t.payload?.data){let{type:e,record:i}=t.payload.data,n=e.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 t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{console.log(`[Tack] Reconnecting... (attempt ${this.reconnectAttempts})`),this.connect()},t)}disconnect(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.ws&&(this.ws.close(),this.ws=null)}};var U=class{constructor(t,e,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=t,this.supabaseKey=e,this.projectId=i}join(t){this.currentUser=t,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(t){this.pagePath=t,this.joined&&this.ws?.readyState===WebSocket.OPEN&&this.trackPresence()}setOnPresenceChange(t){this.onPresenceChange=t}connect(){let t=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",e=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${t}?${e}`),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 t=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:t,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 t=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:t,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(t){if(t.event==="presence_state"){this.users.clear();let e=t.payload||{};for(let i of Object.keys(e)){let n=e[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(t.event==="presence_diff"){let{joins:e,leaves:i}=t.payload||{};if(e)for(let n of Object.keys(e)){let a=e[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 t=Array.from(this.users.values());this.onPresenceChange?.(t)}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 t=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{this.currentUser&&this.connect()},t)}};var j=44,W=20,B=class{constructor(t,e){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=e;let i=et();this.position=i||{edge:"right",y:window.innerHeight-j-W},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),t.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 t=F(this.position.y,j);this.position.y=t,this.el.style.left="",this.el.style.right="",this.el.style.bottom="",this.position.edge==="left"?this.el.style.left=`${W}px`:this.el.style.right=`${W}px`,this.el.style.top=`${t}px`,this.el.classList.toggle("tack-fab--left",this.position.edge==="left")}onResize(){this.dragState==="idle"&&(this.position.y=F(this.position.y,j),this.applyPosition(),Y(this.position))}onPointerDown(t){if(t.button!==0)return;this.dragState="pending",this.startPointerX=t.clientX,this.startPointerY=t.clientY;let e=this.el.getBoundingClientRect();this.startFabX=e.left,this.startFabY=e.top,this.boundOnPointerMove=this.onPointerMove.bind(this),this.boundOnPointerUp=this.onPointerUp.bind(this),window.addEventListener("pointermove",this.boundOnPointerMove),window.addEventListener("pointerup",this.boundOnPointerUp)}onPointerMove(t){if(this.dragState==="pending"){if(!M(this.startPointerX,this.startPointerY,t.clientX,t.clientY))return;this.enterDragState()}if(this.dragState!=="dragging")return;let e=t.clientX-this.startPointerX,i=t.clientY-this.startPointerY,n=this.startFabX+e,a=this.startFabY+i;this.el.style.left=`${n}px`,this.el.style.right="auto",this.el.style.top=`${a}px`,this.updateSnapHint(t.clientX)}onPointerUp(t){let e=this.dragState==="dragging";if(this.dragState==="pending"){this.cleanupDragListeners(),this.dragState="idle",this.handleFabClick(t);return}e&&this.exitDragState(t),this.cleanupDragListeners()}enterDragState(){this.dragState="dragging",this.expanded&&this.collapse(),this.dragOverlay=H({zIndex:10004,cursor:"grabbing"}),this.el.classList.add("tack-fab-dragging");let t=this.el.getBoundingClientRect();this.el.style.left=`${t.left}px`,this.el.style.right="auto",this.el.style.top=`${t.top}px`,document.body.style.userSelect="none"}exitDragState(t){this.dragState="idle",w(this.dragOverlay),this.dragOverlay=null,this.removeSnapHint(),this.el.classList.remove("tack-fab-dragging");let e=this.el.getBoundingClientRect(),n=e.left+e.width/2<window.innerWidth/2?"left":"right",a=F(e.top,j);this.position={edge:n,y:a},Y(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(t){let i=t.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(t){let e=t<window.innerWidth/2?"left":"right";this.snapHint||(this.snapHint=document.createElement("div"),this.snapHint.style.cssText=`
|
|
2577
2635
|
position: fixed;
|
|
2578
2636
|
top: 0;
|
|
2579
2637
|
width: 3px;
|
|
@@ -2582,7 +2640,7 @@
|
|
|
2582
2640
|
z-index: 10003;
|
|
2583
2641
|
pointer-events: none;
|
|
2584
2642
|
transition: left 150ms ease, right 150ms ease, opacity 150ms ease;
|
|
2585
|
-
`,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(),w(this.dragOverlay),this.removeSnapHint(),document.body.style.userSelect="",this.boundOnResize&&(window.removeEventListener("resize",this.boundOnResize),this.boundOnResize=null),this.el.remove()}};var C=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 L(this.config.apiUrl,this.config.projectId),this.auth=new P(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=V(),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 R(this.onElementSelected.bind(this),()=>this.transitionTo("idle")),this.form=new A(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 I(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))},onBatchRead:i=>{this.auth.isAuthenticated()&&this.api.batchMarkAsRead(i).catch(()=>{})}}),this.card=new z(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),onCopyLink:this.onCopyLink.bind(this),onMarkAsUnread:this.onMarkAsUnread.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new _(t,this.onPinClick.bind(this)),this.pins.setHoverCallbacks(i=>{this.panel?.highlightRow(i)},i=>{this.panel?.clearRowHighlight(i)}),this.fab=new B(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 U(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,e.read_comment_ids?.length>0&&this.panel?.syncReadIds(e.read_comment_ids),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)}markCommentAsRead(e){let t=this.comments.find(i=>i.id===e);!t||t.parent_id||(this.panel?.markAsRead(e),this.panel?.render(this.comments),this.auth.isAuthenticated()&&this.api.markAsRead(e).catch(()=>{}))}onCommentClick(e){this.markCommentAsRead(e.id),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.markCommentAsRead(e),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)}onCopyLink(e){let t=new URL(window.location.href);t.searchParams.delete("tack_open"),t.searchParams.delete("tack_comment"),t.searchParams.set("tack_comment",e),navigator.clipboard.writeText(t.toString()).then(()=>{this.showToast("Link copied to clipboard")}).catch(()=>{this.showToast("Failed to copy link")})}async onMarkAsUnread(e){if(this.panel?.markAsUnread(e),this.panel?.render(this.comments),this.showToast("Marked as unread"),this.auth.isAuthenticated())try{await this.api.markAsUnread(e)}catch{this.panel?.markAsRead(e),this.panel?.render(this.comments),this.showToast("Failed to mark as unread")}}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);let t=this.findCommentById(e);t&&t.comment!==t.parent?(t.parent.replies=t.parent.replies?.filter(i=>i.id!==e)||[],this.card?.updateComment(t.parent)):this.comments=this.comments.filter(i=>i.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")}}findCommentById(e){let t=this.comments.find(i=>i.id===e);if(t)return{comment:t,parent:t};for(let i of this.comments){let n=i.replies?.find(a=>a.id===e);if(n)return{comment:n,parent:i}}return null}async onReaction(e,t,i){if(!this.auth.isAuthenticated())return;let n=this.findCommentById(e);if(!n)return;let{comment:a,parent:r}=n,s=this.auth.getUser();a.reactions=a.reactions||[];let l=[...a.reactions];i?(a.reactions.push({emoji:t,user_id:s.id,user_name:s.name}),this.card?.markReactionAdded(e,t)):a.reactions=a.reactions.filter(c=>!(c.emoji===t&&c.user_id===s.id)),this.card?.updateComment(r);try{i?await this.api.addReaction(e,t):await this.api.removeReaction(e,t)}catch(c){console.error("[Tack] Failed to update reaction:",c),a.reactions=l,this.card?.updateComment(r),this.showToast("Couldn\u2019t save reaction")}}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"),this.scrollToComment(n),setTimeout(()=>{let a=this.pins?.getPinElement(i);a&&(this.card?.show(n,a),this.pins?.setActive(i),this.pins?.beacon(i))},400),this.markCommentAsRead(i))}}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(n=>n.id===t.id)||this.comments.some(n=>n.replies?.some(a=>a.id===t.id)))return;if(t.parent_id){let n=this.comments.find(a=>a.id===t.parent_id);n&&(n.replies=n.replies||[],n.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":this.loadComments();return;case"DELETE":this.comments=this.comments.filter(n=>n.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=`
|
|
2643
|
+
`,document.body.appendChild(this.snapHint)),e==="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 t=this.snapHint;this.snapHint=null,setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},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(t){this.panelToggleBtn.classList.toggle("tack-fab-btn--active",t)}setBadgeCount(t){this.badge.textContent=t>99?"99+":String(t),!this.expanded&&t>0?this.badge.classList.add("visible"):this.badge.classList.remove("visible")}destroy(){this.cleanupDragListeners(),w(this.dragOverlay),this.removeSnapHint(),document.body.style.userSelect="",this.boundOnResize&&(window.removeEventListener("resize",this.boundOnResize),this.boundOnResize=null),this.el.remove()}};var C=class{constructor(t){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",...t},this.api=new L(this.config.apiUrl,this.config.projectId),this.auth=new P(this.config.apiUrl)}async mount(){this.container=document.createElement("div"),this.container.id="tack-widget",this.shadowRoot=this.container.attachShadow({mode:"open"});let t=document.createElement("style");t.textContent=V(),this.shadowRoot.appendChild(t),this.injectPageStyles();let e=document.createElement("div");if(e.className="tack-wrapper",this.shadowRoot.appendChild(e),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 R(this.onElementSelected.bind(this),()=>this.transitionTo("idle")),this.form=new A(e,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 I(e,{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))},onBatchRead:i=>{this.auth.isAuthenticated()&&this.api.batchMarkAsRead(i).catch(()=>{})}}),this.card=new z(e,{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),onCopyLink:this.onCopyLink.bind(this),onMarkAsUnread:this.onMarkAsUnread.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new _(e,this.onPinClick.bind(this)),this.pins.setHoverCallbacks(i=>{this.panel?.highlightRow(i)},i=>{this.panel?.clearRowHighlight(i)}),this.fab=new B(e,{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(t){!this.config.supabaseUrl||!this.config.supabaseKey||(this.presence?.leave(),this.presence=new U(this.config.supabaseUrl,this.config.supabaseKey,this.config.projectId),this.presence.setOnPresenceChange(e=>{this.panel?.renderPresence(e)}),this.presence.join(t),this.presence.updatePagePath(this.getPagePath()))}async signIn(){try{await this.auth.signIn()}catch(t){console.error("[Tack] Sign in failed:",t)}}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=(...t)=>{this.originalPushState(...t),this.onUrlChange()},history.replaceState=(...t)=>{this.originalReplaceState(...t),this.onUrlChange()}}onUrlChange(){let t=this.getPagePath();t!==this.currentPagePath&&(this.currentPagePath=t,this.presence?.updatePagePath(t),setTimeout(()=>{this.loadComments()},100))}transitionTo(t){let e=this.state;if(t==="idle"){if(this.form?.isFormVisible()&&this.form.hasContent()){this.form.jitter();return}this.selector?.disable(),this.form?.hide(),this.pins?.hide(),e==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),this.fab?.collapse(),this.container?.classList.remove("tack-active"),this.fab?.setPanelToggleActive(!1),this.updateFabBadge()}else t==="active"?(this.selector?.enable(),this.pins?.show(),e==="active-panel"&&(this.panel?.hide(),this.setPanelOpen(!1)),e==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!1)):t==="active-panel"&&(this.selector?.disable(),this.pins?.show(),this.fab&&this.panel?.setFabOffset(this.fab.getEdge()),this.panel?.show(),this.setPanelOpen(!0),e==="idle"&&this.fab?.expand(),this.container?.classList.add("tack-active"),this.fab?.setPanelToggleActive(!0));this.state=t}updateFabBadge(){let t=this.comments.filter(e=>!e.resolved&&!e.parent_id).length;this.fab?.setBadgeCount(t)}onShare(){let t=new URL(window.location.href);t.searchParams.set("tack_open","true"),navigator.clipboard.writeText(t.toString()).then(()=>{this.showToast("Link copied to clipboard")}).catch(()=>{this.showToast("Failed to copy link")})}injectPageStyles(){}setPanelOpen(t){}setupKeyboardShortcuts(){this.boundOnKeyDown=this.handleKeyDown.bind(this),document.addEventListener("keydown",this.boundOnKeyDown)}handleKeyDown(t){if(t.metaKey||t.ctrlKey||t.altKey)return;let e=t.key.toLowerCase();if(e!=="c"&&e!=="n"&&e!=="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(e==="c"){t.preventDefault(),this.state==="idle"?this.transitionTo("active"):this.state==="active-panel"?this.transitionTo("active"):this.transitionTo("idle");return}this.state==="active-panel"&&(e==="n"?(t.preventDefault(),this.navigateComments("next")):e==="p"&&(t.preventDefault(),this.navigateComments("prev")))}}navigateComments(t){let e=this.panel?.getFilteredCommentIds()||[];if(e.length===0)return;t==="next"?this.navigationIndex=this.navigationIndex<e.length-1?this.navigationIndex+1:0:this.navigationIndex=this.navigationIndex>0?this.navigationIndex-1:e.length-1;let i=e[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 t=await this.api.getComments();this.comments=t.comments,this.currentVersion=t.version,this.navigationIndex=-1,t.read_comment_ids?.length>0&&this.panel?.syncReadIds(t.read_comment_ids),this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}catch(t){console.error("[Tack] Failed to load comments:",t)}}onElementSelected(t){this.form?.isFormVisible()||(this.selector?.disable(),this.form?.show(t))}async onCommentSubmit(t){let e=!1,i=window.setTimeout(()=>{let n=this.auth.getUser();this.pins?.showLoadingPin(t.anchor,{name:n?.name||t.authorName,avatar_url:n?.avatar_url||null}),e=!0},150);try{let n={content:t.content,element_selector:t.anchor.cssSelector,x_percent:t.anchor.relativeX*100,y_percent:t.anchor.relativeY*100,anchor:t.anchor,page_path:this.getPagePath(),screenshot_data:t.screenshot};this.auth.isAuthenticated()||(n.author_name=t.authorName,n.author_email=t.authorEmail);let a=await this.api.createComment(n);clearTimeout(i),e&&this.pins?.resolveLoadingPin();let r={...a,screenshot_url:a.screenshot_url||t.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),e?(this.pendingRetryData=t,this.pins?.failLoadingPin(()=>this.retryFailedComment())):this.showToast("Failed to add comment")}}retryFailedComment(){if(!this.pendingRetryData)return;let t=this.pendingRetryData;this.pendingRetryData=null,this.onCommentSubmit(t)}markCommentAsRead(t){let e=this.comments.find(i=>i.id===t);!e||e.parent_id||(this.panel?.markAsRead(t),this.panel?.render(this.comments),this.auth.isAuthenticated()&&this.api.markAsRead(t).catch(()=>{}))}onCommentClick(t){this.markCommentAsRead(t.id),this.scrollToComment(t),setTimeout(()=>{let e=this.pins?.getPinElement(t.id);e&&(this.card?.show(t,e),this.pins?.setActive(t.id),this.pins?.beacon(t.id))},300)}onPinClick(t,e){let i=this.comments.find(n=>n.id===t);i&&(this.markCommentAsRead(t),this.card?.show(i,e),this.pins?.setActive(t),this.pins?.highlight(t),this.panel?.isOpen()&&this.panel.scrollToComment(t))}onCardClose(){this.pins?.setActive(null)}onCopyLink(t){let e=new URL(window.location.href);e.searchParams.delete("tack_open"),e.searchParams.delete("tack_comment"),e.searchParams.set("tack_comment",t),navigator.clipboard.writeText(e.toString()).then(()=>{this.showToast("Link copied to clipboard")}).catch(()=>{this.showToast("Failed to copy link")})}async onMarkAsUnread(t){if(this.panel?.markAsUnread(t),this.panel?.render(this.comments),this.showToast("Marked as unread"),this.auth.isAuthenticated())try{await this.api.markAsUnread(t)}catch{this.panel?.markAsRead(t),this.panel?.render(this.comments),this.showToast("Failed to mark as unread")}}async onResolve(t,e){try{await this.api.updateComment(t,{resolved:e});let i=this.comments.find(n=>n.id===t);i&&(i.resolved=e,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(t,e){try{let i={content:e,parent_id:t,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===t);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(t,e){try{await this.api.updateComment(t,{content:e});let i=this.comments.find(n=>n.id===t);i&&(i.content=e,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(t){try{await this.api.deleteComment(t);let e=this.findCommentById(t);e&&e.comment!==e.parent?(e.parent.replies=e.parent.replies?.filter(i=>i.id!==t)||[],this.card?.updateComment(e.parent)):this.comments=this.comments.filter(i=>i.id!==t),this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge(),this.showToast("Comment deleted")}catch(e){console.error("[Tack] Failed to delete comment:",e),this.showToast("Failed to delete comment")}}findCommentById(t){let e=this.comments.find(i=>i.id===t);if(e)return{comment:e,parent:e};for(let i of this.comments){let n=i.replies?.find(a=>a.id===t);if(n)return{comment:n,parent:i}}return null}async onReaction(t,e,i){if(!this.auth.isAuthenticated())return;let n=this.findCommentById(t);if(!n)return;let{comment:a,parent:r}=n,s=this.auth.getUser();a.reactions=a.reactions||[];let o=[...a.reactions];i?(a.reactions.push({emoji:e,user_id:s.id,user_name:s.name}),this.card?.markReactionAdded(t,e)):a.reactions=a.reactions.filter(c=>!(c.emoji===e&&c.user_id===s.id)),this.card?.updateComment(r);try{i?await this.api.addReaction(t,e):await this.api.removeReaction(t,e)}catch(c){console.error("[Tack] Failed to update reaction:",c),a.reactions=o,this.card?.updateComment(r),this.showToast("Couldn\u2019t save reaction")}}scrollToComment(t){if(t.element_selector)document.querySelector(t.element_selector)?.scrollIntoView({behavior:"smooth",block:"center"});else if(t.x_percent!==null&&t.y_percent!==null){let e=t.x_percent/100*document.documentElement.scrollWidth,i=t.y_percent/100*document.documentElement.scrollHeight;window.scrollTo({left:e-window.innerWidth/2,top:i-window.innerHeight/2,behavior:"smooth"})}}handleDeepLink(){let t=new URLSearchParams(window.location.search);t.get("tack_open")==="true"&&this.transitionTo("active-panel");let i=t.get("tack_comment");if(i){let n=this.comments.find(a=>a.id===i);n&&(this.transitionTo("active"),this.scrollToComment(n),setTimeout(()=>{let a=this.pins?.getPinElement(i);a&&(this.card?.show(n,a),this.pins?.setActive(i),this.pins?.beacon(i))},400),this.markCommentAsRead(i))}}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,(t,e)=>{this.handleRealtimeEvent(t,e)}),this.realtime.connect()}handleRealtimeEvent(t,e){switch(t){case"INSERT":if(this.comments.some(n=>n.id===e.id)||this.comments.some(n=>n.replies?.some(a=>a.id===e.id)))return;if(e.parent_id){let n=this.comments.find(a=>a.id===e.parent_id);n&&(n.replies=n.replies||[],n.replies.push(e))}else this.comments.push(e);this.showToast(`New comment from ${e.author_name}`);break;case"UPDATE":this.loadComments();return;case"DELETE":this.comments=this.comments.filter(n=>n.id!==e.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments),this.updateFabBadge()}showToast(t){if(!this.shadowRoot)return;let e=document.createElement("div");e.className="tack-toast",e.textContent=t,e.style.cssText=`
|
|
2586
2644
|
position: fixed;
|
|
2587
2645
|
bottom: 80px;
|
|
2588
2646
|
right: 20px;
|
|
@@ -2593,5 +2651,5 @@
|
|
|
2593
2651
|
font-size: 14px;
|
|
2594
2652
|
z-index: 10002;
|
|
2595
2653
|
animation: tack-toast-in 0.3s ease;
|
|
2596
|
-
`,this.shadowRoot.appendChild(
|
|
2654
|
+
`,this.shadowRoot.appendChild(e),setTimeout(()=>{e.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 wt={init(l){let t=new C(l);return t.mount(),t}};0&&(module.exports={Tack,TackWidget});
|
|
2597
2655
|
//# sourceMappingURL=index.js.map
|