Skip to content

Commit

Permalink
feat(better reconnect): check online status and reconnect when we com…
Browse files Browse the repository at this point in the history
…e back online
  • Loading branch information
rileylnapier committed May 24, 2024
1 parent 00141d1 commit a67a3ef
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 27 deletions.
1 change: 0 additions & 1 deletion packages/components/__tests__/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ test("will support onEvent to listen for events on the window", async (done) =>
components: {
inbox: {
onEvent: (params) => {
console.log("params", params);
expect(params).toEqual({
messageId: mockGraphMessage.messageId,
message: mockGraphMessage,
Expand Down
1 change: 0 additions & 1 deletion packages/components/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,6 @@
inbox: {
appendTo: "#test",
onEvent: (params) => {
console.log("params", params);
if (
params.event === "read" &&
window.courier.inbox.pinned.find(
Expand Down
28 changes: 24 additions & 4 deletions packages/react-hooks/src/inbox/use-inbox-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,11 @@ const useInboxActions = (): IInboxActions => {
}
},
markMessageRead: async (messageId: string, fromWS?: boolean) => {
const message = allMessages.find((m) => m.messageId === messageId);
if (message?.read) {
return;
}

dispatch(markMessageRead(messageId));
if (!fromWS) {
await inboxClient.markRead(messageId);
Expand All @@ -198,12 +203,17 @@ const useInboxActions = (): IInboxActions => {
if (onEvent) {
onEvent({
event: "read",
message: allMessages.find((m) => m.messageId === messageId),
message,
messageId,
});
}
},
markMessageUnread: async (messageId, fromWS) => {
const message = allMessages.find((m) => m.messageId === messageId);
if (!message?.read) {
return;
}

dispatch(markMessageUnread(messageId));
if (!fromWS) {
await inboxClient.markUnread(messageId);
Expand All @@ -212,12 +222,17 @@ const useInboxActions = (): IInboxActions => {
if (onEvent) {
onEvent({
messageId,
message: allMessages.find((m) => m.messageId === messageId),
message,
event: "unread",
});
}
},
markMessageOpened: async (messageId, fromWS) => {
const message = allMessages.find((m) => m.messageId === messageId);
if (message?.opened) {
return;
}

dispatch(markMessageOpened(messageId));
if (!fromWS) {
await inboxClient.markOpened(messageId);
Expand All @@ -226,12 +241,17 @@ const useInboxActions = (): IInboxActions => {
if (onEvent) {
onEvent({
messageId,
message: allMessages.find((m) => m.messageId === messageId),
message,
event: "opened",
});
}
},
markMessageArchived: async (messageId, fromWS) => {
const message = allMessages.find((m) => m.messageId === messageId);
if (message?.archived) {
return;
}

dispatch(markMessageArchived(messageId));
if (!fromWS) {
await inboxClient.markArchive(messageId);
Expand All @@ -240,7 +260,7 @@ const useInboxActions = (): IInboxActions => {
if (onEvent) {
onEvent({
messageId,
message: allMessages.find((m) => m.messageId === messageId),
message,
event: "archive",
});
}
Expand Down
37 changes: 25 additions & 12 deletions packages/react-hooks/src/use-transport.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,30 @@
import { useMemo, useRef } from "react";
import {
CourierTransport,
Transport,
ITransportOptions,
} from "@trycourier/transport";
import { useMemo, useRef, useEffect } from "react";
import { CourierTransport, ITransportOptions } from "@trycourier/transport";
import jwtDecode from "jwt-decode";
interface DecodedAuth {
scope: string;
tenantId: string;
}

const useTransport = ({
tenantId,
authorization,
clientSourceId,
clientKey,
clientSourceId,
isOnline,
tenantId,
transport,
userSignature,
wsOptions,
}: {
tenantId?: string;
authorization?: string;
clientSourceId?: string;
clientKey?: string;
transport?: CourierTransport | Transport;
clientSourceId?: string;
isOnline?: boolean;
tenantId?: string;
transport?: CourierTransport;
userSignature?: string;
wsOptions?: ITransportOptions["wsOptions"];
}): CourierTransport | Transport | undefined => {
}): CourierTransport | undefined => {
const transportRef =
useRef<{
authorization: string;
Expand Down Expand Up @@ -90,6 +88,21 @@ const useTransport = ({
return newTransport;
}, [tenantId, authorization, clientKey, transport, userSignature, wsOptions]);

const isConnected = newTransport?.isConnected();
useEffect(() => {
if (!(newTransport instanceof CourierTransport)) {
return;
}

if (!isOnline && isConnected) {
newTransport.closeConnection();
}

if (isOnline && !isConnected) {
newTransport.connect();
}
}, [newTransport, isConnected, isOnline]);

return newTransport;
};

Expand Down
25 changes: 25 additions & 0 deletions packages/react-provider/src/hooks/use-is-online.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useEffect, useState } from "react";

const useIsOnline = (): boolean | undefined => {
if (typeof window === "undefined" || typeof navigator === "undefined") {
return;
}

const [isOnline, setOnlineStatus] = useState(window.navigator.onLine);

useEffect(() => {
const toggleOnlineStatus = () => setOnlineStatus(window.navigator.onLine);

window.addEventListener("online", toggleOnlineStatus);
window.addEventListener("offline", toggleOnlineStatus);

return () => {
window.removeEventListener("online", toggleOnlineStatus);
window.removeEventListener("offline", toggleOnlineStatus);
};
}, [isOnline]);

return isOnline;
};

export { useIsOnline };
9 changes: 6 additions & 3 deletions packages/react-provider/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import useClientSourceId from "./hooks/use-client-source-id";
import deepExtend from "deep-extend";
import { darkVariables, lightVariables } from "./theme";
import { createGlobalStyle } from "styled-components";
import { useIsOnline } from "./hooks/use-is-online";

export * from "./hooks";

Expand Down Expand Up @@ -117,15 +118,17 @@ const CourierProviderInner: React.FunctionComponent<
createReducer<any, Partial<ICourierContext>>(...middleware),
[middleware]
);
const isOnline = useIsOnline();

const transport =
typeof window === "undefined"
? undefined
: useTransport({
tenantId: tenantId,
authorization,
clientSourceId,
clientKey,
clientSourceId,
isOnline,
tenantId: tenantId,
transport: _transport,
userSignature,
wsOptions,
Expand Down Expand Up @@ -224,7 +227,7 @@ const CourierProviderInner: React.FunctionComponent<
try {
parsedLocalStorageState = JSON.parse(localStorageState);
} catch (ex) {
console.log("error", ex);
console.error(ex);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ const MessagesExample: React.FunctionComponent<{
(messageId: string) => async (event: React.MouseEvent) => {
event.preventDefault();
const result = await inboxApi.getMessage(messageId);
console.log("message", message);
if (!result?.message) {
return;
}
Expand Down
1 change: 0 additions & 1 deletion packages/storybook/stories/inbox/with-toast.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ export function AsyncUserId() {

export function OnMessage() {
const handleOnMessage = (message) => {
console.log(message);
return message;
};

Expand Down
6 changes: 4 additions & 2 deletions packages/transport/src/courier/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ export class CourierTransport extends Transport {
userSignature: options.userSignature,
});

this.ws.connect();

if (options.wsOptions?.onReconnect) {
this.ws.onReconnection({
id: "propReconnect",
Expand All @@ -51,6 +49,10 @@ export class CourierTransport extends Transport {
this.ws.connect();
}

isConnected(): boolean {
return this.ws.connected;
}

keepAlive(): void {
this.ws.send({
action: "keepAlive",
Expand Down
5 changes: 3 additions & 2 deletions packages/transport/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { ErrorEventHandler, WSOptions } from "./types";

const SUBSCRIPTION_VERSION = 5;
export class CourierWS {
connection?: ReconnectingWebSocket;
public connection?: ReconnectingWebSocket;
public connected: boolean;

private subscriptions: Array<{
channel: string;
event?: string;
Expand All @@ -28,7 +30,6 @@ export class CourierWS {
private url: string;
private userSignature?: string;
private connectionCount: number;
protected connected;
protected messageCallback;

constructor({
Expand Down

0 comments on commit a67a3ef

Please sign in to comment.