@gamention/pulse-elements 0.1.7 → 0.1.8

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 ne({context:n,subscribe:e}){return(t,i)=>{typeof i=="object"?i.addInitializer((function(){new Ue(this,{context:n,callback:s=>{t.set.call(this,s)},subscribe:e})})):t.constructor.addInitializer((s=>{new Ue(s,{context:n,callback:o=>{s[i]=o},subscribe:e})}))}}var Et=Object.defineProperty,Pt=(n,e,t)=>e in n?Et(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,w=(n,e,t)=>Pt(n,typeof e!="symbol"?e+"":e,t);const _t="ws://localhost:4567";let Te=class{constructor(){w(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()}},Tt=class extends Te{constructor(e){super(),w(this,"ws",null),w(this,"endpoint"),w(this,"reconnectAttempt",0),w(this,"reconnectTimer",null),w(this,"_state","disconnected"),this.endpoint=e??_t}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)}},St=class extends Te{constructor(){super(...arguments),w(this,"_user",null),w(this,"_users",new Map),w(this,"_presence",new Map),w(this,"_threads",new Map),w(this,"_reactions",new Map),w(this,"_notifications",[]),w(this,"_activityLogs",[]),w(this,"_typing",new Map),w(this,"_viewports",new Map),w(this,"_selections",new Map)}get user(){return this._user}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[o,r]of t)i-r<3e3&&s.push(o);return s}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}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,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,e.thread),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(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]=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()}},ht=class extends Te{constructor(e){var t;super(),w(this,"state"),w(this,"connection"),w(this,"config"),w(this,"heartbeatTimer",null),w(this,"lastCursorSend",0),w(this,"pendingCursor",null),w(this,"cursorTimer",null),this.config=e,this.state=new St;const i=((t=e.endpoint)==null?void 0:t.replace(/^http/,"ws"))??void 0;this.connection=new Tt(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}),i}reply(e,t,i=[]){const s=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:s,body:t,mentions:i}),s}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}deleteComment(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,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 o=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(o.error??"Upload failed")}return s.json()}setAppearOffline(e){e?(this.stopHeartbeat(),this.send({type:"presence:update",status:"idle"})):(this.startHeartbeat(),this.send({type:"presence:update",status:"online"}))}};/**
29
+ */function ne({context:n,subscribe:e}){return(t,i)=>{typeof i=="object"?i.addInitializer((function(){new Ue(this,{context:n,callback:s=>{t.set.call(this,s)},subscribe:e})})):t.constructor.addInitializer((s=>{new Ue(s,{context:n,callback:o=>{s[i]=o},subscribe:e})}))}}var Et=Object.defineProperty,Pt=(n,e,t)=>e in n?Et(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,w=(n,e,t)=>Pt(n,typeof e!="symbol"?e+"":e,t);const _t="ws://localhost:4567";let Te=class{constructor(){w(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()}},Tt=class extends Te{constructor(e){super(),w(this,"ws",null),w(this,"endpoint"),w(this,"reconnectAttempt",0),w(this,"reconnectTimer",null),w(this,"_state","disconnected"),this.endpoint=e??_t}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)}},St=class extends Te{constructor(){super(...arguments),w(this,"_user",null),w(this,"_users",new Map),w(this,"_presence",new Map),w(this,"_threads",new Map),w(this,"_reactions",new Map),w(this,"_notifications",[]),w(this,"_activityLogs",[]),w(this,"_typing",new Map),w(this,"_viewports",new Map),w(this,"_selections",new Map)}get user(){return this._user}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[o,r]of t)i-r<3e3&&s.push(o);return s}get viewports(){return this._viewports}getViewport(e){return this._viewports.get(e)}get selections(){return this._selections}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,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,e.thread),this.emit("threads",this.threads);break;case"comment:created":{const t=this._threads.get(e.threadId);t&&(t.comments.push(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]=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()}},ht=class extends Te{constructor(e){var t;super(),w(this,"state"),w(this,"connection"),w(this,"config"),w(this,"heartbeatTimer",null),w(this,"lastCursorSend",0),w(this,"pendingCursor",null),w(this,"cursorTimer",null),this.config=e,this.state=new St;const i=((t=e.endpoint)==null?void 0:t.replace(/^http/,"ws"))??void 0;this.connection=new Tt(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}),i}reply(e,t,i=[]){const s=crypto.randomUUID();return this.send({type:"comment:create",threadId:e,id:s,body:t,mentions:i}),s}editComment(e,t,i=[]){this.send({type:"comment:edit",commentId:e,body:t,mentions:i})}deleteComment(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 o=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(o.error??"Upload failed")}return s.json()}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
@@ -1354,7 +1354,7 @@
1354
1354
  </div>
1355
1355
  `;const i=t.querySelector("input"),s=t.querySelector(".reply-send");this.upload||(this.upload=new ge(this.client)),t.querySelector(".reply-attach-img").addEventListener("click",async()=>{await this.upload.pickFile("image/*")&&this.client.reply(e.id,"(image)")}),t.querySelector(".reply-attach-mic").addEventListener("click",async()=>{this.audioRecorder||(this.audioRecorder=new _e);const r=await this.audioRecorder.startRecording(t);r&&await this.upload.uploadBlob(r,"audio.webm")&&this.client.reply(e.id,"(audio note)")});const o=()=>{const r=i.value.trim();if(!r)return;const l=[...r.matchAll(/@(\w+)/g)].map(a=>a[1]);this.client.reply(e.id,r,l),i.value=""};s.addEventListener("click",o),i.addEventListener("input",()=>{const r=Date.now(),l=this.lastTypingSendPins.get(e.id)??0;r-l>=2e3&&(this.client.sendTyping(e.id),this.lastTypingSendPins.set(e.id,r))}),i.addEventListener("keydown",r=>{r.key==="Enter"&&(r.preventDefault(),o()),r.key==="Escape"&&this.closePopover(),r.stopPropagation()}),this.popover.appendChild(t)}removePickerEl(){var e;(e=this.pickerEl)==null||e.remove(),this.pickerEl=null}showPickerForButton(e,t){this.removePickerEl();const i=e.getBoundingClientRect();this.pickerEl=document.createElement("div"),Object.assign(this.pickerEl.style,{position:"fixed",left:`${i.left}px`,top:`${i.top-4}px`,transform:"translateY(-100%)",display:"flex",gap:"2px",padding:"4px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:"8px",boxShadow:"0 4px 24px rgba(0,0,0,0.12)",zIndex:"10002",fontFamily:ce});for(const s of Hi){const o=document.createElement("button");Object.assign(o.style,{border:"none",background:"none",cursor:"pointer",fontSize:"16px",padding:"4px",borderRadius:"4px",lineHeight:"1"}),o.textContent=s,o.addEventListener("click",r=>{r.stopPropagation();const a=this.client.state.getReactions(t).find(c=>{var h;return c.emoji===s&&c.userId===((h=this.client.state.user)==null?void 0:h.id)});a?this.client.removeReaction(a.id):this.client.addReaction(t,"comment",s),this.popoverPickerOpen=null,this.removePickerEl()}),this.pickerEl.appendChild(o)}document.body.appendChild(this.pickerEl)}buildReactionPillsHtml(e){var a;const t=this.client.state.getReactions(e),i=(a=this.client.state.user)==null?void 0:a.id,s=new Map;for(const c of t){const h=s.get(c.emoji)??{count:0,ownId:null};h.count++,c.userId===i&&(h.ownId=c.id),s.set(c.emoji,h)}const o="display:inline-flex;align-items:center;gap:3px;padding:2px 8px;border-radius:12px;border:1px solid #e2e8f0;background:#fff;font-size:12px;cursor:pointer;transition:all 0.15s;line-height:1.4;",r=o+"background:#eef2ff;border-color:#6366f1;";let l='<div style="margin-left:29px;display:flex;gap:4px;flex-wrap:wrap;margin-top:4px;">';for(const[c,{count:h,ownId:p}]of s){const m=p?r:o;l+=`<button data-reaction-emoji="${c}" data-reaction-target="${e}" ${p?`data-reaction-id="${p}"`:""} style="${m}">
1356
1356
  <span>${c}</span><span style="font-size:11px;font-weight:600;color:#64748b;">${h}</span>
1357
- </button>`}return l+=`<button class="popover-reaction-add" data-comment-id="${e}" style="display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:50%;border:1px dashed #e2e8f0;background:none;cursor:pointer;color:#94a3b8;font-size:14px;">+</button>`,l+="</div>",l}updatePopoverTyping(e){if(!this.popover)return;let t=this.popover.querySelector(".popover-typing");if(!t){t=document.createElement("div"),t.className="popover-typing",Object.assign(t.style,{padding:"0 14px 4px",fontSize:"11px",color:"#94a3b8",fontStyle:"italic",minHeight:"16px"});const s=this.popover.lastElementChild;s&&this.popover.insertBefore(t,s)}const i=this.client.state.getTypingUsers(e).filter(s=>{var o;return s!==((o=this.client.state.user)==null?void 0:o.id)}).map(s=>{const o=this.client.state.presence.find(r=>r.user.id===s);return(o==null?void 0:o.user.name)??"Someone"});i.length===0?t.textContent="":i.length===1?t.textContent=`${i[0]} is typing...`:t.textContent=`${i.join(", ")} are typing...`}formatTime(e){const t=new Date(e),s=new Date().getTime()-t.getTime(),o=Math.floor(s/6e4);if(o<1)return"now";if(o<60)return`${o}m`;const r=Math.floor(o/60);return r<24?`${r}h`:t.toLocaleDateString()}resolvePosition(e){if(e.selector&&e.elementOffsetX!=null&&e.elementOffsetY!=null)try{const t=document.querySelector(e.selector);if(t){const i=t.getBoundingClientRect();return{x:i.left+e.elementOffsetX*i.width,y:i.top+e.elementOffsetY*i.height}}}catch{}return{x:e.x*window.innerWidth,y:e.y*window.innerHeight}}renderPins(){if(!this.container)return;const e=this.threads.filter(i=>i.position&&!i.resolved),t=new Set(e.map(i=>i.id));for(const[i,s]of this.pinEls)t.has(i)||(s.remove(),this.pinEls.delete(i));e.forEach((i,s)=>{const o=i.position;let r=this.pinEls.get(i.id);r||(r=document.createElement("div"),Object.assign(r.style,{position:"fixed",width:"24px",height:"24px",borderRadius:"50%",background:"#6366f1",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:"700",fontFamily:ce,cursor:"pointer",pointerEvents:"auto",boxShadow:"0 2px 8px rgba(99,102,241,0.4)",border:"2px solid #fff",transition:"left 0.15s ease, top 0.15s ease, transform 0.15s ease",zIndex:"9997",transform:"translate(-50%, -50%)"}),r.addEventListener("mouseenter",()=>{r.style.transform="translate(-50%, -50%) scale(1.15)"}),r.addEventListener("mouseleave",()=>{r.style.transform="translate(-50%, -50%)"}),r.addEventListener("click",()=>{if(this.popover&&this.popover.dataset.threadId===i.id){this.closePopover();return}const a=this.threads.find(c=>c.id===i.id);a&&this.showThreadPopover(a,r)}),this.container.appendChild(r),this.pinEls.set(i.id,r)),r.textContent=`${s+1}`;const l=this.resolvePosition(o);r.style.left=`${l.x}px`,r.style.top=`${l.y}px`})}}var qi=Object.defineProperty,Vi=Object.getOwnPropertyDescriptor,L=(n,e,t,i)=>{for(var s=i>1?void 0:i?Vi(e,t):e,o=n.length-1,r;o>=0;o--)(r=n[o])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&qi(e,t,s),s};const Xi=["👍","👎","❤️","🎉","👀","🚀"];let I=class extends _{constructor(){super(...arguments),this.highlightThreadId=null,this.threads=[],this.replyingTo=null,this.editingCommentId=null,this.editBody="",this.pickerOpenForComment=null,this.typingByThread=new Map,this.reactionsVersion=0,this.typingTimers=new Map,this.lastTypingSend=new Map}connectedCallback(){super.connectedCallback(),this.ensureListener()}disconnectedCallback(){super.disconnectedCallback(),this.teardownListeners()}updated(n){var e,t;n.has("client")&&this.client&&this.ensureListener(),(e=this.shadowRoot)==null||e.querySelectorAll(".audio-player-host").forEach(i=>{if(i.children.length>0)return;const s=i.dataset.url;if(s){const o=i.dataset.duration?parseInt(i.dataset.duration):void 0;i.appendChild(Pe.render(s,o))}}),(t=this.shadowRoot)==null||t.querySelectorAll(".video-player-host").forEach(i=>{if(i.children.length>0)return;const s=i.dataset.url;s&&i.appendChild(xt.render(s,i.dataset.poster||void 0))})}teardownListeners(){var n,e,t;(n=this.unsub)==null||n.call(this),this.unsub=void 0,(e=this.reactionUnsub)==null||e.call(this),this.reactionUnsub=void 0,(t=this.typingUnsub)==null||t.call(this),this.typingUnsub=void 0;for(const i of this.typingTimers.values())clearTimeout(i);this.typingTimers.clear()}ensureListener(){this.client&&(this.teardownListeners(),this.threads=[...this.client.state.threads],this.setupListener())}setupListener(){this.client&&(this.threads=this.client.state.threads,this.unsub=this.client.state.on("threads",n=>{this.threads=[...n]}),this.reactionUnsub=this.client.state.on("reactions",()=>{this.reactionsVersion++}),this.typingUnsub=this.client.state.on("typing",({threadId:n})=>{this.refreshTyping(n)}))}refreshTyping(n){const t=this.client.state.getTypingUsers(n).filter(s=>{var o;return s!==((o=this.client.state.user)==null?void 0:o.id)}).map(s=>{const o=this.client.state.presence.find(r=>r.user.id===s);return(o==null?void 0:o.user.name)??"Someone"}),i=new Map(this.typingByThread);i.set(n,t),this.typingByThread=i,this.typingTimers.has(n)&&clearTimeout(this.typingTimers.get(n)),this.typingTimers.set(n,setTimeout(()=>{this.refreshTyping(n)},3500))}handleTypingInput(n){const e=Date.now(),t=this.lastTypingSend.get(n)??0;e-t>=2e3&&(this.client.sendTyping(n),this.lastTypingSend.set(n,e))}toggleReaction(n,e){var o;const t=this.client.state.getReactions(n),i=(o=this.client.state.user)==null?void 0:o.id,s=t.find(r=>r.emoji===e&&r.userId===i);s?this.client.removeReaction(s.id):this.client.addReaction(n,"comment",e),this.pickerOpenForComment=null}fireClose(){this.dispatchEvent(new CustomEvent("panel-close",{bubbles:!0,composed:!0}))}scrollToThread(n){this.updateComplete.then(()=>{var t;const e=(t=this.shadowRoot)==null?void 0:t.querySelector(`[data-thread-id="${n}"]`);e==null||e.scrollIntoView({behavior:"smooth",block:"center"})})}parseMentions(n){return n.split(/(@\w+)/g).map(t=>t.startsWith("@")?d`<span class="mention">${t}</span>`:t)}getInitials(n){return n.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2)}getUserForComment(n){return this.client.state.getUser(n)}formatTime(n){const e=new Date(n),i=new Date().getTime()-e.getTime(),s=Math.floor(i/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const o=Math.floor(s/60);return o<24?`${o}h`:e.toLocaleDateString()}async handleAttachImage(n){this.upload||(this.upload=new ge(this.client)),await this.upload.pickFile("image/*")&&this.client.reply(n,"(image)")}async handleRecordAudio(n){var i;this.upload||(this.upload=new ge(this.client)),this.audioRecorder||(this.audioRecorder=new _e);const e=(i=this.shadowRoot)==null?void 0:i.querySelector(`[data-thread-id="${n}"]`),t=await this.audioRecorder.startRecording(e??document.body);t&&await this.upload.uploadBlob(t,"audio.webm")&&this.client.reply(n,"(audio note)")}handleReply(n,e){e.preventDefault();const i=e.target.querySelector("input"),s=i.value.trim();if(!s)return;const o=[...s.matchAll(/@(\w+)/g)].map(r=>r[1]);this.client.reply(n,s,o),i.value="",this.replyingTo=null}isOwnComment(n){var e,t;return((t=(e=this.client)==null?void 0:e.state.user)==null?void 0:t.id)===n.userId}startEdit(n){this.editingCommentId=n.id,this.editBody=n.body}cancelEdit(){this.editingCommentId=null,this.editBody=""}saveEdit(n){const e=this.editBody.trim();if(!e)return;const t=[...e.matchAll(/@(\w+)/g)].map(i=>i[1]);this.client.editComment(n,e,t),this.editingCommentId=null,this.editBody=""}deleteComment(n){this.client.deleteComment(n)}renderEditForm(n){return d`
1357
+ </button>`}return l+=`<button class="popover-reaction-add" data-comment-id="${e}" style="display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:50%;border:1px dashed #e2e8f0;background:none;cursor:pointer;color:#94a3b8;font-size:14px;">+</button>`,l+="</div>",l}updatePopoverTyping(e){if(!this.popover)return;let t=this.popover.querySelector(".popover-typing");if(!t){t=document.createElement("div"),t.className="popover-typing",Object.assign(t.style,{padding:"0 14px 4px",fontSize:"11px",color:"#94a3b8",fontStyle:"italic",minHeight:"16px"});const s=this.popover.lastElementChild;s&&this.popover.insertBefore(t,s)}const i=this.client.state.getTypingUsers(e).filter(s=>{var o;return s!==((o=this.client.state.user)==null?void 0:o.id)}).map(s=>{const o=this.client.state.presence.find(r=>r.user.id===s);return(o==null?void 0:o.user.name)??"Someone"});i.length===0?t.textContent="":i.length===1?t.textContent=`${i[0]} is typing...`:t.textContent=`${i.join(", ")} are typing...`}formatTime(e){const t=new Date(e),s=new Date().getTime()-t.getTime(),o=Math.floor(s/6e4);if(o<1)return"now";if(o<60)return`${o}m`;const r=Math.floor(o/60);return r<24?`${r}h`:t.toLocaleDateString()}resolvePosition(e){if(e.selector&&e.elementOffsetX!=null&&e.elementOffsetY!=null)try{const t=document.querySelector(e.selector);if(t){const i=t.getBoundingClientRect();return{x:i.left+e.elementOffsetX*i.width,y:i.top+e.elementOffsetY*i.height}}}catch{}return{x:e.x*window.innerWidth,y:e.y*window.innerHeight}}renderPins(){if(!this.container)return;const e=this.threads.filter(i=>i.position&&!i.resolved),t=new Set(e.map(i=>i.id));for(const[i,s]of this.pinEls)t.has(i)||(s.remove(),this.pinEls.delete(i));e.forEach((i,s)=>{const o=i.position;let r=this.pinEls.get(i.id);r||(r=document.createElement("div"),Object.assign(r.style,{position:"fixed",width:"24px",height:"24px",borderRadius:"50%",background:"#6366f1",color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"11px",fontWeight:"700",fontFamily:ce,cursor:"pointer",pointerEvents:"auto",boxShadow:"0 2px 8px rgba(99,102,241,0.4)",border:"2px solid #fff",transition:"left 0.15s ease, top 0.15s ease, transform 0.15s ease",zIndex:"9997",transform:"translate(-50%, -50%)"}),r.addEventListener("mouseenter",()=>{r.style.transform="translate(-50%, -50%) scale(1.15)"}),r.addEventListener("mouseleave",()=>{r.style.transform="translate(-50%, -50%)"}),r.addEventListener("click",()=>{if(this.popover&&this.popover.dataset.threadId===i.id){this.closePopover();return}const a=this.threads.find(c=>c.id===i.id);a&&this.showThreadPopover(a,r)}),this.container.appendChild(r),this.pinEls.set(i.id,r)),r.textContent=`${s+1}`;const l=this.resolvePosition(o);r.style.left=`${l.x}px`,r.style.top=`${l.y}px`})}}var qi=Object.defineProperty,Vi=Object.getOwnPropertyDescriptor,L=(n,e,t,i)=>{for(var s=i>1?void 0:i?Vi(e,t):e,o=n.length-1,r;o>=0;o--)(r=n[o])&&(s=(i?r(e,t,s):r(s))||s);return i&&s&&qi(e,t,s),s};const Xi=["👍","👎","❤️","🎉","👀","🚀"];let I=class extends _{constructor(){super(...arguments),this.highlightThreadId=null,this.threads=[],this.replyingTo=null,this.editingCommentId=null,this.editBody="",this.pickerOpenForComment=null,this.typingByThread=new Map,this.reactionsVersion=0,this.typingTimers=new Map,this.lastTypingSend=new Map}connectedCallback(){super.connectedCallback(),this.ensureListener()}disconnectedCallback(){super.disconnectedCallback(),this.teardownListeners()}willUpdate(n){this.client&&!this.unsub&&this.ensureListener()}updated(n){var e,t;(e=this.shadowRoot)==null||e.querySelectorAll(".audio-player-host").forEach(i=>{if(i.children.length>0)return;const s=i.dataset.url;if(s){const o=i.dataset.duration?parseInt(i.dataset.duration):void 0;i.appendChild(Pe.render(s,o))}}),(t=this.shadowRoot)==null||t.querySelectorAll(".video-player-host").forEach(i=>{if(i.children.length>0)return;const s=i.dataset.url;s&&i.appendChild(xt.render(s,i.dataset.poster||void 0))})}teardownListeners(){var n,e,t;(n=this.unsub)==null||n.call(this),this.unsub=void 0,(e=this.reactionUnsub)==null||e.call(this),this.reactionUnsub=void 0,(t=this.typingUnsub)==null||t.call(this),this.typingUnsub=void 0;for(const i of this.typingTimers.values())clearTimeout(i);this.typingTimers.clear()}ensureListener(){this.client&&(this.teardownListeners(),this.threads=[...this.client.state.threads],this.setupListener())}setupListener(){this.client&&(this.threads=this.client.state.threads,this.unsub=this.client.state.on("threads",n=>{this.threads=[...n]}),this.reactionUnsub=this.client.state.on("reactions",()=>{this.reactionsVersion++}),this.typingUnsub=this.client.state.on("typing",({threadId:n})=>{this.refreshTyping(n)}))}refreshTyping(n){const t=this.client.state.getTypingUsers(n).filter(s=>{var o;return s!==((o=this.client.state.user)==null?void 0:o.id)}).map(s=>{const o=this.client.state.presence.find(r=>r.user.id===s);return(o==null?void 0:o.user.name)??"Someone"}),i=new Map(this.typingByThread);i.set(n,t),this.typingByThread=i,this.typingTimers.has(n)&&clearTimeout(this.typingTimers.get(n)),this.typingTimers.set(n,setTimeout(()=>{this.refreshTyping(n)},3500))}handleTypingInput(n){const e=Date.now(),t=this.lastTypingSend.get(n)??0;e-t>=2e3&&(this.client.sendTyping(n),this.lastTypingSend.set(n,e))}toggleReaction(n,e){var o;const t=this.client.state.getReactions(n),i=(o=this.client.state.user)==null?void 0:o.id,s=t.find(r=>r.emoji===e&&r.userId===i);s?this.client.removeReaction(s.id):this.client.addReaction(n,"comment",e),this.pickerOpenForComment=null}fireClose(){this.dispatchEvent(new CustomEvent("panel-close",{bubbles:!0,composed:!0}))}scrollToThread(n){this.updateComplete.then(()=>{var t;const e=(t=this.shadowRoot)==null?void 0:t.querySelector(`[data-thread-id="${n}"]`);e==null||e.scrollIntoView({behavior:"smooth",block:"center"})})}parseMentions(n){return n.split(/(@\w+)/g).map(t=>t.startsWith("@")?d`<span class="mention">${t}</span>`:t)}getInitials(n){return n.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2)}getUserForComment(n){return this.client.state.getUser(n)}formatTime(n){const e=new Date(n),i=new Date().getTime()-e.getTime(),s=Math.floor(i/6e4);if(s<1)return"now";if(s<60)return`${s}m`;const o=Math.floor(s/60);return o<24?`${o}h`:e.toLocaleDateString()}async handleAttachImage(n){this.upload||(this.upload=new ge(this.client)),await this.upload.pickFile("image/*")&&this.client.reply(n,"(image)")}async handleRecordAudio(n){var i;this.upload||(this.upload=new ge(this.client)),this.audioRecorder||(this.audioRecorder=new _e);const e=(i=this.shadowRoot)==null?void 0:i.querySelector(`[data-thread-id="${n}"]`),t=await this.audioRecorder.startRecording(e??document.body);t&&await this.upload.uploadBlob(t,"audio.webm")&&this.client.reply(n,"(audio note)")}handleReply(n,e){e.preventDefault();const i=e.target.querySelector("input"),s=i.value.trim();if(!s)return;const o=[...s.matchAll(/@(\w+)/g)].map(r=>r[1]);this.client.reply(n,s,o),i.value="",this.replyingTo=null}isOwnComment(n){var e,t;return((t=(e=this.client)==null?void 0:e.state.user)==null?void 0:t.id)===n.userId}startEdit(n){this.editingCommentId=n.id,this.editBody=n.body}cancelEdit(){this.editingCommentId=null,this.editBody=""}saveEdit(n){const e=this.editBody.trim();if(!e)return;const t=[...e.matchAll(/@(\w+)/g)].map(i=>i[1]);this.client.editComment(n,e,t),this.editingCommentId=null,this.editBody=""}deleteComment(n){this.client.deleteComment(n)}renderEditForm(n){return d`
1358
1358
  <div class="edit-form">
1359
1359
  <textarea
1360
1360
  .value=${this.editBody}
@@ -517,7 +517,7 @@ let Le = class {
517
517
  }
518
518
  // ── File Upload ──
519
519
  async uploadFile(e) {
520
- const t = this.config.endpoint ?? window.location.origin, i = new FormData();
520
+ const t = (this.config.endpoint ?? window.location.origin).replace(/^ws(s?):/, "http$1:"), i = new FormData();
521
521
  i.append("file", e);
522
522
  const n = await fetch(`${t}/api/v1/upload`, {
523
523
  method: "POST",
@@ -4216,9 +4216,12 @@ let O = class extends S {
4216
4216
  disconnectedCallback() {
4217
4217
  super.disconnectedCallback(), this.teardownListeners();
4218
4218
  }
4219
+ willUpdate(s) {
4220
+ this.client && !this.unsub && this.ensureListener();
4221
+ }
4219
4222
  updated(s) {
4220
4223
  var e, t;
4221
- s.has("client") && this.client && this.ensureListener(), (e = this.shadowRoot) == null || e.querySelectorAll(".audio-player-host").forEach((i) => {
4224
+ (e = this.shadowRoot) == null || e.querySelectorAll(".audio-player-host").forEach((i) => {
4222
4225
  if (i.children.length > 0) return;
4223
4226
  const n = i.dataset.url;
4224
4227
  if (n) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gamention/pulse-elements",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Drop-in web components for real-time collaboration — comments, cursors, presence, drawing, and more",
5
5
  "type": "module",
6
6
  "main": "./dist/pulse-elements.cjs",
@@ -41,8 +41,8 @@
41
41
  "@lit/context": "^1.1.0",
42
42
  "lit": "^3.2.0",
43
43
  "lucide": "^0.577.0",
44
- "@gamention/pulse-core": "0.1.7",
45
- "@gamention/pulse-shared": "0.1.7"
44
+ "@gamention/pulse-core": "0.1.8",
45
+ "@gamention/pulse-shared": "0.1.8"
46
46
  },
47
47
  "devDependencies": {
48
48
  "typescript": "^5.7.0",