Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get chat session storage working inside useEffect #25

Merged
merged 9 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Contains information from the language-subtag-registry JSON Database (https://github.com/mattcg/language-subtag-registry/tree/master/data/json) which is made available under the ODC Attribution License (https://github.com/mattcg/language-subtag-registry/blob/master/LICENSE.md).
Contains information from the language-subtag-registry JSON Database (https://github.com/mattcg/language-subtag-registry/tree/master/data/json)
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
which is made available under the ODC Attribution License (https://github.com/mattcg/language-subtag-registry/blob/master/LICENSE.md).

The files listed in this repository are licensed under the below license. All other features and products are subject to separate agreements and certain functionality requires paid subscriptions to Yext products.

Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions packages/chat-headless-react/jest.config.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
{
"bail": 0,
"collectCoverage": true,
"collectCoverageFrom": ["src/**", "!src/models/**/*.ts"],
"collectCoverageFrom": ["src/**"],
"verbose": true,
"moduleFileExtensions": ["js", "ts", "tsx"],
"moduleDirectories": ["node_modules", "<rootDir>"],
"testEnvironment": "jsdom",
"testPathIgnorePatterns": ["./tests/mocks/*"],
"testPathIgnorePatterns": ["./tests/mocks/*", "./tests/jest-setup.js"],
"resetMocks": true,
"restoreMocks": true,
"clearMocks": true,
"testMatch": ["<rootDir>/tests/**/*.(test).ts(x)?"]
"testMatch": ["<rootDir>/tests/**/*.[jt]s?(x)"],
"setupFiles": ["<rootDir>/tests/jest-setup.js"]
}
29 changes: 23 additions & 6 deletions packages/chat-headless-react/src/ChatHeadlessProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ChatHeadless, HeadlessConfig } from "@yext/chat-headless";
import { PropsWithChildren, useMemo } from "react";
import { PropsWithChildren, useMemo, useEffect, useState } from "react";
import { Provider } from "react-redux";
import { ChatHeadlessContext } from "./ChatHeadlessContext";
import { updateClientSdk } from "./utils/clientSdk";
Expand All @@ -25,14 +25,31 @@ export function ChatHeadlessProvider(
props: ChatHeadlessProviderProps
): JSX.Element {
const { children, config } = props;
const headless = useMemo(
() => new ChatHeadless(updateClientSdk(config)),
[config]
);
// deferLoad is used with sessionStorage so that the children won't be
// immediately rendered and trigger the "load initial message" flow before
// the state can be loaded from session.
const [deferLoad, setDeferLoad] = useState(config.saveToSessionStorage);

const headless = useMemo(() => {
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
const configWithoutSession = { ...config, saveToSessionStorage: false };
const headless = new ChatHeadless(updateClientSdk(configWithoutSession));
return headless;
}, [config]);

// sessionStorage is overridden here so that it is compatible with server-
// side rendering, which cannot have browser api calls like session storage
// outside of hooks.
useEffect(() => {
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
if (!config.saveToSessionStorage || !headless) {
return;
}
headless.initSessionStorage();
setDeferLoad(false);
}, [headless, config]);

return (
<ChatHeadlessContext.Provider value={headless}>
<Provider store={headless.store}>{children}</Provider>
{deferLoad || <Provider store={headless.store}>{children}</Provider>}
</ChatHeadlessContext.Provider>
);
}
62 changes: 62 additions & 0 deletions packages/chat-headless-react/tests/headlessProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { render } from "@testing-library/react";
import {
ChatHeadlessProvider,
ConversationState,
HeadlessConfig,
} from "../src";
import { renderToString } from "react-dom/server";
import { useChatState } from "../src/useChatState";

it("only fetches session storage on client-side render", async () => {
const win = window;
Object.defineProperty(win, "sessionStorage", {
value: {
...win.sessionStorage,
getItem: (_: string): string => {
return JSON.stringify({
messages: [{ text: "foobar", source: "BOT" }],
isLoading: false,
canSendMessage: false,
} satisfies ConversationState);
},
},
});
const windowSpy = jest
.spyOn(window, "window", "get")
.mockImplementation(() => win);
const config: HeadlessConfig = {
botId: "123",
apiKey: "1234",
saveToSessionStorage: true,
};
const str = () =>
yen-tt marked this conversation as resolved.
Show resolved Hide resolved
renderToString(
<ChatHeadlessProvider config={config}>
<TestComponent />
</ChatHeadlessProvider>
);
const container = document.body.appendChild(document.createElement("div"));
container.innerHTML = str();
expect(windowSpy).not.toHaveBeenCalled();
expect(str()).not.toContain("foobar");

const view = render(
<ChatHeadlessProvider config={config}>
<TestComponent />
</ChatHeadlessProvider>,
{ container, hydrate: true }
);
expect(await view.findByText("foobar")).toBeTruthy();
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
expect(windowSpy).toHaveBeenCalled();
});

const TestComponent = () => {
const messages = useChatState((state) => state.conversation.messages);
return (
<div>
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
{messages.map((msg, i) => (
<span key={i}>{msg.text}</span>
))}
</div>
);
};
8 changes: 8 additions & 0 deletions packages/chat-headless-react/tests/jest-setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { TextDecoder, TextEncoder } from "util";

/**
* jest's jsdom doesn't have the following properties defined in global for the DOM.
* polyfill it with functions from NodeJS. This is to used in Chat Core.
*/
global.TextDecoder = TextDecoder;
global.TextEncoder = TextEncoder;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [@yext/chat-headless](./chat-headless.md) &gt; [ChatHeadless](./chat-headless.chatheadless.md) &gt; [initSessionStorage](./chat-headless.chatheadless.initsessionstorage.md)

## ChatHeadless.initSessionStorage() method

Loads the [ConversationState](./chat-headless.conversationstate.md) from session storage, if present, and adds a listener to keep the conversation state in sync with the stored state

**Signature:**

```typescript
initSessionStorage(): void;
```
**Returns:**

void

## Remarks

This is called by default if [HeadlessConfig.saveToSessionStorage](./chat-headless.headlessconfig.savetosessionstorage.md) is true.

Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export declare class ChatHeadless
| [addListener(listener)](./chat-headless.chatheadless.addlistener.md) | | Adds a listener for a specific state value of type T. |
| [addMessage(message)](./chat-headless.chatheadless.addmessage.md) | | Adds a new message to [ConversationState.messages](./chat-headless.conversationstate.messages.md) |
| [getNextMessage(text, source)](./chat-headless.chatheadless.getnextmessage.md) | | Performs a Chat API request for the next message generated by chat bot using the conversation state (e.g. message history and notes). Update the state with the response data. |
| [initSessionStorage()](./chat-headless.chatheadless.initsessionstorage.md) | | Loads the [ConversationState](./chat-headless.conversationstate.md) from session storage, if present, and adds a listener to keep the conversation state in sync with the stored state |
| [report(eventPayload)](./chat-headless.chatheadless.report.md) | | Send Chat related analytics event to Yext Analytics API. |
| [restartConversation()](./chat-headless.chatheadless.restartconversation.md) | | Resets all fields within [ConversationState](./chat-headless.conversationstate.md) |
| [setChatLoadingStatus(isLoading)](./chat-headless.chatheadless.setchatloadingstatus.md) | | Sets [ConversationState.isLoading](./chat-headless.conversationstate.isloading.md) to the specified loading state |
Expand Down
1 change: 1 addition & 0 deletions packages/chat-headless/etc/chat-headless.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export class ChatHeadless {
addListener<T>(listener: StateListener<T>): Unsubscribe;
addMessage(message: Message): void;
getNextMessage(text?: string, source?: MessageSource): Promise<MessageResponse | undefined>;
initSessionStorage(): void;
report(eventPayload: Omit<ChatEventPayLoad, "chat"> & DeepPartial<Pick<ChatEventPayLoad, "chat">>): Promise<void>;
restartConversation(): void;
setChatLoadingStatus(isLoading: boolean): void;
Expand Down
2 changes: 1 addition & 1 deletion packages/chat-headless/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@yext/chat-headless",
"version": "0.5.4",
"version": "0.5.5",
"description": "A library for powering UI components for Yext Chat integrations",
"main": "./dist/commonjs/src/index.js",
"module": "./dist/esm/src/index.js",
Expand Down
39 changes: 27 additions & 12 deletions packages/chat-headless/src/ChatHeadless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,7 @@ export class ChatHeadless {
...this.config.analyticsConfig,
});
if (this.config.saveToSessionStorage) {
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
this.setState({
...this.state,
conversation: loadSessionState(),
});
this.addListener({
valueAccessor: (s) => s.conversation,
callback: () =>
sessionStorage.setItem(
STATE_SESSION_STORAGE_KEY,
JSON.stringify(this.state.conversation)
),
});
this.initSessionStorage();
}
}

Expand Down Expand Up @@ -136,6 +125,32 @@ export class ChatHeadless {
};
}

/**
* Loads the {@link ConversationState} from session storage, if present,
* and adds a listener to keep the conversation state in sync with the stored
* state
*
* @remarks
* This is called by default if {@link HeadlessConfig.saveToSessionStorage} is
* true.
*
* @public
*/
initSessionStorage() {
nbramblett marked this conversation as resolved.
Show resolved Hide resolved
this.setState({
...this.state,
conversation: loadSessionState(),
});
this.addListener({
valueAccessor: (s) => s.conversation,
callback: () =>
sessionStorage.setItem(
STATE_SESSION_STORAGE_KEY,
JSON.stringify(this.state.conversation)
),
});
}

/**
* Send Chat related analytics event to Yext Analytics API.
*
Expand Down