dxw_govuk_frontend_rails 2.9.0.pre.alpha.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (134) hide show
  1. checksums.yaml +7 -0
  2. data/.circleci/config.yml +33 -0
  3. data/.circleci/setup-rubygems.sh +3 -0
  4. data/.gitignore +9 -0
  5. data/CODE_OF_CONDUCT.md +74 -0
  6. data/Gemfile +4 -0
  7. data/LICENSE.txt +21 -0
  8. data/README.md +91 -0
  9. data/Rakefile +50 -0
  10. data/bin/console +14 -0
  11. data/bin/setup +8 -0
  12. data/dxw_govuk_frontend_rails.gemspec +27 -0
  13. data/lib/dxw_govuk_frontend_rails/version.rb +3 -0
  14. data/lib/dxw_govuk_frontend_rails.rb +12 -0
  15. data/package-lock.json +13 -0
  16. data/package.json +26 -0
  17. data/vendor/assets/fonts/bold-a2452cb66f-v1.woff2 +0 -0
  18. data/vendor/assets/fonts/bold-f38c792ac2-v1.woff +0 -0
  19. data/vendor/assets/fonts/bold-fb2676462a-v1.eot +0 -0
  20. data/vendor/assets/fonts/bold-tabular-357fdfbcc3-v1.eot +0 -0
  21. data/vendor/assets/fonts/bold-tabular-784c21afb8-v1.woff +0 -0
  22. data/vendor/assets/fonts/bold-tabular-b89238d840-v1.woff2 +0 -0
  23. data/vendor/assets/fonts/light-2c037cf7e1-v1.eot +0 -0
  24. data/vendor/assets/fonts/light-458f8ea81c-v1.woff +0 -0
  25. data/vendor/assets/fonts/light-f38ad40456-v1.woff2 +0 -0
  26. data/vendor/assets/fonts/light-tabular-498ea8ffe2-v1.eot +0 -0
  27. data/vendor/assets/fonts/light-tabular-62cc6f0a28-v1.woff +0 -0
  28. data/vendor/assets/fonts/light-tabular-851b10ccdd-v1.woff2 +0 -0
  29. data/vendor/assets/images/favicon.ico +0 -0
  30. data/vendor/assets/images/govuk-apple-touch-icon-152x152.png +0 -0
  31. data/vendor/assets/images/govuk-apple-touch-icon-167x167.png +0 -0
  32. data/vendor/assets/images/govuk-apple-touch-icon-180x180.png +0 -0
  33. data/vendor/assets/images/govuk-apple-touch-icon.png +0 -0
  34. data/vendor/assets/images/govuk-crest-2x.png +0 -0
  35. data/vendor/assets/images/govuk-crest.png +0 -0
  36. data/vendor/assets/images/govuk-logotype-crown.png +0 -0
  37. data/vendor/assets/images/govuk-mask-icon.svg +7 -0
  38. data/vendor/assets/images/govuk-opengraph-image.png +0 -0
  39. data/vendor/assets/images/icon-arrow-left.png +0 -0
  40. data/vendor/assets/images/icon-important.png +0 -0
  41. data/vendor/assets/images/icon-pointer-2x.png +0 -0
  42. data/vendor/assets/images/icon-pointer.png +0 -0
  43. data/vendor/assets/javascripts/govuk_frontend_rails.js +2358 -0
  44. data/vendor/assets/stylesheets/all-ie8.scss +6 -0
  45. data/vendor/assets/stylesheets/all.scss +11 -0
  46. data/vendor/assets/stylesheets/components/_all.scss +29 -0
  47. data/vendor/assets/stylesheets/components/accordion/_accordion.scss +188 -0
  48. data/vendor/assets/stylesheets/components/back-link/_back-link.scss +54 -0
  49. data/vendor/assets/stylesheets/components/breadcrumbs/_breadcrumbs.scss +119 -0
  50. data/vendor/assets/stylesheets/components/button/_button.scss +180 -0
  51. data/vendor/assets/stylesheets/components/character-count/_character-count.scss +31 -0
  52. data/vendor/assets/stylesheets/components/checkboxes/_checkboxes.scss +161 -0
  53. data/vendor/assets/stylesheets/components/date-input/_date-input.scss +30 -0
  54. data/vendor/assets/stylesheets/components/details/_details.scss +89 -0
  55. data/vendor/assets/stylesheets/components/error-message/_error-message.scss +15 -0
  56. data/vendor/assets/stylesheets/components/error-summary/_error-summary.scss +72 -0
  57. data/vendor/assets/stylesheets/components/fieldset/_fieldset.scss +60 -0
  58. data/vendor/assets/stylesheets/components/file-upload/_file-upload.scss +19 -0
  59. data/vendor/assets/stylesheets/components/footer/_footer.scss +233 -0
  60. data/vendor/assets/stylesheets/components/header/_header.scss +304 -0
  61. data/vendor/assets/stylesheets/components/hint/_hint.scss +50 -0
  62. data/vendor/assets/stylesheets/components/input/_input.scss +77 -0
  63. data/vendor/assets/stylesheets/components/inset-text/_inset-text.scss +28 -0
  64. data/vendor/assets/stylesheets/components/label/_label.scss +45 -0
  65. data/vendor/assets/stylesheets/components/panel/_panel.scss +44 -0
  66. data/vendor/assets/stylesheets/components/phase-banner/_phase-banner.scss +31 -0
  67. data/vendor/assets/stylesheets/components/radios/_radios.scss +187 -0
  68. data/vendor/assets/stylesheets/components/select/_select.scss +32 -0
  69. data/vendor/assets/stylesheets/components/skip-link/_skip-link.scss +26 -0
  70. data/vendor/assets/stylesheets/components/summary-list/_summary-list.scss +123 -0
  71. data/vendor/assets/stylesheets/components/table/_table.scss +53 -0
  72. data/vendor/assets/stylesheets/components/tabs/_tabs.scss +130 -0
  73. data/vendor/assets/stylesheets/components/tag/_tag.scss +33 -0
  74. data/vendor/assets/stylesheets/components/textarea/_textarea.scss +32 -0
  75. data/vendor/assets/stylesheets/components/warning-text/_warning-text.scss +59 -0
  76. data/vendor/assets/stylesheets/core/_all.scss +6 -0
  77. data/vendor/assets/stylesheets/core/_global-styles.scss +23 -0
  78. data/vendor/assets/stylesheets/core/_links.scss +31 -0
  79. data/vendor/assets/stylesheets/core/_lists.scss +58 -0
  80. data/vendor/assets/stylesheets/core/_section-break.scss +60 -0
  81. data/vendor/assets/stylesheets/core/_template.scss +35 -0
  82. data/vendor/assets/stylesheets/core/_typography.scss +190 -0
  83. data/vendor/assets/stylesheets/govuk-frontend-rails.scss +16 -0
  84. data/vendor/assets/stylesheets/helpers/_all.scss +12 -0
  85. data/vendor/assets/stylesheets/helpers/_clearfix.scss +15 -0
  86. data/vendor/assets/stylesheets/helpers/_colour.scss +51 -0
  87. data/vendor/assets/stylesheets/helpers/_device-pixels.scss +38 -0
  88. data/vendor/assets/stylesheets/helpers/_focusable.scss +34 -0
  89. data/vendor/assets/stylesheets/helpers/_font-faces.scss +67 -0
  90. data/vendor/assets/stylesheets/helpers/_grid.scss +107 -0
  91. data/vendor/assets/stylesheets/helpers/_links.scss +200 -0
  92. data/vendor/assets/stylesheets/helpers/_media-queries.scss +95 -0
  93. data/vendor/assets/stylesheets/helpers/_shape-arrow.scss +80 -0
  94. data/vendor/assets/stylesheets/helpers/_spacing.scss +152 -0
  95. data/vendor/assets/stylesheets/helpers/_typography.scss +188 -0
  96. data/vendor/assets/stylesheets/helpers/_visually-hidden.scss +82 -0
  97. data/vendor/assets/stylesheets/objects/_all.scss +4 -0
  98. data/vendor/assets/stylesheets/objects/_form-group.scss +25 -0
  99. data/vendor/assets/stylesheets/objects/_grid.scss +27 -0
  100. data/vendor/assets/stylesheets/objects/_main-wrapper.scss +53 -0
  101. data/vendor/assets/stylesheets/objects/_width-container.scss +63 -0
  102. data/vendor/assets/stylesheets/overrides/_all.scss +4 -0
  103. data/vendor/assets/stylesheets/overrides/_display.scss +18 -0
  104. data/vendor/assets/stylesheets/overrides/_spacing.scss +62 -0
  105. data/vendor/assets/stylesheets/overrides/_typography.scss +25 -0
  106. data/vendor/assets/stylesheets/overrides/_width.scss +49 -0
  107. data/vendor/assets/stylesheets/settings/_all.scss +21 -0
  108. data/vendor/assets/stylesheets/settings/_assets.scss +82 -0
  109. data/vendor/assets/stylesheets/settings/_colours-applied.scss +140 -0
  110. data/vendor/assets/stylesheets/settings/_colours-organisations.scss +136 -0
  111. data/vendor/assets/stylesheets/settings/_colours-palette.scss +37 -0
  112. data/vendor/assets/stylesheets/settings/_compatibility.scss +51 -0
  113. data/vendor/assets/stylesheets/settings/_global-styles.scss +13 -0
  114. data/vendor/assets/stylesheets/settings/_ie8.scss +18 -0
  115. data/vendor/assets/stylesheets/settings/_measurements.scss +99 -0
  116. data/vendor/assets/stylesheets/settings/_media-queries.scss +23 -0
  117. data/vendor/assets/stylesheets/settings/_spacing.scss +80 -0
  118. data/vendor/assets/stylesheets/settings/_typography-font-families.scss +22 -0
  119. data/vendor/assets/stylesheets/settings/_typography-font.scss +60 -0
  120. data/vendor/assets/stylesheets/settings/_typography-responsive.scss +180 -0
  121. data/vendor/assets/stylesheets/tools/_all.scss +8 -0
  122. data/vendor/assets/stylesheets/tools/_compatibility.scss +36 -0
  123. data/vendor/assets/stylesheets/tools/_exports.scss +33 -0
  124. data/vendor/assets/stylesheets/tools/_font-url.scss +28 -0
  125. data/vendor/assets/stylesheets/tools/_ie8.scss +51 -0
  126. data/vendor/assets/stylesheets/tools/_iff.scss +15 -0
  127. data/vendor/assets/stylesheets/tools/_image-url.scss +28 -0
  128. data/vendor/assets/stylesheets/tools/_px-to-em.scss +20 -0
  129. data/vendor/assets/stylesheets/tools/_px-to-rem.scss +20 -0
  130. data/vendor/assets/stylesheets/utilities/_all.scss +2 -0
  131. data/vendor/assets/stylesheets/utilities/_clearfix.scss +5 -0
  132. data/vendor/assets/stylesheets/utilities/_visually-hidden.scss +10 -0
  133. data/vendor/assets/stylesheets/vendor/_sass-mq.scss +351 -0
  134. metadata +204 -0
@@ -0,0 +1,2358 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define('GOVUKFrontend', ['exports'], factory) :
4
+ (factory((global.GOVUKFrontend = {})));
5
+ }(this, (function (exports) { 'use strict';
6
+
7
+ /**
8
+ * TODO: Ideally this would be a NodeList.prototype.forEach polyfill
9
+ * This seems to fail in IE8, requires more investigation.
10
+ * See: https://github.com/imagitama/nodelist-foreach-polyfill
11
+ */
12
+ function nodeListForEach (nodes, callback) {
13
+ if (window.NodeList.prototype.forEach) {
14
+ return nodes.forEach(callback)
15
+ }
16
+ for (var i = 0; i < nodes.length; i++) {
17
+ callback.call(window, nodes[i], i, nodes);
18
+ }
19
+ }
20
+
21
+ // Used to generate a unique string, allows multiple instances of the component without
22
+ // Them conflicting with each other.
23
+ // https://stackoverflow.com/a/8809472
24
+ function generateUniqueID () {
25
+ var d = new Date().getTime();
26
+ if (typeof window.performance !== 'undefined' && typeof window.performance.now === 'function') {
27
+ d += window.performance.now(); // use high-precision timer if available
28
+ }
29
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
30
+ var r = (d + Math.random() * 16) % 16 | 0;
31
+ d = Math.floor(d / 16);
32
+ return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
33
+ })
34
+ }
35
+
36
+ (function(undefined) {
37
+
38
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Object/defineProperty/detect.js
39
+ var detect = (
40
+ // In IE8, defineProperty could only act on DOM elements, so full support
41
+ // for the feature requires the ability to set a property on an arbitrary object
42
+ 'defineProperty' in Object && (function() {
43
+ try {
44
+ var a = {};
45
+ Object.defineProperty(a, 'test', {value:42});
46
+ return true;
47
+ } catch(e) {
48
+ return false
49
+ }
50
+ }())
51
+ );
52
+
53
+ if (detect) return
54
+
55
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Object.defineProperty&flags=always
56
+ (function (nativeDefineProperty) {
57
+
58
+ var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
59
+ var ERR_ACCESSORS_NOT_SUPPORTED = 'Getters & setters cannot be defined on this javascript engine';
60
+ var ERR_VALUE_ACCESSORS = 'A property cannot both have accessors and be writable or have a value';
61
+
62
+ Object.defineProperty = function defineProperty(object, property, descriptor) {
63
+
64
+ // Where native support exists, assume it
65
+ if (nativeDefineProperty && (object === window || object === document || object === Element.prototype || object instanceof Element)) {
66
+ return nativeDefineProperty(object, property, descriptor);
67
+ }
68
+
69
+ if (object === null || !(object instanceof Object || typeof object === 'object')) {
70
+ throw new TypeError('Object.defineProperty called on non-object');
71
+ }
72
+
73
+ if (!(descriptor instanceof Object)) {
74
+ throw new TypeError('Property description must be an object');
75
+ }
76
+
77
+ var propertyString = String(property);
78
+ var hasValueOrWritable = 'value' in descriptor || 'writable' in descriptor;
79
+ var getterType = 'get' in descriptor && typeof descriptor.get;
80
+ var setterType = 'set' in descriptor && typeof descriptor.set;
81
+
82
+ // handle descriptor.get
83
+ if (getterType) {
84
+ if (getterType !== 'function') {
85
+ throw new TypeError('Getter must be a function');
86
+ }
87
+ if (!supportsAccessors) {
88
+ throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
89
+ }
90
+ if (hasValueOrWritable) {
91
+ throw new TypeError(ERR_VALUE_ACCESSORS);
92
+ }
93
+ Object.__defineGetter__.call(object, propertyString, descriptor.get);
94
+ } else {
95
+ object[propertyString] = descriptor.value;
96
+ }
97
+
98
+ // handle descriptor.set
99
+ if (setterType) {
100
+ if (setterType !== 'function') {
101
+ throw new TypeError('Setter must be a function');
102
+ }
103
+ if (!supportsAccessors) {
104
+ throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
105
+ }
106
+ if (hasValueOrWritable) {
107
+ throw new TypeError(ERR_VALUE_ACCESSORS);
108
+ }
109
+ Object.__defineSetter__.call(object, propertyString, descriptor.set);
110
+ }
111
+
112
+ // OK to define value unconditionally - if a getter has been specified as well, an error would be thrown above
113
+ if ('value' in descriptor) {
114
+ object[propertyString] = descriptor.value;
115
+ }
116
+
117
+ return object;
118
+ };
119
+ }(Object.defineProperty));
120
+ })
121
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
122
+
123
+ (function(undefined) {
124
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Function/prototype/bind/detect.js
125
+ var detect = 'bind' in Function.prototype;
126
+
127
+ if (detect) return
128
+
129
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Function.prototype.bind&flags=always
130
+ Object.defineProperty(Function.prototype, 'bind', {
131
+ value: function bind(that) { // .length is 1
132
+ // add necessary es5-shim utilities
133
+ var $Array = Array;
134
+ var $Object = Object;
135
+ var ObjectPrototype = $Object.prototype;
136
+ var ArrayPrototype = $Array.prototype;
137
+ var Empty = function Empty() {};
138
+ var to_string = ObjectPrototype.toString;
139
+ var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
140
+ var isCallable; /* inlined from https://npmjs.com/is-callable */ var fnToStr = Function.prototype.toString, tryFunctionObject = function tryFunctionObject(value) { try { fnToStr.call(value); return true; } catch (e) { return false; } }, fnClass = '[object Function]', genClass = '[object GeneratorFunction]'; isCallable = function isCallable(value) { if (typeof value !== 'function') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } var strClass = to_string.call(value); return strClass === fnClass || strClass === genClass; };
141
+ var array_slice = ArrayPrototype.slice;
142
+ var array_concat = ArrayPrototype.concat;
143
+ var array_push = ArrayPrototype.push;
144
+ var max = Math.max;
145
+ // /add necessary es5-shim utilities
146
+
147
+ // 1. Let Target be the this value.
148
+ var target = this;
149
+ // 2. If IsCallable(Target) is false, throw a TypeError exception.
150
+ if (!isCallable(target)) {
151
+ throw new TypeError('Function.prototype.bind called on incompatible ' + target);
152
+ }
153
+ // 3. Let A be a new (possibly empty) internal list of all of the
154
+ // argument values provided after thisArg (arg1, arg2 etc), in order.
155
+ // XXX slicedArgs will stand in for "A" if used
156
+ var args = array_slice.call(arguments, 1); // for normal call
157
+ // 4. Let F be a new native ECMAScript object.
158
+ // 11. Set the [[Prototype]] internal property of F to the standard
159
+ // built-in Function prototype object as specified in 15.3.3.1.
160
+ // 12. Set the [[Call]] internal property of F as described in
161
+ // 15.3.4.5.1.
162
+ // 13. Set the [[Construct]] internal property of F as described in
163
+ // 15.3.4.5.2.
164
+ // 14. Set the [[HasInstance]] internal property of F as described in
165
+ // 15.3.4.5.3.
166
+ var bound;
167
+ var binder = function () {
168
+
169
+ if (this instanceof bound) {
170
+ // 15.3.4.5.2 [[Construct]]
171
+ // When the [[Construct]] internal method of a function object,
172
+ // F that was created using the bind function is called with a
173
+ // list of arguments ExtraArgs, the following steps are taken:
174
+ // 1. Let target be the value of F's [[TargetFunction]]
175
+ // internal property.
176
+ // 2. If target has no [[Construct]] internal method, a
177
+ // TypeError exception is thrown.
178
+ // 3. Let boundArgs be the value of F's [[BoundArgs]] internal
179
+ // property.
180
+ // 4. Let args be a new list containing the same values as the
181
+ // list boundArgs in the same order followed by the same
182
+ // values as the list ExtraArgs in the same order.
183
+ // 5. Return the result of calling the [[Construct]] internal
184
+ // method of target providing args as the arguments.
185
+
186
+ var result = target.apply(
187
+ this,
188
+ array_concat.call(args, array_slice.call(arguments))
189
+ );
190
+ if ($Object(result) === result) {
191
+ return result;
192
+ }
193
+ return this;
194
+
195
+ } else {
196
+ // 15.3.4.5.1 [[Call]]
197
+ // When the [[Call]] internal method of a function object, F,
198
+ // which was created using the bind function is called with a
199
+ // this value and a list of arguments ExtraArgs, the following
200
+ // steps are taken:
201
+ // 1. Let boundArgs be the value of F's [[BoundArgs]] internal
202
+ // property.
203
+ // 2. Let boundThis be the value of F's [[BoundThis]] internal
204
+ // property.
205
+ // 3. Let target be the value of F's [[TargetFunction]] internal
206
+ // property.
207
+ // 4. Let args be a new list containing the same values as the
208
+ // list boundArgs in the same order followed by the same
209
+ // values as the list ExtraArgs in the same order.
210
+ // 5. Return the result of calling the [[Call]] internal method
211
+ // of target providing boundThis as the this value and
212
+ // providing args as the arguments.
213
+
214
+ // equiv: target.call(this, ...boundArgs, ...args)
215
+ return target.apply(
216
+ that,
217
+ array_concat.call(args, array_slice.call(arguments))
218
+ );
219
+
220
+ }
221
+
222
+ };
223
+
224
+ // 15. If the [[Class]] internal property of Target is "Function", then
225
+ // a. Let L be the length property of Target minus the length of A.
226
+ // b. Set the length own property of F to either 0 or L, whichever is
227
+ // larger.
228
+ // 16. Else set the length own property of F to 0.
229
+
230
+ var boundLength = max(0, target.length - args.length);
231
+
232
+ // 17. Set the attributes of the length own property of F to the values
233
+ // specified in 15.3.5.1.
234
+ var boundArgs = [];
235
+ for (var i = 0; i < boundLength; i++) {
236
+ array_push.call(boundArgs, '$' + i);
237
+ }
238
+
239
+ // XXX Build a dynamic function with desired amount of arguments is the only
240
+ // way to set the length property of a function.
241
+ // In environments where Content Security Policies enabled (Chrome extensions,
242
+ // for ex.) all use of eval or Function costructor throws an exception.
243
+ // However in all of these environments Function.prototype.bind exists
244
+ // and so this code will never be executed.
245
+ bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
246
+
247
+ if (target.prototype) {
248
+ Empty.prototype = target.prototype;
249
+ bound.prototype = new Empty();
250
+ // Clean up dangling references.
251
+ Empty.prototype = null;
252
+ }
253
+
254
+ // TODO
255
+ // 18. Set the [[Extensible]] internal property of F to true.
256
+
257
+ // TODO
258
+ // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
259
+ // 20. Call the [[DefineOwnProperty]] internal method of F with
260
+ // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
261
+ // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
262
+ // false.
263
+ // 21. Call the [[DefineOwnProperty]] internal method of F with
264
+ // arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
265
+ // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
266
+ // and false.
267
+
268
+ // TODO
269
+ // NOTE Function objects created using Function.prototype.bind do not
270
+ // have a prototype property or the [[Code]], [[FormalParameters]], and
271
+ // [[Scope]] internal properties.
272
+ // XXX can't delete prototype in pure-js.
273
+
274
+ // 22. Return F.
275
+ return bound;
276
+ }
277
+ });
278
+ })
279
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
280
+
281
+ (function(undefined) {
282
+
283
+ // Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/master/packages/polyfill-library/polyfills/DOMTokenList/detect.js
284
+ var detect = (
285
+ 'DOMTokenList' in this && (function (x) {
286
+ return 'classList' in x ? !x.classList.toggle('x', false) && !x.className : true;
287
+ })(document.createElement('x'))
288
+ );
289
+
290
+ if (detect) return
291
+
292
+ // Polyfill from https://raw.githubusercontent.com/Financial-Times/polyfill-service/master/packages/polyfill-library/polyfills/DOMTokenList/polyfill.js
293
+ (function (global) {
294
+ var nativeImpl = "DOMTokenList" in global && global.DOMTokenList;
295
+
296
+ if (
297
+ !nativeImpl ||
298
+ (
299
+ !!document.createElementNS &&
300
+ !!document.createElementNS('http://www.w3.org/2000/svg', 'svg') &&
301
+ !(document.createElementNS("http://www.w3.org/2000/svg", "svg").classList instanceof DOMTokenList)
302
+ )
303
+ ) {
304
+ global.DOMTokenList = (function() { // eslint-disable-line no-unused-vars
305
+ var dpSupport = true;
306
+ var defineGetter = function (object, name, fn, configurable) {
307
+ if (Object.defineProperty)
308
+ Object.defineProperty(object, name, {
309
+ configurable: false === dpSupport ? true : !!configurable,
310
+ get: fn
311
+ });
312
+
313
+ else object.__defineGetter__(name, fn);
314
+ };
315
+
316
+ /** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */
317
+ try {
318
+ defineGetter({}, "support");
319
+ }
320
+ catch (e) {
321
+ dpSupport = false;
322
+ }
323
+
324
+
325
+ var _DOMTokenList = function (el, prop) {
326
+ var that = this;
327
+ var tokens = [];
328
+ var tokenMap = {};
329
+ var length = 0;
330
+ var maxLength = 0;
331
+ var addIndexGetter = function (i) {
332
+ defineGetter(that, i, function () {
333
+ preop();
334
+ return tokens[i];
335
+ }, false);
336
+
337
+ };
338
+ var reindex = function () {
339
+
340
+ /** Define getter functions for array-like access to the tokenList's contents. */
341
+ if (length >= maxLength)
342
+ for (; maxLength < length; ++maxLength) {
343
+ addIndexGetter(maxLength);
344
+ }
345
+ };
346
+
347
+ /** Helper function called at the start of each class method. Internal use only. */
348
+ var preop = function () {
349
+ var error;
350
+ var i;
351
+ var args = arguments;
352
+ var rSpace = /\s+/;
353
+
354
+ /** Validate the token/s passed to an instance method, if any. */
355
+ if (args.length)
356
+ for (i = 0; i < args.length; ++i)
357
+ if (rSpace.test(args[i])) {
358
+ error = new SyntaxError('String "' + args[i] + '" ' + "contains" + ' an invalid character');
359
+ error.code = 5;
360
+ error.name = "InvalidCharacterError";
361
+ throw error;
362
+ }
363
+
364
+
365
+ /** Split the new value apart by whitespace*/
366
+ if (typeof el[prop] === "object") {
367
+ tokens = ("" + el[prop].baseVal).replace(/^\s+|\s+$/g, "").split(rSpace);
368
+ } else {
369
+ tokens = ("" + el[prop]).replace(/^\s+|\s+$/g, "").split(rSpace);
370
+ }
371
+
372
+ /** Avoid treating blank strings as single-item token lists */
373
+ if ("" === tokens[0]) tokens = [];
374
+
375
+ /** Repopulate the internal token lists */
376
+ tokenMap = {};
377
+ for (i = 0; i < tokens.length; ++i)
378
+ tokenMap[tokens[i]] = true;
379
+ length = tokens.length;
380
+ reindex();
381
+ };
382
+
383
+ /** Populate our internal token list if the targeted attribute of the subject element isn't empty. */
384
+ preop();
385
+
386
+ /** Return the number of tokens in the underlying string. Read-only. */
387
+ defineGetter(that, "length", function () {
388
+ preop();
389
+ return length;
390
+ });
391
+
392
+ /** Override the default toString/toLocaleString methods to return a space-delimited list of tokens when typecast. */
393
+ that.toLocaleString =
394
+ that.toString = function () {
395
+ preop();
396
+ return tokens.join(" ");
397
+ };
398
+
399
+ that.item = function (idx) {
400
+ preop();
401
+ return tokens[idx];
402
+ };
403
+
404
+ that.contains = function (token) {
405
+ preop();
406
+ return !!tokenMap[token];
407
+ };
408
+
409
+ that.add = function () {
410
+ preop.apply(that, args = arguments);
411
+
412
+ for (var args, token, i = 0, l = args.length; i < l; ++i) {
413
+ token = args[i];
414
+ if (!tokenMap[token]) {
415
+ tokens.push(token);
416
+ tokenMap[token] = true;
417
+ }
418
+ }
419
+
420
+ /** Update the targeted attribute of the attached element if the token list's changed. */
421
+ if (length !== tokens.length) {
422
+ length = tokens.length >>> 0;
423
+ if (typeof el[prop] === "object") {
424
+ el[prop].baseVal = tokens.join(" ");
425
+ } else {
426
+ el[prop] = tokens.join(" ");
427
+ }
428
+ reindex();
429
+ }
430
+ };
431
+
432
+ that.remove = function () {
433
+ preop.apply(that, args = arguments);
434
+
435
+ /** Build a hash of token names to compare against when recollecting our token list. */
436
+ for (var args, ignore = {}, i = 0, t = []; i < args.length; ++i) {
437
+ ignore[args[i]] = true;
438
+ delete tokenMap[args[i]];
439
+ }
440
+
441
+ /** Run through our tokens list and reassign only those that aren't defined in the hash declared above. */
442
+ for (i = 0; i < tokens.length; ++i)
443
+ if (!ignore[tokens[i]]) t.push(tokens[i]);
444
+
445
+ tokens = t;
446
+ length = t.length >>> 0;
447
+
448
+ /** Update the targeted attribute of the attached element. */
449
+ if (typeof el[prop] === "object") {
450
+ el[prop].baseVal = tokens.join(" ");
451
+ } else {
452
+ el[prop] = tokens.join(" ");
453
+ }
454
+ reindex();
455
+ };
456
+
457
+ that.toggle = function (token, force) {
458
+ preop.apply(that, [token]);
459
+
460
+ /** Token state's being forced. */
461
+ if (undefined !== force) {
462
+ if (force) {
463
+ that.add(token);
464
+ return true;
465
+ } else {
466
+ that.remove(token);
467
+ return false;
468
+ }
469
+ }
470
+
471
+ /** Token already exists in tokenList. Remove it, and return FALSE. */
472
+ if (tokenMap[token]) {
473
+ that.remove(token);
474
+ return false;
475
+ }
476
+
477
+ /** Otherwise, add the token and return TRUE. */
478
+ that.add(token);
479
+ return true;
480
+ };
481
+
482
+ return that;
483
+ };
484
+
485
+ return _DOMTokenList;
486
+ }());
487
+ }
488
+
489
+ // Add second argument to native DOMTokenList.toggle() if necessary
490
+ (function () {
491
+ var e = document.createElement('span');
492
+ if (!('classList' in e)) return;
493
+ e.classList.toggle('x', false);
494
+ if (!e.classList.contains('x')) return;
495
+ e.classList.constructor.prototype.toggle = function toggle(token /*, force*/) {
496
+ var force = arguments[1];
497
+ if (force === undefined) {
498
+ var add = !this.contains(token);
499
+ this[add ? 'add' : 'remove'](token);
500
+ return add;
501
+ }
502
+ force = !!force;
503
+ this[force ? 'add' : 'remove'](token);
504
+ return force;
505
+ };
506
+ }());
507
+
508
+ // Add multiple arguments to native DOMTokenList.add() if necessary
509
+ (function () {
510
+ var e = document.createElement('span');
511
+ if (!('classList' in e)) return;
512
+ e.classList.add('a', 'b');
513
+ if (e.classList.contains('b')) return;
514
+ var native = e.classList.constructor.prototype.add;
515
+ e.classList.constructor.prototype.add = function () {
516
+ var args = arguments;
517
+ var l = arguments.length;
518
+ for (var i = 0; i < l; i++) {
519
+ native.call(this, args[i]);
520
+ }
521
+ };
522
+ }());
523
+
524
+ // Add multiple arguments to native DOMTokenList.remove() if necessary
525
+ (function () {
526
+ var e = document.createElement('span');
527
+ if (!('classList' in e)) return;
528
+ e.classList.add('a');
529
+ e.classList.add('b');
530
+ e.classList.remove('a', 'b');
531
+ if (!e.classList.contains('b')) return;
532
+ var native = e.classList.constructor.prototype.remove;
533
+ e.classList.constructor.prototype.remove = function () {
534
+ var args = arguments;
535
+ var l = arguments.length;
536
+ for (var i = 0; i < l; i++) {
537
+ native.call(this, args[i]);
538
+ }
539
+ };
540
+ }());
541
+
542
+ }(this));
543
+
544
+ }).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
545
+
546
+ (function(undefined) {
547
+
548
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Document/detect.js
549
+ var detect = ("Document" in this);
550
+
551
+ if (detect) return
552
+
553
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Document&flags=always
554
+ if ((typeof WorkerGlobalScope === "undefined") && (typeof importScripts !== "function")) {
555
+
556
+ if (this.HTMLDocument) { // IE8
557
+
558
+ // HTMLDocument is an extension of Document. If the browser has HTMLDocument but not Document, the former will suffice as an alias for the latter.
559
+ this.Document = this.HTMLDocument;
560
+
561
+ } else {
562
+
563
+ // Create an empty function to act as the missing constructor for the document object, attach the document object as its prototype. The function needs to be anonymous else it is hoisted and causes the feature detect to prematurely pass, preventing the assignments below being made.
564
+ this.Document = this.HTMLDocument = document.constructor = (new Function('return function Document() {}')());
565
+ this.Document.prototype = document;
566
+ }
567
+ }
568
+
569
+
570
+ })
571
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
572
+
573
+ (function(undefined) {
574
+
575
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Element/detect.js
576
+ var detect = ('Element' in this && 'HTMLElement' in this);
577
+
578
+ if (detect) return
579
+
580
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Element&flags=always
581
+ (function () {
582
+
583
+ // IE8
584
+ if (window.Element && !window.HTMLElement) {
585
+ window.HTMLElement = window.Element;
586
+ return;
587
+ }
588
+
589
+ // create Element constructor
590
+ window.Element = window.HTMLElement = new Function('return function Element() {}')();
591
+
592
+ // generate sandboxed iframe
593
+ var vbody = document.appendChild(document.createElement('body'));
594
+ var frame = vbody.appendChild(document.createElement('iframe'));
595
+
596
+ // use sandboxed iframe to replicate Element functionality
597
+ var frameDocument = frame.contentWindow.document;
598
+ var prototype = Element.prototype = frameDocument.appendChild(frameDocument.createElement('*'));
599
+ var cache = {};
600
+
601
+ // polyfill Element.prototype on an element
602
+ var shiv = function (element, deep) {
603
+ var
604
+ childNodes = element.childNodes || [],
605
+ index = -1,
606
+ key, value, childNode;
607
+
608
+ if (element.nodeType === 1 && element.constructor !== Element) {
609
+ element.constructor = Element;
610
+
611
+ for (key in cache) {
612
+ value = cache[key];
613
+ element[key] = value;
614
+ }
615
+ }
616
+
617
+ while (childNode = deep && childNodes[++index]) {
618
+ shiv(childNode, deep);
619
+ }
620
+
621
+ return element;
622
+ };
623
+
624
+ var elements = document.getElementsByTagName('*');
625
+ var nativeCreateElement = document.createElement;
626
+ var interval;
627
+ var loopLimit = 100;
628
+
629
+ prototype.attachEvent('onpropertychange', function (event) {
630
+ var
631
+ propertyName = event.propertyName,
632
+ nonValue = !cache.hasOwnProperty(propertyName),
633
+ newValue = prototype[propertyName],
634
+ oldValue = cache[propertyName],
635
+ index = -1,
636
+ element;
637
+
638
+ while (element = elements[++index]) {
639
+ if (element.nodeType === 1) {
640
+ if (nonValue || element[propertyName] === oldValue) {
641
+ element[propertyName] = newValue;
642
+ }
643
+ }
644
+ }
645
+
646
+ cache[propertyName] = newValue;
647
+ });
648
+
649
+ prototype.constructor = Element;
650
+
651
+ if (!prototype.hasAttribute) {
652
+ // <Element>.hasAttribute
653
+ prototype.hasAttribute = function hasAttribute(name) {
654
+ return this.getAttribute(name) !== null;
655
+ };
656
+ }
657
+
658
+ // Apply Element prototype to the pre-existing DOM as soon as the body element appears.
659
+ function bodyCheck() {
660
+ if (!(loopLimit--)) clearTimeout(interval);
661
+ if (document.body && !document.body.prototype && /(complete|interactive)/.test(document.readyState)) {
662
+ shiv(document, true);
663
+ if (interval && document.body.prototype) clearTimeout(interval);
664
+ return (!!document.body.prototype);
665
+ }
666
+ return false;
667
+ }
668
+ if (!bodyCheck()) {
669
+ document.onreadystatechange = bodyCheck;
670
+ interval = setInterval(bodyCheck, 25);
671
+ }
672
+
673
+ // Apply to any new elements created after load
674
+ document.createElement = function createElement(nodeName) {
675
+ var element = nativeCreateElement(String(nodeName).toLowerCase());
676
+ return shiv(element);
677
+ };
678
+
679
+ // remove sandboxed iframe
680
+ document.removeChild(vbody);
681
+ }());
682
+
683
+ })
684
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
685
+
686
+ (function(undefined) {
687
+
688
+ // Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/8717a9e04ac7aff99b4980fbedead98036b0929a/packages/polyfill-library/polyfills/Element/prototype/classList/detect.js
689
+ var detect = (
690
+ 'document' in this && "classList" in document.documentElement && 'Element' in this && 'classList' in Element.prototype && (function () {
691
+ var e = document.createElement('span');
692
+ e.classList.add('a', 'b');
693
+ return e.classList.contains('b');
694
+ }())
695
+ );
696
+
697
+ if (detect) return
698
+
699
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Element.prototype.classList&flags=always
700
+ (function (global) {
701
+ var dpSupport = true;
702
+ var defineGetter = function (object, name, fn, configurable) {
703
+ if (Object.defineProperty)
704
+ Object.defineProperty(object, name, {
705
+ configurable: false === dpSupport ? true : !!configurable,
706
+ get: fn
707
+ });
708
+
709
+ else object.__defineGetter__(name, fn);
710
+ };
711
+ /** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */
712
+ try {
713
+ defineGetter({}, "support");
714
+ }
715
+ catch (e) {
716
+ dpSupport = false;
717
+ }
718
+ /** Polyfills a property with a DOMTokenList */
719
+ var addProp = function (o, name, attr) {
720
+
721
+ defineGetter(o.prototype, name, function () {
722
+ var tokenList;
723
+
724
+ var THIS = this,
725
+
726
+ /** Prevent this from firing twice for some reason. What the hell, IE. */
727
+ gibberishProperty = "__defineGetter__" + "DEFINE_PROPERTY" + name;
728
+ if(THIS[gibberishProperty]) return tokenList;
729
+ THIS[gibberishProperty] = true;
730
+
731
+ /**
732
+ * IE8 can't define properties on native JavaScript objects, so we'll use a dumb hack instead.
733
+ *
734
+ * What this is doing is creating a dummy element ("reflection") inside a detached phantom node ("mirror")
735
+ * that serves as the target of Object.defineProperty instead. While we could simply use the subject HTML
736
+ * element instead, this would conflict with element types which use indexed properties (such as forms and
737
+ * select lists).
738
+ */
739
+ if (false === dpSupport) {
740
+
741
+ var visage;
742
+ var mirror = addProp.mirror || document.createElement("div");
743
+ var reflections = mirror.childNodes;
744
+ var l = reflections.length;
745
+
746
+ for (var i = 0; i < l; ++i)
747
+ if (reflections[i]._R === THIS) {
748
+ visage = reflections[i];
749
+ break;
750
+ }
751
+
752
+ /** Couldn't find an element's reflection inside the mirror. Materialise one. */
753
+ visage || (visage = mirror.appendChild(document.createElement("div")));
754
+
755
+ tokenList = DOMTokenList.call(visage, THIS, attr);
756
+ } else tokenList = new DOMTokenList(THIS, attr);
757
+
758
+ defineGetter(THIS, name, function () {
759
+ return tokenList;
760
+ });
761
+ delete THIS[gibberishProperty];
762
+
763
+ return tokenList;
764
+ }, true);
765
+ };
766
+
767
+ addProp(global.Element, "classList", "className");
768
+ addProp(global.HTMLElement, "classList", "className");
769
+ addProp(global.HTMLLinkElement, "relList", "rel");
770
+ addProp(global.HTMLAnchorElement, "relList", "rel");
771
+ addProp(global.HTMLAreaElement, "relList", "rel");
772
+ }(this));
773
+
774
+ }).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
775
+
776
+ function Accordion ($module) {
777
+ this.$module = $module;
778
+ this.moduleId = $module.getAttribute('id');
779
+ this.$sections = $module.querySelectorAll('.govuk-accordion__section');
780
+ this.$openAllButton = '';
781
+ this.browserSupportsSessionStorage = helper.checkForSessionStorage();
782
+
783
+ this.controlsClass = 'govuk-accordion__controls';
784
+ this.openAllClass = 'govuk-accordion__open-all';
785
+ this.iconClass = 'govuk-accordion__icon';
786
+
787
+ this.sectionHeaderClass = 'govuk-accordion__section-header';
788
+ this.sectionHeaderFocusedClass = 'govuk-accordion__section-header--focused';
789
+ this.sectionHeadingClass = 'govuk-accordion__section-heading';
790
+ this.sectionSummaryClass = 'govuk-accordion__section-summary';
791
+ this.sectionButtonClass = 'govuk-accordion__section-button';
792
+ this.sectionExpandedClass = 'govuk-accordion__section--expanded';
793
+ }
794
+
795
+ // Initialize component
796
+ Accordion.prototype.init = function () {
797
+ // Check for module
798
+ if (!this.$module) {
799
+ return
800
+ }
801
+
802
+ this.initControls();
803
+
804
+ this.initSectionHeaders();
805
+
806
+ // See if "Open all" button text should be updated
807
+ var areAllSectionsOpen = this.checkIfAllSectionsOpen();
808
+ this.updateOpenAllButton(areAllSectionsOpen);
809
+ };
810
+
811
+ // Initialise controls and set attributes
812
+ Accordion.prototype.initControls = function () {
813
+ // Create "Open all" button and set attributes
814
+ this.$openAllButton = document.createElement('button');
815
+ this.$openAllButton.setAttribute('type', 'button');
816
+ this.$openAllButton.innerHTML = 'Open all <span class="govuk-visually-hidden">sections</span>';
817
+ this.$openAllButton.setAttribute('class', this.openAllClass);
818
+ this.$openAllButton.setAttribute('aria-expanded', 'false');
819
+ this.$openAllButton.setAttribute('type', 'button');
820
+
821
+ // Create control wrapper and add controls to it
822
+ var accordionControls = document.createElement('div');
823
+ accordionControls.setAttribute('class', this.controlsClass);
824
+ accordionControls.appendChild(this.$openAllButton);
825
+ this.$module.insertBefore(accordionControls, this.$module.firstChild);
826
+
827
+ // Handle events for the controls
828
+ this.$openAllButton.addEventListener('click', this.onOpenOrCloseAllToggle.bind(this));
829
+ };
830
+
831
+ // Initialise section headers
832
+ Accordion.prototype.initSectionHeaders = function () {
833
+ // Loop through section headers
834
+ nodeListForEach(this.$sections, function ($section, i) {
835
+ // Set header attributes
836
+ var header = $section.querySelector('.' + this.sectionHeaderClass);
837
+ this.initHeaderAttributes(header, i);
838
+
839
+ this.setExpanded(this.isExpanded($section), $section);
840
+
841
+ // Handle events
842
+ header.addEventListener('click', this.onSectionToggle.bind(this, $section));
843
+
844
+ // See if there is any state stored in sessionStorage and set the sections to
845
+ // open or closed.
846
+ this.setInitialState($section);
847
+ }.bind(this));
848
+ };
849
+
850
+ // Set individual header attributes
851
+ Accordion.prototype.initHeaderAttributes = function ($headerWrapper, index) {
852
+ var $module = this;
853
+ var $span = $headerWrapper.querySelector('.' + this.sectionButtonClass);
854
+ var $heading = $headerWrapper.querySelector('.' + this.sectionHeadingClass);
855
+ var $summary = $headerWrapper.querySelector('.' + this.sectionSummaryClass);
856
+
857
+ // Copy existing span element to an actual button element, for improved accessibility.
858
+ var $button = document.createElement('button');
859
+ $button.setAttribute('type', 'button');
860
+ $button.setAttribute('id', this.moduleId + '-heading-' + (index + 1));
861
+ $button.setAttribute('aria-controls', this.moduleId + '-content-' + (index + 1));
862
+
863
+ // Copy all attributes (https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes) from $span to $button
864
+ for (var i = 0; i < $span.attributes.length; i++) {
865
+ var attr = $span.attributes.item(i);
866
+ $button.setAttribute(attr.nodeName, attr.nodeValue);
867
+ }
868
+
869
+ $button.addEventListener('focusin', function (e) {
870
+ if (!$headerWrapper.classList.contains($module.sectionHeaderFocusedClass)) {
871
+ $headerWrapper.className += ' ' + $module.sectionHeaderFocusedClass;
872
+ }
873
+ });
874
+
875
+ $button.addEventListener('blur', function (e) {
876
+ $headerWrapper.classList.remove($module.sectionHeaderFocusedClass);
877
+ });
878
+
879
+ if (typeof ($summary) !== 'undefined' && $summary !== null) {
880
+ $button.setAttribute('aria-describedby', this.moduleId + '-summary-' + (index + 1));
881
+ }
882
+
883
+ // $span could contain HTML elements (see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content)
884
+ $button.innerHTML = $span.innerHTML;
885
+
886
+ $heading.removeChild($span);
887
+ $heading.appendChild($button);
888
+
889
+ // Add "+/-" icon
890
+ var icon = document.createElement('span');
891
+ icon.className = this.iconClass;
892
+ icon.setAttribute('aria-hidden', 'true');
893
+
894
+ $heading.appendChild(icon);
895
+ };
896
+
897
+ // When section toggled, set and store state
898
+ Accordion.prototype.onSectionToggle = function ($section) {
899
+ var expanded = this.isExpanded($section);
900
+ this.setExpanded(!expanded, $section);
901
+
902
+ // Store the state in sessionStorage when a change is triggered
903
+ this.storeState($section);
904
+ };
905
+
906
+ // When Open/Close All toggled, set and store state
907
+ Accordion.prototype.onOpenOrCloseAllToggle = function () {
908
+ var $module = this;
909
+ var $sections = this.$sections;
910
+
911
+ var nowExpanded = !this.checkIfAllSectionsOpen();
912
+
913
+ nodeListForEach($sections, function ($section) {
914
+ $module.setExpanded(nowExpanded, $section);
915
+ // Store the state in sessionStorage when a change is triggered
916
+ $module.storeState($section);
917
+ });
918
+
919
+ $module.updateOpenAllButton(nowExpanded);
920
+ };
921
+
922
+ // Set section attributes when opened/closed
923
+ Accordion.prototype.setExpanded = function (expanded, $section) {
924
+ var $button = $section.querySelector('.' + this.sectionButtonClass);
925
+ $button.setAttribute('aria-expanded', expanded);
926
+
927
+ if (expanded) {
928
+ $section.classList.add(this.sectionExpandedClass);
929
+ } else {
930
+ $section.classList.remove(this.sectionExpandedClass);
931
+ }
932
+
933
+ // See if "Open all" button text should be updated
934
+ var areAllSectionsOpen = this.checkIfAllSectionsOpen();
935
+ this.updateOpenAllButton(areAllSectionsOpen);
936
+ };
937
+
938
+ // Get state of section
939
+ Accordion.prototype.isExpanded = function ($section) {
940
+ return $section.classList.contains(this.sectionExpandedClass)
941
+ };
942
+
943
+ // Check if all sections are open
944
+ Accordion.prototype.checkIfAllSectionsOpen = function () {
945
+ // Get a count of all the Accordion sections
946
+ var sectionsCount = this.$sections.length;
947
+ // Get a count of all Accordion sections that are expanded
948
+ var expandedSectionCount = this.$module.querySelectorAll('.' + this.sectionExpandedClass).length;
949
+ var areAllSectionsOpen = sectionsCount === expandedSectionCount;
950
+
951
+ return areAllSectionsOpen
952
+ };
953
+
954
+ // Update "Open all" button
955
+ Accordion.prototype.updateOpenAllButton = function (expanded) {
956
+ var newButtonText = expanded ? 'Close all' : 'Open all';
957
+ newButtonText += '<span class="govuk-visually-hidden"> sections</span>';
958
+ this.$openAllButton.setAttribute('aria-expanded', expanded);
959
+ this.$openAllButton.innerHTML = newButtonText;
960
+ };
961
+
962
+ // Check for `window.sessionStorage`, and that it actually works.
963
+ var helper = {
964
+ checkForSessionStorage: function () {
965
+ var testString = 'this is the test string';
966
+ var result;
967
+ try {
968
+ window.sessionStorage.setItem(testString, testString);
969
+ result = window.sessionStorage.getItem(testString) === testString.toString();
970
+ window.sessionStorage.removeItem(testString);
971
+ return result
972
+ } catch (exception) {
973
+ if ((typeof console === 'undefined' || typeof console.log === 'undefined')) {
974
+ console.log('Notice: sessionStorage not available.');
975
+ }
976
+ }
977
+ }
978
+ };
979
+
980
+ // Set the state of the accordions in sessionStorage
981
+ Accordion.prototype.storeState = function ($section) {
982
+ if (this.browserSupportsSessionStorage) {
983
+ // We need a unique way of identifying each content in the accordion. Since
984
+ // an `#id` should be unique and an `id` is required for `aria-` attributes
985
+ // `id` can be safely used.
986
+ var $button = $section.querySelector('.' + this.sectionButtonClass);
987
+
988
+ if ($button) {
989
+ var contentId = $button.getAttribute('aria-controls');
990
+ var contentState = $button.getAttribute('aria-expanded');
991
+
992
+ if (typeof contentId === 'undefined' && (typeof console === 'undefined' || typeof console.log === 'undefined')) {
993
+ console.error(new Error('No aria controls present in accordion section heading.'));
994
+ }
995
+
996
+ if (typeof contentState === 'undefined' && (typeof console === 'undefined' || typeof console.log === 'undefined')) {
997
+ console.error(new Error('No aria expanded present in accordion section heading.'));
998
+ }
999
+
1000
+ // Only set the state when both `contentId` and `contentState` are taken from the DOM.
1001
+ if (contentId && contentState) {
1002
+ window.sessionStorage.setItem(contentId, contentState);
1003
+ }
1004
+ }
1005
+ }
1006
+ };
1007
+
1008
+ // Read the state of the accordions from sessionStorage
1009
+ Accordion.prototype.setInitialState = function ($section) {
1010
+ if (this.browserSupportsSessionStorage) {
1011
+ var $button = $section.querySelector('.' + this.sectionButtonClass);
1012
+
1013
+ if ($button) {
1014
+ var contentId = $button.getAttribute('aria-controls');
1015
+ var contentState = contentId ? window.sessionStorage.getItem(contentId) : null;
1016
+
1017
+ if (contentState !== null) {
1018
+ this.setExpanded(contentState === 'true', $section);
1019
+ }
1020
+ }
1021
+ }
1022
+ };
1023
+
1024
+ (function(undefined) {
1025
+
1026
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Window/detect.js
1027
+ var detect = ('Window' in this);
1028
+
1029
+ if (detect) return
1030
+
1031
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Window&flags=always
1032
+ if ((typeof WorkerGlobalScope === "undefined") && (typeof importScripts !== "function")) {
1033
+ (function (global) {
1034
+ if (global.constructor) {
1035
+ global.Window = global.constructor;
1036
+ } else {
1037
+ (global.Window = global.constructor = new Function('return function Window() {}')()).prototype = this;
1038
+ }
1039
+ }(this));
1040
+ }
1041
+
1042
+ })
1043
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
1044
+
1045
+ (function(undefined) {
1046
+
1047
+ // Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Event/detect.js
1048
+ var detect = (
1049
+ (function(global) {
1050
+
1051
+ if (!('Event' in global)) return false;
1052
+ if (typeof global.Event === 'function') return true;
1053
+
1054
+ try {
1055
+
1056
+ // In IE 9-11, the Event object exists but cannot be instantiated
1057
+ new Event('click');
1058
+ return true;
1059
+ } catch(e) {
1060
+ return false;
1061
+ }
1062
+ }(this))
1063
+ );
1064
+
1065
+ if (detect) return
1066
+
1067
+ // Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Event&flags=always
1068
+ (function () {
1069
+ var unlistenableWindowEvents = {
1070
+ click: 1,
1071
+ dblclick: 1,
1072
+ keyup: 1,
1073
+ keypress: 1,
1074
+ keydown: 1,
1075
+ mousedown: 1,
1076
+ mouseup: 1,
1077
+ mousemove: 1,
1078
+ mouseover: 1,
1079
+ mouseenter: 1,
1080
+ mouseleave: 1,
1081
+ mouseout: 1,
1082
+ storage: 1,
1083
+ storagecommit: 1,
1084
+ textinput: 1
1085
+ };
1086
+
1087
+ // This polyfill depends on availability of `document` so will not run in a worker
1088
+ // However, we asssume there are no browsers with worker support that lack proper
1089
+ // support for `Event` within the worker
1090
+ if (typeof document === 'undefined' || typeof window === 'undefined') return;
1091
+
1092
+ function indexOf(array, element) {
1093
+ var
1094
+ index = -1,
1095
+ length = array.length;
1096
+
1097
+ while (++index < length) {
1098
+ if (index in array && array[index] === element) {
1099
+ return index;
1100
+ }
1101
+ }
1102
+
1103
+ return -1;
1104
+ }
1105
+
1106
+ var existingProto = (window.Event && window.Event.prototype) || null;
1107
+ window.Event = Window.prototype.Event = function Event(type, eventInitDict) {
1108
+ if (!type) {
1109
+ throw new Error('Not enough arguments');
1110
+ }
1111
+
1112
+ var event;
1113
+ // Shortcut if browser supports createEvent
1114
+ if ('createEvent' in document) {
1115
+ event = document.createEvent('Event');
1116
+ var bubbles = eventInitDict && eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false;
1117
+ var cancelable = eventInitDict && eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false;
1118
+
1119
+ event.initEvent(type, bubbles, cancelable);
1120
+
1121
+ return event;
1122
+ }
1123
+
1124
+ event = document.createEventObject();
1125
+
1126
+ event.type = type;
1127
+ event.bubbles = eventInitDict && eventInitDict.bubbles !== undefined ? eventInitDict.bubbles : false;
1128
+ event.cancelable = eventInitDict && eventInitDict.cancelable !== undefined ? eventInitDict.cancelable : false;
1129
+
1130
+ return event;
1131
+ };
1132
+ if (existingProto) {
1133
+ Object.defineProperty(window.Event, 'prototype', {
1134
+ configurable: false,
1135
+ enumerable: false,
1136
+ writable: true,
1137
+ value: existingProto
1138
+ });
1139
+ }
1140
+
1141
+ if (!('createEvent' in document)) {
1142
+ window.addEventListener = Window.prototype.addEventListener = Document.prototype.addEventListener = Element.prototype.addEventListener = function addEventListener() {
1143
+ var
1144
+ element = this,
1145
+ type = arguments[0],
1146
+ listener = arguments[1];
1147
+
1148
+ if (element === window && type in unlistenableWindowEvents) {
1149
+ throw new Error('In IE8 the event: ' + type + ' is not available on the window object. Please see https://github.com/Financial-Times/polyfill-service/issues/317 for more information.');
1150
+ }
1151
+
1152
+ if (!element._events) {
1153
+ element._events = {};
1154
+ }
1155
+
1156
+ if (!element._events[type]) {
1157
+ element._events[type] = function (event) {
1158
+ var
1159
+ list = element._events[event.type].list,
1160
+ events = list.slice(),
1161
+ index = -1,
1162
+ length = events.length,
1163
+ eventElement;
1164
+
1165
+ event.preventDefault = function preventDefault() {
1166
+ if (event.cancelable !== false) {
1167
+ event.returnValue = false;
1168
+ }
1169
+ };
1170
+
1171
+ event.stopPropagation = function stopPropagation() {
1172
+ event.cancelBubble = true;
1173
+ };
1174
+
1175
+ event.stopImmediatePropagation = function stopImmediatePropagation() {
1176
+ event.cancelBubble = true;
1177
+ event.cancelImmediate = true;
1178
+ };
1179
+
1180
+ event.currentTarget = element;
1181
+ event.relatedTarget = event.fromElement || null;
1182
+ event.target = event.target || event.srcElement || element;
1183
+ event.timeStamp = new Date().getTime();
1184
+
1185
+ if (event.clientX) {
1186
+ event.pageX = event.clientX + document.documentElement.scrollLeft;
1187
+ event.pageY = event.clientY + document.documentElement.scrollTop;
1188
+ }
1189
+
1190
+ while (++index < length && !event.cancelImmediate) {
1191
+ if (index in events) {
1192
+ eventElement = events[index];
1193
+
1194
+ if (indexOf(list, eventElement) !== -1 && typeof eventElement === 'function') {
1195
+ eventElement.call(element, event);
1196
+ }
1197
+ }
1198
+ }
1199
+ };
1200
+
1201
+ element._events[type].list = [];
1202
+
1203
+ if (element.attachEvent) {
1204
+ element.attachEvent('on' + type, element._events[type]);
1205
+ }
1206
+ }
1207
+
1208
+ element._events[type].list.push(listener);
1209
+ };
1210
+
1211
+ window.removeEventListener = Window.prototype.removeEventListener = Document.prototype.removeEventListener = Element.prototype.removeEventListener = function removeEventListener() {
1212
+ var
1213
+ element = this,
1214
+ type = arguments[0],
1215
+ listener = arguments[1],
1216
+ index;
1217
+
1218
+ if (element._events && element._events[type] && element._events[type].list) {
1219
+ index = indexOf(element._events[type].list, listener);
1220
+
1221
+ if (index !== -1) {
1222
+ element._events[type].list.splice(index, 1);
1223
+
1224
+ if (!element._events[type].list.length) {
1225
+ if (element.detachEvent) {
1226
+ element.detachEvent('on' + type, element._events[type]);
1227
+ }
1228
+ delete element._events[type];
1229
+ }
1230
+ }
1231
+ }
1232
+ };
1233
+
1234
+ window.dispatchEvent = Window.prototype.dispatchEvent = Document.prototype.dispatchEvent = Element.prototype.dispatchEvent = function dispatchEvent(event) {
1235
+ if (!arguments.length) {
1236
+ throw new Error('Not enough arguments');
1237
+ }
1238
+
1239
+ if (!event || typeof event.type !== 'string') {
1240
+ throw new Error('DOM Events Exception 0');
1241
+ }
1242
+
1243
+ var element = this, type = event.type;
1244
+
1245
+ try {
1246
+ if (!event.bubbles) {
1247
+ event.cancelBubble = true;
1248
+
1249
+ var cancelBubbleEvent = function (event) {
1250
+ event.cancelBubble = true;
1251
+
1252
+ (element || window).detachEvent('on' + type, cancelBubbleEvent);
1253
+ };
1254
+
1255
+ this.attachEvent('on' + type, cancelBubbleEvent);
1256
+ }
1257
+
1258
+ this.fireEvent('on' + type, event);
1259
+ } catch (error) {
1260
+ event.target = element;
1261
+
1262
+ do {
1263
+ event.currentTarget = element;
1264
+
1265
+ if ('_events' in element && typeof element._events[type] === 'function') {
1266
+ element._events[type].call(element, event);
1267
+ }
1268
+
1269
+ if (typeof element['on' + type] === 'function') {
1270
+ element['on' + type].call(element, event);
1271
+ }
1272
+
1273
+ element = element.nodeType === 9 ? element.parentWindow : element.parentNode;
1274
+ } while (element && !event.cancelBubble);
1275
+ }
1276
+
1277
+ return true;
1278
+ };
1279
+
1280
+ // Add the DOMContentLoaded Event
1281
+ document.attachEvent('onreadystatechange', function() {
1282
+ if (document.readyState === 'complete') {
1283
+ document.dispatchEvent(new Event('DOMContentLoaded', {
1284
+ bubbles: true
1285
+ }));
1286
+ }
1287
+ });
1288
+ }
1289
+ }());
1290
+
1291
+ })
1292
+ .call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
1293
+
1294
+ /**
1295
+ * JavaScript 'shim' to trigger the click event of element(s) when the space key is pressed.
1296
+ *
1297
+ * Created since some Assistive Technologies (for example some Screenreaders)
1298
+ * will tell a user to press space on a 'button', so this functionality needs to be shimmed
1299
+ * See https://github.com/alphagov/govuk_elements/pull/272#issuecomment-233028270
1300
+ *
1301
+ * Usage instructions:
1302
+ * the 'shim' will be automatically initialised
1303
+ */
1304
+
1305
+ var KEY_SPACE = 32;
1306
+ var DEBOUNCE_TIMEOUT_IN_SECONDS = 1;
1307
+ var debounceFormSubmitTimer = null;
1308
+
1309
+ function Button ($module) {
1310
+ this.$module = $module;
1311
+ }
1312
+
1313
+ /**
1314
+ * if the event target element has a role='button' and the event is key space pressed
1315
+ * then it prevents the default event and triggers a click event
1316
+ * @param {object} event event
1317
+ */
1318
+ Button.prototype.handleKeyDown = function (event) {
1319
+ // get the target element
1320
+ var target = event.target;
1321
+ // if the element has a role='button' and the pressed key is a space, we'll simulate a click
1322
+ if (target.getAttribute('role') === 'button' && event.keyCode === KEY_SPACE) {
1323
+ event.preventDefault();
1324
+ // trigger the target's click event
1325
+ target.click();
1326
+ }
1327
+ };
1328
+
1329
+ /**
1330
+ * If the click quickly succeeds a previous click then nothing will happen.
1331
+ * This stops people accidentally causing multiple form submissions by
1332
+ * double clicking buttons.
1333
+ */
1334
+ Button.prototype.debounce = function (event) {
1335
+ var target = event.target;
1336
+ // Check the button that is clicked on has the preventDoubleClick feature enabled
1337
+ if (target.getAttribute('data-prevent-double-click') !== 'true') {
1338
+ return
1339
+ }
1340
+
1341
+ // If the timer is still running then we want to prevent the click from submitting the form
1342
+ if (debounceFormSubmitTimer) {
1343
+ event.preventDefault();
1344
+ return false
1345
+ }
1346
+
1347
+ debounceFormSubmitTimer = setTimeout(function () {
1348
+ debounceFormSubmitTimer = null;
1349
+ }, DEBOUNCE_TIMEOUT_IN_SECONDS * 1000);
1350
+ };
1351
+
1352
+ /**
1353
+ * Initialise an event listener for keydown at document level
1354
+ * this will help listening for later inserted elements with a role="button"
1355
+ */
1356
+ Button.prototype.init = function () {
1357
+ this.$module.addEventListener('keydown', this.handleKeyDown);
1358
+ this.$module.addEventListener('click', this.debounce);
1359
+ };
1360
+
1361
+ /**
1362
+ * JavaScript 'polyfill' for HTML5's <details> and <summary> elements
1363
+ * and 'shim' to add accessiblity enhancements for all browsers
1364
+ *
1365
+ * http://caniuse.com/#feat=details
1366
+ *
1367
+ * Usage instructions:
1368
+ * the 'polyfill' will be automatically initialised
1369
+ */
1370
+
1371
+ var KEY_ENTER = 13;
1372
+ var KEY_SPACE$1 = 32;
1373
+
1374
+ // Create a flag to know if the browser supports navtive details
1375
+ var NATIVE_DETAILS = typeof document.createElement('details').open === 'boolean';
1376
+
1377
+ function Details ($module) {
1378
+ this.$module = $module;
1379
+ }
1380
+
1381
+ /**
1382
+ * Handle cross-modal click events
1383
+ * @param {object} node element
1384
+ * @param {function} callback function
1385
+ */
1386
+ Details.prototype.handleInputs = function (node, callback) {
1387
+ node.addEventListener('keypress', function (event) {
1388
+ var target = event.target;
1389
+ // When the key gets pressed - check if it is enter or space
1390
+ if (event.keyCode === KEY_ENTER || event.keyCode === KEY_SPACE$1) {
1391
+ if (target.nodeName.toLowerCase() === 'summary') {
1392
+ // Prevent space from scrolling the page
1393
+ // and enter from submitting a form
1394
+ event.preventDefault();
1395
+ // Click to let the click event do all the necessary action
1396
+ if (target.click) {
1397
+ target.click();
1398
+ } else {
1399
+ // except Safari 5.1 and under don't support .click() here
1400
+ callback(event);
1401
+ }
1402
+ }
1403
+ }
1404
+ });
1405
+
1406
+ // Prevent keyup to prevent clicking twice in Firefox when using space key
1407
+ node.addEventListener('keyup', function (event) {
1408
+ var target = event.target;
1409
+ if (event.keyCode === KEY_SPACE$1) {
1410
+ if (target.nodeName.toLowerCase() === 'summary') {
1411
+ event.preventDefault();
1412
+ }
1413
+ }
1414
+ });
1415
+
1416
+ node.addEventListener('click', callback);
1417
+ };
1418
+
1419
+ Details.prototype.init = function () {
1420
+ var $module = this.$module;
1421
+
1422
+ if (!$module) {
1423
+ return
1424
+ }
1425
+
1426
+ // Save shortcuts to the inner summary and content elements
1427
+ var $summary = this.$summary = $module.getElementsByTagName('summary').item(0);
1428
+ var $content = this.$content = $module.getElementsByTagName('div').item(0);
1429
+
1430
+ // If <details> doesn't have a <summary> and a <div> representing the content
1431
+ // it means the required HTML structure is not met so the script will stop
1432
+ if (!$summary || !$content) {
1433
+ return
1434
+ }
1435
+
1436
+ // If the content doesn't have an ID, assign it one now
1437
+ // which we'll need for the summary's aria-controls assignment
1438
+ if (!$content.id) {
1439
+ $content.id = 'details-content-' + generateUniqueID();
1440
+ }
1441
+
1442
+ // Add ARIA role="group" to details
1443
+ $module.setAttribute('role', 'group');
1444
+
1445
+ // Add role=button to summary
1446
+ $summary.setAttribute('role', 'button');
1447
+
1448
+ // Add aria-controls
1449
+ $summary.setAttribute('aria-controls', $content.id);
1450
+
1451
+ // Set tabIndex so the summary is keyboard accessible for non-native elements
1452
+ // http://www.saliences.com/browserBugs/tabIndex.html
1453
+ if (!NATIVE_DETAILS) {
1454
+ $summary.tabIndex = 0;
1455
+ }
1456
+
1457
+ // Detect initial open state
1458
+ var openAttr = $module.getAttribute('open') !== null;
1459
+ if (openAttr === true) {
1460
+ $summary.setAttribute('aria-expanded', 'true');
1461
+ $content.setAttribute('aria-hidden', 'false');
1462
+ } else {
1463
+ $summary.setAttribute('aria-expanded', 'false');
1464
+ $content.setAttribute('aria-hidden', 'true');
1465
+ if (!NATIVE_DETAILS) {
1466
+ $content.style.display = 'none';
1467
+ }
1468
+ }
1469
+
1470
+ // Bind an event to handle summary elements
1471
+ this.handleInputs($summary, this.setAttributes.bind(this));
1472
+ };
1473
+
1474
+ /**
1475
+ * Define a statechange function that updates aria-expanded and style.display
1476
+ * @param {object} summary element
1477
+ */
1478
+ Details.prototype.setAttributes = function () {
1479
+ var $module = this.$module;
1480
+ var $summary = this.$summary;
1481
+ var $content = this.$content;
1482
+
1483
+ var expanded = $summary.getAttribute('aria-expanded') === 'true';
1484
+ var hidden = $content.getAttribute('aria-hidden') === 'true';
1485
+
1486
+ $summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'));
1487
+ $content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'));
1488
+
1489
+ if (!NATIVE_DETAILS) {
1490
+ $content.style.display = (expanded ? 'none' : '');
1491
+
1492
+ var hasOpenAttr = $module.getAttribute('open') !== null;
1493
+ if (!hasOpenAttr) {
1494
+ $module.setAttribute('open', 'open');
1495
+ } else {
1496
+ $module.removeAttribute('open');
1497
+ }
1498
+ }
1499
+ return true
1500
+ };
1501
+
1502
+ /**
1503
+ * Remove the click event from the node element
1504
+ * @param {object} node element
1505
+ */
1506
+ Details.prototype.destroy = function (node) {
1507
+ node.removeEventListener('keypress');
1508
+ node.removeEventListener('keyup');
1509
+ node.removeEventListener('click');
1510
+ };
1511
+
1512
+ function CharacterCount ($module) {
1513
+ this.$module = $module;
1514
+ this.$textarea = $module.querySelector('.js-character-count');
1515
+ }
1516
+
1517
+ CharacterCount.prototype.defaults = {
1518
+ characterCountAttribute: 'data-maxlength',
1519
+ wordCountAttribute: 'data-maxwords'
1520
+ };
1521
+
1522
+ // Initialize component
1523
+ CharacterCount.prototype.init = function () {
1524
+ // Check for module
1525
+ var $module = this.$module;
1526
+ var $textarea = this.$textarea;
1527
+ if (!$textarea) {
1528
+ return
1529
+ }
1530
+
1531
+ // Read options set using dataset ('data-' values)
1532
+ this.options = this.getDataset($module);
1533
+
1534
+ // Determine the limit attribute (characters or words)
1535
+ var countAttribute = this.defaults.characterCountAttribute;
1536
+ if (this.options.maxwords) {
1537
+ countAttribute = this.defaults.wordCountAttribute;
1538
+ }
1539
+
1540
+ // Save the element limit
1541
+ this.maxLength = $module.getAttribute(countAttribute);
1542
+
1543
+ // Check for limit
1544
+ if (!this.maxLength) {
1545
+ return
1546
+ }
1547
+
1548
+ // Generate and reference message
1549
+ var boundCreateCountMessage = this.createCountMessage.bind(this);
1550
+ this.countMessage = boundCreateCountMessage();
1551
+
1552
+ // If there's a maximum length defined and the count message exists
1553
+ if (this.countMessage) {
1554
+ // Remove hard limit if set
1555
+ $module.removeAttribute('maxlength');
1556
+
1557
+ // Bind event changes to the textarea
1558
+ var boundChangeEvents = this.bindChangeEvents.bind(this);
1559
+ boundChangeEvents();
1560
+
1561
+ // Update count message
1562
+ var boundUpdateCountMessage = this.updateCountMessage.bind(this);
1563
+ boundUpdateCountMessage();
1564
+ }
1565
+ };
1566
+
1567
+ // Read data attributes
1568
+ CharacterCount.prototype.getDataset = function (element) {
1569
+ var dataset = {};
1570
+ var attributes = element.attributes;
1571
+ if (attributes) {
1572
+ for (var i = 0; i < attributes.length; i++) {
1573
+ var attribute = attributes[i];
1574
+ var match = attribute.name.match(/^data-(.+)/);
1575
+ if (match) {
1576
+ dataset[match[1]] = attribute.value;
1577
+ }
1578
+ }
1579
+ }
1580
+ return dataset
1581
+ };
1582
+
1583
+ // Counts characters or words in text
1584
+ CharacterCount.prototype.count = function (text) {
1585
+ var length;
1586
+ if (this.options.maxwords) {
1587
+ var tokens = text.match(/\S+/g) || []; // Matches consecutive non-whitespace chars
1588
+ length = tokens.length;
1589
+ } else {
1590
+ length = text.length;
1591
+ }
1592
+ return length
1593
+ };
1594
+
1595
+ // Generate count message and bind it to the input
1596
+ // returns reference to the generated element
1597
+ CharacterCount.prototype.createCountMessage = function () {
1598
+ var countElement = this.$textarea;
1599
+ var elementId = countElement.id;
1600
+ // Check for existing info count message
1601
+ var countMessage = document.getElementById(elementId + '-info');
1602
+ // If there is no existing info count message we add one right after the field
1603
+ if (elementId && !countMessage) {
1604
+ countElement.insertAdjacentHTML('afterend', '<span id="' + elementId + '-info" class="govuk-hint govuk-character-count__message" aria-live="polite"></span>');
1605
+ this.describedBy = countElement.getAttribute('aria-describedby');
1606
+ this.describedByInfo = this.describedBy + ' ' + elementId + '-info';
1607
+ countElement.setAttribute('aria-describedby', this.describedByInfo);
1608
+ countMessage = document.getElementById(elementId + '-info');
1609
+ } else {
1610
+ // If there is an existing info count message we move it right after the field
1611
+ countElement.insertAdjacentElement('afterend', countMessage);
1612
+ }
1613
+ return countMessage
1614
+ };
1615
+
1616
+ // Bind input propertychange to the elements and update based on the change
1617
+ CharacterCount.prototype.bindChangeEvents = function () {
1618
+ var $textarea = this.$textarea;
1619
+ $textarea.addEventListener('keyup', this.checkIfValueChanged.bind(this));
1620
+
1621
+ // Bind focus/blur events to start/stop polling
1622
+ $textarea.addEventListener('focus', this.handleFocus.bind(this));
1623
+ $textarea.addEventListener('blur', this.handleBlur.bind(this));
1624
+ };
1625
+
1626
+ // Speech recognition software such as Dragon NaturallySpeaking will modify the
1627
+ // fields by directly changing its `value`. These changes don't trigger events
1628
+ // in JavaScript, so we need to poll to handle when and if they occur.
1629
+ CharacterCount.prototype.checkIfValueChanged = function () {
1630
+ if (!this.$textarea.oldValue) this.$textarea.oldValue = '';
1631
+ if (this.$textarea.value !== this.$textarea.oldValue) {
1632
+ this.$textarea.oldValue = this.$textarea.value;
1633
+ var boundUpdateCountMessage = this.updateCountMessage.bind(this);
1634
+ boundUpdateCountMessage();
1635
+ }
1636
+ };
1637
+
1638
+ // Update message box
1639
+ CharacterCount.prototype.updateCountMessage = function () {
1640
+ var countElement = this.$textarea;
1641
+ var options = this.options;
1642
+ var countMessage = this.countMessage;
1643
+
1644
+ // Determine the remaining number of characters/words
1645
+ var currentLength = this.count(countElement.value);
1646
+ var maxLength = this.maxLength;
1647
+ var remainingNumber = maxLength - currentLength;
1648
+
1649
+ // Set threshold if presented in options
1650
+ var thresholdPercent = options.threshold ? options.threshold : 0;
1651
+ var thresholdValue = maxLength * thresholdPercent / 100;
1652
+ if (thresholdValue > currentLength) {
1653
+ countMessage.classList.add('govuk-character-count__message--disabled');
1654
+ } else {
1655
+ countMessage.classList.remove('govuk-character-count__message--disabled');
1656
+ }
1657
+
1658
+ // Update styles
1659
+ if (remainingNumber < 0) {
1660
+ countElement.classList.add('govuk-textarea--error');
1661
+ countMessage.classList.remove('govuk-hint');
1662
+ countMessage.classList.add('govuk-error-message');
1663
+ } else {
1664
+ countElement.classList.remove('govuk-textarea--error');
1665
+ countMessage.classList.remove('govuk-error-message');
1666
+ countMessage.classList.add('govuk-hint');
1667
+ }
1668
+
1669
+ // Update message
1670
+ var charVerb = 'remaining';
1671
+ var charNoun = 'character';
1672
+ var displayNumber = remainingNumber;
1673
+ if (options.maxwords) {
1674
+ charNoun = 'word';
1675
+ }
1676
+ charNoun = charNoun + ((remainingNumber === -1 || remainingNumber === 1) ? '' : 's');
1677
+
1678
+ charVerb = (remainingNumber < 0) ? 'too many' : 'remaining';
1679
+ displayNumber = Math.abs(remainingNumber);
1680
+
1681
+ countMessage.innerHTML = 'You have ' + displayNumber + ' ' + charNoun + ' ' + charVerb;
1682
+ };
1683
+
1684
+ CharacterCount.prototype.handleFocus = function () {
1685
+ // Check if value changed on focus
1686
+ this.valueChecker = setInterval(this.checkIfValueChanged.bind(this), 1000);
1687
+ };
1688
+
1689
+ CharacterCount.prototype.handleBlur = function () {
1690
+ // Cancel value checking on blur
1691
+ clearInterval(this.valueChecker);
1692
+ };
1693
+
1694
+ function Checkboxes ($module) {
1695
+ this.$module = $module;
1696
+ this.$inputs = $module.querySelectorAll('input[type="checkbox"]');
1697
+ }
1698
+
1699
+ Checkboxes.prototype.init = function () {
1700
+ var $module = this.$module;
1701
+ var $inputs = this.$inputs;
1702
+
1703
+ /**
1704
+ * Loop over all items with [data-controls]
1705
+ * Check if they have a matching conditional reveal
1706
+ * If they do, assign attributes.
1707
+ **/
1708
+ nodeListForEach($inputs, function ($input) {
1709
+ var controls = $input.getAttribute('data-aria-controls');
1710
+
1711
+ // Check if input controls anything
1712
+ // Check if content exists, before setting attributes.
1713
+ if (!controls || !$module.querySelector('#' + controls)) {
1714
+ return
1715
+ }
1716
+
1717
+ // If we have content that is controlled, set attributes.
1718
+ $input.setAttribute('aria-controls', controls);
1719
+ $input.removeAttribute('data-aria-controls');
1720
+ this.setAttributes($input);
1721
+ }.bind(this));
1722
+
1723
+ // Handle events
1724
+ $module.addEventListener('click', this.handleClick.bind(this));
1725
+ };
1726
+
1727
+ Checkboxes.prototype.setAttributes = function ($input) {
1728
+ var inputIsChecked = $input.checked;
1729
+ $input.setAttribute('aria-expanded', inputIsChecked);
1730
+
1731
+ var $content = this.$module.querySelector('#' + $input.getAttribute('aria-controls'));
1732
+ if ($content) {
1733
+ $content.classList.toggle('govuk-checkboxes__conditional--hidden', !inputIsChecked);
1734
+ }
1735
+ };
1736
+
1737
+ Checkboxes.prototype.handleClick = function (event) {
1738
+ var $target = event.target;
1739
+
1740
+ // If a checkbox with aria-controls, handle click
1741
+ var isCheckbox = $target.getAttribute('type') === 'checkbox';
1742
+ var hasAriaControls = $target.getAttribute('aria-controls');
1743
+ if (isCheckbox && hasAriaControls) {
1744
+ this.setAttributes($target);
1745
+ }
1746
+ };
1747
+
1748
+ (function(undefined) {
1749
+
1750
+ // Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/1f3c09b402f65bf6e393f933a15ba63f1b86ef1f/packages/polyfill-library/polyfills/Element/prototype/matches/detect.js
1751
+ var detect = (
1752
+ 'document' in this && "matches" in document.documentElement
1753
+ );
1754
+
1755
+ if (detect) return
1756
+
1757
+ // Polyfill from https://raw.githubusercontent.com/Financial-Times/polyfill-service/1f3c09b402f65bf6e393f933a15ba63f1b86ef1f/packages/polyfill-library/polyfills/Element/prototype/matches/polyfill.js
1758
+ Element.prototype.matches = Element.prototype.webkitMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || function matches(selector) {
1759
+ var element = this;
1760
+ var elements = (element.document || element.ownerDocument).querySelectorAll(selector);
1761
+ var index = 0;
1762
+
1763
+ while (elements[index] && elements[index] !== element) {
1764
+ ++index;
1765
+ }
1766
+
1767
+ return !!elements[index];
1768
+ };
1769
+
1770
+ }).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
1771
+
1772
+ (function(undefined) {
1773
+
1774
+ // Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/1f3c09b402f65bf6e393f933a15ba63f1b86ef1f/packages/polyfill-library/polyfills/Element/prototype/closest/detect.js
1775
+ var detect = (
1776
+ 'document' in this && "closest" in document.documentElement
1777
+ );
1778
+
1779
+ if (detect) return
1780
+
1781
+ // Polyfill from https://raw.githubusercontent.com/Financial-Times/polyfill-service/1f3c09b402f65bf6e393f933a15ba63f1b86ef1f/packages/polyfill-library/polyfills/Element/prototype/closest/polyfill.js
1782
+ Element.prototype.closest = function closest(selector) {
1783
+ var node = this;
1784
+
1785
+ while (node) {
1786
+ if (node.matches(selector)) return node;
1787
+ else node = 'SVGElement' in window && node instanceof SVGElement ? node.parentNode : node.parentElement;
1788
+ }
1789
+
1790
+ return null;
1791
+ };
1792
+
1793
+ }).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
1794
+
1795
+ function ErrorSummary ($module) {
1796
+ this.$module = $module;
1797
+ }
1798
+
1799
+ ErrorSummary.prototype.init = function () {
1800
+ var $module = this.$module;
1801
+ if (!$module) {
1802
+ return
1803
+ }
1804
+ $module.focus();
1805
+
1806
+ $module.addEventListener('click', this.handleClick.bind(this));
1807
+ };
1808
+
1809
+ /**
1810
+ * Click event handler
1811
+ *
1812
+ * @param {MouseEvent} event - Click event
1813
+ */
1814
+ ErrorSummary.prototype.handleClick = function (event) {
1815
+ var target = event.target;
1816
+ if (this.focusTarget(target)) {
1817
+ event.preventDefault();
1818
+ }
1819
+ };
1820
+
1821
+ /**
1822
+ * Focus the target element
1823
+ *
1824
+ * By default, the browser will scroll the target into view. Because our labels
1825
+ * or legends appear above the input, this means the user will be presented with
1826
+ * an input without any context, as the label or legend will be off the top of
1827
+ * the screen.
1828
+ *
1829
+ * Manually handling the click event, scrolling the question into view and then
1830
+ * focussing the element solves this.
1831
+ *
1832
+ * This also results in the label and/or legend being announced correctly in
1833
+ * NVDA (as tested in 2018.3.2) - without this only the field type is announced
1834
+ * (e.g. "Edit, has autocomplete").
1835
+ *
1836
+ * @param {HTMLElement} $target - Event target
1837
+ * @returns {boolean} True if the target was able to be focussed
1838
+ */
1839
+ ErrorSummary.prototype.focusTarget = function ($target) {
1840
+ // If the element that was clicked was not a link, return early
1841
+ if ($target.tagName !== 'A' || $target.href === false) {
1842
+ return false
1843
+ }
1844
+
1845
+ var inputId = this.getFragmentFromUrl($target.href);
1846
+ var $input = document.getElementById(inputId);
1847
+ if (!$input) {
1848
+ return false
1849
+ }
1850
+
1851
+ var $legendOrLabel = this.getAssociatedLegendOrLabel($input);
1852
+ if (!$legendOrLabel) {
1853
+ return false
1854
+ }
1855
+
1856
+ // Prefer using the history API where possible, as updating
1857
+ // window.location.hash causes the viewport to jump to the input briefly
1858
+ // before then scrolling to the label/legend in IE10, IE11 and Edge (as tested
1859
+ // in Edge 17).
1860
+ if (window.history.pushState) {
1861
+ window.history.pushState(null, null, '#' + inputId);
1862
+ } else {
1863
+ window.location.hash = inputId;
1864
+ }
1865
+
1866
+ // Scroll the legend or label into view *before* calling focus on the input to
1867
+ // avoid extra scrolling in browsers that don't support `preventScroll` (which
1868
+ // at time of writing is most of them...)
1869
+ $legendOrLabel.scrollIntoView();
1870
+ $input.focus({ preventScroll: true });
1871
+
1872
+ return true
1873
+ };
1874
+
1875
+ /**
1876
+ * Get fragment from URL
1877
+ *
1878
+ * Extract the fragment (everything after the hash) from a URL, but not including
1879
+ * the hash.
1880
+ *
1881
+ * @param {string} url - URL
1882
+ * @returns {string} Fragment from URL, without the hash
1883
+ */
1884
+ ErrorSummary.prototype.getFragmentFromUrl = function (url) {
1885
+ if (url.indexOf('#') === -1) {
1886
+ return false
1887
+ }
1888
+
1889
+ return url.split('#').pop()
1890
+ };
1891
+
1892
+ /**
1893
+ * Get associated legend or label
1894
+ *
1895
+ * Returns the first element that exists from this list:
1896
+ *
1897
+ * - The `<legend>` associated with the closest `<fieldset>` ancestor
1898
+ * - The first `<label>` that is associated with the input using for="inputId"
1899
+ * - The closest parent `<label>`
1900
+ *
1901
+ * @param {HTMLElement} $input - The input
1902
+ * @returns {HTMLElement} Associated legend or label, or null if no associated
1903
+ * legend or label can be found
1904
+ */
1905
+ ErrorSummary.prototype.getAssociatedLegendOrLabel = function ($input) {
1906
+ var $fieldset = $input.closest('fieldset');
1907
+
1908
+ if ($fieldset) {
1909
+ var legends = $fieldset.getElementsByTagName('legend');
1910
+
1911
+ if (legends.length) {
1912
+ return legends[0]
1913
+ }
1914
+ }
1915
+
1916
+ return document.querySelector("label[for='" + $input.getAttribute('id') + "']") ||
1917
+ $input.closest('label')
1918
+ };
1919
+
1920
+ function Header ($module) {
1921
+ this.$module = $module;
1922
+ }
1923
+
1924
+ Header.prototype.init = function () {
1925
+ // Check for module
1926
+ var $module = this.$module;
1927
+ if (!$module) {
1928
+ return
1929
+ }
1930
+
1931
+ // Check for button
1932
+ var $toggleButton = $module.querySelector('.js-header-toggle');
1933
+ if (!$toggleButton) {
1934
+ return
1935
+ }
1936
+
1937
+ // Handle $toggleButton click events
1938
+ $toggleButton.addEventListener('click', this.handleClick.bind(this));
1939
+ };
1940
+
1941
+ /**
1942
+ * Toggle class
1943
+ * @param {object} node element
1944
+ * @param {string} className to toggle
1945
+ */
1946
+ Header.prototype.toggleClass = function (node, className) {
1947
+ if (node.className.indexOf(className) > 0) {
1948
+ node.className = node.className.replace(' ' + className, '');
1949
+ } else {
1950
+ node.className += ' ' + className;
1951
+ }
1952
+ };
1953
+
1954
+ /**
1955
+ * An event handler for click event on $toggleButton
1956
+ * @param {object} event event
1957
+ */
1958
+ Header.prototype.handleClick = function (event) {
1959
+ var $module = this.$module;
1960
+ var $toggleButton = event.target || event.srcElement;
1961
+ var $target = $module.querySelector('#' + $toggleButton.getAttribute('aria-controls'));
1962
+
1963
+ // If a button with aria-controls, handle click
1964
+ if ($toggleButton && $target) {
1965
+ this.toggleClass($target, 'govuk-header__navigation--open');
1966
+ this.toggleClass($toggleButton, 'govuk-header__menu-button--open');
1967
+
1968
+ $toggleButton.setAttribute('aria-expanded', $toggleButton.getAttribute('aria-expanded') !== 'true');
1969
+ $target.setAttribute('aria-hidden', $target.getAttribute('aria-hidden') === 'false');
1970
+ }
1971
+ };
1972
+
1973
+ function Radios ($module) {
1974
+ this.$module = $module;
1975
+ this.$inputs = $module.querySelectorAll('input[type="radio"]');
1976
+ }
1977
+
1978
+ Radios.prototype.init = function () {
1979
+ var $module = this.$module;
1980
+ var $inputs = this.$inputs;
1981
+
1982
+ /**
1983
+ * Loop over all items with [data-controls]
1984
+ * Check if they have a matching conditional reveal
1985
+ * If they do, assign attributes.
1986
+ **/
1987
+ nodeListForEach($inputs, function ($input) {
1988
+ var controls = $input.getAttribute('data-aria-controls');
1989
+
1990
+ // Check if input controls anything
1991
+ // Check if content exists, before setting attributes.
1992
+ if (!controls || !$module.querySelector('#' + controls)) {
1993
+ return
1994
+ }
1995
+
1996
+ // If we have content that is controlled, set attributes.
1997
+ $input.setAttribute('aria-controls', controls);
1998
+ $input.removeAttribute('data-aria-controls');
1999
+ this.setAttributes($input);
2000
+ }.bind(this));
2001
+
2002
+ // Handle events
2003
+ $module.addEventListener('click', this.handleClick.bind(this));
2004
+ };
2005
+
2006
+ Radios.prototype.setAttributes = function ($input) {
2007
+ var inputIsChecked = $input.checked;
2008
+ $input.setAttribute('aria-expanded', inputIsChecked);
2009
+
2010
+ var $content = this.$module.querySelector('#' + $input.getAttribute('aria-controls'));
2011
+ if ($content) {
2012
+ $content.classList.toggle('govuk-radios__conditional--hidden', !inputIsChecked);
2013
+ }
2014
+ };
2015
+
2016
+ Radios.prototype.handleClick = function (event) {
2017
+ nodeListForEach(this.$inputs, function ($input) {
2018
+ // If a radio with aria-controls, handle click
2019
+ var isRadio = $input.getAttribute('type') === 'radio';
2020
+ var hasAriaControls = $input.getAttribute('aria-controls');
2021
+ if (isRadio && hasAriaControls) {
2022
+ this.setAttributes($input);
2023
+ }
2024
+ }.bind(this));
2025
+ };
2026
+
2027
+ function Tabs ($module) {
2028
+ this.$module = $module;
2029
+ this.$tabs = $module.querySelectorAll('.govuk-tabs__tab');
2030
+
2031
+ this.keys = { left: 37, right: 39, up: 38, down: 40 };
2032
+ this.jsHiddenClass = 'govuk-tabs__panel--hidden';
2033
+ }
2034
+
2035
+ Tabs.prototype.init = function () {
2036
+ if (typeof window.matchMedia === 'function') {
2037
+ this.setupResponsiveChecks();
2038
+ } else {
2039
+ this.setup();
2040
+ }
2041
+ };
2042
+
2043
+ Tabs.prototype.setupResponsiveChecks = function () {
2044
+ this.mql = window.matchMedia('(min-width: 40.0625em)');
2045
+ this.mql.addListener(this.checkMode.bind(this));
2046
+ this.checkMode();
2047
+ };
2048
+
2049
+ Tabs.prototype.checkMode = function () {
2050
+ if (this.mql.matches) {
2051
+ this.setup();
2052
+ } else {
2053
+ this.teardown();
2054
+ }
2055
+ };
2056
+
2057
+ Tabs.prototype.setup = function () {
2058
+ var $module = this.$module;
2059
+ var $tabs = this.$tabs;
2060
+ var $tabList = $module.querySelector('.govuk-tabs__list');
2061
+ var $tabListItems = $module.querySelectorAll('.govuk-tabs__list-item');
2062
+
2063
+ if (!$tabs || !$tabList || !$tabListItems) {
2064
+ return
2065
+ }
2066
+
2067
+ $tabList.setAttribute('role', 'tablist');
2068
+
2069
+ nodeListForEach($tabListItems, function ($item) {
2070
+ $item.setAttribute('role', 'presentation');
2071
+ });
2072
+
2073
+ nodeListForEach($tabs, function ($tab) {
2074
+ // Set HTML attributes
2075
+ this.setAttributes($tab);
2076
+
2077
+ // Save bounded functions to use when removing event listeners during teardown
2078
+ $tab.boundTabClick = this.onTabClick.bind(this);
2079
+ $tab.boundTabKeydown = this.onTabKeydown.bind(this);
2080
+
2081
+ // Handle events
2082
+ $tab.addEventListener('click', $tab.boundTabClick, true);
2083
+ $tab.addEventListener('keydown', $tab.boundTabKeydown, true);
2084
+
2085
+ // Remove old active panels
2086
+ this.hideTab($tab);
2087
+ }.bind(this));
2088
+
2089
+ // Show either the active tab according to the URL's hash or the first tab
2090
+ var $activeTab = this.getTab(window.location.hash) || this.$tabs[0];
2091
+ this.showTab($activeTab);
2092
+
2093
+ // Handle hashchange events
2094
+ $module.boundOnHashChange = this.onHashChange.bind(this);
2095
+ window.addEventListener('hashchange', $module.boundOnHashChange, true);
2096
+ };
2097
+
2098
+ Tabs.prototype.teardown = function () {
2099
+ var $module = this.$module;
2100
+ var $tabs = this.$tabs;
2101
+ var $tabList = $module.querySelector('.govuk-tabs__list');
2102
+ var $tabListItems = $module.querySelectorAll('.govuk-tabs__list-item');
2103
+
2104
+ if (!$tabs || !$tabList || !$tabListItems) {
2105
+ return
2106
+ }
2107
+
2108
+ $tabList.removeAttribute('role');
2109
+
2110
+ nodeListForEach($tabListItems, function ($item) {
2111
+ $item.removeAttribute('role', 'presentation');
2112
+ });
2113
+
2114
+ nodeListForEach($tabs, function ($tab) {
2115
+ // Remove events
2116
+ $tab.removeEventListener('click', $tab.boundTabClick, true);
2117
+ $tab.removeEventListener('keydown', $tab.boundTabKeydown, true);
2118
+
2119
+ // Unset HTML attributes
2120
+ this.unsetAttributes($tab);
2121
+ }.bind(this));
2122
+
2123
+ // Remove hashchange event handler
2124
+ window.removeEventListener('hashchange', $module.boundOnHashChange, true);
2125
+ };
2126
+
2127
+ Tabs.prototype.onHashChange = function (e) {
2128
+ var hash = window.location.hash;
2129
+ var $tabWithHash = this.getTab(hash);
2130
+ if (!$tabWithHash) {
2131
+ return
2132
+ }
2133
+
2134
+ // Prevent changing the hash
2135
+ if (this.changingHash) {
2136
+ this.changingHash = false;
2137
+ return
2138
+ }
2139
+
2140
+ // Show either the active tab according to the URL's hash or the first tab
2141
+ var $previousTab = this.getCurrentTab();
2142
+
2143
+ this.hideTab($previousTab);
2144
+ this.showTab($tabWithHash);
2145
+ $tabWithHash.focus();
2146
+ };
2147
+
2148
+ Tabs.prototype.hideTab = function ($tab) {
2149
+ this.unhighlightTab($tab);
2150
+ this.hidePanel($tab);
2151
+ };
2152
+
2153
+ Tabs.prototype.showTab = function ($tab) {
2154
+ this.highlightTab($tab);
2155
+ this.showPanel($tab);
2156
+ };
2157
+
2158
+ Tabs.prototype.getTab = function (hash) {
2159
+ return this.$module.querySelector('.govuk-tabs__tab[href="' + hash + '"]')
2160
+ };
2161
+
2162
+ Tabs.prototype.setAttributes = function ($tab) {
2163
+ // set tab attributes
2164
+ var panelId = this.getHref($tab).slice(1);
2165
+ $tab.setAttribute('id', 'tab_' + panelId);
2166
+ $tab.setAttribute('role', 'tab');
2167
+ $tab.setAttribute('aria-controls', panelId);
2168
+ $tab.setAttribute('tabindex', '-1');
2169
+
2170
+ // set panel attributes
2171
+ var $panel = this.getPanel($tab);
2172
+ $panel.setAttribute('role', 'tabpanel');
2173
+ $panel.setAttribute('aria-labelledby', $tab.id);
2174
+ $panel.classList.add(this.jsHiddenClass);
2175
+ };
2176
+
2177
+ Tabs.prototype.unsetAttributes = function ($tab) {
2178
+ // unset tab attributes
2179
+ $tab.removeAttribute('id');
2180
+ $tab.removeAttribute('role');
2181
+ $tab.removeAttribute('aria-controls');
2182
+ $tab.removeAttribute('tabindex');
2183
+
2184
+ // unset panel attributes
2185
+ var $panel = this.getPanel($tab);
2186
+ $panel.removeAttribute('role');
2187
+ $panel.removeAttribute('aria-labelledby');
2188
+ $panel.classList.remove(this.jsHiddenClass);
2189
+ };
2190
+
2191
+ Tabs.prototype.onTabClick = function (e) {
2192
+ e.preventDefault();
2193
+ var $newTab = e.target;
2194
+ var $currentTab = this.getCurrentTab();
2195
+ this.hideTab($currentTab);
2196
+ this.showTab($newTab);
2197
+ this.createHistoryEntry($newTab);
2198
+ };
2199
+
2200
+ Tabs.prototype.createHistoryEntry = function ($tab) {
2201
+ var $panel = this.getPanel($tab);
2202
+
2203
+ // Save and restore the id
2204
+ // so the page doesn't jump when a user clicks a tab (which changes the hash)
2205
+ var id = $panel.id;
2206
+ $panel.id = '';
2207
+ this.changingHash = true;
2208
+ window.location.hash = this.getHref($tab).slice(1);
2209
+ $panel.id = id;
2210
+ };
2211
+
2212
+ Tabs.prototype.onTabKeydown = function (e) {
2213
+ switch (e.keyCode) {
2214
+ case this.keys.left:
2215
+ case this.keys.up:
2216
+ this.activatePreviousTab();
2217
+ e.preventDefault();
2218
+ break
2219
+ case this.keys.right:
2220
+ case this.keys.down:
2221
+ this.activateNextTab();
2222
+ e.preventDefault();
2223
+ break
2224
+ }
2225
+ };
2226
+
2227
+ Tabs.prototype.activateNextTab = function () {
2228
+ var currentTab = this.getCurrentTab();
2229
+ var nextTabListItem = currentTab.parentNode.nextElementSibling;
2230
+ if (nextTabListItem) {
2231
+ var nextTab = nextTabListItem.firstElementChild;
2232
+ }
2233
+ if (nextTab) {
2234
+ this.hideTab(currentTab);
2235
+ this.showTab(nextTab);
2236
+ nextTab.focus();
2237
+ this.createHistoryEntry(nextTab);
2238
+ }
2239
+ };
2240
+
2241
+ Tabs.prototype.activatePreviousTab = function () {
2242
+ var currentTab = this.getCurrentTab();
2243
+ var previousTabListItem = currentTab.parentNode.previousElementSibling;
2244
+ if (previousTabListItem) {
2245
+ var previousTab = previousTabListItem.firstElementChild;
2246
+ }
2247
+ if (previousTab) {
2248
+ this.hideTab(currentTab);
2249
+ this.showTab(previousTab);
2250
+ previousTab.focus();
2251
+ this.createHistoryEntry(previousTab);
2252
+ }
2253
+ };
2254
+
2255
+ Tabs.prototype.getPanel = function ($tab) {
2256
+ var $panel = this.$module.querySelector(this.getHref($tab));
2257
+ return $panel
2258
+ };
2259
+
2260
+ Tabs.prototype.showPanel = function ($tab) {
2261
+ var $panel = this.getPanel($tab);
2262
+ $panel.classList.remove(this.jsHiddenClass);
2263
+ };
2264
+
2265
+ Tabs.prototype.hidePanel = function (tab) {
2266
+ var $panel = this.getPanel(tab);
2267
+ $panel.classList.add(this.jsHiddenClass);
2268
+ };
2269
+
2270
+ Tabs.prototype.unhighlightTab = function ($tab) {
2271
+ $tab.setAttribute('aria-selected', 'false');
2272
+ $tab.classList.remove('govuk-tabs__tab--selected');
2273
+ $tab.setAttribute('tabindex', '-1');
2274
+ };
2275
+
2276
+ Tabs.prototype.highlightTab = function ($tab) {
2277
+ $tab.setAttribute('aria-selected', 'true');
2278
+ $tab.classList.add('govuk-tabs__tab--selected');
2279
+ $tab.setAttribute('tabindex', '0');
2280
+ };
2281
+
2282
+ Tabs.prototype.getCurrentTab = function () {
2283
+ return this.$module.querySelector('.govuk-tabs__tab--selected')
2284
+ };
2285
+
2286
+ // this is because IE doesn't always return the actual value but a relative full path
2287
+ // should be a utility function most prob
2288
+ // http://labs.thesedays.com/blog/2010/01/08/getting-the-href-value-with-jquery-in-ie/
2289
+ Tabs.prototype.getHref = function ($tab) {
2290
+ var href = $tab.getAttribute('href');
2291
+ var hash = href.slice(href.indexOf('#'), href.length);
2292
+ return hash
2293
+ };
2294
+
2295
+ function initAll (options) {
2296
+ // Set the options to an empty object by default if no options are passed.
2297
+ options = typeof options !== 'undefined' ? options : {};
2298
+
2299
+ // Allow the user to initialise GOV.UK Frontend in only certain sections of the page
2300
+ // Defaults to the entire document if nothing is set.
2301
+ var scope = typeof options.scope !== 'undefined' ? options.scope : document;
2302
+
2303
+ // Find all buttons with [role=button] on the scope to enhance.
2304
+ new Button(scope).init();
2305
+
2306
+ // Find all global accordion components to enhance.
2307
+ var $accordions = scope.querySelectorAll('[data-module="accordion"]');
2308
+ nodeListForEach($accordions, function ($accordion) {
2309
+ new Accordion($accordion).init();
2310
+ });
2311
+
2312
+ // Find all global details elements to enhance.
2313
+ var $details = scope.querySelectorAll('details');
2314
+ nodeListForEach($details, function ($detail) {
2315
+ new Details($detail).init();
2316
+ });
2317
+
2318
+ var $characterCount = scope.querySelectorAll('[data-module="character-count"]');
2319
+ nodeListForEach($characterCount, function ($characterCount) {
2320
+ new CharacterCount($characterCount).init();
2321
+ });
2322
+
2323
+ var $checkboxes = scope.querySelectorAll('[data-module="checkboxes"]');
2324
+ nodeListForEach($checkboxes, function ($checkbox) {
2325
+ new Checkboxes($checkbox).init();
2326
+ });
2327
+
2328
+ // Find first error summary module to enhance.
2329
+ var $errorSummary = scope.querySelector('[data-module="error-summary"]');
2330
+ new ErrorSummary($errorSummary).init();
2331
+
2332
+ // Find first header module to enhance.
2333
+ var $toggleButton = scope.querySelector('[data-module="header"]');
2334
+ new Header($toggleButton).init();
2335
+
2336
+ var $radios = scope.querySelectorAll('[data-module="radios"]');
2337
+ nodeListForEach($radios, function ($radio) {
2338
+ new Radios($radio).init();
2339
+ });
2340
+
2341
+ var $tabs = scope.querySelectorAll('[data-module="tabs"]');
2342
+ nodeListForEach($tabs, function ($tabs) {
2343
+ new Tabs($tabs).init();
2344
+ });
2345
+ }
2346
+
2347
+ exports.initAll = initAll;
2348
+ exports.Accordion = Accordion;
2349
+ exports.Button = Button;
2350
+ exports.Details = Details;
2351
+ exports.CharacterCount = CharacterCount;
2352
+ exports.Checkboxes = Checkboxes;
2353
+ exports.ErrorSummary = ErrorSummary;
2354
+ exports.Header = Header;
2355
+ exports.Radios = Radios;
2356
+ exports.Tabs = Tabs;
2357
+
2358
+ })));