@gamention/pulse-elements 0.1.16 → 0.1.18

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.
@@ -26,7 +26,7 @@
26
26
  * @license
27
27
  * Copyright 2022 Google LLC
28
28
  * SPDX-License-Identifier: BSD-3-Clause
29
- */function ae({context:o,subscribe:e}){return(t,i)=>{typeof i=="object"?i.addInitializer((function(){new Be(this,{context:o,callback:s=>{t.set.call(this,s)},subscribe:e})})):t.constructor.addInitializer((s=>{new Be(s,{context:o,callback:n=>{s[i]=n},subscribe:e})}))}}var At=Object.defineProperty,_t=(o,e,t)=>e in o?At(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,E=(o,e,t)=>_t(o,typeof e!="symbol"?e+"":e,t);const It="ws://localhost:4567";let Me=class{constructor(){E(this,"handlers",new Map)}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);const i=this.handlers.get(e);return i.add(t),()=>i.delete(t)}off(e,t){var i;(i=this.handlers.get(e))==null||i.delete(t)}emit(e,t){var i;(i=this.handlers.get(e))==null||i.forEach(s=>s(t))}removeAll(){this.handlers.clear()}},Mt=class extends Me{constructor(e){super(),E(this,"ws",null),E(this,"endpoint"),E(this,"reconnectAttempt",0),E(this,"reconnectTimer",null),E(this,"_state","disconnected"),this.endpoint=e??It}get state(){return this._state}connect(){this.ws||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",e=>{const t=JSON.parse(e.data);this.emit("message",t)}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var e;(e=this.ws)==null||e.close()}))}disconnect(){var e;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(e=this.ws)==null||e.close(),this.ws=null,this._state="disconnected",this.emit("state",this._state)}send(e){var t;((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){const e=Math.min(1e3*2**this.reconnectAttempt,3e4);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}},Ot=class extends Me{constructor(){super(...arguments),E(this,"baseUrl",""),E(this,"_user",null),E(this,"_users",new Map),E(this,"_presence",new Map),E(this,"_threads",new Map),E(this,"_reactions",new Map),E(this,"_notifications",[]),E(this,"_activityLogs",[]),E(this,"_typing",new Map),E(this,"_viewports",new Map),E(this,"_selections",new Map)}get user(){return this._user}removeComment(e){for(const[t,i]of this._threads){const s=i.comments.findIndex(n=>n.id===e);if(s!==-1){i.comments.splice(s,1),i.comments.length===0&&this._threads.delete(t),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(e=>!e.read).length}get activityLogs(){return this._activityLogs}getUser(e){return this._users.get(e)}getReactions(e){return this._reactions.get(e)??[]}getTypingUsers(e){const t=this._typing.get(e);if(!t)return[];const i=Date.now(),s=[];for(const[n,r]of t)i-r<3e3&&s.push(n);return s}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}resolveUrl(e){return!this.baseUrl||!e||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}${e}`}resolveAttachments(e){return e.map(t=>({...t,url:this.resolveUrl(t.url),thumbnailUrl:t.thumbnailUrl?this.resolveUrl(t.thumbnailUrl):void 0}))}resolveComment(e){return!e.attachments||e.attachments.length===0?e:{...e,attachments:this.resolveAttachments(e.attachments)}}resolveThread(e){return{...e,comments:e.comments.map(t=>this.resolveComment(t))}}handleMessage(e){switch(e.type){case"auth:ok":this._user=e.user,this._users.clear();for(const t of e.users)this._users.set(t.id,t);this._presence.clear();for(const t of e.presence)this._presence.set(t.user.id,t),this._users.set(t.user.id,t.user);this._users.set(e.user.id,e.user),this._threads.clear();for(const t of e.threads)this._threads.set(t.id,this.resolveThread(t));this._notifications=e.notifications,this._reactions.clear();for(const t of e.reactions){const i=this._reactions.get(t.targetId)??[];i.push(t),this._reactions.set(t.targetId,i)}this._activityLogs=[...e.activityLogs],this.emit("auth",e.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(e.user.user.id,e.user),this._users.set(e.user.user.id,e.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(e.userId),this._viewports.delete(e.userId),this._selections.delete(e.userId);for(const t of this._typing.values())t.delete(e.userId);this.emit("presence",this.presence);break;case"presence:update":{const t=this._presence.get(e.userId);t&&(t.status=e.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:e.userId,position:e.position});break;case"click:perform":this.emit("click",{userId:e.userId,position:e.position});break;case"thread:created":this._threads.set(e.thread.id,this.resolveThread(e.thread)),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(this.resolveComment(e.comment)),t.updatedAt=e.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const t=this._threads.get(e.threadId);if(t){const i=t.comments.findIndex(s=>s.id===e.comment.id);i!==-1&&(t.comments[i]=this.resolveComment(e.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const t=this._threads.get(e.threadId);t&&(t.comments=t.comments.filter(i=>i.id!==e.commentId),t.comments.length===0&&this._threads.delete(e.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const t=this._threads.get(e.threadId);t&&(t.resolved=e.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(e.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const t=this._reactions.get(e.reaction.targetId)??[];t.push(e.reaction),this._reactions.set(e.reaction.targetId,t),this.emit("reactions",{targetId:e.reaction.targetId,reactions:t});break}case"reaction:removed":{const t=this._reactions.get(e.targetId);if(t){const i=t.filter(s=>s.id!==e.reactionId);this._reactions.set(e.targetId,i),this.emit("reactions",{targetId:e.targetId,reactions:i})}break}case"notification":this._notifications.unshift(e.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(e.threadId)||this._typing.set(e.threadId,new Map),this._typing.get(e.threadId).set(e.userId,Date.now()),this.emit("typing",{threadId:e.threadId,userId:e.userId});break}case"viewport:update":{this._viewports.set(e.userId,{scrollX:e.scrollX,scrollY:e.scrollY,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,pageWidth:e.pageWidth,pageHeight:e.pageHeight}),this.emit("viewport",{userId:e.userId});break}case"selection:update":this._selections.set(e.userId,e.selection),this.emit("selection",{userId:e.userId,selection:e.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:e.userId,emoji:e.emoji,position:e.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:e.userId,points:e.points,color:e.color,width:e.width});break;case"draw:clear":this.emit("draw-clear",{userId:e.userId});break;case"activity:logged":this._activityLogs.unshift(e.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"error":this.emit("error",e);break}}reset(){this._user=null,this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}},mt=class extends Me{constructor(e){var t;super(),E(this,"state"),E(this,"connection"),E(this,"config"),E(this,"heartbeatTimer",null),E(this,"lastCursorSend",0),E(this,"pendingCursor",null),E(this,"cursorTimer",null),this.config=e,this.state=new Ot,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const i=((t=e.endpoint)==null?void 0:t.replace(/^http/,"ws"))??void 0;this.connection=new Mt(i),this.connection.on("message",s=>{this.state.handleMessage(s),this.emit(s.type,s)}),this.connection.on("state",s=>{this.emit("connection",s),s==="connected"?(this.authenticate(),this.startHeartbeat()):s==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.connection.disconnect(),this.state.reset()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(e){this.connection.send(e)}moveCursor(e){const t=Date.now();this.pendingCursor=e,t-this.lastCursorSend>=50?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},50))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(e){this.send({type:"presence:update",status:e})}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},3e4)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(e,t={}){const i=crypto.randomUUID();return this.send({type:"thread:create",id:i,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),i}reply(e,t,i=[],s){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:i,attachmentIds:s}),n}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}deleteComment(e){this.state.removeComment(e),this.send({type:"comment:delete",commentId:e})}resolveThread(e,t=!0){this.send({type:"thread:resolve",threadId:e,resolved:t})}addReaction(e,t,i){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:i})}removeReaction(e){this.send({type:"reaction:remove",reactionId:e})}markRead(e){this.send({type:"notification:read",notificationId:e})}markAllRead(){this.send({type:"notification:read-all"})}performClick(e){this.send({type:"click:perform",position:e})}sendTyping(e){this.send({type:"typing:start",threadId:e})}updateViewport(e){this.send({type:"viewport:update",...e})}updateSelection(e){this.send({type:"selection:update",selection:e})}dropEmoji(e,t){this.send({type:"emoji:drop",emoji:e,position:t})}drawStroke(e,t,i){this.send({type:"draw:stroke",points:e,color:t,width:i})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=(this.config.endpoint??window.location.origin).replace(/^ws(s?):/,"http$1:"),i=new FormData;i.append("file",e);const s=await fetch(`${t}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:i});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error??"Upload failed")}const n=await s.json();return n.url&&!n.url.startsWith("http")&&(n.url=`${t}${n.url}`),n.thumbnailUrl&&!n.thumbnailUrl.startsWith("http")&&(n.thumbnailUrl=`${t}${n.thumbnailUrl}`),n}setAppearOffline(e){e?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}};/**
29
+ */function ae({context:o,subscribe:e}){return(t,i)=>{typeof i=="object"?i.addInitializer((function(){new Be(this,{context:o,callback:s=>{t.set.call(this,s)},subscribe:e})})):t.constructor.addInitializer((s=>{new Be(s,{context:o,callback:n=>{s[i]=n},subscribe:e})}))}}var At=Object.defineProperty,_t=(o,e,t)=>e in o?At(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,E=(o,e,t)=>_t(o,typeof e!="symbol"?e+"":e,t);const It="ws://localhost:4567";let Me=class{constructor(){E(this,"handlers",new Map)}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set);const i=this.handlers.get(e);return i.add(t),()=>i.delete(t)}off(e,t){var i;(i=this.handlers.get(e))==null||i.delete(t)}emit(e,t){var i;(i=this.handlers.get(e))==null||i.forEach(s=>s(t))}removeAll(){this.handlers.clear()}},Mt=class extends Me{constructor(e){super(),E(this,"ws",null),E(this,"endpoint"),E(this,"reconnectAttempt",0),E(this,"reconnectTimer",null),E(this,"_state","disconnected"),this.endpoint=e??It}get state(){return this._state}connect(){this.ws||(this._state="connecting",this.emit("state",this._state),this.ws=new WebSocket(this.endpoint),this.ws.addEventListener("open",()=>{this._state="connected",this.reconnectAttempt=0,this.emit("state",this._state)}),this.ws.addEventListener("message",e=>{const t=JSON.parse(e.data);this.emit("message",t)}),this.ws.addEventListener("close",()=>{this.ws=null,this._state="disconnected",this.emit("state",this._state),this.scheduleReconnect()}),this.ws.addEventListener("error",()=>{var e;(e=this.ws)==null||e.close()}))}disconnect(){var e;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,(e=this.ws)==null||e.close(),this.ws=null,this._state="disconnected",this.emit("state",this._state)}send(e){var t;((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){const e=Math.min(1e3*2**this.reconnectAttempt,3e4);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}},Ot=class extends Me{constructor(){super(...arguments),E(this,"baseUrl",""),E(this,"_user",null),E(this,"_users",new Map),E(this,"_presence",new Map),E(this,"_threads",new Map),E(this,"_reactions",new Map),E(this,"_notifications",[]),E(this,"_activityLogs",[]),E(this,"_typing",new Map),E(this,"_viewports",new Map),E(this,"_selections",new Map)}get user(){return this._user}removeComment(e){for(const[t,i]of this._threads){const s=i.comments.findIndex(n=>n.id===e);if(s!==-1){i.comments.splice(s,1),i.comments.length===0&&this._threads.delete(t),this.emit("threads",this.threads);return}}}get presence(){return[...this._presence.values()]}get threads(){return[...this._threads.values()]}get notifications(){return this._notifications}get unreadCount(){return this._notifications.filter(e=>!e.read).length}markNotificationRead(e){const t=this._notifications.find(i=>i.id===e);t&&!t.read&&(t.read=!0,this.emit("notifications",this._notifications))}markAllNotificationsRead(){let e=!1;for(const t of this._notifications)t.read||(t.read=!0,e=!0);e&&this.emit("notifications",this._notifications)}get activityLogs(){return this._activityLogs}getUser(e){return this._users.get(e)}getReactions(e){return this._reactions.get(e)??[]}getTypingUsers(e){const t=this._typing.get(e);if(!t)return[];const i=Date.now(),s=[];for(const[n,r]of t)i-r<3e3&&s.push(n);return s}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}resolveUrl(e){return!this.baseUrl||!e||e.startsWith("http://")||e.startsWith("https://")?e:`${this.baseUrl}${e}`}resolveAttachments(e){return e.map(t=>({...t,url:this.resolveUrl(t.url),thumbnailUrl:t.thumbnailUrl?this.resolveUrl(t.thumbnailUrl):void 0}))}resolveComment(e){return!e.attachments||e.attachments.length===0?e:{...e,attachments:this.resolveAttachments(e.attachments)}}resolveThread(e){return{...e,comments:e.comments.map(t=>this.resolveComment(t))}}handleMessage(e){switch(e.type){case"auth:ok":this._user=e.user,this._users.clear();for(const t of e.users)this._users.set(t.id,t);this._presence.clear();for(const t of e.presence)this._presence.set(t.user.id,t),this._users.set(t.user.id,t.user);this._users.set(e.user.id,e.user),this._threads.clear();for(const t of e.threads)this._threads.set(t.id,this.resolveThread(t));this._notifications=e.notifications,this._reactions.clear();for(const t of e.reactions){const i=this._reactions.get(t.targetId)??[];i.push(t),this._reactions.set(t.targetId,i)}this._activityLogs=[...e.activityLogs],this.emit("auth",e.user),this.emit("presence",this.presence),this.emit("threads",this.threads),this.emit("notifications",this._notifications),this.emit("reactions",null),this.emit("activity-logs",this._activityLogs);break;case"presence:join":this._presence.set(e.user.user.id,e.user),this._users.set(e.user.user.id,e.user.user),this.emit("presence",this.presence);break;case"presence:leave":this._presence.delete(e.userId),this._viewports.delete(e.userId),this._selections.delete(e.userId);for(const t of this._typing.values())t.delete(e.userId);this.emit("presence",this.presence);break;case"presence:update":{const t=this._presence.get(e.userId);t&&(t.status=e.status,this.emit("presence",this.presence));break}case"cursor:move":this.emit("cursor",{userId:e.userId,position:e.position});break;case"click:perform":this.emit("click",{userId:e.userId,position:e.position});break;case"thread:created":this._threads.set(e.thread.id,this.resolveThread(e.thread)),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(this.resolveComment(e.comment)),t.updatedAt=e.comment.createdAt,this.emit("threads",this.threads));break}case"comment:edited":{const t=this._threads.get(e.threadId);if(t){const i=t.comments.findIndex(s=>s.id===e.comment.id);i!==-1&&(t.comments[i]=this.resolveComment(e.comment)),this.emit("threads",this.threads)}break}case"comment:deleted":{const t=this._threads.get(e.threadId);t&&(t.comments=t.comments.filter(i=>i.id!==e.commentId),t.comments.length===0&&this._threads.delete(e.threadId),this.emit("threads",this.threads));break}case"thread:resolved":{const t=this._threads.get(e.threadId);t&&(t.resolved=e.resolved,this.emit("threads",this.threads));break}case"thread:deleted":this._threads.delete(e.threadId),this.emit("threads",this.threads);break;case"reaction:added":{const t=this._reactions.get(e.reaction.targetId)??[];t.push(e.reaction),this._reactions.set(e.reaction.targetId,t),this.emit("reactions",{targetId:e.reaction.targetId,reactions:t});break}case"reaction:removed":{const t=this._reactions.get(e.targetId);if(t){const i=t.filter(s=>s.id!==e.reactionId);this._reactions.set(e.targetId,i),this.emit("reactions",{targetId:e.targetId,reactions:i})}break}case"notification":this._notifications.unshift(e.notification),this.emit("notifications",this._notifications);break;case"typing:indicator":{this._typing.has(e.threadId)||this._typing.set(e.threadId,new Map),this._typing.get(e.threadId).set(e.userId,Date.now()),this.emit("typing",{threadId:e.threadId,userId:e.userId});break}case"viewport:update":{this._viewports.set(e.userId,{scrollX:e.scrollX,scrollY:e.scrollY,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,pageWidth:e.pageWidth,pageHeight:e.pageHeight}),this.emit("viewport",{userId:e.userId});break}case"selection:update":this._selections.set(e.userId,e.selection),this.emit("selection",{userId:e.userId,selection:e.selection});break;case"emoji:drop":this.emit("emoji-drop",{userId:e.userId,emoji:e.emoji,position:e.position});break;case"draw:stroke":this.emit("draw-stroke",{userId:e.userId,points:e.points,color:e.color,width:e.width});break;case"draw:clear":this.emit("draw-clear",{userId:e.userId});break;case"activity:logged":this._activityLogs.unshift(e.activityLog),this._activityLogs.length>100&&(this._activityLogs=this._activityLogs.slice(0,100)),this.emit("activity-logs",this._activityLogs);break;case"error":this.emit("error",e);break}}reset(){this._user=null,this._users.clear(),this._presence.clear(),this._threads.clear(),this._reactions.clear(),this._notifications=[],this._activityLogs=[],this._typing.clear(),this._viewports.clear(),this._selections.clear()}},mt=class extends Me{constructor(e){var t;super(),E(this,"state"),E(this,"connection"),E(this,"config"),E(this,"heartbeatTimer",null),E(this,"lastCursorSend",0),E(this,"pendingCursor",null),E(this,"cursorTimer",null),this.config=e,this.state=new Ot,this.state.baseUrl=(e.endpoint??"").replace(/^ws(s?):/,"http$1:").replace(/\/$/,"");const i=((t=e.endpoint)==null?void 0:t.replace(/^http/,"ws"))??void 0;this.connection=new Mt(i),this.connection.on("message",s=>{this.state.handleMessage(s),this.emit(s.type,s)}),this.connection.on("state",s=>{this.emit("connection",s),s==="connected"?(this.authenticate(),this.startHeartbeat()):s==="disconnected"&&this.stopHeartbeat()})}get connectionState(){return this.connection.state}connect(){this.connection.connect()}disconnect(){this.stopHeartbeat(),this.connection.disconnect(),this.state.reset()}authenticate(){this.send({type:"auth",apiKey:this.config.apiKey,token:this.config.token,room:this.config.room})}send(e){this.connection.send(e)}moveCursor(e){const t=Date.now();this.pendingCursor=e,t-this.lastCursorSend>=50?this.flushCursor():this.cursorTimer||(this.cursorTimer=setTimeout(()=>{this.cursorTimer=null,this.flushCursor()},50))}flushCursor(){this.pendingCursor&&(this.send({type:"cursor:move",position:this.pendingCursor}),this.lastCursorSend=Date.now(),this.pendingCursor=null)}updatePresence(e){this.send({type:"presence:update",status:e})}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.send({type:"presence:update",status:"online"})},3e4)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}createThread(e,t={}){const i=crypto.randomUUID();return this.send({type:"thread:create",id:i,body:e,mentions:t.mentions??[],position:t.position??null,attachmentIds:t.attachmentIds}),i}reply(e,t,i=[],s){const n=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:n,body:t,mentions:i,attachmentIds:s}),n}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}deleteComment(e){this.state.removeComment(e),this.send({type:"comment:delete",commentId:e})}resolveThread(e,t=!0){this.send({type:"thread:resolve",threadId:e,resolved:t})}addReaction(e,t,i){this.send({type:"reaction:add",targetId:e,targetType:t,emoji:i})}removeReaction(e){this.send({type:"reaction:remove",reactionId:e})}markRead(e){this.state.markNotificationRead(e),this.send({type:"notification:read",notificationId:e})}markAllRead(){this.state.markAllNotificationsRead(),this.send({type:"notification:read-all"})}performClick(e){this.send({type:"click:perform",position:e})}sendTyping(e){this.send({type:"typing:start",threadId:e})}updateViewport(e){this.send({type:"viewport:update",...e})}updateSelection(e){this.send({type:"selection:update",selection:e})}dropEmoji(e,t){this.send({type:"emoji:drop",emoji:e,position:t})}drawStroke(e,t,i){this.send({type:"draw:stroke",points:e,color:t,width:i})}clearDrawing(){this.send({type:"draw:clear"})}async uploadFile(e){const t=(this.config.endpoint??window.location.origin).replace(/^ws(s?):/,"http$1:"),i=new FormData;i.append("file",e);const s=await fetch(`${t}/api/v1/upload`,{method:"POST",headers:{"X-Pulse-Key":this.config.apiKey,"X-Pulse-Token":this.config.token},body:i});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error??"Upload failed")}const n=await s.json();return n.url&&!n.url.startsWith("http")&&(n.url=`${t}${n.url}`),n.thumbnailUrl&&!n.thumbnailUrl.startsWith("http")&&(n.thumbnailUrl=`${t}${n.thumbnailUrl}`),n}setAppearOffline(e){e?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}};/**
30
30
  * @license
31
31
  * Copyright 2019 Google LLC
32
32
  * SPDX-License-Identifier: BSD-3-Clause
@@ -2547,7 +2547,7 @@
2547
2547
  min-height: 44px;
2548
2548
  }
2549
2549
  }
2550
- `];Ne([x({attribute:!1})],re.prototype,"settings",2);Ne([x()],re.prototype,"roomId",2);re=Ne([L("pulse-widget-settings-panel")],re);const me={enabled:!0,showMyCursor:!0,showOthersCursors:!0,showMyClicks:!0,showOthersClicks:!0,appearOffline:!1,showCommentPins:!0,showViewportIndicators:!0,showSelections:!0,showDrawings:!0},kt="pulse:settings:";function us(o){try{const e=localStorage.getItem(`${kt}${o}`);return e?{...me,...JSON.parse(e)}:{...me}}catch{return{...me}}}function fs(o,e){localStorage.setItem(`${kt}${o}`,JSON.stringify(e))}var ms=Object.defineProperty,gs=Object.getOwnPropertyDescriptor,j=(o,e,t,i)=>{for(var s=i>1?void 0:i?gs(e,t):e,n=o.length-1,r;n>=0;n--)(r=o[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&ms(e,t,s),s};let R=class extends T{constructor(){super(...arguments),this.collapsed=!1,this.activePanel=null,this.pinModeActive=!1,this.featuresDisabled=!1,this.drawModeActive=!1,this.followingUserId=null,this.display="floating",this.users=[],this.unreadCount=0}connectedCallback(){super.connectedCallback(),this.setupPresence()}disconnectedCallback(){var o,e;super.disconnectedCallback(),(o=this.unsub)==null||o.call(this),(e=this.notifUnsub)==null||e.call(this)}updated(o){var e,t;o.has("client")&&this.client&&((e=this.unsub)==null||e.call(this),(t=this.notifUnsub)==null||t.call(this),this.setupPresence())}setupPresence(){this.client&&(this.users=this.client.state.presence,this.unreadCount=this.client.state.unreadCount,this.unsub=this.client.state.on("presence",o=>{this.users=o}),this.notifUnsub=this.client.state.on("notifications",()=>{this.unreadCount=this.client.state.unreadCount}))}getInitials(o){return o.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2)}fire(o){this.dispatchEvent(new CustomEvent("toolbar-action",{detail:o,bubbles:!0,composed:!0}))}fireFollow(o){this.dispatchEvent(new CustomEvent("toolbar-follow",{detail:o,bubbles:!0,composed:!0}))}fireToggle(){this.dispatchEvent(new CustomEvent("toolbar-toggle",{bubbles:!0,composed:!0}))}render(){const o=this.display==="inline";if(this.collapsed)return u`
2550
+ `];Ne([x({attribute:!1})],re.prototype,"settings",2);Ne([x()],re.prototype,"roomId",2);re=Ne([L("pulse-widget-settings-panel")],re);const me={enabled:!0,showMyCursor:!0,showOthersCursors:!0,showMyClicks:!0,showOthersClicks:!0,appearOffline:!1,showCommentPins:!0,showViewportIndicators:!0,showSelections:!0,showDrawings:!0},kt="pulse:settings:";function us(o){try{const e=localStorage.getItem(`${kt}${o}`);return e?{...me,...JSON.parse(e)}:{...me}}catch{return{...me}}}function fs(o,e){localStorage.setItem(`${kt}${o}`,JSON.stringify(e))}var ms=Object.defineProperty,gs=Object.getOwnPropertyDescriptor,j=(o,e,t,i)=>{for(var s=i>1?void 0:i?gs(e,t):e,n=o.length-1,r;n>=0;n--)(r=o[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&ms(e,t,s),s};let R=class extends T{constructor(){super(...arguments),this.collapsed=!1,this.activePanel=null,this.pinModeActive=!1,this.featuresDisabled=!1,this.drawModeActive=!1,this.followingUserId=null,this.display="floating",this.users=[],this.unreadCount=0}connectedCallback(){super.connectedCallback(),this.setupPresence()}disconnectedCallback(){var o,e,t;super.disconnectedCallback(),(o=this.unsub)==null||o.call(this),(e=this.authUnsub)==null||e.call(this),(t=this.notifUnsub)==null||t.call(this)}updated(o){var e,t,i;o.has("client")&&this.client&&((e=this.unsub)==null||e.call(this),(t=this.authUnsub)==null||t.call(this),(i=this.notifUnsub)==null||i.call(this),this.setupPresence())}setupPresence(){this.client&&(this.users=this.client.state.presence,this.unreadCount=this.client.state.unreadCount,this.unsub=this.client.state.on("presence",o=>{this.users=[...o]}),this.authUnsub=this.client.state.on("auth",()=>{this.users=this.client.state.presence,this.unreadCount=this.client.state.unreadCount}),this.notifUnsub=this.client.state.on("notifications",()=>{this.unreadCount=this.client.state.unreadCount}))}getInitials(o){return o.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2)}fire(o){this.dispatchEvent(new CustomEvent("toolbar-action",{detail:o,bubbles:!0,composed:!0}))}fireFollow(o){this.dispatchEvent(new CustomEvent("toolbar-follow",{detail:o,bubbles:!0,composed:!0}))}fireToggle(){this.dispatchEvent(new CustomEvent("toolbar-toggle",{bubbles:!0,composed:!0}))}render(){const o=this.display==="inline";if(this.collapsed)return u`
2551
2551
  <div class="toolbar collapsed ${o?"inline":""}" @click=${this.fireToggle}>
2552
2552
  <span class="fab-icon">${C(_i,o?18:24)}</span>
2553
2553
  </div>
@@ -2859,7 +2859,7 @@
2859
2859
  height: 32px;
2860
2860
  }
2861
2861
  }
2862
- `];j([x({attribute:!1})],R.prototype,"client",2);j([x({type:Boolean})],R.prototype,"collapsed",2);j([x()],R.prototype,"activePanel",2);j([x({type:Boolean})],R.prototype,"pinModeActive",2);j([x({type:Boolean})],R.prototype,"featuresDisabled",2);j([x({type:Boolean})],R.prototype,"drawModeActive",2);j([x()],R.prototype,"followingUserId",2);j([x()],R.prototype,"display",2);j([$()],R.prototype,"users",2);j([$()],R.prototype,"unreadCount",2);R=j([L("pulse-widget-toolbar")],R);class vs{constructor(e){this.container=null,this.unsubs=[],this.enabled=!1,this.pillEls=new Map,this.client=e}enable(){this.enabled||(this.enabled=!0,this.container=document.createElement("div"),this.container.id="pulse-widget-viewports",Object.assign(this.container.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",pointerEvents:"none",zIndex:"9996"}),document.body.appendChild(this.container),this.unsubs.push(this.client.state.on("viewport",()=>{this.render()})),this.unsubs.push(this.client.state.on("presence",()=>{this.render()})),this.render())}disable(){var e;this.enabled&&(this.enabled=!1,this.unsubs.forEach(t=>t()),this.unsubs=[],(e=this.container)==null||e.remove(),this.container=null,this.pillEls.clear())}destroy(){this.disable()}render(){var r;if(!this.container)return;if(document.documentElement.scrollHeight<=window.innerHeight){for(const a of this.pillEls.values())a.remove();this.pillEls.clear();return}const e=window.scrollY,t=window.innerHeight,i=document.documentElement.scrollHeight,s=(r=this.client.state.user)==null?void 0:r.id,n=new Set;for(const[a,l]of this.client.state.viewports){if(a===s)continue;const d=l.scrollY,c=l.scrollY+l.viewportHeight,h=e,p=e+t;if(d>=h&&c<=p){const k=this.pillEls.get(a);k&&(k.style.display="none");continue}n.add(a);const m=this.client.state.presence.find(k=>k.user.id===a);if(!m)continue;const g=l.scrollY+l.viewportHeight/2,y=i>0?g/i:0,b=Math.max(8,Math.min(t-28,y*t));let w=this.pillEls.get(a);w||(w=document.createElement("div"),Object.assign(w.style,{position:"absolute",right:"8px",padding:"2px 6px",borderRadius:"10px",fontSize:"10px",fontWeight:"700",color:"#fff",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",whiteSpace:"nowrap",pointerEvents:"none",transition:"top 0.3s ease"}),this.container.appendChild(w),this.pillEls.set(a,w)),w.style.display="",w.style.background=m.user.color,w.style.top=`${b}px`,w.textContent=this.getInitials(m.user.name)}for(const[a,l]of this.pillEls)!n.has(a)&&!this.client.state.viewports.has(a)&&(l.remove(),this.pillEls.delete(a))}getInitials(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}}var bs=Object.defineProperty,xs=Object.getOwnPropertyDescriptor,A=(o,e,t,i)=>{for(var s=i>1?void 0:i?xs(e,t):e,n=o.length-1,r;n>=0;n--)(r=o[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&bs(e,t,s),s};exports.PulseWidget=class extends T{constructor(){super(...arguments),this.apiKey="",this.token="",this.room="",this.position="bottom-right",this.display="floating",this.collapsed=!0,this.activePanel=null,this.pinModeActive=!1,this.highlightThreadId=null,this.settings={...me},this.followingUserId=null,this.drawModeActive=!1,this.connectionState="disconnected",this.showConnectedFlash=!1,this.unsubs=[],this.clientConfigKey="",this._isFollowScrolling=!1,this._viewportThrottleTimer=null,this._selectionThrottleTimer=null,this._connectedFlashTimer=null,this._wasDisconnected=!1,this.handleScroll=()=>{!this.settings.enabled||!this.client||this._isFollowScrolling||(this.followingUserId&&(this.followingUserId=null),!this._viewportThrottleTimer&&(this._viewportThrottleTimer=setTimeout(()=>{var e;this._viewportThrottleTimer=null,(e=this.client)==null||e.updateViewport({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})},200)))},this.handleSelectionChange=()=>{!this.settings.enabled||!this.settings.showSelections||!this.client||this._selectionThrottleTimer||(this._selectionThrottleTimer=setTimeout(()=>{var i,s;this._selectionThrottleTimer=null;const e=window.getSelection();if(!e||e.isCollapsed){(i=this.client)==null||i.updateSelection(null);return}const t=ls(e);(s=this.client)==null||s.updateSelection(t)},500))},this.handleDocumentClick=e=>{var t;this.settings.enabled&&this.settings.showMyClicks&&(this.contains(e.target)||(t=this.client)==null||t.performClick({x:e.clientX,y:e.clientY,pageX:e.pageX,pageY:e.pageY}))},this.handleKeydown=e=>{var t,i;e.key==="Escape"&&(this.drawModeActive?((t=this.drawingOverlay)==null||t.disableDrawMode(),this.drawModeActive=!1):this.followingUserId?this.followingUserId=null:this.pinModeActive?((i=this.commentPins)==null||i.exitPinMode(),this.pinModeActive=!1):this.activePanel&&(this.activePanel=null,this.highlightThreadId=null))}}connectedCallback(){super.connectedCallback(),document.addEventListener("keydown",this.handleKeydown),document.addEventListener("pointerup",this.handleDocumentClick),this.apiKey&&this.token&&this.room&&this.initClient()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.handleKeydown),document.removeEventListener("pointerup",this.handleDocumentClick),this.teardownClient()}getConfigKey(){return`${this.apiKey}\0${this.token}\0${this.room}\0${this.endpoint??""}`}initClient(){const e={apiKey:this.apiKey,token:this.token,room:this.room,endpoint:this.endpoint};this.client=new mt(e),this.clientConfigKey=this.getConfigKey(),this.cursorOverlay=new rs(this.client),this.commentPins=new Ji(this.client,{onPinModeExit:()=>{this.pinModeActive=!1}}),this.viewportOverlay=new vs(this.client),this.selectionOverlay=new ds(this.client),this.drawingOverlay=new as(this.client),this.settings=us(this.room),this.applySettings(this.settings),this.unsubs.push(this.client.on("connection",t=>{this.connectionState=t,t==="connected"&&this._wasDisconnected?(this.showConnectedFlash=!0,this._connectedFlashTimer&&clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=setTimeout(()=>{this.showConnectedFlash=!1,this._connectedFlashTimer=null},2e3),this._wasDisconnected=!1):(t==="connecting"||t==="disconnected")&&(this._wasDisconnected=!0,this.showConnectedFlash=!1,this._connectedFlashTimer&&(clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=null))})),this.unsubs.push(this.client.state.on("click",({userId:t,position:i})=>{var s;this.settings.showOthersClicks&&((s=this.cursorOverlay)!=null&&s.isEnabled)&&this.cursorOverlay.showClickRipple(t,i)})),this.unsubs.push(this.client.state.on("viewport",({userId:t})=>{if(this.followingUserId===t){const i=this.client.state.getViewport(t);i&&(this._isFollowScrolling=!0,window.scrollTo({top:i.scrollY,left:i.scrollX,behavior:"smooth"}),setTimeout(()=>{this._isFollowScrolling=!1},500))}})),window.addEventListener("scroll",this.handleScroll),document.addEventListener("selectionchange",this.handleSelectionChange),this.client.connect()}teardownClient(){var e,t,i,s,n,r;this.unsubs.forEach(a=>a()),this.unsubs=[],window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("selectionchange",this.handleSelectionChange),this._viewportThrottleTimer&&(clearTimeout(this._viewportThrottleTimer),this._viewportThrottleTimer=null),this._selectionThrottleTimer&&(clearTimeout(this._selectionThrottleTimer),this._selectionThrottleTimer=null),(e=this.cursorOverlay)==null||e.destroy(),(t=this.commentPins)==null||t.destroy(),(i=this.viewportOverlay)==null||i.destroy(),(s=this.selectionOverlay)==null||s.destroy(),(n=this.drawingOverlay)==null||n.destroy(),(r=this.client)==null||r.disconnect(),this.client=void 0,this.cursorOverlay=void 0,this.commentPins=void 0,this.viewportOverlay=void 0,this.selectionOverlay=void 0,this.drawingOverlay=void 0,this.clientConfigKey="",this.followingUserId=null,this.drawModeActive=!1,this.connectionState="disconnected",this.showConnectedFlash=!1,this._wasDisconnected=!1,this._connectedFlashTimer&&(clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=null)}handlePanelClose(){this.activePanel=null,this.highlightThreadId=null}handleToolbarAction(e){var i,s,n,r;const t=e.detail;if(!(!this.settings.enabled&&t!=="settings"))switch(t){case"comments":this.activePanel=this.activePanel==="comments"?null:"comments",this.highlightThreadId=null;break;case"settings":this.activePanel=this.activePanel==="settings"?null:"settings";break;case"notifications":this.activePanel=this.activePanel==="notifications"?null:"notifications";break;case"activity":this.activePanel=this.activePanel==="activity"?null:"activity";break;case"pin-mode":this.pinModeActive=!this.pinModeActive,this.pinModeActive?(i=this.commentPins)==null||i.enterPinMode():(s=this.commentPins)==null||s.exitPinMode();break;case"draw-mode":this.drawModeActive=!this.drawModeActive,this.drawModeActive?(n=this.drawingOverlay)==null||n.enableDrawMode():(r=this.drawingOverlay)==null||r.disableDrawMode();break}}handleFollow(e){const t=e.detail;this.followingUserId===t?this.followingUserId=null:this.followingUserId=t}handleSettingsChange(e){const t=e.detail;this.settings=t,fs(this.room,t),this.applySettings(t)}applySettings(e){var t,i,s,n,r,a,l,d,c,h,p,m,g,y,b,w,k;if(!e.enabled){(t=this.cursorOverlay)==null||t.disable(),(i=this.viewportOverlay)==null||i.disable(),(s=this.selectionOverlay)==null||s.disable(),(n=this.drawingOverlay)==null||n.disable(),this.drawModeActive&&((r=this.drawingOverlay)==null||r.disableDrawMode(),this.drawModeActive=!1),(a=this.client)==null||a.setAppearOffline(!0),(l=this.commentPins)==null||l.setVisible(!1),this.followingUserId=null,this.pinModeActive&&((d=this.commentPins)==null||d.exitPinMode(),this.pinModeActive=!1),this.activePanel=this.activePanel==="settings"?"settings":null,this.highlightThreadId=null;return}this.applyCursorSettings(e),(c=this.client)==null||c.setAppearOffline(e.appearOffline),(h=this.commentPins)==null||h.setVisible(e.showCommentPins),e.showViewportIndicators?(p=this.viewportOverlay)==null||p.enable():(m=this.viewportOverlay)==null||m.disable(),e.showSelections?(g=this.selectionOverlay)==null||g.enable():(y=this.selectionOverlay)==null||y.disable(),e.showDrawings?(b=this.drawingOverlay)==null||b.enable():((w=this.drawingOverlay)==null||w.disable(),this.drawModeActive&&((k=this.drawingOverlay)==null||k.disableDrawMode(),this.drawModeActive=!1))}applyCursorSettings(e){if(!this.cursorOverlay)return;e.showMyCursor||e.showOthersCursors?(this.cursorOverlay.enable(),this.cursorOverlay.setSending(e.showMyCursor),this.cursorOverlay.setReceiving(e.showOthersCursors)):this.cursorOverlay.disable()}updated(e){(e.has("room")||e.has("token")||e.has("apiKey")||e.has("endpoint"))&&this.apiKey&&this.token&&this.room&&this.getConfigKey()!==this.clientConfigKey&&(this.teardownClient(),this.initClient(),this.activePanel=null,this.highlightThreadId=null,this.pinModeActive=!1),(e.has("activePanel")||e.has("collapsed"))&&requestAnimationFrame(()=>this.positionPopups())}positionPopups(){var y,b,w,k;const e=this.display==="inline",t=(y=this.shadowRoot)==null?void 0:y.querySelector(".inline-trigger"),i=(b=this.shadowRoot)==null?void 0:b.querySelector("pulse-widget-toolbar"),s=e?t:i;if(!s)return;const n=s.getBoundingClientRect(),r=window.innerWidth,a=window.innerHeight,l=8,d=(w=this.shadowRoot)==null?void 0:w.querySelector(".toolbar-popover");if(d){Object.assign(d.style,{top:"auto",left:"auto"});const _=d.getBoundingClientRect(),M=this.computePosition(n,_,r,a,l);d.style.top=`${M.top}px`,d.style.left=`${M.left}px`}const c=(k=this.shadowRoot)==null?void 0:k.querySelector(".panel-container");if(!c)return;Object.assign(c.style,{top:"auto",left:"auto"});const h=d??i;if(!h)return;const p=h.getBoundingClientRect(),m=c.getBoundingClientRect(),g=this.computePosition(p,m,r,a,l);c.style.top=`${g.top}px`,c.style.left=`${g.left}px`}computePosition(e,t,i,s,n){const r=e.top,a=s-e.bottom;let l;r>=t.height+n?l=e.top-t.height-n:a>=t.height+n?l=e.bottom+n:l=r>=a?Math.max(n,e.top-t.height-n):e.bottom+n;let d;const c=e.right-t.width;return c>=n?d=c:e.left+t.width+n<=i?d=e.left:d=Math.max(n,Math.min(i-t.width-n,e.left)),l=Math.max(n,Math.min(s-t.height-n,l)),d=Math.max(n,Math.min(i-t.width-n,d)),{top:l,left:d}}getFollowUserName(){var t;if(!this.followingUserId)return"";const e=(t=this.client)==null?void 0:t.state.presence.find(i=>i.user.id===this.followingUserId);return(e==null?void 0:e.user.name)??"user"}renderConnectionBanner(){return this.showConnectedFlash?u`<div class="connection-banner connected">
2862
+ `];j([x({attribute:!1})],R.prototype,"client",2);j([x({type:Boolean})],R.prototype,"collapsed",2);j([x()],R.prototype,"activePanel",2);j([x({type:Boolean})],R.prototype,"pinModeActive",2);j([x({type:Boolean})],R.prototype,"featuresDisabled",2);j([x({type:Boolean})],R.prototype,"drawModeActive",2);j([x()],R.prototype,"followingUserId",2);j([x()],R.prototype,"display",2);j([$()],R.prototype,"users",2);j([$()],R.prototype,"unreadCount",2);R=j([L("pulse-widget-toolbar")],R);class vs{constructor(e){this.container=null,this.unsubs=[],this.enabled=!1,this.pillEls=new Map,this.client=e}enable(){this.enabled||(this.enabled=!0,this.container=document.createElement("div"),this.container.id="pulse-widget-viewports",Object.assign(this.container.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",pointerEvents:"none",zIndex:"9996"}),document.body.appendChild(this.container),this.unsubs.push(this.client.state.on("viewport",()=>{this.render()})),this.unsubs.push(this.client.state.on("presence",()=>{this.render()})),this.render())}disable(){var e;this.enabled&&(this.enabled=!1,this.unsubs.forEach(t=>t()),this.unsubs=[],(e=this.container)==null||e.remove(),this.container=null,this.pillEls.clear())}destroy(){this.disable()}render(){var r;if(!this.container)return;if(document.documentElement.scrollHeight<=window.innerHeight){for(const a of this.pillEls.values())a.remove();this.pillEls.clear();return}const e=window.scrollY,t=window.innerHeight,i=document.documentElement.scrollHeight,s=(r=this.client.state.user)==null?void 0:r.id,n=new Set;for(const[a,l]of this.client.state.viewports){if(a===s)continue;const d=l.scrollY,c=l.scrollY+l.viewportHeight,h=e,p=e+t;if(d>=h&&c<=p){const k=this.pillEls.get(a);k&&(k.style.display="none");continue}n.add(a);const m=this.client.state.presence.find(k=>k.user.id===a);if(!m)continue;const g=l.scrollY+l.viewportHeight/2,y=i>0?g/i:0,b=Math.max(8,Math.min(t-28,y*t));let w=this.pillEls.get(a);w||(w=document.createElement("div"),Object.assign(w.style,{position:"absolute",right:"8px",padding:"2px 6px",borderRadius:"10px",fontSize:"10px",fontWeight:"700",color:"#fff",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",whiteSpace:"nowrap",pointerEvents:"none",transition:"top 0.3s ease"}),this.container.appendChild(w),this.pillEls.set(a,w)),w.style.display="",w.style.background=m.user.color,w.style.top=`${b}px`,w.textContent=this.getInitials(m.user.name)}for(const[a,l]of this.pillEls)!n.has(a)&&!this.client.state.viewports.has(a)&&(l.remove(),this.pillEls.delete(a))}getInitials(e){return e.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2)}}var bs=Object.defineProperty,xs=Object.getOwnPropertyDescriptor,A=(o,e,t,i)=>{for(var s=i>1?void 0:i?xs(e,t):e,n=o.length-1,r;n>=0;n--)(r=o[n])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&bs(e,t,s),s};exports.PulseWidget=class extends T{constructor(){super(...arguments),this.apiKey="",this.token="",this.room="",this.position="bottom-right",this.display="floating",this.collapsed=!0,this.activePanel=null,this.pinModeActive=!1,this.highlightThreadId=null,this.settings={...me},this.followingUserId=null,this.drawModeActive=!1,this.connectionState="disconnected",this.showConnectedFlash=!1,this.unsubs=[],this.clientConfigKey="",this._isFollowScrolling=!1,this._viewportThrottleTimer=null,this._selectionThrottleTimer=null,this._connectedFlashTimer=null,this._wasDisconnected=!1,this.handleScroll=()=>{!this.settings.enabled||!this.client||this._isFollowScrolling||(this.followingUserId&&(this.followingUserId=null),!this._viewportThrottleTimer&&(this._viewportThrottleTimer=setTimeout(()=>{var e;this._viewportThrottleTimer=null,(e=this.client)==null||e.updateViewport({scrollX:window.scrollX,scrollY:window.scrollY,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,pageWidth:document.documentElement.scrollWidth,pageHeight:document.documentElement.scrollHeight})},200)))},this.handleSelectionChange=()=>{!this.settings.enabled||!this.settings.showSelections||!this.client||this._selectionThrottleTimer||(this._selectionThrottleTimer=setTimeout(()=>{var i,s;this._selectionThrottleTimer=null;const e=window.getSelection();if(!e||e.isCollapsed){(i=this.client)==null||i.updateSelection(null);return}const t=ls(e);(s=this.client)==null||s.updateSelection(t)},500))},this.handleDocumentClick=e=>{var t;this.settings.enabled&&this.settings.showMyClicks&&(this.contains(e.target)||(t=this.client)==null||t.performClick({x:e.clientX,y:e.clientY,pageX:e.pageX,pageY:e.pageY}))},this.handleKeydown=e=>{var t,i;e.key==="Escape"&&(this.drawModeActive?((t=this.drawingOverlay)==null||t.disableDrawMode(),this.drawModeActive=!1):this.followingUserId?this.followingUserId=null:this.pinModeActive?((i=this.commentPins)==null||i.exitPinMode(),this.pinModeActive=!1):this.activePanel&&(this.activePanel=null,this.highlightThreadId=null))}}connectedCallback(){super.connectedCallback(),document.addEventListener("keydown",this.handleKeydown),document.addEventListener("pointerup",this.handleDocumentClick),this.apiKey&&this.token&&this.room&&this.initClient()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("keydown",this.handleKeydown),document.removeEventListener("pointerup",this.handleDocumentClick),this.teardownClient()}getConfigKey(){return`${this.apiKey}\0${this.token}\0${this.room}\0${this.endpoint??""}`}initClient(){const e={apiKey:this.apiKey,token:this.token,room:this.room,endpoint:this.endpoint};this.client=new mt(e),this.clientConfigKey=this.getConfigKey(),this.cursorOverlay=new rs(this.client),this.commentPins=new Ji(this.client,{onPinModeExit:()=>{this.pinModeActive=!1}}),this.viewportOverlay=new vs(this.client),this.selectionOverlay=new ds(this.client),this.drawingOverlay=new as(this.client),this.settings=us(this.room),this.applySettings(this.settings),this.unsubs.push(this.client.on("connection",t=>{this.connectionState=t,t==="connected"&&this._wasDisconnected?(this.showConnectedFlash=!0,this._connectedFlashTimer&&clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=setTimeout(()=>{this.showConnectedFlash=!1,this._connectedFlashTimer=null},2e3),this._wasDisconnected=!1):(t==="connecting"||t==="disconnected")&&(this._wasDisconnected=!0,this.showConnectedFlash=!1,this._connectedFlashTimer&&(clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=null))})),this.unsubs.push(this.client.state.on("click",({userId:t,position:i})=>{var s;this.settings.showOthersClicks&&((s=this.cursorOverlay)!=null&&s.isEnabled)&&this.cursorOverlay.showClickRipple(t,i)})),this.unsubs.push(this.client.state.on("viewport",({userId:t})=>{if(this.followingUserId===t){const i=this.client.state.getViewport(t);i&&(this._isFollowScrolling=!0,window.scrollTo({top:i.scrollY,left:i.scrollX,behavior:"smooth"}),setTimeout(()=>{this._isFollowScrolling=!1},500))}})),window.addEventListener("scroll",this.handleScroll),document.addEventListener("selectionchange",this.handleSelectionChange),this.client.connect()}teardownClient(){var e,t,i,s,n,r;this.unsubs.forEach(a=>a()),this.unsubs=[],window.removeEventListener("scroll",this.handleScroll),document.removeEventListener("selectionchange",this.handleSelectionChange),this._viewportThrottleTimer&&(clearTimeout(this._viewportThrottleTimer),this._viewportThrottleTimer=null),this._selectionThrottleTimer&&(clearTimeout(this._selectionThrottleTimer),this._selectionThrottleTimer=null),(e=this.cursorOverlay)==null||e.destroy(),(t=this.commentPins)==null||t.destroy(),(i=this.viewportOverlay)==null||i.destroy(),(s=this.selectionOverlay)==null||s.destroy(),(n=this.drawingOverlay)==null||n.destroy(),(r=this.client)==null||r.disconnect(),this.client=void 0,this.cursorOverlay=void 0,this.commentPins=void 0,this.viewportOverlay=void 0,this.selectionOverlay=void 0,this.drawingOverlay=void 0,this.clientConfigKey="",this.followingUserId=null,this.drawModeActive=!1,this.connectionState="disconnected",this.showConnectedFlash=!1,this._wasDisconnected=!1,this._connectedFlashTimer&&(clearTimeout(this._connectedFlashTimer),this._connectedFlashTimer=null)}handlePanelClose(){this.activePanel=null,this.highlightThreadId=null}handleToolbarAction(e){var s,n,r,a;const t=e.detail;if(!this.settings.enabled&&t!=="settings")return;const i=t==="comments"||t==="settings"||t==="notifications"||t==="activity";switch((i||t==="pin-mode")&&this.drawModeActive&&(this.drawModeActive=!1,(s=this.drawingOverlay)==null||s.disableDrawMode()),(i||t==="draw-mode")&&this.pinModeActive&&(this.pinModeActive=!1,(n=this.commentPins)==null||n.exitPinMode()),(t==="pin-mode"||t==="draw-mode")&&(this.activePanel=null),t){case"comments":this.activePanel=this.activePanel==="comments"?null:"comments",this.highlightThreadId=null;break;case"settings":this.activePanel=this.activePanel==="settings"?null:"settings";break;case"notifications":this.activePanel=this.activePanel==="notifications"?null:"notifications";break;case"activity":this.activePanel=this.activePanel==="activity"?null:"activity";break;case"pin-mode":this.pinModeActive=!this.pinModeActive,this.pinModeActive&&((r=this.commentPins)==null||r.enterPinMode());break;case"draw-mode":this.drawModeActive=!this.drawModeActive,this.drawModeActive&&((a=this.drawingOverlay)==null||a.enableDrawMode());break}}handleFollow(e){const t=e.detail;this.followingUserId===t?this.followingUserId=null:this.followingUserId=t}handleSettingsChange(e){const t=e.detail;this.settings=t,fs(this.room,t),this.applySettings(t)}applySettings(e){var t,i,s,n,r,a,l,d,c,h,p,m,g,y,b,w,k;if(!e.enabled){(t=this.cursorOverlay)==null||t.disable(),(i=this.viewportOverlay)==null||i.disable(),(s=this.selectionOverlay)==null||s.disable(),(n=this.drawingOverlay)==null||n.disable(),this.drawModeActive&&((r=this.drawingOverlay)==null||r.disableDrawMode(),this.drawModeActive=!1),(a=this.client)==null||a.setAppearOffline(!0),(l=this.commentPins)==null||l.setVisible(!1),this.followingUserId=null,this.pinModeActive&&((d=this.commentPins)==null||d.exitPinMode(),this.pinModeActive=!1),this.activePanel=this.activePanel==="settings"?"settings":null,this.highlightThreadId=null;return}this.applyCursorSettings(e),(c=this.client)==null||c.setAppearOffline(e.appearOffline),(h=this.commentPins)==null||h.setVisible(e.showCommentPins),e.showViewportIndicators?(p=this.viewportOverlay)==null||p.enable():(m=this.viewportOverlay)==null||m.disable(),e.showSelections?(g=this.selectionOverlay)==null||g.enable():(y=this.selectionOverlay)==null||y.disable(),e.showDrawings?(b=this.drawingOverlay)==null||b.enable():((w=this.drawingOverlay)==null||w.disable(),this.drawModeActive&&((k=this.drawingOverlay)==null||k.disableDrawMode(),this.drawModeActive=!1))}applyCursorSettings(e){if(!this.cursorOverlay)return;e.showMyCursor||e.showOthersCursors?(this.cursorOverlay.enable(),this.cursorOverlay.setSending(e.showMyCursor),this.cursorOverlay.setReceiving(e.showOthersCursors)):this.cursorOverlay.disable()}updated(e){(e.has("room")||e.has("token")||e.has("apiKey")||e.has("endpoint"))&&this.apiKey&&this.token&&this.room&&this.getConfigKey()!==this.clientConfigKey&&(this.teardownClient(),this.initClient(),this.activePanel=null,this.highlightThreadId=null,this.pinModeActive=!1),(e.has("activePanel")||e.has("collapsed"))&&requestAnimationFrame(()=>this.positionPopups())}positionPopups(){var y,b,w,k;const e=this.display==="inline",t=(y=this.shadowRoot)==null?void 0:y.querySelector(".inline-trigger"),i=(b=this.shadowRoot)==null?void 0:b.querySelector("pulse-widget-toolbar"),s=e?t:i;if(!s)return;const n=s.getBoundingClientRect(),r=window.innerWidth,a=window.innerHeight,l=8,d=(w=this.shadowRoot)==null?void 0:w.querySelector(".toolbar-popover");if(d){Object.assign(d.style,{top:"auto",left:"auto"});const _=d.getBoundingClientRect(),M=this.computePosition(n,_,r,a,l);d.style.top=`${M.top}px`,d.style.left=`${M.left}px`}const c=(k=this.shadowRoot)==null?void 0:k.querySelector(".panel-container");if(!c)return;Object.assign(c.style,{top:"auto",left:"auto"});const h=d??i;if(!h)return;const p=h.getBoundingClientRect(),m=c.getBoundingClientRect(),g=this.computePosition(p,m,r,a,l);c.style.top=`${g.top}px`,c.style.left=`${g.left}px`}computePosition(e,t,i,s,n){const r=e.top,a=s-e.bottom;let l;r>=t.height+n?l=e.top-t.height-n:a>=t.height+n?l=e.bottom+n:l=r>=a?Math.max(n,e.top-t.height-n):e.bottom+n;let d;const c=e.right-t.width;return c>=n?d=c:e.left+t.width+n<=i?d=e.left:d=Math.max(n,Math.min(i-t.width-n,e.left)),l=Math.max(n,Math.min(s-t.height-n,l)),d=Math.max(n,Math.min(i-t.width-n,d)),{top:l,left:d}}getFollowUserName(){var t;if(!this.followingUserId)return"";const e=(t=this.client)==null?void 0:t.state.presence.find(i=>i.user.id===this.followingUserId);return(e==null?void 0:e.user.name)??"user"}renderConnectionBanner(){return this.showConnectedFlash?u`<div class="connection-banner connected">
2863
2863
  <span class="connection-dot"></span>Connected
2864
2864
  </div>`:this.connectionState==="connecting"?u`<div class="connection-banner connecting">
2865
2865
  <span class="connection-dot"></span>Reconnecting...