@tacktext/widget 0.1.3 → 0.1.5
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.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +97 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +98 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -26,6 +26,8 @@ declare class TackWidget {
|
|
|
26
26
|
private originalReplaceState;
|
|
27
27
|
private pollingInterval;
|
|
28
28
|
private boundOnUrlChange;
|
|
29
|
+
private boundOnKeyDown;
|
|
30
|
+
private navigationIndex;
|
|
29
31
|
constructor(config: TackConfig);
|
|
30
32
|
mount(): Promise<void>;
|
|
31
33
|
private joinPresence;
|
|
@@ -42,6 +44,9 @@ declare class TackWidget {
|
|
|
42
44
|
private injectPageStyles;
|
|
43
45
|
private setPanelOpen;
|
|
44
46
|
private updateToggleAria;
|
|
47
|
+
private setupKeyboardShortcuts;
|
|
48
|
+
private handleKeyDown;
|
|
49
|
+
private navigateComments;
|
|
45
50
|
private loadComments;
|
|
46
51
|
private onElementSelected;
|
|
47
52
|
private onCommentSubmit;
|
|
@@ -52,6 +57,7 @@ declare class TackWidget {
|
|
|
52
57
|
private onReply;
|
|
53
58
|
private onEdit;
|
|
54
59
|
private onDelete;
|
|
60
|
+
private onReaction;
|
|
55
61
|
private scrollToComment;
|
|
56
62
|
private handleDeepLink;
|
|
57
63
|
private subscribeToRealtime;
|
package/dist/index.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ declare class TackWidget {
|
|
|
26
26
|
private originalReplaceState;
|
|
27
27
|
private pollingInterval;
|
|
28
28
|
private boundOnUrlChange;
|
|
29
|
+
private boundOnKeyDown;
|
|
30
|
+
private navigationIndex;
|
|
29
31
|
constructor(config: TackConfig);
|
|
30
32
|
mount(): Promise<void>;
|
|
31
33
|
private joinPresence;
|
|
@@ -42,6 +44,9 @@ declare class TackWidget {
|
|
|
42
44
|
private injectPageStyles;
|
|
43
45
|
private setPanelOpen;
|
|
44
46
|
private updateToggleAria;
|
|
47
|
+
private setupKeyboardShortcuts;
|
|
48
|
+
private handleKeyDown;
|
|
49
|
+
private navigateComments;
|
|
45
50
|
private loadComments;
|
|
46
51
|
private onElementSelected;
|
|
47
52
|
private onCommentSubmit;
|
|
@@ -52,6 +57,7 @@ declare class TackWidget {
|
|
|
52
57
|
private onReply;
|
|
53
58
|
private onEdit;
|
|
54
59
|
private onDelete;
|
|
60
|
+
private onReaction;
|
|
55
61
|
private scrollToComment;
|
|
56
62
|
private handleDeepLink;
|
|
57
63
|
private subscribeToRealtime;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var V=Object.create;var x=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var Z=(o,e)=>{for(var t in e)x(o,t,{get:e[t],enumerable:!0})},U=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of J(e))!G.call(o,n)&&n!==t&&x(o,n,{get:()=>e[n],enumerable:!(i=X(e,n))||i.enumerable});return o};var ee=(o,e,t)=>(t=o!=null?V(Q(o)):{},U(e||!o||!o.__esModule?x(t,"default",{value:o,enumerable:!0}):t,o)),te=o=>U(x({},"__esModule",{value:!0}),o);var se={};Z(se,{Tack:()=>ae,TackWidget:()=>g});module.exports=te(se);var w=class{constructor(e,t){this.authToken=null;this.onUnauthorized=null;this.baseUrl=e,this.projectId=t}setAuthToken(e){this.authToken=e}setOnUnauthorized(e){this.onUnauthorized=e}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async handleResponse(e){return e.status===401&&this.onUnauthorized?.(),e}async getComments(){let e=await fetch(`${this.baseUrl}/projects/${this.projectId}/comments?path=${encodeURIComponent(window.location.pathname)}`,{headers:this.getHeaders()});if(await this.handleResponse(e),!e.ok)throw new Error("Failed to fetch comments");return e.json()}async createComment(e){let t=await fetch(`${this.baseUrl}/comments`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({project_id:this.projectId,...e})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to create comment");return t.json()}async updateComment(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(t)});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to update comment");return i.json()}async deleteComment(e){let t=await fetch(`${this.baseUrl}/comments/${e}`,{method:"DELETE",headers:this.getHeaders()});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to delete comment")}async addReaction(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}/reactions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({emoji:t})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to add reaction")}async removeReaction(e,t){let i=await fetch(`${this.baseUrl}/comments/${e}/reactions`,{method:"DELETE",headers:this.getHeaders(),body:JSON.stringify({emoji:t})});if(await this.handleResponse(i),!i.ok)throw new Error("Failed to remove reaction")}async uploadScreenshot(e){let t=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({image:e,project_id:this.projectId})});if(await this.handleResponse(t),!t.ok)throw new Error("Failed to upload screenshot");let{url:i}=await t.json();return i}};var y=class{constructor(e){this.sessionToken=null;this.user=null;this.onAuthChange=null;this.apiUrl=e}async init(){let e=localStorage.getItem("tack_session");if(e)try{let t=await fetch(`${this.apiUrl}/auth/widget-session`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok){localStorage.removeItem("tack_session");return}let{user:i}=await t.json();this.sessionToken=e,this.user={id:i.user_id,name:i.user_name,email:i.user_email,avatar_url:i.user_avatar_url},this.onAuthChange?.(this.user)}catch{localStorage.removeItem("tack_session")}}signIn(){return new Promise((e,t)=>{let i=this.apiUrl.replace(/\/api$/,""),n=window.open(`${i}/auth/widget`,"tack-auth","width=500,height=600,popup=yes");if(!n){t(new Error("Popup blocked"));return}let r=new URL(this.apiUrl).origin,a=l=>{if(l.data?.type!=="tack:auth"||l.origin!==r)return;window.removeEventListener("message",a),clearInterval(s);let{token:c,user:d}=l.data;this.sessionToken=c,this.user={id:d.user_id,name:d.user_name,email:d.user_email,avatar_url:d.user_avatar_url},localStorage.setItem("tack_session",c),this.onAuthChange?.(this.user),e(this.user)};window.addEventListener("message",a);let s=setInterval(()=>{n.closed&&(clearInterval(s),window.removeEventListener("message",a),this.user||t(new Error("Auth popup closed")))},500)})}signOut(){this.sessionToken&&fetch(`${this.apiUrl}/auth/widget-session`,{method:"DELETE",headers:{Authorization:`Bearer ${this.sessionToken}`}}).catch(()=>{}),this.sessionToken=null,this.user=null,localStorage.removeItem("tack_session"),this.onAuthChange?.(null)}getUser(){return this.user}getSessionToken(){return this.sessionToken}isAuthenticated(){return this.user!==null}setOnAuthChange(e){this.onAuthChange=e}};function D(){return`
|
|
2
2
|
* {
|
|
3
3
|
box-sizing: border-box;
|
|
4
4
|
}
|
|
@@ -1323,6 +1323,96 @@
|
|
|
1323
1323
|
margin: 8px 0 0 36px;
|
|
1324
1324
|
}
|
|
1325
1325
|
|
|
1326
|
+
/* Reactions */
|
|
1327
|
+
.tack-reaction-bar {
|
|
1328
|
+
display: flex;
|
|
1329
|
+
flex-wrap: wrap;
|
|
1330
|
+
gap: 4px;
|
|
1331
|
+
padding: 6px 0 2px 36px;
|
|
1332
|
+
align-items: center;
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
.tack-reaction-pill {
|
|
1336
|
+
display: inline-flex;
|
|
1337
|
+
align-items: center;
|
|
1338
|
+
gap: 4px;
|
|
1339
|
+
padding: 2px 8px;
|
|
1340
|
+
border-radius: 12px;
|
|
1341
|
+
background: #F4F4F5;
|
|
1342
|
+
border: 1px solid transparent;
|
|
1343
|
+
font-size: 13px;
|
|
1344
|
+
cursor: pointer;
|
|
1345
|
+
line-height: 1.4;
|
|
1346
|
+
transition: background 0.15s, border-color 0.15s;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
.tack-reaction-pill:hover {
|
|
1350
|
+
background: #E4E4E7;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
.tack-reaction-pill.mine {
|
|
1354
|
+
background: #EEF2FF;
|
|
1355
|
+
border-color: #C7D2FE;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
.tack-reaction-pill.mine:hover {
|
|
1359
|
+
background: #E0E7FF;
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
.tack-reaction-add {
|
|
1363
|
+
display: inline-flex;
|
|
1364
|
+
align-items: center;
|
|
1365
|
+
justify-content: center;
|
|
1366
|
+
width: 26px;
|
|
1367
|
+
height: 26px;
|
|
1368
|
+
border-radius: 50%;
|
|
1369
|
+
background: #F4F4F5;
|
|
1370
|
+
border: 1px solid transparent;
|
|
1371
|
+
font-size: 14px;
|
|
1372
|
+
color: #A1A1AA;
|
|
1373
|
+
cursor: pointer;
|
|
1374
|
+
transition: background 0.15s, color 0.15s;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
.tack-reaction-add:hover {
|
|
1378
|
+
background: #E4E4E7;
|
|
1379
|
+
color: #71717A;
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
.tack-reaction-picker {
|
|
1383
|
+
display: flex;
|
|
1384
|
+
gap: 2px;
|
|
1385
|
+
background: white;
|
|
1386
|
+
border: 1px solid #E4E4E7;
|
|
1387
|
+
border-radius: 8px;
|
|
1388
|
+
padding: 4px;
|
|
1389
|
+
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
|
1390
|
+
position: absolute;
|
|
1391
|
+
z-index: 10;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
.tack-reaction-picker-item {
|
|
1395
|
+
width: 32px;
|
|
1396
|
+
height: 32px;
|
|
1397
|
+
display: flex;
|
|
1398
|
+
align-items: center;
|
|
1399
|
+
justify-content: center;
|
|
1400
|
+
border: none;
|
|
1401
|
+
background: none;
|
|
1402
|
+
border-radius: 6px;
|
|
1403
|
+
font-size: 18px;
|
|
1404
|
+
cursor: pointer;
|
|
1405
|
+
transition: background 0.1s;
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
.tack-reaction-picker-item:hover {
|
|
1409
|
+
background: #F4F4F5;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
.tack-reaction-picker-item.mine {
|
|
1413
|
+
background: #EEF2FF;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1326
1416
|
/* Divider */
|
|
1327
1417
|
.tack-card-divider {
|
|
1328
1418
|
height: 1px;
|
|
@@ -1651,7 +1741,7 @@
|
|
|
1651
1741
|
Sign in
|
|
1652
1742
|
</button>
|
|
1653
1743
|
</div>
|
|
1654
|
-
`,this.attachFormListeners(e)}attachFormListeners(e){e.addEventListener("mousedown",i=>i.stopPropagation()),e.addEventListener("click",i=>i.stopPropagation()),e.querySelector(".tack-sign-in-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.onSignIn?.()}),e.querySelector(".tack-form-pill-send")?.addEventListener("click",i=>{i.stopPropagation(),this.handleSubmit()});let t=e.querySelector("#tack-comment-content");t&&(t.addEventListener("input",()=>{this.autoExpandTextarea(t);let i=e.querySelector(".tack-form-pill-send");i&&i.classList.toggle("active",t.value.trim().length>0)}),t.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSubmit())})),e.addEventListener("keydown",i=>{let n=i;n.key==="Escape"&&(n.preventDefault(),this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await O(e.anchor.cssSelector,e.anchor.relativeX*100,e.anchor.relativeY*100),e.element&&this.highlightElement){let l=e.element.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.left=`${l.left-4}px`,this.highlightElement.style.top=`${l.top-4}px`,this.highlightElement.style.width=`${l.width+8}px`,this.highlightElement.style.height=`${l.height+8}px`}let t,i;if(e.element){let l=e.element.getBoundingClientRect();t=l.right+12,i=l.top;let c=300;t+c>window.innerWidth-380&&(t=l.left-c-12)}else t=e.anchor.relativeX*window.innerWidth+20,i=e.anchor.relativeY*window.innerHeight;let n=300,r=52,a=Math.min(t,window.innerWidth-n-380),s=Math.min(i,window.innerHeight-r-20);a=Math.max(20,a),s=Math.max(20,s),this.form.style.left=`${a}px`,this.form.style.top=`${s}px`,this.form.classList.add("visible"),setTimeout(()=>{this.form.querySelector("#tack-comment-content")?.focus()},50)}hide(){if(!this.isVisible)return;this.isVisible=!1,this.form.classList.remove("visible"),this.currentTarget=null,this.capturedScreenshot=void 0;let e=this.form.querySelector("#tack-comment-content");e&&(e.value="",e.style.height="28px",e.style.overflowY="hidden");let t=this.form.querySelector(".tack-form-pill-send");t&&t.classList.remove("active"),this.highlightElement&&(this.highlightElement.style.display="none"),this.onHide?.()}isFormVisible(){return this.isVisible}autoExpandTextarea(e){e.style.height="auto";let t=120;e.style.height=`${Math.min(e.scrollHeight,t)}px`,e.style.overflowY=e.scrollHeight>t?"auto":"hidden"}async handleSubmit(){if(this.isSubmitting||!this.currentTarget)return;let e=this.form.querySelector("#tack-comment-content")?.value.trim();if(!e)return;let t;if(this.currentUser)t=this.currentUser.name;else if(t=this.form.querySelector("#tack-author-name")?.value.trim()||"",!t)return;this.isSubmitting=!0;let i=this.form.querySelector(".tack-form-pill-send");i&&i.classList.add("sending");try{this.currentUser||localStorage.setItem("tack_author_name",t);let n={content:e,authorName:t,anchor:this.currentTarget.anchor,screenshot:this.capturedScreenshot};this.hide(),await this.onSubmit(n)}catch(n){console.error("[Tack] Submit failed:",n)}finally{this.isSubmitting=!1,i&&i.classList.remove("sending")}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var
|
|
1744
|
+
`,this.attachFormListeners(e)}attachFormListeners(e){e.addEventListener("mousedown",i=>i.stopPropagation()),e.addEventListener("click",i=>i.stopPropagation()),e.querySelector(".tack-sign-in-btn")?.addEventListener("click",i=>{i.stopPropagation(),this.onSignIn?.()}),e.querySelector(".tack-form-pill-send")?.addEventListener("click",i=>{i.stopPropagation(),this.handleSubmit()});let t=e.querySelector("#tack-comment-content");t&&(t.addEventListener("input",()=>{this.autoExpandTextarea(t);let i=e.querySelector(".tack-form-pill-send");i&&i.classList.toggle("active",t.value.trim().length>0)}),t.addEventListener("keydown",i=>{let n=i;n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.handleSubmit())})),e.addEventListener("keydown",i=>{let n=i;n.key==="Escape"&&(n.preventDefault(),this.hide())})}async show(e){if(this.isVisible)return;if(this.currentTarget=e,this.isVisible=!0,this.capturedScreenshot=await O(e.anchor.cssSelector,e.anchor.relativeX*100,e.anchor.relativeY*100),e.element&&this.highlightElement){let l=e.element.getBoundingClientRect();this.highlightElement.style.display="block",this.highlightElement.style.left=`${l.left-4}px`,this.highlightElement.style.top=`${l.top-4}px`,this.highlightElement.style.width=`${l.width+8}px`,this.highlightElement.style.height=`${l.height+8}px`}let t,i;if(e.element){let l=e.element.getBoundingClientRect();t=l.right+12,i=l.top;let c=300;t+c>window.innerWidth-380&&(t=l.left-c-12)}else t=e.anchor.relativeX*window.innerWidth+20,i=e.anchor.relativeY*window.innerHeight;let n=300,r=52,a=Math.min(t,window.innerWidth-n-380),s=Math.min(i,window.innerHeight-r-20);a=Math.max(20,a),s=Math.max(20,s),this.form.style.left=`${a}px`,this.form.style.top=`${s}px`,this.form.classList.add("visible"),setTimeout(()=>{this.form.querySelector("#tack-comment-content")?.focus()},50)}hide(){if(!this.isVisible)return;this.isVisible=!1,this.form.classList.remove("visible"),this.currentTarget=null,this.capturedScreenshot=void 0;let e=this.form.querySelector("#tack-comment-content");e&&(e.value="",e.style.height="28px",e.style.overflowY="hidden");let t=this.form.querySelector(".tack-form-pill-send");t&&t.classList.remove("active"),this.highlightElement&&(this.highlightElement.style.display="none"),this.onHide?.()}isFormVisible(){return this.isVisible}autoExpandTextarea(e){e.style.height="auto";let t=120;e.style.height=`${Math.min(e.scrollHeight,t)}px`,e.style.overflowY=e.scrollHeight>t?"auto":"hidden"}async handleSubmit(){if(this.isSubmitting||!this.currentTarget)return;let e=this.form.querySelector("#tack-comment-content")?.value.trim();if(!e)return;let t;if(this.currentUser)t=this.currentUser.name;else if(t=this.form.querySelector("#tack-author-name")?.value.trim()||"",!t)return;this.isSubmitting=!0;let i=this.form.querySelector(".tack-form-pill-send");i&&i.classList.add("sending");try{this.currentUser||localStorage.setItem("tack_author_name",t);let n={content:e,authorName:t,anchor:this.currentTarget.anchor,screenshot:this.capturedScreenshot};this.hide(),await this.onSubmit(n)}catch(n){console.error("[Tack] Submit failed:",n)}finally{this.isSubmitting=!1,i&&i.classList.remove("sending")}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var M=class{constructor(){this.cache=new Map;this.pending=new Map}get(e){return this.cache.get(e)||e}async preload(e){let t=[...new Set(e.filter(i=>!!i&&!this.cache.has(i)))];t.length!==0&&await Promise.all(t.map(i=>this.resolve(i)))}resolve(e){if(this.cache.has(e))return Promise.resolve(this.cache.get(e));if(this.pending.has(e))return this.pending.get(e);let t=fetch(e,{mode:"cors"}).then(i=>{if(!i.ok)throw new Error(`${i.status}`);return i.blob()}).then(i=>{let n=URL.createObjectURL(i);return this.cache.set(e,n),this.pending.delete(e),n}).catch(()=>(this.pending.delete(e),e));return this.pending.set(e,t),t}destroy(){this.cache.forEach(e=>URL.revokeObjectURL(e)),this.cache.clear(),this.pending.clear()}},h=new M;var F=[["#818CF8","#6366F1"],["#A78BFA","#7C3AED"],["#F472B6","#EC4899"],["#FBBF24","#F59E0B"],["#34D399","#10B981"],["#60A5FA","#3B82F6"],["#F87171","#EF4444"],["#2DD4BF","#14B8A6"]],z=F.map(([,o])=>o);function B(o){let e=0;for(let t=0;t<o.length;t++)e=o.charCodeAt(t)+((e<<5)-e);return Math.abs(e)}function j(o){return z[B(o)%z.length]}function $(o){let[e,t]=F[B(o)%F.length];return`linear-gradient(135deg, ${e} 0%, ${t} 100%)`}function u(o){let e=o.trim().split(/\s+/);return e.length>=2?(e[0][0]+e[e.length-1][0]).toUpperCase():o.slice(0,2).toUpperCase()}function m(o,e,t,i=""){let n=Math.round(t*.38),r=i?` ${i}`:"";return e?`<img
|
|
1655
1745
|
src="${h.get(e)}"
|
|
1656
1746
|
alt="${u(o)}"
|
|
1657
1747
|
class="tack-avatar-img${r}"
|
|
@@ -1813,7 +1903,7 @@
|
|
|
1813
1903
|
<div class="tack-comment-content">${this.escapeHtml(e.content)}</div>
|
|
1814
1904
|
</div>
|
|
1815
1905
|
</div>
|
|
1816
|
-
`}getFilteredComments(){let e=this.comments.filter(t=>!t.parent_id);if(this.filters.showResolved||(e=e.filter(t=>!t.resolved)),this.filters.onlyYourThreads&&this.currentUser){let t=this.currentUser.id,i=this.currentUser.name;e=e.filter(n=>!!(n.user_id===t||n.author_name===i||n.replies?.some(r=>r.user_id===t||r.author_name===i)))}if(this.filters.onlyCurrentPage){let t=this.getCurrentPagePath();e=e.filter(i=>i.page_path===t)}if(this.searchQuery){let t=this.searchQuery;e=e.filter(i=>!!(i.author_name.toLowerCase().includes(t)||i.content.toLowerCase().includes(t)||i.replies?.some(n=>n.content.toLowerCase().includes(t)||n.author_name.toLowerCase().includes(t))))}switch(this.filters.sort){case"unread":e.sort((t,i)=>{let n=this.isRead(t.id)?1:0,r=this.isRead(i.id)?1:0;return n!==r?n-r:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;case"replies":e.sort((t,i)=>{let n=t.replies?.length||0,r=i.replies?.length||0;return r!==n?r-n:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;default:e.sort((t,i)=>new Date(i.created_at).getTime()-new Date(t.created_at).getTime());break}return e}scrollToComment(e){this.highlightedId=e,this.renderComments(),this.panel.querySelector(`[data-id="${e}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.highlightedId=null,this.renderComments()},2e3)}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var S=class{resolve(e){if(!e)return{element:null,confidence:"none",method:"none"};if(e.cssSelector){let t=this.tryCssSelector(e);if(t.element)return t}if(e.xpath){let t=this.tryXPath(e);if(t.element)return t}if(e.textQuote){let t=this.tryTextQuote(e.textQuote);if(t.element)return t}if(e.textQuote){let t=this.tryFuzzySearch(e.textQuote);if(t.element)return t}return{element:null,confidence:"none",method:"none"}}calculatePinPosition(e,t){let i=e.getBoundingClientRect(),n=i.left+t.relativeX*i.width+window.scrollX,r=i.top+t.relativeY*i.height+window.scrollY;return{x:n,y:r}}tryCssSelector(e){try{let t=document.querySelector(e.cssSelector);return t?e.contentHash?this.generateContentHash(t)===e.contentHash?{element:t,confidence:"high",method:"css"}:{element:t,confidence:"medium",method:"css"}:{element:t,confidence:"high",method:"css"}:{element:null,confidence:"none",method:"css"}}catch{return{element:null,confidence:"none",method:"css"}}}tryXPath(e){try{let i=document.evaluate(e.xpath,document.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return i?e.contentHash?this.generateContentHash(i)===e.contentHash?{element:i,confidence:"high",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:null,confidence:"none",method:"xpath"}}catch{return{element:null,confidence:"none",method:"xpath"}}}tryTextQuote(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=t.nextNode();for(;i;){let n=i,r=n.textContent?.trim();if(r&&r.includes(e.exact)&&this.verifyContext(n,e))return{element:n,confidence:"high",method:"textQuote"};i=t.nextNode()}return{element:null,confidence:"none",method:"textQuote"}}tryFuzzySearch(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=null,n=e.exact.toLowerCase(),r=t.nextNode();for(;r;){let a=r,s=a.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let l=this.similarityScore(s,n);l>.7&&(!i||l>i.score)&&(i={element:a,score:l})}r=t.nextNode()}return i?{element:i.element,confidence:i.score>.9?"medium":"low",method:"fuzzy"}:{element:null,confidence:"none",method:"fuzzy"}}verifyContext(e,t){if(!t.prefix&&!t.suffix)return!0;let i=e.parentElement;if(!i)return!0;let n=i.textContent||"",r=e.textContent||"",a=n.indexOf(r);if(a===-1)return!0;if(t.prefix&&!n.slice(Math.max(0,a-50),a).trim().includes(t.prefix.slice(-20)))return!1;if(t.suffix){let s=a+r.length;if(!n.slice(s,s+50).trim().includes(t.suffix.slice(0,20)))return!1}return!0}similarityScore(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let i=new Set,n=new Set;for(let a=0;a<e.length-1;a++)i.add(e.slice(a,a+2));for(let a=0;a<t.length-1;a++)n.add(t.slice(a,a+2));let r=0;return i.forEach(a=>{n.has(a)&&r++}),2*r/(i.size+n.size)}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}};function re(o){return o.map(e=>`${e.id}:${e.resolved}:${e.content}:${e.replies?.length||0}`).join("|")}var A=class{constructor(e,t){this.highlightedId=null;this.activeId=null;this.pins=new Map;this.resizeObserver=null;this.repositionRAF=null;this.hoverTimers=new Map;this.leaveTimers=new Map;this.currentlyExpanded=null;this.lastFingerprint="";this.container=e,this.onClick=t,this.anchoring=new S,this.boundScheduleReposition=this.scheduleReposition.bind(this),this.pinsContainer=document.createElement("div"),this.pinsContainer.className="tack-pins-container",this.container.appendChild(this.pinsContainer),this.setupResizeObserver(),window.addEventListener("scroll",this.boundScheduleReposition,{passive:!0}),window.addEventListener("resize",this.boundScheduleReposition,{passive:!0})}setupResizeObserver(){this.resizeObserver=new ResizeObserver(()=>{this.scheduleReposition()}),this.resizeObserver.observe(document.body)}scheduleReposition(){this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),this.repositionRAF=requestAnimationFrame(()=>{this.repositionAllPins()})}repositionAllPins(){this.pins.forEach((e,t)=>{e.targetElement&&!document.contains(e.targetElement)&&(e.anchorResult=this.anchoring.resolve(e.comment.anchor),e.targetElement=e.anchorResult.element),this.positionPin(e)})}getCurrentPagePath(){return window.location.pathname}render(e){let t=this.getCurrentPagePath(),i=t+"::"+re(e);if(i===this.lastFingerprint)return;this.lastFingerprint=i,this.hoverTimers.forEach(r=>clearTimeout(r)),this.hoverTimers.clear(),this.leaveTimers.forEach(r=>clearTimeout(r)),this.leaveTimers.clear(),this.currentlyExpanded=null,this.pinsContainer.innerHTML="",this.pins.clear(),e.filter(r=>!r.parent_id&&r.page_path===t).forEach(r=>{let a=this.createPin(r);a&&(this.pins.set(r.id,a),this.pinsContainer.appendChild(a.element))})}getUniqueAuthors(e){let t=new Set,i=[],n=e.user_id||e.author_name;if(t.add(n),i.push({name:e.author_name,avatar_url:e.author_avatar_url}),e.replies)for(let r of e.replies){let a=r.user_id||r.author_name;t.has(a)||(t.add(a),i.push({name:r.author_name,avatar_url:r.author_avatar_url}))}return i}renderInsetAvatar(e,t){let i=u(e.name),n
|
|
1906
|
+
`}getFilteredComments(){let e=this.comments.filter(t=>!t.parent_id);if(this.filters.showResolved||(e=e.filter(t=>!t.resolved)),this.filters.onlyYourThreads&&this.currentUser){let t=this.currentUser.id,i=this.currentUser.name;e=e.filter(n=>!!(n.user_id===t||n.author_name===i||n.replies?.some(r=>r.user_id===t||r.author_name===i)))}if(this.filters.onlyCurrentPage){let t=this.getCurrentPagePath();e=e.filter(i=>i.page_path===t)}if(this.searchQuery){let t=this.searchQuery;e=e.filter(i=>!!(i.author_name.toLowerCase().includes(t)||i.content.toLowerCase().includes(t)||i.replies?.some(n=>n.content.toLowerCase().includes(t)||n.author_name.toLowerCase().includes(t))))}switch(this.filters.sort){case"unread":e.sort((t,i)=>{let n=this.isRead(t.id)?1:0,r=this.isRead(i.id)?1:0;return n!==r?n-r:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;case"replies":e.sort((t,i)=>{let n=t.replies?.length||0,r=i.replies?.length||0;return r!==n?r-n:new Date(i.created_at).getTime()-new Date(t.created_at).getTime()});break;default:e.sort((t,i)=>new Date(i.created_at).getTime()-new Date(t.created_at).getTime());break}return e}getFilteredCommentIds(){return this.getFilteredComments().map(e=>e.id)}scrollToComment(e){this.highlightedId=e,this.renderComments(),this.panel.querySelector(`[data-id="${e}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.highlightedId=null,this.renderComments()},2e3)}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var S=class{resolve(e){if(!e)return{element:null,confidence:"none",method:"none"};if(e.cssSelector){let t=this.tryCssSelector(e);if(t.element)return t}if(e.xpath){let t=this.tryXPath(e);if(t.element)return t}if(e.textQuote){let t=this.tryTextQuote(e.textQuote);if(t.element)return t}if(e.textQuote){let t=this.tryFuzzySearch(e.textQuote);if(t.element)return t}return{element:null,confidence:"none",method:"none"}}calculatePinPosition(e,t){let i=e.getBoundingClientRect(),n=i.left+t.relativeX*i.width+window.scrollX,r=i.top+t.relativeY*i.height+window.scrollY;return{x:n,y:r}}tryCssSelector(e){try{let t=document.querySelector(e.cssSelector);return t?e.contentHash?this.generateContentHash(t)===e.contentHash?{element:t,confidence:"high",method:"css"}:{element:t,confidence:"medium",method:"css"}:{element:t,confidence:"high",method:"css"}:{element:null,confidence:"none",method:"css"}}catch{return{element:null,confidence:"none",method:"css"}}}tryXPath(e){try{let i=document.evaluate(e.xpath,document.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return i?e.contentHash?this.generateContentHash(i)===e.contentHash?{element:i,confidence:"high",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:i,confidence:"medium",method:"xpath"}:{element:null,confidence:"none",method:"xpath"}}catch{return{element:null,confidence:"none",method:"xpath"}}}tryTextQuote(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=t.nextNode();for(;i;){let n=i,r=n.textContent?.trim();if(r&&r.includes(e.exact)&&this.verifyContext(n,e))return{element:n,confidence:"high",method:"textQuote"};i=t.nextNode()}return{element:null,confidence:"none",method:"textQuote"}}tryFuzzySearch(e){let t=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,null),i=null,n=e.exact.toLowerCase(),r=t.nextNode();for(;r;){let a=r,s=a.textContent?.trim().toLowerCase();if(s&&s.length<1e3){let l=this.similarityScore(s,n);l>.7&&(!i||l>i.score)&&(i={element:a,score:l})}r=t.nextNode()}return i?{element:i.element,confidence:i.score>.9?"medium":"low",method:"fuzzy"}:{element:null,confidence:"none",method:"fuzzy"}}verifyContext(e,t){if(!t.prefix&&!t.suffix)return!0;let i=e.parentElement;if(!i)return!0;let n=i.textContent||"",r=e.textContent||"",a=n.indexOf(r);if(a===-1)return!0;if(t.prefix&&!n.slice(Math.max(0,a-50),a).trim().includes(t.prefix.slice(-20)))return!1;if(t.suffix){let s=a+r.length;if(!n.slice(s,s+50).trim().includes(t.suffix.slice(0,20)))return!1}return!0}similarityScore(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let i=new Set,n=new Set;for(let a=0;a<e.length-1;a++)i.add(e.slice(a,a+2));for(let a=0;a<t.length-1;a++)n.add(t.slice(a,a+2));let r=0;return i.forEach(a=>{n.has(a)&&r++}),2*r/(i.size+n.size)}generateContentHash(e){let t=e.textContent?.trim().slice(0,500)||"",i=e.tagName.toLowerCase(),n=e.className?.toString()||"",r=`${i}:${n}:${t}`,a=5381;for(let s=0;s<r.length;s++)a=(a<<5)+a+r.charCodeAt(s);return(a>>>0).toString(16)}};function re(o){return o.map(e=>`${e.id}:${e.resolved}:${e.content}:${e.replies?.length||0}`).join("|")}var A=class{constructor(e,t){this.highlightedId=null;this.activeId=null;this.pins=new Map;this.resizeObserver=null;this.repositionRAF=null;this.hoverTimers=new Map;this.leaveTimers=new Map;this.currentlyExpanded=null;this.lastFingerprint="";this.container=e,this.onClick=t,this.anchoring=new S,this.boundScheduleReposition=this.scheduleReposition.bind(this),this.pinsContainer=document.createElement("div"),this.pinsContainer.className="tack-pins-container",this.container.appendChild(this.pinsContainer),this.setupResizeObserver(),window.addEventListener("scroll",this.boundScheduleReposition,{passive:!0}),window.addEventListener("resize",this.boundScheduleReposition,{passive:!0})}setupResizeObserver(){this.resizeObserver=new ResizeObserver(()=>{this.scheduleReposition()}),this.resizeObserver.observe(document.body)}scheduleReposition(){this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),this.repositionRAF=requestAnimationFrame(()=>{this.repositionAllPins()})}repositionAllPins(){this.pins.forEach((e,t)=>{e.targetElement&&!document.contains(e.targetElement)&&(e.anchorResult=this.anchoring.resolve(e.comment.anchor),e.targetElement=e.anchorResult.element),this.positionPin(e)})}getCurrentPagePath(){return window.location.pathname}render(e){let t=this.getCurrentPagePath(),i=t+"::"+re(e);if(i===this.lastFingerprint)return;this.lastFingerprint=i,this.hoverTimers.forEach(r=>clearTimeout(r)),this.hoverTimers.clear(),this.leaveTimers.forEach(r=>clearTimeout(r)),this.leaveTimers.clear(),this.currentlyExpanded=null,this.pinsContainer.innerHTML="",this.pins.clear(),e.filter(r=>!r.parent_id&&r.page_path===t).forEach(r=>{let a=this.createPin(r);a&&(this.pins.set(r.id,a),this.pinsContainer.appendChild(a.element))})}getUniqueAuthors(e){let t=new Set,i=[],n=e.user_id||e.author_name;if(t.add(n),i.push({name:e.author_name,avatar_url:e.author_avatar_url}),e.replies)for(let r of e.replies){let a=r.user_id||r.author_name;t.has(a)||(t.add(a),i.push({name:r.author_name,avatar_url:r.author_avatar_url}))}return i}renderInsetAvatar(e,t){let i=u(e.name),n=$(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${h.get(e.avatar_url)}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}renderStackedAvatar(e,t){let i=u(e.name),n=$(e.name),r=Math.round(t*.38);return e.avatar_url?`<img src="${h.get(e.avatar_url)}" alt="${i}" class="tack-pin-avatar-img" style="width:${t}px;height:${t}px;" onerror="this.outerHTML='<div class=\\'tack-pin-avatar-fallback\\' style=\\'width:${t}px;height:${t}px;background:${n};font-size:${r}px;\\'>${i}</div>'" />`:`<div class="tack-pin-avatar-fallback" style="width:${t}px;height:${t}px;background:${n};font-size:${r}px;">${i}</div>`}createPin(e){let t={element:null,confidence:"none",method:"none"},i=null;e.anchor?(t=this.anchoring.resolve(e.anchor),i=t.element):e.element_selector&&(i=document.querySelector(e.element_selector),i&&(t={element:i,confidence:"medium",method:"css"}));let n=document.createElement("div"),r=e.id===this.activeId,a=e.id===this.highlightedId,s=this.getUniqueAuthors(e),l=s.length>1;n.className=`tack-pin${e.resolved?" resolved":""}${r?" active":""}${a?" highlighted":""}${l?" multi-author":""}`,n.dataset.id=e.id,t.confidence==="low"&&n.classList.add("low-confidence");let c=s[0],d=this.formatTimeAgo(new Date(e.created_at)),p=this.escapeHtml(e.content),v=e.replies?.length||0,H=`<div class="tack-pin-preview">
|
|
1817
1907
|
<div class="tack-pin-preview-header">
|
|
1818
1908
|
<div class="tack-pin-preview-avatar">${this.renderInsetAvatar(c,28)}</div>
|
|
1819
1909
|
<div class="tack-pin-preview-meta">
|
|
@@ -1823,7 +1913,7 @@
|
|
|
1823
1913
|
</div>
|
|
1824
1914
|
<p class="tack-pin-preview-text">${p}</p>
|
|
1825
1915
|
${v>0?`<span class="tack-pin-preview-replies">${v} ${v===1?"reply":"replies"}</span>`:""}
|
|
1826
|
-
</div>`,f;if(l){let Y=s.slice(0,3),I=s.length-3,b='<div class="tack-pin-shell"><div class="tack-pin-avatars">';Y.forEach((W,
|
|
1916
|
+
</div>`,f;if(l){let Y=s.slice(0,3),I=s.length-3,b='<div class="tack-pin-shell"><div class="tack-pin-avatars">';Y.forEach((W,K)=>{b+=`<div class="tack-pin-avatar-stacked" style="z-index:${K+1}">${this.renderStackedAvatar(W,24)}</div>`}),I>0&&(b+=`<div class="tack-pin-avatar-stacked tack-pin-avatar-overflow" style="z-index:4">+${I}</div>`),b+=`</div>${H}</div>`,f=b}else{let k=s[0];f=`<div class="tack-pin-shell">${this.renderInsetAvatar(k,32)}${H}</div>`}e.resolved&&(f+='<div class="tack-pin-check"></div>'),n.innerHTML=f,n.addEventListener("click",k=>{k.stopPropagation(),this.collapsePin(e.id,n),this.onClick(e.id,n)}),this.setupHoverListeners(n,e);let _={comment:e,element:n,targetElement:i,anchorResult:t};return this.positionPin(_),n.style.left===""&&n.style.top===""?null:_}positionPin(e){let{comment:t,element:i,targetElement:n}=e,r=7,a=45;if(t.anchor&&n){let s=this.anchoring.calculatePinPosition(n,t.anchor);i.style.left=`${s.x-r}px`,i.style.top=`${s.y-a}px`;return}if(n){let s=n.getBoundingClientRect();i.style.left=`${s.left+window.scrollX-r}px`,i.style.top=`${s.top+window.scrollY-a}px`;return}if(t.x_percent!==null&&t.y_percent!==null){let s=t.x_percent/100*document.documentElement.scrollWidth,l=t.y_percent/100*document.documentElement.scrollHeight;i.style.left=`${s-r}px`,i.style.top=`${l-a}px`;return}i.style.display="none"}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}setupHoverListeners(e,t){e.addEventListener("mouseenter",()=>{let i=this.leaveTimers.get(t.id);i&&(clearTimeout(i),this.leaveTimers.delete(t.id));let n=window.setTimeout(()=>{this.expandPin(t.id,e),this.hoverTimers.delete(t.id)},150);this.hoverTimers.set(t.id,n)}),e.addEventListener("mouseleave",()=>{let i=this.hoverTimers.get(t.id);i&&(clearTimeout(i),this.hoverTimers.delete(t.id));let n=window.setTimeout(()=>{this.collapsePin(t.id,e),this.leaveTimers.delete(t.id)},120);this.leaveTimers.set(t.id,n)})}expandPin(e,t){if(t.classList.contains("active"))return;if(this.currentlyExpanded&&this.currentlyExpanded!==e){let n=this.pins.get(this.currentlyExpanded);n&&n.element.classList.remove("expanded","expand-left")}this.currentlyExpanded=e;let i=t.getBoundingClientRect();window.innerWidth-i.left<300?t.classList.add("expand-left"):t.classList.remove("expand-left"),t.classList.add("expanded")}collapsePin(e,t){t.classList.remove("expanded","expand-left"),this.currentlyExpanded===e&&(this.currentlyExpanded=null)}setActive(e){this.activeId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("active",i===e)})}highlight(e){this.highlightedId=e,this.pins.forEach((t,i)=>{t.element.classList.toggle("highlighted",i===e)}),setTimeout(()=>{this.highlightedId=null,this.pins.forEach(t=>{t.element.classList.remove("highlighted")})},2e3)}show(){this.pinsContainer.classList.add("visible")}hide(){this.pinsContainer.classList.remove("visible")}destroy(){this.hoverTimers.forEach(e=>clearTimeout(e)),this.leaveTimers.forEach(e=>clearTimeout(e)),this.resizeObserver&&this.resizeObserver.disconnect(),this.repositionRAF&&cancelAnimationFrame(this.repositionRAF),window.removeEventListener("scroll",this.boundScheduleReposition),window.removeEventListener("resize",this.boundScheduleReposition)}};var L=class{constructor(e,t){this.currentComment=null;this.currentUser=null;this.visible=!1;this.editing=!1;this.dropdownOpen=!1;this.pickerOpen=!1;this.container=e,this.callbacks=t,this.card=document.createElement("div"),this.card.className="tack-card",this.card.setAttribute("role","dialog"),this.card.setAttribute("aria-label","Comment details"),this.container.appendChild(this.card),this.card.addEventListener("mousedown",i=>i.stopPropagation()),this.card.addEventListener("click",i=>i.stopPropagation()),this.boundOnMouseDown=this.onDocumentMouseDown.bind(this),this.boundOnKeyDown=this.onKeyDown.bind(this)}setUser(e){this.currentUser=e}show(e,t){if(this.visible&&this.currentComment?.id===e.id){this.hide();return}this.currentComment=e,this.visible=!0,this.editing=!1,this.dropdownOpen=!1,this.pickerOpen=!1,this.renderCard(e),this.positionNear(t),this.card.classList.add("visible"),this.attachListeners(),document.addEventListener("mousedown",this.boundOnMouseDown,!0),document.addEventListener("keydown",this.boundOnKeyDown)}hide(){this.visible&&(this.visible=!1,this.currentComment=null,this.editing=!1,this.dropdownOpen=!1,this.card.classList.remove("visible"),document.removeEventListener("mousedown",this.boundOnMouseDown,!0),document.removeEventListener("keydown",this.boundOnKeyDown),this.callbacks.onClose())}isVisible(){return this.visible}updateComment(e){!this.visible||this.currentComment?.id!==e.id||(this.currentComment=e,this.renderCard(e),this.attachListeners())}onDocumentMouseDown(e){this.card.contains(e.target)||e.composedPath().includes(this.card)||this.hide()}onKeyDown(e){if(e.key==="Escape"){if(this.dropdownOpen){this.dropdownOpen=!1,this.renderCard(this.currentComment),this.attachListeners();return}if(this.editing){this.editing=!1,this.renderCard(this.currentComment),this.attachListeners();return}e.preventDefault(),this.hide()}}positionNear(e){let t=e.getBoundingClientRect(),i=320,n=8,r=document.body.classList.contains("tack-panel-open")?360:0,a=window.innerWidth-r-16,s=t.right+n+window.scrollX;s+i>a+window.scrollX&&(s=t.left-i-n+window.scrollX),s=Math.max(16,s);let l=t.top+window.scrollY,c=window.innerHeight+window.scrollY-16,d=300;l+d>c&&(l=c-d),l=Math.max(16+window.scrollY,l),this.card.style.left=`${s}px`,this.card.style.top=`${l}px`}isOwnComment(e){return this.currentUser?.id&&e.user_id?this.currentUser.id===e.user_id:(localStorage.getItem("tack_author_name")||"")===e.author_name}renderCard(e){let t=e.replies||[],i=localStorage.getItem("tack_author_name")||"Anonymous",n=`
|
|
1827
1917
|
<div class="tack-card-title-bar">
|
|
1828
1918
|
<span class="tack-card-title">Comment</span>
|
|
1829
1919
|
<div class="tack-card-title-actions">
|
|
@@ -1882,7 +1972,7 @@
|
|
|
1882
1972
|
<button class="tack-card-edit-cancel">Cancel</button>
|
|
1883
1973
|
<button class="tack-card-edit-save">Save</button>
|
|
1884
1974
|
</div>
|
|
1885
|
-
</div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,r+="</div>",r}attachListeners(){this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",t=>{t.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelector(".tack-card-more-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.dropdownOpen=!this.dropdownOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-card-dropdown-item").forEach(t=>{t.addEventListener("click",i=>{i.stopPropagation();let n=t.dataset.action;if(n==="edit"){this.dropdownOpen=!1,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let r=this.card.querySelector(".tack-card-edit-textarea");r?.focus(),r?.setSelectionRange(r.value.length,r.value.length)}else n==="delete"&&(this.dropdownOpen=!1,this.currentComment&&(this.callbacks.onDelete(this.currentComment.id),this.hide()))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",t=>{t.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",t=>{t.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),this.saveEdit())}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",t=>{t.stopPropagation(),this.submitReply()})}saveEdit(){if(!this.currentComment)return;let t=this.card.querySelector(".tack-card-edit-textarea")?.value.trim();t&&(this.editing=!1,this.callbacks.onEdit(this.currentComment.id,t))}submitReply(){if(!this.currentComment)return;let e=this.card.querySelector(".tack-card-reply-bar-input"),t=e?.value.trim();t&&(this.callbacks.onReply(this.currentComment.id,t),e.value="")}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var P=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 M=class{constructor(e,t,i){this.ws=null;this.currentUser=null;this.pagePath="";this.users=new Map;this.onPresenceChange=null;this.heartbeatTimer=null;this.reconnectAttempts=0;this.joined=!1;this.ref=1;this.supabaseUrl=e,this.supabaseKey=t,this.projectId=i}join(e){this.currentUser=e,this.connect()}leave(){this.joined=!1,this.currentUser=null,this.users.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.ws&&(this.ws.close(),this.ws=null)}updatePagePath(e){this.pagePath=e,this.joined&&this.ws?.readyState===WebSocket.OPEN&&this.trackPresence()}setOnPresenceChange(e){this.onPresenceChange=e}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.joinChannel()},this.ws.onmessage=i=>{try{let n=JSON.parse(i.data);this.handleMessage(n)}catch{}},this.ws.onclose=()=>{this.currentUser&&this.attemptReconnect()},this.ws.onerror=()=>{}}nextRef(){return(this.ref++).toString()}joinChannel(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"phx_join",payload:{config:{presence:{key:this.currentUser.id}}},ref:this.nextRef()})),this.startHeartbeat(),setTimeout(()=>{this.joined=!0,this.trackPresence()},200)}trackPresence(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.currentUser)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"presence",payload:{type:"presence",event:"track",payload:{user_id:this.currentUser.id,name:this.currentUser.name,avatar_url:this.currentUser.avatar_url,page_path:this.pagePath,online_at:Date.now()}},ref:this.nextRef()}))}handleMessage(e){if(e.event==="presence_state"){this.users.clear();let t=e.payload||{};for(let i of Object.keys(t)){let n=t[i]?.metas;if(n?.length>0){let r=n[0];this.users.set(i,{id:r.user_id||i,name:r.name||"Unknown",avatar_url:r.avatar_url||null})}}this.notifyChange()}else if(e.event==="presence_diff"){let{joins:t,leaves:i}=e.payload||{};if(t)for(let n of Object.keys(t)){let r=t[n]?.metas;if(r?.length>0){let a=r[0];this.users.set(n,{id:a.user_id||n,name:a.name||"Unknown",avatar_url:a.avatar_url||null})}}if(i)for(let n of Object.keys(i))this.users.delete(n);this.notifyChange()}}notifyChange(){let e=Array.from(this.users.values());this.onPresenceChange?.(e)}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:this.nextRef()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=5)return;this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{this.currentUser&&this.connect()},e)}};var g=class{constructor(e){this.container=null;this.shadowRoot=null;this.selector=null;this.form=null;this.panel=null;this.pins=null;this.card=null;this.realtime=null;this.presence=null;this.commentMode=!1;this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.config={apiUrl:"https://tacktext.vercel.app/api",supabaseUrl:"https://etpavqvnpupqdxdptkhc.supabase.co",supabaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0cGF2cXZucHVwcWR4ZHB0a2hjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4MzU4MzgsImV4cCI6MjA5MDQxMTgzOH0.GMSIuPmMaEkNhss_laSm_NchihN_KF9VyyEh5YH4Ru0",...e},this.api=new w(this.config.apiUrl,this.config.projectId),this.auth=new y(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=D(),this.shadowRoot.appendChild(e),this.injectPageStyles();let t=document.createElement("div");if(t.className="tack-wrapper",this.shadowRoot.appendChild(t),this.auth.setOnAuthChange(i=>{this.api.setAuthToken(i?this.auth.getSessionToken():null),this.form?.setUser(i),this.card?.setUser(i),this.panel?.setUser(i),i?this.joinPresence(i):(this.presence?.leave(),this.presence=null)}),await this.auth.init(),this.auth.isAuthenticated()&&this.api.setAuthToken(this.auth.getSessionToken()),this.api.setOnUnauthorized(()=>{this.auth.signOut(),this.showToast("Session expired. Please sign in again.")}),this.selector=new C(this.onElementSelected.bind(this)),this.form=new E(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.panel?.isOpen()&&this.enableCommentMode()}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new T(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:this.onPanelClose.bind(this),onAddComment:this.enableCommentMode.bind(this),onShare:this.onShare.bind(this)}),this.card=new L(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new A(t,this.onPinClick.bind(this)),this.createToggleButton(t),document.body.appendChild(this.container),await this.loadComments(),this.handleDeepLink(),this.subscribeToRealtime(),this.setupUrlChangeDetection(),this.auth.isAuthenticated()){let i=this.auth.getUser();this.joinPresence(i)}}joinPresence(e){!this.config.supabaseUrl||!this.config.supabaseKey||(this.presence?.leave(),this.presence=new M(this.config.supabaseUrl,this.config.supabaseKey,this.config.projectId),this.presence.setOnPresenceChange(t=>{this.panel?.renderPresence(t)}),this.presence.join(e),this.presence.updatePagePath(this.getPagePath()))}async signIn(){try{await this.auth.signIn()}catch(e){console.error("[Tack] Sign in failed:",e)}}getPagePath(){return window.location.pathname}setupUrlChangeDetection(){this.currentPagePath=this.getPagePath(),this.boundOnUrlChange=this.onUrlChange.bind(this),window.addEventListener("popstate",this.boundOnUrlChange),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState(...e),this.onUrlChange()},history.replaceState=(...e)=>{this.originalReplaceState(...e),this.onUrlChange()}}onUrlChange(){let e=this.getPagePath();e!==this.currentPagePath&&(this.currentPagePath=e,this.presence?.updatePagePath(e),setTimeout(()=>{this.loadComments()},100))}createToggleButton(e){let t=document.createElement("button");t.className="tack-toggle",t.setAttribute("aria-label","Toggle comments"),t.setAttribute("aria-expanded","false"),t.innerHTML=`
|
|
1975
|
+
</div>`:r+=`<div class="tack-card-row-body">${this.escapeHtml(e.content)}</div>`,t&&(r+=this.renderReactions(e)),r+="</div>",r}renderReactions(e){let t=e.reactions||[],i=this.currentUser?.id,n=new Map;for(let a of t){let s=n.get(a.emoji)||{count:0,userReacted:!1,users:[]};s.count++,s.users.push(a.user_name),a.user_id===i&&(s.userReacted=!0),n.set(a.emoji,s)}let r='<div class="tack-reaction-bar">';for(let[a,s]of n){let l=s.userReacted?" mine":"",c=s.users.join(", ");r+=`<button class="tack-reaction-pill${l}" data-emoji="${a}" title="${this.escapeHtml(c)}">${a} ${s.count}</button>`}if(r+='<button class="tack-reaction-add" title="Add reaction">+</button>',this.pickerOpen){let a=["\u{1F44D}","\u{1F44E}","\u2764\uFE0F","\u{1F389}","\u{1F440}","\u{1F680}"];r+='<div class="tack-reaction-picker">';for(let s of a){let l=n.get(s)?.userReacted?" mine":"";r+=`<button class="tack-reaction-picker-item${l}" data-picker-emoji="${s}">${s}</button>`}r+="</div>"}return r+="</div>",r}attachListeners(){this.card.querySelector(".tack-card-close-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.hide()}),this.card.querySelector(".tack-card-resolve-icon")?.addEventListener("click",t=>{t.stopPropagation(),this.currentComment&&this.callbacks.onResolve(this.currentComment.id,!this.currentComment.resolved)}),this.card.querySelector(".tack-card-more-btn")?.addEventListener("click",t=>{t.stopPropagation(),this.dropdownOpen=!this.dropdownOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-card-dropdown-item").forEach(t=>{t.addEventListener("click",i=>{i.stopPropagation();let n=t.dataset.action;if(n==="edit"){this.dropdownOpen=!1,this.editing=!0,this.renderCard(this.currentComment),this.attachListeners();let r=this.card.querySelector(".tack-card-edit-textarea");r?.focus(),r?.setSelectionRange(r.value.length,r.value.length)}else n==="delete"&&(this.dropdownOpen=!1,this.currentComment&&(this.callbacks.onDelete(this.currentComment.id),this.hide()))})}),this.card.querySelector(".tack-card-edit-cancel")?.addEventListener("click",t=>{t.stopPropagation(),this.editing=!1,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelector(".tack-card-edit-save")?.addEventListener("click",t=>{t.stopPropagation(),this.saveEdit()}),this.card.querySelector(".tack-card-edit-textarea")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),this.saveEdit())}),this.card.querySelectorAll(".tack-reaction-pill").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.emoji,r=t.classList.contains("mine");this.callbacks.onReaction(this.currentComment.id,n,!r)})}),this.card.querySelector(".tack-reaction-add")?.addEventListener("click",t=>{t.stopPropagation(),this.pickerOpen=!this.pickerOpen,this.renderCard(this.currentComment),this.attachListeners()}),this.card.querySelectorAll(".tack-reaction-picker-item").forEach(t=>{t.addEventListener("click",i=>{if(i.stopPropagation(),!this.currentComment||!this.currentUser)return;let n=t.dataset.pickerEmoji,r=t.classList.contains("mine");this.pickerOpen=!1,this.callbacks.onReaction(this.currentComment.id,n,!r)})}),this.card.querySelector(".tack-card-reply-bar-input")?.addEventListener("keydown",t=>{let i=t;i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.submitReply())}),this.card.querySelector(".tack-card-reply-bar-send")?.addEventListener("click",t=>{t.stopPropagation(),this.submitReply()})}saveEdit(){if(!this.currentComment)return;let t=this.card.querySelector(".tack-card-edit-textarea")?.value.trim();t&&(this.editing=!1,this.callbacks.onEdit(this.currentComment.id,t))}submitReply(){if(!this.currentComment)return;let e=this.card.querySelector(".tack-card-reply-bar-input"),t=e?.value.trim();t&&(this.callbacks.onReply(this.currentComment.id,t),e.value="")}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<604800?`${Math.floor(t/86400)}d ago`:e.toLocaleDateString()}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}};var R=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 P=class{constructor(e,t,i){this.ws=null;this.currentUser=null;this.pagePath="";this.users=new Map;this.onPresenceChange=null;this.heartbeatTimer=null;this.reconnectAttempts=0;this.joined=!1;this.ref=1;this.supabaseUrl=e,this.supabaseKey=t,this.projectId=i}join(e){this.currentUser=e,this.connect()}leave(){this.joined=!1,this.currentUser=null,this.users.clear(),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.ws&&(this.ws.close(),this.ws=null)}updatePagePath(e){this.pagePath=e,this.joined&&this.ws?.readyState===WebSocket.OPEN&&this.trackPresence()}setOnPresenceChange(e){this.onPresenceChange=e}connect(){let e=this.supabaseUrl.replace("https://","wss://")+"/realtime/v1/websocket",t=new URLSearchParams({apikey:this.supabaseKey,vsn:"1.0.0"});this.ws=new WebSocket(`${e}?${t}`),this.ws.onopen=()=>{this.reconnectAttempts=0,this.joinChannel()},this.ws.onmessage=i=>{try{let n=JSON.parse(i.data);this.handleMessage(n)}catch{}},this.ws.onclose=()=>{this.currentUser&&this.attemptReconnect()},this.ws.onerror=()=>{}}nextRef(){return(this.ref++).toString()}joinChannel(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"phx_join",payload:{config:{presence:{key:this.currentUser.id}}},ref:this.nextRef()})),this.startHeartbeat(),setTimeout(()=>{this.joined=!0,this.trackPresence()},200)}trackPresence(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.currentUser)return;let e=`realtime:presence:${this.projectId}`;this.ws.send(JSON.stringify({topic:e,event:"presence",payload:{type:"presence",event:"track",payload:{user_id:this.currentUser.id,name:this.currentUser.name,avatar_url:this.currentUser.avatar_url,page_path:this.pagePath,online_at:Date.now()}},ref:this.nextRef()}))}handleMessage(e){if(e.event==="presence_state"){this.users.clear();let t=e.payload||{};for(let i of Object.keys(t)){let n=t[i]?.metas;if(n?.length>0){let r=n[0];this.users.set(i,{id:r.user_id||i,name:r.name||"Unknown",avatar_url:r.avatar_url||null})}}this.notifyChange()}else if(e.event==="presence_diff"){let{joins:t,leaves:i}=e.payload||{};if(t)for(let n of Object.keys(t)){let r=t[n]?.metas;if(r?.length>0){let a=r[0];this.users.set(n,{id:a.user_id||n,name:a.name||"Unknown",avatar_url:a.avatar_url||null})}}if(i)for(let n of Object.keys(i))this.users.delete(n);this.notifyChange()}}notifyChange(){let e=Array.from(this.users.values());this.onPresenceChange?.(e)}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({topic:"phoenix",event:"heartbeat",payload:{},ref:this.nextRef()}))},3e4)}attemptReconnect(){if(this.reconnectAttempts>=5)return;this.reconnectAttempts++;let e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);setTimeout(()=>{this.currentUser&&this.connect()},e)}};var g=class{constructor(e){this.container=null;this.shadowRoot=null;this.selector=null;this.form=null;this.panel=null;this.pins=null;this.card=null;this.realtime=null;this.presence=null;this.commentMode=!1;this.comments=[];this.currentVersion=null;this.currentPagePath="";this.originalPushState=null;this.originalReplaceState=null;this.pollingInterval=null;this.boundOnUrlChange=null;this.boundOnKeyDown=null;this.navigationIndex=-1;this.config={apiUrl:"https://tacktext.vercel.app/api",supabaseUrl:"https://etpavqvnpupqdxdptkhc.supabase.co",supabaseKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV0cGF2cXZucHVwcWR4ZHB0a2hjIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4MzU4MzgsImV4cCI6MjA5MDQxMTgzOH0.GMSIuPmMaEkNhss_laSm_NchihN_KF9VyyEh5YH4Ru0",...e},this.api=new w(this.config.apiUrl,this.config.projectId),this.auth=new y(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=D(),this.shadowRoot.appendChild(e),this.injectPageStyles();let t=document.createElement("div");if(t.className="tack-wrapper",this.shadowRoot.appendChild(t),this.auth.setOnAuthChange(i=>{this.api.setAuthToken(i?this.auth.getSessionToken():null),this.form?.setUser(i),this.card?.setUser(i),this.panel?.setUser(i),i?this.joinPresence(i):(this.presence?.leave(),this.presence=null)}),await this.auth.init(),this.auth.isAuthenticated()&&this.api.setAuthToken(this.auth.getSessionToken()),this.api.setOnUnauthorized(()=>{this.auth.signOut(),this.showToast("Session expired. Please sign in again.")}),this.selector=new C(this.onElementSelected.bind(this)),this.form=new E(t,this.onCommentSubmit.bind(this)),this.form.setUser(this.auth.getUser()),this.form.setOnHide(()=>{this.panel?.isOpen()&&this.enableCommentMode()}),this.form.setOnSignIn(()=>this.signIn()),this.panel=new T(t,{onCommentClick:this.onCommentClick.bind(this),onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onClose:this.onPanelClose.bind(this),onAddComment:this.enableCommentMode.bind(this),onShare:this.onShare.bind(this)}),this.card=new L(t,{onResolve:this.onResolve.bind(this),onReply:this.onReply.bind(this),onEdit:this.onEdit.bind(this),onDelete:this.onDelete.bind(this),onReaction:this.onReaction.bind(this),onClose:this.onCardClose.bind(this)}),this.card.setUser(this.auth.getUser()),this.panel.setUser(this.auth.getUser()),this.panel.setProjectId(this.config.projectId),this.pins=new A(t,this.onPinClick.bind(this)),this.createToggleButton(t),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 P(this.config.supabaseUrl,this.config.supabaseKey,this.config.projectId),this.presence.setOnPresenceChange(t=>{this.panel?.renderPresence(t)}),this.presence.join(e),this.presence.updatePagePath(this.getPagePath()))}async signIn(){try{await this.auth.signIn()}catch(e){console.error("[Tack] Sign in failed:",e)}}getPagePath(){return window.location.pathname}setupUrlChangeDetection(){this.currentPagePath=this.getPagePath(),this.boundOnUrlChange=this.onUrlChange.bind(this),window.addEventListener("popstate",this.boundOnUrlChange),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...e)=>{this.originalPushState(...e),this.onUrlChange()},history.replaceState=(...e)=>{this.originalReplaceState(...e),this.onUrlChange()}}onUrlChange(){let e=this.getPagePath();e!==this.currentPagePath&&(this.currentPagePath=e,this.presence?.updatePagePath(e),setTimeout(()=>{this.loadComments()},100))}createToggleButton(e){let t=document.createElement("button");t.className="tack-toggle",t.setAttribute("aria-label","Toggle comments"),t.setAttribute("aria-expanded","false"),t.innerHTML=`
|
|
1886
1976
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1887
1977
|
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
|
|
1888
1978
|
</svg>
|
|
@@ -1894,7 +1984,7 @@
|
|
|
1894
1984
|
body {
|
|
1895
1985
|
transition: margin-right 250ms cubic-bezier(0.16, 1, 0.3, 1);
|
|
1896
1986
|
}
|
|
1897
|
-
`,document.head.appendChild(t)}setPanelOpen(e){e?document.body.classList.add("tack-panel-open"):document.body.classList.remove("tack-panel-open")}updateToggleAria(e){let t=this.shadowRoot?.querySelector(".tack-toggle");t&&t.setAttribute("aria-expanded",String(e))}async loadComments(){try{let e=await this.api.getComments();this.comments=e.comments,this.currentVersion=e.version;let t=this.comments.flatMap(i=>[i.author_avatar_url,...i.replies?.map(n=>n.author_avatar_url)||[]]);await h.preload(t),this.pins?.render(this.comments),this.panel?.render(this.comments)}catch(e){console.error("[Tack] Failed to load comments:",e)}}onElementSelected(e){this.form?.isFormVisible()||(this.selector?.disable(),this.form?.show(e))}async onCommentSubmit(e){try{let t={content:e.content,element_selector:e.anchor.cssSelector,x_percent:e.anchor.relativeX*100,y_percent:e.anchor.relativeY*100,anchor:e.anchor,page_path:this.getPagePath(),screenshot_data:e.screenshot};this.auth.isAuthenticated()||(t.author_name=e.authorName,t.author_email=e.authorEmail);let i=await this.api.createComment(t),n={...i,screenshot_url:i.screenshot_url||e.screenshot||null};this.comments.push(n),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.panel?.isOpen()&&this.enableCommentMode()}catch(t){console.error("[Tack] Failed to submit comment:",t),this.showToast("Failed to add comment")}}onCommentClick(e){this.pins?.highlight(e.id),this.scrollToComment(e)}onPinClick(e,t){let i=this.comments.find(n=>n.id===e);i&&(this.card?.show(i,t),this.pins?.setActive(e),this.pins?.highlight(e),this.panel?.isOpen()&&this.panel.scrollToComment(e))}onCardClose(){this.pins?.setActive(null)}async onResolve(e,t){try{await this.api.updateComment(e,{resolved:t});let i=this.comments.find(n=>n.id===e);i&&(i.resolved=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to update comment:",i)}}async onReply(e,t){try{let i={content:t,parent_id:e,page_path:this.getPagePath()};this.auth.isAuthenticated()||(i.author_name=localStorage.getItem("tack_author_name")||"Anonymous");let n=await this.api.createComment(i),r=this.comments.find(a=>a.id===e);r&&(r.replies=r.replies||[],r.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(r))}catch(i){console.error("[Tack] Failed to submit reply:",i)}}async onEdit(e,t){try{await this.api.updateComment(e,{content:t});let i=this.comments.find(n=>n.id===e);i&&(i.content=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to edit comment:",i),this.showToast("Failed to edit comment")}}async onDelete(e){try{await this.api.deleteComment(e),this.comments=this.comments.filter(t=>t.id!==e),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}scrollToComment(e){if(e.element_selector)document.querySelector(e.element_selector)?.scrollIntoView({behavior:"smooth",block:"center"});else if(e.x_percent!==null&&e.y_percent!==null){let t=e.x_percent/100*document.documentElement.scrollWidth,i=e.y_percent/100*document.documentElement.scrollHeight;window.scrollTo({left:t-window.innerWidth/2,top:i-window.innerHeight/2,behavior:"smooth"})}}handleDeepLink(){let e=new URLSearchParams(window.location.search);e.get("tack_open")==="true"&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0));let i=e.get("tack_comment");if(i){let n=this.comments.find(r=>r.id===i);n&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0),this.panel?.scrollToComment(i),this.pins?.highlight(i),this.scrollToComment(n))}}subscribeToRealtime(){if(!this.currentVersion||!this.config.supabaseUrl||!this.config.supabaseKey){this.pollingInterval=setInterval(()=>this.loadComments(),3e4);return}this.realtime=new
|
|
1987
|
+
`,document.head.appendChild(t)}setPanelOpen(e){e?document.body.classList.add("tack-panel-open"):document.body.classList.remove("tack-panel-open")}updateToggleAria(e){let t=this.shadowRoot?.querySelector(".tack-toggle");t&&t.setAttribute("aria-expanded",String(e))}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.toggleCommentMode();return}this.panel?.isOpen()&&(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(r=>r.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;let t=this.comments.flatMap(i=>[i.author_avatar_url,...i.replies?.map(n=>n.author_avatar_url)||[]]);await h.preload(t),this.pins?.render(this.comments),this.panel?.render(this.comments)}catch(e){console.error("[Tack] Failed to load comments:",e)}}onElementSelected(e){this.form?.isFormVisible()||(this.selector?.disable(),this.form?.show(e))}async onCommentSubmit(e){try{let t={content:e.content,element_selector:e.anchor.cssSelector,x_percent:e.anchor.relativeX*100,y_percent:e.anchor.relativeY*100,anchor:e.anchor,page_path:this.getPagePath(),screenshot_data:e.screenshot};this.auth.isAuthenticated()||(t.author_name=e.authorName,t.author_email=e.authorEmail);let i=await this.api.createComment(t),n={...i,screenshot_url:i.screenshot_url||e.screenshot||null};this.comments.push(n),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment added"),this.panel?.isOpen()&&this.enableCommentMode()}catch(t){console.error("[Tack] Failed to submit comment:",t),this.showToast("Failed to add comment")}}onCommentClick(e){this.pins?.highlight(e.id),this.scrollToComment(e)}onPinClick(e,t){let i=this.comments.find(n=>n.id===e);i&&(this.card?.show(i,t),this.pins?.setActive(e),this.pins?.highlight(e),this.panel?.isOpen()&&this.panel.scrollToComment(e))}onCardClose(){this.pins?.setActive(null)}async onResolve(e,t){try{await this.api.updateComment(e,{resolved:t});let i=this.comments.find(n=>n.id===e);i&&(i.resolved=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to update comment:",i)}}async onReply(e,t){try{let i={content:t,parent_id:e,page_path:this.getPagePath()};this.auth.isAuthenticated()||(i.author_name=localStorage.getItem("tack_author_name")||"Anonymous");let n=await this.api.createComment(i),r=this.comments.find(a=>a.id===e);r&&(r.replies=r.replies||[],r.replies.push(n),this.panel?.render(this.comments),this.card?.updateComment(r))}catch(i){console.error("[Tack] Failed to submit reply:",i)}}async onEdit(e,t){try{await this.api.updateComment(e,{content:t});let i=this.comments.find(n=>n.id===e);i&&(i.content=t,this.pins?.render(this.comments),this.panel?.render(this.comments),this.card?.updateComment(i))}catch(i){console.error("[Tack] Failed to edit comment:",i),this.showToast("Failed to edit comment")}}async onDelete(e){try{await this.api.deleteComment(e),this.comments=this.comments.filter(t=>t.id!==e),this.pins?.render(this.comments),this.panel?.render(this.comments),this.showToast("Comment deleted")}catch(t){console.error("[Tack] Failed to delete comment:",t),this.showToast("Failed to delete comment")}}async onReaction(e,t,i){if(!this.auth.isAuthenticated())return;let n=this.comments.find(a=>a.id===e);if(!n)return;let r=this.auth.getUser();n.reactions=n.reactions||[],i?n.reactions.push({emoji:t,user_id:r.id,user_name:r.name}):n.reactions=n.reactions.filter(a=>!(a.emoji===t&&a.user_id===r.id)),this.card?.updateComment(n);try{i?await this.api.addReaction(e,t):await this.api.removeReaction(e,t)}catch(a){console.error("[Tack] Failed to update reaction:",a),await this.loadComments()}}scrollToComment(e){if(e.element_selector)document.querySelector(e.element_selector)?.scrollIntoView({behavior:"smooth",block:"center"});else if(e.x_percent!==null&&e.y_percent!==null){let t=e.x_percent/100*document.documentElement.scrollWidth,i=e.y_percent/100*document.documentElement.scrollHeight;window.scrollTo({left:t-window.innerWidth/2,top:i-window.innerHeight/2,behavior:"smooth"})}}handleDeepLink(){let e=new URLSearchParams(window.location.search);e.get("tack_open")==="true"&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0));let i=e.get("tack_comment");if(i){let n=this.comments.find(r=>r.id===i);n&&(this.panel?.show(),this.setPanelOpen(!0),this.pins?.show(),this.container?.classList.add("tack-active"),this.updateToggleAria(!0),this.panel?.scrollToComment(i),this.pins?.highlight(i),this.scrollToComment(n))}}subscribeToRealtime(){if(!this.currentVersion||!this.config.supabaseUrl||!this.config.supabaseKey){this.pollingInterval=setInterval(()=>this.loadComments(),3e4);return}this.realtime=new R(this.config.supabaseUrl,this.config.supabaseKey,this.currentVersion.id,(e,t)=>{this.handleRealtimeEvent(e,t)}),this.realtime.connect()}handleRealtimeEvent(e,t){switch(e){case"INSERT":if(this.comments.some(r=>r.id===t.id)||this.comments.some(r=>r.replies?.some(a=>a.id===t.id)))return;if(t.parent_id){let r=this.comments.find(a=>a.id===t.parent_id);r&&(r.replies=r.replies||[],r.replies.push(t))}else this.comments.push(t);this.showToast(`New comment from ${t.author_name}`);break;case"UPDATE":let n=this.comments.find(r=>r.id===t.id);n&&Object.assign(n,t);break;case"DELETE":this.comments=this.comments.filter(r=>r.id!==t.id);break}this.pins?.render(this.comments),this.panel?.render(this.comments)}showToast(e){if(!this.shadowRoot)return;let t=document.createElement("div");t.className="tack-toast",t.textContent=e,t.style.cssText=`
|
|
1898
1988
|
position: fixed;
|
|
1899
1989
|
bottom: 80px;
|
|
1900
1990
|
right: 20px;
|
|
@@ -1905,5 +1995,5 @@
|
|
|
1905
1995
|
font-size: 14px;
|
|
1906
1996
|
z-index: 10002;
|
|
1907
1997
|
animation: tack-toast-in 0.3s ease;
|
|
1908
|
-
`,this.shadowRoot.appendChild(t),setTimeout(()=>{t.remove()},3e3)}destroy(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.selector?.disable(),this.realtime?.disconnect(),this.presence?.leave(),this.pins?.destroy(),h.destroy(),this.boundOnUrlChange&&(window.removeEventListener("popstate",this.boundOnUrlChange),this.boundOnUrlChange=null),this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),document.getElementById("tack-page-styles")?.remove(),document.body.classList.remove("tack-panel-open"),this.container?.remove()}};var ae={init(o){let e=new g(o);return e.mount(),e}};0&&(module.exports={Tack,TackWidget});
|
|
1998
|
+
`,this.shadowRoot.appendChild(t),setTimeout(()=>{t.remove()},3e3)}destroy(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.selector?.disable(),this.realtime?.disconnect(),this.presence?.leave(),this.pins?.destroy(),h.destroy(),this.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),document.getElementById("tack-page-styles")?.remove(),document.body.classList.remove("tack-panel-open"),this.container?.remove()}};var ae={init(o){let e=new g(o);return e.mount(),e}};0&&(module.exports={Tack,TackWidget});
|
|
1909
1999
|
//# sourceMappingURL=index.js.map
|