@defra/flood-webchat 1.0.11 → 1.0.12
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.
- package/dist/client.js +1 -1
- package/dist/server.js +1 -1
- package/package.json +12 -12
- package/src/client/components/availability/availability.jsx +1 -11
- package/src/client/components/chat/chat.jsx +6 -10
- package/src/client/components/panel/panel-header.jsx +3 -3
- package/src/client/components/panel/panel.scss +1 -1
- package/src/client/lib/history.js +0 -4
- package/src/client/store/AppProvider.jsx +1 -2
- package/src/client/store/actions-map.js +1 -2
- package/src/client/store/constants.js +0 -1
- package/src/server/lib/client.js +2 -2
- package/src/server/lib/utils.js +1 -7
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var e={792:(e,t,a)=>{const{DateTime:n}=a(168),o=e=>Number(e.split(":")[0]);e.exports={isWithinHours:(e,t)=>{const a=t?n.fromISO(t):n.local();a.setZone("Europe/London");const l=t?new Date(t):new Date,r=l.toLocaleDateString("en-GB",{weekday:"long"}),s=l.toLocaleDateString("en-GB").split("/"),c=e.find((e=>e.day===r)),i=n.local(Number(s[2]),Number(s[1]),Number(s[0]),o(c.openTime)),u=n.local(Number(s[2]),Number(s[1]),Number(s[0]),o(c.closeTime));return a.diff(i).milliseconds>=0&&a.diff(u).milliseconds<=0},stripPageTitle:e=>e.replace(/^\(\d+ new messages?\) - /,"")}},168:e=>{"use strict";e.exports=require("luxon")}},t={};function a(n){var o=t[n];if(void 0!==o)return o.exports;var l=t[n]={exports:{}};return e[n](l,l.exports,a),l.exports}a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";a.r(n),a.d(n,{init:()=>ne});const e=require("react");var t=a.n(e);const o=require("react-dom/client"),l=require("@nice-devone/nice-cxone-chat-web-sdk"),r=(...e)=>e.filter((e=>e&&"string"==typeof e)).join(" "),s=require("react-dom");var c=a(168);const i=require("html-react-parser");var u=a.n(i);const d=/(?:www|https?)[^\s]+/gi,m=e=>(e.match(d)&&(e=e.replace(d,(e=>`<a class="govuk-link" href="${e}" target="_blank" rel="noreferrer">${e.replace(/https?:\/\//gi,"")}</a>`))),u()(e)),g=e=>({id:e.id,text:e.messageContent?.text,createdAt:new Date(e.createdAt),user:e.authorEndUserIdentity?.fullName?.trim()||null,assignee:e.authorUser?.firstName||null,direction:e.direction}),h=e=>{const t=c.DateTime.local();t.setZone("Europe/London");let a=`Floodline webchat transcript, ${t.toFormat("HH:mm:ss a, dd LLLL yyyy")}\n\n`;for(const t of e){const{text:e,direction:n,user:o,assignee:l,createdAt:r}=t,s="inbound"===n?o:`${l} (Floodline adviser)`;a+=`[${c.DateTime.fromJSDate(new Date(r)).setZone("Europe/London").toFormat("HH:mm:ss a, dd LLLL yyyy")}] ${s}: \n${e}\n\n`}return a=a.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i,""),encodeURIComponent(a)},E="webchat_settings",w="webchat_customer_id",v="webchat_thread_id",b=4e3,y="message_unseen_count",f={SET_CHAT_VISIBILITY:(e,t)=>({...e,isChatOpen:t}),SET_AVAILABILITY:(e,t)=>({...e,availability:t}),SET_SETTINGS:(e,t)=>(t?window.localStorage.setItem(E,JSON.stringify(t)):window.localStorage.removeItem(E),{...e,settings:t}),SET_CUSTOMER_ID:(e,t)=>(t?window.localStorage.setItem(w,t):window.localStorage.removeItem(w),{...e,customerId:t}),SET_THREAD_ID:(e,t)=>(t?window.localStorage.setItem(v,t):window.localStorage.removeItem(v),{...e,threadId:t}),SET_THREAD:(e,t)=>({...e,thread:t}),SET_MESSAGE:(e,t)=>({...e,message:g(t),messages:[...e.messages,g(t)]}),SET_MESSAGES:(e,t)=>{return{...e,messages:(a=t,a.map((e=>g(e)))).reverse()};var a},SET_AGENT:(e,t)=>({...e,agent:t}),SET_AGENT_TYPING:(e,t)=>({...e,isAgentTyping:t}),SET_AGENT_STATUS:(e,t)=>({...e,agentStatus:t}),SET_UNSEEN_COUNT:(e,t)=>(window.localStorage.setItem(y,t),{...e,unseenCount:t}),SET_INSTIGATOR_ID:(e,t)=>({...e,instigatorId:t}),SET_LIVE_REGION_TEXT:(e,t)=>({...e,liveRegionText:t}),TOGGLE_IS_MOBILE:(e,t)=>({...e,isMobile:t}),TOGGLE_IS_KEYBOARD:(e,t)=>({...e,isKeyboard:t})},p={availability:null,customerId:null,threadId:null,thread:null,messages:[],unseenCount:0,instigatorId:null,agent:null,agentStatus:null,isAgentTyping:!1,isChatOpen:!1,isMobile:window.matchMedia("(max-width: 640px)").matches,isKeyboard:!1,settings:{audio:!0,scroll:!0}},k=(e,t)=>{const{type:a,payload:n}=t,o=f[a];return o?o.bind(void 0,e,n)():e},S=(0,e.createContext)(p),_=({sdk:a,availability:n,playSound:o,children:r})=>{const[s,c]=(0,e.useReducer)(k,p),i=e=>{c({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),c({type:"SET_AGENT_STATUS",payload:e.detail.data.contact.status}),c({type:"SET_UNSEEN_COUNT",payload:e.detail.data.contact.customerStatistics.unseenMessagesCount})},u=e=>{c({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),c({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},d=()=>{c({type:"SET_AGENT_TYPING",payload:!0})},m=()=>{c({type:"SET_AGENT_TYPING",payload:!1}),c({type:"SET_LIVE_REGION_TEXT"})},g=e=>{c({type:"SET_MESSAGE",payload:e.detail.data.message}),c({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status}),c({type:"SET_UNSEEN_COUNT",payload:e.detail.data.case.customerStatistics.unseenMessagesCount}),JSON.parse(window.localStorage.getItem(E)).audio&&"outbound"===e.detail.data.message.direction&&o&&o()},h=e=>{c({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},b=e=>{c({type:"TOGGLE_IS_MOBILE",payload:e.matches})},f=()=>{c({type:"TOGGLE_IS_KEYBOARD",payload:!0})},_=()=>{c({type:"TOGGLE_IS_KEYBOARD",payload:!1})};(0,e.useEffect)((()=>(a.onChatEvent(l.ChatEvent.LIVECHAT_RECOVERED,i),a.onChatEvent(l.ChatEvent.MESSAGE_CREATED,g),a.onChatEvent(l.ChatEvent.AGENT_TYPING_STARTED,d),a.onChatEvent(l.ChatEvent.AGENT_TYPING_ENDED,m),a.onChatEvent(l.ChatEvent.ASSIGNED_AGENT_CHANGED,u),a.onChatEvent(l.ChatEvent.CONTACT_STATUS_CHANGED,h),window.matchMedia("(max-width: 640px)").addEventListener("change",b),window.addEventListener("keydown",f),window.addEventListener("pointerdown",_),()=>{window.removeEventListener("change",b),window.removeEventListener("keydown",f),window.removeEventListener("pointerdown",_)})),[a]),(0,e.useEffect)((()=>{c({type:"SET_AVAILABILITY",payload:n}),T(window.localStorage.getItem(w)),C(window.localStorage.getItem(v)),A(JSON.parse(window.localStorage.getItem(E))||s.settings),x(window.localStorage.getItem(y))}),[]),(0,e.useEffect)((()=>{"#webchat"===window.location.hash&&N(!0);const e=()=>{"#webchat"===window.location.hash?N(!0):N(!1)};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}}),[]);const N=e=>{c({type:"SET_CHAT_VISIBILITY",payload:e})},T=e=>{c({type:"SET_CUSTOMER_ID",payload:e})},C=e=>{c({type:"SET_THREAD_ID",payload:e})},I=e=>{c({type:"SET_THREAD",payload:e})},L=e=>{c({type:"SET_MESSAGES",payload:e})},A=e=>{c({type:"SET_SETTINGS",payload:e})},x=e=>{c({type:"SET_UNSEEN_COUNT",payload:e})},D=e=>{c({type:"SET_INSTIGATOR_ID",payload:e})},G=e=>{c({type:"SET_LIVE_REGION_TEXT",payload:e})},q=(0,e.useMemo)((()=>({...s,sdk:a,setSettings:A,setCustomerId:T,setThreadId:C,setThread:I,setMessages:L,setUnseenCount:x,setChatVisibility:N,setInstigatorId:D,setLiveRegionText:G,onLiveChatRecovered:i,onAssignedAgentChanged:u,onAgentTypingStarted:d,onAgentTypingEnded:m,onMessageCreated:g,onContactStatusChanged:h})));return t().createElement(S.Provider,{value:q},r)},N=()=>(0,e.useContext)(S),{stripPageTitle:T}=a(792),C=()=>{const e=window.location.href.split("#")[0];document.title=T(document.title),window.history.pushState({history:!0},null,`${e}#webchat`)},I=()=>{if(window.history.state?.history)return window.history.back();document.title=T(document.title);const e=window.location.href.split("#")[0];return window.history.replaceState(null,null,e)};function L(){const{thread:e,threadId:a,setChatVisibility:n,setUnseenCount:o,isMobile:l}=N(),r=t=>{t.preventDefault(),n(!1),I(),a&&(e?.lastMessageSeen(),o(0))},s=t().createElement("button",{className:"wc-header__back","aria-label":"Close the webchat",onClick:r},t().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},t().createElement("path",{d:"M4.828,11L12.314,18.485L10.899,19.899L1,10L10.899,0.101L12.314,1.515L4.828,9L19,9L19,11L4.828,11Z",fill:"currentColor"}))),c=t().createElement("button",{className:"wc-header__close","aria-label":"Close the webchat",onClick:r},t().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},t().createElement("path",{d:"M10,8.6L15.6,3L17,4.4L11.4,10L17,15.6L15.6,17L10,11.4L4.4,17L3,15.6L8.6,10L3,4.4L4.4,3L10,8.6Z",fill:"currentColor"}))),i=t().createElement("button",{className:"wc-header__hide","aria-label":"Minimise the webchat",onClick:r},t().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},t().createElement("path",{d:"M10 14.4l-7-7L4.4 6l5.6 5.6L15.6 6 17 7.4l-7 7z",fill:"currentColor"}))),u=l&&window.history.state,d=l&&!window.history.state;let m=c;return a&&(m=i,d&&(m=i)),!a&&d&&(m=c),u&&(m=null),t().createElement("div",{className:"wc-header"},u?s:null,t().createElement("h2",{id:"wc-header",className:"wc-header__title"},"Floodline webchat"),m)}function A({onContinue:e}){return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("div",{className:"wc-content"},t().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"What you can use webchat for"),t().createElement("p",null,"Webchat lets you talk directly to a Floodline adviser."),t().createElement("p",null,"You can use webchat to get:"),t().createElement("ul",{className:"wc-list"},t().createElement("li",null,"current flood warnings and alerts in your area"),t().createElement("li",null,"information on the flood warning service"),t().createElement("li",null,"advice on what to do before, during and after a flood")),t().createElement("p",null,"There are other ways to ",t().createElement("a",{className:"govuk-link",href:"https://www.gov.uk/sign-up-for-flood-warnings",target:"_blank",rel:"noreferrer"},"sign up for flood warnings")," and ",t().createElement("a",{className:"govuk-link",href:"https://www.fws.environment-agency.gov.uk/app/olr/login",target:"_blank",rel:"noreferrer"},"manage your flood warnings account"),"."),t().createElement("p",null,"Do not use webchat to ",t().createElement("a",{className:"govuk-link",href:"https://www.gov.uk/report-flood-cause",target:"_blank",rel:"noreferrer"},"report a flood"),"."),t().createElement("button",{className:"govuk-button wc-button govuk-!-margin-top-1","data-module":"govuk-button",onClick:e},"Continue"),t().createElement("h3",{className:"wc-heading"},"Other flood information"),t().createElement("p",null,"Call Floodline for all other flood and flood warning information."),t().createElement("p",null,t().createElement("strong",null,"Floodline helpline"),t().createElement("br",null),"Telephone: 0345 988 1188",t().createElement("br",null),"Textphone: 0345 602 6340",t().createElement("br",null),"Open 24 hours a day, 7 days a week",t().createElement("br",null),t().createElement("a",{className:"govuk-link",href:"https://gov.uk/call-charges",target:"_blank",rel:"noreferrer"},"Find out more about call charges")))))}const x=require("uuid"),D=e=>{const t=async()=>e.authorize();return{connect:t,fetchCustomerId:async()=>{const e=await t();return e?.consumerIdentity.idOnExternalPlatform},fetchThread:async a=>(await t(),e.getThread(a)),fetchMessages:async(e,a)=>{await t();const n=await e.recover(a),o=[];let l=n.messages;for(;l.length;){l.map((e=>o.push(e)));try{l=(await e.loadMoreMessages()).data.messages}catch(e){l=[]}}return o}}},G=({errors:e})=>{const a=Object.keys(e),n=e=>{e.preventDefault();const t=e.target.getAttribute("data-key");document.querySelector(`#wc-${t}`).focus()};return 0===a.length?null:t().createElement("div",{className:"govuk-error-summary govuk-!-static-margin-bottom-7","data-module":"govuk-error-summary",tabIndex:"-1"},t().createElement("div",{role:"alert"},t().createElement("h2",{id:"wc-error",className:"wc-error-summary__title govuk-error-summary__title"},"There is a problem"),t().createElement("div",{className:"govuk-error-summary__body"},t().createElement("ul",{className:"govuk-list govuk-error-summary__list wc-error-summary__list"},a.map((a=>t().createElement("li",{key:a},t().createElement("a",{href:"#","data-key":a,onClick:n},e[a]))))))))},q=500;function O({onPreChatScreen:a}){const{sdk:n,setCustomerId:o,setThreadId:l,setThread:s,setLiveRegionText:c}=N(),{fetchCustomerId:i,fetchThread:u}=D(n),[d,m]=(0,e.useState)({}),[g,h]=(0,e.useState)(0),[E,w]=(0,e.useState)(!1),v=(0,e.useRef)(),b=(0,e.useRef)(),y=q>=g;let f=`You have ${q-g} characters remaining`;y||(f=`You have ${g-q} characters too many`),(0,e.useEffect)((()=>{Object.keys(d).length&&document.querySelector(".govuk-error-summary")?.focus()}),[d]);const p=E?"Requesting...":"Request chat";return(0,e.useEffect)((()=>{E&&c(p)}),[E]),t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("div",{className:"wc-content"},t().createElement("a",{href:"#",className:"wc-back-link govuk-back-link",onClick:a},"What you can use webchat for"),t().createElement(G,{errors:d}),t().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Your name and question"),t().createElement("form",null,t().createElement("div",{className:r("wc-form-group","govuk-form-group",d.name&&"govuk-form-group--error")},t().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-name"},"Your name"),d.name&&t().createElement("p",{className:"govuk-error-message"},t().createElement("span",{className:"govuk-visually-hidden"},"Error:")," ",d.name),t().createElement("input",{ref:v,className:r("wc-input","govuk-input",d.name&&"govuk-input--error"),id:"wc-name",name:"name",type:"text","data-testid":"request-chat-user-name"})),t().createElement("div",{className:"wc-form-group govuk-character-count","data-module":"govuk-character-count","data-maxlength":"500"},t().createElement("div",{className:r("govuk-form-group",d.question&&"govuk-form-group--error")},t().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-question"},"Your question"),d.question&&t().createElement("p",{className:"govuk-error-message"},t().createElement("span",{className:"govuk-visually-hidden"},"Error:"),d.question),t().createElement("textarea",{ref:b,id:"wc-question",name:"question",rows:"5","aria-describedby":"wc-question-info",onChange:e=>{h(e.target.value.length)},className:r("wc-textarea","govuk-textarea","govuk-js-character-count",!y||d.question?"govuk-textarea--error":""),"data-testid":"request-chat-user-question"}),t().createElement("div",{id:"wc-question-info",className:"wc-hint govuk-hint govuk-char-count__msg",style:{color:y?"":"#d4351c"},"aria-hidden":"true"},f),t().createElement("div",{className:"govuk-character-count__sr-status govuk-visually-hidden","aria-live":"polite"},f))),t().createElement("div",{className:"wc-inset-text govuk-inset-text"},"By selecting 'Request chat' you agree to the terms of our ",t().createElement("a",{href:"https://check-for-flooding.service.gov.uk/privacy-notice",target:"_blank",rel:"noreferrer",className:"govuk-link"},"privacy notice"),"."),t().createElement("button",{className:"wc-button govuk-button govuk-!-margin-top-1","data-module":"govuk-button",onClick:async e=>{if(e.preventDefault(),E)return;const t={};if(0===v.current.value.length&&(t.name="Enter your name"),0===b.current.value.length&&(t.question="Enter your question"),b.current.value.length>q&&(t.question="Your question must be 500 characters or less"),0===Object.keys(t).length)try{w(!0);const e=x.v4(),t=await i(),a=await u(e);n.getCustomer().setName(v.current.value),await a.startChat(b.current.value||"Begin conversation"),o(t),l(e),s(a),a.setCustomField("threadid",e)}catch(e){console.log("[Request chat Error]",e)}m(t)},"aria-disabled":E},p)))))}const M=require("lodash.debounce");var R=a.n(M);function F({children:e}){return t().createElement("div",{className:"wc-footer"},e)}function B({message:e,previousMessage:a}){const n="outbound"===e.direction,o=e?.direction===a?.direction;return t().createElement("li",{className:r("wc-chat__message",n?"outbound":"inbound")},t().createElement("div",{className:"wc-chat__from"},o?null:t().createElement("span",{className:r(n?"outbound":"inbound")},n?e.assignee:"You"),t().createElement("span",{className:"govuk-visually-hidden"},":")),t().createElement("div",{className:r("wc-chat__text",n?"outbound":"inbound")},m(e.text)))}const U=(t,a)=>{(0,e.useEffect)((()=>{if(t){t.style.height="0px";const e=t.scrollHeight;t.style.height=`${e}px`}}),[t,a])},$=(e,t,a)=>{if("UNAVAILABLE"===e)return"Webchat is not currently available";if(!t)return"Connecting to Floodline";switch(t){case"closed":case"resolved":return a?`${a} ended the session`:"Session ended by advisor";default:return a?`You are speaking with ${a}`:"Waiting for an adviser"}};function Y({onEndChatScreen:a,onSettingsScreen:n}){const{availability:o,thread:l,messages:r,agent:s,agentStatus:c,isAgentTyping:i,isChatOpen:u,settings:d,isKeyboard:m,setLiveRegionText:g}=N(),[E,w]=(0,e.useState)(""),[v,y]=(0,e.useState)(!1),f=(0,e.useRef)();U(f.current,E),(0,e.useEffect)((()=>{if(d.scroll&&0!==r.length){const e=document.querySelector(".wc-body");e.scrollTop=e.scrollHeight}}),[r,i]),(0,e.useEffect)((()=>{const e=document.querySelector(".wc-form__label");0===E.length?e.classList.remove("govuk-visually-hidden"):e.classList.add("govuk-visually-hidden")}),[E]);const p=s?.nickname||s?.firstName,k=$(o,c,p);(0,e.useEffect)((()=>(k&&g(`Floodline webchat - ${k}`),()=>{g()})),[k]),(0,e.useEffect)((()=>(i&&u&&g(`${p} is typing...`),()=>{g()})),[i,u]),(0,e.useEffect)((()=>{const e=r[r.length-1];return"closed"!==c&&"outbound"===e?.direction&&g(`${p} said: ${e.text}`),()=>{g()}}),[r]);const S=()=>{if(0!==f.current.value.length&&"closed"!==c){try{const e=f.current.value.trim();l.sendTextMessage(e),g(`You said: ${e}`)}catch(e){console.log("[Chat Error] sendMessage",e)}w("")}},_=()=>{const e=h(r);document.querySelector("#transcript-download").setAttribute("href",`data:text/plain;charset=utf-8,${e}`)},T=(0,e.useCallback)(R()((()=>{l.keystroke(),setTimeout((()=>{l.stopTyping()}),b)}),100),[l]),C=e=>{if("Enter"!==e.key||e.shiftKey)" "===e.key?("end-chat"===e.target.id&&a(e),"wc-settings"===e.target.id&&n(e)):T();else switch(e.target.id){case"text-area":e.preventDefault(),S();break;case"end-chat":a(e);break;case"wc-settings":n(e);break;case"transcript-download":_()}};return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-status"},t().createElement("p",{className:"wc-status__availability"},k),t().createElement("a",{id:"end-chat",className:"wc-status__link",href:"#","data-module":"govuk-button",role:"button",onClick:a,onKeyDown:C},"End chat")),t().createElement("div",{className:"wc-body",tabIndex:"0"},t().createElement("ul",{className:"wc-chat"},r.length?r.map(((e,a)=>t().createElement(B,{key:e.id,message:e,previousMessage:r[a-1]}))):null,i?t().createElement("li",{className:"wc-chat__message outbound"},t().createElement("div",{className:"wc-chat__from"},p," is typing"),t().createElement("div",{className:"wc-chat__text outbound"},t().createElement("svg",{width:"28",height:"16",x:"0px",y:"0px",viewBox:"0 0 28 16"},t().createElement("circle",{stroke:"none",cx:"3",cy:"8",r:"3",fill:"currentColor"}),t().createElement("circle",{stroke:"none",cx:"14",cy:"8",r:"3",fill:"currentColor"}),t().createElement("circle",{stroke:"none",cx:"25",cy:"8",r:"3",fill:"currentColor"})))):null)),t().createElement(F,null,t().createElement("form",{className:"wc-form"+(v?" wc-focus-within":""),noValidate:!0,onSubmit:e=>{e.preventDefault(),S()}},t().createElement("label",{className:"govuk-label wc-form__label",htmlFor:"wc-form-textarea"},"Your message",t().createElement("span",{className:"govuk-visually-hidden"}," (enter key submits)")),t().createElement("textarea",{ref:f,rows:"1","aria-required":"true",className:"wc-form__textarea",id:"text-area",name:"message",onChange:e=>{w(e.target?.value)},onKeyDown:C,onFocus:()=>{y(m)},onBlur:()=>{y(!1)},value:E}),t().createElement("input",{type:"submit",className:"wc-form__button govuk-button",value:"Send","data-prevent-double-click":"true"})),t().createElement("div",{className:"wc-footer__settings"},t().createElement("a",{href:"#",id:"wc-settings",className:"wc-footer__settings-link","data-module":"govuk-button",onKeyDown:C,onClick:n},"Settings"),t().createElement("a",{href:"#",id:"transcript-download",className:"wc-footer__settings-link","data-module":"govuk-button",download:"floodline-webchat-transcript.txt",onKeyDown:C,onClick:_},"Save chat"))))}function K(){return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("h3",{id:"wc-subtitle",className:"govuk-heading-m"},"Webchat is currently not available"),t().createElement("p",{className:"govuk-body-s"},"Try again later, or call Floodline:"),t().createElement("p",{className:"govuk-body-s"},t().createElement("strong",null,"Floodline helpline"),t().createElement("br",null),"Telephone: 0345 988 1188",t().createElement("br",null),"Textphone: 0345 602 6340",t().createElement("br",null),"Open 24 hours a day, 7 days a week",t().createElement("br",null),t().createElement("a",{className:"govuk-link",href:"https://gov.uk/call-charges"},"Find out more about call charges")),t().createElement("p",{className:"govuk-body-s"},"We're running webchat as a trial, it will not always be available.")))}function V({onChatScreen:a,onEndChatConfirm:n}){const{setCustomerId:o,setThreadId:l,setMessages:r,agentStatus:s,thread:c,threadId:i,setUnseenCount:u,isKeyboard:d}=N(),m=async e=>{e.preventDefault(),window.localStorage.setItem("tmpThreadId",i),l(),r([]),o(),c.lastMessageSeen(),u(0),"closed"!==s&&c.endChat(),n(e)};(0,e.useEffect)((()=>{d&&setTimeout((()=>{document.querySelector("#confirm-endchat").focus()}),10)}),[]);const g=e=>{"Enter"!==e.key&&" "!==e.key||"confirm-endchat"!==e.target.id||m(e),"Enter"!==e.key&&" "!==e.key||"resume-chat"!==e.target.id||a(e)};return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("div",{className:"wc-content"},t().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Are you sure you want to end the chat?"),t().createElement("div",{className:"govuk-button-group"},t().createElement("a",{id:"confirm-endchat",href:"#endChat",role:"button",className:"wc-button govuk-button","data-module":"govuk-button",onClick:m,onKeyDown:g},"Yes, end chat"),t().createElement("a",{id:"resume-chat",href:"#resumeChat",role:"button",className:"wc-link govuk-link","data-module":"govuk-button",onClick:a,onKeyDown:g},"No, resume chat")))))}function P({onCancel:a}){const{settings:n,setSettings:o}=N(),[l,r]=(0,e.useState)(n.audio),[s,c]=(0,e.useState)(n.scroll),i=e=>{e.preventDefault(),o({audio:l,scroll:s}),a(e)},u=e=>{"Enter"!==e.key&&" "!==e.key||"settings-save"!==e.target.id?"Enter"!==e.key&&" "!==e.key||"settings-cancel"!==e.target.id||a(e):i(e)};return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("div",{className:"wc-content"},t().createElement("fieldset",{className:"govuk-fieldset govuk-!-margin-bottom-4"},t().createElement("legend",{className:"govuk-fieldset__legend govuk-fieldset__legend"},t().createElement("h3",{id:"wc-subtitle",className:"wc-heading"},"Change settings")),t().createElement("div",{className:"govuk-checkboxes govuk-checkboxes--small","data-module":"govuk-checkboxes"},t().createElement("div",{className:"govuk-checkboxes__item"},t().createElement("input",{id:"audio",name:"audio",type:"checkbox",value:"audio",className:"govuk-checkboxes__input",defaultChecked:l,onChange:()=>r(!l)}),t().createElement("label",{className:"wc-label govuk-label govuk-checkboxes__label",htmlFor:"audio"},"Play a sound when receiving a new message")),t().createElement("div",{className:"govuk-checkboxes__item"},t().createElement("input",{id:"scroll",name:"scroll",type:"checkbox",value:"scroll",className:"govuk-checkboxes__input",defaultChecked:s,onChange:()=>c(!s)}),t().createElement("label",{className:"wc-label govuk-label govuk-checkboxes__label",htmlFor:"scroll"},"Scroll automatically to a new message")))),t().createElement("div",{className:"govuk-button-group"},t().createElement("a",{id:"settings-save",href:"#",className:"wc-button govuk-button","data-module":"govuk-button",role:"button",onClick:i,onKeyDown:u},"Save"),t().createElement("a",{id:"settings-cancel",href:"#",className:"wc-link govuk-link","data-module":"govuk-button",role:"button",onClick:a,onKeyDown:u},"Cancel")))))}function H({onCancel:e}){const a=()=>{const e=window.localStorage.getItem("tmpThreadId");window.location.href=`https://defragroup.eu.qualtrics.com/jfe/form/SV_8dgFSJcxxIfqx5Y?Id=${e}&Source=${window.location.href}`,window.localStorage.removeItem("tmpThreadId")},n=async t=>{window.localStorage.removeItem("tmpThreadId"),e(t)},o=e=>{"Enter"!==e.key&&" "!==e.key||("feedback-close"===e.target.id&&n(e),"feedback-send"===e.target.id&&a())};return t().createElement(t().Fragment,null,t().createElement(L,null),t().createElement("div",{className:"wc-body"},t().createElement("div",{className:"wc-content"},t().createElement("h3",{id:"wc-subtitle",className:"wc-heading"},"Give feedback on Floodline webchat"),t().createElement("p",null,"We're running webchat as a trial. you can ",t().createElement("a",{id:"feedback-send",className:"govuk-link",href:"#",target:"_blank",rel:"noreferrer",onKeyDown:o,onClick:a},"give feedback")," to help us improve it."),t().createElement("p",null,t().createElement("a",{id:"feedback-close",className:"wc-link govuk-link",href:"#","data-module":"govuk-button",role:"button",onKeyDown:o,onClick:n},"Close")))))}const j=()=>{const{agentStatus:a,liveRegionText:n,setLiveRegionText:o}=N(),[l,r]=(0,e.useState)(),[s,c]=(0,e.useState)(),i="closed"===a||null===a,u=()=>{r(),c()},d=(0,e.useCallback)(R()((e=>{l?c(e):r(e)}),2e3),[l,s]);return(0,e.useEffect)((()=>(n&&(u(),d(n)),i&&(u(),o()),()=>{u(),o()})),[n]),t().createElement(t().Fragment,null,t().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},l),t().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},s))},W="aria-hidden",J="data-wc-inert",Z=e=>{for(const t of document.body.children)"wc-panel"!==t.id&&(e&&!t.getAttribute(W)?(t.setAttribute(W,"true"),t.setAttribute(J,"")):t.hasAttribute(J)&&(t.removeAttribute(W),t.removeAttribute(J)))},X=t=>{const[a,n]=(0,e.useState)([]),o=(0,e.useCallback)((e=>{const t=document.querySelector("#wc-panel");"Tab"===e.key&&(t&&!document.activeElement.closest("#wc-panel")&&t.focus(),e.shiftKey?(document.activeElement===a[0]||document.activeElement===document.querySelector("#wc-panel"))&&(a[a.length-1].focus(),e.preventDefault()):document.activeElement===a[a.length-1]&&(a[0].focus(),e.preventDefault()))}),[a]);(0,e.useEffect)((()=>{n((()=>{const e=document.body.querySelectorAll(["#wc-panel a:not([disabled])","#wc-panel button:not([disabled])","#wc-panel select:not([disabled])","#wc-panel input:not([disabled])","#wc-panel textarea:not([disabled])",'#wc-panel *[tabindex="0"]:not([disabled])'].join(","));return Array.from(e).filter((e=>!e.closest("[hidden]")&&!e.closest('[aria-hidden="true"]')))})())}),[t]),(0,e.useEffect)((()=>(Z(!0),document.querySelector("#wc-panel").focus(),document.addEventListener("keydown",o),()=>{Z(),document.removeEventListener("keydown",o)})),[a])};function z(){const{sdk:a,availability:n,instigatorId:o,thread:l,threadId:c,setThread:i,setThreadId:u,setChatVisibility:d,setMessages:m,setUnseenCount:g,isMobile:h,isKeyboard:E}=N(),{fetchThread:w,fetchMessages:v}=D(a),[b,y]=(0,e.useState)(c?2:0);X(b);const f=(0,e.useCallback)((e=>{"Escape"!==e.key&&"Esc"!==e.key||(c&&(l?.lastMessageSeen(),g(0)),d(!1),I())}),[l,c,g,d]);(0,e.useEffect)((()=>()=>{document.getElementById(o)?.focus()}),[]),(0,e.useEffect)((()=>(document.body.classList.remove("wc-u-hidden"),document.getElementsByTagName("html")[0].classList.add("wc-u-html"),document.body.classList.add("wc-u-body"),()=>{document.getElementsByTagName("html")[0].classList.remove("wc-u-html"),document.body.classList.remove("wc-u-body")})),[h]),(0,e.useEffect)((()=>(document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f)})),[f,d]),(0,e.useEffect)((()=>{c&&(l?(l.lastMessageSeen(),g(0),y(2)):(async()=>{try{const e=await w(c);i(e);const t=await v(e,c);m(t)}catch(e){console.log("[Chat Error] fetchThread",e),u(),i(),y(0)}})())}),[l,c]);const p=e=>t=>{t.preventDefault(),y(e)},k=p(0),S=p(1),_=p(2),T=p(3),C=p(4),L=p(5);let x;switch(b){case 0:default:x=t().createElement(A,{onContinue:S});break;case 1:x=t().createElement(O,{onPreChatScreen:k});break;case 2:x=t().createElement(Y,{onSettingsScreen:L,onEndChatScreen:T});break;case 3:x=t().createElement(V,{onChatScreen:_,onEndChatConfirm:C});break;case 4:x=t().createElement(H,{onCancel:()=>{d(!1),I()}});break;case 5:x=t().createElement(P,{onCancel:_})}"UNAVAILABLE"===n&&(x=t().createElement(K,null));const G=t().createElement("div",{id:"wc-panel",role:"dialog",className:r("wc-panel",E&&"wc-focus-visible"),tabIndex:"-1","aria-modal":"true","aria-labelledby":"wc-header wc-subtitle"},t().createElement("div",{className:"wc-panel__inner"},x),t().createElement(j,null));return t().createElement(t().Fragment,null,(0,s.createPortal)(G,document.body))}const Q=()=>{const{threadId:e,setInstigatorId:a}=N();if(!e)return null;const n=document.getElementById("webchat-skip-link-container");return n?t().createElement(t().Fragment,null,(0,s.createPortal)(t().createElement("a",{id:"webchat-skip-link",href:"#webchat",className:"govuk-skip-link","data-module":"govuk-skip-link",onClick:e=>{e.preventDefault(),a(e.target.id),window.location.hash="#webchat"},"data-wc-skiplink":!0,"data-wc-open-btn":!0},"Skip to webchat"),n)):null},{stripPageTitle:ee}=a(792);function te(){const{availability:a,isChatOpen:n,setChatVisibility:o,unseenCount:l,threadId:s,setUnseenCount:c,setInstigatorId:i,setLiveRegionText:u}=N(),d=(0,e.useRef)(),m=l>1?"new messages":"new message",g=l>0&&!n,h=ee(document.title),E=e=>{e.preventDefault(),c(0),o(!n),i(e.target.id),n?I():C()},w=e=>{" "===e.key&&e.preventDefault()},v=e=>{" "===e.key&&(c(0),o(!n))};switch((0,e.useEffect)((()=>{g&&(document.title=`(${l} ${m}) - ${h}`)}),[l]),(0,e.useEffect)((()=>(g&&u(`Floodline webchat - ${l} ${m}`),()=>{u()})),[l,n]),(0,e.useEffect)((()=>{const e=()=>{if(!s)return;if("AVAILABLE"!==a)return;const e=d.current.parentElement.getBoundingClientRect().top+35>(window.innerHeight||document.documentElement.clientHeight),t=!n&&e;document.documentElement.classList.toggle("wc-u-scroll-padding",t),document.body.classList.toggle("wc-u-scroll-padding",t),d.current.classList.toggle("wc-availability--fixed",t)};return document.addEventListener("scroll",e),e(),()=>{document.removeEventListener("scroll",e)}}),[s,n,a]),a){case"AVAILABLE":return t().createElement(t().Fragment,null,t().createElement("div",{className:r("wc-availability",n&&"wc-open"),ref:d},t().createElement("div",{className:"wc-availability__inner"},t().createElement("a",{id:"webchat-start-chat-link",className:"wc-availability__link",href:"#webchat",draggable:"false",onClick:E,onKeyUp:v,onKeyDown:w,role:"button","data-module":"govuk-button"},s?t().createElement(t().Fragment,null,"Show chat"):t().createElement(t().Fragment,null,"Start chat"),g?t().createElement("span",{className:"wc-availability__unseen"},l,t().createElement("span",{className:"govuk-visually-hidden"}," ",m)):null))),n?t().createElement(z,null):t().createElement(j,null),t().createElement(Q,null));case"EXISTING":case"UNAVAILABLE":return t().createElement("p",{className:"govuk-body"},"When it is available, a 'start chat' link will appear.");default:return t().createElement("p",{className:"govuk-body"},"Checking availability")}}const ae=async e=>{const t=new(window.AudioContext||window.webkitAudioContext);if("suspended"===t.state){const e=["touchstart","touchend","mousedown","wheel","keydown","click"],a=n=>{e.forEach((e=>{document.body.removeEventListener(e,a)})),t.resume()};e.forEach((e=>{document.body.addEventListener(e,a,!1)}))}const a=await fetch(e),n=await a.arrayBuffer(),o=await t.decodeAudioData(n);return()=>{const e=t.createBufferSource();e.buffer=o,e.connect(t.destination),e.start()}};async function ne(e,a){const n=new l.ChatSdk({brandId:a.brandId,channelId:a.channelId,customerId:window.localStorage.getItem(w)||"",environment:a.environment}),r=(0,o.createRoot)(e);let s,c;try{const e=await async function(e){const t=await fetch(e);return{availability:(await t.json()).availability||"UNAVAILABLE"}}(a.availabilityEndpoint);c=await ae(a.audioUrl),s=e.availability}catch(e){s="UNAVAILABLE"}r.render(t().createElement(_,{sdk:n,availability:s,playSound:c},t().createElement(te,null)))}})(),module.exports=n})();
|
|
1
|
+
(()=>{"use strict";var e={n:t=>{var a=t&&t.__esModule?()=>t.default:()=>t;return e.d(a,{a}),a},d:(t,a)=>{for(var n in a)e.o(a,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:a[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{init:()=>ee});const a=require("react");var n=e.n(a);const l=require("react-dom/client"),o=require("@nice-devone/nice-cxone-chat-web-sdk"),r=(...e)=>e.filter(e=>e&&"string"==typeof e).join(" "),c=require("react-dom"),s=require("luxon"),i=require("html-react-parser");var u=e.n(i);const d=/(?:www|https?)[^\s]+/gi,m=e=>(e.match(d)&&(e=e.replace(d,e=>`<a class="govuk-link" href="${e}" target="_blank" rel="noreferrer">${e.replace(/https?:\/\//gi,"")}</a>`)),u()(e)),g=e=>({id:e.id,text:e.messageContent?.text,createdAt:new Date(e.createdAt),user:e.authorEndUserIdentity?.fullName?.trim()||null,assignee:e.authorUser?.firstName||null,direction:e.direction}),h=e=>{const t=s.DateTime.local();t.setZone("Europe/London");let a=`Floodline webchat transcript, ${t.toFormat("HH:mm:ss a, dd LLLL yyyy")}\n\n`;for(const t of e){const{text:e,direction:n,user:l,assignee:o,createdAt:r}=t,c="inbound"===n?l:`${o} (Floodline adviser)`;a+=`[${s.DateTime.fromJSDate(new Date(r)).setZone("Europe/London").toFormat("HH:mm:ss a, dd LLLL yyyy")}] ${c}: \n${e}\n\n`}return a=a.replace(/<a\b[^>]*>/i,"").replace(/<\/a>/i,""),encodeURIComponent(a)},E="webchat_settings",w="webchat_customer_id",v="webchat_thread_id",b=4e3,y={SET_CHAT_VISIBILITY:(e,t)=>({...e,isChatOpen:t}),SET_AVAILABILITY:(e,t)=>({...e,availability:t}),SET_SETTINGS:(e,t)=>(t?window.localStorage.setItem(E,JSON.stringify(t)):window.localStorage.removeItem(E),{...e,settings:t}),SET_CUSTOMER_ID:(e,t)=>(t?window.localStorage.setItem(w,t):window.localStorage.removeItem(w),{...e,customerId:t}),SET_THREAD_ID:(e,t)=>(t?window.localStorage.setItem(v,t):window.localStorage.removeItem(v),{...e,threadId:t}),SET_THREAD:(e,t)=>({...e,thread:t}),SET_MESSAGE:(e,t)=>({...e,message:g(t),messages:[...e.messages,g(t)]}),SET_MESSAGES:(e,t)=>{return{...e,messages:(a=t,a.map(e=>g(e))).reverse()};var a},SET_AGENT:(e,t)=>({...e,agent:t}),SET_AGENT_TYPING:(e,t)=>({...e,isAgentTyping:t}),SET_AGENT_STATUS:(e,t)=>({...e,agentStatus:t}),SET_UNSEEN_COUNT:(e,t)=>({...e,unseenCount:t}),SET_INSTIGATOR_ID:(e,t)=>({...e,instigatorId:t}),SET_LIVE_REGION_TEXT:(e,t)=>({...e,liveRegionText:t}),TOGGLE_IS_MOBILE:(e,t)=>({...e,isMobile:t}),TOGGLE_IS_KEYBOARD:(e,t)=>({...e,isKeyboard:t})},f={availability:null,customerId:null,threadId:null,thread:null,messages:[],unseenCount:0,instigatorId:null,agent:null,agentStatus:null,isAgentTyping:!1,isChatOpen:!1,isMobile:window.matchMedia("(max-width: 640px)").matches,isKeyboard:!1,settings:{audio:!0,scroll:!0}},p=(e,t)=>{const{type:a,payload:n}=t,l=y[a];return l?l.bind(void 0,e,n)():e},k=(0,a.createContext)(f),_=({sdk:e,availability:t,playSound:l,children:r})=>{const[c,s]=(0,a.useReducer)(p,f),i=e=>{s({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),s({type:"SET_AGENT_STATUS",payload:e.detail.data.contact.status}),s({type:"SET_UNSEEN_COUNT",payload:e.detail.data.contact.customerStatistics.unseenMessagesCount})},u=e=>{s({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),s({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},d=()=>{s({type:"SET_AGENT_TYPING",payload:!0})},m=()=>{s({type:"SET_AGENT_TYPING",payload:!1}),s({type:"SET_LIVE_REGION_TEXT"})},g=e=>{s({type:"SET_MESSAGE",payload:e.detail.data.message}),s({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status}),s({type:"SET_UNSEEN_COUNT",payload:e.detail.data.case.customerStatistics.unseenMessagesCount}),JSON.parse(window.localStorage.getItem(E)).audio&&"outbound"===e.detail.data.message.direction&&l&&l()},h=e=>{s({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},b=e=>{s({type:"TOGGLE_IS_MOBILE",payload:e.matches})},y=()=>{s({type:"TOGGLE_IS_KEYBOARD",payload:!0})},_=()=>{s({type:"TOGGLE_IS_KEYBOARD",payload:!1})};(0,a.useEffect)(()=>(e.onChatEvent(o.ChatEvent.LIVECHAT_RECOVERED,i),e.onChatEvent(o.ChatEvent.MESSAGE_CREATED,g),e.onChatEvent(o.ChatEvent.AGENT_TYPING_STARTED,d),e.onChatEvent(o.ChatEvent.AGENT_TYPING_ENDED,m),e.onChatEvent(o.ChatEvent.ASSIGNED_AGENT_CHANGED,u),e.onChatEvent(o.ChatEvent.CONTACT_STATUS_CHANGED,h),window.matchMedia("(max-width: 640px)").addEventListener("change",b),window.addEventListener("keydown",y),window.addEventListener("pointerdown",_),()=>{window.removeEventListener("change",b),window.removeEventListener("keydown",y),window.removeEventListener("pointerdown",_)}),[e]),(0,a.useEffect)(()=>{s({type:"SET_AVAILABILITY",payload:t}),N(window.localStorage.getItem(w)),T(window.localStorage.getItem(v)),A(JSON.parse(window.localStorage.getItem(E))||c.settings)},[]),(0,a.useEffect)(()=>{"#webchat"===window.location.hash&&S(!0);const e=()=>{"#webchat"===window.location.hash?S(!0):S(!1)};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}},[]);const S=e=>{s({type:"SET_CHAT_VISIBILITY",payload:e})},N=e=>{s({type:"SET_CUSTOMER_ID",payload:e})},T=e=>{s({type:"SET_THREAD_ID",payload:e})},C=e=>{s({type:"SET_THREAD",payload:e})},I=e=>{s({type:"SET_MESSAGES",payload:e})},A=e=>{s({type:"SET_SETTINGS",payload:e})},L=e=>{s({type:"SET_UNSEEN_COUNT",payload:e})},x=e=>{s({type:"SET_INSTIGATOR_ID",payload:e})},D=e=>{s({type:"SET_LIVE_REGION_TEXT",payload:e})},G=(0,a.useMemo)(()=>({...c,sdk:e,setSettings:A,setCustomerId:N,setThreadId:T,setThread:C,setMessages:I,setUnseenCount:L,setChatVisibility:S,setInstigatorId:x,setLiveRegionText:D,onLiveChatRecovered:i,onAssignedAgentChanged:u,onAgentTypingStarted:d,onAgentTypingEnded:m,onMessageCreated:g,onContactStatusChanged:h}));return n().createElement(k.Provider,{value:G},r)},S=()=>(0,a.useContext)(k),N=()=>{const e=window.location.href.split("#")[0];window.history.pushState({history:!0},null,`${e}#webchat`)},T=()=>{if(window.history.state?.history)return window.history.back();const e=window.location.href.split("#")[0];return window.history.replaceState(null,null,e)};function C(){const{thread:e,threadId:t,setChatVisibility:a,setUnseenCount:l,isMobile:o}=S(),r=n=>{n.preventDefault(),a(!1),T(),t&&(e?.lastMessageSeen(),l(0))},c=n().createElement("button",{className:"wc-header__back","aria-label":"Close the webchat",onClick:r},n().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},n().createElement("path",{d:"M4.828,11L12.314,18.485L10.899,19.899L1,10L10.899,0.101L12.314,1.515L4.828,9L19,9L19,11L4.828,11Z",fill:"currentColor"}))),s=n().createElement("button",{className:"wc-header__close","aria-label":"Close the webchat",onClick:r},n().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},n().createElement("path",{d:"M10,8.6L15.6,3L17,4.4L11.4,10L17,15.6L15.6,17L10,11.4L4.4,17L3,15.6L8.6,10L3,4.4L4.4,3L10,8.6Z",fill:"currentColor"}))),i=n().createElement("button",{className:"wc-header__hide","aria-label":"Minimise the webchat",onClick:r},n().createElement("svg",{"aria-hidden":"true",focusable:"false",width:"20",height:"20",viewBox:"0 0 20 20"},n().createElement("path",{d:"M10 14.4l-7-7L4.4 6l5.6 5.6L15.6 6 17 7.4l-7 7z",fill:"currentColor"}))),u=o&&globalThis.history.state,d=o&&!globalThis.history.state;let m=s;return t&&(m=i,d&&(m=i)),!t&&d&&(m=s),u&&(m=null),n().createElement("div",{className:"wc-header govuk-header"},u?c:null,n().createElement("h2",{id:"wc-header",className:"wc-header__title"},"Floodline webchat"),m)}function I({onContinue:e}){return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("div",{className:"wc-content"},n().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"What you can use webchat for"),n().createElement("p",null,"Webchat lets you talk directly to a Floodline adviser."),n().createElement("p",null,"You can use webchat to get:"),n().createElement("ul",{className:"wc-list"},n().createElement("li",null,"current flood warnings and alerts in your area"),n().createElement("li",null,"information on the flood warning service"),n().createElement("li",null,"advice on what to do before, during and after a flood")),n().createElement("p",null,"There are other ways to ",n().createElement("a",{className:"govuk-link",href:"https://www.gov.uk/sign-up-for-flood-warnings",target:"_blank",rel:"noreferrer"},"sign up for flood warnings")," and ",n().createElement("a",{className:"govuk-link",href:"https://www.fws.environment-agency.gov.uk/app/olr/login",target:"_blank",rel:"noreferrer"},"manage your flood warnings account"),"."),n().createElement("p",null,"Do not use webchat to ",n().createElement("a",{className:"govuk-link",href:"https://www.gov.uk/report-flood-cause",target:"_blank",rel:"noreferrer"},"report a flood"),"."),n().createElement("button",{className:"govuk-button wc-button govuk-!-margin-top-1","data-module":"govuk-button",onClick:e},"Continue"),n().createElement("h3",{className:"wc-heading"},"Other flood information"),n().createElement("p",null,"Call Floodline for all other flood and flood warning information."),n().createElement("p",null,n().createElement("strong",null,"Floodline helpline"),n().createElement("br",null),"Telephone: 0345 988 1188",n().createElement("br",null),"Textphone: 0345 602 6340",n().createElement("br",null),"Open 24 hours a day, 7 days a week",n().createElement("br",null),n().createElement("a",{className:"govuk-link",href:"https://gov.uk/call-charges",target:"_blank",rel:"noreferrer"},"Find out more about call charges")))))}const A=require("uuid"),L=e=>{const t=async()=>e.authorize();return{connect:t,fetchCustomerId:async()=>{const e=await t();return e?.consumerIdentity.idOnExternalPlatform},fetchThread:async a=>(await t(),e.getThread(a)),fetchMessages:async(e,a)=>{await t();const n=await e.recover(a),l=[];let o=n.messages;for(;o.length;){o.map(e=>l.push(e));try{o=(await e.loadMoreMessages()).data.messages}catch(e){o=[]}}return l}}},x=({errors:e})=>{const t=Object.keys(e),a=e=>{e.preventDefault();const t=e.target.getAttribute("data-key");document.querySelector(`#wc-${t}`).focus()};return 0===t.length?null:n().createElement("div",{className:"govuk-error-summary govuk-!-static-margin-bottom-7","data-module":"govuk-error-summary",tabIndex:"-1"},n().createElement("div",{role:"alert"},n().createElement("h2",{id:"wc-error",className:"wc-error-summary__title govuk-error-summary__title"},"There is a problem"),n().createElement("div",{className:"govuk-error-summary__body"},n().createElement("ul",{className:"govuk-list govuk-error-summary__list wc-error-summary__list"},t.map(t=>n().createElement("li",{key:t},n().createElement("a",{href:"#","data-key":t,onClick:a},e[t])))))))},D=500;function G({onPreChatScreen:e}){const{sdk:t,setCustomerId:l,setThreadId:o,setThread:c,setLiveRegionText:s}=S(),{fetchCustomerId:i,fetchThread:u}=L(t),[d,m]=(0,a.useState)({}),[g,h]=(0,a.useState)(0),[E,w]=(0,a.useState)(!1),v=(0,a.useRef)(),b=(0,a.useRef)(),y=D>=g;let f=`You have ${D-g} characters remaining`;y||(f=`You have ${g-D} characters too many`),(0,a.useEffect)(()=>{Object.keys(d).length&&document.querySelector(".govuk-error-summary")?.focus()},[d]);const p=E?"Requesting...":"Request chat";return(0,a.useEffect)(()=>{E&&s(p)},[E]),n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("div",{className:"wc-content"},n().createElement("a",{href:"#",className:"wc-back-link govuk-back-link",onClick:e},"What you can use webchat for"),n().createElement(x,{errors:d}),n().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Your name and question"),n().createElement("form",null,n().createElement("div",{className:r("wc-form-group","govuk-form-group",d.name&&"govuk-form-group--error")},n().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-name"},"Your name"),d.name&&n().createElement("p",{className:"govuk-error-message"},n().createElement("span",{className:"govuk-visually-hidden"},"Error:")," ",d.name),n().createElement("input",{ref:v,className:r("wc-input","govuk-input",d.name&&"govuk-input--error"),id:"wc-name",name:"name",type:"text","data-testid":"request-chat-user-name"})),n().createElement("div",{className:"wc-form-group govuk-character-count","data-module":"govuk-character-count","data-maxlength":"500"},n().createElement("div",{className:r("govuk-form-group",d.question&&"govuk-form-group--error")},n().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-question"},"Your question"),d.question&&n().createElement("p",{className:"govuk-error-message"},n().createElement("span",{className:"govuk-visually-hidden"},"Error:"),d.question),n().createElement("textarea",{ref:b,id:"wc-question",name:"question",rows:"5","aria-describedby":"wc-question-info",onChange:e=>{h(e.target.value.length)},className:r("wc-textarea","govuk-textarea","govuk-js-character-count",!y||d.question?"govuk-textarea--error":""),"data-testid":"request-chat-user-question"}),n().createElement("div",{id:"wc-question-info",className:"wc-hint govuk-hint govuk-char-count__msg",style:{color:y?"":"#d4351c"},"aria-hidden":"true"},f),n().createElement("div",{className:"govuk-character-count__sr-status govuk-visually-hidden","aria-live":"polite"},f))),n().createElement("div",{className:"wc-inset-text govuk-inset-text"},"By selecting 'Request chat' you agree to the terms of our ",n().createElement("a",{href:"https://check-for-flooding.service.gov.uk/privacy-notice",target:"_blank",rel:"noreferrer",className:"govuk-link"},"privacy notice"),"."),n().createElement("button",{className:"wc-button govuk-button govuk-!-margin-top-1","data-module":"govuk-button",onClick:async e=>{if(e.preventDefault(),E)return;const a={};if(0===v.current.value.length&&(a.name="Enter your name"),0===b.current.value.length&&(a.question="Enter your question"),b.current.value.length>D&&(a.question="Your question must be 500 characters or less"),0===Object.keys(a).length)try{w(!0);const e=A.v4(),a=await i(),n=await u(e);t.getCustomer().setName(v.current.value),await n.startChat(b.current.value||"Begin conversation"),l(a),o(e),c(n),n.setCustomField("threadid",e)}catch(e){console.log("[Request chat Error]",e)}m(a)},"aria-disabled":E},p)))))}function q({children:e}){return n().createElement("div",{className:"wc-footer"},e)}function O({message:e,previousMessage:t}){const a="outbound"===e.direction,l=e?.direction===t?.direction;return n().createElement("li",{className:r("wc-chat__message",a?"outbound":"inbound")},n().createElement("div",{className:"wc-chat__from"},l?null:n().createElement("span",{className:r(a?"outbound":"inbound")},a?e.assignee:"You"),n().createElement("span",{className:"govuk-visually-hidden"},":")),n().createElement("div",{className:r("wc-chat__text",a?"outbound":"inbound")},m(e.text)))}const M=(e,t)=>{(0,a.useEffect)(()=>{if(e){e.style.height="0px";const t=e.scrollHeight;e.style.height=`${t}px`}},[e,t])},R=(e,t,a)=>{if("UNAVAILABLE"===e)return"Webchat is not currently available";if(!t)return"Connecting to Floodline";switch(t){case"closed":case"resolved":return a?`${a} ended the session`:"Session ended by advisor";default:return a?`You are speaking with ${a}`:"Waiting for an adviser"}};function F({onEndChatScreen:e,onSettingsScreen:t}){const{availability:l,thread:o,messages:r,agent:c,agentStatus:s,isAgentTyping:i,isChatOpen:u,settings:d,isKeyboard:m,setLiveRegionText:g}=S(),[E,w]=(0,a.useState)(""),[v,y]=(0,a.useState)(!1),f=(0,a.useRef)();M(f.current,E),(0,a.useEffect)(()=>{if(d.scroll&&0!==r.length){const e=document.querySelector(".wc-body");e.scrollTop=e.scrollHeight}},[r,i]),(0,a.useEffect)(()=>{const e=document.querySelector(".wc-form__label");0===E.length?e.classList.remove("govuk-visually-hidden"):e.classList.add("govuk-visually-hidden")},[E]);const p=c?.nickname||c?.firstName,k=R(l,s,p);(0,a.useEffect)(()=>(k&&g(`Floodline webchat - ${k}`),()=>{g()}),[k]),(0,a.useEffect)(()=>(i&&u&&g(`${p} is typing...`),()=>{g()}),[i,u]),(0,a.useEffect)(()=>{const e=r[r.length-1];return"closed"!==s&&"outbound"===e?.direction&&g(`${p} said: ${e.text}`),()=>{g()}},[r]);const _=()=>{if(0!==f.current.value.length&&"closed"!==s){try{const e=f.current.value.trim();o.sendTextMessage(e),g(`You said: ${e}`)}catch(e){console.log("[Chat Error] sendMessage",e)}w("")}},N=()=>{const e=h(r);document.querySelector("#transcript-download").setAttribute("href",`data:text/plain;charset=utf-8,${e}`)},T=a=>{if("Enter"!==a.key||a.shiftKey)" "===a.key?("end-chat"===a.target.id&&e(a),"wc-settings"===a.target.id&&t(a)):(o.keystroke(),setTimeout(()=>{o.stopTyping()},b));else switch(a.target.id){case"text-area":a.preventDefault(),_();break;case"end-chat":e(a);break;case"wc-settings":t(a);break;case"transcript-download":N()}};return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-status"},n().createElement("p",{className:"wc-status__availability"},k),n().createElement("a",{id:"end-chat",className:"wc-status__link",href:"#","data-module":"govuk-button",role:"button",onClick:e,onKeyDown:T},"End chat")),n().createElement("div",{className:"wc-body",tabIndex:"0"},n().createElement("ul",{className:"wc-chat"},r.length?r.map((e,t)=>n().createElement(O,{key:e.id,message:e,previousMessage:r[t-1]})):null,i?n().createElement("li",{className:"wc-chat__message outbound"},n().createElement("div",{className:"wc-chat__from"},p," is typing"),n().createElement("div",{className:"wc-chat__text outbound"},n().createElement("svg",{width:"28",height:"16",x:"0px",y:"0px",viewBox:"0 0 28 16"},n().createElement("circle",{stroke:"none",cx:"3",cy:"8",r:"3",fill:"currentColor"}),n().createElement("circle",{stroke:"none",cx:"14",cy:"8",r:"3",fill:"currentColor"}),n().createElement("circle",{stroke:"none",cx:"25",cy:"8",r:"3",fill:"currentColor"})))):null)),n().createElement(q,null,n().createElement("form",{className:"wc-form"+(v?" wc-focus-within":""),noValidate:!0,onSubmit:e=>{e.preventDefault(),_()}},n().createElement("label",{className:"govuk-label wc-form__label",htmlFor:"wc-form-textarea"},"Your message",n().createElement("span",{className:"govuk-visually-hidden"}," (enter key submits)")),n().createElement("textarea",{ref:f,rows:"1","aria-required":"true",className:"wc-form__textarea",id:"text-area",name:"message",onChange:e=>{w(e.target?.value)},onKeyDown:T,onFocus:()=>{y(m)},onBlur:()=>{y(!1)},value:E}),n().createElement("input",{type:"submit",className:"wc-form__button govuk-button",value:"Send","data-prevent-double-click":"true"})),n().createElement("div",{className:"wc-footer__settings"},n().createElement("a",{href:"#",id:"wc-settings",className:"wc-footer__settings-link","data-module":"govuk-button",onKeyDown:T,onClick:t},"Settings"),n().createElement("a",{href:"#",id:"transcript-download",className:"wc-footer__settings-link","data-module":"govuk-button",download:"floodline-webchat-transcript.txt",onKeyDown:T,onClick:N},"Save chat"))))}function U(){return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("h3",{id:"wc-subtitle",className:"govuk-heading-m"},"Webchat is currently not available"),n().createElement("p",{className:"govuk-body-s"},"Try again later, or call Floodline:"),n().createElement("p",{className:"govuk-body-s"},n().createElement("strong",null,"Floodline helpline"),n().createElement("br",null),"Telephone: 0345 988 1188",n().createElement("br",null),"Textphone: 0345 602 6340",n().createElement("br",null),"Open 24 hours a day, 7 days a week",n().createElement("br",null),n().createElement("a",{className:"govuk-link",href:"https://gov.uk/call-charges"},"Find out more about call charges")),n().createElement("p",{className:"govuk-body-s"},"We're running webchat as a trial, it will not always be available.")))}function B({onChatScreen:e,onEndChatConfirm:t}){const{setCustomerId:l,setThreadId:o,setMessages:r,agentStatus:c,thread:s,threadId:i,setUnseenCount:u,isKeyboard:d}=S(),m=async e=>{e.preventDefault(),window.localStorage.setItem("tmpThreadId",i),o(),r([]),l(),s.lastMessageSeen(),u(0),"closed"!==c&&s.endChat(),t(e)};(0,a.useEffect)(()=>{d&&setTimeout(()=>{document.querySelector("#confirm-endchat").focus()},10)},[]);const g=t=>{"Enter"!==t.key&&" "!==t.key||"confirm-endchat"!==t.target.id||m(t),"Enter"!==t.key&&" "!==t.key||"resume-chat"!==t.target.id||e(t)};return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("div",{className:"wc-content"},n().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Are you sure you want to end the chat?"),n().createElement("div",{className:"govuk-button-group"},n().createElement("a",{id:"confirm-endchat",href:"#endChat",role:"button",className:"wc-button govuk-button","data-module":"govuk-button",onClick:m,onKeyDown:g},"Yes, end chat"),n().createElement("a",{id:"resume-chat",href:"#resumeChat",role:"button",className:"wc-link govuk-link","data-module":"govuk-button",onClick:e,onKeyDown:g},"No, resume chat")))))}function Y({onCancel:e}){const{settings:t,setSettings:l}=S(),[o,r]=(0,a.useState)(t.audio),[c,s]=(0,a.useState)(t.scroll),i=t=>{t.preventDefault(),l({audio:o,scroll:c}),e(t)},u=t=>{"Enter"!==t.key&&" "!==t.key||"settings-save"!==t.target.id?"Enter"!==t.key&&" "!==t.key||"settings-cancel"!==t.target.id||e(t):i(t)};return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("div",{className:"wc-content"},n().createElement("fieldset",{className:"govuk-fieldset govuk-!-margin-bottom-4"},n().createElement("legend",{className:"govuk-fieldset__legend govuk-fieldset__legend"},n().createElement("h3",{id:"wc-subtitle",className:"wc-heading"},"Change settings")),n().createElement("div",{className:"govuk-checkboxes govuk-checkboxes--small","data-module":"govuk-checkboxes"},n().createElement("div",{className:"govuk-checkboxes__item"},n().createElement("input",{id:"audio",name:"audio",type:"checkbox",value:"audio",className:"govuk-checkboxes__input",defaultChecked:o,onChange:()=>r(!o)}),n().createElement("label",{className:"wc-label govuk-label govuk-checkboxes__label",htmlFor:"audio"},"Play a sound when receiving a new message")),n().createElement("div",{className:"govuk-checkboxes__item"},n().createElement("input",{id:"scroll",name:"scroll",type:"checkbox",value:"scroll",className:"govuk-checkboxes__input",defaultChecked:c,onChange:()=>s(!c)}),n().createElement("label",{className:"wc-label govuk-label govuk-checkboxes__label",htmlFor:"scroll"},"Scroll automatically to a new message")))),n().createElement("div",{className:"govuk-button-group"},n().createElement("a",{id:"settings-save",href:"#",className:"wc-button govuk-button","data-module":"govuk-button",role:"button",onClick:i,onKeyDown:u},"Save"),n().createElement("a",{id:"settings-cancel",href:"#",className:"wc-link govuk-link","data-module":"govuk-button",role:"button",onClick:e,onKeyDown:u},"Cancel")))))}function $({onCancel:e}){const t=()=>{const e=window.localStorage.getItem("tmpThreadId");window.location.href=`https://defragroup.eu.qualtrics.com/jfe/form/SV_8dgFSJcxxIfqx5Y?Id=${e}&Source=${window.location.href}`,window.localStorage.removeItem("tmpThreadId")},a=async t=>{window.localStorage.removeItem("tmpThreadId"),e(t)},l=e=>{"Enter"!==e.key&&" "!==e.key||("feedback-close"===e.target.id&&a(e),"feedback-send"===e.target.id&&t())};return n().createElement(n().Fragment,null,n().createElement(C,null),n().createElement("div",{className:"wc-body"},n().createElement("div",{className:"wc-content"},n().createElement("h3",{id:"wc-subtitle",className:"wc-heading"},"Give feedback on Floodline webchat"),n().createElement("p",null,"We're running webchat as a trial. you can ",n().createElement("a",{id:"feedback-send",className:"govuk-link",href:"#",target:"_blank",rel:"noreferrer",onKeyDown:l,onClick:t},"give feedback")," to help us improve it."),n().createElement("p",null,n().createElement("a",{id:"feedback-close",className:"wc-link govuk-link",href:"#","data-module":"govuk-button",role:"button",onKeyDown:l,onClick:a},"Close")))))}const K=require("lodash.debounce");var V=e.n(K);const H=()=>{const{agentStatus:e,liveRegionText:t,setLiveRegionText:l}=S(),[o,r]=(0,a.useState)(),[c,s]=(0,a.useState)(),i="closed"===e||null===e,u=()=>{r(),s()},d=(0,a.useCallback)(V()(e=>{o?s(e):r(e)},2e3),[o,c]);return(0,a.useEffect)(()=>(t&&(u(),d(t)),i&&(u(),l()),()=>{u(),l()}),[t]),n().createElement(n().Fragment,null,n().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},o),n().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},c))},P="aria-hidden",j="data-wc-inert",W=e=>{for(const t of document.body.children)"wc-panel"!==t.id&&(e&&!t.getAttribute(P)?(t.setAttribute(P,"true"),t.setAttribute(j,"")):t.hasAttribute(j)&&(t.removeAttribute(P),t.removeAttribute(j)))},J=e=>{const[t,n]=(0,a.useState)([]),l=(0,a.useCallback)(e=>{const a=document.querySelector("#wc-panel");"Tab"===e.key&&(a&&!document.activeElement.closest("#wc-panel")&&a.focus(),e.shiftKey?(document.activeElement===t[0]||document.activeElement===document.querySelector("#wc-panel"))&&(t[t.length-1].focus(),e.preventDefault()):document.activeElement===t[t.length-1]&&(t[0].focus(),e.preventDefault()))},[t]);(0,a.useEffect)(()=>{n((()=>{const e=document.body.querySelectorAll(["#wc-panel a:not([disabled])","#wc-panel button:not([disabled])","#wc-panel select:not([disabled])","#wc-panel input:not([disabled])","#wc-panel textarea:not([disabled])",'#wc-panel *[tabindex="0"]:not([disabled])'].join(","));return Array.from(e).filter(e=>!e.closest("[hidden]")&&!e.closest('[aria-hidden="true"]'))})())},[e]),(0,a.useEffect)(()=>(W(!0),document.querySelector("#wc-panel").focus(),document.addEventListener("keydown",l),()=>{W(),document.removeEventListener("keydown",l)}),[t])};function X(){const{sdk:e,availability:t,instigatorId:l,thread:o,threadId:s,setThread:i,setThreadId:u,setChatVisibility:d,setMessages:m,setUnseenCount:g,isMobile:h,isKeyboard:E}=S(),{fetchThread:w,fetchMessages:v}=L(e),[b,y]=(0,a.useState)(s?2:0);J(b);const f=(0,a.useCallback)(e=>{"Escape"!==e.key&&"Esc"!==e.key||(s&&(o?.lastMessageSeen(),g(0)),d(!1),T())},[o,s,g,d]);(0,a.useEffect)(()=>()=>{document.getElementById(l)?.focus()},[]),(0,a.useEffect)(()=>(document.body.classList.remove("wc-u-hidden"),document.getElementsByTagName("html")[0].classList.add("wc-u-html"),document.body.classList.add("wc-u-body"),()=>{document.getElementsByTagName("html")[0].classList.remove("wc-u-html"),document.body.classList.remove("wc-u-body")}),[h]),(0,a.useEffect)(()=>(document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f)}),[f,d]),(0,a.useEffect)(()=>{s&&(o?(o.lastMessageSeen(),g(0),y(2)):(async()=>{try{const e=await w(s);i(e);const t=await v(e,s);m(t)}catch(e){console.log("[Chat Error] fetchThread",e),u(),i(),y(0)}})())},[o,s]);const p=e=>t=>{t.preventDefault(),y(e)},k=p(0),_=p(1),N=p(2),C=p(3),A=p(4),x=p(5);let D;switch(b){case 0:default:D=n().createElement(I,{onContinue:_});break;case 1:D=n().createElement(G,{onPreChatScreen:k});break;case 2:D=n().createElement(F,{onSettingsScreen:x,onEndChatScreen:C});break;case 3:D=n().createElement(B,{onChatScreen:N,onEndChatConfirm:A});break;case 4:D=n().createElement($,{onCancel:()=>{d(!1),T()}});break;case 5:D=n().createElement(Y,{onCancel:N})}"UNAVAILABLE"===t&&(D=n().createElement(U,null));const q=n().createElement("div",{id:"wc-panel",role:"dialog",className:r("wc-panel",E&&"wc-focus-visible"),tabIndex:"-1","aria-modal":"true","aria-labelledby":"wc-header wc-subtitle"},n().createElement("div",{className:"wc-panel__inner"},D),n().createElement(H,null));return n().createElement(n().Fragment,null,(0,c.createPortal)(q,document.body))}const Z=()=>{const{threadId:e,setInstigatorId:t}=S();if(!e)return null;const a=document.getElementById("webchat-skip-link-container");return a?n().createElement(n().Fragment,null,(0,c.createPortal)(n().createElement("a",{id:"webchat-skip-link",href:"#webchat",className:"govuk-skip-link","data-module":"govuk-skip-link",onClick:e=>{e.preventDefault(),t(e.target.id),window.location.hash="#webchat"},"data-wc-skiplink":!0,"data-wc-open-btn":!0},"Skip to webchat"),a)):null};function z(){const{availability:e,isChatOpen:t,setChatVisibility:l,unseenCount:o,threadId:c,setUnseenCount:s,setInstigatorId:i,setLiveRegionText:u}=S(),d=(0,a.useRef)(),m=o>0&&!t,g=o>1?"new messages":"new message",h=e=>{e.preventDefault(),s(0),l(!t),i(e.target.id),t?T():N()},E=e=>{" "===e.key&&e.preventDefault()},w=e=>{" "===e.key&&(s(0),l(!t))};switch((0,a.useEffect)(()=>(m&&u(`Floodline webchat - ${o} ${g}`),()=>{u()}),[o,t]),(0,a.useEffect)(()=>{const a=()=>{if(!c)return;if("AVAILABLE"!==e)return;const a=d.current.parentElement.getBoundingClientRect().top+35>(window.innerHeight||document.documentElement.clientHeight),n=!t&&a;document.documentElement.classList.toggle("wc-u-scroll-padding",n),document.body.classList.toggle("wc-u-scroll-padding",n),d.current.classList.toggle("wc-availability--fixed",n)};return document.addEventListener("scroll",a),a(),()=>{document.removeEventListener("scroll",a)}},[c,t,e]),e){case"AVAILABLE":return n().createElement(n().Fragment,null,n().createElement("div",{className:r("wc-availability",t&&"wc-open"),ref:d},n().createElement("div",{className:"wc-availability__inner"},n().createElement("a",{id:"webchat-start-chat-link",className:"wc-availability__link",href:"#webchat",draggable:"false",onClick:h,onKeyUp:w,onKeyDown:E,role:"button","data-module":"govuk-button"},c?n().createElement(n().Fragment,null,"Show chat"):n().createElement(n().Fragment,null,"Start chat"),m?n().createElement("span",{className:"wc-availability__unseen"},o,n().createElement("span",{className:"govuk-visually-hidden"}," ",g)):null))),t?n().createElement(X,null):n().createElement(H,null),n().createElement(Z,null));case"EXISTING":case"UNAVAILABLE":return n().createElement("p",{className:"govuk-body"},"When it is available, a 'start chat' link will appear.");default:return n().createElement("p",{className:"govuk-body"},"Checking availability")}}const Q=async e=>{const t=new(window.AudioContext||window.webkitAudioContext);if("suspended"===t.state){const e=["touchstart","touchend","mousedown","wheel","keydown","click"],a=n=>{e.forEach(e=>{document.body.removeEventListener(e,a)}),t.resume()};e.forEach(e=>{document.body.addEventListener(e,a,!1)})}const a=await fetch(e),n=await a.arrayBuffer(),l=await t.decodeAudioData(n);return()=>{const e=t.createBufferSource();e.buffer=l,e.connect(t.destination),e.start()}};async function ee(e,t){const a=new o.ChatSdk({brandId:t.brandId,channelId:t.channelId,customerId:window.localStorage.getItem(w)||"",environment:t.environment}),r=(0,l.createRoot)(e);let c,s;try{const e=await async function(e){const t=await fetch(e);return{availability:(await t.json()).availability||"UNAVAILABLE"}}(t.availabilityEndpoint);s=await Q(t.audioUrl),c=e.availability}catch(e){c="UNAVAILABLE"}r.render(n().createElement(_,{sdk:a,availability:c,playSound:s},n().createElement(z,null)))}module.exports=t})();
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var e={
|
|
1
|
+
(()=>{var e={45:e=>{"use strict";e.exports=require("querystring")},158:e=>{"use strict";e.exports=require("jwt-decode")},168:e=>{"use strict";e.exports=require("luxon")},398:(e,t,n)=>{const o=n(45),a=n(938),{jwtDecode:i}=n(158),{isWithinHours:s}=n(792),r="application/x-www-form-urlencoded";e.exports={authenticate:async({authenticationUri:e,authorisation:t,accessKey:n,accessSecret:s})=>{const c=new URL(e),u=o.stringify({grant_type:"password",username:n,password:s}),l=await a.post(c.href,u,{signal:AbortSignal.timeout(3e3),headers:{Host:c.host,"Content-Type":r,Authorization:t}});return{token:l.data.access_token,tokenType:l.data.token_type,tenantId:i(l.data.id_token)?.tenantId}},getApiBaseUrl:async({wellKnownUri:e,tenantId:t})=>{const n=new URL(e);n.searchParams.set("tenantId",t);const{data:o}=await a.get(n.href,{headers:{Host:n.host},signal:AbortSignal.timeout(3e3)});return o.api_endpoint},getIsOpen:async({baseUrl:e,token:t,tokenType:n,hoursEndpoint:o})=>{const i=new URL(o,e),c=(await a.get(i.href,{signal:AbortSignal.timeout(3e3),headers:{Host:i.host,Authorization:`${n} ${t}`,"Content-Type":r}})).data.resultSet.hoursOfOperationProfiles[0].days;return s(c)},getActivity:async({tokenType:e,token:t,baseUrl:n,skillEndpoint:o,maxQueueCount:i})=>{const s=new URL(o,n),c=(await a.get(s.href,{signal:AbortSignal.timeout(3e3),headers:{Host:s.host,Authorization:`${e} ${t}`,"Content-Type":r}})).data.skillActivity[0];return{hasCapacity:c.queueCount<i,hasAgentsAvailable:c.agentsAvailable>=1}}}},525:(e,t,n)=>{const{authenticate:o,getApiBaseUrl:a,getIsOpen:i,getActivity:s}=n(398);e.exports=async function({clientId:e,clientSecret:t,accessKey:n,accessSecret:r,maxQueueCount:c,skillEndpoint:u,hoursEndpoint:l,wellKnownUri:p="https://cxone.niceincontact.com/.well-known/cxone-configuration",authenticationUri:d="https://cxone.niceincontact.com/auth/token"}){const h="Basic "+Buffer.from(`${encodeURIComponent(e)}:${encodeURIComponent(t)}`).toString("base64"),{tenantId:m,token:w,tokenType:y}=await o({authenticationUri:d,authorisation:h,accessKey:n,accessSecret:r}),g=await a({wellKnownUri:p,tenantId:m}),[{hasCapacity:A,hasAgentsAvailable:k},f]=await Promise.all([s({baseUrl:g,tokenType:y,token:w,skillEndpoint:u,maxQueueCount:c}),i({baseUrl:g,token:w,tokenType:y,hoursEndpoint:l})]);let x="UNAVAILABLE";return f&&k&&A?x="AVAILABLE":f&&k&&!A&&(x="EXISTING"),{date:new Date,availability:x}}},792:(e,t,n)=>{const{DateTime:o}=n(168),a=e=>Number(e.split(":")[0]);e.exports={isWithinHours:(e,t)=>{const n=t?o.fromISO(t):o.local();n.setZone("Europe/London");const i=t?new Date(t):new Date,s=i.toLocaleDateString("en-GB",{weekday:"long"}),r=i.toLocaleDateString("en-GB").split("/"),c=e.find(e=>e.day===s),u=o.local(Number(r[2]),Number(r[1]),Number(r[0]),a(c.openTime)),l=o.local(Number(r[2]),Number(r[1]),Number(r[0]),a(c.closeTime));return n.diff(u).milliseconds>=0&&n.diff(l).milliseconds<=0}}},938:e=>{"use strict";e.exports=require("axios")}},t={},n=function n(o){var a=t[o];if(void 0!==a)return a.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}(525);module.exports=n})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@defra/flood-webchat",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/server.js",
|
|
6
6
|
"browser": "dist/client.js",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"@babel/preset-env": "^7.24.6",
|
|
32
32
|
"@babel/preset-react": "^7.24.6",
|
|
33
33
|
"@testing-library/jest-dom": "^6.4.5",
|
|
34
|
-
"@testing-library/react": "^
|
|
34
|
+
"@testing-library/react": "^16.0.0",
|
|
35
35
|
"@testing-library/user-event": "^14.5.2",
|
|
36
36
|
"@types/jest": "^29.5.12",
|
|
37
37
|
"babel-jest": "^29.6.4",
|
|
@@ -39,18 +39,18 @@
|
|
|
39
39
|
"core-js": "^3.37.1",
|
|
40
40
|
"css-loader": "^7.1.2",
|
|
41
41
|
"dotenv": "^16.4.5",
|
|
42
|
-
"husky": "^
|
|
42
|
+
"husky": "^9.0.11",
|
|
43
43
|
"jest": "^29.7.0",
|
|
44
44
|
"jest-environment-jsdom": "^29.7.0",
|
|
45
|
-
"mini-css-extract-plugin": "^2.
|
|
45
|
+
"mini-css-extract-plugin": "^2.9.0",
|
|
46
46
|
"node-cache": "^5.1.2",
|
|
47
47
|
"node-sass": "^9.0.0",
|
|
48
|
-
"sass": "^1.
|
|
48
|
+
"sass": "^1.77.5",
|
|
49
49
|
"sass-loader": "^14.2.1",
|
|
50
50
|
"standard": "^17.1.0",
|
|
51
51
|
"stylelint": "^15.11.0",
|
|
52
|
-
"stylelint-config-gds": "^1.
|
|
53
|
-
"webpack": "^5.
|
|
52
|
+
"stylelint-config-gds": "^1.1.1",
|
|
53
|
+
"webpack": "^5.92.0",
|
|
54
54
|
"webpack-cli": "^5.1.4",
|
|
55
55
|
"webpack-dev-server": "^5.0.4",
|
|
56
56
|
"webpack-merge": "^5.10.0",
|
|
@@ -63,12 +63,12 @@
|
|
|
63
63
|
"@nice-devone/nice-cxone-chat-web-sdk": "^1.18.0",
|
|
64
64
|
"axios": "^1.7.2",
|
|
65
65
|
"html-react-parser": "^5.1.10",
|
|
66
|
-
"jwt-decode": "^
|
|
66
|
+
"jwt-decode": "^4.0.0",
|
|
67
67
|
"lodash.debounce": "^4.0.8",
|
|
68
|
-
"luxon": "^3.4.
|
|
68
|
+
"luxon": "^3.4.4",
|
|
69
69
|
"querystring": "^0.2.1",
|
|
70
|
-
"react": "^18.
|
|
71
|
-
"react-dom": "^18.
|
|
72
|
-
"uuid": "^
|
|
70
|
+
"react": "^18.3.1",
|
|
71
|
+
"react-dom": "^18.3.1",
|
|
72
|
+
"uuid": "^10.0.0"
|
|
73
73
|
}
|
|
74
74
|
}
|
|
@@ -8,18 +8,14 @@ import { useApp } from '../../store/useApp'
|
|
|
8
8
|
import { historyPushState, historyReplaceState } from '../../lib/history.js'
|
|
9
9
|
import { LiveRegion } from '../live-region.jsx'
|
|
10
10
|
|
|
11
|
-
const { stripPageTitle } = require('../../../server/lib/utils')
|
|
12
|
-
|
|
13
11
|
export function Availability () {
|
|
14
12
|
const { availability, isChatOpen, setChatVisibility, unseenCount, threadId, setUnseenCount, setInstigatorId, setLiveRegionText } = useApp()
|
|
15
13
|
|
|
16
14
|
const buttonRef = useRef()
|
|
17
15
|
|
|
18
|
-
const messageText = unseenCount > 1 ? 'new messages' : 'new message'
|
|
19
|
-
|
|
20
16
|
const showUnseenCount = unseenCount > 0 && !isChatOpen
|
|
21
17
|
|
|
22
|
-
const
|
|
18
|
+
const messageText = unseenCount > 1 ? 'new messages' : 'new message'
|
|
23
19
|
|
|
24
20
|
const onClick = e => {
|
|
25
21
|
e.preventDefault()
|
|
@@ -47,12 +43,6 @@ export function Availability () {
|
|
|
47
43
|
}
|
|
48
44
|
}
|
|
49
45
|
|
|
50
|
-
useEffect(() => {
|
|
51
|
-
if (showUnseenCount) {
|
|
52
|
-
document.title = `(${unseenCount} ${messageText}) - ${originalTitle}`
|
|
53
|
-
}
|
|
54
|
-
}, [unseenCount])
|
|
55
|
-
|
|
56
46
|
useEffect(() => {
|
|
57
47
|
if (showUnseenCount) {
|
|
58
48
|
setLiveRegionText(`Floodline webchat - ${unseenCount} ${messageText}`)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import React, { useEffect, useRef, useState
|
|
1
|
+
import React, { useEffect, useRef, useState } from 'react'
|
|
2
2
|
|
|
3
3
|
import { TYPING_INDICATOR_DURATION } from '../../store/constants.js'
|
|
4
|
-
|
|
4
|
+
|
|
5
5
|
import { PanelHeader } from '../panel/panel-header.jsx'
|
|
6
6
|
import { PanelFooter } from '../panel/panel-footer.jsx'
|
|
7
7
|
import { Message } from '../message/message.jsx'
|
|
@@ -107,13 +107,6 @@ export function Chat ({ onEndChatScreen, onSettingsScreen }) {
|
|
|
107
107
|
saveChatLink.setAttribute('href', `data:text/plain;charset=utf-8,${transcript}`)
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
const debouncedKeystroke = useCallback(debounce(() => {
|
|
111
|
-
thread.keystroke()
|
|
112
|
-
setTimeout(() => {
|
|
113
|
-
thread.stopTyping()
|
|
114
|
-
}, TYPING_INDICATOR_DURATION)
|
|
115
|
-
}, 100), [thread])
|
|
116
|
-
|
|
117
110
|
const handleKeyPress = e => {
|
|
118
111
|
if (e.key === 'Enter' && !e.shiftKey) {
|
|
119
112
|
switch (e.target.id) {
|
|
@@ -141,7 +134,10 @@ export function Chat ({ onEndChatScreen, onSettingsScreen }) {
|
|
|
141
134
|
onSettingsScreen(e)
|
|
142
135
|
}
|
|
143
136
|
} else {
|
|
144
|
-
|
|
137
|
+
thread.keystroke()
|
|
138
|
+
setTimeout(() => {
|
|
139
|
+
thread.stopTyping()
|
|
140
|
+
}, TYPING_INDICATOR_DURATION)
|
|
145
141
|
}
|
|
146
142
|
}
|
|
147
143
|
|
|
@@ -40,8 +40,8 @@ export function PanelHeader () {
|
|
|
40
40
|
</button>
|
|
41
41
|
)
|
|
42
42
|
|
|
43
|
-
const isMobileAndHasHistory = isMobile &&
|
|
44
|
-
const isMobileAndNoHistory = isMobile && !
|
|
43
|
+
const isMobileAndHasHistory = isMobile && globalThis.history.state
|
|
44
|
+
const isMobileAndNoHistory = isMobile && !globalThis.history.state
|
|
45
45
|
|
|
46
46
|
let RightButtonComponent = CloseButtonComponent
|
|
47
47
|
|
|
@@ -62,7 +62,7 @@ export function PanelHeader () {
|
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
return (
|
|
65
|
-
<div className='wc-header'>
|
|
65
|
+
<div className='wc-header govuk-header'>
|
|
66
66
|
{isMobileAndHasHistory ? BackButtonComponent : null}
|
|
67
67
|
|
|
68
68
|
<h2 id='wc-header' className='wc-header__title'>
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
const { stripPageTitle } = require('../../server/lib/utils')
|
|
2
|
-
|
|
3
1
|
export const historyPushState = () => {
|
|
4
2
|
const url = window.location.href.split('#')[0]
|
|
5
|
-
document.title = stripPageTitle(document.title)
|
|
6
3
|
window.history.pushState({ history: true }, null, `${url}#webchat`)
|
|
7
4
|
}
|
|
8
5
|
|
|
@@ -11,7 +8,6 @@ export const historyReplaceState = () => {
|
|
|
11
8
|
return window.history.back()
|
|
12
9
|
}
|
|
13
10
|
|
|
14
|
-
document.title = stripPageTitle(document.title)
|
|
15
11
|
const url = window.location.href.split('#')[0]
|
|
16
12
|
return window.history.replaceState(null, null, url)
|
|
17
13
|
}
|
|
@@ -2,7 +2,7 @@ import React, { createContext, useEffect, useReducer, useMemo } from 'react'
|
|
|
2
2
|
import { ChatEvent } from '@nice-devone/nice-cxone-chat-web-sdk'
|
|
3
3
|
|
|
4
4
|
import { initialState, reducer } from './reducer.js'
|
|
5
|
-
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY
|
|
5
|
+
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from './constants.js'
|
|
6
6
|
|
|
7
7
|
export const AppContext = createContext(initialState)
|
|
8
8
|
|
|
@@ -88,7 +88,6 @@ export const AppProvider = ({ sdk, availability, playSound, children }) => {
|
|
|
88
88
|
setCustomerId(window.localStorage.getItem(CUSTOMER_ID_STORAGE_KEY))
|
|
89
89
|
setThreadId(window.localStorage.getItem(THREAD_ID_STORAGE_KEY))
|
|
90
90
|
setSettings(JSON.parse(window.localStorage.getItem(SETTINGS_STORAGE_KEY)) || state.settings)
|
|
91
|
-
setUnseenCount(window.localStorage.getItem(MESSAGES_UNSEEN_COUNT))
|
|
92
91
|
}, [])
|
|
93
92
|
|
|
94
93
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { transformMessages, transformMessage } from '../lib/transform-messages'
|
|
2
|
-
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY
|
|
2
|
+
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from './constants'
|
|
3
3
|
|
|
4
4
|
const setSettings = (state, payload) => {
|
|
5
5
|
if (payload) {
|
|
@@ -98,7 +98,6 @@ const setAgentStatus = (state, payload) => {
|
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
const setUnseenCount = (state, payload) => {
|
|
101
|
-
window.localStorage.setItem(MESSAGES_UNSEEN_COUNT, payload)
|
|
102
101
|
return {
|
|
103
102
|
...state,
|
|
104
103
|
unseenCount: payload
|
|
@@ -2,4 +2,3 @@ export const SETTINGS_STORAGE_KEY = 'webchat_settings'
|
|
|
2
2
|
export const CUSTOMER_ID_STORAGE_KEY = 'webchat_customer_id'
|
|
3
3
|
export const THREAD_ID_STORAGE_KEY = 'webchat_thread_id'
|
|
4
4
|
export const TYPING_INDICATOR_DURATION = 4000
|
|
5
|
-
export const MESSAGES_UNSEEN_COUNT = 'message_unseen_count'
|
package/src/server/lib/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const querystring = require('querystring')
|
|
2
2
|
const axios = require('axios')
|
|
3
|
-
const
|
|
3
|
+
const { jwtDecode } = require('jwt-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:
|
|
28
|
+
tenantId: jwtDecode(auth.data.id_token)?.tenantId
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
|
package/src/server/lib/utils.js
CHANGED
|
@@ -18,12 +18,6 @@ const isWithinHours = (days, date) => {
|
|
|
18
18
|
return now.diff(todaysDateTimeOpen).milliseconds >= 0 && now.diff(todaysDateTimeClose).milliseconds <= 0
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
const stripPageTitle = title => {
|
|
22
|
-
const prefixPattern = /^\(\d+ new messages?\) - /
|
|
23
|
-
return title.replace(prefixPattern, '')
|
|
24
|
-
}
|
|
25
|
-
|
|
26
21
|
module.exports = {
|
|
27
|
-
isWithinHours
|
|
28
|
-
stripPageTitle
|
|
22
|
+
isWithinHours
|
|
29
23
|
}
|