From b79a47199c042524724ae7f943c7461019ffaca0 Mon Sep 17 00:00:00 2001 From: "Damon Lundin (IBM)" Date: Tue, 14 Nov 2023 11:15:27 -0600 Subject: [PATCH] feat: added the WebChatCustomElement component to aid in using web chat with a custom element (#23) --- .eslintrc.js | 1 + README.md | 46 ++++++++++++++++- setupTests.js | 8 +++ src/WebChatCustomElement.tsx | 98 ++++++++++++++++++++++++++++++++++++ 4 files changed, 152 insertions(+), 1 deletion(-) create mode 100644 src/WebChatCustomElement.tsx diff --git a/.eslintrc.js b/.eslintrc.js index 9b4be4c..d815b3d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -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', diff --git a/README.md b/README.md index 68053ce..8217674 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ The primary utility provided by this library is the `WebChatContainer` functiona Table of contents - [Installation](#installation) -- [Using WebChatContainer](#webchatcontainer) +- [Using WebChatContainer](#using-webchatcontainer) +- [WebChatCustomElement](#webchatcustomelement) - [API](#api) - [withWebChat](#withWebChat) - [Additional resources](#additional-resources) @@ -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 ; +} +``` + +```css +.MyCustomElement { + position: absolute; + left: 100px; + top: 100px; + width: 500px; + height: 500px; +} + +#WACContainer.WACContainer .HideWebChat { + display: none; +} +``` + ## API ### WebChatContainer API @@ -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. diff --git a/setupTests.js b/setupTests.js index fe1cc0b..ff1ec76 100644 --- a/setupTests.js +++ b/setupTests.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-empty-function */ /** * (C) Copyright IBM Corp. 2021. * @@ -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) { diff --git a/src/WebChatCustomElement.tsx b/src/WebChatCustomElement.tsx new file mode 100644 index 0000000..e1071e5 --- /dev/null +++ b/src/WebChatCustomElement.tsx @@ -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(); + + // 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 ( + <> +
+ {customElement && ( + + )} + + ); +} + +export { WebChatCustomElement };