UNPKG

@ministryofjustice/hmpps-digital-prison-reporting-frontend

Version:

The Digital Prison Reporting Frontend contains templates and code to help display data effectively in UI applications.

2 lines 53 kB
var K=Object.defineProperty,Z=Object.defineProperties;var tt=Object.getOwnPropertyDescriptors;var z=Object.getOwnPropertySymbols;var et=Object.prototype.hasOwnProperty,st=Object.prototype.propertyIsEnumerable;var X=(o,t,e)=>t in o?K(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,h=(o,t)=>{for(var e in t||(t={}))et.call(t,e)&&X(o,e,t[e]);if(z)for(var e of z(t))st.call(t,e)&&X(o,e,t[e]);return o},f=(o,t)=>Z(o,tt(t));var l=(o,t,e)=>new Promise((s,a)=>{var i=d=>{try{n(e.next(d))}catch(u){a(u)}},r=d=>{try{n(e.throw(d))}catch(u){a(u)}},n=d=>d.done?s(d.value):Promise.resolve(d.value).then(i,r);n((e=e.apply(o,t)).next())});var S=class{showLoadingAnimation(t){document.querySelectorAll(".dpr-loading-panel").forEach(a=>{a.classList.add("show")});let s=".dpr-loading-anim";t&&(s=`.${t} ${s}`),document.querySelectorAll(s).forEach(a=>{a.classList.add("show")})}hideLoadingAnimation(){document.querySelectorAll(".dpr-loading-panel").forEach(t=>{t.classList.remove("show")}),document.querySelectorAll(".dpr-loading-anim").forEach(t=>{t.classList.remove("show")})}};var c=class{constructor(t,e){this.element=t,this.loadingHelper=e}static getModuleName(){throw new Error("Module name not set")}getElement(){return this.element}initialise(){throw new Error("Initialisation not configured")}};var w=class extends c{static getModuleName(){return"card-group"}initialise(){let t=this.getElement().querySelectorAll("[data-click-navigate-to]"),e="card-loading";t.forEach(s=>{s.addEventListener("click",()=>{s.classList.add(e),this.loadingHelper.showLoadingAnimation(e),t.forEach(a=>{a.classList.contains("card-loading")||a.classList.add("card-disabled")}),window.location.href=s.dataset.clickNavigateTo})})}};var I=class extends c{static getModuleName(){return"dpr-catalogue-search"}initialise(){this.searchBox=this.getElement().querySelector(".dpr-search-box"),this.shwoUnauthorisedCheckbox=this.getElement().querySelector("#show-unauthorised"),this.totalShown=this.getElement().querySelector("#total-shown"),this.totalAmount=this.getElement().querySelector("#total-amount"),this.table=this.getElement().querySelector("table").querySelector("tbody"),this.totalRows=Array.from(this.table.rows).length,this.shownRows=this.totalRows,this.searchBox&&this.initSeachBoxEvents(),this.shwoUnauthorisedCheckbox&&this.initShowUnauthorisedEvents(),this.initInputFromQueryParams(),this.updateTotals()}initSeachBoxEvents(){this.searchBox.addEventListener("keyup",t=>{this.updateTableRows(t.target.value);let e=new URLSearchParams(window.location.search);e.set(this.searchBox.id,t.target.value),window.history.replaceState(null,null,`?${e.toString()}`)})}initShowUnauthorisedEvents(){this.shwoUnauthorisedCheckbox.addEventListener("change",t=>{let e=new URLSearchParams(window.location.search);t.target.checked?e.set(t.target.id,t.target.value):e.delete(t.target.id,t.target.value),window.history.replaceState(null,null,`?${e.toString()}`),this.updateTableRows(this.searchBox.value)}),this.updateTableRows(this.searchBox.value)}updateTableRows(t){let e=this.getElement().querySelector("table").querySelector("tbody"),s=Array.from(e.rows);s.forEach(a=>a.classList.add("search-option-hide")),this.updateSearchListing(s,t),this.toggleUnauthorisedRows(s),this.updateTotals()}updateTotals(){this.totalShown.innerText=this.shownRows,this.totalAmount.innerText=this.totalRows}toggleUnauthorisedRows(t){let s=new URLSearchParams(window.location.search).get("show-unauthorised");t.filter(a=>Array.from(a.cells).find(i=>i.innerHTML.includes("dpr-unauthorised-report"))).forEach(a=>{s?a.classList.remove("search-option-hide"):a.classList.contains("search-option-hide")||a.classList.add("search-option-hide")})}updateSearchListing(t,e){let s=0;t.filter(a=>!e||e.length===0||Array.from(a.cells).find(i=>{let r=e.toLowerCase();return i.innerText.toLowerCase().includes(r.toLowerCase())})).forEach(a=>{a.classList.remove("search-option-hide"),s+=1}),this.shownRows=s}initInputFromQueryParams(){new URLSearchParams(window.location.search).forEach((e,s)=>{let a=document.getElementById(s);a&&a.classList.contains("dpr-search-box")&&(a.value=e,this.updateTableRows(a.value)),a&&a.id==="show-unauthorised"&&a.setAttribute("checked","")})}};var x=class extends c{static getModuleName(){return"bookmark-toggle"}initialise(){this.initToggles()}initToggles(){this.getElement().querySelectorAll(".bookmark-input[type=checkbox]").forEach(e=>{let s=e.getAttribute("data-csrf-token"),a=e.getAttribute("data-report-id"),i=e.getAttribute("data-id"),r=e.getAttribute("data-report-type");this.bookmarkWrapper=e.parentNode,this.bookmarkColumn=this.bookmarkWrapper.parentNode,this.bookmarkLabel=this.bookmarkWrapper.querySelector(".dpr-bookmark-label--component"),e.addEventListener("change",()=>l(this,null,function*(){e.checked?yield this.addBookmark(e,i,a,r,s):yield this.removeBookmark(e,i,a,r,s)})),this.bookmarkColumn.addEventListener("keyup",n=>l(this,null,function*(){n.key==="Enter"&&(yield this.handleBookmarkChange(e,i,a,r,s))}))})}addBookmark(t,e,s,a,i){return l(this,null,function*(){t.setAttribute("checked",""),this.bookmarkWrapper.setAttribute("tooltip","Remove bookmark"),this.bookmarkLabel&&(this.bookmarkLabel.innerText="Bookmarked"),yield this.toggleBookmark("add",e,s,a,i)})}removeBookmark(t,e,s,a,i){return l(this,null,function*(){t.removeAttribute("checked"),this.bookmarkWrapper.setAttribute("tooltip","Add bookmark"),this.bookmarkLabel&&(this.bookmarkLabel.innerText="Bookmark removed"),yield this.toggleBookmark("remove",e,s,a,i)})}handleBookmarkChange(t,e,s,a,i){return l(this,null,function*(){t.checked?(t.removeAttribute("checked"),this.bookmarkWrapper.setAttribute("tooltip","Add bookmark"),this.bookmarkLabel&&(this.bookmarkLabel.innerText="Bookmark removed"),yield this.toggleBookmark("remove",e,s,a,i)):(t.setAttribute("checked",""),this.bookmarkWrapper.setAttribute("tooltip","Bookmarked"),this.bookmarkLabel&&(this.bookmarkLabel.innerText="Bookmarked"),yield this.toggleBookmark("add",e,s,a,i))})}toggleBookmark(t,e,s,a,i){return l(this,null,function*(){yield fetch(t==="add"?"/dpr/addBookmark/":"/dpr/removeBookmark/",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json","CSRF-Token":i},body:JSON.stringify({id:e,reportId:s,reportType:a})}).then(()=>{window.location.href.includes("/report")||window.location.reload()}).catch(n=>console.error("Error:",n))})}};var D=class extends c{static getModuleName(){return"show-more"}initialise(){this.initShowMore()}initShowMore(){let t=this.getElement(),e=t.querySelector(".dpr-show-more-content"),s=t.querySelector(".dpr-show-hide-button"),a=t.getAttribute("data-content"),i=+t.getAttribute("data-length")||200,r=a.replaceAll(/<[^>]+>/g,"").substring(0,i);a.length>i?e.innerHTML=`${r}... `:(e.innerHTML=`${a}`,s.style.display="none"),s.addEventListener("click",n=>{n.preventDefault(),s.innerHTML==="show more"?(e.innerHTML=`${a} `,s.innerHTML="show less"):s.innerHTML==="show less"&&(e.innerHTML=`${r}... `,s.innerHTML="show more")})}};var p=class extends c{initInputsFromQueryParams(){this.queryParams=new URLSearchParams(window.location.search),this.queryParams.forEach((t,e)=>{let s=document.getElementsByName(e);if(s.length){let a=s[0],{type:i}=a;if(i==="radio"||i==="checkbox")this.setMultiSelectValue(s,t);else if(a.classList.contains("moj-js-datepicker-input")){let r=dayjs(t,"YYYY-MM-DD").format("DD/MM/YYYY");a.value=r!=="Invalid Date"?r:""}else a.value=t}})}initInputEvents(t){Array.from(t).forEach(e=>{e.addEventListener("change",()=>{this.setQueryParamFromInput(e,!0,!1)})})}initQueryParamsFromInputs(t){Array.from(t).forEach(e=>{e.type!=="hidden"&&this.setQueryParamFromInput(e,!1,!0)})}setQueryParamFromInput(t,e=!1,s=!1){let{type:a}=t;if(a==="checkbox"||a==="radio")this.setMultiSelectQueryParam(t,e,s);else{let{name:i}=t,{value:r}=t,{staticOptionNameValue:n}=t,d=t.classList.contains("moj-js-datepicker-input");if(d){let m=dayjs(r,"D/M/YYYY").format("YYYY-MM-DD");r=m!=="Invalid Date"?m:""}let u=!d&&n?n:r;i&&this.updateQueryParam(i,u.trim())}}setMultiSelectQueryParam(t,e,s){this.queryParams=new URLSearchParams(window.location.search);let{name:a,value:i,checked:r,type:n}=t;if(r&&!this.queryParams.has(a,i)){let d;n==="checkbox"&&(d="append",!s&&a!=="columns"&&this.updateQueryParam("preventDefault",!0)),this.updateQueryParam(a,i,d)}else!r&&this.queryParams.has(a,i)&&e&&(n==="checkbox"&&!s&&a!=="columns"&&this.updateQueryParam("preventDefault",!0),this.updateQueryParam(a,i,"delete"))}updateQueryParam(t,e,s){if(this.queryParams=new URLSearchParams(window.location.search),!e&&t.length)this.queryParams.delete(t);else switch(s){case"append":this.queryParams.append(t,e);break;case"delete":this.queryParams.delete(t,e);break;default:this.queryParams.set(t,e);break}window.history.replaceState(null,null,`?${this.queryParams.toString()}`)}clearQueryParams(t){this.queryParams=new URLSearchParams(window.location.search),Array.from(this.queryParams).forEach(s=>{t&&s[0].includes(t)&&this.queryParams.delete(s[0],s[1]),t==="filters"&&this.queryParams.delete("preventDefault")}),window.history.replaceState(null,null,`?${this.queryParams.toString()}`)}getFormDataAsObject(t,e){let s=new FormData(t),a=Array.from(s.entries()).filter(i=>i[1]!=="").map(i=>({[`${e}${i[0]}`]:i[1]}));return Object.assign({},...a)}setMultiSelectValue(t,e){let s=Array.from(t).find(a=>a.getAttribute("value")===e);s&&(s.checked=!0)}setCheckBoxValues(t,e){let s=Array.from(t).find(a=>a.getAttribute("value")===e);s&&(s.checked=!0)}removeNoFilterValues(){this.queryParams=new URLSearchParams(window.location.search),Array.from(this.queryParams).forEach(e=>{e[1].includes("no-filter")&&this.queryParams.delete(e[0],e[1])}),window.history.replaceState(null,null,`?${this.queryParams.toString()}`)}};var b=class extends p{initFormValidation(t){t.forEach(e=>{let s=e.closest("div.govuk-form-group");if(s){let a=s.querySelector("p.govuk-error-message");a&&(s.classList.remove("govuk-form-group--error"),a.classList.add("govuk-error-message--hidden"),e.classList.remove("govuk-input--error"),e.classList.remove("govuk-textarea--error"),e.classList.remove("govuk-select--error"))}})}validateForm(){this.errorMessages=[];let t="";this.formFields.forEach(e=>{if(e.getAttribute("name")!==t&&e.tagName!=="BUTTON"){let a=e.closest("div.govuk-form-group");if(a){let i=a.querySelector("p.govuk-error-message");this.fieldIsValid(e)?i&&a&&this.hideFieldError(e,a,i):this.showFieldError(e,a,i)}}t=e.getAttribute("name")}),this.errorMessages.length?(this.buildErrorSummary(),this.errorSummary.classList.remove("query-error-summary--hidden")):this.errorSummary.classList.add("query-error-summary--hidden")}fieldIsValid(t){let{type:e}=t;switch(e){case"checkbox":return this.validateCheckbox(t);default:return t.checkValidity()}}validateCheckbox(t){let e=t.closest("div.govuk-checkboxes");if(e.hasAttribute("required")){let s=e.querySelectorAll('input[type="checkbox"]');return Array.from(s).some(a=>a.checked)}return!0}showFieldError(t,e,s){e.classList.add("govuk-form-group--error");let a=this.setValidationMessage(t.validity,t,s);s.innerHTML=`<span class="govuk-visually-hidden">Error:</span>${a}`,s.classList.remove("govuk-error-message--hidden"),t.classList.add("govuk-input--error")}hideFieldError(t,e,s){e.classList.remove("govuk-form-group--error"),s.classList.add("govuk-error-message--hidden"),t.classList.remove("govuk-input--error")}buildErrorSummary(){let t=this.errorSummary.querySelector("div.govuk-error-summary__body"),e="";this.errorMessages.forEach(a=>{e+=`<li><a href="${a.href}">${a.text}</a></li>`});let s=`<ul class="govuk-list govuk-error-summary__list">${e}</ul>`;t.innerHTML=s}getDisplayName(t){switch(t.getAttribute("type")){case"text":return t.getAttribute("display-name");case"radio":return t.closest("div.govuk-radios").getAttribute("display-name");case"checkbox":return t.closest("div.govuk-checkboxes").getAttribute("display-name");default:return t.getAttribute("display-name")}}setValidationMessage(t,e,s){let a=s.lastChild.nodeValue.replace(/(\r\n|\n|\r)/gm,"").trim(),i=e.getAttribute("id"),r=this.getDisplayName(e),n;if((t.valueMissing||e.type==="checkbox")&&(n=a.length?a:`${r} is required`,this.errorMessages.push({text:n,href:`#${i}`})),t.patternMismatch){let d=e.getAttribute("pattern-hint")||e.getAttribute("pattern");n=a.length?a:`The value for ${r} must be in the correct pattern: ${d}`,this.errorMessages.push({text:n,href:`#${i}`})}return n}};var L=class extends b{static getModuleName(){return"download-feedback-form"}initialise(){this.errorMessages=[],this.mainForm=document.getElementById("download-feedback-form"),this.mainForm.noValidate=!0,this.formFields=Array.from(this.mainForm.elements),this.errorSummary=document.getElementById("download-feedback-form-summary"),this.submitButton=document.getElementById("download-feedback-form-submit"),this.success=document.getElementById("download-feedback-form-success"),this.initSubmitButton(),this.initFormValidation(this.formFields),this.mainForm.classList.remove("download-feedback-form--hidden")}initSubmitButton(){this.submitButton.addEventListener("click",t=>{t.preventDefault(),this.validateForm(),this.mainForm.checkValidity()&&this.mainForm.requestSubmit()})}};var P=class extends p{static getModuleName(){return"pagination"}initialise(){this.pageSizeSelect=document.getElementById("page-size-select"),this.initInputsFromQueryParams(),this.initSelectEvent()}initSelectEvent(){this.pageSizeSelect.addEventListener("change",()=>{this.queryParams=new URLSearchParams(window.location.search);let{name:t,value:e}=this.pageSizeSelect;this.queryParams.set(t,e),this.queryParams.set("selectedPage","1"),window.history.replaceState(null,null,`?${this.queryParams.toString()}`),window.location.reload()})}};var A=class extends c{static getModuleName(){return"report-actions"}initialise(){this.refreshButton=document.getElementById("dpr-button-refresh"),this.printButton=document.getElementById("dpr-button-printable"),this.shareButton=document.getElementById("dpr-button-sharable"),this.downloadButton=document.getElementById("dpr-button-downloadable"),this.copyButton=document.getElementById("dpr-button-copy"),this.initRefreshEvent(),this.initPrintButtonEvent(),this.initShareButtonEvent(),this.initCopyButtonEvent()}initPrintButtonEvent(){if(this.printButton){let t=this.printButton.getAttribute("data-disabled");this.printButton.addEventListener("click",()=>{t!=="true"&&window.print()}),this.printButton.addEventListener("keyup",e=>{e.key==="Enter"&&t!=="true"&&window.print()})}}initShareButtonEvent(){if(this.shareButton){let t=this.shareButton.getAttribute("data-href");this.shareButton.addEventListener("click",()=>{window.location=t}),this.shareButton.addEventListener("keyup",e=>{e.key==="Enter"&&(window.location=t)})}}initCopyButtonEvent(){if(this.copyButton){let t=this.copyButton.getAttribute("data-href");this.copyButton.addEventListener("click",()=>{navigator.clipboard.writeText(t)}),this.copyButton.addEventListener("keyup",e=>{e.key==="Enter"&&navigator.clipboard.writeText(t)})}}initRefreshEvent(){if(this.refreshButton){let t=this.refreshButton.getAttribute("data-href");this.refreshButton.addEventListener("click",()=>{window.location=t}),this.refreshButton.addEventListener("keyup",e=>{e.key==="Enter"&&(window.location=t)})}}};var C=class extends c{static getModuleName(){return"data-table"}initialise(){this.tableContainer=document.getElementById("dpr-table-wrapper"),this.table=document.getElementById("dpr-data-table"),this.overflowGradient=document.getElementById("dpr-overflow-gradient"),this.createTableHeaderAndFooter(),this.initTableScrollListener()}initTableScrollListener(){this.checkOffsetWidths(),window.addEventListener("resize",()=>{this.checkOffsetWidths()}),this.tableContainer.addEventListener("scroll",t=>{let e=this.table.offsetWidth,s=t.target.offsetWidth+t.target.scrollLeft;e===s?this.overflowGradient.style.display="none":this.overflowGradient.style.display="block"})}checkOffsetWidths(){this.tableContainer.offsetWidth>=this.table.offsetWidth?this.overflowGradient.style.display="none":this.overflowGradient.style.display="block"}createTableHeaderAndFooter(){if(this.table){let t=this.table.getAttribute("data-classification"),e=Number(this.table.getAttribute("data-col-length")),s=`<b>${t}</b>`,r=this.table.createTHead().insertRow(0).insertCell(0);r.outerHTML=`<th class="govuk-table__header govuk-table__cell--content print-header-footer" colspan=${e}>${s}</th>`;let u=this.table.createTFoot().insertRow(0).insertCell(0);u.outerHTML=`<td class="govuk-table__cell govuk-table__cell--content print-header-footer table-row--no-border" colspan=${e}>${s}</td>`}}};var q=class extends p{static getModuleName(){return"columns"}initialise(){this.form=this.getElement(),this.submitButton=this.getElement().querySelector(".dpr-apply-columns-button"),this.resetButton=this.getElement().querySelector(".dpr-reset-columns-button"),this.initInputsFromQueryParams(),this.initQueryParamsFromInputs(this.form.elements),this.initInputEvents(this.form.elements),this.initSubmitButton(),this.initResetButton()}initSubmitButton(){this.submitButton.addEventListener("click",t=>{t.preventDefault(),this.loadingHelper.showLoadingAnimation(),window.location.reload()})}initResetButton(){this.resetButton.addEventListener("click",t=>{t.preventDefault(),this.loadingHelper.showLoadingAnimation(),this.clearQueryParams("columns"),window.location.reload()})}};var B=class extends c{static getModuleName(){return"download-message"}initialise(){this.downloadMessage=this.getElement(),window.location.href.indexOf("download-disabled")>-1&&this.downloadMessage.classList.remove("dpr-download-message--hidden")}};var F=class extends b{initFiltersForm({formId:t,submitButtonId:e,resetButtonId:s,selectedFiltersId:a,removeSelectedButtonClass:i}){this.errorMessages=[],this.mainForm=document.getElementById(t),this.mainForm.noValidate=!0,this.formFields=Array.from(this.mainForm.elements),this.errorSummary=document.getElementById("query-error-summary"),this.submitButton=document.getElementById(e),this.resetButton=document.getElementById(s),this.selectedFiltersWrapper=document.getElementById(a),this.selectedFiltersButtons=document.querySelectorAll(`.${i}`),this.initValues(),this.initSubmitButton(),this.initResetButton(),this.initFormData()}initValues(){this.initInputsFromQueryParams(),this.initQueryParamsFromInputs(this.mainForm.elements),this.initInputEvents(this.mainForm.elements)}initFormData(){this.initFormValidation(this.formFields),this.mainForm.classList.remove("async-filters-form--hidden")}initSubmitButton(){this.submitButton.addEventListener("click",t=>{t.preventDefault(),this.initFormData(),this.validateForm(),this.mainForm.checkValidity()&&this.submitAction()})}initResetButton(){this.resetButton&&(this.defaultQuery=this.resetButton.getAttribute("defaultQuery"),this.resetButton.addEventListener("click",t=>{t.preventDefault(),this.clearQueryParams("filters"),this.resetAction()}))}resetAction(){if(this.defaultQuery){let t=this.defaultQuery.substring(1),e=`${window.location.href}&${t}`;window.location.href=e}else window.location.reload()}submitAction(){window.location.reload()}};var v=class extends F{static getModuleName(){return"selected-filters"}initInteractiveSelectedFilterButtonsEvents(){this.selectedFiltersButtons&&this.selectedFiltersButtons.forEach(t=>{t.addEventListener("click",e=>{e.preventDefault();let s=JSON.parse(e.target.getAttribute("data-query-param-key"))||[],a=JSON.parse(e.target.getAttribute("data-query-param-value"))||[],i=e.target.getAttribute("data-query-constraint-values");i=i?JSON.parse(e.target.getAttribute("data-query-constraint-values")):void 0,s.forEach(r=>{if(a.forEach(n=>{this.updateQueryParam(r,n,"delete")}),i){let n=i.find(d=>d.key===r);n&&this.updateQueryParam(r,n.value)}}),this.updateQueryParam("preventDefault",!0),window.location.reload()})})}initSelectedFiltersButtons(){let t=this.getSelectedFilterData();t=this.setPresetDateRangeSelectedFilter(t),t=this.setMultiselectSelectedFilterValue(t),this.createSelectedFilterElements(t)}initInputEventsForSelectedFilters(t){Array.from(t).forEach(e=>{e.addEventListener("change",()=>{this.initSelectedFiltersButtons()})})}getSelectedFilterData(){this.queryParams=new URLSearchParams(window.location.search),this.selectedFiltersWrapper.innerHTML="";let t=[];return this.queryParams.forEach((e,s)=>{let a=s,i=e;if(s.includes("filters.")){let r=document.getElementsByName(s);if(r.length){a=this.getDisplayName(r[0]),i=this.getInputDisplayValue(r);let n=t.findIndex(d=>d.key===s);n===-1?i&&t.push({displayName:a,displayValue:i,key:s,value:[e],type:r[0]}):t[n]=f(h({},t[n]),{displayValue:t[n].displayValue,value:t[n].value})}}}),t}createSelectedFilterElements(t){t.length?t.forEach(e=>{let{displayName:s,displayValue:a,key:i,value:r}=e,n=this.createSelectedFilterElement(s,a,i,r);this.selectedFiltersWrapper.appendChild(n),this.initSelectedButtonEvent()}):this.createNoFiltersSelectedMessageEl()}getInputDisplayValue(t){let e;switch(t[0].type){case"text":e=t[0].value;break;case"radio":{e=Array.from(t).find(a=>a.checked).labels[0].innerText;break}case"select-one":e=t[0].options[t[0].selectedIndex].text;break;case"checkbox":{e=Array.from(t).filter(a=>a.checked).map(a=>` ${a.labels[0].innerText}`);break}default:e=t[0].value;break}return e}initSelectedButtonEvent(){Array.from(this.selectedFiltersWrapper.children).forEach(t=>{t.addEventListener("click",e=>{e.preventDefault();let s=document.getElementsByName(t.dataset.dataQueryParamKey);if(s.length){switch(s[0].type){case"checkbox":case"radio":s.forEach(i=>{i.checked=!1;let r=new Event("change");i.dispatchEvent(r)});break;case"search":s[0].value="",s[0].staticOptionNameValue="";break;default:s[0].value="";break}let a=new Event("change");s[0].dispatchEvent(a)}})})}createSelectedFilterElement(t,e,s,a){let i=document.createElement("a");i.classList="govuk-link govuk-body interactive-remove-filter-button",i.dataset.dataQueryParamKey=s,i.dataset.dataQueryParamValue=`[ "${a}" ]`;let r=document.createTextNode(`${t}: ${e}`);return i.appendChild(r),i}createNoFiltersSelectedMessageEl(){let t=document.createElement("p");t.classList="govuk-body-s govuk-!-margin-top-2 govuk-!-margin-bottom-0";let e=document.createTextNode("No filters selected");t.appendChild(e),this.selectedFiltersWrapper.appendChild(t)}setPresetDateRangeSelectedFilter(t){let e=t,s=t.find(a=>a.displayName==="Preset date range");return s&&(e=t.filter(a=>{let i=a.key.split(".");return!a.key.includes(`${i[0]}.${i[1]}`)||a.key===s.key})),e}setMultiselectSelectedFilterValue(t){let e=t;return e=t.map(s=>{if(Array.isArray(s.displayValue)&&s.displayValue.length>3){let a=`${s.displayValue[0]}, ${s.displayValue[1]}, ${s.displayValue[2]} + ${s.displayValue.length-3} more`;return f(h({},s),{displayValue:a})}return s}),e}};var T=class extends v{static getModuleName(){return"interactive-filters"}initialise(){this.initFiltersForm({formId:"interactive-filters-form",submitButtonId:"interactive-apply-filters-button",resetButtonId:"interactive-reset-filters-button",removeSelectedButtonClass:"interactive-remove-filter-button"}),this.initInteractiveSelectedFilterButtonsEvents()}};var g=class extends c{getPollingFrquency(){return"2000"}getPollingStatuses(){return["SUBMITTED","STARTED","PICKED"]}getEndStatuses(){return["FINISHED","FAILED","EXPIRED","ABORTED"]}getExpiredCheckStatuses(){return["FAILED","EXPIRED","ABORTED"]}getRequestStatus(t,e){return l(this,null,function*(){return this.getStatus("/dpr/getStatus/",t,e)})}getExpiredStatus(t,e,s){return l(this,null,function*(){return this.getStatus(t,e,s)})}shouldPollStatus(t){return JSON.parse(t).some(e=>!this.END_STATUSES.includes(e.status))}shouldPollExpired(t){return JSON.parse(t).some(e=>!this.EXPIRED_END_STATUSES.includes(e.status))}getStatus(t,e,s){return l(this,null,function*(){let a;return yield fetch(t,{method:"post",headers:{Accept:"application/json","Content-Type":"application/json","CSRF-Token":s},body:JSON.stringify(h({},e))}).then(i=>i.json()).then(i=>{a=i}).catch(i=>console.error("Error:",i)),a})}};var R=class extends g{static getModuleName(){return"async-polling-content"}initialise(){this.POLLING_STATUSES=this.getPollingStatuses(),this.POLLING_FREQUENCY=this.getPollingFrquency(),this.statusSection=document.getElementById("async-request-polling-status"),this.retryRequestButton=document.getElementById("retry-async-request"),this.cancelRequestButton=document.getElementById("cancel-async-request"),this.viewReportButton=document.getElementById("view-async-report-button"),this.requestData=this.statusSection.getAttribute("data-request-data"),this.currentStatus=this.statusSection.getAttribute("data-current-status"),this.csrfToken=this.statusSection.getAttribute("data-csrf-token"),this.reportUrl=this.statusSection.getAttribute("data-report-url"),this.initCancelRequestButton(),this.initPollingInterval()}initPollingInterval(){return l(this,null,function*(){this.POLLING_STATUSES.includes(this.currentStatus)?this.pollingInterval=setInterval(()=>l(this,null,function*(){yield this.pollStatus()}),this.POLLING_FREQUENCY):this.currentStatus==="FINISHED"&&(window.location.href=this.reportUrl)})}pollStatus(){return l(this,null,function*(){if(this.requestData){let t=JSON.parse(this.requestData),e=yield this.getRequestStatus(t,this.csrfToken);this.currentStatus!==e.status&&(clearInterval(this.pollingInterval),window.location.reload())}})}initCancelRequestButton(){if(this.cancelRequestButton){let t=this.cancelRequestButton.getAttribute("data-execution-id"),e=this.cancelRequestButton.getAttribute("data-report-id"),s=this.cancelRequestButton.getAttribute("data-id"),a=this.cancelRequestButton.getAttribute("data-type"),i=this.cancelRequestButton.getAttribute("data-csrf-token");this.cancelRequestButton.addEventListener("click",()=>l(this,null,function*(){yield fetch("/dpr/cancelRequest/",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json","CSRF-Token":i},body:JSON.stringify({executionId:t,reportId:e,id:s,type:a})}).then(()=>{window.location.reload()}).catch(r=>console.error("Error:",r))}))}}};var N=class extends v{static getModuleName(){return"async-filters"}initialise(){this.initFiltersForm({formId:"async-filters-form",submitButtonId:"async-request-report-button",resetButtonId:"async-request-reset-filters-button",selectedFiltersId:"dpr-selected-filters",removeSelectedButtonClass:"interactive-remove-filter-button"}),this.initSelectedFiltersButtons()}initFormData(){let{origin:t,pathname:e,search:s}=window.location;document.getElementById("async-filters-form-pathname").value=e,document.getElementById("async-filters-form-origin").value=t,document.getElementById("async-filters-form-search").value=s;let a=new URLSearchParams(s),i=a.size>0?`?${a.toString()}`:"";document.getElementById("async-filters-form-href").value=`${t}${e}${i}`,this.initFormValidation(this.formFields),this.mainForm.classList.remove("async-filters-form--hidden")}submitAction(){this.mainForm.requestSubmit()}initValues(){this.initInputsFromQueryParams(),this.initQueryParamsFromInputs(this.mainForm.elements),this.initInputEvents(this.mainForm.elements),this.initSelectedButtonEvent(),this.initInputEventsForSelectedFilters(this.mainForm.elements)}};var $=class extends c{static getModuleName(){return"sync-loading"}initialise(){this.element=this.getElement(),this.form=this.element.querySelector("#dpr-sync-loading-form"),this.load()}load(){return l(this,null,function*(){this.form.submit()})}};var M=class extends c{static getModuleName(){return"date-input"}initialise(){let t=this.getElement();this.dateInput=t.querySelector("input.moj-js-datepicker-input"),this.setToValueTriggers=document.querySelectorAll("[data-set-min-max-trigger='true']"),this.required=this.getElement().getAttribute("data-required"),this.displayName=this.getElement().getAttribute("data-display-name"),this.pattern=this.getElement().getAttribute("data-pattern"),this.patternHint=this.getElement().getAttribute("data-pattern-hint"),this.min=this.getElement().getAttribute("data-min"),this.max=this.getElement().getAttribute("data-max"),this.setValidationOnInputEl(),this.setMinMaxEventListener(),this.setToMinMax(),this.setToValue()}setValidationOnInputEl(){this.required&&this.required==="true"&&this.dateInput.setAttribute("required",!0),this.min&&this.dateInput.setAttribute("min",this.min),this.max&&this.dateInput.setAttribute("max",this.max),this.dateInput.setAttribute("display-name",this.displayName),this.dateInput.setAttribute("pattern",this.pattern),this.dateInput.setAttribute("pattern-hint",this.patternHint)}setMinMaxEventListener(){this.dateInput.addEventListener("blur",()=>{this.setToMinMax()})}setToMinMax(){if(this.dateInput.value){let e=new Date(this.dateInput.value);if(this.min){let s=new Date(this.min);e<s&&(this.dateInput.value=dayjs(this.min).format("DD/MM/YYYY"))}if(this.max){let s=new Date(this.max);e>s&&(this.dateInput.value=dayjs(this.max).format("DD/MM/YYYY"))}}let t=new Event("change");this.dateInput.dispatchEvent(t)}setToValue(){this.setToValueTriggers.forEach(t=>{t.addEventListener("click",e=>{e.preventDefault();let s=e.target.getAttribute("data-set-min-max-value"),a=e.target.getAttribute("data-set-to-input"),i=document.getElementById(a);i.value=s;let r=new Event("change");i.dispatchEvent(r)})})}};var V=class extends c{static getModuleName(){return"date-range-input"}initialise(){this.dateRangeInputs=document.getElementById("dpr-date-range"),this.filtersAccordion=document.getElementById("dpr-interactive-filters-details"),this.fieldName=this.dateRangeInputs.getAttribute("data-field-name"),this.startInputID=`filters.${this.fieldName}.start`,this.endInputID=`filters.${this.fieldName}.end`,this.durationInputID=`filters.${this.fieldName}.relative-duration`,this.relativeRangeRadioButtons=document.querySelectorAll(`input[name='${this.durationInputID}']`),this.startInput=document.querySelector(`input[name='${this.startInputID}']`),this.endInput=document.querySelector(`input[name='${this.endInputID}']`),this.startRequired=this.startInput.required,this.endRequired=this.endInput.required,this.datePickerTab=document.getElementById("tab_date-picker"),this.relativeDurationTab=document.getElementById("tab_relative-range"),this.durationValue=void 0,this.datePickerTab&&this.relativeDurationTab&&(this.initDatePickerTabClick(),this.initRelativeDurationTabClick(),this.initTabs(),this.initDurationRadionButtonClick())}initTabs(){this.queryParams=new URLSearchParams(window.location.search),this.queryParams.has(this.durationInputID)&&this.relativeRangeRadioButtons.forEach(t=>{this.updateCheckedDuration(t)})}initDatePickerTabClick(){this.datePickerTab.addEventListener("click",()=>{let t;this.queryParams=new URLSearchParams(window.location.search),this.queryParams.has(this.durationInputID)&&(t=this.queryParams.get(this.durationInputID),this.removeSearchParam(this.durationInputID)),this.updateInputs(t),window.location.hash="date-picker"})}initRelativeDurationTabClick(){this.relativeDurationTab.addEventListener("click",()=>{this.relativeRangeRadioButtons.forEach(t=>{this.updateCheckedDuration(t)}),window.location.hash="relative-range"})}initDurationRadionButtonClick(){this.relativeRangeRadioButtons.forEach(t=>{t.addEventListener("click",e=>{let s=e.target.value;this.durationValue=s,this.updateInputs(s),this.removeRequiredFromDatePickers()})}),this.relativeRangeRadioButtons.forEach(t=>{t.addEventListener("change",()=>{Array.from(this.relativeRangeRadioButtons).every(e=>!e.checked)&&(this.durationValue=null,this.updateInputs(this.durationValue))})})}removeSearchParam(t,e){this.queryParams=new URLSearchParams(window.location.search),this.queryParams.delete(t),e&&this.queryParams.delete(e),window.history.replaceState(null,null,`?${this.queryParams.toString()}`)}updateCheckedDuration(t){if(t.checked){let e=t.value;this.updateInputs(e);let s=new Event("change");t.dispatchEvent(s)}}removeRequiredFromDatePickers(){this.startInput.removeAttribute("required"),this.endInput.removeAttribute("required"),this.startInput.value="",this.endInput.value=""}updateInputs(t){if(this.startInput.required=this.startRequired,this.endInput.required=this.endRequired,console.log({durationValue:t,durationValue2:this.durationValue}),t||this.durationValue){let s=t||this.durationValue,{startDate:a,endDate:i}=this.calculateDateForDatepicker(s);this.startInput.value=a,this.endInput.value=i}else this.startInput.value=null,this.endInput.value=null;let e=new Event("change");this.startInput.dispatchEvent(e),this.endInput.dispatchEvent(e)}calculateDateForDatepicker(t){let e,s;switch(t){case"none":e="",s="";break;case"yesterday":s=dayjs(),e=s.subtract(1,"day");break;case"tomorrow":e=dayjs(),s=e.add(1,"day");break;case"last-week":s=dayjs(),e=s.subtract(1,"week");break;case"next-week":e=dayjs(),s=e.add(1,"week");break;case"last-month":s=dayjs(),e=s.subtract(1,"month");break;case"next-month":e=dayjs(),s=e.add(1,"month");break;default:e="",s="";break}return{startDate:e?e.format("DD/MM/YYYY").toString():"",endDate:s?s.format("DD/MM/YYYY").toString():""}}};var O=class extends c{static getModuleName(){return"autocomplete-text-input"}constructor(t){super(t);let e=this.getTextInput().getAttribute("aria-owns");this.listItemsSelector=`#${e} li`,this.listParentSelector=`#${e} ul`}initialise(){let t=this.getTextInput();t.addEventListener("keyup",e=>{this.onTextInput(e,t)}),this.getElement().querySelectorAll(".autocomplete-text-input-list-button").forEach(e=>{e.addEventListener("click",s=>{this.onOptionClick(s,t,this.getElement())})})}getTextInput(){return this.getElement().querySelector(".autocomplete-text-input-box")}onTextInput(t,e){let s=Number(e.dataset.minimumLength),{resourceEndpoint:a}=e.dataset,i=t.target.value.toLowerCase();if(a?i.length>=s?(this.addItem(this.clearListAndRecreateTemplate(),"<i>Searching...</i>"),this.populateOptionsDynamically(a,i,e,()=>this.clearListAndRecreateTemplate())):this.clearListAndRecreateTemplate():this.getElement().querySelectorAll(this.listItemsSelector).forEach(r=>{i.length>=s&&this.isMatchingStaticOptionNameOrDisplayPrefix(this.getInputListButton(r),i,r)?r.classList.remove("autocomplete-text-input-item-hide"):r.classList.add("autocomplete-text-input-item-hide")}),i.length===0){let r=new Event("change");e.dispatchEvent(r)}}getInputListButton(t){return t.querySelector(".autocomplete-text-input-list-button")}isMatchingStaticOptionNameOrDisplayPrefix(t,e,s){return this.isStaticOptionsNamePrefix(t.dataset.staticOptionNameValue,e)||s.innerText.trim().toLowerCase().startsWith(e)}isStaticOptionsNamePrefix(t,e){return t&&t.trim().toLowerCase().startsWith(e)}populateOptionsDynamically(t,e,s,a){return l(this,null,function*(){try{let r=yield(yield fetch(t.replace("{prefix}",encodeURI(e)))).json();if(e===s.value.toLowerCase()){let n=a();r.forEach(d=>{this.addItem(n,d,u=>{this.onOptionClick(u,s,this.getElement())})})}}catch(i){this.addItem(a(),`Failed to retrieve results: ${i}`)}})}onOptionClick(t,e,s){t.preventDefault(),e.value=t.target.innerText.trim(),e.staticOptionNameValue=t.target.dataset.staticOptionNameValue,e.focus();let a=new Event("change");e.dispatchEvent(a),s.querySelectorAll("li").forEach(i=>{i.classList.add("autocomplete-text-input-item-hide")})}addItem(t,e,s){let a=t.cloneNode(!0);a.querySelector("button").innerHTML=e,a.classList.remove("autocomplete-text-input-item-hide"),this.getElement().querySelector(this.listParentSelector).appendChild(a),s&&a.addEventListener("click",i=>{s(i)})}clearListAndRecreateTemplate(){let t=this.getElement().querySelector(this.listItemsSelector).cloneNode(!0);return t.classList.add("autocomplete-text-input-item-hide"),this.getElement().querySelectorAll(this.listItemsSelector).forEach(e=>e.remove()),this.getElement().querySelector(this.listParentSelector).append(t),t}};var j=class extends c{static getModuleName(){return"granular-date-range-input"}initialise(){this.filter=this.getElement(),this.fieldName=this.filter.getAttribute("data-field-name");let t=`filters.${this.fieldName}`;this.quickFiltersInput=this.filter.querySelector(`select[name='${t}.quick-filter']`),this.granularityInput=this.filter.querySelector(`select[name='${t}.granularity']`),this.startInput=this.filter.querySelector(`input[name='${t}.start']`),this.endInput=this.filter.querySelector(`input[name='${t}.end']`),this.initStartEndInputChangetEvent(),this.initGranularityChangeEvent(),this.initQuickFilterChangeEvent()}initGranularityChangeEvent(){this.granularityInput.addEventListener("change",t=>{this.resetQuickFilters()})}initQuickFilterChangeEvent(){this.quickFiltersInput.addEventListener("change",t=>{this.updateStartEndValues(t.target.value)})}initStartEndInputChangetEvent(){this.startInput.addEventListener("change",t=>{this.resetQuickFilters()}),this.endInput.addEventListener("change",t=>{this.resetQuickFilters()})}setGranularityValue(t){this.granularityInput.value=t}setStartValue(t){this.startInput.value=t}setEndValue(t){this.endInput.value=t}resetQuickFilters(){this.quickFiltersInput.value="none";let t=new URLSearchParams(window.location.search);t.set(this.quickFiltersInput.id,"none"),window.history.replaceState(null,null,`?${t.toString()}`)}updateStartEndValues(t){let e,s,a;switch(t){case"today":s=dayjs(),e=dayjs(),a="daily";break;case"yesterday":s=dayjs().subtract(1,"day"),e=dayjs().subtract(1,"day"),a="daily";break;case"last-seven-days":s=dayjs(),e=s.subtract(7,"day").add(1,"day"),a="daily";break;case"last-thirty-days":s=dayjs(),e=s.subtract(30,"day").add(1,"day"),a="daily";break;case"last-month":s=dayjs(),e=s.subtract(1,"month").add(1,"day"),a="monthly";break;case"last-full-month":s=dayjs().subtract(1,"month").endOf("month"),e=s.startOf("month"),a="monthly";break;case"last-ninety-days":s=dayjs(),e=s.subtract(90,"day").add(1,"day"),a="daily";break;case"last-three-months":s=dayjs(),e=s.subtract(3,"month").add(1,"day"),a="monthly";break;case"last-full-three-months":s=dayjs().subtract(1,"month").endOf("month"),e=s.subtract(2,"month").startOf("month"),a="monthly";break;case"last-six-months":s=dayjs(),e=s.subtract(6,"month").add(1,"day"),a="monthly";break;case"last-full-six-months":s=dayjs().subtract(1,"month").endOf("month"),e=s.subtract(6,"month").startOf("month"),a="monthly";break;case"last-year":s=dayjs(),e=s.subtract(1,"year").add(1,"day"),a="annually";break;case"last-full-year":s=dayjs().subtract(1,"year").endOf("year"),e=s.startOf("year"),a="annually";break;case"tomorrow":s=dayjs().add(1,"day"),e=dayjs().add(1,"day"),a="daily";break;case"next-seven-days":e=dayjs(),s=dayjs().add(7,"day").subtract(1,"day"),a="daily";break;case"next-thirty-days":e=dayjs(),s=dayjs().add(30,"day").subtract(1,"day"),a="daily";break;case"next-month":e=dayjs(),s=dayjs().add(1,"month").subtract(1,"day"),a="monthly";break;case"next-full-month":e=dayjs().add(1,"month").startOf("month"),s=e.endOf("month"),a="monthly";break;case"next-ninety-days":e=dayjs(),s=dayjs().add(90,"day").subtract(1,"day"),a="daily";break;case"next-three-months":e=dayjs(),s=dayjs().add(3,"month").subtract(1,"day"),a="monthly";break;case"next-full-three-months":e=dayjs().add(1,"month").startOf("month"),s=e.add(2,"month").endOf("month"),a="monthly";break;case"next-year":e=dayjs(),s=dayjs().add(1,"year").subtract(1,"day"),a="annually";break;case"next-full-year":e=dayjs().add(1,"year").startOf("year"),s=e.endOf("year"),a="annually";break;default:break}this.setStartValue(e.format("DD/MM/YYYY").toString()),this.setEndValue(s.format("DD/MM/YYYY").toString()),this.setGranularityValue(a);let i=new URLSearchParams(window.location.search);i.set(this.granularityInput.id,a),i.set(this.startInput.id,e.format("YYYY/MM/DD").toString()),i.set(this.endInput.id,s.format("YYYY/MM/DD").toString()),window.history.replaceState(null,null,`?${i.toString()}`)}};var Y=class extends g{static getModuleName(){return"async-request-list"}initialise(){this.END_STATUSES=this.getEndStatuses(),this.EXPIRED_END_STATUSES=this.getExpiredCheckStatuses(),this.POLLING_FREQUENCY=this.getPollingFrquency(),this.requestList=document.getElementById("dpr-async-request-component"),this.requestData=this.requestList.getAttribute("data-request-data"),this.csrfToken=this.requestList.getAttribute("data-csrf-token"),this.removeActions=document.querySelectorAll(".dpr-remove-requested-report-button"),this.initItemActions(),this.initPollingIntervals()}initPollingIntervals(){return l(this,null,function*(){yield this.checkIfExpired(),this.requestData&&(this.shouldPollExpired(this.requestData)&&(this.expiredInterval=setInterval(()=>l(this,null,function*(){yield this.checkIfExpired()}),"60000")),this.shouldPollStatus(this.requestData)&&(this.pollingInterval=setInterval(()=>l(this,null,function*(){yield this.pollStatus()}),this.POLLING_FREQUENCY)))})}checkIfExpired(){return l(this,null,function*(){yield Promise.all(JSON.parse(this.requestData).map(t=>l(this,null,function*(){if(!this.EXPIRED_END_STATUSES.includes(t.status)){let e=yield this.getExpiredStatus("/dpr/getRequestedExpiredStatus/",t,this.csrfToken);e&&e.isExpired&&(clearInterval(this.expiredInterval),window.location.reload())}})))})}pollStatus(){return l(this,null,function*(){yield Promise.all(JSON.parse(this.requestData).map(t=>l(this,null,function*(){if(!this.END_STATUSES.includes(t.status)){let e=yield this.getRequestStatus(t,this.csrfToken);this.END_STATUSES.includes(e.status)&&(clearInterval(this.pollingInterval),window.location.reload())}})))})}initItemActions(){this.removeActions.forEach(t=>{let e=t.getAttribute("data-execution-id");t.addEventListener("click",s=>l(this,null,function*(){s.preventDefault(),yield this.removeItemFromList(e)}))})}removeItemFromList(t){return l(this,null,function*(){let e;return yield fetch("/dpr/removeRequestedItem/",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json","CSRF-Token":this.csrfToken},body:JSON.stringify({executionId:t})}).then(()=>{window.location.reload()}).catch(s=>console.error("Error:",s)),e})}};var Q=class extends g{static getModuleName(){return"recently-viewed-list"}initialise(){this.EXPIRED_END_STATUSES=this.getExpiredCheckStatuses(),this.POLLING_FREQUENCY="60000",this.viewedList=document.getElementById("dpr-recently-viewed-component"),this.viewedReportData=this.viewedList.getAttribute("data-request-data"),this.csrfToken=this.viewedList.getAttribute("data-csrf-token"),this.removeActions=document.querySelectorAll(".dpr-remove-viewed-report-button"),this.initItemActions(),this.initPollingIntervals()}initPollingIntervals(){return l(this,null,function*(){yield this.checkIsExpired(),this.viewedReportData&&this.shouldPollExpired(this.viewedReportData)&&(this.expiredViewedInterval=setInterval(()=>l(this,null,function*(){yield this.checkIsExpired()}),this.POLLING_FREQUENCY))})}checkIsExpired(){return l(this,null,function*(){yield Promise.all(JSON.parse(this.viewedReportData).map(t=>l(this,null,function*(){if(t.status!=="EXPIRED"){let e=yield this.getExpiredStatus("/dpr/getExpiredStatus/",t,this.csrfToken);e&&e.isExpired&&clearInterval(this.expiredViewedInterval)}})))})}initItemActions(){this.removeActions.forEach(t=>{let e=t.getAttribute("data-execution-id");t.addEventListener("click",s=>l(this,null,function*(){s.preventDefault(),yield this.removeItemFromList(e)}))})}removeItemFromList(t){return l(this,null,function*(){let e;return yield fetch("/dpr/removeViewedItem/",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json","CSRF-Token":this.csrfToken},body:JSON.stringify({executionId:t})}).then(()=>{window.location.reload()}).catch(s=>console.error("Error:",s)),e})}};var y=class extends c{setupCanvas(){this.chartContext=this.getElement().querySelector("canvas"),this.id=this.chartContext.getAttribute("id"),this.chartParams=JSON.parse(this.getElement().getAttribute("data-dpr-chart-data")),this.type=this.getElement().getAttribute("data-dpr-chart-type"),this.setValueSuffix(),this.legend=this.getElement().querySelector(`#js-legend-${this.id}`),this.tooltipDetailsEl=document.getElementById(`dpr-${this.id}-tooltip-details`),this.headlineValuesEl=document.getElementById(`dpr-${this.id}-headline-values`),this.labelElement=document.getElementById(`dpr-${this.id}-label`),this.valueElement=document.getElementById(`dpr-${this.id}-value`),this.legendElement=document.getElementById(`dpr-${this.id}-legend`),this.legendElement=document.getElementById(`dpr-${this.id}-legend`),this.timeseries=this.getElement().getAttribute("data-dpr-chart-timeseries"),(this.timeseries||this.type==="line")&&(this.daterangeInputs=document.querySelectorAll(".dpr-granular-date-range"),this.daterangeInputs&&this.daterangeInputs.length?this.daterangeInputs.forEach(t=>{this.partialStart=t.getAttribute("data-partial-start")==="true",this.partialEnd=t.getAttribute("data-partial-end")==="true"}):(this.partialStart=!1,this.partialEnd=!1)),this.singleDataset=this.chartParams.datasets.length===1}initChart(){Chart.defaults.font.family="GDS Transport",Chart.register(ChartDataLabels),Chart.defaults.font.size=12,this.chart=new Chart(this.chartContext,this.chartData),this.initChartEvents()}getColourPallette(){return[{name:"blue",hex:"#5694ca"},{name:"purple",hex:"#912b88"},{name:"green",hex:"#00703c"},{name:"dark_blue",hex:"#003078"},{name:"orange",hex:"#f47738"},{name:"orange",hex:"#28a197"}]}mapHexColourToName(t,e){let a=e.getColourPallette().find(i=>i.hex===t);return a?a.name:""}createDatasets(t,e){return t.map((s,a)=>{let{label:i,data:r}=s,n=e[a%6]?e[a%6]:e[0];return h({label:i,data:r},n)})}generateChartData(t){let{datasets:e,labels:s}=this.chartParams,{options:a,styling:i,datalabels:r,plugins:n,pluginsOptions:d,toolTipOptions:u,hoverEvent:m}=t;return{type:this.type,data:{labels:s,datasets:this.createDatasets(e,i)},options:f(h(h({responsive:!0,maintainAspectRatio:!1,animation:{duration:0},hover:{animationDuration:0}},a&&a),m&&m),{plugins:f(h(h({legend:{position:"bottom"}},d&&d),r&&{datalabels:r}),{tooltip:h(h({},this.setToolTip()),u&&u)})}),plugins:n&&n.length?[...n]:[]}}setToolTip(){return{backgroundColor:"#FFF",bodyColor:"#000",titleFont:{size:16},bodyFont:{size:16},titleColor:"#000",displayColors:!1,borderWidth:1,borderColor:"#b1b4b6",cornerRadius:0,padding:20,footerFont:{weight:"bold"},animation:{duration:0}}}setHoverValue({label:t,value:e,legend:s,ctx:a}){a.tooltipDetailsEl&&(a.tooltipDetailsEl.style.display="block",a.labelElement.innerHTML=a.singleDataset?`${t}`:`${s}: ${t}`,a.valueElement.innerHTML=`${e}`),a.headlineValuesEl&&(a.headlineValuesEl.style.display="none"),s||(a.legendElement.style.display="none")}setValueSuffix(){this.unit=this.getElement().getAttribute("data-dpr-chart-unit"),this.suffix=this.unit==="percentage"?"%":""}isPercentage(){return this.unit==="percentage"}initChartEvents(){this.chart.canvas.addEventListener("mouseout",t=>{this.tooltipDetailsEl&&(this.tooltipDetailsEl.style.display="none"),this.headlineValuesEl&&(this.headlineValuesEl.style.display="block")})}};var _=class extends y{static getModuleName(){return"bar-chart"}initialise(){this.setupCanvas(),this.settings=this.initSettings(),this.chartData=this.generateChartData(this.settings),this.initChart(this.chartData)}initSettings(){return{options:this.setOptions(),toolTipOptions:this.setToolTipOptions(),datalabels:this.setDataLabels(),styling:this.setDatasetStyling()}}setDatasetStyling(){return this.getColourPallette().map(e=>f(h({borderColor:e.hex},this.setBackgroundColour(e.hex)),{datalabels:{align:"center",anchor:"center"}}))}setBackgroundColour(t){let e=this.chartParams.labels.length-1,s=[],a=[],i=[];return this.chartParams.labels.forEach((r,n)=>{this.partialEnd&&n===e||this.partialStart&&n===0?(s.push(t),a.push(3),i.push("#b1b4b6")):(s.push(t),a.push(0),i.push(t))}),{backgroundColor:s,borderWidth:a,borderColor:i}}setToolTipOptions(){let t=this;return{callbacks:{title(e){let{label:s,dataset:a}=e[0],{label:i}=a;return t.singleDataset?`${s}`:`${i}: ${s}`},label(e){let{label:s}=e,{data:a,label:i}=e.dataset,r=`${a[e.dataIndex]}${t.suffix}`;return t.setHoverValue({label:s,value:r,legend:i,ctx:t}),r}}}}setOptions(){let{indexAxis:t,stacked:e}=this.chartParams;return h({indexAxis:t||"x"},e&&{scales:{x:{stacked:!0},y:{stacked:!0}}})}setDataLabels(){return{color:"#FFF",display:()=>!this.timeseries,formatter:t=>`${t}${this.suffix}`,labels:{title:{font:{weight:"bold",size:16,color:"#FFF"}}}}}};var U=class extends y{static getModuleName(){return"doughnut-chart"}initialise(){this.setupCanvas(),this.settings=this.initSettings(),this.chartData=this.generateChartData(this.settings),this.initChart(this.chartData)}initSettings(){return{options:this.setOptions(),styling:this.setDatasetStyling(),datalabels:this.setDataLabels(),pluginsOptions:this.setPluginsOptions(),toolTipOptions:this.setToolTipOptions(),plugins:this.setPlugins()}}setDatasetStyling(){let e=this.getColourPallette().map(s=>s.hex);return[{backgroundColor:[...e,...e],hoverOffset:4,datalabels:{anchor:"center",borderWidth:0}}]}setOptions(){return{cutout:this.chartParams.datasets.length===1?"50%":"20%"}}setPluginsOptions(){return{legend:{display:!0,position:"bottom"}}}setPlugins(){let t=[];return this.chartParams.datasets.length===1&&!this.isPercentage&&t.push(this.setCentralText()),t}setCentralText(){return{id:"text",beforeDraw(t){let{width:e}=t,{height:s}=t,{ctx:a}=t;a.textBaseline="middle";let i=2.5;a.font=`100 ${i}em GDS Transport`,a.fillStyle=" #505a5f";let n=t.data.datasets[0].data.reduce((J,G)=>J+G,0),d=Math.round((e-a.measureText(n).width)/2),u=s/2;a.fillText(n,d,u),a.save(),a.textBaseline="middle",i=1,a.font=`100 ${i}em GDS Transport`,a.fillStyle=" #505a5f";let m="Total",E=Math.round((e-a.measureText(m).width)/2),k=u+30;a.fillText(m,E,k),a.save()}}}setLegend(){let t=this,{legend:e,suffix:s}=this;return{id:"legend",beforeInit(a){let i=document.createElement("ul"),{labels:r}=a.data,{backgroundColor:n,data:d}=a.data.datasets[0];return r.forEach((u,m)=>{let E=m%n.length,k=n[E],J=t.mapHexColourToName(k,t),G=a.data.datasets.length===1?`${d[m]}${s}`:"";i.innerHTML+=` <li aria-label="${u} ${G