@defra/flood-webchat 0.0.1-beta.9 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +6 -0
  2. package/dist/client.js +1 -329
  3. package/dist/server.js +1 -286
  4. package/main.scss +13 -8
  5. package/package.json +29 -22
  6. package/src/client/components/availability/availability.jsx +94 -65
  7. package/src/client/components/availability/availability.scss +20 -32
  8. package/src/client/components/chat/chat.jsx +239 -0
  9. package/src/client/components/chat/chat.scss +258 -0
  10. package/src/client/components/errorSummary/error-summary.jsx +34 -0
  11. package/src/client/components/live-region.jsx +55 -0
  12. package/src/client/components/message/message.jsx +21 -0
  13. package/src/client/components/panel/panel-footer.jsx +9 -0
  14. package/src/client/components/panel/panel-header.jsx +75 -0
  15. package/src/client/components/panel/panel.jsx +163 -0
  16. package/src/client/components/panel/panel.scss +112 -0
  17. package/src/client/components/screens/end-chat.jsx +77 -0
  18. package/src/client/components/screens/feedback.jsx +65 -0
  19. package/src/client/components/screens/pre-chat.jsx +62 -0
  20. package/src/client/components/screens/request-chat.jsx +183 -0
  21. package/src/client/components/screens/settings.jsx +97 -0
  22. package/src/client/components/screens/unavailable.jsx +23 -0
  23. package/src/client/components/skip-link.jsx +42 -0
  24. package/src/client/hooks/useFocusedElements.js +80 -0
  25. package/src/client/hooks/useTextareaAutosize.js +13 -0
  26. package/src/client/index.jsx +18 -1
  27. package/src/client/lib/agent-status-headline.js +17 -0
  28. package/src/client/lib/check-availability.js +1 -0
  29. package/src/client/lib/history.js +13 -0
  30. package/src/client/lib/message-notification.js +30 -0
  31. package/src/client/lib/transform-messages.js +47 -0
  32. package/src/client/scss/_objects.scss +33 -0
  33. package/src/client/scss/_settings.scss +101 -0
  34. package/src/client/scss/_tools.scss +33 -0
  35. package/src/client/scss/_utilities.scss +25 -0
  36. package/src/client/store/AppProvider.jsx +183 -0
  37. package/src/client/store/actions-map.js +152 -0
  38. package/src/client/store/constants.js +4 -0
  39. package/src/client/store/reducer.js +31 -0
  40. package/src/client/store/useApp.js +5 -0
  41. package/src/client/store/useChatSdk.js +37 -0
  42. package/src/server/lib/client.js +2 -2
  43. package/src/server/lib/utils.js +16 -8
  44. package/webpack.config.mjs +0 -2
  45. package/webpack.prod.mjs +7 -0
  46. package/dist/client.js.map +0 -1
  47. package/dist/server.js.map +0 -1
  48. package/src/client/lib/external-stores.js +0 -4
  49. package/src/client/lib/external-sync-store.js +0 -42
@@ -0,0 +1,97 @@
1
+ import React, { useState } from 'react'
2
+ import { PanelHeader } from '../panel/panel-header.jsx'
3
+
4
+ import { useApp } from '../../store/useApp.js'
5
+
6
+ export function Settings ({ onCancel }) {
7
+ const { settings, setSettings } = useApp()
8
+
9
+ const [optionAudio, setOptionAudio] = useState(settings.audio)
10
+ const [optionScroll, setOptionScroll] = useState(settings.scroll)
11
+
12
+ const onSave = e => {
13
+ e.preventDefault()
14
+
15
+ setSettings({ audio: optionAudio, scroll: optionScroll })
16
+ onCancel(e)
17
+ }
18
+
19
+ const handleKeyPress = e => {
20
+ if ((e.key === 'Enter' || e.key === ' ') && e.target.id === 'settings-save') {
21
+ onSave(e)
22
+ } else if ((e.key === 'Enter' || e.key === ' ') && e.target.id === 'settings-cancel') {
23
+ onCancel(e)
24
+ }
25
+ }
26
+
27
+ return (
28
+ <>
29
+ <PanelHeader />
30
+
31
+ <div className='wc-body'>
32
+ <div className='wc-content'>
33
+ <fieldset className='govuk-fieldset govuk-!-margin-bottom-4'>
34
+ <legend className='govuk-fieldset__legend govuk-fieldset__legend'>
35
+ <h3 id='wc-subtitle' className='wc-heading'>Change settings</h3>
36
+ </legend>
37
+ <div className='govuk-checkboxes govuk-checkboxes--small' data-module='govuk-checkboxes'>
38
+ <div className='govuk-checkboxes__item'>
39
+ <input
40
+ id='audio'
41
+ name='audio'
42
+ type='checkbox'
43
+ value='audio'
44
+ className='govuk-checkboxes__input'
45
+ defaultChecked={optionAudio}
46
+ onChange={() => setOptionAudio(!optionAudio)}
47
+ />
48
+ <label className='wc-label govuk-label govuk-checkboxes__label' htmlFor='audio'>
49
+ Play a sound when receiving a new message
50
+ </label>
51
+ </div>
52
+ <div className='govuk-checkboxes__item'>
53
+ <input
54
+ id='scroll'
55
+ name='scroll'
56
+ type='checkbox'
57
+ value='scroll'
58
+ className='govuk-checkboxes__input'
59
+ defaultChecked={optionScroll}
60
+ onChange={() => setOptionScroll(!optionScroll)}
61
+ />
62
+ <label className='wc-label govuk-label govuk-checkboxes__label' htmlFor='scroll'>
63
+ Scroll automatically to a new message
64
+ </label>
65
+ </div>
66
+ </div>
67
+ </fieldset>
68
+
69
+ <div className='govuk-button-group'>
70
+ <a
71
+ id='settings-save'
72
+ href='#'
73
+ className='wc-button govuk-button'
74
+ data-module='govuk-button'
75
+ role='button'
76
+ onClick={onSave}
77
+ onKeyDown={handleKeyPress}
78
+ >
79
+ Save
80
+ </a>
81
+ <a
82
+ id='settings-cancel'
83
+ href='#'
84
+ className='wc-link govuk-link'
85
+ data-module='govuk-button'
86
+ role='button'
87
+ onClick={onCancel}
88
+ onKeyDown={handleKeyPress}
89
+ >
90
+ Cancel
91
+ </a>
92
+ </div>
93
+ </div>
94
+ </div>
95
+ </>
96
+ )
97
+ }
@@ -0,0 +1,23 @@
1
+ import React from 'react'
2
+ import { PanelHeader } from '../panel/panel-header.jsx'
3
+
4
+ export function Unavailable () {
5
+ return (
6
+ <>
7
+ <PanelHeader />
8
+
9
+ <div className='wc-body'>
10
+ <h3 id='wc-subtitle' className='govuk-heading-m'>Webchat is currently not available</h3>
11
+ <p className='govuk-body-s'>Try again later, or call Floodline:</p>
12
+ <p className='govuk-body-s'>
13
+ <strong>Floodline helpline</strong>
14
+ <br />Telephone: 0345 988 1188
15
+ <br />Textphone: 0345 602 6340
16
+ <br />Open 24 hours a day, 7 days a week
17
+ <br /><a className='govuk-link' href='https://gov.uk/call-charges'>Find out more about call charges</a>
18
+ </p>
19
+ <p className='govuk-body-s'>We're running webchat as a trial, it will not always be available.</p>
20
+ </div>
21
+ </>
22
+ )
23
+ }
@@ -0,0 +1,42 @@
1
+ import React from 'react'
2
+ import { createPortal } from 'react-dom'
3
+ import { useApp } from '../store/useApp'
4
+
5
+ export const SkipLink = () => {
6
+ const { threadId, setInstigatorId } = useApp()
7
+
8
+ if (!threadId) {
9
+ return null
10
+ }
11
+
12
+ const targetContainer = document.getElementById('webchat-skip-link-container')
13
+
14
+ if (!targetContainer) {
15
+ return null
16
+ }
17
+
18
+ const onClick = e => {
19
+ e.preventDefault()
20
+ setInstigatorId(e.target.id)
21
+ window.location.hash = '#webchat'
22
+ }
23
+
24
+ return (
25
+ <>
26
+ {createPortal(
27
+ <a
28
+ id='webchat-skip-link'
29
+ href='#webchat'
30
+ className='govuk-skip-link'
31
+ data-module='govuk-skip-link'
32
+ onClick={onClick}
33
+ data-wc-skiplink
34
+ data-wc-open-btn
35
+ >
36
+ Skip to webchat
37
+ </a>,
38
+ targetContainer
39
+ )}
40
+ </>
41
+ )
42
+ }
@@ -0,0 +1,80 @@
1
+ import { useState, useEffect, useCallback } from 'react'
2
+
3
+ const ariaHidden = 'aria-hidden'
4
+ const dataWcInert = 'data-wc-inert'
5
+
6
+ const setAriaHidden = isInert => {
7
+ for (const node of document.body.children) {
8
+ if (node.id !== 'wc-panel') {
9
+ // We only want to toggle elements that aren't already inert
10
+ if (isInert && !node.getAttribute(ariaHidden)) {
11
+ node.setAttribute(ariaHidden, 'true')
12
+ node.setAttribute(dataWcInert, '')
13
+ } else if (node.hasAttribute(dataWcInert)) {
14
+ node.removeAttribute(ariaHidden)
15
+ node.removeAttribute(dataWcInert)
16
+ }
17
+ }
18
+ }
19
+ }
20
+
21
+ export const getFocusableElements = () => {
22
+ const selectors = [
23
+ '#wc-panel a:not([disabled])',
24
+ '#wc-panel button:not([disabled])',
25
+ '#wc-panel select:not([disabled])',
26
+ '#wc-panel input:not([disabled])',
27
+ '#wc-panel textarea:not([disabled])',
28
+ '#wc-panel *[tabindex="0"]:not([disabled])'
29
+ ]
30
+
31
+ const elements = document.body.querySelectorAll(selectors.join(','))
32
+ return Array.from(elements).filter(e => !e.closest('[hidden]') && !e.closest('[aria-hidden="true"]'))
33
+ }
34
+
35
+ const useFocusedElements = screen => {
36
+ const [panelElements, setPanelElements] = useState([])
37
+
38
+ const onKeyDown = useCallback(e => {
39
+ const webchatPanelElement = document.querySelector('#wc-panel')
40
+
41
+ if (e.key === 'Tab') {
42
+ if (webchatPanelElement && !document.activeElement.closest('#wc-panel')) {
43
+ webchatPanelElement.focus()
44
+ }
45
+
46
+ if (e.shiftKey) {
47
+ if (document.activeElement === panelElements[0]) {
48
+ panelElements[panelElements.length - 1].focus()
49
+ e.preventDefault()
50
+ } else if (document.activeElement === document.querySelector('#wc-panel')) {
51
+ panelElements[panelElements.length - 1]?.focus()
52
+ e.preventDefault()
53
+ }
54
+ } else if (document.activeElement === panelElements[panelElements.length - 1]) {
55
+ panelElements[0].focus()
56
+ e.preventDefault()
57
+ }
58
+ }
59
+ }, [panelElements])
60
+
61
+ useEffect(() => {
62
+ setPanelElements(getFocusableElements())
63
+ }, [screen])
64
+
65
+ useEffect(() => {
66
+ setAriaHidden(true)
67
+
68
+ const panelElement = document.querySelector('#wc-panel')
69
+ panelElement.focus()
70
+
71
+ document.addEventListener('keydown', onKeyDown)
72
+
73
+ return () => {
74
+ setAriaHidden()
75
+ document.removeEventListener('keydown', onKeyDown)
76
+ }
77
+ }, [panelElements])
78
+ }
79
+
80
+ export { useFocusedElements }
@@ -0,0 +1,13 @@
1
+ import { useEffect } from 'react'
2
+
3
+ export const useTextareaAutosize = (textAreaRef, value) => {
4
+ useEffect(() => {
5
+ if (textAreaRef) {
6
+ textAreaRef.style.height = '0px'
7
+
8
+ const scrollHeight = textAreaRef.scrollHeight
9
+
10
+ textAreaRef.style.height = `${scrollHeight}px`
11
+ }
12
+ }, [textAreaRef, value])
13
+ }
@@ -1,16 +1,33 @@
1
1
  import React from 'react'
2
2
  import { createRoot } from 'react-dom/client'
3
+ import { ChatSdk } from '@nice-devone/nice-cxone-chat-web-sdk'
3
4
  import { Availability } from './components/availability/availability.jsx'
4
5
  import { checkAvailability } from './lib/check-availability'
6
+ import { AppProvider } from './store/AppProvider.jsx'
7
+ import { CUSTOMER_ID_STORAGE_KEY } from './store/constants.js'
8
+ import { messageNotification } from './lib/message-notification.js'
5
9
 
6
10
  export async function init (container, options) {
11
+ const sdk = new ChatSdk({
12
+ brandId: options.brandId,
13
+ channelId: options.channelId,
14
+ customerId: window.localStorage.getItem(CUSTOMER_ID_STORAGE_KEY) || '',
15
+ environment: options.environment
16
+ })
17
+
7
18
  const root = createRoot(container)
8
19
  let availability
20
+ let playSound
9
21
  try {
10
22
  const result = await checkAvailability(options.availabilityEndpoint)
23
+ playSound = await messageNotification(options.audioUrl)
11
24
  availability = result.availability
12
25
  } catch (e) {
13
26
  availability = 'UNAVAILABLE'
14
27
  }
15
- root.render(<Availability availability={availability} />)
28
+ root.render(
29
+ <AppProvider sdk={sdk} availability={availability} playSound={playSound}>
30
+ <Availability />
31
+ </AppProvider>
32
+ )
16
33
  }
@@ -0,0 +1,17 @@
1
+ export const agentStatusHeadline = (availability, agentStatus, agentName) => {
2
+ if (availability === 'UNAVAILABLE') {
3
+ return 'Webchat is not currently available'
4
+ }
5
+
6
+ if (!agentStatus) {
7
+ return 'Connecting to Floodline'
8
+ }
9
+
10
+ switch (agentStatus) {
11
+ case 'closed':
12
+ case 'resolved':
13
+ return agentName ? `${agentName} ended the session` : 'Session ended by advisor'
14
+ default:
15
+ return agentName ? `You are speaking with ${agentName}` : 'Waiting for an adviser'
16
+ }
17
+ }
@@ -1,6 +1,7 @@
1
1
  export async function checkAvailability (endpoint) {
2
2
  const response = await fetch(endpoint)
3
3
  const data = await response.json()
4
+
4
5
  return {
5
6
  availability: data.availability || 'UNAVAILABLE'
6
7
  }
@@ -0,0 +1,13 @@
1
+ export const historyPushState = () => {
2
+ const url = window.location.href.split('#')[0]
3
+ window.history.pushState({ history: true }, null, `${url}#webchat`)
4
+ }
5
+
6
+ export const historyReplaceState = () => {
7
+ if (window.history.state?.history) {
8
+ return window.history.back()
9
+ }
10
+
11
+ const url = window.location.href.split('#')[0]
12
+ return window.history.replaceState(null, null, url)
13
+ }
@@ -0,0 +1,30 @@
1
+ export const messageNotification = async audioUrl => {
2
+ const context = new (window.AudioContext || window.webkitAudioContext)()
3
+
4
+ if (context.state === 'suspended') {
5
+ const events = ['touchstart', 'touchend', 'mousedown', 'wheel', 'keydown', 'click']
6
+
7
+ const unlock = _e => {
8
+ events.forEach(event => {
9
+ document.body.removeEventListener(event, unlock)
10
+ })
11
+
12
+ context.resume()
13
+ }
14
+
15
+ events.forEach(event => {
16
+ document.body.addEventListener(event, unlock, false)
17
+ })
18
+ }
19
+
20
+ const response = await fetch(audioUrl)
21
+ const arrayBuffer = await response.arrayBuffer()
22
+ const buffer = await context.decodeAudioData(arrayBuffer)
23
+
24
+ return () => {
25
+ const source = context.createBufferSource()
26
+ source.buffer = buffer
27
+ source.connect(context.destination)
28
+ source.start()
29
+ }
30
+ }
@@ -0,0 +1,47 @@
1
+ import { DateTime } from 'luxon'
2
+ import parse from 'html-react-parser'
3
+
4
+ const websiteRegex = /(?:www|https?)[^\s]+/gi
5
+
6
+ export const formatMessage = message => {
7
+ if (message.match(websiteRegex)) {
8
+ message = message.replace(websiteRegex, link => {
9
+ return `<a class="govuk-link" href="${link}" target="_blank" rel="noreferrer">${link.replace(/https?:\/\//gi, '')}</a>`
10
+ })
11
+ }
12
+
13
+ return parse(message)
14
+ }
15
+
16
+ export const transformMessage = message => {
17
+ return {
18
+ id: message.id,
19
+ text: message.messageContent?.text,
20
+ createdAt: new Date(message.createdAt),
21
+ user: message.authorEndUserIdentity?.fullName?.trim() || null,
22
+ assignee: message.authorUser?.firstName || null,
23
+ direction: message.direction
24
+ }
25
+ }
26
+
27
+ export const transformMessages = messages => messages.map(message => transformMessage(message))
28
+
29
+ export const formatTranscript = messages => {
30
+ const now = DateTime.local()
31
+ now.setZone('Europe/London')
32
+
33
+ let string = `Floodline webchat transcript, ${now.toFormat('HH:mm:ss a, dd LLLL yyyy')}\n\n`
34
+
35
+ for (const message of messages) {
36
+ const { text, direction, user, assignee, createdAt } = message
37
+
38
+ const author = direction === 'inbound' ? user : `${assignee} (Floodline adviser)`
39
+ const date = DateTime.fromJSDate(new Date(createdAt)).setZone('Europe/London').toFormat('HH:mm:ss a, dd LLLL yyyy')
40
+
41
+ string += `[${date}] ${author}: \n${text}\n\n`
42
+ }
43
+
44
+ string = string.replace(/<a\b[^>]*>/i, '').replace(/<\/a>/i, '')
45
+
46
+ return encodeURIComponent(string)
47
+ }
@@ -0,0 +1,33 @@
1
+ %wc-link-button {
2
+ @extend %govuk-link;
3
+ position: relative;
4
+ display: inline-block;
5
+ font-size: 16px;
6
+ color: govuk-colour('black');
7
+
8
+ &:hover {
9
+ color: govuk-colour('black');
10
+ }
11
+
12
+ &:visited:not(:hover):not(:focus) {
13
+ color: govuk-colour('black');
14
+ }
15
+
16
+ &:active {
17
+ color: govuk-colour('black');
18
+ }
19
+
20
+ &:focus {
21
+ box-shadow: none;
22
+ background-color: transparent;
23
+ text-decoration: underline;
24
+ color: govuk-colour('black');
25
+ }
26
+
27
+ &:focus-visible {
28
+ background-color: $govuk-focus-colour;
29
+ box-shadow: 0 -2px $govuk-focus-colour, 0 4px govuk-colour('black');
30
+ text-decoration: none;
31
+ color: govuk-colour('black');
32
+ }
33
+ }
@@ -0,0 +1,101 @@
1
+ .wc-heading {
2
+ @extend %govuk-heading-m;
3
+ font-size: 19px;
4
+ margin-bottom: 15px;
5
+ }
6
+
7
+ .wc-list {
8
+ @extend %govuk-list;
9
+ @extend %govuk-list--bullet;
10
+ font-size: 16px;
11
+ line-height: 1.25;
12
+ }
13
+
14
+ .wc-body p {
15
+ font-size: 16px;
16
+ line-height: 1.25;
17
+ margin-bottom: 15px;
18
+ @extend %govuk-body-s;
19
+ }
20
+
21
+ .wc-body .govuk-error-message {
22
+ color: govuk-colour('red');
23
+ font-weight: 700;
24
+ }
25
+
26
+ .wc-link,
27
+ .wc-button,
28
+ .govuk-button-group .wc-button,
29
+ .govuk-button-group .wc-link {
30
+ font-size: 16px;
31
+ }
32
+
33
+ .wc-button[aria-disabled="true"] {
34
+ cursor: not-allowed;
35
+ opacity: 0.5;
36
+ }
37
+
38
+ .wc-label {
39
+ font-size: 16px;
40
+ line-height: 1.25;
41
+ }
42
+
43
+ .wc-form-group {
44
+ margin-bottom: 15px;
45
+ }
46
+
47
+ .wc-hint {
48
+ font-size: 16px;
49
+ line-height: 1.25;
50
+ }
51
+
52
+ .wc-inset-text {
53
+ margin: 0 0 20px;
54
+ padding: 5px 5px 5px 15px;
55
+ font-size: 16px;
56
+ border-left-width: 5px;
57
+ }
58
+
59
+ .wc-error-summary__title {
60
+ font-size: 19px;
61
+ line-height: 1.25;
62
+ margin-bottom: 15px;
63
+ }
64
+
65
+ .wc-error-summary__list,
66
+ .wc-error-message {
67
+ font-size: 16px;
68
+ line-height: 1.25;
69
+ }
70
+
71
+ .wc-input, .wc-textarea {
72
+ font-size: 16px;
73
+ line-height: 1.25;
74
+ }
75
+
76
+ .wc-back-link {
77
+ font-size: 16px;
78
+ line-height: 1.25;
79
+ margin: 0 0 25px;
80
+ }
81
+
82
+ // stylelint-disable declaration-no-important
83
+ .wc-live {
84
+ position: absolute !important;
85
+ width: 1px !important;
86
+ height: 1px !important;
87
+ margin: 0 !important;
88
+ padding: 0 !important;
89
+ overflow: hidden !important;
90
+ clip: rect(0 0 0 0) !important;
91
+ -webkit-clip-path: inset(50%) !important;
92
+ clip-path: inset(50%) !important;
93
+ border: 0 !important;
94
+ white-space: nowrap !important;
95
+
96
+ &::before,
97
+ &::after {
98
+ content: ' ';
99
+ }
100
+ }
101
+ // stylelint-enable declaration-no-important
@@ -0,0 +1,33 @@
1
+ // Check there is ot already similar functinality in GOV.UK Frontend
2
+
3
+ @mixin defra-visually-hidden() {
4
+ position: absolute;
5
+ width: 1px;
6
+ height: 1px;
7
+ margin: 0;
8
+ padding: 0;
9
+ overflow: hidden;
10
+ clip: rect(0 0 0 0);
11
+ -webkit-clip-path: inset(50%);
12
+ clip-path: inset(50%);
13
+ border: 0;
14
+ white-space: nowrap;
15
+ }
16
+
17
+ // Map specific mixins
18
+ @mixin focus($glow: 8px, $strong: 5px, $background: 2px, $inset: 0) {
19
+ position:absolute;
20
+ content:'';
21
+ left: 5px;
22
+ right: 5px;
23
+ top: 5px;
24
+ bottom: 5px;
25
+ box-shadow:
26
+ 0 0 0 $background #ffffff,
27
+ inset 0 0 0 $inset govuk-colour('black'),
28
+ 0 0 0 $strong govuk-colour('black'),
29
+ 0 0 0 $glow $govuk-focus-colour;
30
+ outline: 3px solid transparent;
31
+ pointer-events: none;
32
+ z-index: 99;
33
+ }
@@ -0,0 +1,25 @@
1
+ .wc-u-html {
2
+ @include mq ($until: tablet) {
3
+ height: 100vh;
4
+ overflow: hidden;
5
+ }
6
+ }
7
+
8
+ .wc-u-body {
9
+ @include mq ($until: tablet) {
10
+ position: fixed;
11
+ overflow: hidden;
12
+ top:0;
13
+ right:0;
14
+ bottom:0;
15
+ left:0;
16
+ }
17
+ }
18
+
19
+ .wc-u-hidden {
20
+ visibility: hidden;
21
+ }
22
+
23
+ .wc-u-scroll-padding {
24
+ scroll-padding-bottom: calc(2rem + 20px);
25
+ }