Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@cs-chatbots/webchat-ui

Package Overview
Dependencies
Maintainers
0
Versions
654
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cs-chatbots/webchat-ui

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

  • 1.146.2
  • latest
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

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

parameterdefaultdescriptionexample
channelIdrequiredIdentifier of channel'88099916-6b18-11e9-9b46-1681be663d3e'
apiUrlrequiredOverride an API URL of widget
wsUrlrequiredOverride an websocket URL of the widget
refLinksfalseEnables ability to run certain action using a ?ref=<payload> link in navigation
inactivityTimerEnabledfalseWebchat will a postback after certain timeout
inactivityTimerTimeout20000Timeout 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
userDataAppIdnullApplication name used in postback by userDataUpdate
startAppIdnullApplication name used in postback by start action
tokenRefreshInterval20000Interval in miliseconds to refresh the credentials
retryInterval5000Websockets reconnect interval in miliseconds
wsAuthTokenIntervalMs60000Authorization token over Websocket interval in milliseconds. Default value 60000ms. 0 means Authorization token over Websocket will be omitted.
getStartednullOverride the action, which will occur after pressing the start button'start-elsewhere'
isTeaserActivetrueInteractive Teaser handle minimize and reveal Coversation functionality
resetSessionOnInitfalseInit with or without conversation history
onConnectionErrorHandlernullRegister function, which is called in case of Webchat connection error instead of display InitFailedOverlay
useEventsDecoratorstrueAllow 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.
useImagesAsFullscreenOverlaytrueAllow 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'
spinnerDelayMs0Number of milliseconds after which the display of the connecting/reconnecting spinner will be delayed.
externalAuthorizationnullIf 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.
externalAuthorizationAutorecoveryfalseValid only if the <GeorgeChat /> component is used. If set to true remount Webchat component and invoke start postback on error OIDC process occured.
externalAuthorizationTokenExchangeAccessTokennullTokenExchange Access Token. Value is used on externalAuthorizationMethod equals 'tokenExchange' only. Valid only if the <GeorgeChat /> component is used.
externalAuthorizationTokenExchangeUrlnullTokenExchange 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'
externalAuthorizationTokenInvalidationUrlnullOIDC/TokenExchange invalidation URL. Valid only if the <GeorgeChat /> component is used.'https://apifat.erstebank.hr/george/v1/netbanking/auth/token/invalidate'
externalAuthorizationTokenExchangeKeepAccessTokenInCookiefalseThis 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
showClientIdentityfalseAllow hide/show client icon in conversation. In the case of <GeorgeChat /> component is used, the parameter default value is true
useAuthenticatedFlagfalseEnable support of the authenticated feature. Each client event is extended with persona object. Authenticated client icon is decorated with the "verified" badge.true
useInvalidationWhenSessionExpiredfalseThis 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.
hideOnUnsupportedLanguagetrueHide Webchat widget on unsupported language detected.
themenull

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'
onStateChangenullCallback 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.
onActivitynullCallback handler that is called for each conversational activity.
allowBrowserTabConversationSeparationfalse

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.
maintenanceModeAllowedfalse

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" }
maintenanceChatHiddenfalseAllow hide/show widget while maintenance mode is on.
expandOnMaintenanceMessagefalseExpand 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.
languagePackageIn case no languagePackage is provided, the defaultlanguagePackage will be usedSet language-package, due to the every country specifications. Suffix -cz means which country language-pack will be usedgeorge-cz
highlightChatAllowedfalseAllow showing message alerts on a chat
showAlertsOnExpandedChatfalseShow message alert even if the chat is expanded
ignoreFocusChangeOnMinimizedChatfalseIgnore any focus changes on a chat component, when the chat is minimized. Focus changes affect showing/hiding message alerts. This flag depends on highlightChatAllowed
allowClosingStatesInUrlfalsePromote 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.
allowChatFocusedInUrlfalsePromote to "chat focused by the User" in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowChatInProgressInUrlfalsePromote to "user write some utterance" in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowLoadingFinishedInUrlfalsePromote to loading finished in hash part of url. Its necessary for Hey George mobile integration. Valid values true or false.
allowHideComposerOnCampaignfalseAllow to hide Composer (user input) if it is detected that it is a conversation in a campaign. Valid values true or false.
richTextDeeplinkPrefixWhen 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=']
enableBodyScrollLockfalseEnables 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
useAnonymizationfalseTurns on content anonymization. Currently only access_token in url.true
useKeepalivetrueIn 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
enableFileUploadfalseEnable the File Upload feature. It extends the capabilities of the Composer component with the ability to attach a file to the message.true
fileUploadMaxFileCount10The maximum number of files that can be attached to each message.3
fileUploadMaxFileSizeBytes10485760Maximum number of bytes for each file separately. E.g. 10485760 means 10MiB = (10 * 1024 * 1024)B.10485760
fileUploadEnabledModeanytimeDefines 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 bankeranytime
enableConversationHeaderfalseEnables 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'
channelAvailabilityBasicAuthBase64nullDefault Channel availability Basic Authentication in BASE64. Will be used when the ConversationHeader is visible.'Y2hhbmdlbWU='
showDebugtrueEnables visualise debug messages in the conversation.false
composerMaxLength1000Max number of characters allowed enter into the Composer.3000
enableTopShadowfalseIf 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 falsetrue
enableGeorgeActionsfalseIf set to true, carousel buttons call george action by default if the action is sent by botfalse
enableWebsocketRequestQueuefalseIf set to true, multiple messages are able to get to the message queue prior websocket is connected and then be sent immediately after connection is establishedfalse

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.

statedescriptionwidget visual state
INITIALIZINGJust after starting the chat. The previous state can be null.The Widget is not render yet.
READYThe chat received both a token and a channel, but the conversation has not yet begun.The Widget is minimized.
OPENEDThe conversation has already begun and the Widget is visible open.The Widget is expanded.
MINIMIZEDThe conversation has already begun, the Widget is visible in a minimized state.The Widget is minimized.
MINIMIZED_WITH_NOTIFICATIONThe 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.
FINISHEDThe 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.

functionargsdescription
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.
postBackactionUsed to send a non-visual chat event. The 'start' value in action argument is used to start the conversation. E.g. postBack('start');
disconnectendSession = trueUsed 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

Keywords

FAQs

Package last updated on 04 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc