Skip to content

Commit

Permalink
Add Brand ID To Provider Config (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sterling (Jay) Scott authored Apr 13, 2021
1 parent 2f81759 commit 4763a14
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 76 deletions.
2 changes: 1 addition & 1 deletion packages/react-inbox/__tests__/Inbox.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function renderInboxComponent(props?: Partial<InboxProps>) {
};

return render(
<CourierProvider>
<CourierProvider clientKey="1232132123" userId="12312312">
<Inbox {...defaultProps} {...props} />
</CourierProvider>
);
Expand Down
21 changes: 8 additions & 13 deletions packages/react-inbox/src/components/Inbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ const Inbox: React.FunctionComponent<InboxProps> = (props) => {
const { clientKey, userId, brand } = courierContext;
useMessageCount();
const inbox = useInbox();
const { init: initInbox } = inbox;

const tippyProps: TippyProps = {
trigger: props.trigger ?? "click",
placement: props.placement ?? "right",
Expand All @@ -95,29 +93,26 @@ const Inbox: React.FunctionComponent<InboxProps> = (props) => {

if (localStorageState) {
try {
initInbox({
...JSON.parse(localStorageState),
config: props,
});
return;
const { messages, unreadMessageCount } = JSON.parse(
localStorageState
);
inbox.init({ messages, unreadMessageCount, config: props });
} catch (ex) {
console.log("error", ex);
// do nothing
}
} else {
inbox.init({
config: props,
});
}
}

initInbox({
config: props,
});
}, [props, clientKey, userId]);

useEffect(() => {
localStorage.setItem(
`${clientKey}/${userId}/inbox`,
JSON.stringify({
messages: inbox.messages,
config: inbox.config,
unreadMessageCount: inbox.unreadMessageCount,
})
);
Expand Down
4 changes: 2 additions & 2 deletions packages/react-inbox/src/components/Message/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,14 @@ const Message: React.FunctionComponent<MessageProps> = ({
showMarkAsRead && {
label: MESSAGE_LABELS.MARK_AS_READ,
onClick: () => {
markMessageRead(messageId, readTrackingId);
markMessageRead(messageId, readTrackingId || "");
},
},

showMarkAsUnread && {
label: MESSAGE_LABELS.MARK_AS_UNREAD,
onClick: () => {
markMessageUnread(messageId, unreadTrackingId);
markMessageUnread(messageId, unreadTrackingId || "");
},
},
].filter(Boolean),
Expand Down
15 changes: 15 additions & 0 deletions packages/react-inbox/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,18 @@ export const MESSAGE_LABELS = {
MARK_AS_READ: "Mark as Read",
MARK_AS_UNREAD: "Mark as Unread",
};

export const DEFAULT_TABS = [
{
id: "unread",
label: "Unread",
filter: {
isRead: false,
},
},
{
id: "all",
label: "All Messages",
filter: {},
},
];
52 changes: 22 additions & 30 deletions packages/react-inbox/src/hooks/use-inbox.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,46 @@
import { useEffect, useCallback } from "react";
import { useEffect } from "react";
import { useCourier, useTrackEvent } from "@trycourier/react-provider";
import useMessages from "~/hooks/use-messages";
import { DEFAULT_TABS } from "~/constants";

export default () => {
const { fetch: fetchMessages } = useMessages();
const { dispatch, inbox, transport } = useCourier();

const { trackEvent, batchTrackEvent } = useTrackEvent();

const newMessage = useCallback(
(payload) => {
dispatch({
type: "inbox/NEW_MESSAGE",
payload,
});
},
[dispatch]
);
const {
messages,
config,
currentTab,
isLoading,
startCursor,
unreadMessageCount,
} = inbox || {};

useEffect(() => {
transport?.listen({
id: "inbox-listener",
listener: (courierEvent) => {
newMessage(courierEvent?.data);
dispatch({
type: "inbox/NEW_MESSAGE",
payload: courierEvent?.data,
});
},
});
}, [newMessage, transport]);
}, [transport]);

return {
...inbox,

messages: messages || [],
config,
currentTab,
isLoading,
startCursor,
unreadMessageCount,
init: (payload) => {
payload = {
...payload,
config: {
...payload.config,
tabs: payload.config.tabs ?? [
{
id: "unread",
label: "Unread",
filter: {
isRead: false,
},
},
{
id: "all",
label: "All Messages",
filter: {},
},
],
tabs: payload.config.tabs ?? DEFAULT_TABS,
},
};

Expand Down
23 changes: 23 additions & 0 deletions packages/react-provider/src/actions/brand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const GET_BRAND = `
query GetBrand($brandId: String!) {
brand(brandId: $brandId) {
settings {
colors {
primary
}
}
}
}
`;

export const getBrand = async (client, brandId) => {
const results = await client
.query(GET_BRAND, {
brandId,
})
.toPromise();
const primaryColor = results?.data?.brand?.settings?.colors?.primary;
return {
primaryColor,
};
};
5 changes: 1 addition & 4 deletions packages/react-provider/src/hooks/use-graphql-client.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { useMemo } from "react";
import { createClient } from "urql";
import useCourier from "./use-courier";

export default () => {
const { clientKey, userId, userSignature, apiUrl } = useCourier();

export default ({ clientKey, userId, userSignature, apiUrl }) => {
const client = useMemo(() => {
return createClient({
url: `${
Expand Down
47 changes: 30 additions & 17 deletions packages/react-provider/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useMemo } from "react";
import createReducer from "react-use/lib/factory/createReducer";
import { Provider } from "urql";
import { Client } from "@urql/core";
import * as types from "./types";

import useGraphQlClient from "./hooks/use-graphql-client";
Expand All @@ -10,6 +11,7 @@ import * as TransportTypes from "./transports/types";
import reducer, { registerReducer as _registerReducer } from "./reducer";

import middleware from "./middleware";
import { getBrand } from "./actions/brand";

export * from "./transports";
export * from "./hooks";
Expand All @@ -23,21 +25,25 @@ export const CourierContext = React.createContext<ICourierContext | undefined>(
undefined
);

const GraphQLProvider: React.FunctionComponent = ({ children }) => {
const client = useGraphQlClient();
const GraphQLProvider: React.FunctionComponent<{ client: Client }> = ({
children,
client,
}) => {
return <Provider value={client}>{children}</Provider>;
};

export const CourierProvider: React.FunctionComponent<ICourierContext> = ({
apiUrl,
brand,
brandId,
children,
clientKey,
transport,
userId,
userSignature,
wsUrl,
}) => {
const client = useGraphQlClient({ clientKey, userId, userSignature, apiUrl });
transport = useMemo(() => {
if (transport) {
return transport;
Expand All @@ -52,29 +58,37 @@ export const CourierProvider: React.FunctionComponent<ICourierContext> = ({
wsUrl,
});
}, [transport, clientKey, wsUrl]);

const [state, dispatch] = useReducer(reducer, {
apiUrl,
brand,
brandId,
clientKey,
transport,
userId,
userSignature,
});

useEffect(() => {
dispatch({
type: "root/INIT",
payload: {
apiUrl,
brand,
clientKey,
transport,
userId,
userSignature,
},
});
}, [apiUrl, brand, clientKey, transport, userId, userSignature]);
if (clientKey && userId) {
dispatch({
type: "root/INIT",
payload: {
apiUrl,
brandId,
clientKey,
transport,
userId,
userSignature,
},
});
if (brandId) {
dispatch({
type: "root/GET_BRAND",
payload: () => getBrand(client, brandId),
});
}
}
}, [apiUrl, clientKey, transport, userId, userSignature, brandId]);

useEffect(() => {
if (!transport || !userId) {
Expand All @@ -88,15 +102,14 @@ export const CourierProvider: React.FunctionComponent<ICourierContext> = ({
courierTransport.unsubscribe(userId);
};
}, [transport, userId]);

return (
<CourierContext.Provider
value={{
...(state as any),
dispatch,
}}
>
<GraphQLProvider>{children}</GraphQLProvider>
<GraphQLProvider client={client}>{children}</GraphQLProvider>
</CourierContext.Provider>
);
};
7 changes: 7 additions & 0 deletions packages/react-provider/src/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ const rootReducer = (state, action) => {
transport: action.payload.transport,
userId: action.payload.userId,
userSignature: action.payload.userSignature,
brandId: action.payload.brandId,
};
}
case "root/GET_BRAND/DONE": {
return {
...state,
brand: action.payload,
};
}

Expand Down
17 changes: 10 additions & 7 deletions packages/react-provider/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { Transport } from "./transports";

interface Brand {
primaryColor?: string;
icons?: {
message?: string;
bell?: string;
};
}
export interface ICourierContext {
apiUrl?: string;
clientKey?: string;
Expand All @@ -7,11 +15,6 @@ export interface ICourierContext {
userId?: string;
userSignature?: string;
wsUrl?: string;
brand?: {
primaryColor?: string;
icons?: {
message?: string;
bell?: string;
};
};
brandId?: string;
brand?: Brand;
}
5 changes: 3 additions & 2 deletions packages/react-provider/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ export class WS {
}

send(message: { [key: string]: any }): void {
this.connection?.send(JSON.stringify(message));
if (this.connected) {
this.connection?.send(JSON.stringify(message));
}
}

unsubscribe(channel: string, event: string, clientKey: string): void {
Expand All @@ -89,7 +91,6 @@ export class WS {
return;
}

this.connection.onopen = this.onConnectionOpen.bind(this);
this.connection.onmessage = this.onMessage.bind(this);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export function Default() {
clientKey={clientKey}
userId={userId}
transport={courierTransport}
brandId={process.env.BRAND_ID || ""}
>
<Toast />
<Inbox title="Inbox" />
Expand Down

0 comments on commit 4763a14

Please sign in to comment.