@knocklabs/client
Advanced tools
Comparing version 0.10.7 to 0.10.8
# Changelog | ||
## 0.10.8 | ||
### Patch Changes | ||
- 29e3942: fix: introduce new useNotificationStore hook to prevent issues that prevent state updates | ||
## 0.10.7 | ||
@@ -4,0 +10,0 @@ |
@@ -1,2 +0,2 @@ | ||
"use strict";var p=Object.defineProperty;var S=(m,e,t)=>e in m?p(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var u=(m,e,t)=>(S(m,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),f=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},y=2e3;class v{constructor(e,t,a){u(this,"userFeedId");u(this,"channel");u(this,"broadcaster");u(this,"defaultOptions");u(this,"broadcastChannel");u(this,"disconnectTimer",null);u(this,"hasSubscribedToRealTimeUpdates",!1);u(this,"visibilityChangeHandler",()=>{});u(this,"visibilityChangeListenerConnected",!1);u(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new k({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...a},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this),this.store.destroy()}listenForUpdates(){this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0;const e=this.knock.client().socket;e&&!e.isConnected()&&e.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unseen")t(i=>i.resetStore({...a,total_count:0,unseen_count:0}));else{t(o=>o.setMetadata({...a,unseen_count:0}));const i={seen_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",n),s}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{getState:e,setState:t}=this.store,{metadata:a,items:n}=e();if(this.defaultOptions.status==="unread")t(i=>i.resetStore({...a,total_count:0,unread_count:0}));else{t(o=>o.setMetadata({...a,unread_count:0}));const i={read_at:new Date().toISOString()},l=n.map(o=>o.id);t(o=>o.setItemAttrs(l,i))}const s=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",n),s}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const{getState:t,setState:a}=this.store,n=t(),r=this.defaultOptions.archived==="exclude",s=Array.isArray(e)?e:[e],i=s.map(l=>l.id);if(r){const l=s.filter(c=>!c.seen_at).length,o=s.filter(c=>!c.read_at).length,d={...n.metadata,total_count:n.metadata.total_count-s.length,unseen_count:n.metadata.unseen_count-l,unread_count:n.metadata.unread_count-o},h=n.items.filter(c=>!i.includes(c.id));a(c=>c.setResult({entries:h,meta:d,page_info:c.pageInfo}))}else n.setItemAttrs(i,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{setState:e,getState:t}=this.store,{items:a}=t(),n=this.defaultOptions.archived==="exclude";e(n?s=>s.resetStore():s=>{const i=a.map(l=>l.id);s.setItemAttrs(i,{archived_at:new Date().toISOString()})});const r=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",a),r}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{setState:t,getState:a}=this.store,{networkStatus:n}=a();if(f.isRequestInFlight(n))return;t(d=>d.setNetworkStatus(e.__loadingType??f.NetworkStatus.loading));const r={...this.defaultOptions,...e,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},s=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:r});if(s.statusCode==="error"||!s.body)return t(d=>d.setNetworkStatus(f.NetworkStatus.error)),{status:s.statusCode,data:s.error||s.body};const i={entries:s.body.entries,meta:s.body.meta,page_info:s.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};t(h=>h.setResult(i,d))}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};t(h=>h.setResult(i,d))}else t(d=>d.setResult(i));this.broadcast("messages.new",i);const l=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:l};return this.broadcast(o.event,o),{data:i,status:s.statusCode}}async fetchNextPage(){const{getState:e}=this.store,{pageInfo:t}=e();t.after&&this.fetch({after:t.after,__loadingType:f.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{getState:t,setState:a}=this.store,{items:n}=t(),r=n[0];a(s=>s.setMetadata(e)),this.fetch({before:r==null?void 0:r.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,a,n){const{getState:r,setState:s}=this.store,i=Array.isArray(e)?e:[e],l=i.map(o=>o.id);if(n){const{metadata:o}=r(),d=i.filter(c=>{switch(t){case"seen":return c.seen_at===null;case"unseen":return c.seen_at!==null;case"read":case"interacted":return c.read_at===null;case"unread":return c.read_at!==null;default:return!0}}),h=t.startsWith("un")?d.length:-d.length;s(c=>c.setMetadata({...o,[n]:Math.max(0,o[n]+h)}))}s(o=>o.setItemAttrs(l,a))}async makeStatusUpdate(e,t){const a=Array.isArray(e)?e:[e],n=a.map(s=>s.id),r=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,a),r}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const a=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:a})}catch(a){console.warn(`Could not broadcast ${e}, got error: ${a}`)}}initializeRealtimeConnection(){const{socket:e}=this.knock.client();e&&(this.channel=e.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",t=>this.onNewMessageReceived(t)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&(e.isConnected()||e.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var a;const e=this.defaultOptions.auto_manage_socket_connection_delay??y,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(a=t.socket)!=null&&a.isConnected()||this.initializeRealtimeConnection())}}exports.default=v; | ||
"use strict";var f=Object.defineProperty;var p=(u,e,t)=>e in u?f(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var r=(u,e,t)=>(p(u,typeof e!="symbol"?e+"":e,t),t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("eventemitter2"),m=require("../../networkStatus.js"),g=require("./store.js"),_={archived:"exclude"},S=2e3;class y{constructor(e,t,s){r(this,"userFeedId");r(this,"channel");r(this,"broadcaster");r(this,"defaultOptions");r(this,"broadcastChannel");r(this,"disconnectTimer",null);r(this,"hasSubscribedToRealTimeUpdates",!1);r(this,"visibilityChangeHandler",()=>{});r(this,"visibilityChangeListenerConnected",!1);r(this,"store");this.knock=e,this.feedId=t,this.feedId=t,this.userFeedId=this.buildUserFeedId(),this.store=g.default(),this.broadcaster=new k({wildcard:!0,delimiter:"."}),this.defaultOptions={..._,...s},this.knock.log(`[Feed] Initialized a feed on channel ${t}`),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}reinitialize(){this.userFeedId=this.buildUserFeedId(),this.initializeRealtimeConnection(),this.setupBroadcastChannel()}teardown(){this.knock.log("[Feed] Tearing down feed instance"),this.channel&&(this.channel.leave(),this.channel.off("new-message")),this.teardownAutoSocketManager(),this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.broadcastChannel&&this.broadcastChannel.close()}dispose(){this.knock.log("[Feed] Disposing of feed instance"),this.teardown(),this.broadcaster.removeAllListeners(),this.knock.feeds.removeInstance(this),this.store.destroy()}listenForUpdates(){this.knock.log("[Feed] Connecting to real-time service"),this.hasSubscribedToRealTimeUpdates=!0;const e=this.knock.client().socket;e&&!e.isConnected()&&e.connect(),this.channel&&["closed","errored"].includes(this.channel.state)&&this.channel.join()}on(e,t){this.broadcaster.on(e,t)}off(e,t){this.broadcaster.off(e,t)}getState(){return this.store.getState()}async markAsSeen(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"seen",{seen_at:t},"unseen_count"),this.makeStatusUpdate(e,"seen")}async markAllAsSeen(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unseen")s.resetStore({...e,total_count:0,unseen_count:0});else{s.setMetadata({...e,unseen_count:0});const i={seen_at:new Date().toISOString()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("seen");return this.emitEvent("all_seen",t),a}async markAsUnseen(e){return this.optimisticallyPerformStatusUpdate(e,"unseen",{seen_at:null},"unseen_count"),this.makeStatusUpdate(e,"unseen")}async markAsRead(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"read",{read_at:t},"unread_count"),this.makeStatusUpdate(e,"read")}async markAllAsRead(){const{metadata:e,items:t,...s}=this.store.getState();if(this.defaultOptions.status==="unread")s.resetStore({...e,total_count:0,unread_count:0});else{s.setMetadata({...e,unread_count:0});const i={read_at:new Date().toISOString()},c=t.map(o=>o.id);s.setItemAttrs(c,i)}const a=await this.makeBulkStatusUpdate("read");return this.emitEvent("all_read",t),a}async markAsUnread(e){return this.optimisticallyPerformStatusUpdate(e,"unread",{read_at:null},"unread_count"),this.makeStatusUpdate(e,"unread")}async markAsInteracted(e){const t=new Date().toISOString();return this.optimisticallyPerformStatusUpdate(e,"interacted",{read_at:t,interacted_at:t},"unread_count"),this.makeStatusUpdate(e,"interacted")}async markAsArchived(e){const t=this.store.getState(),s=this.defaultOptions.archived==="exclude",n=Array.isArray(e)?e:[e],a=n.map(i=>i.id);if(s){const i=n.filter(l=>!l.seen_at).length,c=n.filter(l=>!l.read_at).length,o={...t.metadata,total_count:t.metadata.total_count-n.length,unseen_count:t.metadata.unseen_count-i,unread_count:t.metadata.unread_count-c},d=t.items.filter(l=>!a.includes(l.id));t.setResult({entries:d,meta:o,page_info:t.pageInfo})}else t.setItemAttrs(a,{archived_at:new Date().toISOString()});return this.makeStatusUpdate(e,"archived")}async markAllAsArchived(){const{items:e,...t}=this.store.getState();if(this.defaultOptions.archived==="exclude")t.resetStore();else{const a=e.map(i=>i.id);t.setItemAttrs(a,{archived_at:new Date().toISOString()})}const n=await this.makeBulkStatusUpdate("archive");return this.emitEvent("all_archived",e),n}async markAsUnarchived(e){return this.optimisticallyPerformStatusUpdate(e,"unarchived",{archived_at:null}),this.makeStatusUpdate(e,"unarchived")}async fetch(e={}){const{networkStatus:t,...s}=this.store.getState();if(m.isRequestInFlight(t))return;s.setNetworkStatus(e.__loadingType??m.NetworkStatus.loading);const n={...this.defaultOptions,...e,__loadingType:void 0,__fetchSource:void 0,__experimentalCrossBrowserUpdates:void 0,auto_manage_socket_connection:void 0,auto_manage_socket_connection_delay:void 0},a=await this.knock.client().makeRequest({method:"GET",url:`/v1/users/${this.knock.userId}/feeds/${this.feedId}`,params:n});if(a.statusCode==="error"||!a.body)return s.setNetworkStatus(m.NetworkStatus.error),{status:a.statusCode,data:a.error||a.body};const i={entries:a.body.entries,meta:a.body.meta,page_info:a.body.page_info};if(e.before){const d={shouldSetPage:!1,shouldAppend:!0};s.setResult(i,d)}else if(e.after){const d={shouldSetPage:!0,shouldAppend:!0};s.setResult(i,d)}else s.setResult(i);this.broadcast("messages.new",i);const c=e.__fetchSource==="socket"?"items.received.realtime":"items.received.page",o={items:i.entries,metadata:i.meta,event:c};return this.broadcast(o.event,o),{data:i,status:a.statusCode}}async fetchNextPage(){const{pageInfo:e}=this.store.getState();e.after&&this.fetch({after:e.after,__loadingType:m.NetworkStatus.fetchMore})}broadcast(e,t){this.broadcaster.emit(e,t)}async onNewMessageReceived({metadata:e}){this.knock.log("[Feed] Received new real-time message");const{items:t,...s}=this.store.getState(),n=t[0];s.setMetadata(e),this.fetch({before:n==null?void 0:n.__cursor,__fetchSource:"socket"})}buildUserFeedId(){return`${this.feedId}:${this.knock.userId}`}optimisticallyPerformStatusUpdate(e,t,s,n){const a=this.store.getState(),i=Array.isArray(e)?e:[e],c=i.map(o=>o.id);if(n){const{metadata:o}=a,d=i.filter(h=>{switch(t){case"seen":return h.seen_at===null;case"unseen":return h.seen_at!==null;case"read":case"interacted":return h.read_at===null;case"unread":return h.read_at!==null;default:return!0}}),l=t.startsWith("un")?d.length:-d.length;a.setMetadata({...o,[n]:Math.max(0,o[n]+l)})}a.setItemAttrs(c,s)}async makeStatusUpdate(e,t){const s=Array.isArray(e)?e:[e],n=s.map(i=>i.id),a=await this.knock.messages.batchUpdateStatuses(n,t);return this.emitEvent(t,s),a}async makeBulkStatusUpdate(e){const t={user_ids:[this.knock.userId],engagement_status:this.defaultOptions.status!=="all"?this.defaultOptions.status:void 0,archived:this.defaultOptions.archived,has_tenant:this.defaultOptions.has_tenant,tenants:this.defaultOptions.tenant?[this.defaultOptions.tenant]:void 0};return await this.knock.messages.bulkUpdateAllStatusesInChannel({channelId:this.feedId,status:e,options:t})}setupBroadcastChannel(){this.broadcastChannel=typeof self<"u"&&"BroadcastChannel"in self?new BroadcastChannel(`knock:feed:${this.userFeedId}`):null,this.broadcastChannel&&this.defaultOptions.__experimentalCrossBrowserUpdates===!0&&(this.broadcastChannel.onmessage=e=>{switch(e.data.type){case"items:archived":case"items:unarchived":case"items:seen":case"items:unseen":case"items:read":case"items:unread":case"items:all_read":case"items:all_seen":case"items:all_archived":return this.fetch();default:return null}})}broadcastOverChannel(e,t){if(this.broadcastChannel)try{const s=JSON.parse(JSON.stringify(t));this.broadcastChannel.postMessage({type:e,payload:s})}catch(s){console.warn(`Could not broadcast ${e}, got error: ${s}`)}}initializeRealtimeConnection(){const{socket:e}=this.knock.client();e&&(this.channel=e.channel(`feeds:${this.userFeedId}`,this.defaultOptions),this.channel.on("new-message",t=>this.onNewMessageReceived(t)),this.defaultOptions.auto_manage_socket_connection&&this.setupAutoSocketManager(),this.hasSubscribedToRealTimeUpdates&&(e.isConnected()||e.connect(),this.channel.join()))}setupAutoSocketManager(){typeof document>"u"||this.visibilityChangeListenerConnected||(this.visibilityChangeHandler=this.handleVisibilityChange.bind(this),this.visibilityChangeListenerConnected=!0,document.addEventListener("visibilitychange",this.visibilityChangeHandler))}teardownAutoSocketManager(){typeof document>"u"||(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeListenerConnected=!1)}emitEvent(e,t){this.broadcaster.emit(`items.${e}`,{items:t}),this.broadcaster.emit(`items:${e}`,{items:t}),this.broadcastOverChannel(`items:${e}`,{items:t})}handleVisibilityChange(){var s;const e=this.defaultOptions.auto_manage_socket_connection_delay??S,t=this.knock.client();document.visibilityState==="hidden"?this.disconnectTimer=setTimeout(()=>{var n;(n=t.socket)==null||n.disconnect(),this.disconnectTimer=null},e):document.visibilityState==="visible"&&(this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),(s=t.socket)!=null&&s.isConnected()||this.initializeRealtimeConnection())}}exports.default=y; | ||
//# sourceMappingURL=feed.js.map |
{ | ||
"name": "@knocklabs/client", | ||
"version": "0.10.7", | ||
"version": "0.10.8", | ||
"description": "The clientside library for interacting with Knock", | ||
@@ -5,0 +5,0 @@ "homepage": "https://github.com/knocklabs/javascript/tree/main/packages/client", |
@@ -183,4 +183,3 @@ import EventEmitter from "eventemitter2"; | ||
// items by removing everything from view. | ||
const { getState, setState } = this.store; | ||
const { metadata, items } = getState(); | ||
const { metadata, items, ...state } = this.store.getState(); | ||
@@ -193,12 +192,10 @@ const isViewingOnlyUnseen = this.defaultOptions.status === "unseen"; | ||
if (isViewingOnlyUnseen) { | ||
setState((store) => | ||
store.resetStore({ | ||
...metadata, | ||
total_count: 0, | ||
unseen_count: 0, | ||
}), | ||
); | ||
state.resetStore({ | ||
...metadata, | ||
total_count: 0, | ||
unseen_count: 0, | ||
}); | ||
} else { | ||
// Otherwise we want to update the metadata and mark all of the items in the store as seen | ||
setState((store) => store.setMetadata({ ...metadata, unseen_count: 0 })); | ||
state.setMetadata({ ...metadata, unseen_count: 0 }); | ||
@@ -208,3 +205,3 @@ const attrs = { seen_at: new Date().toISOString() }; | ||
setState((store) => store.setItemAttrs(itemIds, attrs)); | ||
state.setItemAttrs(itemIds, attrs); | ||
} | ||
@@ -254,4 +251,3 @@ | ||
// items by removing everything from view. | ||
const { getState, setState } = this.store; | ||
const { metadata, items } = getState(); | ||
const { metadata, items, ...state } = this.store.getState(); | ||
@@ -264,12 +260,10 @@ const isViewingOnlyUnread = this.defaultOptions.status === "unread"; | ||
if (isViewingOnlyUnread) { | ||
setState((store) => | ||
store.resetStore({ | ||
...metadata, | ||
total_count: 0, | ||
unread_count: 0, | ||
}), | ||
); | ||
state.resetStore({ | ||
...metadata, | ||
total_count: 0, | ||
unread_count: 0, | ||
}); | ||
} else { | ||
// Otherwise we want to update the metadata and mark all of the items in the store as seen | ||
setState((store) => store.setMetadata({ ...metadata, unread_count: 0 })); | ||
state.setMetadata({ ...metadata, unread_count: 0 }); | ||
@@ -279,3 +273,3 @@ const attrs = { read_at: new Date().toISOString() }; | ||
setState((store) => store.setItemAttrs(itemIds, attrs)); | ||
state.setItemAttrs(itemIds, attrs); | ||
} | ||
@@ -325,4 +319,3 @@ | ||
async markAsArchived(itemOrItems: FeedItemOrItems) { | ||
const { getState, setState } = this.store; | ||
const state = getState(); | ||
const state = this.store.getState(); | ||
@@ -384,9 +377,7 @@ const shouldOptimisticallyRemoveItems = | ||
setState((state) => | ||
state.setResult({ | ||
entries: entriesToSet, | ||
meta: updatedMetadata, | ||
page_info: state.pageInfo, | ||
}), | ||
); | ||
state.setResult({ | ||
entries: entriesToSet, | ||
meta: updatedMetadata, | ||
page_info: state.pageInfo, | ||
}); | ||
} else { | ||
@@ -404,4 +395,3 @@ // Mark all the entries being updated as archived either way so the state is correct | ||
// the update has been processed we'll effectively reset the `unseen_count` to be what it was. | ||
const { setState, getState } = this.store; | ||
const { items } = getState(); | ||
const { items, ...state } = this.store.getState(); | ||
@@ -415,9 +405,7 @@ // Here if we're looking at a feed that excludes all of the archived items by default then we | ||
// Reset the store to clear out all of items and reset the badge count | ||
setState((store) => store.resetStore()); | ||
state.resetStore(); | ||
} else { | ||
// Mark all the entries being updated as archived either way so the state is correct | ||
setState((store) => { | ||
const itemIds = items.map((i) => i.id); | ||
store.setItemAttrs(itemIds, { archived_at: new Date().toISOString() }); | ||
}); | ||
const itemIds = items.map((i) => i.id); | ||
state.setItemAttrs(itemIds, { archived_at: new Date().toISOString() }); | ||
} | ||
@@ -442,4 +430,3 @@ | ||
async fetch(options: FetchFeedOptions = {}) { | ||
const { setState, getState } = this.store; | ||
const { networkStatus } = getState(); | ||
const { networkStatus, ...state } = this.store.getState(); | ||
@@ -452,5 +439,3 @@ // If there's an existing request in flight, then do nothing | ||
// Set the loading type based on the request type it is | ||
setState((store) => | ||
store.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading), | ||
); | ||
state.setNetworkStatus(options.__loadingType ?? NetworkStatus.loading); | ||
@@ -476,3 +461,3 @@ // Always include the default params, if they have been set | ||
if (result.statusCode === "error" || !result.body) { | ||
setState((store) => store.setNetworkStatus(NetworkStatus.error)); | ||
state.setNetworkStatus(NetworkStatus.error); | ||
@@ -493,8 +478,8 @@ return { | ||
const opts = { shouldSetPage: false, shouldAppend: true }; | ||
setState((state) => state.setResult(response, opts)); | ||
state.setResult(response, opts); | ||
} else if (options.after) { | ||
const opts = { shouldSetPage: true, shouldAppend: true }; | ||
setState((state) => state.setResult(response, opts)); | ||
state.setResult(response, opts); | ||
} else { | ||
setState((state) => state.setResult(response)); | ||
state.setResult(response); | ||
} | ||
@@ -524,4 +509,3 @@ | ||
// Attempts to fetch the next page of results (if we have any) | ||
const { getState } = this.store; | ||
const { pageInfo } = getState(); | ||
const { pageInfo } = this.store.getState(); | ||
@@ -553,7 +537,6 @@ if (!pageInfo.after) { | ||
// Handle the new message coming in | ||
const { getState, setState } = this.store; | ||
const { items } = getState(); | ||
const { items, ...state } = this.store.getState(); | ||
const currentHead: FeedItem | undefined = items[0]; | ||
// Optimistically set the badge counts | ||
setState((state) => state.setMetadata(metadata)); | ||
state.setMetadata(metadata); | ||
// Fetch the items before the current head (if it exists) | ||
@@ -573,3 +556,3 @@ this.fetch({ before: currentHead?.__cursor, __fetchSource: "socket" }); | ||
) { | ||
const { getState, setState } = this.store; | ||
const state = this.store.getState(); | ||
const normalizedItems = Array.isArray(itemOrItems) | ||
@@ -581,3 +564,3 @@ ? itemOrItems | ||
if (badgeCountAttr) { | ||
const { metadata } = getState(); | ||
const { metadata } = state; | ||
@@ -608,12 +591,10 @@ // We only want to update the counts of items that have not already been counted towards the | ||
setState((store) => | ||
store.setMetadata({ | ||
...metadata, | ||
[badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction), | ||
}), | ||
); | ||
state.setMetadata({ | ||
...metadata, | ||
[badgeCountAttr]: Math.max(0, metadata[badgeCountAttr] + direction), | ||
}); | ||
} | ||
// Update the items with the given attributes | ||
setState((store) => store.setItemAttrs(itemIds, attrs)); | ||
state.setItemAttrs(itemIds, attrs); | ||
} | ||
@@ -620,0 +601,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
329414
3510