Skip to content

Commit

Permalink
feat: added the WebChatCustomElement component to aid in using web ch…
Browse files Browse the repository at this point in the history
…at with a custom element
  • Loading branch information
TazmanianDI committed Nov 10, 2023
1 parent a969b54 commit def4465
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 1 deletion.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ module.exports = {
'import/prefer-default-export': 'off',
'react/jsx-filename-extension': [1, { extensions: ['.tsx', '.jsx'] }],
'react/require-default-props': 'off',
'react/jsx-props-no-spreading': 'off',
'no-use-before-define': 'off',
// Airbnb allows arrow functions but not regular functions which doesn't make any sense.
'react/jsx-no-bind': 'off',
Expand Down
46 changes: 45 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ The primary utility provided by this library is the `WebChatContainer` functiona
<summary>Table of contents</summary>

- [Installation](#installation)
- [Using WebChatContainer](#webchatcontainer)
- [Using WebChatContainer](#using-webchatcontainer)
- [WebChatCustomElement](#webchatcustomelement)
- [API](#api)
- [withWebChat](#withWebChat)
- [Additional resources](#additional-resources)
Expand Down Expand Up @@ -124,6 +125,41 @@ function renderCustomResponse(event) {
}
```

## WebChatCustomElement

This library provides the component `WebChatCustomElement` which can be used to aid in render web chat inside a custom element. This is needed if you want to be able to change the location where web chat is rendered. This component will render an element in your React app and use that element as the custom element for rendering web chat. It will also the `WebChatContainer` component to manage the life cycle of web chat so you will use `WebChatCustomElement`.

If you use this component, you will need to provide some CSS styles to control how the transition occurs between web chat showing and hiding. By default, the component will simply add a `HideWebChat` class to the web chat main window when it is closed. All you need to do is provide a `#WACContainer.WACContainer .HideWebChat { display: none }` rule in your CSS. You can also override the view change code is you need more fine-grained control over the style changes that occur. This would be useful if you wanted to animate the transitions.

The simplest example is this:

```javascript
import React from 'react';
import { WebChatCustomElement } from '@ibm-watson/assistant-web-chat-react';

import './App.css';

const webChatOptions = { /* Web chat options */ };

function App() {
return <WebChatCustomElement className="MyCustomElement" config={webChatOptions} />;
}
```

```css
.MyCustomElement {
position: absolute;
left: 100px;
top: 100px;
width: 500px;
height: 500px;
}

#WACContainer.WACContainer .HideWebChat {
display: none;
}
```

## API

### WebChatContainer API
Expand All @@ -144,6 +180,14 @@ Note that this component will call the [web chat render](https://web-chat.global
| onAfterRender | No | function | This is a callback function that is called after web chat has been loaded and after the `render` function is called. This function is passed a single argument which is the instance of web chat that was loaded. This function can be used to obtain a reference to the web chat instance if you want to make use of the instance methods that are available. |
| renderCustomResponse | No | function | This function is a callback function that will be called by this container to render custom responses. If this prop is provided, then the container will listen for custom response events from web chat and will generate a React portal for each event. This function will be called once during component render for each custom response event. This function takes two arguments. The first is the [custom response event](https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html?to=api-events#customresponse) that triggered the custom response. The second is a convenience argument that is the instance of web chat. The function should return a `ReactNode` that renders the custom content for the response. |

`WebChatCustomElement` inherits all of the props from `WebChatContainer`. It also has the following additional optional props.

| Attribute | Type | Description |
|-----------|---------|-------------|
| className | string | An optional classname that will be added to the custom element. |
| id | string | An optional id that will be added to the custom element. |
| onViewChange | function | An optional listener for "view:change" events. Such a listener is required when using a custom element in order to control the visibility of the web chat main window. If no callback is provided here, a default one will be used that just adds the classname "HideWebChat" when the main window is closed and removes it when the main window is opened. If you use the default, you will also need to add a "#WACContainer.WACContainer .HideWebChat { display: none }" rule to your CSS. You can provide a different callback here if you want custom behavior such as an animation when the main window is opened or closed. Note that this function can only be provided before web chat is loaded. After web chat is loaded, the event handler will not be updated. See the web chat [view:change documentation](https://web-chat.global.assistant.watson.cloud.ibm.com/docs.html?to=api-events#view:change) for more information. Also see the [tutorial for using animiations with custom elements](https://github.com/watson-developer-cloud/assistant-toolkit/tree/master/integrations/webchat/examples/custom-element/client/javascript-animation) for an example of what can be done here. |

### Debugging

In addition to the props above, the `WebChatContainer` component can output additional debug information. To enable this output, call the `setEnableDebug` function which is exported from this library.
Expand Down
8 changes: 8 additions & 0 deletions setupTests.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-empty-function */
/**
* (C) Copyright IBM Corp. 2021.
*
Expand All @@ -15,6 +16,13 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nodeCrypto = require('crypto');

// Hide all the internal output from test cases.
console.error = () => {};
console.warn = () => {};
console.log = () => {};
console.debug = () => {};
console.info = () => {};

// eslint-disable-next-line no-undef
window.crypto = {
getRandomValues(buffer) {
Expand Down
98 changes: 98 additions & 0 deletions src/WebChatCustomElement.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* (C) Copyright IBM Corp. 2022.
*
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/

import React, { useCallback, useMemo, useState } from 'react';
import { WebChatContainer, WebChatContainerProps } from './WebChatContainer';
import { WebChatInstance } from './types/WebChatInstance';

interface WebChatCustomElementProps extends WebChatContainerProps {
/**
* An optional classname that will be added to the custom element.
*/
className?: string;

/**
* An optional id that will be added to the custom element.
*/
id?: string;

/**
* An optional listener for "view:change" events. Such a listener is required when using a custom element in order
* to control the visibility of the web chat main window. If no callback is provided here, a default one will be
* used that just adds the classname "HideWebChat" when the main window is closed and removes it when the main
* window is opened. If you use the default, you will also need to add a
* "#WACContainer.WACContainer .HideWebChat { display: none }" rule to your CSS.
*
* You can provide a different callback here if you want custom behavior such as an animation when the main window
* is opened or closed.
*
* Note that this function can only be provided before web chat is loaded. After web chat is loaded, the event
* handler will not be updated.
*/
onViewChange?: (event: any, instance: WebChatInstance) => void;
}

/**
* This component can be used if you want to render web chat inside a custom element. It will perform two functions:
*
* 1. It will create the custom element as part of the React application.
* 2. It will attach web chat to the custom element and use the WebChatContainer component to manage the life cycle
* of the web chat instance.
*/
function WebChatCustomElement(props: WebChatCustomElementProps) {
const { className, id, onViewChange, config, onBeforeRender, ...containerProps } = props;
const [customElement, setCustomElement] = useState<HTMLDivElement>();

// Make sure to memoize the config object. If we pass a new object to WebChatContainer (even if all the properties
// inside of it are the same), the container will just continually destroy and recreate the web chat instance
// because it thinks the config keeps changing.
const useConfig = useMemo(() => {
return {
...config,
element: customElement,
};
}, [config, customElement]);

const onBeforeRenderOverride = useCallback(
async (instance: WebChatInstance) => {
/**
* A default handler for the "view:change" event. This will be used to show or hide the web chat main window
* using a simple classname.
*/
function defaultViewChangeHandler(event: any, instance: WebChatInstance) {
if (event.newViewState.mainWindow) {
instance.elements.getMainWindow().removeClassName('HideWebChat');
} else {
instance.elements.getMainWindow().addClassName('HideWebChat');
}
}

instance.on({ type: 'view:change', handler: onViewChange || defaultViewChangeHandler });

return onBeforeRender?.(instance);
},
[onBeforeRender, onViewChange],
);

return (
<>
<div className={className} id={id} ref={setCustomElement} />
{customElement && (
<WebChatContainer config={useConfig} onBeforeRender={onBeforeRenderOverride} {...containerProps} />
)}
</>
);
}

export { WebChatCustomElement };

0 comments on commit def4465

Please sign in to comment.