katalyst-govuk-formbuilder 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. checksums.yaml +4 -4
  2. data/app/assets/builds/katalyst/govuk/formbuilder.css +2 -1
  3. data/app/assets/builds/katalyst/govuk/formbuilder.js +112 -51
  4. data/app/assets/builds/katalyst/govuk/formbuilder.min.js +8 -8
  5. data/app/assets/builds/katalyst/govuk/formbuilder.min.js.map +1 -1
  6. data/app/helpers/katalyst/govuk/form_builder/builder.rb +4 -4
  7. data/app/helpers/katalyst/govuk/form_builder/frontend.rb +1 -2
  8. data/app/helpers/katalyst/govuk/form_builder/traits/attachment.rb +1 -2
  9. data/node_modules/govuk-frontend/dist/govuk/components/_index.import.scss +2 -0
  10. data/node_modules/govuk-frontend/dist/govuk/components/_index.scss +2 -0
  11. data/node_modules/govuk-frontend/dist/govuk/components/cookie-banner/_mixin.scss +6 -0
  12. data/node_modules/govuk-frontend/dist/govuk/components/feedback/_feedback.import.scss +6 -0
  13. data/node_modules/govuk-frontend/dist/govuk/components/feedback/_index.import.scss +8 -0
  14. data/node_modules/govuk-frontend/dist/govuk/components/feedback/_index.scss +5 -0
  15. data/node_modules/govuk-frontend/dist/govuk/components/feedback/_mixin.scss +48 -0
  16. data/node_modules/govuk-frontend/dist/govuk/components/footer/_mixin.scss +6 -0
  17. data/node_modules/govuk-frontend/dist/govuk/components/language-navigation/_index.import.scss +8 -0
  18. data/node_modules/govuk-frontend/dist/govuk/components/language-navigation/_index.scss +6 -0
  19. data/node_modules/govuk-frontend/dist/govuk/components/language-navigation/_language-navigation.import.scss +6 -0
  20. data/node_modules/govuk-frontend/dist/govuk/components/language-navigation/_mixin.scss +68 -0
  21. data/node_modules/govuk-frontend/dist/govuk/components/service-navigation/_mixin.scss +48 -3
  22. data/node_modules/govuk-frontend/dist/govuk/custom-properties/_frontend-version.mixin.scss +1 -1
  23. data/node_modules/govuk-frontend/dist/govuk/custom-properties/_functional-colours.mixin.scss +1 -0
  24. data/node_modules/govuk-frontend/dist/govuk/helpers/_colour.scss +1 -1
  25. data/node_modules/govuk-frontend/dist/govuk/settings/_colours-organisations.scss +16 -2
  26. metadata +10 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bfaf577c810adcbb0beccb5c19593d351212fa47ac656eab727fddac588dbaa2
4
- data.tar.gz: 498dc851c834e026add583e93c411496007d4bfc3905957686b9a02b854fcb51
3
+ metadata.gz: 6b11ea9e2fcbabca9d00b729bd36da326f97547e04509a29e9f53707ad211033
4
+ data.tar.gz: 4e61026e8417546f56f226ac45ed93429d706b3df7445e1ce994979e360d2b6f
5
5
  SHA512:
6
- metadata.gz: a0534e3ca97f200c06440c6c2d5e698f8f3912ad3b804fbaac7627d0f2c46eea005191033289b7be1358f98e87763d171202e8af6d986a03614e05abd9510a4b
7
- data.tar.gz: db9d235514210ce9a33f31abc660642837a1de680c84e32a968ac118705495b8de8383ebad0a82832da0a3da646e227bcd03c6402021deda7ecc421ec4db40c4
6
+ metadata.gz: 57db78a09877aee800d6a6c8550bed2eb2754f66efb6e5a39e9d75bc82dd7ba2d929d206682f92aa42c3a26c9c195c787e36e57aa1b77ed360a16b18970f6fe1
7
+ data.tar.gz: 5b0addff5eba73d353adbc048e828734051a42f779f31dbb2c7f3bc693e1a887059f4fa659e3070f0a43fa2149e4d5f781abc8b458f5b3b7d9a6375488f29d65
@@ -6,7 +6,7 @@
6
6
  }
7
7
 
8
8
  :root {
9
- --govuk-frontend-version: "6.4.0";
9
+ --govuk-frontend-version: "6.6.0";
10
10
  }
11
11
 
12
12
  :root {
@@ -35,6 +35,7 @@
35
35
  @media print {
36
36
  :root {
37
37
  --govuk-text-colour: var(--govuk-print-text-colour, #000000);
38
+ --govuk-input-border-colour: var(--govuk-print-text-colour, #000000);
38
39
  }
39
40
  }
40
41
 
@@ -46,6 +46,10 @@ function isObject(option) {
46
46
  return !!option && typeof option === "object" && !isArray(option);
47
47
  }
48
48
 
49
+ function isScope($scope) {
50
+ return !!$scope && ($scope instanceof Element || $scope instanceof Document);
51
+ }
52
+
49
53
  function formatErrorMessage(Component, message) {
50
54
  return `${Component.moduleName}: ${message}`;
51
55
  }
@@ -58,9 +62,12 @@ class GOVUKFrontendError extends Error {
58
62
  }
59
63
 
60
64
  class SupportError extends GOVUKFrontendError {
61
- constructor($scope = document.body) {
62
- const supportMessage = "noModule" in HTMLScriptElement.prototype ? 'GOV.UK Frontend initialised without `<body class="govuk-frontend-supported">` from template `<script>` snippet' : "GOV.UK Frontend is not supported in this browser";
63
- super($scope ? supportMessage : 'GOV.UK Frontend initialised without `<script type="module">`');
65
+ constructor(scopeOrMessage = document.body) {
66
+ let supportMessage = "noModule" in HTMLScriptElement.prototype ? 'GOV.UK Frontend initialised without `<body class="govuk-frontend-supported">` from template `<script>` snippet' : "GOV.UK Frontend is not supported in this browser";
67
+ if (!isScope(scopeOrMessage)) {
68
+ supportMessage = 'GOV.UK Frontend initialised without `<script type="module">`';
69
+ }
70
+ super(typeof scopeOrMessage === "string" ? scopeOrMessage : supportMessage);
64
71
  this.name = "SupportError";
65
72
  }
66
73
  }
@@ -96,6 +103,8 @@ class InitError extends GOVUKFrontendError {
96
103
  }
97
104
  }
98
105
 
106
+ const _self = typeof globalThis !== "undefined" ? globalThis : self;
107
+
99
108
  class Component {
100
109
  get $root() {
101
110
  return this._$root;
@@ -135,7 +144,7 @@ class Component {
135
144
  }
136
145
  }
137
146
 
138
- Component.elementType = HTMLElement;
147
+ Component.elementType = _self.HTMLElement;
139
148
 
140
149
  const configOverride = Symbol.for("configOverride");
141
150
 
@@ -154,11 +163,15 @@ class ConfigurableComponent extends Component {
154
163
  throw new ConfigError(formatErrorMessage(childConstructor, "Config passed as parameter into constructor but no defaults defined"));
155
164
  }
156
165
  const datasetConfig = normaliseDataset(childConstructor, this._$root.dataset);
157
- this._config = mergeConfigs(childConstructor.defaults, config != null ? config : {}, this[configOverride](datasetConfig), datasetConfig);
166
+ this._config = mergeConfigs(childConstructor.defaults, config != null ? config : {});
167
+ this._config = mergeConfigs(this._config, this[configOverride](datasetConfig), datasetConfig);
158
168
  }
159
169
  }
160
170
 
161
171
  function normaliseString(value, property) {
172
+ if (property != null && property.type && ![ "string", "number", "boolean" ].includes(property.type)) {
173
+ return;
174
+ }
162
175
  const trimmedValue = value ? value.trim() : "";
163
176
  let output;
164
177
  let outputType = property == null ? void 0 : property.type;
@@ -265,6 +278,17 @@ function extractConfigByNamespace(schema, dataset, namespace) {
265
278
  return newObject[namespace];
266
279
  }
267
280
 
281
+ function createElement(tagName, attributes = {}, children = []) {
282
+ const $element = document.createElement(tagName);
283
+ Object.entries(attributes).forEach(([name, value]) => {
284
+ $element.setAttribute(name, value);
285
+ });
286
+ for (const child of children) {
287
+ $element.append(child);
288
+ }
289
+ return $element;
290
+ }
291
+
268
292
  class I18n {
269
293
  constructor(translations = {}, config = {}) {
270
294
  var _config$locale;
@@ -411,13 +435,22 @@ function closestAttributeValue($element, attributeName) {
411
435
  maxwords: undefined
412
436
  };
413
437
  }
438
+ if ("maxwords" in datasetConfig || this.config.maxwords !== undefined) {
439
+ console.warn(formatErrorMessage(CharacterCount, 'Option `maxwords` is deprecated. Use `maxlength` with `countType: "words"` instead.'));
440
+ if (!("maxlength" in datasetConfig)) {
441
+ var _datasetConfig$maxwor;
442
+ configOverrides.maxlength = (_datasetConfig$maxwor = datasetConfig.maxwords) != null ? _datasetConfig$maxwor : this.config.maxwords;
443
+ configOverrides.countType = "words";
444
+ }
445
+ }
414
446
  return configOverrides;
415
447
  }
416
448
  constructor($root, config = {}) {
417
- var _ref, _this$config$maxwords;
449
+ var _this$config$maxlengt;
418
450
  super($root, config);
419
451
  this.$textarea = void 0;
420
452
  this.count = 0;
453
+ this.segmenter = null;
421
454
  this.$visibleCountMessage = void 0;
422
455
  this.$screenReaderCountMessage = void 0;
423
456
  this.lastInputTimestamp = null;
@@ -441,7 +474,15 @@ function closestAttributeValue($element, attributeName) {
441
474
  this.i18n = new I18n(this.config.i18n, {
442
475
  locale: closestAttributeValue(this.$root, "lang")
443
476
  });
444
- this.maxLength = (_ref = (_this$config$maxwords = this.config.maxwords) != null ? _this$config$maxwords : this.config.maxlength) != null ? _ref : Infinity;
477
+ if (this.config.countType === "characters" || this.config.countType === "words" && this.config.maxwords === undefined) {
478
+ if (!("Segmenter" in Intl)) {
479
+ throw new SupportError(formatErrorMessage(CharacterCount, 'Support for "Intl.Segmenter" required'));
480
+ }
481
+ this.segmenter = new Intl.Segmenter(this.i18n.locale, {
482
+ granularity: this.config.countType === "words" ? "word" : "grapheme"
483
+ });
484
+ }
485
+ this.maxLength = (_this$config$maxlengt = this.config.maxlength) != null ? _this$config$maxlengt : Infinity;
445
486
  this.$textarea = $textarea;
446
487
  const textareaDescriptionId = `${this.$textarea.id}-info`;
447
488
  const $textareaDescription = document.getElementById(textareaDescriptionId);
@@ -459,15 +500,16 @@ function closestAttributeValue($element, attributeName) {
459
500
  });
460
501
  }
461
502
  this.$textarea.insertAdjacentElement("afterend", $textareaDescription);
462
- const $screenReaderCountMessage = document.createElement("div");
463
- $screenReaderCountMessage.className = "govuk-character-count__sr-status govuk-visually-hidden";
464
- $screenReaderCountMessage.setAttribute("aria-live", "polite");
503
+ const $screenReaderCountMessage = createElement("div", {
504
+ class: "govuk-character-count__sr-status govuk-visually-hidden",
505
+ "aria-live": "polite"
506
+ });
465
507
  this.$screenReaderCountMessage = $screenReaderCountMessage;
466
508
  $textareaDescription.insertAdjacentElement("afterend", $screenReaderCountMessage);
467
- const $visibleCountMessage = document.createElement("div");
468
- $visibleCountMessage.className = $textareaDescription.className;
469
- $visibleCountMessage.classList.add("govuk-character-count__status");
470
- $visibleCountMessage.setAttribute("aria-hidden", "true");
509
+ const $visibleCountMessage = createElement("div", {
510
+ class: `${$textareaDescription.className} govuk-character-count__status`,
511
+ "aria-hidden": "true"
512
+ });
471
513
  this.$visibleCountMessage = $visibleCountMessage;
472
514
  $textareaDescription.insertAdjacentElement("afterend", $visibleCountMessage);
473
515
  $textareaDescription.classList.add("govuk-visually-hidden");
@@ -535,26 +577,38 @@ function closestAttributeValue($element, attributeName) {
535
577
  }
536
578
  updateCount() {
537
579
  const text = this.$textarea.value;
538
- if (this.config.maxwords) {
539
- var _text$match;
540
- const tokens = (_text$match = text.match(/\S+/g)) != null ? _text$match : [];
541
- this.count = tokens.length;
580
+ if (this.config.countType === "characters") {
581
+ this.count = this.segmenter ? Array.from(this.segmenter.segment(text)).length : 0;
582
+ return;
583
+ }
584
+ if (this.config.countType === "words") {
585
+ if (this.config.maxwords !== undefined) {
586
+ var _text$match$length, _text$match;
587
+ this.count = (_text$match$length = (_text$match = text.match(/\S+/g)) == null ? void 0 : _text$match.length) != null ? _text$match$length : 0;
588
+ return;
589
+ }
590
+ const segments = this.segmenter ? Array.from(this.segmenter.segment(text)) : [];
591
+ this.count = segments.filter(segment => segment.isWordLike).length;
542
592
  return;
543
593
  }
544
594
  this.count = text.length;
545
595
  }
546
596
  getCountMessage() {
547
597
  const remainingNumber = this.maxLength - this.count;
548
- const countType = this.config.maxwords ? "words" : "characters";
549
- return this.formatCountMessage(remainingNumber, countType);
598
+ return this.formatCountMessage(remainingNumber);
550
599
  }
551
600
  formatCountMessage(remainingNumber, countType) {
601
+ countType = countType != null ? countType : this.config.countType;
602
+ let translationKeyPrefix = "characters";
603
+ let translationKeySuffix = remainingNumber < 0 ? "OverLimit" : "UnderLimit";
604
+ if (countType === "words") {
605
+ translationKeyPrefix = "words";
606
+ }
552
607
  if (remainingNumber === 0) {
553
- return this.i18n.t(`${countType}AtLimit`);
608
+ translationKeySuffix = "AtLimit";
554
609
  }
555
- const translationKeySuffix = remainingNumber < 0 ? "OverLimit" : "UnderLimit";
556
- return this.i18n.t(`${countType}${translationKeySuffix}`, {
557
- count: Math.abs(remainingNumber)
610
+ return this.i18n.t(`${translationKeyPrefix}${translationKeySuffix}`, {
611
+ count: remainingNumber === 0 ? undefined : Math.abs(remainingNumber)
558
612
  });
559
613
  }
560
614
  isOverThreshold() {
@@ -572,6 +626,7 @@ CharacterCount.moduleName = "govuk-character-count";
572
626
 
573
627
  CharacterCount.defaults = Object.freeze({
574
628
  threshold: 0,
629
+ countType: "length",
575
630
  i18n: {
576
631
  charactersUnderLimit: {
577
632
  one: "You have %{count} character remaining",
@@ -610,6 +665,9 @@ CharacterCount.schema = Object.freeze({
610
665
  },
611
666
  threshold: {
612
667
  type: "number"
668
+ },
669
+ countType: {
670
+ type: "string"
613
671
  }
614
672
  },
615
673
  anyOf: [ {
@@ -842,46 +900,48 @@ ErrorSummary.schema = Object.freeze({
842
900
  this.$input.addEventListener("change", this.onChange.bind(this));
843
901
  this.updateDisabledState();
844
902
  this.observeDisabledState();
845
- this.$announcements = document.createElement("span");
846
- this.$announcements.classList.add("govuk-file-upload-announcements");
847
- this.$announcements.classList.add("govuk-visually-hidden");
848
- this.$announcements.setAttribute("aria-live", "assertive");
903
+ this.$announcements = createElement("span", {
904
+ class: "govuk-file-upload-announcements govuk-visually-hidden",
905
+ "aria-live": "assertive"
906
+ });
849
907
  this.$root.insertAdjacentElement("afterend", this.$announcements);
850
908
  this.bindDraggingEvents();
851
909
  }
852
910
  createStatus() {
853
- const $status = document.createElement("span");
854
- $status.className = "govuk-body govuk-file-upload-button__status";
855
- $status.setAttribute("aria-live", "polite");
911
+ const $status = createElement("span", {
912
+ class: "govuk-body govuk-file-upload-button__status",
913
+ "aria-live": "polite"
914
+ });
856
915
  $status.innerText = this.i18n.t("noFileChosen");
857
916
  return $status;
858
917
  }
859
918
  createButton() {
860
- const $button = document.createElement("button");
861
- $button.classList.add("govuk-file-upload-button");
862
- $button.type = "button";
863
- $button.id = this.id;
864
- $button.classList.add("govuk-file-upload-button--empty");
919
+ const $button = createElement("button", {
920
+ class: "govuk-file-upload-button govuk-file-upload-button--empty",
921
+ type: "button",
922
+ id: this.id
923
+ });
865
924
  const ariaDescribedBy = this.$input.getAttribute("aria-describedby");
866
925
  if (ariaDescribedBy) {
867
926
  $button.setAttribute("aria-describedby", ariaDescribedBy);
868
927
  }
869
928
  $button.appendChild(this.$status);
870
- const commaSpan = document.createElement("span");
871
- commaSpan.className = "govuk-visually-hidden";
872
- commaSpan.innerText = ", ";
873
- commaSpan.id = `${this.id}-comma`;
929
+ const commaSpan = createElement("span", {
930
+ class: "govuk-visually-hidden",
931
+ id: `${this.id}-comma`
932
+ }, [ ", " ]);
874
933
  $button.appendChild(commaSpan);
875
- const containerSpan = document.createElement("span");
876
- containerSpan.className = "govuk-file-upload-button__pseudo-button-container";
877
- const buttonSpan = document.createElement("span");
878
- buttonSpan.className = "govuk-button govuk-button--secondary govuk-file-upload-button__pseudo-button";
879
- buttonSpan.innerText = this.i18n.t("chooseFilesButton");
934
+ const containerSpan = createElement("span", {
935
+ class: "govuk-file-upload-button__pseudo-button-container"
936
+ });
937
+ const buttonSpan = createElement("span", {
938
+ class: "govuk-button govuk-button--secondary govuk-file-upload-button__pseudo-button"
939
+ }, [ this.i18n.t("chooseFilesButton") ]);
880
940
  containerSpan.appendChild(buttonSpan);
881
941
  containerSpan.insertAdjacentText("beforeend", " ");
882
- const instructionSpan = document.createElement("span");
883
- instructionSpan.className = "govuk-body govuk-file-upload-button__instruction";
884
- instructionSpan.innerText = this.i18n.t("dropInstruction");
942
+ const instructionSpan = createElement("span", {
943
+ class: "govuk-body govuk-file-upload-button__instruction"
944
+ }, [ this.i18n.t("dropInstruction") ]);
885
945
  containerSpan.appendChild(instructionSpan);
886
946
  $button.appendChild(containerSpan);
887
947
  $button.setAttribute("aria-labelledby", `${this.$label.id} ${commaSpan.id} ${$button.id}`);
@@ -1078,9 +1138,10 @@ function countFileItems$1(list) {
1078
1138
  locale: closestAttributeValue(this.$root, "lang")
1079
1139
  });
1080
1140
  this.$showHideButton.removeAttribute("hidden");
1081
- const $screenReaderStatusMessage = document.createElement("div");
1082
- $screenReaderStatusMessage.className = "govuk-password-input__sr-status govuk-visually-hidden";
1083
- $screenReaderStatusMessage.setAttribute("aria-live", "polite");
1141
+ const $screenReaderStatusMessage = createElement("div", {
1142
+ class: "govuk-password-input__sr-status govuk-visually-hidden",
1143
+ "aria-live": "polite"
1144
+ });
1084
1145
  this.$screenReaderStatusMessage = $screenReaderStatusMessage;
1085
1146
  this.$input.insertAdjacentElement("afterend", $screenReaderStatusMessage);
1086
1147
  this.$showHideButton.addEventListener("click", this.toggle.bind(this));
@@ -1,11 +1,11 @@
1
- import{Controller as t,Application as e}from"@hotwired/stimulus";import{DirectUploadController as n}from"@rails/activestorage";function i(t,e){return t instanceof HTMLElement&&t.hasAttribute(`data-${e}-init`)}function s(t=document.body){return!!t&&t.classList.contains("govuk-frontend-supported")}function o(t){return!!t&&"object"==typeof t&&!function(t){return Array.isArray(t)}(t)}function r(t,e){return`${t.moduleName}: ${e}`}class a extends Error{constructor(...t){super(...t),this.name="GOVUKFrontendError"}}class l extends a{constructor(t=document.body){const e="noModule"in HTMLScriptElement.prototype?'GOV.UK Frontend initialised without `<body class="govuk-frontend-supported">` from template `<script>` snippet':"GOV.UK Frontend is not supported in this browser";super(t?e:'GOV.UK Frontend initialised without `<script type="module">`'),this.name="SupportError"}}class u extends a{constructor(...t){super(...t),this.name="ConfigError"}}class d extends a{constructor(t){let e="string"==typeof t?t:"";if(o(t)){const{component:n,identifier:i,element:s,expectedType:o}=t;e=i,e+=s?` is not of type ${null!=o?o:"HTMLElement"}`:" not found",n&&(e=r(n,e))}super(e),this.name="ElementError"}}class c extends a{constructor(t){super("string"==typeof t?t:r(t,"Root element (`$root`) already initialised")),this.name="InitError"}}class h{get $root(){return this._$root}constructor(t){this._$root=void 0;const e=this.constructor;if("string"!=typeof e.moduleName)throw new c("`moduleName` not defined in component");if(!(t instanceof e.elementType))throw new d({element:t,component:e,identifier:"Root element (`$root`)",expectedType:e.elementType.name});this._$root=t,e.checkSupport(),this.checkInitialised();const n=e.moduleName;this.$root.setAttribute(`data-${n}-init`,"")}checkInitialised(){const t=this.constructor,e=t.moduleName;if(e&&i(this.$root,e))throw new c(t)}static checkSupport(){if(!s())throw new l}}h.elementType=HTMLElement;const p=Symbol.for("configOverride");class m extends h{[p](t){return{}}get config(){return this._config}constructor(t,e){super(t),this._config=void 0;const n=this.constructor;if(!o(n.defaults))throw new u(r(n,"Config passed as parameter into constructor but no defaults defined"));const i=f(n,this._$root.dataset);this._config=v(n.defaults,null!=e?e:{},this[p](i),i)}}function g(t,e){const n=t?t.trim():"";let i,s=null==e?void 0:e.type;switch(s||(["true","false"].includes(n)&&(s="boolean"),n.length>0&&isFinite(Number(n))&&(s="number")),s){case"boolean":i="true"===n;break;case"number":i=Number(n);break;default:i=t}return i}function f(t,e){if(!o(t.schema))throw new u(r(t,"Config passed as parameter into constructor but no schema defined"));const n={},i=Object.entries(t.schema.properties);for(const s of i){const[i,o]=s,r=i.toString();r in e&&(n[r]=g(e[r],o)),"object"===(null==o?void 0:o.type)&&(n[r]=b(t.schema,e,i))}return n}function v(...t){const e={};for(const n of t)for(const t of Object.keys(n)){const i=e[t],s=n[t];o(i)&&o(s)?e[t]=v(i,s):e[t]=s}return e}function b(t,e,n){const i=t.properties[n];if("object"!==(null==i?void 0:i.type))return;const s={[n]:{}};for(const[t,i]of Object.entries(e)){let e=s;const r=t.split(".");for(const[s,a]of r.entries())o(e)&&(s<r.length-1?(o(e[a])||(e[a]={}),e=e[a]):t!==n&&(e[a]=g(i)))}return s[n]}class y{constructor(t={},e={}){var n;this.translations=void 0,this.locale=void 0,this.translations=t,this.locale=null!=(n=e.locale)?n:document.documentElement.lang||"en"}t(t,e){if(!t)throw new Error("i18n: lookup key missing");let n=this.translations[t];if("number"==typeof(null==e?void 0:e.count)&&o(n)){const i=n[this.getPluralSuffix(t,e.count)];i&&(n=i)}if("string"==typeof n){if(n.match(/%{(.\S+)}/)){if(!e)throw new Error("i18n: cannot replace placeholders in string if no option data provided");return this.replacePlaceholders(n,e)}return n}return t}replacePlaceholders(t,e){const n=Intl.NumberFormat.supportedLocalesOf(this.locale).length?new Intl.NumberFormat(this.locale):void 0;return t.replace(/%{(.\S+)}/g,function(t,i){if(Object.prototype.hasOwnProperty.call(e,i)){const t=e[i];return!1===t||"number"!=typeof t&&"string"!=typeof t?"":"number"==typeof t?n?n.format(t):`${t}`:t}throw new Error(`i18n: no data found to replace ${t} placeholder in string`)})}hasIntlPluralRulesSupport(){return Boolean("PluralRules"in window.Intl&&Intl.PluralRules.supportedLocalesOf(this.locale).length)}getPluralSuffix(t,e){if(e=Number(e),!isFinite(e))return"other";const n=this.translations[t],i=this.hasIntlPluralRulesSupport()?new Intl.PluralRules(this.locale).select(e):"other";if(o(n)){if(i in n)return i;if("other"in n)return console.warn(`i18n: Missing plural form ".${i}" for "${this.locale}" locale. Falling back to ".other".`),"other"}throw new Error(`i18n: Plural form ".other" is required for "${this.locale}" locale`)}}
1
+ import{Controller as t,Application as e}from"@hotwired/stimulus";import{DirectUploadController as n}from"@rails/activestorage";function i(t,e){return t instanceof HTMLElement&&t.hasAttribute(`data-${e}-init`)}function s(t=document.body){return!!t&&t.classList.contains("govuk-frontend-supported")}function o(t){return!!t&&"object"==typeof t&&!function(t){return Array.isArray(t)}(t)}function r(t,e){return`${t.moduleName}: ${e}`}class a extends Error{constructor(...t){super(...t),this.name="GOVUKFrontendError"}}class l extends a{constructor(t=document.body){let e="noModule"in HTMLScriptElement.prototype?'GOV.UK Frontend initialised without `<body class="govuk-frontend-supported">` from template `<script>` snippet':"GOV.UK Frontend is not supported in this browser";var n;(n=t)&&(n instanceof Element||n instanceof Document)||(e='GOV.UK Frontend initialised without `<script type="module">`'),super("string"==typeof t?t:e),this.name="SupportError"}}class u extends a{constructor(...t){super(...t),this.name="ConfigError"}}class d extends a{constructor(t){let e="string"==typeof t?t:"";if(o(t)){const{component:n,identifier:i,element:s,expectedType:o}=t;e=i,e+=s?` is not of type ${null!=o?o:"HTMLElement"}`:" not found",n&&(e=r(n,e))}super(e),this.name="ElementError"}}class c extends a{constructor(t){super("string"==typeof t?t:r(t,"Root element (`$root`) already initialised")),this.name="InitError"}}const h="undefined"!=typeof globalThis?globalThis:self;class p{get $root(){return this._$root}constructor(t){this._$root=void 0;const e=this.constructor;if("string"!=typeof e.moduleName)throw new c("`moduleName` not defined in component");if(!(t instanceof e.elementType))throw new d({element:t,component:e,identifier:"Root element (`$root`)",expectedType:e.elementType.name});this._$root=t,e.checkSupport(),this.checkInitialised();const n=e.moduleName;this.$root.setAttribute(`data-${n}-init`,"")}checkInitialised(){const t=this.constructor,e=t.moduleName;if(e&&i(this.$root,e))throw new c(t)}static checkSupport(){if(!s())throw new l}}p.elementType=h.HTMLElement;const m=Symbol.for("configOverride");class g extends p{[m](t){return{}}get config(){return this._config}constructor(t,e){super(t),this._config=void 0;const n=this.constructor;if(!o(n.defaults))throw new u(r(n,"Config passed as parameter into constructor but no defaults defined"));const i=v(n,this._$root.dataset);this._config=b(n.defaults,null!=e?e:{}),this._config=b(this._config,this[m](i),i)}}function f(t,e){if(null!=e&&e.type&&!["string","number","boolean"].includes(e.type))return;const n=t?t.trim():"";let i,s=null==e?void 0:e.type;switch(s||(["true","false"].includes(n)&&(s="boolean"),n.length>0&&isFinite(Number(n))&&(s="number")),s){case"boolean":i="true"===n;break;case"number":i=Number(n);break;default:i=t}return i}function v(t,e){if(!o(t.schema))throw new u(r(t,"Config passed as parameter into constructor but no schema defined"));const n={},i=Object.entries(t.schema.properties);for(const s of i){const[i,o]=s,r=i.toString();r in e&&(n[r]=f(e[r],o)),"object"===(null==o?void 0:o.type)&&(n[r]=y(t.schema,e,i))}return n}function b(...t){const e={};for(const n of t)for(const t of Object.keys(n)){const i=e[t],s=n[t];o(i)&&o(s)?e[t]=b(i,s):e[t]=s}return e}function y(t,e,n){const i=t.properties[n];if("object"!==(null==i?void 0:i.type))return;const s={[n]:{}};for(const[t,i]of Object.entries(e)){let e=s;const r=t.split(".");for(const[s,a]of r.entries())o(e)&&(s<r.length-1?(o(e[a])||(e[a]={}),e=e[a]):t!==n&&(e[a]=f(i)))}return s[n]}function w(t,e={},n=[]){const i=document.createElement(t);Object.entries(e).forEach(([t,e])=>{i.setAttribute(t,e)});for(const t of n)i.append(t);return i}class ${constructor(t={},e={}){var n;this.translations=void 0,this.locale=void 0,this.translations=t,this.locale=null!=(n=e.locale)?n:document.documentElement.lang||"en"}t(t,e){if(!t)throw new Error("i18n: lookup key missing");let n=this.translations[t];if("number"==typeof(null==e?void 0:e.count)&&o(n)){const i=n[this.getPluralSuffix(t,e.count)];i&&(n=i)}if("string"==typeof n){if(n.match(/%{(.\S+)}/)){if(!e)throw new Error("i18n: cannot replace placeholders in string if no option data provided");return this.replacePlaceholders(n,e)}return n}return t}replacePlaceholders(t,e){const n=Intl.NumberFormat.supportedLocalesOf(this.locale).length?new Intl.NumberFormat(this.locale):void 0;return t.replace(/%{(.\S+)}/g,function(t,i){if(Object.prototype.hasOwnProperty.call(e,i)){const t=e[i];return!1===t||"number"!=typeof t&&"string"!=typeof t?"":"number"==typeof t?n?n.format(t):`${t}`:t}throw new Error(`i18n: no data found to replace ${t} placeholder in string`)})}hasIntlPluralRulesSupport(){return Boolean("PluralRules"in window.Intl&&Intl.PluralRules.supportedLocalesOf(this.locale).length)}getPluralSuffix(t,e){if(e=Number(e),!isFinite(e))return"other";const n=this.translations[t],i=this.hasIntlPluralRulesSupport()?new Intl.PluralRules(this.locale).select(e):"other";if(o(n)){if(i in n)return i;if("other"in n)return console.warn(`i18n: Missing plural form ".${i}" for "${this.locale}" locale. Falling back to ".other".`),"other"}throw new Error(`i18n: Plural form ".other" is required for "${this.locale}" locale`)}}
2
2
  /**
3
3
  * JavaScript enhancements for the Button component
4
4
  *
5
5
  * @preserve
6
6
  * @augments ConfigurableComponent<ButtonConfig>
7
7
  */
8
- class w extends m{constructor(t,e={}){super(t,e),this.debounceFormSubmitTimer=null,this.$root.addEventListener("keydown",t=>this.handleKeyDown(t)),this.$root.addEventListener("click",t=>this.debounce(t))}handleKeyDown(t){const e=t.target;" "===t.key&&e instanceof HTMLElement&&"button"===e.getAttribute("role")&&(t.preventDefault(),e.click())}debounce(t){if(this.config.preventDoubleClick)return this.debounceFormSubmitTimer?(t.preventDefault(),!1):void(this.debounceFormSubmitTimer=window.setTimeout(()=>{this.debounceFormSubmitTimer=null},1e3))}}function $(t,e){const n=t.closest(`[${e}]`);return n?n.getAttribute(e):null}
8
+ class E extends g{constructor(t,e={}){super(t,e),this.debounceFormSubmitTimer=null,this.$root.addEventListener("keydown",t=>this.handleKeyDown(t)),this.$root.addEventListener("click",t=>this.debounce(t))}handleKeyDown(t){const e=t.target;" "===t.key&&e instanceof HTMLElement&&"button"===e.getAttribute("role")&&(t.preventDefault(),e.click())}debounce(t){if(this.config.preventDoubleClick)return this.debounceFormSubmitTimer?(t.preventDefault(),!1):void(this.debounceFormSubmitTimer=window.setTimeout(()=>{this.debounceFormSubmitTimer=null},1e3))}}function C(t,e){const n=t.closest(`[${e}]`);return n?n.getAttribute(e):null}
9
9
  /**
10
10
  * Character count component
11
11
  *
@@ -18,13 +18,13 @@ class w extends m{constructor(t,e={}){super(t,e),this.debounceFormSubmitTimer=nu
18
18
  *
19
19
  * @preserve
20
20
  * @augments ConfigurableComponent<CharacterCountConfig>
21
- */w.moduleName="govuk-button",w.defaults=Object.freeze({preventDoubleClick:!1}),w.schema=Object.freeze({properties:{preventDoubleClick:{type:"boolean"}}});class E extends m{[p](t){let e={};return("maxwords"in t||"maxlength"in t)&&(e={maxlength:void 0,maxwords:void 0}),e}constructor(t,e={}){var n,i;super(t,e),this.$textarea=void 0,this.count=0,this.$visibleCountMessage=void 0,this.$screenReaderCountMessage=void 0,this.lastInputTimestamp=null,this.lastInputValue="",this.valueChecker=null,this.i18n=void 0,this.maxLength=void 0;const s=this.$root.querySelector(".govuk-js-character-count");if(!(s instanceof HTMLTextAreaElement||s instanceof HTMLInputElement))throw new d({component:E,element:s,expectedType:"HTMLTextareaElement or HTMLInputElement",identifier:"Form field (`.govuk-js-character-count`)"});const o=function(t,e){const n=[];for(const[i,s]of Object.entries(t)){const t=[];if(Array.isArray(s)){for(const{required:n,errorMessage:i}of s)n.every(t=>!!e[t])||t.push(i);"anyOf"!==i||s.length-t.length>=1||n.push(...t)}}return n}(E.schema,this.config);if(o[0])throw new u(r(E,o[0]));this.i18n=new y(this.config.i18n,{locale:$(this.$root,"lang")}),this.maxLength=null!=(n=null!=(i=this.config.maxwords)?i:this.config.maxlength)?n:1/0,this.$textarea=s;const a=`${this.$textarea.id}-info`,l=document.getElementById(a);if(!l)throw new d({component:E,element:l,identifier:`Count message (\`id="${a}"\`)`});this.$errorMessage=this.$root.querySelector(".govuk-error-message"),l.textContent.match(/^\s*$/)&&(l.textContent=this.i18n.t("textareaDescription",{count:this.maxLength})),this.$textarea.insertAdjacentElement("afterend",l);const c=document.createElement("div");c.className="govuk-character-count__sr-status govuk-visually-hidden",c.setAttribute("aria-live","polite"),this.$screenReaderCountMessage=c,l.insertAdjacentElement("afterend",c);const h=document.createElement("div");h.className=l.className,h.classList.add("govuk-character-count__status"),h.setAttribute("aria-hidden","true"),this.$visibleCountMessage=h,l.insertAdjacentElement("afterend",h),l.classList.add("govuk-visually-hidden"),this.$textarea.removeAttribute("maxlength"),this.bindChangeEvents(),window.addEventListener("pageshow",()=>{this.$textarea.value!==this.$textarea.textContent&&(this.updateCount(),this.updateCountMessage())}),this.updateCount(),this.updateCountMessage()}bindChangeEvents(){this.$textarea.addEventListener("input",()=>this.handleInput()),this.$textarea.addEventListener("focus",()=>this.handleFocus()),this.$textarea.addEventListener("blur",()=>this.handleBlur())}handleInput(){this.updateCount(),this.updateVisibleCountMessage(),this.lastInputTimestamp=Date.now()}handleFocus(){this.valueChecker=window.setInterval(()=>{(!this.lastInputTimestamp||Date.now()-500>=this.lastInputTimestamp)&&this.updateIfValueChanged()},1e3)}handleBlur(){this.valueChecker&&window.clearInterval(this.valueChecker)}updateIfValueChanged(){this.$textarea.value!==this.lastInputValue&&(this.lastInputValue=this.$textarea.value,this.updateCountMessage())}updateCountMessage(){this.updateVisibleCountMessage(),this.updateScreenReaderCountMessage()}updateVisibleCountMessage(){const t=this.maxLength-this.count<0;this.$visibleCountMessage.classList.toggle("govuk-character-count__message--disabled",!this.isOverThreshold()),this.$errorMessage||this.$textarea.classList.toggle("govuk-textarea--error",t),this.$visibleCountMessage.classList.toggle("govuk-error-message",t),this.$visibleCountMessage.classList.toggle("govuk-hint",!t),this.$visibleCountMessage.textContent=this.getCountMessage()}updateScreenReaderCountMessage(){this.isOverThreshold()?this.$screenReaderCountMessage.removeAttribute("aria-hidden"):this.$screenReaderCountMessage.setAttribute("aria-hidden","true"),this.$screenReaderCountMessage.textContent=this.getCountMessage()}updateCount(){const t=this.$textarea.value;if(this.config.maxwords){var e;const n=null!=(e=t.match(/\S+/g))?e:[];return void(this.count=n.length)}this.count=t.length}getCountMessage(){const t=this.maxLength-this.count,e=this.config.maxwords?"words":"characters";return this.formatCountMessage(t,e)}formatCountMessage(t,e){if(0===t)return this.i18n.t(`${e}AtLimit`);const n=t<0?"OverLimit":"UnderLimit";return this.i18n.t(`${e}${n}`,{count:Math.abs(t)})}isOverThreshold(){if(!this.config.threshold)return!0;const t=this.count;return this.maxLength*this.config.threshold/100<=t}}E.moduleName="govuk-character-count",E.defaults=Object.freeze({threshold:0,i18n:{charactersUnderLimit:{one:"You have %{count} character remaining",other:"You have %{count} characters remaining"},charactersAtLimit:"You have 0 characters remaining",charactersOverLimit:{one:"You have %{count} character too many",other:"You have %{count} characters too many"},wordsUnderLimit:{one:"You have %{count} word remaining",other:"You have %{count} words remaining"},wordsAtLimit:"You have 0 words remaining",wordsOverLimit:{one:"You have %{count} word too many",other:"You have %{count} words too many"},textareaDescription:{other:""}}}),E.schema=Object.freeze({properties:{i18n:{type:"object"},maxwords:{type:"number"},maxlength:{type:"number"},threshold:{type:"number"}},anyOf:[{required:["maxwords"],errorMessage:'Either "maxlength" or "maxwords" must be provided'},{required:["maxlength"],errorMessage:'Either "maxlength" or "maxwords" must be provided'}]});
21
+ */E.moduleName="govuk-button",E.defaults=Object.freeze({preventDoubleClick:!1}),E.schema=Object.freeze({properties:{preventDoubleClick:{type:"boolean"}}});class T extends g{[m](t){let e={};var n;(("maxwords"in t||"maxlength"in t)&&(e={maxlength:void 0,maxwords:void 0}),"maxwords"in t||void 0!==this.config.maxwords)&&(console.warn(r(T,'Option `maxwords` is deprecated. Use `maxlength` with `countType: "words"` instead.')),"maxlength"in t||(e.maxlength=null!=(n=t.maxwords)?n:this.config.maxwords,e.countType="words"));return e}constructor(t,e={}){var n;super(t,e),this.$textarea=void 0,this.count=0,this.segmenter=null,this.$visibleCountMessage=void 0,this.$screenReaderCountMessage=void 0,this.lastInputTimestamp=null,this.lastInputValue="",this.valueChecker=null,this.i18n=void 0,this.maxLength=void 0;const i=this.$root.querySelector(".govuk-js-character-count");if(!(i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement))throw new d({component:T,element:i,expectedType:"HTMLTextareaElement or HTMLInputElement",identifier:"Form field (`.govuk-js-character-count`)"});const s=function(t,e){const n=[];for(const[i,s]of Object.entries(t)){const t=[];if(Array.isArray(s)){for(const{required:n,errorMessage:i}of s)n.every(t=>!!e[t])||t.push(i);"anyOf"!==i||s.length-t.length>=1||n.push(...t)}}return n}(T.schema,this.config);if(s[0])throw new u(r(T,s[0]));if(this.i18n=new $(this.config.i18n,{locale:C(this.$root,"lang")}),"characters"===this.config.countType||"words"===this.config.countType&&void 0===this.config.maxwords){if(!("Segmenter"in Intl))throw new l(r(T,'Support for "Intl.Segmenter" required'));this.segmenter=new Intl.Segmenter(this.i18n.locale,{granularity:"words"===this.config.countType?"word":"grapheme"})}this.maxLength=null!=(n=this.config.maxlength)?n:1/0,this.$textarea=i;const o=`${this.$textarea.id}-info`,a=document.getElementById(o);if(!a)throw new d({component:T,element:a,identifier:`Count message (\`id="${o}"\`)`});this.$errorMessage=this.$root.querySelector(".govuk-error-message"),a.textContent.match(/^\s*$/)&&(a.textContent=this.i18n.t("textareaDescription",{count:this.maxLength})),this.$textarea.insertAdjacentElement("afterend",a);const c=w("div",{class:"govuk-character-count__sr-status govuk-visually-hidden","aria-live":"polite"});this.$screenReaderCountMessage=c,a.insertAdjacentElement("afterend",c);const h=w("div",{class:`${a.className} govuk-character-count__status`,"aria-hidden":"true"});this.$visibleCountMessage=h,a.insertAdjacentElement("afterend",h),a.classList.add("govuk-visually-hidden"),this.$textarea.removeAttribute("maxlength"),this.bindChangeEvents(),window.addEventListener("pageshow",()=>{this.$textarea.value!==this.$textarea.textContent&&(this.updateCount(),this.updateCountMessage())}),this.updateCount(),this.updateCountMessage()}bindChangeEvents(){this.$textarea.addEventListener("input",()=>this.handleInput()),this.$textarea.addEventListener("focus",()=>this.handleFocus()),this.$textarea.addEventListener("blur",()=>this.handleBlur())}handleInput(){this.updateCount(),this.updateVisibleCountMessage(),this.lastInputTimestamp=Date.now()}handleFocus(){this.valueChecker=window.setInterval(()=>{(!this.lastInputTimestamp||Date.now()-500>=this.lastInputTimestamp)&&this.updateIfValueChanged()},1e3)}handleBlur(){this.valueChecker&&window.clearInterval(this.valueChecker)}updateIfValueChanged(){this.$textarea.value!==this.lastInputValue&&(this.lastInputValue=this.$textarea.value,this.updateCountMessage())}updateCountMessage(){this.updateVisibleCountMessage(),this.updateScreenReaderCountMessage()}updateVisibleCountMessage(){const t=this.maxLength-this.count<0;this.$visibleCountMessage.classList.toggle("govuk-character-count__message--disabled",!this.isOverThreshold()),this.$errorMessage||this.$textarea.classList.toggle("govuk-textarea--error",t),this.$visibleCountMessage.classList.toggle("govuk-error-message",t),this.$visibleCountMessage.classList.toggle("govuk-hint",!t),this.$visibleCountMessage.textContent=this.getCountMessage()}updateScreenReaderCountMessage(){this.isOverThreshold()?this.$screenReaderCountMessage.removeAttribute("aria-hidden"):this.$screenReaderCountMessage.setAttribute("aria-hidden","true"),this.$screenReaderCountMessage.textContent=this.getCountMessage()}updateCount(){const t=this.$textarea.value;if("characters"!==this.config.countType){if("words"===this.config.countType){var e,n;if(void 0!==this.config.maxwords)return void(this.count=null!=(e=null==(n=t.match(/\S+/g))?void 0:n.length)?e:0);const i=this.segmenter?Array.from(this.segmenter.segment(t)):[];return void(this.count=i.filter(t=>t.isWordLike).length)}this.count=t.length}else this.count=this.segmenter?Array.from(this.segmenter.segment(t)).length:0}getCountMessage(){const t=this.maxLength-this.count;return this.formatCountMessage(t)}formatCountMessage(t,e){let n="characters",i=t<0?"OverLimit":"UnderLimit";return"words"===(e=null!=e?e:this.config.countType)&&(n="words"),0===t&&(i="AtLimit"),this.i18n.t(`${n}${i}`,{count:0===t?void 0:Math.abs(t)})}isOverThreshold(){if(!this.config.threshold)return!0;const t=this.count;return this.maxLength*this.config.threshold/100<=t}}T.moduleName="govuk-character-count",T.defaults=Object.freeze({threshold:0,countType:"length",i18n:{charactersUnderLimit:{one:"You have %{count} character remaining",other:"You have %{count} characters remaining"},charactersAtLimit:"You have 0 characters remaining",charactersOverLimit:{one:"You have %{count} character too many",other:"You have %{count} characters too many"},wordsUnderLimit:{one:"You have %{count} word remaining",other:"You have %{count} words remaining"},wordsAtLimit:"You have 0 words remaining",wordsOverLimit:{one:"You have %{count} word too many",other:"You have %{count} words too many"},textareaDescription:{other:""}}}),T.schema=Object.freeze({properties:{i18n:{type:"object"},maxwords:{type:"number"},maxlength:{type:"number"},threshold:{type:"number"},countType:{type:"string"}},anyOf:[{required:["maxwords"],errorMessage:'Either "maxlength" or "maxwords" must be provided'},{required:["maxlength"],errorMessage:'Either "maxlength" or "maxwords" must be provided'}]});
22
22
  /**
23
23
  * Checkboxes component
24
24
  *
25
25
  * @preserve
26
26
  */
27
- class C extends h{constructor(t){super(t),this.$inputs=void 0;const e=this.$root.querySelectorAll('input[type="checkbox"]');if(!e.length)throw new d({component:C,identifier:'Form inputs (`<input type="checkbox">`)'});this.$inputs=e,this.$inputs.forEach(t=>{const e=t.getAttribute("data-aria-controls");if(e){if(!document.getElementById(e))throw new d({component:C,identifier:`Conditional reveal (\`id="${e}"\`)`});t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls")}}),window.addEventListener("pageshow",()=>this.syncAllConditionalReveals()),this.syncAllConditionalReveals(),this.$root.addEventListener("click",t=>this.handleClick(t))}syncAllConditionalReveals(){this.$inputs.forEach(t=>this.syncConditionalRevealWithInputState(t))}syncConditionalRevealWithInputState(t){const e=t.getAttribute("aria-controls");if(!e)return;const n=document.getElementById(e);if(null!=n&&n.classList.contains("govuk-checkboxes__conditional")){const e=t.checked;t.setAttribute("aria-expanded",e.toString()),n.classList.toggle("govuk-checkboxes__conditional--hidden",!e)}}unCheckAllInputsExcept(t){document.querySelectorAll(`input[type="checkbox"][name="${t.name}"]`).forEach(e=>{t.form===e.form&&e!==t&&(e.checked=!1,this.syncConditionalRevealWithInputState(e))})}unCheckExclusiveInputs(t){document.querySelectorAll(`input[data-behaviour="exclusive"][type="checkbox"][name="${t.name}"]`).forEach(e=>{t.form===e.form&&(e.checked=!1,this.syncConditionalRevealWithInputState(e))})}handleClick(t){const e=t.target;if(!(e instanceof HTMLInputElement)||"checkbox"!==e.type)return;if(e.getAttribute("aria-controls")&&this.syncConditionalRevealWithInputState(e),!e.checked)return;"exclusive"===e.getAttribute("data-behaviour")?this.unCheckAllInputsExcept(e):this.unCheckExclusiveInputs(e)}}C.moduleName="govuk-checkboxes";
27
+ class k extends p{constructor(t){super(t),this.$inputs=void 0;const e=this.$root.querySelectorAll('input[type="checkbox"]');if(!e.length)throw new d({component:k,identifier:'Form inputs (`<input type="checkbox">`)'});this.$inputs=e,this.$inputs.forEach(t=>{const e=t.getAttribute("data-aria-controls");if(e){if(!document.getElementById(e))throw new d({component:k,identifier:`Conditional reveal (\`id="${e}"\`)`});t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls")}}),window.addEventListener("pageshow",()=>this.syncAllConditionalReveals()),this.syncAllConditionalReveals(),this.$root.addEventListener("click",t=>this.handleClick(t))}syncAllConditionalReveals(){this.$inputs.forEach(t=>this.syncConditionalRevealWithInputState(t))}syncConditionalRevealWithInputState(t){const e=t.getAttribute("aria-controls");if(!e)return;const n=document.getElementById(e);if(null!=n&&n.classList.contains("govuk-checkboxes__conditional")){const e=t.checked;t.setAttribute("aria-expanded",e.toString()),n.classList.toggle("govuk-checkboxes__conditional--hidden",!e)}}unCheckAllInputsExcept(t){document.querySelectorAll(`input[type="checkbox"][name="${t.name}"]`).forEach(e=>{t.form===e.form&&e!==t&&(e.checked=!1,this.syncConditionalRevealWithInputState(e))})}unCheckExclusiveInputs(t){document.querySelectorAll(`input[data-behaviour="exclusive"][type="checkbox"][name="${t.name}"]`).forEach(e=>{t.form===e.form&&(e.checked=!1,this.syncConditionalRevealWithInputState(e))})}handleClick(t){const e=t.target;if(!(e instanceof HTMLInputElement)||"checkbox"!==e.type)return;if(e.getAttribute("aria-controls")&&this.syncConditionalRevealWithInputState(e),!e.checked)return;"exclusive"===e.getAttribute("data-behaviour")?this.unCheckAllInputsExcept(e):this.unCheckExclusiveInputs(e)}}k.moduleName="govuk-checkboxes";
28
28
  /**
29
29
  * Error summary component
30
30
  *
@@ -34,24 +34,24 @@ class C extends h{constructor(t){super(t),this.$inputs=void 0;const e=this.$root
34
34
  * @preserve
35
35
  * @augments ConfigurableComponent<ErrorSummaryConfig>
36
36
  */
37
- class T extends m{constructor(t,e={}){super(t,e),this.config.disableAutoFocus||function(t,e={}){var n;const i=t.getAttribute("tabindex");function s(){var n;null==(n=e.onBlur)||n.call(t),i||t.removeAttribute("tabindex")}i||t.setAttribute("tabindex","-1"),t.addEventListener("focus",function(){t.addEventListener("blur",s,{once:!0})},{once:!0}),null==(n=e.onBeforeFocus)||n.call(t),t.focus()}(this.$root),this.$root.addEventListener("click",t=>this.handleClick(t))}handleClick(t){const e=t.target;e&&this.focusTarget(e)&&t.preventDefault()}focusTarget(t){if(!(t instanceof HTMLAnchorElement))return!1;const e=t.hash.replace("#","");if(!e)return!1;const n=document.getElementById(e);if(!n)return!1;const i=this.getAssociatedLegendOrLabel(n);return!!i&&(i.scrollIntoView(),n.focus({preventScroll:!0}),!0)}getAssociatedLegendOrLabel(t){var e;const n=t.closest("fieldset");if(n){const e=n.getElementsByTagName("legend");if(e.length){const n=e[0];if(t instanceof HTMLInputElement&&("checkbox"===t.type||"radio"===t.type))return n;const i=n.getBoundingClientRect().top,s=t.getBoundingClientRect();if(s.height&&window.innerHeight){if(s.top+s.height-i<window.innerHeight/2)return n}}}return null!=(e=document.querySelector(`label[for='${t.getAttribute("id")}']`))?e:t.closest("label")}}T.moduleName="govuk-error-summary",T.defaults=Object.freeze({disableAutoFocus:!1}),T.schema=Object.freeze({properties:{disableAutoFocus:{type:"boolean"}}});
37
+ class x extends g{constructor(t,e={}){super(t,e),this.config.disableAutoFocus||function(t,e={}){var n;const i=t.getAttribute("tabindex");function s(){var n;null==(n=e.onBlur)||n.call(t),i||t.removeAttribute("tabindex")}i||t.setAttribute("tabindex","-1"),t.addEventListener("focus",function(){t.addEventListener("blur",s,{once:!0})},{once:!0}),null==(n=e.onBeforeFocus)||n.call(t),t.focus()}(this.$root),this.$root.addEventListener("click",t=>this.handleClick(t))}handleClick(t){const e=t.target;e&&this.focusTarget(e)&&t.preventDefault()}focusTarget(t){if(!(t instanceof HTMLAnchorElement))return!1;const e=t.hash.replace("#","");if(!e)return!1;const n=document.getElementById(e);if(!n)return!1;const i=this.getAssociatedLegendOrLabel(n);return!!i&&(i.scrollIntoView(),n.focus({preventScroll:!0}),!0)}getAssociatedLegendOrLabel(t){var e;const n=t.closest("fieldset");if(n){const e=n.getElementsByTagName("legend");if(e.length){const n=e[0];if(t instanceof HTMLInputElement&&("checkbox"===t.type||"radio"===t.type))return n;const i=n.getBoundingClientRect().top,s=t.getBoundingClientRect();if(s.height&&window.innerHeight){if(s.top+s.height-i<window.innerHeight/2)return n}}}return null!=(e=document.querySelector(`label[for='${t.getAttribute("id")}']`))?e:t.closest("label")}}x.moduleName="govuk-error-summary",x.defaults=Object.freeze({disableAutoFocus:!1}),x.schema=Object.freeze({properties:{disableAutoFocus:{type:"boolean"}}});
38
38
  /**
39
39
  * File upload component
40
40
  *
41
41
  * @preserve
42
42
  * @augments ConfigurableComponent<FileUploadConfig>
43
43
  */
44
- class L extends m{constructor(t,e={}){super(t,e),this.$input=void 0,this.$button=void 0,this.$status=void 0,this.$label=void 0,this.i18n=void 0,this.id=void 0,this.$announcements=void 0,this.enteredAnotherElement=void 0;const n=this.$root.querySelector('input[type="file"]');if(null===n)throw new d({component:L,identifier:'File inputs (`<input type="file">`)'});if(this.$input=n,!this.$input.id)throw new d({component:L,identifier:'File input (`<input type="file">`) attribute (`id`)'});this.id=this.$input.id,this.i18n=new y(this.config.i18n,{locale:$(this.$root,"lang")});const i=this.findLabel();i.id||(i.id=`${this.id}-label`),this.$label=i,this.$input.id=`${this.id}-input`,this.$input.setAttribute("hidden","hidden"),this.$status=this.createStatus(),this.$button=this.createButton(),this.$root.insertAdjacentElement("afterbegin",this.$button),this.$input.addEventListener("change",this.onChange.bind(this)),this.updateDisabledState(),this.observeDisabledState(),this.$announcements=document.createElement("span"),this.$announcements.classList.add("govuk-file-upload-announcements"),this.$announcements.classList.add("govuk-visually-hidden"),this.$announcements.setAttribute("aria-live","assertive"),this.$root.insertAdjacentElement("afterend",this.$announcements),this.bindDraggingEvents()}createStatus(){const t=document.createElement("span");return t.className="govuk-body govuk-file-upload-button__status",t.setAttribute("aria-live","polite"),t.innerText=this.i18n.t("noFileChosen"),t}createButton(){const t=document.createElement("button");t.classList.add("govuk-file-upload-button"),t.type="button",t.id=this.id,t.classList.add("govuk-file-upload-button--empty");const e=this.$input.getAttribute("aria-describedby");e&&t.setAttribute("aria-describedby",e),t.appendChild(this.$status);const n=document.createElement("span");n.className="govuk-visually-hidden",n.innerText=", ",n.id=`${this.id}-comma`,t.appendChild(n);const i=document.createElement("span");i.className="govuk-file-upload-button__pseudo-button-container";const s=document.createElement("span");s.className="govuk-button govuk-button--secondary govuk-file-upload-button__pseudo-button",s.innerText=this.i18n.t("chooseFilesButton"),i.appendChild(s),i.insertAdjacentText("beforeend"," ");const o=document.createElement("span");return o.className="govuk-body govuk-file-upload-button__instruction",o.innerText=this.i18n.t("dropInstruction"),i.appendChild(o),t.appendChild(i),t.setAttribute("aria-labelledby",`${this.$label.id} ${n.id} ${t.id}`),t.addEventListener("click",this.onClick.bind(this)),t.addEventListener("dragover",t=>{t.preventDefault()}),t}bindDraggingEvents(){this.$button.addEventListener("drop",this.onDrop.bind(this)),document.addEventListener("dragenter",this.updateDropzoneVisibility.bind(this)),document.addEventListener("dragenter",()=>{this.enteredAnotherElement=!0}),document.addEventListener("dragleave",()=>{this.enteredAnotherElement||this.$button.disabled||(this.hideDraggingState(),this.$announcements.innerText=this.i18n.t("leftDropZone")),this.enteredAnotherElement=!1})}updateDropzoneVisibility(t){this.$button.disabled||t.target instanceof Node&&(this.$root.contains(t.target)?t.dataTransfer&&this.canDrop(t.dataTransfer)&&(this.$button.classList.contains("govuk-file-upload-button--dragging")||(this.showDraggingState(),this.$announcements.innerText=this.i18n.t("enteredDropZone"))):this.$button.classList.contains("govuk-file-upload-button--dragging")&&(this.hideDraggingState(),this.$announcements.innerText=this.i18n.t("leftDropZone")))}showDraggingState(){this.$button.classList.add("govuk-file-upload-button--dragging")}hideDraggingState(){this.$button.classList.remove("govuk-file-upload-button--dragging")}onDrop(t){t.preventDefault(),t.dataTransfer&&this.canFillInput(t.dataTransfer)&&(this.$input.files=t.dataTransfer.files,this.$input.dispatchEvent(new CustomEvent("change")),this.hideDraggingState())}canFillInput(t){return this.matchesInputCapacity(t.files.length)}canDrop(t){return t.items.length?this.matchesInputCapacity(function(t){let e=0;for(let n=0;n<t.length;n++)"file"===t[n].kind&&e++;return e}
44
+ class L extends g{constructor(t,e={}){super(t,e),this.$input=void 0,this.$button=void 0,this.$status=void 0,this.$label=void 0,this.i18n=void 0,this.id=void 0,this.$announcements=void 0,this.enteredAnotherElement=void 0;const n=this.$root.querySelector('input[type="file"]');if(null===n)throw new d({component:L,identifier:'File inputs (`<input type="file">`)'});if(this.$input=n,!this.$input.id)throw new d({component:L,identifier:'File input (`<input type="file">`) attribute (`id`)'});this.id=this.$input.id,this.i18n=new $(this.config.i18n,{locale:C(this.$root,"lang")});const i=this.findLabel();i.id||(i.id=`${this.id}-label`),this.$label=i,this.$input.id=`${this.id}-input`,this.$input.setAttribute("hidden","hidden"),this.$status=this.createStatus(),this.$button=this.createButton(),this.$root.insertAdjacentElement("afterbegin",this.$button),this.$input.addEventListener("change",this.onChange.bind(this)),this.updateDisabledState(),this.observeDisabledState(),this.$announcements=w("span",{class:"govuk-file-upload-announcements govuk-visually-hidden","aria-live":"assertive"}),this.$root.insertAdjacentElement("afterend",this.$announcements),this.bindDraggingEvents()}createStatus(){const t=w("span",{class:"govuk-body govuk-file-upload-button__status","aria-live":"polite"});return t.innerText=this.i18n.t("noFileChosen"),t}createButton(){const t=w("button",{class:"govuk-file-upload-button govuk-file-upload-button--empty",type:"button",id:this.id}),e=this.$input.getAttribute("aria-describedby");e&&t.setAttribute("aria-describedby",e),t.appendChild(this.$status);const n=w("span",{class:"govuk-visually-hidden",id:`${this.id}-comma`},[", "]);t.appendChild(n);const i=w("span",{class:"govuk-file-upload-button__pseudo-button-container"}),s=w("span",{class:"govuk-button govuk-button--secondary govuk-file-upload-button__pseudo-button"},[this.i18n.t("chooseFilesButton")]);i.appendChild(s),i.insertAdjacentText("beforeend"," ");const o=w("span",{class:"govuk-body govuk-file-upload-button__instruction"},[this.i18n.t("dropInstruction")]);return i.appendChild(o),t.appendChild(i),t.setAttribute("aria-labelledby",`${this.$label.id} ${n.id} ${t.id}`),t.addEventListener("click",this.onClick.bind(this)),t.addEventListener("dragover",t=>{t.preventDefault()}),t}bindDraggingEvents(){this.$button.addEventListener("drop",this.onDrop.bind(this)),document.addEventListener("dragenter",this.updateDropzoneVisibility.bind(this)),document.addEventListener("dragenter",()=>{this.enteredAnotherElement=!0}),document.addEventListener("dragleave",()=>{this.enteredAnotherElement||this.$button.disabled||(this.hideDraggingState(),this.$announcements.innerText=this.i18n.t("leftDropZone")),this.enteredAnotherElement=!1})}updateDropzoneVisibility(t){this.$button.disabled||t.target instanceof Node&&(this.$root.contains(t.target)?t.dataTransfer&&this.canDrop(t.dataTransfer)&&(this.$button.classList.contains("govuk-file-upload-button--dragging")||(this.showDraggingState(),this.$announcements.innerText=this.i18n.t("enteredDropZone"))):this.$button.classList.contains("govuk-file-upload-button--dragging")&&(this.hideDraggingState(),this.$announcements.innerText=this.i18n.t("leftDropZone")))}showDraggingState(){this.$button.classList.add("govuk-file-upload-button--dragging")}hideDraggingState(){this.$button.classList.remove("govuk-file-upload-button--dragging")}onDrop(t){t.preventDefault(),t.dataTransfer&&this.canFillInput(t.dataTransfer)&&(this.$input.files=t.dataTransfer.files,this.$input.dispatchEvent(new CustomEvent("change")),this.hideDraggingState())}canFillInput(t){return this.matchesInputCapacity(t.files.length)}canDrop(t){return t.items.length?this.matchesInputCapacity(function(t){let e=0;for(let n=0;n<t.length;n++)"file"===t[n].kind&&e++;return e}
45
45
  /**
46
46
  * Password input component
47
47
  *
48
48
  * @preserve
49
49
  * @augments ConfigurableComponent<PasswordInputConfig>
50
- */(t.items)):!t.types.length||t.types.includes("Files")}matchesInputCapacity(t){return this.$input.multiple?t>0:1===t}onChange(){const t=this.$input.files.length;0===t?(this.$status.innerText=this.i18n.t("noFileChosen"),this.$button.classList.add("govuk-file-upload-button--empty")):(this.$status.innerText=1===t?this.$input.files[0].name:this.i18n.t("multipleFilesChosen",{count:t}),this.$button.classList.remove("govuk-file-upload-button--empty"))}findLabel(){const t=document.querySelector(`label[for="${this.$input.id}"]`);if(!t)throw new d({component:L,identifier:`Field label (\`<label for=${this.$input.id}>\`)`});return t}onClick(){this.$input.click()}observeDisabledState(){new MutationObserver(t=>{for(const e of t)"attributes"===e.type&&"disabled"===e.attributeName&&this.updateDisabledState()}).observe(this.$input,{attributes:!0})}updateDisabledState(){this.$button.disabled=this.$input.disabled,this.$root.classList.toggle("govuk-file-upload-wrapper--disabled",this.$button.disabled)}}L.moduleName="govuk-file-upload",L.defaults=Object.freeze({i18n:{chooseFilesButton:"Choose file",dropInstruction:"or drop file",noFileChosen:"No file chosen",multipleFilesChosen:{one:"%{count} file chosen",other:"%{count} files chosen"},enteredDropZone:"Entered drop zone",leftDropZone:"Left drop zone"}}),L.schema=Object.freeze({properties:{i18n:{type:"object"}}});class k extends m{constructor(t,e={}){super(t,e),this.i18n=void 0,this.$input=void 0,this.$showHideButton=void 0,this.$screenReaderStatusMessage=void 0;const n=this.$root.querySelector(".govuk-js-password-input-input");if(!(n instanceof HTMLInputElement))throw new d({component:k,element:n,expectedType:"HTMLInputElement",identifier:"Form field (`.govuk-js-password-input-input`)"});if("password"!==n.type)throw new d("Password input: Form field (`.govuk-js-password-input-input`) must be of type `password`.");const i=this.$root.querySelector(".govuk-js-password-input-toggle");if(!(i instanceof HTMLButtonElement))throw new d({component:k,element:i,expectedType:"HTMLButtonElement",identifier:"Button (`.govuk-js-password-input-toggle`)"});if("button"!==i.type)throw new d("Password input: Button (`.govuk-js-password-input-toggle`) must be of type `button`.");this.$input=n,this.$showHideButton=i,this.i18n=new y(this.config.i18n,{locale:$(this.$root,"lang")}),this.$showHideButton.removeAttribute("hidden");const s=document.createElement("div");s.className="govuk-password-input__sr-status govuk-visually-hidden",s.setAttribute("aria-live","polite"),this.$screenReaderStatusMessage=s,this.$input.insertAdjacentElement("afterend",s),this.$showHideButton.addEventListener("click",this.toggle.bind(this)),this.$input.form&&this.$input.form.addEventListener("submit",()=>this.hide()),window.addEventListener("pageshow",t=>{t.persisted&&"password"!==this.$input.type&&this.hide()}),this.hide()}toggle(t){t.preventDefault(),"password"!==this.$input.type?this.hide():this.show()}show(){this.setType("text")}hide(){this.setType("password")}setType(t){if(t===this.$input.type)return;this.$input.setAttribute("type",t);const e="password"===t,n=e?"show":"hide",i=e?"passwordHidden":"passwordShown";this.$showHideButton.innerText=this.i18n.t(`${n}Password`),this.$showHideButton.setAttribute("aria-label",this.i18n.t(`${n}PasswordAriaLabel`)),this.$screenReaderStatusMessage.innerText=this.i18n.t(`${i}Announcement`)}}k.moduleName="govuk-password-input",k.defaults=Object.freeze({i18n:{showPassword:"Show",hidePassword:"Hide",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password",passwordShownAnnouncement:"Your password is visible",passwordHiddenAnnouncement:"Your password is hidden"}}),k.schema=Object.freeze({properties:{i18n:{type:"object"}}});
50
+ */(t.items)):!t.types.length||t.types.includes("Files")}matchesInputCapacity(t){return this.$input.multiple?t>0:1===t}onChange(){const t=this.$input.files.length;0===t?(this.$status.innerText=this.i18n.t("noFileChosen"),this.$button.classList.add("govuk-file-upload-button--empty")):(this.$status.innerText=1===t?this.$input.files[0].name:this.i18n.t("multipleFilesChosen",{count:t}),this.$button.classList.remove("govuk-file-upload-button--empty"))}findLabel(){const t=document.querySelector(`label[for="${this.$input.id}"]`);if(!t)throw new d({component:L,identifier:`Field label (\`<label for=${this.$input.id}>\`)`});return t}onClick(){this.$input.click()}observeDisabledState(){new MutationObserver(t=>{for(const e of t)"attributes"===e.type&&"disabled"===e.attributeName&&this.updateDisabledState()}).observe(this.$input,{attributes:!0})}updateDisabledState(){this.$button.disabled=this.$input.disabled,this.$root.classList.toggle("govuk-file-upload-wrapper--disabled",this.$button.disabled)}}L.moduleName="govuk-file-upload",L.defaults=Object.freeze({i18n:{chooseFilesButton:"Choose file",dropInstruction:"or drop file",noFileChosen:"No file chosen",multipleFilesChosen:{one:"%{count} file chosen",other:"%{count} files chosen"},enteredDropZone:"Entered drop zone",leftDropZone:"Left drop zone"}}),L.schema=Object.freeze({properties:{i18n:{type:"object"}}});class S extends g{constructor(t,e={}){super(t,e),this.i18n=void 0,this.$input=void 0,this.$showHideButton=void 0,this.$screenReaderStatusMessage=void 0;const n=this.$root.querySelector(".govuk-js-password-input-input");if(!(n instanceof HTMLInputElement))throw new d({component:S,element:n,expectedType:"HTMLInputElement",identifier:"Form field (`.govuk-js-password-input-input`)"});if("password"!==n.type)throw new d("Password input: Form field (`.govuk-js-password-input-input`) must be of type `password`.");const i=this.$root.querySelector(".govuk-js-password-input-toggle");if(!(i instanceof HTMLButtonElement))throw new d({component:S,element:i,expectedType:"HTMLButtonElement",identifier:"Button (`.govuk-js-password-input-toggle`)"});if("button"!==i.type)throw new d("Password input: Button (`.govuk-js-password-input-toggle`) must be of type `button`.");this.$input=n,this.$showHideButton=i,this.i18n=new $(this.config.i18n,{locale:C(this.$root,"lang")}),this.$showHideButton.removeAttribute("hidden");const s=w("div",{class:"govuk-password-input__sr-status govuk-visually-hidden","aria-live":"polite"});this.$screenReaderStatusMessage=s,this.$input.insertAdjacentElement("afterend",s),this.$showHideButton.addEventListener("click",this.toggle.bind(this)),this.$input.form&&this.$input.form.addEventListener("submit",()=>this.hide()),window.addEventListener("pageshow",t=>{t.persisted&&"password"!==this.$input.type&&this.hide()}),this.hide()}toggle(t){t.preventDefault(),"password"!==this.$input.type?this.hide():this.show()}show(){this.setType("text")}hide(){this.setType("password")}setType(t){if(t===this.$input.type)return;this.$input.setAttribute("type",t);const e="password"===t,n=e?"show":"hide",i=e?"passwordHidden":"passwordShown";this.$showHideButton.innerText=this.i18n.t(`${n}Password`),this.$showHideButton.setAttribute("aria-label",this.i18n.t(`${n}PasswordAriaLabel`)),this.$screenReaderStatusMessage.innerText=this.i18n.t(`${i}Announcement`)}}S.moduleName="govuk-password-input",S.defaults=Object.freeze({i18n:{showPassword:"Show",hidePassword:"Hide",showPasswordAriaLabel:"Show password",hidePasswordAriaLabel:"Hide password",passwordShownAnnouncement:"Your password is visible",passwordHiddenAnnouncement:"Your password is hidden"}}),S.schema=Object.freeze({properties:{i18n:{type:"object"}}});
51
51
  /**
52
52
  * Radios component
53
53
  *
54
54
  * @preserve
55
55
  */
56
- class x extends h{constructor(t){super(t),this.$inputs=void 0;const e=this.$root.querySelectorAll('input[type="radio"]');if(!e.length)throw new d({component:x,identifier:'Form inputs (`<input type="radio">`)'});this.$inputs=e,this.$inputs.forEach(t=>{const e=t.getAttribute("data-aria-controls");if(e){if(!document.getElementById(e))throw new d({component:x,identifier:`Conditional reveal (\`id="${e}"\`)`});t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls")}}),window.addEventListener("pageshow",()=>this.syncAllConditionalReveals()),this.syncAllConditionalReveals(),this.$root.addEventListener("click",t=>this.handleClick(t))}syncAllConditionalReveals(){this.$inputs.forEach(t=>this.syncConditionalRevealWithInputState(t))}syncConditionalRevealWithInputState(t){const e=t.getAttribute("aria-controls");if(!e)return;const n=document.getElementById(e);if(null!=n&&n.classList.contains("govuk-radios__conditional")){const e=t.checked;t.setAttribute("aria-expanded",e.toString()),n.classList.toggle("govuk-radios__conditional--hidden",!e)}}handleClick(t){const e=t.target;if(!(e instanceof HTMLInputElement)||"radio"!==e.type)return;const n=document.querySelectorAll('input[type="radio"][aria-controls]'),i=e.form,s=e.name;n.forEach(t=>{const e=t.form===i;t.name===s&&e&&this.syncConditionalRevealWithInputState(t)})}}x.moduleName="govuk-radios";const A={brand:"govuk"},S="[type='button']:has(+ input[type='file'])",I={moduleName:"govuk-attachment",defaults:{i18n:{...L.defaults.i18n,uploadSucceeded:"Uploaded successfully",uploadFailed:"Upload failed — try again",retryButton:"Try again",fileRemoved:"%{filename} removed",removeButton:"Remove %{filename}",removeButtonContent:"Remove"}},schema:{properties:{i18n:{type:"object"}}}};function D(t){return v(I.defaults,f(I,t?.dataset??{}))}class M extends n{async start(t){this.dispatch("start");try{const e=await new Promise((t,e)=>{this.directUpload.create((n,i)=>n?e(n):t(i))});t.value=e.signed_id}catch(t){throw this.dispatch("error",{error:t}),t}finally{this.dispatch("end")}}}let B=0;function F(t,e,n){const i=document.createElement("TEMPLATE"),s=++B;i.innerHTML=`\n <figure class="${A.brand}-attachment" data-controller="govuk-attachment" aria-labelledby="attachment-${s}-filename">\n <img alt="" class="preview" src="">\n <figcaption class="caption" aria-atomic="true" aria-live="polite">\n <span id="attachment-${s}-filename" class="filename"></span>\n <span class="size"></span>\n <span class="status"></span>\n </figcaption>\n <div class="actions">\n <select id="attachment-${s}-input" name="${t.name}" aria-labelledby="attachment-${s}-filename">\n <option selected="selected" value=""></option>\n <option value=""></option>\n </select>\n <button type="button" class="${A.brand}-button ${A.brand}-button--secondary ${A.brand}-attachment__remove" data-action="govuk-attachment#destroy" data-module="govuk-button"></button>\n </div>\n </figure>\n `;const o=i.content.firstElementChild;o.querySelector(".filename").textContent=e.name,o.querySelector(".size").textContent=function(t){if(1===t)return"1 Byte";if(t<1024)return`${t} Bytes`;const e=Math.min(Math.floor(Math.log2(t)/10),P.length-1);return`${Number((t/1024**e).toPrecision(3))} ${P[e]}`}(e.size);const[r,a]=o.querySelectorAll("option");r.textContent=e.name,a.textContent=n.t("removeButton",{filename:e.name});const l=o.querySelector("button");return l.textContent=n.t("removeButtonContent"),l.setAttribute("aria-label",n.t("removeButton",{filename:e.name})),o.file=e,o}const P=["Bytes","KB","MB","GB","TB","PB"];class R extends t{static targets=["preview","destroy"];static values={mimeTypes:Array};connect(){this.counter=0,this.initialPreviewContent=null,this.onUploadFlag=!1}onUpload(t){this.onUploadFlag=!0,this.hasDestroyTarget&&(this.destroyTarget.value=!1),this.previewTarget.removeAttribute("hidden"),this.hasPreviewTarget&&(t.currentTarget.files.length>0?this.showPreview(t.currentTarget.files[0]):this.setPreviewContent(this.initialPreviewContent))}setDestroy(t){t.preventDefault(),this.initialPreviewContent&&this.onUploadFlag?(this.onUploadFlag=!1,this.setPreviewContent(this.initialPreviewContent)):(this.hasDestroyTarget&&(this.destroyTarget.value=!0),this.hasPreviewTarget&&(this.previewTarget.setAttribute("hidden",""),this.setPreviewContent("")),this.previousInput&&this.previousInput.toggleAttribute("disabled",!0)),this.fileInput.value=""}setPreviewContent(t){this.filenameTag&&(this.filenameTag.innerText=text)}drop(t){t.preventDefault();const e=this.fileForEvent(t,this.mimeTypesValue);if(e){const t=new DataTransfer;t.items.add(e),this.fileInput.files=t.files,this.fileInput.dispatchEvent(new Event("change"))}this.counter=0,this.element.classList.remove("droppable")}dragover(t){t.preventDefault()}dragenter(t){t.preventDefault(),0===this.counter&&this.element.classList.add("droppable"),this.counter++}dragleave(t){t.preventDefault(),this.counter--,0===this.counter&&this.element.classList.remove("droppable")}get fileInput(){return this.element.querySelector("input[type='file']")}get previousInput(){return this.element.querySelector(`input[type='hidden'][name='${this.fileInput.name}']`)}get filenameTag(){return this.hasPreviewTarget?this.previewTarget.querySelector("p.preview-filename"):null}showPreview(t){const e=new FileReader;e.onload=e=>{this.filenameTag&&(this.filenameTag.innerText=t.name)},e.readAsDataURL(t)}fileForEvent(t,e){const n=t=>e.indexOf(t.type)>-1;let i;if(t.dataTransfer.items){const e=[...t.dataTransfer.items].find(n);e&&(i=e.getAsFile())}else i=[...t.dataTransfer.files].find(n);return i}}const O=[{identifier:"govuk-attachment",controllerConstructor:class extends t{connect(){this.config=D(this.element.closest(`.${A.brand}-file-upload-wrapper`)),this.i18n=new y(this.config.i18n,{locale:$(this.element,"lang")}),this.select.addEventListener("change",this.change),this.previewPendingFile(),this.uploadPendingFile()}disconnect(){this.select?.removeEventListener("change",this.change)}previewPendingFile(){const t=this.element.file;if(!t)return;if(!t.type.startsWith("image/"))return void this.imageTag?.remove();const e=new FileReader;e.onload=this.onPreviewReady,e.readAsDataURL(t)}uploadPendingFile(){const t=this.element.file;t&&this.input?.dataset.directUploadUrl&&(delete this.element.file,this.input.dispatchEvent(new CustomEvent("govuk:upload",{detail:{file:t}})),this.performUpload(t))}async performUpload(t){this.uploader=new M(this.input,t),this.element.dataset.state="uploading",this.statusText="",this.retryButton?.remove();const e=function(t){const e=document.createElement("PROGRESS");e.className=`${A.brand}-attachment-progress`,t&&e.setAttribute("aria-labelledby",t);return e.value=0,e.max=100,e}(this.filenameTag.id);this.captionTag.appendChild(e),this.input.addEventListener("direct-upload:progress",this.progress);try{await this.uploader.start(this.inputOption),this.element.dataset.state="upload-successful",this.statusText=this.i18n.t("uploadSucceeded")}catch(e){console.warn(e),this.element.dataset.state="upload-failed",this.statusText=this.i18n.t("uploadFailed"),this.actionsTag?.prepend(function(t,e){const n=document.createElement("BUTTON");return n.type="button",n.className=`${A.brand}-button ${A.brand}-button--secondary ${A.brand}-attachment__retry`,n.textContent=e.t("retryButton"),n.setAttribute("aria-label",`${e.t("retryButton")} ${t}`),n.dataset.action="govuk-attachment#retry",n.dataset.module="govuk-button",n}(t.name,this.i18n))}finally{this.input.removeEventListener("direct-upload:progress",this.progress),e.remove()}}onPreviewReady=t=>{this.imageTag.src=t.target.result};change=()=>{""===this.select.value&&this.destroy()};retry(){this.performUpload(this.directUpload.file),this.removeButton?.focus()}progress=({detail:t})=>{t.id===this.id&&this.progressTag&&(this.progressTag.value=t.progress)};destroy(){const t=this.uploadButton,e=new CustomEvent("govuk:remove",{detail:{name:this.element.querySelector(".filename")?.textContent,file:this.element.file},cancelable:!0});this.input.dispatchEvent(e)&&(this.element.remove(),t?.focus())}get id(){return this.directUpload?.id??this.select.id}get directUpload(){return this.uploader?.directUpload}get input(){return this.element.closest(`.${A.brand}-file-upload-wrapper`)?.querySelector("input[type=file]")}get uploadButton(){return this.element.closest(`.${A.brand}-file-upload-wrapper`)?.querySelector(S)}set statusText(t){const e=this.element.querySelector("figcaption .status");e&&(e.textContent=t)}get captionTag(){return this.element.querySelector("figcaption")}get filenameTag(){return this.element.querySelector("figcaption .filename")}get actionsTag(){return this.element.querySelector(".actions")}get select(){return this.element.querySelector("select")}get inputOption(){return this.element.querySelector("option")}get imageTag(){return this.element.querySelector("img")}get progressTag(){return this.element.querySelector("progress")}get retryButton(){return this.element.querySelector(".actions button[data-action*='retry']")}get removeButton(){return this.element.querySelector(".actions button[data-action*='destroy']")}}},{identifier:"govuk-document-field",controllerConstructor:class extends R{connect(){super.connect(),this.initialPreviewContent=this.filenameTag.text}setPreviewContent(t){this.filenameTag.innerText=t}showPreview(t){const e=new FileReader;e.onload=e=>{this.filenameTag&&(this.filenameTag.innerText=t.name)},e.readAsDataURL(t)}get filenameTag(){return this.previewTarget.querySelector("p.preview-filename")}}},{identifier:"govuk-file-upload",controllerConstructor:class extends t{connect(){if(!this.fileInput)throw new Error(`Missing file input for ${this.element}`);this.config=D(this.element),this.i18n=new y(this.config.i18n,{locale:$(this.element,"lang")}),this.id=this.uploadButton?.id??this.fileInput.id,document.addEventListener("dragenter",this.onDragenter),document.addEventListener("dragleave",this.onDragleave),this.element.addEventListener("dragover",this.onDragover),this.element.addEventListener("drop",this.onDrop),this.enhance(),this.morphObserver=new MutationObserver(this.onMorph),this.morphObserver.observe(this.element,{childList:!0})}disconnect(){this.morphObserver?.disconnect(),this.disabledObserver?.disconnect(),this.uploadButton?.removeEventListener("click",this.onClick),this.element.removeEventListener("dragover",this.onDragover),this.element.removeEventListener("drop",this.onDrop),this.unbindInput(),document.removeEventListener("dragenter",this.onDragenter),document.removeEventListener("dragleave",this.onDragleave),this.announcements?.remove()}enhance(){const t=this.fileInput;let e=this.uploadButton;e||(this.ensureLabelId(),t.id=`${this.id}-input`,t.setAttribute("hidden","hidden"),e=function(t,e,n){const i=A.brand,s=document.createElement("TEMPLATE");s.innerHTML=`\n <button\n class="${i}-file-upload-button ${i}-file-upload-button--empty"\n type="button"\n id="${t}"\n aria-labelledby="${t}-label ${t}-comma ${t}"\n >\n <span class="${i}-body ${i}-file-upload-button__status"\n aria-live="polite">${e.t("noFileChosen")}</span>\n <span class="${i}-visually-hidden" id="${t}-comma">, </span>\n <span class="${i}-file-upload-button__pseudo-button-container">\n <span class="${i}-button\n ${i}-button--secondary\n ${i}-file-upload-button__pseudo-button">${e.t("chooseFilesButton")}</span>\n <span class="${i}-body ${i}-file-upload-button__instruction">${e.t("dropInstruction")}</span>\n </span>\n </button>\n `;const o=s.content.firstElementChild,r=n.getAttribute("aria-describedby");r&&o.setAttribute("aria-describedby",r);return o}(this.id,this.i18n,t),t.insertAdjacentElement("beforebegin",e),e.addEventListener("click",this.onClick)),this.announcements||this.element.appendChild(function(){const t=document.createElement("span");return t.className=`${A.brand}-file-upload-announcements ${A.brand}-visually-hidden`,t.setAttribute("aria-live","assertive"),t}()),this.unbindInput(),t.addEventListener("change",this.onChange),t.addEventListener("govuk:upload",this.onUpload),t.addEventListener("govuk:remove",this.onRemove),this.updateDisabledState(),this.observeDisabledState(),this.updateCount()}unbindInput(){this.fileInput?.removeEventListener("change",this.onChange),this.fileInput?.removeEventListener("govuk:upload",this.onUpload),this.fileInput?.removeEventListener("govuk:remove",this.onRemove)}onMorph=()=>{this.uploadButton||(this.fileInput.value="",this.element.querySelectorAll("figure").forEach(t=>{delete t.file}),this.enhance())};ensureLabelId(){const t=document.querySelector(`label[for="${this.id}"]`);t&&!t.id&&(t.id=`${this.id}-label`)}updateDisabledState(){if(!this.uploadButton)return;const t=this.fileInput.disabled;this.uploadButton.disabled=t,this.element.classList.toggle(`${A.brand}-file-upload-wrapper--disabled`,t)}observeDisabledState(){this.disabledObserver?.disconnect(),this.disabledObserver=new MutationObserver(t=>{for(const e of t)"disabled"===e.attributeName&&this.updateDisabledState()}),this.disabledObserver.observe(this.fileInput,{attributes:!0})}onClick=t=>{this.fileInput.click()};onDragover=t=>{this.fileInput.disabled||t.preventDefault()};onDragenter=t=>{this.updateDropzoneVisibility(t),this.enteredAnotherElement=!0};onDragleave=()=>{this.enteredAnotherElement||this.uploadButton.disabled||(this.hideDraggingState(),this.announce(this.i18n.t("leftDropZone"))),this.enteredAnotherElement=!1};onDrop=t=>{this.fileInput.disabled||(t.preventDefault(),t.dataTransfer&&this.canFillInput(t.dataTransfer)&&(this.fileInput.files=t.dataTransfer.files,this.fileInput.dispatchEvent(new CustomEvent("change")),this.hideDraggingState()))};updateDropzoneVisibility(t){this.uploadButton.disabled||t.target instanceof Node&&(this.element.contains(t.target)?t.dataTransfer&&this.canDrop(t.dataTransfer)&&(this.isDragging||(this.showDraggingState(),this.announce(this.i18n.t("enteredDropZone")))):this.isDragging&&(this.hideDraggingState(),this.announce(this.i18n.t("leftDropZone"))))}showDraggingState(){this.uploadButton.classList.add(`${A.brand}-file-upload-button--dragging`)}hideDraggingState(){this.uploadButton.classList.remove(`${A.brand}-file-upload-button--dragging`)}announce(t){this.announcements&&(this.announcements.textContent=t)}get announcements(){return this.element.querySelector(`.${A.brand}-file-upload-announcements`)}matchesInputCapacity(t){return this.fileInput.multiple?t>0:1===t}canDrop(t){return t.items.length?this.matchesInputCapacity((e=t.items,Array.from(e).filter(t=>"file"===t.kind).length)):!t.types.length||t.types.includes("Files");var e}canFillInput(t){return this.matchesInputCapacity(t.files.length)}onChange=()=>{const t=Array.from(this.fileInput.files),e=Array.from(this.element.querySelectorAll("figure"));e.forEach(e=>{e.file&&!t.includes(e.file)&&e.remove()}),t.forEach(t=>{if(e.some(e=>e.file===t))return;const n=F(this.fileInput,t,this.i18n);this.uploadButton.insertAdjacentElement("beforebegin",n)}),this.updateCount()};onUpload=({detail:{file:t}})=>{this.releaseFile(t),this.updateCount()};releaseFile(t){const e=new DataTransfer;for(const n of this.fileInput.files)n!==t&&e.items.add(n);this.fileInput.files=e.files}onRemove=async t=>{if(await Promise.resolve(),t.defaultPrevented)return;const{name:e,file:n}=t.detail;n&&this.releaseFile(n),this.announce(this.i18n.t("fileRemoved",{filename:e})),this.updateCount()};updateCount(){const t=this.fileCount;0===t?(this.statusTag.innerText=this.i18n.t("noFileChosen"),this.uploadButton.classList.add(`${A.brand}-file-upload-button--empty`)):(this.statusTag.innerText=this.i18n.t("multipleFilesChosen",{count:t}),this.uploadButton.classList.remove(`${A.brand}-file-upload-button--empty`))}get fileInput(){return this.element.querySelector("input[type='file']")}get uploadButton(){return this.element.querySelector(S)}get isDragging(){return this.uploadButton.classList.contains(`${A.brand}-file-upload-button--dragging`)}get statusTag(){return this.element.querySelector("button [aria-live]")}get fileCount(){let t=this.fileInput.files.length;return this.element.querySelectorAll(`select[name='${this.fileInput.name}']`).forEach(e=>{e.closest("figure")?.file||(t+=1)}),this.fileInput.multiple||(t=Math.min(t,1)),t}}},{identifier:"govuk-image-field",controllerConstructor:class extends R{connect(){super.connect(),this.initialPreviewContent=this.imageTag.getAttribute("src")}setPreviewContent(t){this.imageTag.src=t}showPreview(t){const e=new FileReader;e.onload=t=>{this.imageTag.src=t.target.result},e.readAsDataURL(t)}get imageTag(){return this.previewTarget.querySelector("img")}}}];let _={};function q(t=document){if(!s())return void console.log(new l);[[w,_.button],[E,_.characterCount],[C],[T,_.errorSummary],[L,_.fileUpload],[x],[k,_.passwordInput]].forEach(([e,n])=>{const s=`[data-module="${e.moduleName}"]`;[...t instanceof Element&&t.matches(s)?[t]:[],...t.querySelectorAll(s)].forEach(t=>{if(!i(t,e.moduleName))try{"defaults"in e?new e(t,n):new e(t)}catch(t){console.log(t)}})})}function j(t){t.classList.toggle("js-enabled",!0),t.classList.toggle("govuk-frontend-supported","noModule"in HTMLScriptElement.prototype)}function N(t){new MutationObserver(()=>{(function(t){const e="noModule"in HTMLScriptElement.prototype;return t.classList.contains("js-enabled")&&t.classList.contains("govuk-frontend-supported")===e})(t)||(j(t),q())}).observe(t,{attributes:!0,attributeFilter:["class"]}),new MutationObserver(t=>{for(const e of t)for(const t of e.addedNodes)t instanceof Element&&q(t)}).observe(t,{childList:!0,subtree:!0})}function H(t){t&&!t.__govukFormbuilderInit&&(t.__govukFormbuilderInit=!0,j(t),q(),N(t))}let U=!1;function z(t=void 0){U||(U=!0,(t??e.start()).load(O))}function V(t){t.brand&&(A.brand=t.brand),_=t}function Y(t={}){V(t),z(),H(document.body)}let W=!1;var Z={start:function(t=void 0,e={}){V(e),z(t),W||(W=!0,new MutationObserver(()=>H(document.body)).observe(document.documentElement,{childList:!0})),H(document.body)}};export{w as Button,E as CharacterCount,C as Checkboxes,T as ErrorSummary,k as PasswordInput,x as Radios,Z as default,Y as initAll};
56
+ class A extends p{constructor(t){super(t),this.$inputs=void 0;const e=this.$root.querySelectorAll('input[type="radio"]');if(!e.length)throw new d({component:A,identifier:'Form inputs (`<input type="radio">`)'});this.$inputs=e,this.$inputs.forEach(t=>{const e=t.getAttribute("data-aria-controls");if(e){if(!document.getElementById(e))throw new d({component:A,identifier:`Conditional reveal (\`id="${e}"\`)`});t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls")}}),window.addEventListener("pageshow",()=>this.syncAllConditionalReveals()),this.syncAllConditionalReveals(),this.$root.addEventListener("click",t=>this.handleClick(t))}syncAllConditionalReveals(){this.$inputs.forEach(t=>this.syncConditionalRevealWithInputState(t))}syncConditionalRevealWithInputState(t){const e=t.getAttribute("aria-controls");if(!e)return;const n=document.getElementById(e);if(null!=n&&n.classList.contains("govuk-radios__conditional")){const e=t.checked;t.setAttribute("aria-expanded",e.toString()),n.classList.toggle("govuk-radios__conditional--hidden",!e)}}handleClick(t){const e=t.target;if(!(e instanceof HTMLInputElement)||"radio"!==e.type)return;const n=document.querySelectorAll('input[type="radio"][aria-controls]'),i=e.form,s=e.name;n.forEach(t=>{const e=t.form===i;t.name===s&&e&&this.syncConditionalRevealWithInputState(t)})}}A.moduleName="govuk-radios";const I={brand:"govuk"},D="[type='button']:has(+ input[type='file'])",M={moduleName:"govuk-attachment",defaults:{i18n:{...L.defaults.i18n,uploadSucceeded:"Uploaded successfully",uploadFailed:"Upload failed — try again",retryButton:"Try again",fileRemoved:"%{filename} removed",removeButton:"Remove %{filename}",removeButtonContent:"Remove"}},schema:{properties:{i18n:{type:"object"}}}};function B(t){return b(M.defaults,v(M,t?.dataset??{}))}class F extends n{async start(t){this.dispatch("start");try{const e=await new Promise((t,e)=>{this.directUpload.create((n,i)=>n?e(n):t(i))});t.value=e.signed_id}catch(t){throw this.dispatch("error",{error:t}),t}finally{this.dispatch("end")}}}let O=0;function P(t,e,n){const i=document.createElement("TEMPLATE"),s=++O;i.innerHTML=`\n <figure class="${I.brand}-attachment" data-controller="govuk-attachment" aria-labelledby="attachment-${s}-filename">\n <img alt="" class="preview" src="">\n <figcaption class="caption" aria-atomic="true" aria-live="polite">\n <span id="attachment-${s}-filename" class="filename"></span>\n <span class="size"></span>\n <span class="status"></span>\n </figcaption>\n <div class="actions">\n <select id="attachment-${s}-input" name="${t.name}" aria-labelledby="attachment-${s}-filename">\n <option selected="selected" value=""></option>\n <option value=""></option>\n </select>\n <button type="button" class="${I.brand}-button ${I.brand}-button--secondary ${I.brand}-attachment__remove" data-action="govuk-attachment#destroy" data-module="govuk-button"></button>\n </div>\n </figure>\n `;const o=i.content.firstElementChild;o.querySelector(".filename").textContent=e.name,o.querySelector(".size").textContent=function(t){if(1===t)return"1 Byte";if(t<1024)return`${t} Bytes`;const e=Math.min(Math.floor(Math.log2(t)/10),R.length-1);return`${Number((t/1024**e).toPrecision(3))} ${R[e]}`}(e.size);const[r,a]=o.querySelectorAll("option");r.textContent=e.name,a.textContent=n.t("removeButton",{filename:e.name});const l=o.querySelector("button");return l.textContent=n.t("removeButtonContent"),l.setAttribute("aria-label",n.t("removeButton",{filename:e.name})),o.file=e,o}const R=["Bytes","KB","MB","GB","TB","PB"];class _ extends t{static targets=["preview","destroy"];static values={mimeTypes:Array};connect(){this.counter=0,this.initialPreviewContent=null,this.onUploadFlag=!1}onUpload(t){this.onUploadFlag=!0,this.hasDestroyTarget&&(this.destroyTarget.value=!1),this.previewTarget.removeAttribute("hidden"),this.hasPreviewTarget&&(t.currentTarget.files.length>0?this.showPreview(t.currentTarget.files[0]):this.setPreviewContent(this.initialPreviewContent))}setDestroy(t){t.preventDefault(),this.initialPreviewContent&&this.onUploadFlag?(this.onUploadFlag=!1,this.setPreviewContent(this.initialPreviewContent)):(this.hasDestroyTarget&&(this.destroyTarget.value=!0),this.hasPreviewTarget&&(this.previewTarget.setAttribute("hidden",""),this.setPreviewContent("")),this.previousInput&&this.previousInput.toggleAttribute("disabled",!0)),this.fileInput.value=""}setPreviewContent(t){this.filenameTag&&(this.filenameTag.innerText=text)}drop(t){t.preventDefault();const e=this.fileForEvent(t,this.mimeTypesValue);if(e){const t=new DataTransfer;t.items.add(e),this.fileInput.files=t.files,this.fileInput.dispatchEvent(new Event("change"))}this.counter=0,this.element.classList.remove("droppable")}dragover(t){t.preventDefault()}dragenter(t){t.preventDefault(),0===this.counter&&this.element.classList.add("droppable"),this.counter++}dragleave(t){t.preventDefault(),this.counter--,0===this.counter&&this.element.classList.remove("droppable")}get fileInput(){return this.element.querySelector("input[type='file']")}get previousInput(){return this.element.querySelector(`input[type='hidden'][name='${this.fileInput.name}']`)}get filenameTag(){return this.hasPreviewTarget?this.previewTarget.querySelector("p.preview-filename"):null}showPreview(t){const e=new FileReader;e.onload=e=>{this.filenameTag&&(this.filenameTag.innerText=t.name)},e.readAsDataURL(t)}fileForEvent(t,e){const n=t=>e.indexOf(t.type)>-1;let i;if(t.dataTransfer.items){const e=[...t.dataTransfer.items].find(n);e&&(i=e.getAsFile())}else i=[...t.dataTransfer.files].find(n);return i}}const q=[{identifier:"govuk-attachment",controllerConstructor:class extends t{connect(){this.config=B(this.element.closest(`.${I.brand}-file-upload-wrapper`)),this.i18n=new $(this.config.i18n,{locale:C(this.element,"lang")}),this.select.addEventListener("change",this.change),this.previewPendingFile(),this.uploadPendingFile()}disconnect(){this.select?.removeEventListener("change",this.change)}previewPendingFile(){const t=this.element.file;if(!t)return;if(!t.type.startsWith("image/"))return void this.imageTag?.remove();const e=new FileReader;e.onload=this.onPreviewReady,e.readAsDataURL(t)}uploadPendingFile(){const t=this.element.file;t&&this.input?.dataset.directUploadUrl&&(delete this.element.file,this.input.dispatchEvent(new CustomEvent("govuk:upload",{detail:{file:t}})),this.performUpload(t))}async performUpload(t){this.uploader=new F(this.input,t),this.element.dataset.state="uploading",this.statusText="",this.retryButton?.remove();const e=function(t){const e=document.createElement("PROGRESS");e.className=`${I.brand}-attachment-progress`,t&&e.setAttribute("aria-labelledby",t);return e.value=0,e.max=100,e}(this.filenameTag.id);this.captionTag.appendChild(e),this.input.addEventListener("direct-upload:progress",this.progress);try{await this.uploader.start(this.inputOption),this.element.dataset.state="upload-successful",this.statusText=this.i18n.t("uploadSucceeded")}catch(e){console.warn(e),this.element.dataset.state="upload-failed",this.statusText=this.i18n.t("uploadFailed"),this.actionsTag?.prepend(function(t,e){const n=document.createElement("BUTTON");return n.type="button",n.className=`${I.brand}-button ${I.brand}-button--secondary ${I.brand}-attachment__retry`,n.textContent=e.t("retryButton"),n.setAttribute("aria-label",`${e.t("retryButton")} ${t}`),n.dataset.action="govuk-attachment#retry",n.dataset.module="govuk-button",n}(t.name,this.i18n))}finally{this.input.removeEventListener("direct-upload:progress",this.progress),e.remove()}}onPreviewReady=t=>{this.imageTag.src=t.target.result};change=()=>{""===this.select.value&&this.destroy()};retry(){this.performUpload(this.directUpload.file),this.removeButton?.focus()}progress=({detail:t})=>{t.id===this.id&&this.progressTag&&(this.progressTag.value=t.progress)};destroy(){const t=this.uploadButton,e=new CustomEvent("govuk:remove",{detail:{name:this.element.querySelector(".filename")?.textContent,file:this.element.file},cancelable:!0});this.input.dispatchEvent(e)&&(this.element.remove(),t?.focus())}get id(){return this.directUpload?.id??this.select.id}get directUpload(){return this.uploader?.directUpload}get input(){return this.element.closest(`.${I.brand}-file-upload-wrapper`)?.querySelector("input[type=file]")}get uploadButton(){return this.element.closest(`.${I.brand}-file-upload-wrapper`)?.querySelector(D)}set statusText(t){const e=this.element.querySelector("figcaption .status");e&&(e.textContent=t)}get captionTag(){return this.element.querySelector("figcaption")}get filenameTag(){return this.element.querySelector("figcaption .filename")}get actionsTag(){return this.element.querySelector(".actions")}get select(){return this.element.querySelector("select")}get inputOption(){return this.element.querySelector("option")}get imageTag(){return this.element.querySelector("img")}get progressTag(){return this.element.querySelector("progress")}get retryButton(){return this.element.querySelector(".actions button[data-action*='retry']")}get removeButton(){return this.element.querySelector(".actions button[data-action*='destroy']")}}},{identifier:"govuk-document-field",controllerConstructor:class extends _{connect(){super.connect(),this.initialPreviewContent=this.filenameTag.text}setPreviewContent(t){this.filenameTag.innerText=t}showPreview(t){const e=new FileReader;e.onload=e=>{this.filenameTag&&(this.filenameTag.innerText=t.name)},e.readAsDataURL(t)}get filenameTag(){return this.previewTarget.querySelector("p.preview-filename")}}},{identifier:"govuk-file-upload",controllerConstructor:class extends t{connect(){if(!this.fileInput)throw new Error(`Missing file input for ${this.element}`);this.config=B(this.element),this.i18n=new $(this.config.i18n,{locale:C(this.element,"lang")}),this.id=this.uploadButton?.id??this.fileInput.id,document.addEventListener("dragenter",this.onDragenter),document.addEventListener("dragleave",this.onDragleave),this.element.addEventListener("dragover",this.onDragover),this.element.addEventListener("drop",this.onDrop),this.enhance(),this.morphObserver=new MutationObserver(this.onMorph),this.morphObserver.observe(this.element,{childList:!0})}disconnect(){this.morphObserver?.disconnect(),this.disabledObserver?.disconnect(),this.uploadButton?.removeEventListener("click",this.onClick),this.element.removeEventListener("dragover",this.onDragover),this.element.removeEventListener("drop",this.onDrop),this.unbindInput(),document.removeEventListener("dragenter",this.onDragenter),document.removeEventListener("dragleave",this.onDragleave),this.announcements?.remove()}enhance(){const t=this.fileInput;let e=this.uploadButton;e||(this.ensureLabelId(),t.id=`${this.id}-input`,t.setAttribute("hidden","hidden"),e=function(t,e,n){const i=I.brand,s=document.createElement("TEMPLATE");s.innerHTML=`\n <button\n class="${i}-file-upload-button ${i}-file-upload-button--empty"\n type="button"\n id="${t}"\n aria-labelledby="${t}-label ${t}-comma ${t}"\n >\n <span class="${i}-body ${i}-file-upload-button__status"\n aria-live="polite">${e.t("noFileChosen")}</span>\n <span class="${i}-visually-hidden" id="${t}-comma">, </span>\n <span class="${i}-file-upload-button__pseudo-button-container">\n <span class="${i}-button\n ${i}-button--secondary\n ${i}-file-upload-button__pseudo-button">${e.t("chooseFilesButton")}</span>\n <span class="${i}-body ${i}-file-upload-button__instruction">${e.t("dropInstruction")}</span>\n </span>\n </button>\n `;const o=s.content.firstElementChild,r=n.getAttribute("aria-describedby");r&&o.setAttribute("aria-describedby",r);return o}(this.id,this.i18n,t),t.insertAdjacentElement("beforebegin",e),e.addEventListener("click",this.onClick)),this.announcements||this.element.appendChild(function(){const t=document.createElement("span");return t.className=`${I.brand}-file-upload-announcements ${I.brand}-visually-hidden`,t.setAttribute("aria-live","assertive"),t}()),this.unbindInput(),t.addEventListener("change",this.onChange),t.addEventListener("govuk:upload",this.onUpload),t.addEventListener("govuk:remove",this.onRemove),this.updateDisabledState(),this.observeDisabledState(),this.updateCount()}unbindInput(){this.fileInput?.removeEventListener("change",this.onChange),this.fileInput?.removeEventListener("govuk:upload",this.onUpload),this.fileInput?.removeEventListener("govuk:remove",this.onRemove)}onMorph=()=>{this.uploadButton||(this.fileInput.value="",this.element.querySelectorAll("figure").forEach(t=>{delete t.file}),this.enhance())};ensureLabelId(){const t=document.querySelector(`label[for="${this.id}"]`);t&&!t.id&&(t.id=`${this.id}-label`)}updateDisabledState(){if(!this.uploadButton)return;const t=this.fileInput.disabled;this.uploadButton.disabled=t,this.element.classList.toggle(`${I.brand}-file-upload-wrapper--disabled`,t)}observeDisabledState(){this.disabledObserver?.disconnect(),this.disabledObserver=new MutationObserver(t=>{for(const e of t)"disabled"===e.attributeName&&this.updateDisabledState()}),this.disabledObserver.observe(this.fileInput,{attributes:!0})}onClick=t=>{this.fileInput.click()};onDragover=t=>{this.fileInput.disabled||t.preventDefault()};onDragenter=t=>{this.updateDropzoneVisibility(t),this.enteredAnotherElement=!0};onDragleave=()=>{this.enteredAnotherElement||this.uploadButton.disabled||(this.hideDraggingState(),this.announce(this.i18n.t("leftDropZone"))),this.enteredAnotherElement=!1};onDrop=t=>{this.fileInput.disabled||(t.preventDefault(),t.dataTransfer&&this.canFillInput(t.dataTransfer)&&(this.fileInput.files=t.dataTransfer.files,this.fileInput.dispatchEvent(new CustomEvent("change")),this.hideDraggingState()))};updateDropzoneVisibility(t){this.uploadButton.disabled||t.target instanceof Node&&(this.element.contains(t.target)?t.dataTransfer&&this.canDrop(t.dataTransfer)&&(this.isDragging||(this.showDraggingState(),this.announce(this.i18n.t("enteredDropZone")))):this.isDragging&&(this.hideDraggingState(),this.announce(this.i18n.t("leftDropZone"))))}showDraggingState(){this.uploadButton.classList.add(`${I.brand}-file-upload-button--dragging`)}hideDraggingState(){this.uploadButton.classList.remove(`${I.brand}-file-upload-button--dragging`)}announce(t){this.announcements&&(this.announcements.textContent=t)}get announcements(){return this.element.querySelector(`.${I.brand}-file-upload-announcements`)}matchesInputCapacity(t){return this.fileInput.multiple?t>0:1===t}canDrop(t){return t.items.length?this.matchesInputCapacity((e=t.items,Array.from(e).filter(t=>"file"===t.kind).length)):!t.types.length||t.types.includes("Files");var e}canFillInput(t){return this.matchesInputCapacity(t.files.length)}onChange=()=>{const t=Array.from(this.fileInput.files),e=Array.from(this.element.querySelectorAll("figure"));e.forEach(e=>{e.file&&!t.includes(e.file)&&e.remove()}),t.forEach(t=>{if(e.some(e=>e.file===t))return;const n=P(this.fileInput,t,this.i18n);this.uploadButton.insertAdjacentElement("beforebegin",n)}),this.updateCount()};onUpload=({detail:{file:t}})=>{this.releaseFile(t),this.updateCount()};releaseFile(t){const e=new DataTransfer;for(const n of this.fileInput.files)n!==t&&e.items.add(n);this.fileInput.files=e.files}onRemove=async t=>{if(await Promise.resolve(),t.defaultPrevented)return;const{name:e,file:n}=t.detail;n&&this.releaseFile(n),this.announce(this.i18n.t("fileRemoved",{filename:e})),this.updateCount()};updateCount(){const t=this.fileCount;0===t?(this.statusTag.innerText=this.i18n.t("noFileChosen"),this.uploadButton.classList.add(`${I.brand}-file-upload-button--empty`)):(this.statusTag.innerText=this.i18n.t("multipleFilesChosen",{count:t}),this.uploadButton.classList.remove(`${I.brand}-file-upload-button--empty`))}get fileInput(){return this.element.querySelector("input[type='file']")}get uploadButton(){return this.element.querySelector(D)}get isDragging(){return this.uploadButton.classList.contains(`${I.brand}-file-upload-button--dragging`)}get statusTag(){return this.element.querySelector("button [aria-live]")}get fileCount(){let t=this.fileInput.files.length;return this.element.querySelectorAll(`select[name='${this.fileInput.name}']`).forEach(e=>{e.closest("figure")?.file||(t+=1)}),this.fileInput.multiple||(t=Math.min(t,1)),t}}},{identifier:"govuk-image-field",controllerConstructor:class extends _{connect(){super.connect(),this.initialPreviewContent=this.imageTag.getAttribute("src")}setPreviewContent(t){this.imageTag.src=t}showPreview(t){const e=new FileReader;e.onload=t=>{this.imageTag.src=t.target.result},e.readAsDataURL(t)}get imageTag(){return this.previewTarget.querySelector("img")}}}];let j={};function U(t=document){if(!s())return void console.log(new l);[[E,j.button],[T,j.characterCount],[k],[x,j.errorSummary],[L,j.fileUpload],[A],[S,j.passwordInput]].forEach(([e,n])=>{const s=`[data-module="${e.moduleName}"]`;[...t instanceof Element&&t.matches(s)?[t]:[],...t.querySelectorAll(s)].forEach(t=>{if(!i(t,e.moduleName))try{"defaults"in e?new e(t,n):new e(t)}catch(t){console.log(t)}})})}function H(t){t.classList.toggle("js-enabled",!0),t.classList.toggle("govuk-frontend-supported","noModule"in HTMLScriptElement.prototype)}function N(t){new MutationObserver(()=>{(function(t){const e="noModule"in HTMLScriptElement.prototype;return t.classList.contains("js-enabled")&&t.classList.contains("govuk-frontend-supported")===e})(t)||(H(t),U())}).observe(t,{attributes:!0,attributeFilter:["class"]}),new MutationObserver(t=>{for(const e of t)for(const t of e.addedNodes)t instanceof Element&&U(t)}).observe(t,{childList:!0,subtree:!0})}function z(t){t&&!t.__govukFormbuilderInit&&(t.__govukFormbuilderInit=!0,H(t),U(),N(t))}let V=!1;function Y(t=void 0){V||(V=!0,(t??e.start()).load(q))}function W(t){t.brand&&(I.brand=t.brand),j=t}function Z(t={}){W(t),Y(),z(document.body)}let K=!1;var G={start:function(t=void 0,e={}){W(e),Y(t),K||(K=!0,new MutationObserver(()=>z(document.body)).observe(document.documentElement,{childList:!0})),z(document.body)}};export{E as Button,T as CharacterCount,k as Checkboxes,x as ErrorSummary,S as PasswordInput,A as Radios,G as default,Z as initAll};
57
57
  //# sourceMappingURL=formbuilder.min.js.map