@cs-chatbots/webchat-ui

1.143.3 • Public • Published

Webchat-UI

Web client (widget) designed to communicate with the Webchat router. This package includes several graphic themes and language packs.

Installation

npm install @cs-chatbots/webchat-ui

George Web React Integration Example

Webchat-ui integration example as George Web React Component.

The following React example shows the initialization of the GeorgeChat Widget. You can start the conversation by pressing the "Start chat" button or by clicking on the displayed "Teaser".

import React, { useRef, useEffect } from 'react';

import GeorgeChat from '@cs-chatbots/webchat-ui/dist/georgechat';

const getCookie = (t) => {
    const e = document.cookie.match(`(^|;) ?${t}=([^;]*)(;|$)`);
    return Array.isArray(e) ? e[2] : null;
}

const supportedLanguages = ['cs', 'en'];
const maintenanceModeMessage = {
    en: 'Maintenance mode',
    cs: 'Režim údržby'
};
const sharedContext = {
    georgeCluidHashed: getCookie('csasauxid'),
    ga: getCookie('_ga'),
    externalId: getCookie('extcsasid') || '' // optional
};
const externalAuthorization = george.token;

function ChatWidget() {
    const georgechatRef = useRef();
    const onStart = () => georgechatRef.current.initResume();
    const onLogout = () => georgechatRef.current.logout();

    const onMinimize = () => georgechatRef.current.minimize();
    const onExpand = () => georgechatRef.current.expand();

    const onStateChangeHandler = (state, prevState) => {
        console.log('GeorgeChat stateChange (state, prevState):', state, prevState);
    };
    const onActivityHandler = () => {
        console.log('GeorgeChat conversation activity');
    };

    return (
        <>
            <button
                type="button"
                onClick={onStart}
            >
                Start Chat
            </button>
            <button
                type="button"
                onClick={onLogout}
            >
                Logout
            </button>

            <button
                type="button"
                onClick={onMinimize}
            >
                Minimize Chat
            </button>
            <button
                type="button"
                onClick={onExpand}
            >
                Expand Chat
            </button>

            <GeorgeChat
                ref={georgechatRef}
                apiUrl={'https://george.csast.csas.cz/api/georgechat/api'}
                wsUrl={'wss://george.csast.csas.cz/api/georgechat/'}
                channelId={'erste-welcome-genesys'}
                supportedLanguages={supportedLanguages}
                fallbackLanguage={'cs'}
                languagePackage={'george-cz'}
                sharedContext={sharedContext}
                externalAuthorization={externalAuthorization}
                onStateChange={onStateChangeHandler}
                onActivity={onActivityHandler}
                maintenanceModeMessage={maintenanceModeMessage}
            />
        </>
    );
}

export default ChatWidget;

Generic React Integration Example

Webchat-ui integration example as React Component.

The following React example shows the initialization of the Webchat Widget. You can start the conversation by pressing the "Start chat" button or by clicking on the displayed "Teaser".

import React, { useRef } from 'react';

import { Webchat } from '@cs-chatbots/webchat-ui';
import '@cs-chatbots/webchat-ui/dist/flp.css';

const supportedLanguages = ['cs', 'en'];

function ChatWidget() {
    const webchatRef = useRef();
    const onStartChat = () => webchatRef.current.postBack('start');

    return (
        <>
            <button
                type="button"
                onClick={onStartChat}
            >
                Start chat
            </button>

            <Webchat
                ref={webchatRef}
                apiUrl={'http://localhost:3000/api'}
                wsUrl={'ws://localhost:3000/'}
                channelId={'88099916-6b18-11e9-9b46-1681be663d3e'}
                theme={'flp'}
                supportedLanguages={supportedLanguages}
                fallbackLanguage={'cs'}
            />
        </>
    );
}

export default ChatWidget;

Webchat/GeorgeChat component Configuration params resp. React props

Warning: it is required to inform chat squad by email (MLChatDEVEGIT@erstegroup.com) every time you add a new parameter which may differ per country

parameter default description example
channelId required Identifier of channel '88099916-6b18-11e9-9b46-1681be663d3e'
apiUrl required Override an API URL of widget
wsUrl required Override an websocket URL of the widget
refLinks false Enables ability to run certain action using a ?ref=<payload> link in navigation
inactivityTimerEnabled false Webchat will a postback after certain timeout
inactivityTimerTimeout 20000 Timeout in miliseconds
inactivityTimerPayload 'user-timeout-on-page' An actions payload to be fired as inactivity postback
userDataAction 'user-data-update' An action name, which will be sent as a postback and it will contain collected data about page
userDataAppId null Application name used in postback by userDataUpdate
startAppId null Application name used in postback by start action
tokenRefreshInterval 20000 Interval in miliseconds to refresh the credentials
retryInterval 5000 Websockets reconnect interval in miliseconds
wsAuthTokenIntervalMs 60000 Authorization token over Websocket interval in milliseconds. Default value 60000ms. 0 means Authorization token over Websocket will be omitted.
getStarted null Override the action, which will occur after pressing the start button 'start-elsewhere'
isTeaserActive true Interactive Teaser handle minimize and reveal Coversation functionality
resetSessionOnInit false Init with or without conversation history
onConnectionErrorHandler null Register function, which is called in case of Webchat connection error instead of display InitFailedOverlay
useEventsDecorators true Allow display visual decorators before and after Event on click.
sharedContext {} An object or function returning an object - this object is used to extend the shared context on its initialization.
useImagesAsFullscreenOverlay true Allow display images as fullscreen overlay with zoom and download ability.
spinnerMode 'classic' Supported values: 'classic' 'george' 'heygeorge'.
'classic': The first loading screen contains a bar spinner with text underneath. Reconnecting is shown in the conversation (as a messge). Again as a bar spinner with text underneath.
'george': First loading screen uses a circular spinner same as in the George, with text underneath. Reconnecting is shown as a semi-opaque overlay above the conversation. It is a circular spinner same as in the George, with text underneath.
'heygeorge': It is identical to the George option, but the first loading screen / reconnecting is displayed with a spinnerDelayMs (500ms) delay and contains no text. Just a circular spinner.
'classic'
spinnerDelayMs 0 Number of milliseconds after which the display of the connecting/reconnecting spinner will be delayed.
externalAuthorization null If provided, the "external authorization token" is validated against MEP service, hashed and added to the conversation token under key "ea". If the authorization token doesn't validate or the hash doesn't match the "ea" value previously stored, the conversation gets restarted.
externalAuthorizationMethod 'property' Specify a token acquisition method for the externalAuthorization property. Valid values are 'property' | 'oidc' | 'tokenExchange' | 'tokenExchangeInvalidationPost'.
'property' - the externalAuthorization property is taken into account.
'oidc' - externalAuthorization is performed by an internal OIDC process, the externalAuthorization property is ignored.
'tokenExchnage' - externalAuthorization is performed by an internal tokenExchange process, the externalAuthorization property is ignored.
'tokenExchangeInvalidationPost' - externalAuthorization is performed by an internal tokenExchange process, but the invalidation is not with DELETE method, but POST method.
externalAuthorizationAutorecovery false Valid only if the <GeorgeChat /> component is used. If set to true remount Webchat component and invoke start postback on error OIDC process occured.
externalAuthorizationTokenExchangeAccessToken null TokenExchange Access Token. Value is used on externalAuthorizationMethod equals 'tokenExchange' only. Valid only if the <GeorgeChat /> component is used.
externalAuthorizationTokenExchangeUrl null TokenExchange URL. Value is used on externalAuthorizationMethod equals 'tokenExchange' only. Valid only if the <GeorgeChat /> component is used. 'https://apifat.erstebank.hr/george/v1/netbanking/hr/exchange?targetClientId=george-cc'
externalAuthorizationTokenInvalidationUrl null OIDC/TokenExchange invalidation URL. Valid only if the <GeorgeChat /> component is used. 'https://apifat.erstebank.hr/george/v1/netbanking/auth/token/invalidate'
externalAuthorizationTokenExchangeKeepAccessTokenInCookie false This flag decides whether the Chat Token will be kept in cookies or not. If true, Chat Token will be saved to a browser cookies, then starts the process of checking cookies for Chat token change
showClientIdentity false Allow hide/show client icon in conversation. In the case of <GeorgeChat /> component is used, the parameter default value is true
useAuthenticatedFlag false Enable support of the authenticated feature. Each client event is extended with persona object. Authenticated client icon is decorated with the "verified" badge. true
useInvalidationWhenSessionExpired false This flag decides whether invalidation token service will be called or not, when the session have been expired
supportedLanguages ['en', 'cs'] An array of two-letter ISO 639-1 language codes.
fallbackLanguage 'en' Two-letter ISO 639-1 language code used when detection failed. Language code detection is performed according to the attribute lang of the <html> tag.
hideOnUnsupportedLanguage true Hide Webchat widget on unsupported language detected.
theme null

In the case of <GeorgeChat /> component is used, the parameter is ignored and its value is set to 'george'.
Some graphical themes have also its own language sets. 'flp'
onStateChange null Callback handler that is called on the Widget State change. The function has two arguments: (state: string, prevState: string|null). state and prevState, both of which can take the values listed in the following table.
onActivity null Callback handler that is called for each conversational activity.
allowBrowserTabConversationSeparation false

In the case of <GeorgeChat /> component is used, the parameter is ignored and its value is set to true.
It is only taken into account in combination with the ignoreBrowserCookie channel setting. If allowBrowserTabConversationSeparation is set to true, sessionStorage is used to store the conversation session - this makes it possible to run separate conversations per Browser Tab. Otherwise (and by default) localStorage is used.
maintenanceModeAllowed false

In the case of <GeorgeChat /> component is used, the parameter is ignored and its value is set to true.
Allow turn on maintenance mode.
maintenanceModeMessage {} Static maintenance mode message. Overrides language file message. { en: "Maintenance mode", cs: "Režim údržby" }
maintenanceChatHidden false Allow hide/show widget while maintenance mode is on.
expandOnMaintenanceMessage false Expand widget on visible maintenance message.
finishedChatBehaviour 'minimize' 'minimize' | 'hide' | 'keepexpanded' | 'keepexpanded_on_closing_screen'. When the conversation is finished:
When ('minimize') is used, the Chat Widget is minimized. Only the Teaser keeps visible.
When 'hide' is used, the whole Widget (the Teaser included) gets hidden.
When 'keepexpanded' is used, the whole Widget keeps expanded and the user has to press the "Start the chat" button to start a new conversation.
When 'keepexpanded_on_closing_screen' is used, the whole Widget keeps expanded on closing screen. This option is suitable for use alongside 'allowClosingStatesInUrl' set to true.
languagePackage In case no languagePackage is provided, the defaultlanguagePackage will be used Set language-package, due to the every country specifications. Suffix -cz means which country language-pack will be used george-cz
highlightChatAllowed false Allow showing message alerts on a chat
showAlertsOnExpandedChat false Show message alert even if the chat is expanded
ignoreFocusChangeOnMinimizedChat false Ignore any focus changes on a chat component, when the chat is minimized. Focus changes affect showing/hiding message alerts. This flag depends on highlightChatAllowed
allowClosingStatesInUrl false Promote to and react on closing states changes in hash part of url. Namely closing (NPS) screen (closing-screen) and finish state (closed). Its necessary for George mobile integration. Valid values true or false.
allowChatFocusedInUrl false Promote to "chat focused by the User" in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowChatInProgressInUrl false Promote to "user write some utterance" in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowLoadingFinishedInUrl false Promote to loading finished in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowHideComposerOnCampaign false Allow to hide Composer (user input) if it is detected that it is a conversation in a campaign. Valid values true or false.
richTextDeeplinkPrefix When set, original link in conversation message will be encodeURIComponent and appended to {richTextDeeplinkPrefix}/open_external_link?url=. Except original link startsWith 'georgeapp'. E.g. georgeapp://cz/open_external_link?url=https%3A%2F%2Fexample.com%2Ftest%2F1%3Fkey%3Dvalue%26otherkey%3Dvalue.
When set, anchor in conversation message will applied on template {richTextDeeplinkPrefix}/deeplink?path={anchor}&dataReload=true. E.g. georgeapp://cz/deeplink?path=settings/customersafe&dataReload=true
'georgeapp://cz'
processAsAnchorUrlPrefixes [] String array of prefixes, wich will be used to detect URLs that will be treated as if they were anchors. And therefore will be threated as deeplinks. Note. the '#' is automatically included in the array. ['https://george.fat.sparkasse.at/index.html?at=c#', 'https://george.fat.sparkasse.at/index.html?at=c&state=']
enableBodyScrollLock false Enables set of special behavior for mobile devices solving e.g. soft keypad problems. Usable especially for webview. Originally body-scroll-lock packages were allowed to be used here. Usable especially for webview. true
useAnonymization false Turns on content anonymization. Currently only access_token in url. true
useKeepalive true In some cases it is preferred to use another method of sending the event. E.g. sending the close-chat can be immediately followed by going to another browser page and it is necessary to ensure that it is sent by HTTP POST with the 'keepalive' attribute. true
enableFileUpload false Enable the File Upload feature. It extends the capabilities of the Composer component with the ability to attach a file to the message. true
fileUploadMaxFileCount 10 The maximum number of files that can be attached to each message. 3
fileUploadMaxFileSizeBytes 10485760 Maximum number of bytes for each file separately. E.g. 10485760 means 10MiB = (10 * 1024 * 1024)B. 10485760
fileUploadEnabledMode anytime Defines when file upload feature is enabled. First of all enableFileUpload must be set to true to enable file upload feature. Valid values are anytime, onadvisor. anytime - file upload is always enable. onadvisor - file upload is enabled only in conversation with banker anytime
enableConversationHeader false Enables Conversation header with information about advisor/bot and alternative "End Chat" button. This parameter is linked to the functionality of displaying the name of the advisor/bot and the time of its message. true
conversationHeaderMode 'full' Modifies the ConversationHeader functionality if enabled. Valid values: 'full', 'offlineOrAdvisorOnly', 'fullWhenUserFocusedNoneOtherwise'. The default value is 'full'. 'full'
channelAvailabilityBasicAuthBase64 null Default Channel availability Basic Authentication in BASE64. Will be used when the ConversationHeader is visible. 'Y2hhbmdlbWU='
showDebug true Enables visualise debug messages in the conversation. false
composerMaxLength 1000 Max number of characters allowed enter into the Composer. 3000
enableTopShadow false If the shadow on that is displayed when content overflows the height of the container should be visible. Is always true whe conversationHeaderMode is set to false true
enableGeorgeActions false If set to true, carousel buttons call george action by default if the action is sent by bot false

Widget state table

A description of the states that can come as values in the state and prevState arguments of the onStateChange handler described above.

state description widget visual state
INITIALIZING Just after starting the chat. The previous state can be null. The Widget is not render yet.
READY The chat received both a token and a channel, but the conversation has not yet begun. The Widget is minimized.
OPENED The conversation has already begun and the Widget is visible open. The Widget is expanded.
MINIMIZED The conversation has already begun, the Widget is visible in a minimized state. The Widget is minimized.
MINIMIZED_WITH_NOTIFICATION The conversation has already begun, the Widget is visible in a minimized state. Can happen only if widget is minimized and new message received. The Widget is minimized.
FINISHED The user has closed the chat that has already loaded new credentials. The Widget is minimized.

The Widget states

Widget public API

The widget offers a public API, which is described in the following table.

function args description
initResume - The function only exists in the <GeorgeChat /> component. It is called in a scenario specific to GeorgeWeb. The GeorgeChat component is mounted on the page each time it is rendered. At such a moment, GeorgeChat just checks to see if a conversation session has already started. If it is, it starts normally. If not, its further initialization is suspended due to resource savings. You need to call this function to continue initialization.
postBack action Used to send a non-visual chat event. The 'start' value in action argument is used to start the conversation. E.g. postBack('start');
disconnect endSession = true Used to notify the widget that it will be unmounted so it can end performing conversation. Unmount is safe only after setting the FINISHED state.
The true value in endSession argument is used when user click on Logout button. true is default value.
The false value in endSession argument is used when user session expires. E.g. disconnect(false);
reset - Function used to reset the conversation and start from the very beginning. Used mostly for OAI Bot, in conclusion to a full reload, after the reset is triggered.
expand - Used to change widget state to OPENED
minimize - Used to change widget state to MINIMIZED

Readme

Keywords

Package Sidebar

Install

npm i @cs-chatbots/webchat-ui

Weekly Downloads

790

Version

1.143.3

License

UNLICENSED

Unpacked Size

21.6 MB

Total Files

836

Last publish

Collaborators

  • jaroslavgalambosi-ext44603
  • vaclavklecanda-ext44263
  • michal_jankovsky
  • janmalcanek-ext44166
  • tomaserben
  • ext54551
  • 4everyoung
  • pavelpalecekcsas