@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,183 @@
1
+ import React, { createContext, useEffect, useReducer, useMemo } from 'react'
2
+ import { ChatEvent } from '@nice-devone/nice-cxone-chat-web-sdk'
3
+
4
+ import { initialState, reducer } from './reducer.js'
5
+ import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from './constants.js'
6
+
7
+ export const AppContext = createContext(initialState)
8
+
9
+ export const AppProvider = ({ sdk, availability, playSound, children }) => {
10
+ const [state, dispatch] = useReducer(reducer, initialState)
11
+
12
+ /**
13
+ * SDK event handlers
14
+ */
15
+ const onLiveChatRecovered = e => {
16
+ dispatch({ type: 'SET_AGENT', payload: e.detail.data.inboxAssignee })
17
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.contact.status })
18
+ dispatch({ type: 'SET_UNSEEN_COUNT', payload: e.detail.data.contact.customerStatistics.unseenMessagesCount })
19
+ }
20
+
21
+ const onAssignedAgentChanged = e => {
22
+ dispatch({ type: 'SET_AGENT', payload: e.detail.data.inboxAssignee })
23
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
24
+ }
25
+
26
+ const onAgentTypingStarted = () => {
27
+ dispatch({ type: 'SET_AGENT_TYPING', payload: true })
28
+ }
29
+
30
+ const onAgentTypingEnded = () => {
31
+ dispatch({ type: 'SET_AGENT_TYPING', payload: false })
32
+ dispatch({ type: 'SET_LIVE_REGION_TEXT' })
33
+ }
34
+
35
+ const onMessageCreated = e => {
36
+ dispatch({ type: 'SET_MESSAGE', payload: e.detail.data.message })
37
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
38
+ dispatch({ type: 'SET_UNSEEN_COUNT', payload: e.detail.data.case.customerStatistics.unseenMessagesCount })
39
+
40
+ const isAudioOn = JSON.parse(window.localStorage.getItem(SETTINGS_STORAGE_KEY)).audio
41
+
42
+ if (isAudioOn && e.detail.data.message.direction === 'outbound' && playSound) {
43
+ playSound()
44
+ }
45
+ }
46
+
47
+ const onContactStatusChanged = e => {
48
+ dispatch({ type: 'SET_AGENT_STATUS', payload: e.detail.data.case.status })
49
+ }
50
+
51
+ const onMatchMedia = e => {
52
+ dispatch({ type: 'TOGGLE_IS_MOBILE', payload: e.matches })
53
+ }
54
+
55
+ const onKeydown = () => {
56
+ dispatch({ type: 'TOGGLE_IS_KEYBOARD', payload: true })
57
+ }
58
+
59
+ const onPointerdown = () => {
60
+ dispatch({ type: 'TOGGLE_IS_KEYBOARD', payload: false })
61
+ }
62
+
63
+ useEffect(() => {
64
+ sdk.onChatEvent(ChatEvent.LIVECHAT_RECOVERED, onLiveChatRecovered)
65
+ sdk.onChatEvent(ChatEvent.MESSAGE_CREATED, onMessageCreated)
66
+ sdk.onChatEvent(ChatEvent.AGENT_TYPING_STARTED, onAgentTypingStarted)
67
+ sdk.onChatEvent(ChatEvent.AGENT_TYPING_ENDED, onAgentTypingEnded)
68
+ sdk.onChatEvent(ChatEvent.ASSIGNED_AGENT_CHANGED, onAssignedAgentChanged)
69
+ sdk.onChatEvent(ChatEvent.CONTACT_STATUS_CHANGED, onContactStatusChanged)
70
+ // We need to know if it is a mobile and if it is a keyboard interaction
71
+ window.matchMedia('(max-width: 640px)').addEventListener('change', onMatchMedia)
72
+ window.addEventListener('keydown', onKeydown)
73
+ window.addEventListener('pointerdown', onPointerdown)
74
+ // Tidying up
75
+ return () => {
76
+ window.removeEventListener('change', onMatchMedia)
77
+ window.removeEventListener('keydown', onKeydown)
78
+ window.removeEventListener('pointerdown', onPointerdown)
79
+ }
80
+ }, [sdk])
81
+
82
+ /**
83
+ * Initialize customerId, threadId and whether the webchat should be open
84
+ */
85
+ useEffect(() => {
86
+ dispatch({ type: 'SET_AVAILABILITY', payload: availability })
87
+
88
+ setCustomerId(window.localStorage.getItem(CUSTOMER_ID_STORAGE_KEY))
89
+ setThreadId(window.localStorage.getItem(THREAD_ID_STORAGE_KEY))
90
+ setSettings(JSON.parse(window.localStorage.getItem(SETTINGS_STORAGE_KEY)) || state.settings)
91
+ }, [])
92
+
93
+ /**
94
+ * Set browser history on start chat click
95
+ */
96
+ useEffect(() => {
97
+ if (window.location.hash === '#webchat') {
98
+ setChatVisibility(true)
99
+ }
100
+
101
+ const onBrowserNavigation = () => {
102
+ if (window.location.hash === '#webchat') {
103
+ setChatVisibility(true)
104
+ } else {
105
+ setChatVisibility(false)
106
+ }
107
+ }
108
+
109
+ window.addEventListener('popstate', onBrowserNavigation)
110
+
111
+ return () => {
112
+ window.removeEventListener('popstate', onBrowserNavigation)
113
+ }
114
+ }, [])
115
+
116
+ /**
117
+ * State update functions
118
+ */
119
+ const setChatVisibility = payload => {
120
+ dispatch({ type: 'SET_CHAT_VISIBILITY', payload })
121
+ }
122
+
123
+ const setCustomerId = customerId => {
124
+ dispatch({ type: 'SET_CUSTOMER_ID', payload: customerId })
125
+ }
126
+
127
+ const setThreadId = threadId => {
128
+ dispatch({ type: 'SET_THREAD_ID', payload: threadId })
129
+ }
130
+
131
+ const setThread = thread => {
132
+ dispatch({ type: 'SET_THREAD', payload: thread })
133
+ }
134
+
135
+ const setMessages = messages => {
136
+ dispatch({ type: 'SET_MESSAGES', payload: messages })
137
+ }
138
+
139
+ const setSettings = data => {
140
+ dispatch({ type: 'SET_SETTINGS', payload: data })
141
+ }
142
+
143
+ const setUnseenCount = unseenCount => {
144
+ dispatch({ type: 'SET_UNSEEN_COUNT', payload: unseenCount })
145
+ }
146
+
147
+ const setInstigatorId = id => {
148
+ dispatch({ type: 'SET_INSTIGATOR_ID', payload: id })
149
+ }
150
+
151
+ const setLiveRegionText = text => {
152
+ dispatch({ type: 'SET_LIVE_REGION_TEXT', payload: text })
153
+ }
154
+
155
+ /**
156
+ * Application-wide state and state functions
157
+ */
158
+ const store = useMemo(() => ({
159
+ ...state,
160
+ sdk,
161
+ setSettings,
162
+ setCustomerId,
163
+ setThreadId,
164
+ setThread,
165
+ setMessages,
166
+ setUnseenCount,
167
+ setChatVisibility,
168
+ setInstigatorId,
169
+ setLiveRegionText,
170
+ onLiveChatRecovered,
171
+ onAssignedAgentChanged,
172
+ onAgentTypingStarted,
173
+ onAgentTypingEnded,
174
+ onMessageCreated,
175
+ onContactStatusChanged
176
+ }))
177
+
178
+ return (
179
+ <AppContext.Provider value={store}>
180
+ {children}
181
+ </AppContext.Provider>
182
+ )
183
+ }
@@ -0,0 +1,152 @@
1
+ import { transformMessages, transformMessage } from '../lib/transform-messages'
2
+ import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from './constants'
3
+
4
+ const setSettings = (state, payload) => {
5
+ if (payload) {
6
+ window.localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(payload))
7
+ } else {
8
+ window.localStorage.removeItem(SETTINGS_STORAGE_KEY)
9
+ }
10
+
11
+ return {
12
+ ...state,
13
+ settings: payload
14
+ }
15
+ }
16
+
17
+ const setCustomerId = (state, payload) => {
18
+ if (payload) {
19
+ window.localStorage.setItem(CUSTOMER_ID_STORAGE_KEY, payload)
20
+ } else {
21
+ window.localStorage.removeItem(CUSTOMER_ID_STORAGE_KEY)
22
+ }
23
+
24
+ return {
25
+ ...state,
26
+ customerId: payload
27
+ }
28
+ }
29
+
30
+ const setThreadId = (state, payload) => {
31
+ if (payload) {
32
+ window.localStorage.setItem(THREAD_ID_STORAGE_KEY, payload)
33
+ } else {
34
+ window.localStorage.removeItem(THREAD_ID_STORAGE_KEY)
35
+ }
36
+
37
+ return {
38
+ ...state,
39
+ threadId: payload
40
+ }
41
+ }
42
+
43
+ const setChatVisibility = (state, payload) => {
44
+ return {
45
+ ...state,
46
+ isChatOpen: payload
47
+ }
48
+ }
49
+
50
+ const setAvailability = (state, payload) => {
51
+ return {
52
+ ...state,
53
+ availability: payload
54
+ }
55
+ }
56
+
57
+ const setThread = (state, payload) => {
58
+ return {
59
+ ...state,
60
+ thread: payload
61
+ }
62
+ }
63
+
64
+ const setMessages = (state, payload) => {
65
+ return {
66
+ ...state,
67
+ messages: transformMessages(payload).reverse()
68
+ }
69
+ }
70
+
71
+ const setMessage = (state, payload) => {
72
+ return {
73
+ ...state,
74
+ message: transformMessage(payload),
75
+ messages: [...state.messages, transformMessage(payload)]
76
+ }
77
+ }
78
+
79
+ const setAgent = (state, payload) => {
80
+ return {
81
+ ...state,
82
+ agent: payload
83
+ }
84
+ }
85
+
86
+ const setAgentIsTyping = (state, payload) => {
87
+ return {
88
+ ...state,
89
+ isAgentTyping: payload
90
+ }
91
+ }
92
+
93
+ const setAgentStatus = (state, payload) => {
94
+ return {
95
+ ...state,
96
+ agentStatus: payload
97
+ }
98
+ }
99
+
100
+ const setUnseenCount = (state, payload) => {
101
+ return {
102
+ ...state,
103
+ unseenCount: payload
104
+ }
105
+ }
106
+
107
+ const setInstigatorId = (state, payload) => {
108
+ return {
109
+ ...state,
110
+ instigatorId: payload
111
+ }
112
+ }
113
+
114
+ const setLiveRegionText = (state, payload) => {
115
+ return {
116
+ ...state,
117
+ liveRegionText: payload
118
+ }
119
+ }
120
+
121
+ const toggleIsMobile = (state, payload) => {
122
+ return {
123
+ ...state,
124
+ isMobile: payload
125
+ }
126
+ }
127
+
128
+ const toggleIsKeyboard = (state, payload) => {
129
+ return {
130
+ ...state,
131
+ isKeyboard: payload
132
+ }
133
+ }
134
+
135
+ export const actionsMap = {
136
+ SET_CHAT_VISIBILITY: setChatVisibility,
137
+ SET_AVAILABILITY: setAvailability,
138
+ SET_SETTINGS: setSettings,
139
+ SET_CUSTOMER_ID: setCustomerId,
140
+ SET_THREAD_ID: setThreadId,
141
+ SET_THREAD: setThread,
142
+ SET_MESSAGE: setMessage,
143
+ SET_MESSAGES: setMessages,
144
+ SET_AGENT: setAgent,
145
+ SET_AGENT_TYPING: setAgentIsTyping,
146
+ SET_AGENT_STATUS: setAgentStatus,
147
+ SET_UNSEEN_COUNT: setUnseenCount,
148
+ SET_INSTIGATOR_ID: setInstigatorId,
149
+ SET_LIVE_REGION_TEXT: setLiveRegionText,
150
+ TOGGLE_IS_MOBILE: toggleIsMobile,
151
+ TOGGLE_IS_KEYBOARD: toggleIsKeyboard
152
+ }
@@ -0,0 +1,4 @@
1
+ export const SETTINGS_STORAGE_KEY = 'webchat_settings'
2
+ export const CUSTOMER_ID_STORAGE_KEY = 'webchat_customer_id'
3
+ export const THREAD_ID_STORAGE_KEY = 'webchat_thread_id'
4
+ export const TYPING_INDICATOR_DURATION = 4000
@@ -0,0 +1,31 @@
1
+ import { actionsMap } from './actions-map'
2
+
3
+ export const initialState = {
4
+ availability: null,
5
+ customerId: null,
6
+ threadId: null,
7
+ thread: null,
8
+ messages: [],
9
+ unseenCount: 0,
10
+ instigatorId: null,
11
+ agent: null,
12
+ agentStatus: null,
13
+ isAgentTyping: false,
14
+ isChatOpen: false,
15
+ isMobile: window.matchMedia('(max-width: 640px)').matches,
16
+ isKeyboard: false,
17
+ settings: { audio: true, scroll: true }
18
+ }
19
+
20
+ export const reducer = (state, action) => {
21
+ const { type, payload } = action
22
+
23
+ const fn = actionsMap[type]
24
+
25
+ if (fn) {
26
+ const actionFunction = fn.bind(this, state, payload)
27
+ return actionFunction()
28
+ }
29
+
30
+ return state
31
+ }
@@ -0,0 +1,5 @@
1
+ import { useContext } from 'react'
2
+
3
+ import { AppContext } from './AppProvider.jsx'
4
+
5
+ export const useApp = () => useContext(AppContext)
@@ -0,0 +1,37 @@
1
+ export const useChatSdk = sdk => {
2
+ const connect = async () => sdk.authorize()
3
+
4
+ const fetchCustomerId = async () => {
5
+ const response = await connect()
6
+ return response?.consumerIdentity.idOnExternalPlatform
7
+ }
8
+
9
+ const fetchThread = async threadId => {
10
+ await connect()
11
+ return sdk.getThread(threadId)
12
+ }
13
+
14
+ const fetchMessages = async (thread, threadId) => {
15
+ await connect()
16
+
17
+ const recovered = await thread.recover(threadId)
18
+
19
+ const allMessages = []
20
+ let fetchedMessages = recovered.messages
21
+
22
+ while (fetchedMessages.length) {
23
+ fetchedMessages.map(msg => allMessages.push(msg))
24
+
25
+ try {
26
+ const response = await thread.loadMoreMessages()
27
+ fetchedMessages = response.data.messages
28
+ } catch (err) {
29
+ fetchedMessages = []
30
+ }
31
+ }
32
+
33
+ return allMessages
34
+ }
35
+
36
+ return { connect, fetchCustomerId, fetchThread, fetchMessages }
37
+ }
@@ -1,6 +1,6 @@
1
1
  const querystring = require('querystring')
2
2
  const axios = require('axios')
3
- const jwtdecode = require('jwt-decode')
3
+ const jwtDecode = require('jwt-decode').decode
4
4
  const { isWithinHours } = require('./utils.js')
5
5
 
6
6
  const contentType = 'application/x-www-form-urlencoded'
@@ -25,7 +25,7 @@ const authenticate = async ({ authenticationUri, authorisation, accessKey, acces
25
25
  return {
26
26
  token: auth.data.access_token,
27
27
  tokenType: auth.data.token_type,
28
- tenantId: jwtdecode(auth.data.id_token)?.tenantId
28
+ tenantId: jwtDecode(auth.data.id_token)?.tenantId
29
29
  }
30
30
  }
31
31
 
@@ -1,13 +1,21 @@
1
- const isWithinHours = (days, date = null) => {
2
- const now = date ? new Date(date) : new Date()
1
+ const { DateTime } = require('luxon')
3
2
 
4
- const name = now.toLocaleDateString('en-GB', { weekday: 'long' })
5
- const day = days.find(d => d.day.toLowerCase() === name.toLowerCase())
6
- const dateItems = now.toLocaleDateString('en-GB').split('/')
7
- const open = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.openTime}`
8
- const close = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.closeTime}`
3
+ const getHour = time => Number(time.split(':')[0])
9
4
 
10
- return now.getTime() >= Date.parse(open) && now.getTime() <= Date.parse(close)
5
+ const isWithinHours = (days, date) => {
6
+ const now = date ? DateTime.fromISO(date) : DateTime.local()
7
+ now.setZone('Europe/London')
8
+
9
+ const newDate = date ? new Date(date) : new Date()
10
+
11
+ const today = newDate.toLocaleDateString('en-GB', { weekday: 'long' })
12
+ const dateParts = newDate.toLocaleDateString('en-GB').split('/')
13
+
14
+ const todaysAvailability = days.find(item => item.day === today)
15
+ const todaysDateTimeOpen = DateTime.local(Number(dateParts[2]), Number(dateParts[1]), Number(dateParts[0]), getHour(todaysAvailability.openTime))
16
+ const todaysDateTimeClose = DateTime.local(Number(dateParts[2]), Number(dateParts[1]), Number(dateParts[0]), getHour(todaysAvailability.closeTime))
17
+
18
+ return now.diff(todaysDateTimeOpen).milliseconds >= 0 && now.diff(todaysDateTimeClose).milliseconds <= 0
11
19
  }
12
20
 
13
21
  module.exports = {
@@ -9,8 +9,6 @@ export default {
9
9
  client: path.join(__dirname, 'src/client/index.jsx'),
10
10
  server: path.join(__dirname, 'src/server/index.js')
11
11
  },
12
- devtool: 'source-map',
13
- mode: 'development',
14
12
  output: {
15
13
  path: path.resolve(__dirname, 'dist'),
16
14
  library: {
@@ -0,0 +1,7 @@
1
+ import { merge } from 'webpack-merge'
2
+
3
+ import common from './webpack.config.mjs'
4
+
5
+ export default merge(common, {
6
+ mode: 'production'
7
+ })
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","mappings":";;;;;;;;;;;;;;;;;;AAA0D;AACT;AACgC;AAE1E,SAASO,YAAYA,CAAEC,KAAK,EAAE;EACnC,MAAM,CAACC,MAAM,EAAEC,OAAO,CAAC,GAAGJ,yEAAmB,CAAC,CAAC;EAC/C,MAAM,CAACK,OAAO,EAAEC,QAAQ,CAAC,GAAGT,+CAAQ,CAAC,KAAK,CAAC;EAC3C,MAAMU,SAAS,GAAGX,6CAAM,CAAC,CAAC;EAC1B,MAAMY,OAAO,GAAGA,CAAA,KAAM;IACpBJ,OAAO,CAAC,CAAC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;EACpC,CAAC,CAAC,OAAOkD,CAAC,EAAE;IACVlD,YAAY,GAAG,aAAa;EAC9B;EACA+C,IAAI,CAACI,MAAM,eAAC3F,0DAAA,CAACO,mFAAY;IAACiC,YAAY,EAAEA;EAAa,CAAE,CAAC,CAAC;AAC3D,C","sources":["webpack://@defra/flood-webchat/./src/client/components/availability/availability.jsx","webpack://@defra/flood-webchat/./src/client/lib/check-availability.js","webpack://@defra/flood-webchat/./src/client/lib/classnames.js","webpack://@defra/flood-webchat/./src/client/lib/external-stores.js","webpack://@defra/flood-webchat/./src/client/lib/external-sync-store.js","webpack://@defra/flood-webchat/external commonjs \"react\"","webpack://@defra/flood-webchat/external commonjs \"react-dom/client\"","webpack://@defra/flood-webchat/webpack/bootstrap","webpack://@defra/flood-webchat/webpack/runtime/compat get default export","webpack://@defra/flood-webchat/webpack/runtime/define property getters","webpack://@defra/flood-webchat/webpack/runtime/hasOwnProperty shorthand","webpack://@defra/flood-webchat/webpack/runtime/make namespace object","webpack://@defra/flood-webchat/./src/client/index.jsx"],"sourcesContent":["import React, { useEffect, useRef, useState } from 'react'\nimport { classnames } from '../../lib/classnames'\nimport { useMessageThread, useWebchatOpenState } from '../../lib/external-stores'\n\nexport function Availability (props) {\n const [isOpen, setOpen] = useWebchatOpenState()\n const [isFixed, setFixed] = useState(false)\n const buttonRef = useRef()\n const onClick = () => {\n setOpen(!isOpen)\n }\n const onKeyDown = event => {\n if (event.key === ' ') {\n event.preventDefault()\n }\n }\n const onKeyUp = event => {\n if (event.key === ' ') {\n setOpen(!isOpen)\n }\n }\n\n const intersectionCallback = entries => {\n const [entry] = entries\n const isBelowFold = !entry.isIntersecting && entry.boundingClientRect.top > 0\n setFixed(!isOpen && isBelowFold)\n }\n\n useEffect(() => {\n const observer = new window.IntersectionObserver(intersectionCallback, {\n rootMargin: '35px'\n })\n const parentElement = buttonRef.current?.parentElement\n if (parentElement) {\n observer.observe(parentElement)\n }\n return () => {\n if (parentElement) {\n observer.unobserve(parentElement)\n }\n }\n }, [buttonRef, isOpen])\n\n useEffect(() => {\n document.documentElement.classList.toggle('wc-scroll-padding', isFixed)\n document.body.classList.toggle('wc-scroll-padding', isFixed)\n }, [isFixed])\n\n switch (props.availability) {\n case 'AVAILABLE':\n return (\n <div\n className={classnames('wc-availability', isFixed && 'wc-availability--fixed')}\n ref={buttonRef}\n >\n <div className='wc-availability__inner'>\n <a\n className='wc-availability__link'\n href='#webchat' role='button' draggable='false'\n onClick={onClick}\n onKeyUp={onKeyUp}\n onKeyDown={onKeyDown}\n >\n <AvailabilityContent />\n </a>\n </div>\n </div>\n )\n case 'EXISTING':\n case 'UNAVAILABLE':\n return (\n <p className='govuk-body'>When it is available, a 'start chat' link will appear.</p>\n )\n default:\n return (\n <p className='govuk-body'>Checking availability</p>\n )\n }\n}\n\nfunction AvailabilityContent () {\n const [thread] = useMessageThread()\n const unreadMessageCount = thread.filter(message => !message.read).length\n if (!thread.length) {\n return (\n <>\n Start Chat\n </>\n )\n }\n return (\n <>\n Show Chat {!!unreadMessageCount && (\n <>\n <span className='wc-availability__unseen'>{unreadMessageCount}</span>\n <span className='govuk-visually-hidden'> {unreadMessageCount === 1 ? 'new message' : 'new messages'}</span>\n </>\n )}\n </>\n )\n}\n","export async function checkAvailability (endpoint) {\n const response = await fetch(endpoint)\n const data = await response.json()\n return {\n availability: data.availability || 'UNAVAILABLE'\n }\n}\n","export const classnames = (...classes) => classes.filter(classname => classname && typeof classname === 'string').join(' ')\n","import ExternalSyncStore from './external-sync-store'\n\nexport const useWebchatOpenState = ExternalSyncStore.create(false)\nexport const useMessageThread = ExternalSyncStore.create([])\n","import { useSyncExternalStore } from 'react'\n\nexport default class ExternalSyncStore {\n constructor (initialValue) {\n this._value = initialValue\n this._listeners = []\n }\n\n update (value) {\n this._value = value\n this.emitChange()\n }\n\n subscribe (listener) {\n this._listeners = [...this._listeners, listener]\n return () => {\n this._listeners = this._listeners.filter(l => l !== listener)\n }\n }\n\n emitChange () {\n for (const listener of this._listeners) {\n listener()\n }\n }\n\n getSnapshot () {\n return this._value\n }\n\n static create (initialValue) {\n const store = new ExternalSyncStore(initialValue)\n const boundSubscribe = store.subscribe.bind(store)\n const boundGetSnapshot = store.getSnapshot.bind(store)\n const boundUpdate = store.update.bind(store)\n\n return () => [\n useSyncExternalStore(boundSubscribe, boundGetSnapshot),\n boundUpdate\n ]\n }\n}\n","module.exports = require(\"react\");","module.exports = require(\"react-dom/client\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { Availability } from './components/availability/availability.jsx'\nimport { checkAvailability } from './lib/check-availability'\n\nexport async function init (container, options) {\n const root = createRoot(container)\n let availability\n try {\n const result = await checkAvailability(options.availabilityEndpoint)\n availability = result.availability\n } catch (e) {\n availability = 'UNAVAILABLE'\n }\n root.render(<Availability availability={availability} />)\n}\n"],"names":["React","useEffect","useRef","useState","classnames","useMessageThread","useWebchatOpenState","Availability","props","isOpen","setOpen","isFixed","setFixed","buttonRef","onClick","onKeyDown","event","key","preventDefault","onKeyUp","intersectionCallback","entries","entry","isBelowFold","isIntersecting","boundingClientRect","top","observer","window","IntersectionObserver","rootMargin","parentElement","current","observe","unobserve","document","documentElement","classList","toggle","body","availability","createElement","className","ref","href","role","draggable","AvailabilityContent","thread","unreadMessageCount","filter","message","read","length","Fragment","checkAvailability","endpoint","response","fetch","data","json","classes","classname","join","ExternalSyncStore","create","useSyncExternalStore","constructor","initialValue","_value","_listeners","update","value","emitChange","subscribe","listener","l","getSnapshot","store","boundSubscribe","bind","boundGetSnapshot","boundUpdate","createRoot","init","container","options","root","result","availabilityEndpoint","e","render"],"sourceRoot":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"server.js","mappings":";;;;;;;;;AAAA,MAAM;EAAEA,YAAY;EAAEC,aAAa;EAAEC,SAAS;EAAEC;AAAY,CAAC,GAAGC,mBAAO,CAAC,mDAAiB,CAAC;;AAE1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACAC,MAAM,CAACC,OAAO,GAAG,eAAeC,eAAeA,CAAE;EAC/CC,QAAQ;EACRC,YAAY;EACZC,SAAS;EACTC,YAAY;EACZC,aAAa;EACbC,aAAa;EACbC,aAAa;EACbC,YAAY,GAAG,iEAAiE;EAChFC,iBAAiB,GAAG;AACtB,CAAC,EAAE;EACD,MAAMC,aAAa,GAAG,QAAQ,GAAGC,MAAM,CAACC,IAAI,CAAE,GAAEC,kBAAkB,CAACZ,QAAQ,CAAE,IAAGY,kBAAkB,CAACX,YAAY,CAAE,EAA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IV,GAAG,CAACc,OAAO,CAAC,CAAC,IAAItD,IAAI,CAACuD,KAAK,CAACH,KAAK,CAAC;AAChF,CAAC;AAEDnF,MAAM,CAACC,OAAO,GAAG;EACfkC;AACF,CAAC;;;;;;;;;;;ACdD;;;;;;;;;;;ACAA;;;;;;;;;;;ACAA;;;;;;UCAA;UACA;;UAEA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;UAEA;UACA;;UAEA;UACA;UACA;;;;UEtBA;UACA;UACA;UACA","sources":["webpack://@defra/flood-webchat/./src/server/index.js","webpack://@defra/flood-webchat/./src/server/lib/client.js","webpack://@defra/flood-webchat/./src/server/lib/utils.js","webpack://@defra/flood-webchat/external commonjs \"axios\"","webpack://@defra/flood-webchat/external commonjs \"jwt-decode\"","webpack://@defra/flood-webchat/external commonjs \"querystring\"","webpack://@defra/flood-webchat/webpack/bootstrap","webpack://@defra/flood-webchat/webpack/before-startup","webpack://@defra/flood-webchat/webpack/startup","webpack://@defra/flood-webchat/webpack/after-startup"],"sourcesContent":["const { authenticate, getApiBaseUrl, getIsOpen, getActivity } = require('./lib/client.js')\n\n/**\n * Returns webchat availability\n * @param options {object}\n * @param options.clientId {string}\n * @param options.clientSecret {string}\n * @param options.accessKey {string}\n * @param options.accessSecret {string}\n * @param options.skillEndpoint {string}\n * @param options.hoursEndpoint {string}\n * @param options.authenticationUri {string}\n * @param options.wellKnownUri {string}\n * @param options.maxQueueCount {string}\n * @returns {Promise<{date: Date, availability: (string)}>}\n */\nmodule.exports = async function getAvailability ({\n clientId,\n clientSecret,\n accessKey,\n accessSecret,\n maxQueueCount,\n skillEndpoint,\n hoursEndpoint,\n wellKnownUri = 'https://cxone.niceincontact.com/.well-known/cxone-configuration',\n authenticationUri = 'https://cxone.niceincontact.com/auth/token'\n}) {\n const authorisation = 'Basic ' + Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString('base64')\n\n // Cache authentication and re-authenticate when needed (lasts 1 hour?)\n const { tenantId, token, tokenType } = await authenticate({\n authenticationUri,\n authorisation,\n accessKey,\n accessSecret\n })\n\n const apiBaseUrl = await getApiBaseUrl({ wellKnownUri, tenantId })\n\n const [{ hasCapacity, hasAgentsAvailable }, isOpen] = await Promise.all([\n getActivity({ baseUrl: apiBaseUrl, tokenType, token, skillEndpoint, maxQueueCount }),\n getIsOpen({ baseUrl: apiBaseUrl, token, tokenType, hoursEndpoint })\n ])\n\n const isAvailable = isOpen && hasAgentsAvailable && hasCapacity\n const isExistingOnly = isOpen && hasAgentsAvailable && !hasCapacity\n\n let availability = 'UNAVAILABLE'\n\n if (isAvailable) {\n availability = 'AVAILABLE'\n } else if (isExistingOnly) {\n availability = 'EXISTING'\n }\n\n return {\n date: new Date(),\n availability\n }\n}\n","const querystring = require('querystring')\nconst axios = require('axios')\nconst jwtdecode = require('jwt-decode')\nconst { isWithinHours } = require('./utils.js')\n\nconst contentType = 'application/x-www-form-urlencoded'\n\nconst authenticate = async ({ authenticationUri, authorisation, accessKey, accessSecret }) => {\n const url = new URL(authenticationUri)\n const body = querystring.stringify({\n grant_type: 'password',\n username: accessKey,\n password: accessSecret\n })\n\n const auth = await axios.post(url.href, body, {\n signal: AbortSignal.timeout(3000),\n headers: {\n Host: url.host,\n 'Content-Type': contentType,\n Authorization: authorisation\n }\n })\n\n return {\n token: auth.data.access_token,\n tokenType: auth.data.token_type,\n tenantId: jwtdecode(auth.data.id_token)?.tenantId\n }\n}\n\nconst getApiBaseUrl = async ({ wellKnownUri, tenantId }) => {\n const url = new URL(wellKnownUri)\n url.searchParams.set('tenantId', tenantId)\n\n const { data } = await axios.get(url.href, {\n headers: {\n Host: url.host\n },\n signal: AbortSignal.timeout(3000)\n })\n\n return data.api_endpoint\n}\n\nconst getActivity = async ({ tokenType, token, baseUrl, skillEndpoint, maxQueueCount }) => {\n const url = new URL(skillEndpoint, baseUrl)\n\n const skill = await axios.get(url.href, {\n signal: AbortSignal.timeout(3000),\n headers: {\n Host: url.host,\n Authorization: `${tokenType} ${token}`,\n 'Content-Type': contentType\n }\n })\n\n const activity = skill.data.skillActivity[0]\n\n return {\n hasCapacity: activity.queueCount < maxQueueCount,\n hasAgentsAvailable: activity.agentsAvailable >= 1\n }\n}\n\nconst getIsOpen = async ({ baseUrl, token, tokenType, hoursEndpoint }) => {\n const url = new URL(hoursEndpoint, baseUrl)\n\n const hours = await axios.get(url.href, {\n signal: AbortSignal.timeout(3000),\n headers: {\n Host: url.host,\n Authorization: `${tokenType} ${token}`,\n 'Content-Type': contentType\n }\n })\n\n const days = hours.data.resultSet.hoursOfOperationProfiles[0].days\n\n return isWithinHours(days)\n}\n\nmodule.exports = {\n authenticate,\n getApiBaseUrl,\n getIsOpen,\n getActivity\n}\n","const isWithinHours = (days, date = null) => {\n const now = date ? new Date(date) : new Date()\n\n const name = now.toLocaleDateString('en-GB', { weekday: 'long' })\n const day = days.find(d => d.day.toLowerCase() === name.toLowerCase())\n const dateItems = now.toLocaleDateString('en-GB').split('/')\n const open = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.openTime}`\n const close = `${dateItems[2]}-${dateItems[1]}-${dateItems[0]}T${day.closeTime}`\n\n return now.getTime() >= Date.parse(open) && now.getTime() <= Date.parse(close)\n}\n\nmodule.exports = {\n isWithinHours\n}\n","module.exports = require(\"axios\");","module.exports = require(\"jwt-decode\");","module.exports = require(\"querystring\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(\"./src/server/index.js\");\n",""],"names":["authenticate","getApiBaseUrl","getIsOpen","getActivity","require","module","exports","getAvailability","clientId","clientSecret","accessKey","accessSecret","maxQueueCount","skillEndpoint","hoursEndpoint","wellKnownUri","authenticationUri","authorisation","Buffer","from","encodeURIComponent","toString","tenantId","token","tokenType","apiBaseUrl","hasCapacity","hasAgentsAvailable","isOpen","Promise","all","baseUrl","isAvailable","isExistingOnly","availability","date","Date","querystring","axios","jwtdecode","isWithinHours","contentType","url","URL","body","stringify","grant_type","username","password","auth","post","href","signal","AbortSignal","timeout","headers","Host","host","Authorization","data","access_token","token_type","id_token","searchParams","set","get","api_endpoint","skill","activity","skillActivity","queueCount","agentsAvailable","hours","days","resultSet","hoursOfOperationProfiles","now","name","toLocaleDateString","weekday","day","find","d","toLowerCase","dateItems","split","open","openTime","close","closeTime","getTime","parse"],"sourceRoot":""}
@@ -1,4 +0,0 @@
1
- import ExternalSyncStore from './external-sync-store'
2
-
3
- export const useWebchatOpenState = ExternalSyncStore.create(false)
4
- export const useMessageThread = ExternalSyncStore.create([])
@@ -1,42 +0,0 @@
1
- import { useSyncExternalStore } from 'react'
2
-
3
- export default class ExternalSyncStore {
4
- constructor (initialValue) {
5
- this._value = initialValue
6
- this._listeners = []
7
- }
8
-
9
- update (value) {
10
- this._value = value
11
- this.emitChange()
12
- }
13
-
14
- subscribe (listener) {
15
- this._listeners = [...this._listeners, listener]
16
- return () => {
17
- this._listeners = this._listeners.filter(l => l !== listener)
18
- }
19
- }
20
-
21
- emitChange () {
22
- for (const listener of this._listeners) {
23
- listener()
24
- }
25
- }
26
-
27
- getSnapshot () {
28
- return this._value
29
- }
30
-
31
- static create (initialValue) {
32
- const store = new ExternalSyncStore(initialValue)
33
- const boundSubscribe = store.subscribe.bind(store)
34
- const boundGetSnapshot = store.getSnapshot.bind(store)
35
- const boundUpdate = store.update.bind(store)
36
-
37
- return () => [
38
- useSyncExternalStore(boundSubscribe, boundGetSnapshot),
39
- boundUpdate
40
- ]
41
- }
42
- }