@defra/flood-webchat 1.0.6 → 1.0.7
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 +1 -1
- package/src/client/components/availability/availability.jsx +11 -1
- package/src/client/lib/history.js +4 -0
- package/src/client/store/app/AppProvider.jsx +2 -1
- package/src/client/store/app/actions-map.js +2 -1
- package/src/client/store/constants.js +1 -0
- package/src/server/lib/utils.js +7 -1
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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:()=>le});const a=require("react");var n=e.n(a);const o=require("react-dom/client"),l=require("@nice-devone/nice-cxone-chat-web-sdk"),r="webchat_settings",c="webchat_customer_id",s="webchat_thread_id",i=4e3,u={SET_SDK:(e,t)=>({...e,sdk:t}),SET_THREAD:(e,t)=>({...e,thread:t}),SET_CHAT_VISIBILITY:(e,t)=>({...e,isChatOpen:t}),SET_AVAILABILITY:(e,t)=>({...e,availability:t}),SET_SETTINGS:(e,t)=>(t?window.localStorage.setItem(r,JSON.stringify(t)):window.localStorage.removeItem(r),{...e,settings:t}),SET_CUSTOMER_ID:(e,t)=>(t?window.localStorage.setItem(c,t):window.localStorage.removeItem(c),{...e,customerId:t}),SET_THREAD_ID:(e,t)=>(t?window.localStorage.setItem(s,t):window.localStorage.removeItem(s),{...e,threadId: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})},d={sdk:null,availability:null,customerId:null,threadId:null,thread:null,unseenCount:0,instigatorId:null,isChatOpen:!1,isMobile:window.matchMedia("(max-width: 640px)").matches,isKeyboard:!1,settings:{audio:!0,scroll:!0}},m=(e,t)=>{const{type:a,payload:n}=t,o=u[a];return o?o.bind(void 0,e,n)():e},g=(0,a.createContext)(d),E=({availability:e,children:t})=>{const[o,l]=(0,a.useReducer)(m,d);(0,a.useEffect)((()=>{l({type:"SET_AVAILABILITY",payload:e}),v(window.localStorage.getItem(c)),y(window.localStorage.getItem(s)),f(JSON.parse(window.localStorage.getItem(r))||o.settings)}),[]),(0,a.useEffect)((()=>{"#webchat"===window.location.hash&&w(!0);const e=()=>{"#webchat"===window.location.hash?w(!0):w(!1)};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}}),[]);const i=e=>{l({type:"TOGGLE_IS_MOBILE",payload:e.matches})},u=()=>{l({type:"TOGGLE_IS_KEYBOARD",payload:!0})},E=()=>{l({type:"TOGGLE_IS_KEYBOARD",payload:!1})};(0,a.useEffect)((()=>(window.matchMedia("(max-width: 640px)").addEventListener("change",i),window.addEventListener("keydown",u),window.addEventListener("pointerdown",E),()=>{window.removeEventListener("change",i),window.removeEventListener("keydown",u),window.removeEventListener("pointerdown",E)})),[]);const h=e=>{l({type:"SET_SDK",payload:e})},w=e=>{l({type:"SET_CHAT_VISIBILITY",payload:e})},v=e=>{l({type:"SET_CUSTOMER_ID",payload:e})},y=e=>{l({type:"SET_THREAD_ID",payload:e})},b=e=>{l({type:"SET_THREAD",payload:e})},f=e=>{l({type:"SET_SETTINGS",payload:e})},p=e=>{l({type:"SET_UNSEEN_COUNT",payload:e})},k=e=>{l({type:"SET_INSTIGATOR_ID",payload:e})},S=e=>{l({type:"SET_LIVE_REGION_TEXT",payload:e})},_=(0,a.useMemo)((()=>({...o,setSdk:h,setSettings:f,setCustomerId:v,setThreadId:y,setThread:b,setUnseenCount:p,setChatVisibility:w,setInstigatorId:k,setLiveRegionText:S})));return n().createElement(g.Provider,{value:_},t)},h=()=>(0,a.useContext)(g),w=(...e)=>e.filter((e=>e&&"string"==typeof e)).join(" "),v=()=>{const e=window.location.href.split("#")[0];window.history.pushState({history:!0},null,`${e}#webchat`)},y=()=>{if(window.history.state?.history)return window.history.back();const e=window.location.href.split("#")[0];return window.history.replaceState(null,null,e)},b=require("lodash.debounce");var f=e.n(b);const p=require("luxon"),k=require("html-react-parser");var S=e.n(k);const _=/(?:www|https?)[^\s]+/gi,N=e=>(e.match(_)&&(e=e.replace(_,(e=>`<a class="govuk-link" href="${e}" target="_blank" rel="noreferrer">${e.replace(/https?:\/\//gi,"")}</a>`))),S()(e)),T=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}),C=e=>{const t=p.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,c="inbound"===n?o:`${l} (Floodline adviser)`;a+=`[${p.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)},I={SET_MESSAGE:(e,t)=>({...e,message:T(t),messages:[...e.messages,T(t)]}),SET_MESSAGES:(e,t)=>{return{...e,messages:(a=t,a.map((e=>T(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})},A={messages:[],agent:null,agentStatus:null,isAgentTyping:!1},L=(e,t)=>{const{type:a,payload:n}=t,o=I[a];return o?o.bind(void 0,e,n)():e},x=(0,a.createContext)(A),D=({sdk:e,playSound:t,onRecoverError:o,children:c})=>{const[s,i]=(0,a.useReducer)(L,A),{thread:u,threadId:d,setThread:m,setThreadId:g,setUnseenCount:E}=h(),w=e=>{i({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.contact.status}),E(e.detail.data.contact.customerStatistics.unseenMessagesCount)},v=e=>{i({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},y=()=>{i({type:"SET_AGENT_TYPING",payload:!0})},b=()=>{i({type:"SET_AGENT_TYPING",payload:!1}),i({type:"SET_LIVE_REGION_TEXT"})},f=e=>{i({type:"SET_MESSAGE",payload:e.detail.data.message}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status}),E(e.detail.data.case.customerStatistics.unseenMessagesCount),JSON.parse(window.localStorage.getItem(r)).audio&&"outbound"===e.detail.data.message.direction&&t&&t()},p=e=>{i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})};(0,a.useEffect)((()=>{e&&(e.onChatEvent(l.ChatEvent.LIVECHAT_RECOVERED,w),e.onChatEvent(l.ChatEvent.MESSAGE_CREATED,f),e.onChatEvent(l.ChatEvent.AGENT_TYPING_STARTED,y),e.onChatEvent(l.ChatEvent.AGENT_TYPING_ENDED,b),e.onChatEvent(l.ChatEvent.ASSIGNED_AGENT_CHANGED,v),e.onChatEvent(l.ChatEvent.CONTACT_STATUS_CHANGED,p))}),[e]);const k=async e=>{const t=await e.recover(),a=[];let n=t.messages;for(;n.length;){n.map((e=>a.push(e)));try{n=(await e.loadMoreMessages()).data.messages}catch(e){n=[]}}return a};(0,a.useEffect)((()=>{e&&d&&!u&&(console.log("recovering chat..."),(async()=>{try{await e.authorize();const t=await e.getThread(d),a=await k(t);m(t),S(a)}catch(e){console.log("[Chat Error] fetchThread",e),g(),m(),o()}})())}),[e,u,d]);const S=e=>{i({type:"SET_MESSAGES",payload:e})},_=(0,a.useMemo)((()=>({...s,sdk:e,fetchMessages:k,setMessages:S,onLiveChatRecovered:w,onAssignedAgentChanged:v,onAgentTypingStarted:y,onAgentTypingEnded:b,onMessageCreated:f,onContactStatusChanged:p})));return n().createElement(x.Provider,{value:_},c)},G=()=>(0,a.useContext)(x),q=()=>{const{liveRegionText:e,setLiveRegionText:t}=h(),{agentStatus:o}=G(),[l,r]=(0,a.useState)(),[c,s]=(0,a.useState)(),i="closed"===o||null===o,u=()=>{r(),s()},d=(0,a.useCallback)(f()((e=>{l?s(e):r(e)}),2e3),[l,c]);return(0,a.useEffect)((()=>(e&&(u(),d(e)),i&&(u(),t()),()=>{u(),t()})),[e]),n().createElement(n().Fragment,null,n().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},l),n().createElement("div",{className:"wc-live",role:"status","aria-atomic":"true"},c))};function O(){const{availability:e,isChatOpen:t,setChatVisibility:o,unseenCount:l,threadId:r,setUnseenCount:c,setInstigatorId:s,setLiveRegionText:i}=h(),u=(0,a.useRef)(),d=l>0&&!t,m=l>1?"new messages":"new message",g=e=>{e.preventDefault(),c(0),o(!t),s(e.target.id),t?y():v()},E=e=>{" "===e.key&&e.preventDefault()},b=e=>{" "===e.key&&(c(0),o(!t))};switch((0,a.useEffect)((()=>(d&&i(`Floodline webchat - ${l} ${m}`),()=>{i()})),[l,t]),(0,a.useEffect)((()=>{const a=()=>{if(!r)return;if("AVAILABLE"!==e)return;const a=u.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),u.current.classList.toggle("wc-availability--fixed",n)};return document.addEventListener("scroll",a),a(),()=>{document.removeEventListener("scroll",a)}}),[r,t,e]),e){case"EXISTING":case"UNAVAILABLE":return n().createElement("p",{className:"govuk-body"},"When it is available, a 'start chat' link will appear.");case"AVAILABLE":return n().createElement(n().Fragment,null,n().createElement("div",{className:w("wc-availability",t&&"wc-open"),ref:u},n().createElement("div",{className:"wc-availability__inner"},n().createElement("a",{id:"webchat-start-chat-link",className:"wc-availability__link",href:"#webchat",draggable:"false",onClick:g,onKeyUp:b,onKeyDown:E,role:"button","data-module":"govuk-button"},r?n().createElement(n().Fragment,null,"Show chat"):n().createElement(n().Fragment,null,"Start chat"),d?n().createElement("span",{className:"wc-availability__unseen"},l,n().createElement("span",{className:"govuk-visually-hidden"}," ",m)):null))),!t&&n().createElement(q,null));default:return n().createElement("p",{className:"govuk-body"},"Checking availability")}}const R=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()}},M=require("react-dom"),F=()=>{const{threadId:e,setInstigatorId:t}=h();if(!e)return null;const a=document.getElementById("webchat-skip-link-container");return a?n().createElement(n().Fragment,null,(0,M.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 B(){const{thread:e,threadId:t,setChatVisibility:a,setUnseenCount:o,isMobile:l}=h(),r=n=>{n.preventDefault(),a(!1),y(),t&&(e?.lastMessageSeen(),o(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=l&&window.history.state,d=l&&!window.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"},u?c:null,n().createElement("h2",{id:"wc-header",className:"wc-header__title"},"Floodline webchat"),m)}function U({onContinue:e}){return n().createElement(n().Fragment,null,n().createElement(B,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 Y=require("uuid"),K=({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]))))))))},$=500;function V({initSdk:e,onPreChatScreen:t}){const{setSdk:o,setCustomerId:l,setThreadId:r,setThread:c,setLiveRegionText:s}=h(),[i,u]=(0,a.useState)({}),[d,m]=(0,a.useState)(0),[g,E]=(0,a.useState)(!1),v=(0,a.useRef)(),y=(0,a.useRef)(),b=$>=d;let f=`You have ${$-d} characters remaining`;b||(f=`You have ${d-$} characters too many`),(0,a.useEffect)((()=>{Object.keys(i).length&&document.querySelector(".govuk-error-summary")?.focus()}),[i]);const p=g?"Requesting...":"Request chat";return(0,a.useEffect)((()=>{g&&s(p)}),[g]),n().createElement(n().Fragment,null,n().createElement(B,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:t},"What you can use webchat for"),n().createElement(K,{errors:i}),n().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Your name and question"),n().createElement("form",null,n().createElement("div",{className:w("wc-form-group","govuk-form-group",i.name&&"govuk-form-group--error")},n().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-name"},"Your name"),i.name&&n().createElement("p",{className:"govuk-error-message"},n().createElement("span",{className:"govuk-visually-hidden"},"Error:")," ",i.name),n().createElement("input",{ref:v,className:w("wc-input","govuk-input",i.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:w("govuk-form-group",i.question&&"govuk-form-group--error")},n().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-question"},"Your question"),i.question&&n().createElement("p",{className:"govuk-error-message"},n().createElement("span",{className:"govuk-visually-hidden"},"Error:"),i.question),n().createElement("textarea",{ref:y,id:"wc-question",name:"question",rows:"5","aria-describedby":"wc-question-info",onChange:e=>{m(e.target.value.length)},className:w("wc-textarea","govuk-textarea","govuk-js-character-count",!b||i.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:b?"":"#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 t=>{if(t.preventDefault(),g)return;const a={};if(0===v.current.value.length&&(a.name="Enter your name"),0===y.current.value.length&&(a.question="Enter your question"),y.current.value.length>$&&(a.question="Your question must be 500 characters or less"),0===Object.keys(a).length)try{E(!0);const t=Y.v4(),a=e(),n=await a.authorize(),s=n?.consumerIdentity.idOnExternalPlatform,i=await a.getThread(t);i.setCustomField("threadid",t),await a.getCustomer().setName(v.current.value),await i.startChat(y.current.value||"Begin conversation"),o(a),l(s),r(t),c(i)}catch(e){console.log("[Request chat Error]",e)}u(a)},"aria-disabled":g},p)))))}function H({children:e}){return n().createElement("div",{className:"wc-footer"},e)}function P({message:e,previousMessage:t}){const a="outbound"===e.direction,o=e?.direction===t?.direction;return n().createElement("li",{className:w("wc-chat__message",a?"outbound":"inbound")},n().createElement("div",{className:"wc-chat__from"},o?null:n().createElement("span",{className:w(a?"outbound":"inbound")},a?e.assignee:"You"),n().createElement("span",{className:"govuk-visually-hidden"},":")),n().createElement("div",{className:w("wc-chat__text",a?"outbound":"inbound")},N(e.text)))}const j=(e,t)=>{(0,a.useEffect)((()=>{if(e){e.style.height="0px";const t=e.scrollHeight;e.style.height=`${t}px`}}),[e,t])},W=(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 J({onEndChatScreen:e,onSettingsScreen:t}){const{availability:o,thread:l,isChatOpen:r,settings:c,isKeyboard:s,setLiveRegionText:u}=h(),{messages:d,agent:m,agentStatus:g,isAgentTyping:E}=G(),[w,v]=(0,a.useState)(""),[y,b]=(0,a.useState)(),[f,p]=(0,a.useState)(),[k,S]=(0,a.useState)(!1),_=(0,a.useRef)();j(_.current,w),(0,a.useEffect)((()=>{if(c.scroll&&0!==d.length){const e=document.querySelector(".wc-body");e.scrollTop=e.scrollHeight}}),[d,E]),(0,a.useEffect)((()=>{const e=document.querySelector(".wc-form__label");0===w.length?e.classList.remove("govuk-visually-hidden"):e.classList.add("govuk-visually-hidden")}),[w]),(0,a.useEffect)((()=>{b(m?.nickname||m?.firstName),p(W(o,g,y))}),[m,y,g]),(0,a.useEffect)((()=>(f&&r&&u(`Floodline webchat - ${f}`),()=>{u()})),[f,r]),(0,a.useEffect)((()=>(E&&r&&u(`${y} is typing...`),()=>{u()})),[E,r]),(0,a.useEffect)((()=>{const e=d[d.length-1];return"closed"!==g&&"outbound"===e?.direction&&r&&u(`${y} said: ${e.text}`),()=>{u()}}),[d,r]);const N=()=>{if(0!==_.current.value.length&&"closed"!==g){try{const e=_.current.value.trim();l.sendTextMessage(e),u(`You said: ${e}`)}catch(e){console.log("[Chat Error] sendMessage",e)}v("")}},T=()=>{const e=C(d);document.querySelector("#transcript-download").setAttribute("href",`data:text/plain;charset=utf-8,${e}`)},I=a=>{if("Enter"!==a.key||a.shiftKey)" "===a.key?("end-chat"===a.target.id&&e(a),"wc-settings"===a.target.id&&t(a)):(l.keystroke(),setTimeout((()=>{l.stopTyping()}),i));else switch(a.target.id){case"text-area":a.preventDefault(),N();break;case"end-chat":e(a);break;case"wc-settings":t(a);break;case"transcript-download":T()}};return n().createElement(n().Fragment,null,n().createElement(B,null),n().createElement("div",{className:"wc-status"},n().createElement("p",{className:"wc-status__availability"},f),n().createElement("a",{id:"end-chat",className:"wc-status__link",href:"#","data-module":"govuk-button",role:"button",onClick:e,onKeyDown:I},"End chat")),n().createElement("div",{className:"wc-body",tabIndex:"0"},n().createElement("ul",{className:"wc-chat"},d.length?d.map(((e,t)=>n().createElement(P,{key:e.id,message:e,previousMessage:d[t-1]}))):null,E?n().createElement("li",{className:"wc-chat__message outbound"},n().createElement("div",{className:"wc-chat__from"},y," 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(H,null,n().createElement("form",{className:"wc-form"+(k?" wc-focus-within":""),noValidate:!0,onSubmit:e=>{e.preventDefault(),N()}},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:_,rows:"1","aria-required":"true",className:"wc-form__textarea",id:"text-area",name:"message",onChange:e=>{v(e.target?.value)},onKeyDown:I,onFocus:()=>{S(s)},onBlur:()=>{S(!1)},value:w}),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:I,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:I,onClick:T},"Save chat"))))}function X(){return n().createElement(n().Fragment,null,n().createElement(B,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 Z({onChatScreen:e,onEndChatConfirm:t}){const{thread:o,setSdk:l,setCustomerId:r,setThreadId:c,threadId:s,setUnseenCount:i,isKeyboard:u}=h(),{agentStatus:d,setMessages:m}=G(),g=async e=>{e.preventDefault(),window.localStorage.setItem("tmpThreadId",s),o?.lastMessageSeen(),l(),c(),m([]),r(),i(0),"closed"!==d&&o.endChat(),t(e)};(0,a.useEffect)((()=>{u&&setTimeout((()=>{document.querySelector("#confirm-endchat").focus()}),10)}),[]);const E=t=>{"Enter"!==t.key&&" "!==t.key||"confirm-endchat"!==t.target.id||g(t),"Enter"!==t.key&&" "!==t.key||"resume-chat"!==t.target.id||e(t)};return n().createElement(n().Fragment,null,n().createElement(B,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:g,onKeyDown:E},"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:E},"No, resume chat")))))}function z({onCancel:e}){const{settings:t,setSettings:o}=h(),[l,r]=(0,a.useState)(t.audio),[c,s]=(0,a.useState)(t.scroll),i=t=>{t.preventDefault(),o({audio:l,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(B,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:l,onChange:()=>r(!l)}),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 Q({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)},o=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(B,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:o,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:o,onClick:a},"Close")))))}const ee="aria-hidden",te="data-wc-inert",ae=e=>{for(const t of document.body.children)"wc-panel"!==t.id&&(e&&!t.getAttribute(ee)?(t.setAttribute(ee,"true"),t.setAttribute(te,"")):t.hasAttribute(te)&&(t.removeAttribute(ee),t.removeAttribute(te)))},ne=(e,t)=>{const[n,o]=(0,a.useState)([]),l=(0,a.useCallback)((e=>{const t=document.querySelector("#wc-panel");"Tab"===e.key&&(t&&!document.activeElement.closest("#wc-panel")&&t.focus(),e.shiftKey?(document.activeElement===n[0]||document.activeElement===document.querySelector("#wc-panel"))&&(n[n.length-1].focus(),e.preventDefault()):document.activeElement===n[n.length-1]&&(n[0].focus(),e.preventDefault()))}),[n]);(0,a.useEffect)((()=>{o((()=>{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)((()=>(t&&(ae(!0),document.querySelector("#wc-panel").focus(),document.addEventListener("keydown",l)),()=>{ae(),document.removeEventListener("keydown",l)})),[n,t])};function oe({initSdk:e,playSound:t}){const{sdk:o,thread:l,availability:r,instigatorId:c,threadId:s,setSdk:i,setChatVisibility:u,setUnseenCount:d,isMobile:m,isKeyboard:g,isChatOpen:E}=h(),[v,b]=(0,a.useState)(s?2:0);ne(v,E);const f=(0,a.useCallback)((e=>{"Escape"!==e.key&&"Esc"!==e.key||(s&&(l?.lastMessageSeen(),d(0)),u(!1),y())}),[l,s,d,u]);(0,a.useEffect)((()=>{E||document.getElementById(c)?.focus()}),[E]),(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")})),[m]),(0,a.useEffect)((()=>(document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f)})),[f,u]),(0,a.useEffect)((()=>{E&&s&&(l||i(e()),b(2))}),[E,l,s]);const p=e=>t=>{t.preventDefault(),b(e)},k=p(0),S=p(1),_=p(2),N=p(3),T=p(4),C=p(5);let I;switch(v){case 0:default:I=n().createElement(U,{onContinue:S});break;case 1:I=n().createElement(V,{initSdk:e,onPreChatScreen:k});break;case 2:I=n().createElement(D,{sdk:o,playSound:t,onRecoverError:()=>b(0)},n().createElement(J,{onSettingsScreen:C,onEndChatScreen:N}));break;case 3:I=n().createElement(D,{sdk:o,playSound:t},n().createElement(Z,{onChatScreen:_,onEndChatConfirm:T}));break;case 4:I=n().createElement(Q,{onCancel:()=>{u(!1),y(),b(0)}});break;case 5:I=n().createElement(D,{sdk:o,playSound:t},n().createElement(z,{onCancel:_}))}"UNAVAILABLE"===r&&(I=n().createElement(X,null));const A=n().createElement("div",{id:"wc-panel",role:"dialog",style:{display:E?"flex":"none"},className:w("wc-panel",g&&"wc-focus-visible"),tabIndex:"-1","aria-modal":"true","aria-labelledby":"wc-header wc-subtitle",open:E},n().createElement("div",{className:"wc-panel__inner"},I),n().createElement(q,null));return n().createElement(n().Fragment,null,(0,M.createPortal)(A,document.body))}async function le(e,t){const a=(0,o.createRoot)(e);let r,s;try{const e=await async function(e){const t=await fetch(e);return{availability:(await t.json()).availability||"UNAVAILABLE"}}(t.availabilityEndpoint);s=await R(t.audioUrl),r=e.availability}catch(e){r="UNAVAILABLE"}a.render(n().createElement(E,{availability:r},n().createElement(O,null),n().createElement(F,null),n().createElement(oe,{initSdk:()=>new l.ChatSdk({brandId:t.brandId,channelId:t.channelId,customerId:window.localStorage.getItem(c)||"",environment:t.environment,onError:e=>{console.log("ChatSdk onError",e)}}),playSound:s})))}module.exports=t})();
|
|
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:()=>ce});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="webchat_settings",s="webchat_customer_id",c="webchat_thread_id",i=4e3,u="message_unseen_count",d={SET_SDK:(e,t)=>({...e,sdk:t}),SET_THREAD:(e,t)=>({...e,thread:t}),SET_CHAT_VISIBILITY:(e,t)=>({...e,isChatOpen:t}),SET_AVAILABILITY:(e,t)=>({...e,availability:t}),SET_SETTINGS:(e,t)=>(t?window.localStorage.setItem(r,JSON.stringify(t)):window.localStorage.removeItem(r),{...e,settings:t}),SET_CUSTOMER_ID:(e,t)=>(t?window.localStorage.setItem(s,t):window.localStorage.removeItem(s),{...e,customerId:t}),SET_THREAD_ID:(e,t)=>(t?window.localStorage.setItem(c,t):window.localStorage.removeItem(c),{...e,threadId:t}),SET_UNSEEN_COUNT:(e,t)=>(window.localStorage.setItem(u,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})},m={sdk:null,availability:null,customerId:null,threadId:null,thread:null,unseenCount:0,instigatorId:null,isChatOpen:!1,isMobile:window.matchMedia("(max-width: 640px)").matches,isKeyboard:!1,settings:{audio:!0,scroll:!0}},g=(e,t)=>{const{type:a,payload:n}=t,o=d[a];return o?o.bind(void 0,e,n)():e},E=(0,e.createContext)(m),h=({availability:a,children:n})=>{const[o,l]=(0,e.useReducer)(g,m);(0,e.useEffect)((()=>{l({type:"SET_AVAILABILITY",payload:a}),b(window.localStorage.getItem(s)),y(window.localStorage.getItem(c)),p(JSON.parse(window.localStorage.getItem(r))||o.settings),k(window.localStorage.getItem(u))}),[]),(0,e.useEffect)((()=>{"#webchat"===window.location.hash&&v(!0);const e=()=>{"#webchat"===window.location.hash?v(!0):v(!1)};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}}),[]);const i=e=>{l({type:"TOGGLE_IS_MOBILE",payload:e.matches})},d=()=>{l({type:"TOGGLE_IS_KEYBOARD",payload:!0})},h=()=>{l({type:"TOGGLE_IS_KEYBOARD",payload:!1})};(0,e.useEffect)((()=>(window.matchMedia("(max-width: 640px)").addEventListener("change",i),window.addEventListener("keydown",d),window.addEventListener("pointerdown",h),()=>{window.removeEventListener("change",i),window.removeEventListener("keydown",d),window.removeEventListener("pointerdown",h)})),[]);const w=e=>{l({type:"SET_SDK",payload:e})},v=e=>{l({type:"SET_CHAT_VISIBILITY",payload:e})},b=e=>{l({type:"SET_CUSTOMER_ID",payload:e})},y=e=>{l({type:"SET_THREAD_ID",payload:e})},f=e=>{l({type:"SET_THREAD",payload:e})},p=e=>{l({type:"SET_SETTINGS",payload:e})},k=e=>{l({type:"SET_UNSEEN_COUNT",payload:e})},S=e=>{l({type:"SET_INSTIGATOR_ID",payload:e})},_=e=>{l({type:"SET_LIVE_REGION_TEXT",payload:e})},N=(0,e.useMemo)((()=>({...o,setSdk:w,setSettings:p,setCustomerId:b,setThreadId:y,setThread:f,setUnseenCount:k,setChatVisibility:v,setInstigatorId:S,setLiveRegionText:_})));return t().createElement(E.Provider,{value:N},n)},w=()=>(0,e.useContext)(E),v=(...e)=>e.filter((e=>e&&"string"==typeof e)).join(" "),{stripPageTitle:b}=a(792),y=()=>{const e=window.location.href.split("#")[0];document.title=b(document.title),window.history.pushState({history:!0},null,`${e}#webchat`)},f=()=>{if(window.history.state?.history)return window.history.back();document.title=b(document.title);const e=window.location.href.split("#")[0];return window.history.replaceState(null,null,e)},p=require("lodash.debounce");var k=a.n(p),S=a(168);const _=require("html-react-parser");var N=a.n(_);const T=/(?:www|https?)[^\s]+/gi,C=e=>(e.match(T)&&(e=e.replace(T,(e=>`<a class="govuk-link" href="${e}" target="_blank" rel="noreferrer">${e.replace(/https?:\/\//gi,"")}</a>`))),N()(e)),I=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}),L=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:o,assignee:l,createdAt:r}=t,s="inbound"===n?o:`${l} (Floodline adviser)`;a+=`[${S.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)},A={SET_MESSAGE:(e,t)=>({...e,message:I(t),messages:[...e.messages,I(t)]}),SET_MESSAGES:(e,t)=>{return{...e,messages:(a=t,a.map((e=>I(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})},x={messages:[],agent:null,agentStatus:null,isAgentTyping:!1},D=(e,t)=>{const{type:a,payload:n}=t,o=A[a];return o?o.bind(void 0,e,n)():e},G=(0,e.createContext)(x),q=({sdk:a,playSound:n,onRecoverError:o,children:s})=>{const[c,i]=(0,e.useReducer)(D,x),{thread:u,threadId:d,setThread:m,setThreadId:g,setUnseenCount:E}=w(),h=e=>{i({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.contact.status}),E(e.detail.data.contact.customerStatistics.unseenMessagesCount)},v=e=>{i({type:"SET_AGENT",payload:e.detail.data.inboxAssignee}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})},b=()=>{i({type:"SET_AGENT_TYPING",payload:!0})},y=()=>{i({type:"SET_AGENT_TYPING",payload:!1}),i({type:"SET_LIVE_REGION_TEXT"})},f=e=>{i({type:"SET_MESSAGE",payload:e.detail.data.message}),i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status}),E(e.detail.data.case.customerStatistics.unseenMessagesCount),JSON.parse(window.localStorage.getItem(r)).audio&&"outbound"===e.detail.data.message.direction&&n&&n()},p=e=>{i({type:"SET_AGENT_STATUS",payload:e.detail.data.case.status})};(0,e.useEffect)((()=>{a&&(a.onChatEvent(l.ChatEvent.LIVECHAT_RECOVERED,h),a.onChatEvent(l.ChatEvent.MESSAGE_CREATED,f),a.onChatEvent(l.ChatEvent.AGENT_TYPING_STARTED,b),a.onChatEvent(l.ChatEvent.AGENT_TYPING_ENDED,y),a.onChatEvent(l.ChatEvent.ASSIGNED_AGENT_CHANGED,v),a.onChatEvent(l.ChatEvent.CONTACT_STATUS_CHANGED,p))}),[a]);const k=async e=>{const t=await e.recover(),a=[];let n=t.messages;for(;n.length;){n.map((e=>a.push(e)));try{n=(await e.loadMoreMessages()).data.messages}catch(e){n=[]}}return a};(0,e.useEffect)((()=>{a&&d&&!u&&(console.log("recovering chat..."),(async()=>{try{await a.authorize();const e=await a.getThread(d),t=await k(e);m(e),S(t)}catch(e){console.log("[Chat Error] fetchThread",e),g(),m(),o()}})())}),[a,u,d]);const S=e=>{i({type:"SET_MESSAGES",payload:e})},_=(0,e.useMemo)((()=>({...c,sdk:a,fetchMessages:k,setMessages:S,onLiveChatRecovered:h,onAssignedAgentChanged:v,onAgentTypingStarted:b,onAgentTypingEnded:y,onMessageCreated:f,onContactStatusChanged:p})));return t().createElement(G.Provider,{value:_},s)},O=()=>(0,e.useContext)(G),R=()=>{const{liveRegionText:a,setLiveRegionText:n}=w(),{agentStatus:o}=O(),[l,r]=(0,e.useState)(),[s,c]=(0,e.useState)(),i="closed"===o||null===o,u=()=>{r(),c()},d=(0,e.useCallback)(k()((e=>{l?c(e):r(e)}),2e3),[l,s]);return(0,e.useEffect)((()=>(a&&(u(),d(a)),i&&(u(),n()),()=>{u(),n()})),[a]),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))},{stripPageTitle:M}=a(792);function F(){const{availability:a,isChatOpen:n,setChatVisibility:o,unseenCount:l,threadId:r,setUnseenCount:s,setInstigatorId:c,setLiveRegionText:i}=w(),u=(0,e.useRef)(),d=l>1?"new messages":"new message",m=l>0&&!n,g=M(document.title),E=e=>{e.preventDefault(),s(0),o(!n),c(e.target.id),n?f():y()},h=e=>{" "===e.key&&e.preventDefault()},b=e=>{" "===e.key&&(s(0),o(!n))};switch((0,e.useEffect)((()=>{m&&(document.title=`(${l} ${d}) - ${g}`)}),[l]),(0,e.useEffect)((()=>(m&&i(`Floodline webchat - ${l} ${d}`),()=>{i()})),[l,n]),(0,e.useEffect)((()=>{const e=()=>{if(!r)return;if("AVAILABLE"!==a)return;const e=u.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),u.current.classList.toggle("wc-availability--fixed",t)};return document.addEventListener("scroll",e),e(),()=>{document.removeEventListener("scroll",e)}}),[r,n,a]),a){case"EXISTING":case"UNAVAILABLE":return t().createElement("p",{className:"govuk-body"},"When it is available, a 'start chat' link will appear.");case"AVAILABLE":return t().createElement(t().Fragment,null,t().createElement("div",{className:v("wc-availability",n&&"wc-open"),ref:u},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:b,onKeyDown:h,role:"button","data-module":"govuk-button"},r?t().createElement(t().Fragment,null,"Show chat"):t().createElement(t().Fragment,null,"Start chat"),m?t().createElement("span",{className:"wc-availability__unseen"},l,t().createElement("span",{className:"govuk-visually-hidden"}," ",d)):null))),!n&&t().createElement(R,null));default:return t().createElement("p",{className:"govuk-body"},"Checking availability")}}const B=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()}},U=require("react-dom"),$=()=>{const{threadId:e,setInstigatorId:a}=w();if(!e)return null;const n=document.getElementById("webchat-skip-link-container");return n?t().createElement(t().Fragment,null,(0,U.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};function Y(){const{thread:e,threadId:a,setChatVisibility:n,setUnseenCount:o,isMobile:l}=w(),r=t=>{t.preventDefault(),n(!1),f(),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 K({onContinue:e}){return t().createElement(t().Fragment,null,t().createElement(Y,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 V=require("uuid"),P=({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]))))))))},H=500;function j({initSdk:a,onPreChatScreen:n}){const{setSdk:o,setCustomerId:l,setThreadId:r,setThread:s,setLiveRegionText:c}=w(),[i,u]=(0,e.useState)({}),[d,m]=(0,e.useState)(0),[g,E]=(0,e.useState)(!1),h=(0,e.useRef)(),b=(0,e.useRef)(),y=H>=d;let f=`You have ${H-d} characters remaining`;y||(f=`You have ${d-H} characters too many`),(0,e.useEffect)((()=>{Object.keys(i).length&&document.querySelector(".govuk-error-summary")?.focus()}),[i]);const p=g?"Requesting...":"Request chat";return(0,e.useEffect)((()=>{g&&c(p)}),[g]),t().createElement(t().Fragment,null,t().createElement(Y,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:n},"What you can use webchat for"),t().createElement(P,{errors:i}),t().createElement("h3",{id:"wc-subtitle",className:"wc-heading","aria-live":"polite"},"Your name and question"),t().createElement("form",null,t().createElement("div",{className:v("wc-form-group","govuk-form-group",i.name&&"govuk-form-group--error")},t().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-name"},"Your name"),i.name&&t().createElement("p",{className:"govuk-error-message"},t().createElement("span",{className:"govuk-visually-hidden"},"Error:")," ",i.name),t().createElement("input",{ref:h,className:v("wc-input","govuk-input",i.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:v("govuk-form-group",i.question&&"govuk-form-group--error")},t().createElement("label",{className:"wc-label govuk-label",htmlFor:"wc-question"},"Your question"),i.question&&t().createElement("p",{className:"govuk-error-message"},t().createElement("span",{className:"govuk-visually-hidden"},"Error:"),i.question),t().createElement("textarea",{ref:b,id:"wc-question",name:"question",rows:"5","aria-describedby":"wc-question-info",onChange:e=>{m(e.target.value.length)},className:v("wc-textarea","govuk-textarea","govuk-js-character-count",!y||i.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(),g)return;const t={};if(0===h.current.value.length&&(t.name="Enter your name"),0===b.current.value.length&&(t.question="Enter your question"),b.current.value.length>H&&(t.question="Your question must be 500 characters or less"),0===Object.keys(t).length)try{E(!0);const e=V.v4(),t=a(),n=await t.authorize(),c=n?.consumerIdentity.idOnExternalPlatform,i=await t.getThread(e);i.setCustomField("threadid",e),await t.getCustomer().setName(h.current.value),await i.startChat(b.current.value||"Begin conversation"),o(t),l(c),r(e),s(i)}catch(e){console.log("[Request chat Error]",e)}u(t)},"aria-disabled":g},p)))))}function W({children:e}){return t().createElement("div",{className:"wc-footer"},e)}function J({message:e,previousMessage:a}){const n="outbound"===e.direction,o=e?.direction===a?.direction;return t().createElement("li",{className:v("wc-chat__message",n?"outbound":"inbound")},t().createElement("div",{className:"wc-chat__from"},o?null:t().createElement("span",{className:v(n?"outbound":"inbound")},n?e.assignee:"You"),t().createElement("span",{className:"govuk-visually-hidden"},":")),t().createElement("div",{className:v("wc-chat__text",n?"outbound":"inbound")},C(e.text)))}const Z=(t,a)=>{(0,e.useEffect)((()=>{if(t){t.style.height="0px";const e=t.scrollHeight;t.style.height=`${e}px`}}),[t,a])},X=(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 z({onEndChatScreen:a,onSettingsScreen:n}){const{availability:o,thread:l,isChatOpen:r,settings:s,isKeyboard:c,setLiveRegionText:u}=w(),{messages:d,agent:m,agentStatus:g,isAgentTyping:E}=O(),[h,v]=(0,e.useState)(""),[b,y]=(0,e.useState)(),[f,p]=(0,e.useState)(),[k,S]=(0,e.useState)(!1),_=(0,e.useRef)();Z(_.current,h),(0,e.useEffect)((()=>{if(s.scroll&&0!==d.length){const e=document.querySelector(".wc-body");e.scrollTop=e.scrollHeight}}),[d,E]),(0,e.useEffect)((()=>{const e=document.querySelector(".wc-form__label");0===h.length?e.classList.remove("govuk-visually-hidden"):e.classList.add("govuk-visually-hidden")}),[h]),(0,e.useEffect)((()=>{y(m?.nickname||m?.firstName),p(X(o,g,b))}),[m,b,g]),(0,e.useEffect)((()=>(f&&r&&u(`Floodline webchat - ${f}`),()=>{u()})),[f,r]),(0,e.useEffect)((()=>(E&&r&&u(`${b} is typing...`),()=>{u()})),[E,r]),(0,e.useEffect)((()=>{const e=d[d.length-1];return"closed"!==g&&"outbound"===e?.direction&&r&&u(`${b} said: ${e.text}`),()=>{u()}}),[d,r]);const N=()=>{if(0!==_.current.value.length&&"closed"!==g){try{const e=_.current.value.trim();l.sendTextMessage(e),u(`You said: ${e}`)}catch(e){console.log("[Chat Error] sendMessage",e)}v("")}},T=()=>{const e=L(d);document.querySelector("#transcript-download").setAttribute("href",`data:text/plain;charset=utf-8,${e}`)},C=e=>{if("Enter"!==e.key||e.shiftKey)" "===e.key?("end-chat"===e.target.id&&a(e),"wc-settings"===e.target.id&&n(e)):(l.keystroke(),setTimeout((()=>{l.stopTyping()}),i));else switch(e.target.id){case"text-area":e.preventDefault(),N();break;case"end-chat":a(e);break;case"wc-settings":n(e);break;case"transcript-download":T()}};return t().createElement(t().Fragment,null,t().createElement(Y,null),t().createElement("div",{className:"wc-status"},t().createElement("p",{className:"wc-status__availability"},f),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"},d.length?d.map(((e,a)=>t().createElement(J,{key:e.id,message:e,previousMessage:d[a-1]}))):null,E?t().createElement("li",{className:"wc-chat__message outbound"},t().createElement("div",{className:"wc-chat__from"},b," 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(W,null,t().createElement("form",{className:"wc-form"+(k?" wc-focus-within":""),noValidate:!0,onSubmit:e=>{e.preventDefault(),N()}},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:_,rows:"1","aria-required":"true",className:"wc-form__textarea",id:"text-area",name:"message",onChange:e=>{v(e.target?.value)},onKeyDown:C,onFocus:()=>{S(c)},onBlur:()=>{S(!1)},value:h}),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:T},"Save chat"))))}function Q(){return t().createElement(t().Fragment,null,t().createElement(Y,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 ee({onChatScreen:a,onEndChatConfirm:n}){const{thread:o,setSdk:l,setCustomerId:r,setThreadId:s,threadId:c,setUnseenCount:i,isKeyboard:u}=w(),{agentStatus:d,setMessages:m}=O(),g=async e=>{e.preventDefault(),window.localStorage.setItem("tmpThreadId",c),o?.lastMessageSeen(),l(),s(),m([]),r(),i(0),"closed"!==d&&o.endChat(),n(e)};(0,e.useEffect)((()=>{u&&setTimeout((()=>{document.querySelector("#confirm-endchat").focus()}),10)}),[]);const E=e=>{"Enter"!==e.key&&" "!==e.key||"confirm-endchat"!==e.target.id||g(e),"Enter"!==e.key&&" "!==e.key||"resume-chat"!==e.target.id||a(e)};return t().createElement(t().Fragment,null,t().createElement(Y,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:g,onKeyDown:E},"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:E},"No, resume chat")))))}function te({onCancel:a}){const{settings:n,setSettings:o}=w(),[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(Y,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 ae({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(Y,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 ne="aria-hidden",oe="data-wc-inert",le=e=>{for(const t of document.body.children)"wc-panel"!==t.id&&(e&&!t.getAttribute(ne)?(t.setAttribute(ne,"true"),t.setAttribute(oe,"")):t.hasAttribute(oe)&&(t.removeAttribute(ne),t.removeAttribute(oe)))},re=(t,a)=>{const[n,o]=(0,e.useState)([]),l=(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===n[0]||document.activeElement===document.querySelector("#wc-panel"))&&(n[n.length-1].focus(),e.preventDefault()):document.activeElement===n[n.length-1]&&(n[0].focus(),e.preventDefault()))}),[n]);(0,e.useEffect)((()=>{o((()=>{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)((()=>(a&&(le(!0),document.querySelector("#wc-panel").focus(),document.addEventListener("keydown",l)),()=>{le(),document.removeEventListener("keydown",l)})),[n,a])};function se({initSdk:a,playSound:n}){const{sdk:o,thread:l,availability:r,instigatorId:s,threadId:c,setSdk:i,setChatVisibility:u,setUnseenCount:d,isMobile:m,isKeyboard:g,isChatOpen:E}=w(),[h,b]=(0,e.useState)(c?2:0);re(h,E);const y=(0,e.useCallback)((e=>{"Escape"!==e.key&&"Esc"!==e.key||(c&&(l?.lastMessageSeen(),d(0)),u(!1),f())}),[l,c,d,u]);(0,e.useEffect)((()=>{E||document.getElementById(s)?.focus()}),[E]),(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")})),[m]),(0,e.useEffect)((()=>(document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)})),[y,u]),(0,e.useEffect)((()=>{E&&c&&(l||i(a()),b(2))}),[E,l,c]);const p=e=>t=>{t.preventDefault(),b(e)},k=p(0),S=p(1),_=p(2),N=p(3),T=p(4),C=p(5);let I;switch(h){case 0:default:I=t().createElement(K,{onContinue:S});break;case 1:I=t().createElement(j,{initSdk:a,onPreChatScreen:k});break;case 2:I=t().createElement(q,{sdk:o,playSound:n,onRecoverError:()=>b(0)},t().createElement(z,{onSettingsScreen:C,onEndChatScreen:N}));break;case 3:I=t().createElement(q,{sdk:o,playSound:n},t().createElement(ee,{onChatScreen:_,onEndChatConfirm:T}));break;case 4:I=t().createElement(ae,{onCancel:()=>{u(!1),f(),b(0)}});break;case 5:I=t().createElement(q,{sdk:o,playSound:n},t().createElement(te,{onCancel:_}))}"UNAVAILABLE"===r&&(I=t().createElement(Q,null));const L=t().createElement("div",{id:"wc-panel",role:"dialog",style:{display:E?"flex":"none"},className:v("wc-panel",g&&"wc-focus-visible"),tabIndex:"-1","aria-modal":"true","aria-labelledby":"wc-header wc-subtitle",open:E},t().createElement("div",{className:"wc-panel__inner"},I),t().createElement(R,null));return t().createElement(t().Fragment,null,(0,U.createPortal)(L,document.body))}async function ce(e,a){const n=(0,o.createRoot)(e);let r,c;try{const e=await async function(e){const t=await fetch(e);return{availability:(await t.json()).availability||"UNAVAILABLE"}}(a.availabilityEndpoint);c=await B(a.audioUrl),r=e.availability}catch(e){r="UNAVAILABLE"}n.render(t().createElement(h,{availability:r},t().createElement(F,null),t().createElement($,null),t().createElement(se,{initSdk:()=>new l.ChatSdk({brandId:a.brandId,channelId:a.channelId,customerId:window.localStorage.getItem(s)||"",environment:a.environment,onError:e=>{console.log("ChatSdk onError",e)}}),playSound:c})))}})(),module.exports=n})();
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var e={525:(e,t,n)=>{const{authenticate:o,getApiBaseUrl:a,getIsOpen:
|
|
1
|
+
(()=>{var e={525:(e,t,n)=>{const{authenticate:o,getApiBaseUrl:a,getIsOpen:s,getActivity:i}=n(398);e.exports=async function({clientId:e,clientSecret:t,accessKey:n,accessSecret:r,maxQueueCount:c,skillEndpoint:l,hoursEndpoint:u,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:g,tokenType:w}=await o({authenticationUri:d,authorisation:h,accessKey:n,accessSecret:r}),y=await a({wellKnownUri:p,tenantId:m}),[{hasCapacity:A,hasAgentsAvailable:k},f]=await Promise.all([i({baseUrl:y,tokenType:w,token:g,skillEndpoint:l,maxQueueCount:c}),s({baseUrl:y,token:g,tokenType:w,hoursEndpoint:u})]);let x="UNAVAILABLE";return f&&k&&A?x="AVAILABLE":f&&k&&!A&&(x="EXISTING"),{date:new Date,availability:x}}},398:(e,t,n)=>{const o=n(45),a=n(938),s=n(158),{isWithinHours:i}=n(792),r="application/x-www-form-urlencoded";e.exports={authenticate:async({authenticationUri:e,authorisation:t,accessKey:n,accessSecret:i})=>{const c=new URL(e),l=o.stringify({grant_type:"password",username:n,password:i}),u=await a.post(c.href,l,{signal:AbortSignal.timeout(3e3),headers:{Host:c.host,"Content-Type":r,Authorization:t}});return{token:u.data.access_token,tokenType:u.data.token_type,tenantId:s(u.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 s=new URL(o,e),c=(await a.get(s.href,{signal:AbortSignal.timeout(3e3),headers:{Host:s.host,Authorization:`${n} ${t}`,"Content-Type":r}})).data.resultSet.hoursOfOperationProfiles[0].days;return i(c)},getActivity:async({tokenType:e,token:t,baseUrl:n,skillEndpoint:o,maxQueueCount:s})=>{const i=new URL(o,n),c=(await a.get(i.href,{signal:AbortSignal.timeout(3e3),headers:{Host:i.host,Authorization:`${e} ${t}`,"Content-Type":r}})).data.skillActivity[0];return{hasCapacity:c.queueCount<s,hasAgentsAvailable:c.agentsAvailable>=1}}}},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 s=t?new Date(t):new Date,i=s.toLocaleDateString("en-GB",{weekday:"long"}),r=s.toLocaleDateString("en-GB").split("/"),c=e.find((e=>e.day===i)),l=o.local(Number(r[2]),Number(r[1]),Number(r[0]),a(c.openTime)),u=o.local(Number(r[2]),Number(r[1]),Number(r[0]),a(c.closeTime));return n.diff(l).milliseconds>=0&&n.diff(u).milliseconds<=0},stripPageTitle:e=>e.replace(/^\(\d+ new messages?\) - /,"")}},938:e=>{"use strict";e.exports=require("axios")},158:e=>{"use strict";e.exports=require("jwt-decode")},168:e=>{"use strict";e.exports=require("luxon")},45:e=>{"use strict";e.exports=require("querystring")}},t={},n=function n(o){var a=t[o];if(void 0!==a)return a.exports;var s=t[o]={exports:{}};return e[o](s,s.exports,n),s.exports}(525);module.exports=n})();
|
package/package.json
CHANGED
|
@@ -5,14 +5,18 @@ import { classnames } from '../../lib/classnames'
|
|
|
5
5
|
import { historyPushState, historyReplaceState } from '../../lib/history.js'
|
|
6
6
|
import { LiveRegion } from '../live-region.jsx'
|
|
7
7
|
|
|
8
|
+
const { stripPageTitle } = require('../../../server/lib/utils')
|
|
9
|
+
|
|
8
10
|
export function Availability () {
|
|
9
11
|
const { availability, isChatOpen, setChatVisibility, unseenCount, threadId, setUnseenCount, setInstigatorId, setLiveRegionText } = useApp()
|
|
10
12
|
|
|
11
13
|
const buttonRef = useRef()
|
|
12
14
|
|
|
15
|
+
const messageText = unseenCount > 1 ? 'new messages' : 'new message'
|
|
16
|
+
|
|
13
17
|
const showUnseenCount = unseenCount > 0 && !isChatOpen
|
|
14
18
|
|
|
15
|
-
const
|
|
19
|
+
const originalTitle = stripPageTitle(document.title)
|
|
16
20
|
|
|
17
21
|
const onClick = e => {
|
|
18
22
|
e.preventDefault()
|
|
@@ -40,6 +44,12 @@ export function Availability () {
|
|
|
40
44
|
}
|
|
41
45
|
}
|
|
42
46
|
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
if (showUnseenCount) {
|
|
49
|
+
document.title = `(${unseenCount} ${messageText}) - ${originalTitle}`
|
|
50
|
+
}
|
|
51
|
+
}, [unseenCount])
|
|
52
|
+
|
|
43
53
|
useEffect(() => {
|
|
44
54
|
if (showUnseenCount) {
|
|
45
55
|
setLiveRegionText(`Floodline webchat - ${unseenCount} ${messageText}`)
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
const { stripPageTitle } = require('../../server/lib/utils')
|
|
2
|
+
|
|
1
3
|
export const historyPushState = () => {
|
|
2
4
|
const url = window.location.href.split('#')[0]
|
|
5
|
+
document.title = stripPageTitle(document.title)
|
|
3
6
|
window.history.pushState({ history: true }, null, `${url}#webchat`)
|
|
4
7
|
}
|
|
5
8
|
|
|
@@ -8,6 +11,7 @@ export const historyReplaceState = () => {
|
|
|
8
11
|
return window.history.back()
|
|
9
12
|
}
|
|
10
13
|
|
|
14
|
+
document.title = stripPageTitle(document.title)
|
|
11
15
|
const url = window.location.href.split('#')[0]
|
|
12
16
|
return window.history.replaceState(null, null, url)
|
|
13
17
|
}
|
|
@@ -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 } from '../constants.js'
|
|
5
|
+
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY, MESSAGES_UNSEEN_COUNT } from '../constants.js'
|
|
6
6
|
|
|
7
7
|
export const AppContext = createContext(initialState)
|
|
8
8
|
|
|
@@ -18,6 +18,7 @@ export const AppProvider = ({ availability, children }) => {
|
|
|
18
18
|
setCustomerId(window.localStorage.getItem(CUSTOMER_ID_STORAGE_KEY))
|
|
19
19
|
setThreadId(window.localStorage.getItem(THREAD_ID_STORAGE_KEY))
|
|
20
20
|
setSettings(JSON.parse(window.localStorage.getItem(SETTINGS_STORAGE_KEY)) || state.settings)
|
|
21
|
+
setUnseenCount(window.localStorage.getItem(MESSAGES_UNSEEN_COUNT))
|
|
21
22
|
}, [])
|
|
22
23
|
|
|
23
24
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY } from '../constants'
|
|
1
|
+
import { CUSTOMER_ID_STORAGE_KEY, THREAD_ID_STORAGE_KEY, SETTINGS_STORAGE_KEY, MESSAGES_UNSEEN_COUNT } from '../constants'
|
|
2
2
|
|
|
3
3
|
const setSdk = (state, payload) => {
|
|
4
4
|
return {
|
|
@@ -68,6 +68,7 @@ const setAvailability = (state, payload) => {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
const setUnseenCount = (state, payload) => {
|
|
71
|
+
window.localStorage.setItem(MESSAGES_UNSEEN_COUNT, payload)
|
|
71
72
|
return {
|
|
72
73
|
...state,
|
|
73
74
|
unseenCount: payload
|
|
@@ -2,3 +2,4 @@ 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/utils.js
CHANGED
|
@@ -18,6 +18,12 @@ 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
|
+
|
|
21
26
|
module.exports = {
|
|
22
|
-
isWithinHours
|
|
27
|
+
isWithinHours,
|
|
28
|
+
stripPageTitle
|
|
23
29
|
}
|