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

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 (48) 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 +28 -21
  6. package/src/client/components/availability/availability.jsx +104 -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 +16 -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 +184 -0
  37. package/src/client/store/actions-map.js +153 -0
  38. package/src/client/store/constants.js +5 -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/utils.js +25 -9
  43. package/webpack.config.mjs +0 -2
  44. package/webpack.prod.mjs +7 -0
  45. package/dist/client.js.map +0 -1
  46. package/dist/server.js.map +0 -1
  47. package/src/client/lib/external-stores.js +0 -4
  48. package/src/client/lib/external-sync-store.js +0 -42
@@ -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
+ }
@@ -0,0 +1,184 @@
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, MESSAGES_UNSEEN_COUNT } 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
+ setUnseenCount(window.localStorage.getItem(MESSAGES_UNSEEN_COUNT))
92
+ }, [])
93
+
94
+ /**
95
+ * Set browser history on start chat click
96
+ */
97
+ useEffect(() => {
98
+ if (window.location.hash === '#webchat') {
99
+ setChatVisibility(true)
100
+ }
101
+
102
+ const onBrowserNavigation = () => {
103
+ if (window.location.hash === '#webchat') {
104
+ setChatVisibility(true)
105
+ } else {
106
+ setChatVisibility(false)
107
+ }
108
+ }
109
+
110
+ window.addEventListener('popstate', onBrowserNavigation)
111
+
112
+ return () => {
113
+ window.removeEventListener('popstate', onBrowserNavigation)
114
+ }
115
+ }, [])
116
+
117
+ /**
118
+ * State update functions
119
+ */
120
+ const setChatVisibility = payload => {
121
+ dispatch({ type: 'SET_CHAT_VISIBILITY', payload })
122
+ }
123
+
124
+ const setCustomerId = customerId => {
125
+ dispatch({ type: 'SET_CUSTOMER_ID', payload: customerId })
126
+ }
127
+
128
+ const setThreadId = threadId => {
129
+ dispatch({ type: 'SET_THREAD_ID', payload: threadId })
130
+ }
131
+
132
+ const setThread = thread => {
133
+ dispatch({ type: 'SET_THREAD', payload: thread })
134
+ }
135
+
136
+ const setMessages = messages => {
137
+ dispatch({ type: 'SET_MESSAGES', payload: messages })
138
+ }
139
+
140
+ const setSettings = data => {
141
+ dispatch({ type: 'SET_SETTINGS', payload: data })
142
+ }
143
+
144
+ const setUnseenCount = unseenCount => {
145
+ dispatch({ type: 'SET_UNSEEN_COUNT', payload: unseenCount })
146
+ }
147
+
148
+ const setInstigatorId = id => {
149
+ dispatch({ type: 'SET_INSTIGATOR_ID', payload: id })
150
+ }
151
+
152
+ const setLiveRegionText = text => {
153
+ dispatch({ type: 'SET_LIVE_REGION_TEXT', payload: text })
154
+ }
155
+
156
+ /**
157
+ * Application-wide state and state functions
158
+ */
159
+ const store = useMemo(() => ({
160
+ ...state,
161
+ sdk,
162
+ setSettings,
163
+ setCustomerId,
164
+ setThreadId,
165
+ setThread,
166
+ setMessages,
167
+ setUnseenCount,
168
+ setChatVisibility,
169
+ setInstigatorId,
170
+ setLiveRegionText,
171
+ onLiveChatRecovered,
172
+ onAssignedAgentChanged,
173
+ onAgentTypingStarted,
174
+ onAgentTypingEnded,
175
+ onMessageCreated,
176
+ onContactStatusChanged
177
+ }))
178
+
179
+ return (
180
+ <AppContext.Provider value={store}>
181
+ {children}
182
+ </AppContext.Provider>
183
+ )
184
+ }
@@ -0,0 +1,153 @@
1
+ import { transformMessages, transformMessage } from '../lib/transform-messages'
2
+ import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY, MESSAGES_UNSEEN_COUNT } 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
+ window.localStorage.setItem(MESSAGES_UNSEEN_COUNT, payload)
102
+ return {
103
+ ...state,
104
+ unseenCount: payload
105
+ }
106
+ }
107
+
108
+ const setInstigatorId = (state, payload) => {
109
+ return {
110
+ ...state,
111
+ instigatorId: payload
112
+ }
113
+ }
114
+
115
+ const setLiveRegionText = (state, payload) => {
116
+ return {
117
+ ...state,
118
+ liveRegionText: payload
119
+ }
120
+ }
121
+
122
+ const toggleIsMobile = (state, payload) => {
123
+ return {
124
+ ...state,
125
+ isMobile: payload
126
+ }
127
+ }
128
+
129
+ const toggleIsKeyboard = (state, payload) => {
130
+ return {
131
+ ...state,
132
+ isKeyboard: payload
133
+ }
134
+ }
135
+
136
+ export const actionsMap = {
137
+ SET_CHAT_VISIBILITY: setChatVisibility,
138
+ SET_AVAILABILITY: setAvailability,
139
+ SET_SETTINGS: setSettings,
140
+ SET_CUSTOMER_ID: setCustomerId,
141
+ SET_THREAD_ID: setThreadId,
142
+ SET_THREAD: setThread,
143
+ SET_MESSAGE: setMessage,
144
+ SET_MESSAGES: setMessages,
145
+ SET_AGENT: setAgent,
146
+ SET_AGENT_TYPING: setAgentIsTyping,
147
+ SET_AGENT_STATUS: setAgentStatus,
148
+ SET_UNSEEN_COUNT: setUnseenCount,
149
+ SET_INSTIGATOR_ID: setInstigatorId,
150
+ SET_LIVE_REGION_TEXT: setLiveRegionText,
151
+ TOGGLE_IS_MOBILE: toggleIsMobile,
152
+ TOGGLE_IS_KEYBOARD: toggleIsKeyboard
153
+ }
@@ -0,0 +1,5 @@
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
5
+ export const MESSAGES_UNSEEN_COUNT = 'message_unseen_count'
@@ -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,15 +1,31 @@
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
19
+ }
20
+
21
+ const stripPageTitle = title => {
22
+ const prefixPattern = /^\(\d+ new messages?\) - /
23
+
24
+ return title.replace(prefixPattern, '')
11
25
  }
12
26
 
13
27
  module.exports = {
14
- isWithinHours
28
+ isWithinHours,
29
+ stripPageTitle
30
+
15
31
  }
@@ -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,CAACD,MAAM,CAAC;EAClB,CAAC;EACD,MAAMM,SAAS,GAAGC,KAAK,IAAI;IACzB,IAAIA,KAAK,CAACC,GAAG,KAAK,GAAG,EAAE;MACrBD,KAAK,CAACE,cAAc,CA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AAEA;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":""}