@connectycube/use-chat
Version:
A React hook for state management in ConnectyCube-powered chat solutions
3 lines (2 loc) • 26.9 kB
JavaScript
;var t,e,a=require("react/jsx-runtime"),n=require("react"),s=require("connectycube"),r=require("connectycube/types");function i(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var o=i(function(){if(e)return t;e=1;var a=n;return t=function(t){var e=a.useState(t),n=e[0],s=e[1],r=a.useRef(n);return[n,a.useCallback(function(t){r.current=function(t){return"function"==typeof t}(t)?t(r.current):t,s(r.current)},[]),r]}}());const c=43200,u=Symbol.for("constructDateFrom");function d(t,e){return"function"==typeof t?t(e):t&&"object"==typeof t&&u in t?t[u](e):t instanceof Date?new t.constructor(e):new Date(e)}function l(t,e){return d(t,t)}let h={};function m(){return h}function f(t){const e=l(t),a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+t-+a}function g(t,...e){const a=d.bind(null,t||e.find(t=>"object"==typeof t));return e.map(a)}function p(t,e){const a=+l(t)-+l(e);return a<0?-1:a>0?1:a}function y(t,e){const a=l(t);return+function(t){const e=l(t);return e.setHours(23,59,59,999),e}(a)===+function(t){const e=l(t),a=e.getMonth();return e.setFullYear(e.getFullYear(),a+1,0),e.setHours(23,59,59,999),e}(a)}function _(t,e,a){const[n,s,r]=g(a?.in,t,t,e),i=p(s,r),o=Math.abs(function(t,e,a){const[n,s]=g(a?.in,t,e);return 12*(n.getFullYear()-s.getFullYear())+(n.getMonth()-s.getMonth())}(s,r));if(o<1)return 0;1===s.getMonth()&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*o);let c=p(s,r)===-i;y(n)&&1===o&&1===p(n,r)&&(c=!1);const u=i*(o-+c);return 0===u?0:u}function S(t,e,a){const n=function(t,e){return+l(t)-+l(e)}(t,e)/1e3;return(s=a?.roundingMethod,t=>{const e=(s?Math[s]:Math.trunc)(t);return 0===e?0:e})(n);var s}const v={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function w(t){return(e={})=>{const a=e.width?String(e.width):t.defaultWidth;return t.formats[a]||t.formats[t.defaultWidth]}}const E={date:w({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:w({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:w({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},D={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function C(t){return(e,a)=>{let n;if("formatting"===(a?.context?String(a.context):"standalone")&&t.formattingValues){const e=t.defaultFormattingWidth||t.defaultWidth,s=a?.width?String(a.width):e;n=t.formattingValues[s]||t.formattingValues[e]}else{const e=t.defaultWidth,s=a?.width?String(a.width):t.defaultWidth;n=t.values[s]||t.values[e]}return n[t.argumentCallback?t.argumentCallback(e):e]}}function T(t){return(e,a={})=>{const n=a.width,s=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],r=e.match(s);if(!r)return null;const i=r[0],o=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],c=Array.isArray(o)?function(t,e){for(let a=0;a<t.length;a++)if(e(t[a]))return a;return}(o,t=>t.test(i)):function(t,e){for(const a in t)if(Object.prototype.hasOwnProperty.call(t,a)&&e(t[a]))return a;return}(o,t=>t.test(i));let u;u=t.valueCallback?t.valueCallback(c):c,u=a.valueCallback?a.valueCallback(u):u;return{value:u,rest:e.slice(i.length)}}}var M;const A={code:"en-US",formatDistance:(t,e,a)=>{let n;const s=v[t];return n="string"==typeof s?s:1===e?s.one:s.other.replace("{{count}}",e.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+n:n+" ago":n},formatLong:E,formatRelative:(t,e,a,n)=>D[t],localize:{ordinalNumber:(t,e)=>{const a=Number(t),n=a%100;if(n>20||n<10)switch(n%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:C({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:C({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:t=>t-1}),month:C({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:C({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:C({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:(M={matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:t=>parseInt(t,10)},(t,e={})=>{const a=t.match(M.matchPattern);if(!a)return null;const n=a[0],s=t.match(M.parsePattern);if(!s)return null;let r=M.valueCallback?M.valueCallback(s[0]):s[0];return r=e.valueCallback?e.valueCallback(r):r,{value:r,rest:t.slice(n.length)}}),era:T({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:T({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:t=>t+1}),month:T({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:T({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:T({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},options:{weekStartsOn:0,firstWeekContainsDate:1}};function b(t,e){return function(t,e,a){const n=m(),s=a?.locale??n.locale??A,r=p(t,e);if(isNaN(r))throw new RangeError("Invalid time value");const i=Object.assign({},a,{addSuffix:a?.addSuffix,comparison:r}),[o,u]=g(a?.in,...r>0?[e,t]:[t,e]),d=S(u,o),l=(f(u)-f(o))/1e3,h=Math.round((d-l)/60);let y;if(h<2)return a?.includeSeconds?d<5?s.formatDistance("lessThanXSeconds",5,i):d<10?s.formatDistance("lessThanXSeconds",10,i):d<20?s.formatDistance("lessThanXSeconds",20,i):d<40?s.formatDistance("halfAMinute",0,i):d<60?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",1,i):0===h?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",h,i);if(h<45)return s.formatDistance("xMinutes",h,i);if(h<90)return s.formatDistance("aboutXHours",1,i);if(h<1440){const t=Math.round(h/60);return s.formatDistance("aboutXHours",t,i)}if(h<2520)return s.formatDistance("xDays",1,i);if(h<c){const t=Math.round(h/1440);return s.formatDistance("xDays",t,i)}if(h<86400)return y=Math.round(h/c),s.formatDistance("aboutXMonths",y,i);if(y=_(u,o),y<12){const t=Math.round(h/c);return s.formatDistance("xMonths",t,i)}{const t=y%12,e=Math.trunc(y/12);return t<3?s.formatDistance("aboutXYears",e,i):t<9?s.formatDistance("overXYears",e,i):s.formatDistance("almostXYears",e+1,i)}}(t,function(t){return d(t,Date.now())}(t),e)}var O,N,x;!function(t){t.ADDED_TO_DIALOG="dialog/ADDED_TO_DIALOG",t.REMOVED_FROM_DIALOG="dialog/REMOVED_FROM_DIALOG",t.ADD_PARTICIPANTS="dialog/ADD_PARTICIPANTS",t.REMOVE_PARTICIPANTS="dialog/REMOVE_PARTICIPANTS",t.NEW_DIALOG="dialog/NEW_DIALOG"}(O||(O={})),exports.MessageStatus=void 0,(N=exports.MessageStatus||(exports.MessageStatus={})).WAIT="wait",N.LOST="lost",N.SENT="sent",N.READ="read",exports.ChatStatus=void 0,(x=exports.ChatStatus||(exports.ChatStatus={})).DISCONNECTED="disconnected",x.CONNECTING="connecting",x.CONNECTED="connected",x.NOT_AUTHORIZED="not-authorized",x.ERROR="error";const I="[useChat][useBlockList]",R="ConnectyCubeBlockList";function P(t){const[e,a]=n.useState(new Set),i=n.useRef(!1),o=t=>e.has(t),c=async(n,o)=>{if(!t)return void console.warn(`${I}[upsert]: ${o} user ${n} failed, chat is not connected`);const c=new Set(e),u={name:R,items:[{user_id:n,action:o,mutualBlock:!0}]};try{o===r.PrivacyListAction.DENY?c.add(n):o===r.PrivacyListAction.ALLOW&&c.delete(n),i.current?(await s.chat.privacylist.setAsDefault(null),await s.chat.privacylist.update(u),c.size>0&&await s.chat.privacylist.setAsDefault(R)):(await s.chat.privacylist.create(u),await s.chat.privacylist.setAsDefault(R))}catch(t){return}finally{a(c)}};return n.useEffect(()=>{t&&(async()=>{if(!t)return void console.warn(`${I}[fetch]: chat is not connected`);if((await s.chat.privacylist.getNames()).default===R){const t=(await s.chat.privacylist.getList(R)).items.reduce((t,e)=>(e.action===r.PrivacyListAction.DENY&&t.add(+e.user_id),t),new Set);i.current=!0,a(t)}})()},[t]),{blockedUsers:Array.from(e),isBlockedUser:o,unblockUser:async t=>{o(t)?await c(t,r.PrivacyListAction.ALLOW):console.warn(`${I}[unblock]: user ${t} is not blocked`)},blockUser:async t=>{o(t)?console.warn(`${I}[block]: user ${t} is already blocked`):await c(t,r.PrivacyListAction.DENY)}}}function L(t){const e=n.useRef(void 0),[a,r]=n.useState(navigator.onLine),i=()=>{e.current&&(clearInterval(e.current),e.current=void 0)};return n.useEffect(()=>{t?(i(),e.current=setInterval(async()=>{try{await s.chat.pingWithTimeout(1e3),r(!0)}catch(t){r(!1),setTimeout(async()=>{try{await s.chat.pingWithTimeout(1e3),r(!0)}catch(t){r(!1)}},5e3)}},4e4)):i()},[t]),n.useEffect(()=>{const t=()=>r(!0),e=()=>r(!1);return window.addEventListener("online",t),window.addEventListener("offline",e),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",e)}},[]),{isOnline:a}}const W=t=>{let e;if("string"==typeof t){const a=new Date(t).getTime();e=isNaN(a)?void 0:a}else"number"==typeof t&&(e=1e3*t);return e},k=t=>{let e;if(t<=30)e="Online";else if(t<3600)e=`Last seen ${Math.ceil(t/60)} minutes ago`;else if(t<86400)e=`Last seen ${Math.ceil(t/3600)} hours ago`;else{const a=new Date(Date.now()-1e3*t);e=`Last seen ${a.getUTCDate()}/${(a.getMonth()+1).toString().padStart(2,"0")}/${a.getFullYear()}`}return e},U=t=>W(t.last_message_date_sent)||W(t.updated_at)||W(t.created_at)||0,G="[useChat][useUsers]",j=100;function F(t){const[e,a]=n.useState({}),[i,o]=n.useState({}),[c,u]=n.useState(0),[d,l]=n.useState({}),h=n.useRef(0),m=n.useRef({}),f=async t=>{const{items:e}=await s.users.getV2(t);return a(t=>e.reduce((t,e)=>({...t,[e.id]:e}),{...t})),o(t=>e.reduce((t,e)=>t[e.id]?{...t,[e.id]:e}:t,{...t})),e.forEach(t=>{m.current[t.id]=Date.now()}),e},g=n.useCallback(async e=>{const{items:a}=await s.users.getV2({full_name:{start_with:e},limit:j}),{items:n}=await s.users.getV2({login:{start_with:e},limit:j}),r=new Map;return[...a,...n].forEach(t=>{r.set(t.id,t)}),Array.from(r.values()).filter(e=>e.id!==t)},[t]),p=async()=>{let t=c;try{const{count:e}=await s.users.getOnlineCount();t=e,u(t)}catch(t){console.error(`${G}[getOnlineCount][Error]:`,t)}return t};return n.useEffect(()=>(s.chat.addListener(r.ChatEvent.USER_LAST_ACTIVITY,(t,e)=>{if("number"==typeof t&&e>=0){const a=k(e);l(e=>({...e,[t]:a}))}}),()=>{s.chat.removeListener(r.ChatEvent.USER_LAST_ACTIVITY)}),[]),{_retrieveAndStoreUsers:async t=>{const a=t.filter(t=>!e[t]);a.length>0&&await f({limit:j,id:{in:a}})},exports:{users:e,getAndStoreUsers:f,searchUsers:g,fetchUserById:async(t,n=!1)=>{const r=m.current[t]||0,i=Date.now()-r>3e4;let c=e[t];if(i||n){const e=await s.users.getV2({id:t,limit:1}),n=e?.items?.[0];n&&(a(e=>({...e,[t]:n})),o(e=>e[t]?{...e,[t]:n}:e),m.current[t]=Date.now(),c=n)}return c},listOnlineUsers:async(t=!1)=>{const e=h.current,n=Date.now();let r=i;return(n-e>6e4||t)&&(r=await(async()=>{const t=await p(),e=[];let n={};try{let r=j,i=0;for(;i<t;)e.push(s.users.listOnline({limit:r,offset:i}).then(({users:t})=>t)),i+=r;const c=(await Promise.all(e)).flat();n=c.reduce((t,e)=>(t[e.id]=e,t),{}),a(t=>({...t,...n})),o(n)}catch(t){console.error(`${G}[listOnline][Error]:`,t)}return n})(),h.current=Date.now()),Object.values(r)},listOnlineUsersWithParams:async t=>{let e={};try{const{users:n}=await s.users.listOnline(t);e=n.reduce((t,e)=>(t[e.id]=e,t),{}),a(t=>({...t,...e})),o(e)}catch(t){console.error(`${G}[listOnlineWithParams][Error]:`,t)}return Object.values(e)},onlineUsers:Object.values(i),getOnlineUsersCount:p,onlineUsersCount:c,lastActivity:d,getLastActivity:async t=>{let e="Last seen recently";try{const{seconds:a}=await s.chat.getLastUserActivity(t);e=k(a)}catch(t){console.error(`${G}[getLastActivity][Error]:`,t)}finally{return l(a=>({...a,[t]:e})),e}},subscribeToUserLastActivityStatus:t=>{s.chat.subscribeToUserLastActivityStatus(t)},unsubscribeFromUserLastActivityStatus:t=>{s.chat.unsubscribeFromUserLastActivityStatus(t)}}}}const V=n.createContext(void 0);V.displayName="ChatContext";exports.ChatProvider=({children:t})=>{const[e,i]=n.useState(!1),[c,u]=n.useState({total:0}),[d,l]=n.useState({}),[h,m]=n.useState({}),[f,g]=n.useState(!1),[p,y,_]=o({}),[S,v,w]=o([]),[E,D,C]=o(),[T,M,A]=o(),[N,x,I]=o(exports.ChatStatus.DISCONNECTED),R=n.useRef({}),k=n.useRef(null),G=n.useRef(null),j=n.useRef(null),Y=n.useRef(null),$=n.useRef({}),X=n.useRef({}),H=P(e),q=F(E),{isOnline:z}=L(e),{_retrieveAndStoreUsers:J}=q,B=async(t=exports.ChatStatus.DISCONNECTED)=>{let e=!1;return s.chat.isConnected&&(e=await s.chat.disconnect(),i(!1),D(void 0),x(t),Z()),e},Q=(t=exports.ChatStatus.DISCONNECTED)=>{s.chat.terminate(),x(t),Z(),ot()},Z=()=>{$.current={},g(!1),m({})},K=async t=>{const e={sort_desc:"date_sent",limit:100,skip:0,...t},{items:a,skip:n,limit:r,total_entries:i}=await s.chat.dialog.list(e);g(n+r>=i),v(t=>{const e=[...t,...a];return Array.from(new Map(e.map(t=>[t._id,t])).values()).sort((t,e)=>U(e)-U(t))});const o=a.flatMap(t=>t.occupants_ids),c=Array.from(new Set(o));return J(c),a},tt=async(t,e={})=>{const a={chat_dialog_id:t,sort_desc:"date_sent",limit:100,skip:0,...e};try{const{items:e,skip:n,limit:r}=await s.chat.message.list(a),i=_.current[t]??[],o=n+r>e.length+i.length;return m(e=>({...e,[t]:o})),e.sort((t,e)=>t._id.toString().localeCompare(e._id.toString())).map(t=>{const e=t.attachments?.map(t=>({...t,url:s.storage.privateUrl(t.uid)}));return{...t,attachments:e,status:t.read?exports.MessageStatus.READ:exports.MessageStatus.SENT}})}catch(t){if(404===t.code)return[];throw t}},et=async t=>{try{const e=await tt(t);return y(a=>({...a,[t]:e})),e}catch(t){throw t}},at=t=>{if(t??=T,!t)throw"No dialog provided. You need to provide a dialog via function argument or select a dialog via 'selectDialog'.";if(t.type!==r.DialogType.PRIVATE)return;const e=t.occupants_ids.find(t=>t!==E);return e&&(X.current[e]=t._id),e},nt=async t=>{const e={read:1,chat_dialog_id:t._id};await s.chat.message.update("",e),v(e=>e.map(e=>e._id===t._id?{...e,unread_messages_count:0}:e))},st=(t,e,a,n)=>{const i={type:a.type===r.DialogType.PRIVATE?r.ChatType.CHAT:r.ChatType.GROUPCHAT,body:t,extension:{save_to_history:1,dialog_id:a._id}};e&&(i.extension.attachments=e);return s.chat.send(a.type===r.DialogType.PRIVATE?n:a._id,i)},rt=(t,e,a,n,s,r,i)=>{const o=Math.round((new Date).getTime()/1e3);v(t=>t.map(t=>t._id===a?{...t,last_message:e,last_message_user_id:n,last_message_date_sent:o}:t).sort((t,e)=>{const a=W(t.last_message_date_sent)||W(t.created_at);return(W(e.last_message_date_sent)||W(e.created_at))-a})),y(c=>({...c,[a]:[...c[a]||[],{_id:t,created_at:o,updated_at:o,chat_dialog_id:a,message:e,sender_id:n,recipient_id:s,date_sent:o,read:0,read_ids:[n],delivered_ids:[n],views_count:0,attachments:r||[],reactions:{},isLoading:i,status:I.current===exports.ChatStatus.CONNECTED?exports.MessageStatus.WAIT:exports.MessageStatus.LOST}]}))},it=(t,e,a,n)=>{y(s=>({...s,[a]:s[a]?.map(a=>a._id===e?{...a,read_ids:n?a.read_ids?[...new Set([...a.read_ids,n])]:[n]:a.read_ids,read:t===exports.MessageStatus.READ?1:a.read,status:t===exports.MessageStatus.SENT&&a.status===exports.MessageStatus.LOST?a.status:t}:a)??[]}))},ot=()=>{y(t=>Object.fromEntries(Object.entries(t).map(([t,e])=>[t,e.map(t=>t.status===exports.MessageStatus.WAIT?{...t,status:exports.MessageStatus.LOST}:t)])))},ct=(t,e,a,n={})=>{const r={body:t,extension:{dialogId:e,...n}};s.chat.sendSystemMessage(a,r)},ut=(t,e,a)=>{l(n=>{const s=n[t],r=s?new Set(s):new Set;return a?r.add(e):r.delete(e),{...n,[t]:[...r]}})},dt=(t,e)=>{ut(t,e,!1),clearTimeout(R.current[t]?.[e]),delete R.current[t]?.[e]},lt=()=>{I.current!==exports.ChatStatus.CONNECTING&&(x(exports.ChatStatus.DISCONNECTED),Z()),ot()},ht=()=>{x(exports.ChatStatus.CONNECTED)},mt=async(t={})=>{if("not-authorized"===t?.condition||"Password not verified"===t?.text||"SASLError"===t?.name){await B(exports.ChatStatus.NOT_AUTHORIZED)||Q(exports.ChatStatus.NOT_AUTHORIZED)}else x(exports.ChatStatus.ERROR)},ft=(t,e)=>{if(k.current&&k.current(t,e),t===C.current||e.delay&&e.type===r.ChatType.CHAT)return;const a=A.current,n=e.dialog_id,i=e.id,o=e.body||"",c=e.type===r.ChatType.CHAT?C.current:void 0,u=e.extension.attachments?.length>0?e.extension.attachments.map(t=>({...t,url:s.storage.privateUrl(t.uid)})):void 0;rt(i,o,n,t,c,u),dt(n,t),v(t=>t.map(t=>t._id===n?{...t,unread_messages_count:a&&a._id===e.dialog_id?t.unread_messages_count:(t.unread_messages_count||0)+1,last_message:e.body,last_message_date_sent:parseInt(e.extension.date_sent)}:t))},gt=(t,e)=>{Y.current&&Y.current(t,e)},pt=(t,e)=>{j.current&&j.current(t,e);const a=e?exports.MessageStatus.SENT:t?exports.MessageStatus.LOST:void 0,n=e?e.id:t?t.id:void 0,s=e?e.extension.dialog_id:t?t.extension.dialog_id:void 0;a&&n&&s&&it(a,n,s)},yt=async t=>{const e=t.extension.dialogId,a=t.userId;if(G.current&&G.current(t),a!==C.current)switch(t.body){case O.NEW_DIALOG:case O.ADDED_TO_DIALOG:{const t=(await s.chat.dialog.list({_id:e})).items[0];J(t.occupants_ids),v(e=>[t,...e.filter(e=>e._id!==t._id)]);break}case O.ADD_PARTICIPANTS:{const a=t.extension.addedParticipantsIds.split(",").map(Number);J(a),v(t=>t.map(t=>(t._id===e&&(t.occupants_ids=Array.from(new Set([...t.occupants_ids,...a]))),t)));break}case O.REMOVE_PARTICIPANTS:{const a=t.extension.removedParticipantsIds.split(",").map(Number);v(t=>t.map(t=>(t._id===e&&(t.occupants_ids=t.occupants_ids.filter(t=>!a.includes(t))),t)));break}case O.REMOVED_FROM_DIALOG:v(t=>t.map(t=>(t._id===e&&t.type!==r.DialogType.PRIVATE&&(t.occupants_ids=t.occupants_ids.filter(t=>t!==a)),t)))}},_t=(t,e,a)=>{a!==C.current&&it(exports.MessageStatus.READ,t,e,a)},St=(t,e,a)=>{const n=a||(t=>{let e=X.current[t];if(!e){const a=w.current.find(e=>e.type===r.DialogType.PRIVATE&&at(e)===t);a&&(e=a._id,X.current[t]=e)}return e})(e);n&&e&&e!==C.current&&(ut(n,e,t),R.current[n]||(R.current[n]={}),t?(R.current[n][e]&&(clearTimeout(R.current[n][e]),delete R.current[n][e]),R.current[n][e]=setTimeout(()=>{dt(n,e)},6e3)):dt(n,e))};return n.useEffect(()=>(s.chat.addListener(r.ChatEvent.DISCONNECTED,lt),s.chat.addListener(r.ChatEvent.RECONNECTED,ht),s.chat.addListener(r.ChatEvent.ERROR,mt),s.chat.addListener(r.ChatEvent.MESSAGE,ft),s.chat.addListener(r.ChatEvent.ERROR_MESSAGE,gt),s.chat.addListener(r.ChatEvent.SENT_MESSAGE,pt),s.chat.addListener(r.ChatEvent.SYSTEM_MESSAGE,yt),s.chat.addListener(r.ChatEvent.READ_MESSAGE,_t),s.chat.addListener(r.ChatEvent.TYPING_MESSAGE,St),()=>{s.chat.removeAllListeners()}),[]),n.useEffect(()=>{(()=>{const t={total:0};S.forEach(({_id:e,unread_messages_count:a=0})=>{e!==T?._id&&(t[e]=a,t.total+=a)}),u(t)})()},[S]),n.useEffect(()=>{(async t=>{if(t&&I.current!==exports.ChatStatus.ERROR)I.current!==exports.ChatStatus.DISCONNECTED&&I.current!==exports.ChatStatus.NOT_AUTHORIZED||x(exports.ChatStatus.CONNECTING);else try{await s.chat.pingWithTimeout(1e3),x(exports.ChatStatus.CONNECTED)}catch(t){Q()}})(z)},[z]),a.jsx(V.Provider,{value:{isOnline:z,isConnected:e,chatStatus:N,connect:async t=>{x(exports.ChatStatus.CONNECTING);try{const e=await s.chat.connect(t);return e&&(x(exports.ChatStatus.CONNECTED),i(e),D(t.userId)),e}catch(t){return x(exports.ChatStatus.DISCONNECTED),console.error(`Failed to connect due to ${t}`),!1}},disconnect:B,terminate:Q,currentUserId:E,selectDialog:async t=>{M(t),t&&($.current[t._id]||(await et(t._id),$.current[t._id]=!0),t.unread_messages_count>0&&await nt(t).catch(t=>{}))},selectedDialog:T,getDialogOpponentId:at,unreadMessagesCount:c,getMessages:et,getNextMessages:async t=>{const e=_.current[t]??[],a=e.length;try{const n=[...await tt(t,{skip:a}),...e];return y(e=>({...e,[t]:n})),n}catch(t){throw t}},totalMessagesReached:h,messages:p,sendSignal:(t,e,a={})=>{const n=Array.isArray(t)?t:[t],r={body:e,extension:a};n.forEach(t=>{s.chat.sendSystemMessage(t,r)})},sendMessage:(t,e)=>{if(e??=T,!e)throw"No dialog provided. You need to provide a dialog via function argument or select a dialog via 'selectDialog'.";const a=at(e),n=st(t,null,e,a);rt(n,t,e._id,E,a)},dialogs:S,getDialogs:K,getNextDialogs:async()=>{const t=w.current.length;return K({skip:t})},totalDialogReached:f,createChat:async(t,e)=>{const a={type:r.DialogType.PRIVATE,occupants_ids:[t],extensions:e},n=await s.chat.dialog.create(a);return v(t=>[n,...t.filter(t=>t._id!==n._id)]),m(t=>({...t,[n._id]:!0})),X.current[t]=n._id,ct(O.NEW_DIALOG,n._id,t),J([t,E]),n},createGroupChat:async(t,e,a,n)=>{const i={name:e,photo:a,type:r.DialogType.GROUP,occupants_ids:t,extensions:n},o=await s.chat.dialog.create(i);return v(t=>[o,...t.filter(t=>t._id!==o._id)]),m(t=>({...t,[o._id]:!0})),t.forEach(t=>{ct(O.NEW_DIALOG,o._id,t)}),J([...t,E]),o},sendTypingStatus:t=>{if(t??=T,!t)throw"No dialog provided. You need to provide a dialog via function argument or select a dialog via 'selectDialog'.";s.chat.sendIsTypingStatus(t.type===r.DialogType.PRIVATE?at(t):t._id)},typingStatus:d,sendMessageWithAttachment:async(t,e)=>{if(e??=T,!e)throw"No dialog provided. You need to provide a dialog via function argument or select a dialog via 'selectDialog'.";const a=at(e),n=Date.now()+"",r=t.map((t,e)=>({uid:`local-${n}-${e}`,type:t.type,url:URL.createObjectURL(t)}));rt(n,"Attachment",e._id,E,a,r,!0);const i=t.map(t=>{const{name:e,type:a,size:n}=t,r={file:t,name:e,type:a,size:n,public:!1};return s.storage.createAndUpload(r)}),o=(await Promise.all(i)).map(({uid:t,content_type:e=""})=>({uid:t,type:e,url:s.storage.privateUrl(t)})),c=st("Attachment",o,e,a);y(t=>({...t,[e._id]:t[e._id].map(t=>t._id===n?{...t,_id:c,attachments:r,isLoading:!1,status:I.current===exports.ChatStatus.CONNECTED?exports.MessageStatus.WAIT:exports.MessageStatus.LOST}:t)}))},markDialogAsRead:nt,removeUsersFromGroupChat:async t=>{if(!T)throw new Error("No dialog selected");const e=T._id,a={pull_all:{occupants_ids:t}};await s.chat.dialog.update(e,a),t.forEach(t=>{ct(O.REMOVED_FROM_DIALOG,e,t)}),T.occupants_ids.filter(e=>!t.includes(e)&&e!==E).forEach(a=>{ct(O.REMOVE_PARTICIPANTS,e,a,{removedParticipantsIds:t.join()})});const n={...T,occupants_ids:T.occupants_ids.filter(e=>!t.includes(e))};v(t=>t.map(t=>t._id===e?n:t)),M(n)},addUsersToGroupChat:async t=>{if(!T)throw new Error("No dialog selected");const e=T._id,a={push_all:{occupants_ids:t}};await s.chat.dialog.update(e,a),T.occupants_ids.filter(t=>t!==E).forEach(a=>{ct(O.ADD_PARTICIPANTS,e,a,{addedParticipantsIds:t.join()})}),t.forEach(t=>{ct(O.ADDED_TO_DIALOG,e,t)}),J(t);const n={...T,occupants_ids:Array.from(new Set([...T.occupants_ids,...t]))};v(t=>t.map(t=>t._id===e?n:t)),M(n)},leaveGroupChat:async()=>{if(!T)throw new Error("No dialog selected");await s.chat.dialog.delete(T._id),T.occupants_ids.filter(t=>t!==E).forEach(t=>{ct(O.REMOVED_FROM_DIALOG,T._id,t)}),v(S.filter(t=>t._id!==T._id)),M(void 0)},readMessage:(t,e,a)=>{s.chat.sendReadStatus({messageId:t,userId:e,dialogId:a}),it(exports.MessageStatus.READ,t,a,e),v(t=>t.map(t=>t._id===a?{...t,unread_messages_count:Math.max(0,t.unread_messages_count-1)}:t))},lastMessageSentTimeString:t=>b(t.last_message_date_sent?1e3*t.last_message_date_sent:t.created_at,{addSuffix:!0}),messageSentTimeString:t=>b(1e3*t.date_sent,{addSuffix:!0}),processOnSignal:t=>{G.current=t},processOnMessage:t=>{k.current=t},processOnMessageError:t=>{Y.current=t},processOnMessageSent:t=>{j.current=t},...H,...q.exports},children:t})},exports.useChat=()=>{const t=n.useContext(V);if(!t)throw new Error("useChat must be within ChatProvider");return t};
//# sourceMappingURL=index.cjs.map