-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathaccordion.js
1011 lines (838 loc) · 37.7 KB
/
accordion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define('GOVUKFrontend', factory) :
(global.GOVUKFrontend = factory());
}(this, (function () { 'use strict';
/**
* TODO: Ideally this would be a NodeList.prototype.forEach polyfill
* This seems to fail in IE8, requires more investigation.
* See: https://github.com/imagitama/nodelist-foreach-polyfill
*/
function nodeListForEach (nodes, callback) {
if (window.NodeList.prototype.forEach) {
return nodes.forEach(callback)
}
for (var i = 0; i < nodes.length; i++) {
callback.call(window, nodes[i], i, nodes);
}
}
(function(undefined) {
// Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Object/defineProperty/detect.js
var detect = (
// In IE8, defineProperty could only act on DOM elements, so full support
// for the feature requires the ability to set a property on an arbitrary object
'defineProperty' in Object && (function() {
try {
var a = {};
Object.defineProperty(a, 'test', {value:42});
return true;
} catch(e) {
return false
}
}())
);
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Object.defineProperty&flags=always
(function (nativeDefineProperty) {
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
var ERR_ACCESSORS_NOT_SUPPORTED = 'Getters & setters cannot be defined on this javascript engine';
var ERR_VALUE_ACCESSORS = 'A property cannot both have accessors and be writable or have a value';
Object.defineProperty = function defineProperty(object, property, descriptor) {
// Where native support exists, assume it
if (nativeDefineProperty && (object === window || object === document || object === Element.prototype || object instanceof Element)) {
return nativeDefineProperty(object, property, descriptor);
}
if (object === null || !(object instanceof Object || typeof object === 'object')) {
throw new TypeError('Object.defineProperty called on non-object');
}
if (!(descriptor instanceof Object)) {
throw new TypeError('Property description must be an object');
}
var propertyString = String(property);
var hasValueOrWritable = 'value' in descriptor || 'writable' in descriptor;
var getterType = 'get' in descriptor && typeof descriptor.get;
var setterType = 'set' in descriptor && typeof descriptor.set;
// handle descriptor.get
if (getterType) {
if (getterType !== 'function') {
throw new TypeError('Getter must be a function');
}
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
if (hasValueOrWritable) {
throw new TypeError(ERR_VALUE_ACCESSORS);
}
Object.__defineGetter__.call(object, propertyString, descriptor.get);
} else {
object[propertyString] = descriptor.value;
}
// handle descriptor.set
if (setterType) {
if (setterType !== 'function') {
throw new TypeError('Setter must be a function');
}
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
if (hasValueOrWritable) {
throw new TypeError(ERR_VALUE_ACCESSORS);
}
Object.__defineSetter__.call(object, propertyString, descriptor.set);
}
// OK to define value unconditionally - if a getter has been specified as well, an error would be thrown above
if ('value' in descriptor) {
object[propertyString] = descriptor.value;
}
return object;
};
}(Object.defineProperty));
})
.call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
(function(undefined) {
// Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Function/prototype/bind/detect.js
var detect = 'bind' in Function.prototype;
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Function.prototype.bind&flags=always
Object.defineProperty(Function.prototype, 'bind', {
value: function bind(that) { // .length is 1
// add necessary es5-shim utilities
var $Array = Array;
var $Object = Object;
var ObjectPrototype = $Object.prototype;
var ArrayPrototype = $Array.prototype;
var Empty = function Empty() {};
var to_string = ObjectPrototype.toString;
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
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; };
var array_slice = ArrayPrototype.slice;
var array_concat = ArrayPrototype.concat;
var array_push = ArrayPrototype.push;
var max = Math.max;
// /add necessary es5-shim utilities
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (!isCallable(target)) {
throw new TypeError('Function.prototype.bind called on incompatible ' + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = array_slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound;
var binder = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
array_concat.call(args, array_slice.call(arguments))
);
if ($Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
array_concat.call(args, array_slice.call(arguments))
);
}
};
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
var boundLength = max(0, target.length - args.length);
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
array_push.call(boundArgs, '$' + i);
}
// XXX Build a dynamic function with desired amount of arguments is the only
// way to set the length property of a function.
// In environments where Content Security Policies enabled (Chrome extensions,
// for ex.) all use of eval or Function costructor throws an exception.
// However in all of these environments Function.prototype.bind exists
// and so this code will never be executed.
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
if (target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
// Clean up dangling references.
Empty.prototype = null;
}
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
}
});
})
.call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
(function(undefined) {
// Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/master/packages/polyfill-library/polyfills/DOMTokenList/detect.js
var detect = (
'DOMTokenList' in this && (function (x) {
return 'classList' in x ? !x.classList.toggle('x', false) && !x.className : true;
})(document.createElement('x'))
);
if (detect) return
// Polyfill from https://raw.githubusercontent.com/Financial-Times/polyfill-service/master/packages/polyfill-library/polyfills/DOMTokenList/polyfill.js
(function (global) {
var nativeImpl = "DOMTokenList" in global && global.DOMTokenList;
if (
!nativeImpl ||
(
!!document.createElementNS &&
!!document.createElementNS('http://www.w3.org/2000/svg', 'svg') &&
!(document.createElementNS("http://www.w3.org/2000/svg", "svg").classList instanceof DOMTokenList)
)
) {
global.DOMTokenList = (function() { // eslint-disable-line no-unused-vars
var dpSupport = true;
var defineGetter = function (object, name, fn, configurable) {
if (Object.defineProperty)
Object.defineProperty(object, name, {
configurable: false === dpSupport ? true : !!configurable,
get: fn
});
else object.__defineGetter__(name, fn);
};
/** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */
try {
defineGetter({}, "support");
}
catch (e) {
dpSupport = false;
}
var _DOMTokenList = function (el, prop) {
var that = this;
var tokens = [];
var tokenMap = {};
var length = 0;
var maxLength = 0;
var addIndexGetter = function (i) {
defineGetter(that, i, function () {
preop();
return tokens[i];
}, false);
};
var reindex = function () {
/** Define getter functions for array-like access to the tokenList's contents. */
if (length >= maxLength)
for (; maxLength < length; ++maxLength) {
addIndexGetter(maxLength);
}
};
/** Helper function called at the start of each class method. Internal use only. */
var preop = function () {
var error;
var i;
var args = arguments;
var rSpace = /\s+/;
/** Validate the token/s passed to an instance method, if any. */
if (args.length)
for (i = 0; i < args.length; ++i)
if (rSpace.test(args[i])) {
error = new SyntaxError('String "' + args[i] + '" ' + "contains" + ' an invalid character');
error.code = 5;
error.name = "InvalidCharacterError";
throw error;
}
/** Split the new value apart by whitespace*/
if (typeof el[prop] === "object") {
tokens = ("" + el[prop].baseVal).replace(/^\s+|\s+$/g, "").split(rSpace);
} else {
tokens = ("" + el[prop]).replace(/^\s+|\s+$/g, "").split(rSpace);
}
/** Avoid treating blank strings as single-item token lists */
if ("" === tokens[0]) tokens = [];
/** Repopulate the internal token lists */
tokenMap = {};
for (i = 0; i < tokens.length; ++i)
tokenMap[tokens[i]] = true;
length = tokens.length;
reindex();
};
/** Populate our internal token list if the targeted attribute of the subject element isn't empty. */
preop();
/** Return the number of tokens in the underlying string. Read-only. */
defineGetter(that, "length", function () {
preop();
return length;
});
/** Override the default toString/toLocaleString methods to return a space-delimited list of tokens when typecast. */
that.toLocaleString =
that.toString = function () {
preop();
return tokens.join(" ");
};
that.item = function (idx) {
preop();
return tokens[idx];
};
that.contains = function (token) {
preop();
return !!tokenMap[token];
};
that.add = function () {
preop.apply(that, args = arguments);
for (var args, token, i = 0, l = args.length; i < l; ++i) {
token = args[i];
if (!tokenMap[token]) {
tokens.push(token);
tokenMap[token] = true;
}
}
/** Update the targeted attribute of the attached element if the token list's changed. */
if (length !== tokens.length) {
length = tokens.length >>> 0;
if (typeof el[prop] === "object") {
el[prop].baseVal = tokens.join(" ");
} else {
el[prop] = tokens.join(" ");
}
reindex();
}
};
that.remove = function () {
preop.apply(that, args = arguments);
/** Build a hash of token names to compare against when recollecting our token list. */
for (var args, ignore = {}, i = 0, t = []; i < args.length; ++i) {
ignore[args[i]] = true;
delete tokenMap[args[i]];
}
/** Run through our tokens list and reassign only those that aren't defined in the hash declared above. */
for (i = 0; i < tokens.length; ++i)
if (!ignore[tokens[i]]) t.push(tokens[i]);
tokens = t;
length = t.length >>> 0;
/** Update the targeted attribute of the attached element. */
if (typeof el[prop] === "object") {
el[prop].baseVal = tokens.join(" ");
} else {
el[prop] = tokens.join(" ");
}
reindex();
};
that.toggle = function (token, force) {
preop.apply(that, [token]);
/** Token state's being forced. */
if (undefined !== force) {
if (force) {
that.add(token);
return true;
} else {
that.remove(token);
return false;
}
}
/** Token already exists in tokenList. Remove it, and return FALSE. */
if (tokenMap[token]) {
that.remove(token);
return false;
}
/** Otherwise, add the token and return TRUE. */
that.add(token);
return true;
};
return that;
};
return _DOMTokenList;
}());
}
// Add second argument to native DOMTokenList.toggle() if necessary
(function () {
var e = document.createElement('span');
if (!('classList' in e)) return;
e.classList.toggle('x', false);
if (!e.classList.contains('x')) return;
e.classList.constructor.prototype.toggle = function toggle(token /*, force*/) {
var force = arguments[1];
if (force === undefined) {
var add = !this.contains(token);
this[add ? 'add' : 'remove'](token);
return add;
}
force = !!force;
this[force ? 'add' : 'remove'](token);
return force;
};
}());
// Add multiple arguments to native DOMTokenList.add() if necessary
(function () {
var e = document.createElement('span');
if (!('classList' in e)) return;
e.classList.add('a', 'b');
if (e.classList.contains('b')) return;
var native = e.classList.constructor.prototype.add;
e.classList.constructor.prototype.add = function () {
var args = arguments;
var l = arguments.length;
for (var i = 0; i < l; i++) {
native.call(this, args[i]);
}
};
}());
// Add multiple arguments to native DOMTokenList.remove() if necessary
(function () {
var e = document.createElement('span');
if (!('classList' in e)) return;
e.classList.add('a');
e.classList.add('b');
e.classList.remove('a', 'b');
if (!e.classList.contains('b')) return;
var native = e.classList.constructor.prototype.remove;
e.classList.constructor.prototype.remove = function () {
var args = arguments;
var l = arguments.length;
for (var i = 0; i < l; i++) {
native.call(this, args[i]);
}
};
}());
}(this));
}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
(function(undefined) {
// Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Document/detect.js
var detect = ("Document" in this);
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Document&flags=always
if ((typeof WorkerGlobalScope === "undefined") && (typeof importScripts !== "function")) {
if (this.HTMLDocument) { // IE8
// HTMLDocument is an extension of Document. If the browser has HTMLDocument but not Document, the former will suffice as an alias for the latter.
this.Document = this.HTMLDocument;
} else {
// 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.
this.Document = this.HTMLDocument = document.constructor = (new Function('return function Document() {}')());
this.Document.prototype = document;
}
}
})
.call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
(function(undefined) {
// Detection from https://github.com/Financial-Times/polyfill-service/blob/master/packages/polyfill-library/polyfills/Element/detect.js
var detect = ('Element' in this && 'HTMLElement' in this);
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Element&flags=always
(function () {
// IE8
if (window.Element && !window.HTMLElement) {
window.HTMLElement = window.Element;
return;
}
// create Element constructor
window.Element = window.HTMLElement = new Function('return function Element() {}')();
// generate sandboxed iframe
var vbody = document.appendChild(document.createElement('body'));
var frame = vbody.appendChild(document.createElement('iframe'));
// use sandboxed iframe to replicate Element functionality
var frameDocument = frame.contentWindow.document;
var prototype = Element.prototype = frameDocument.appendChild(frameDocument.createElement('*'));
var cache = {};
// polyfill Element.prototype on an element
var shiv = function (element, deep) {
var
childNodes = element.childNodes || [],
index = -1,
key, value, childNode;
if (element.nodeType === 1 && element.constructor !== Element) {
element.constructor = Element;
for (key in cache) {
value = cache[key];
element[key] = value;
}
}
while (childNode = deep && childNodes[++index]) {
shiv(childNode, deep);
}
return element;
};
var elements = document.getElementsByTagName('*');
var nativeCreateElement = document.createElement;
var interval;
var loopLimit = 100;
prototype.attachEvent('onpropertychange', function (event) {
var
propertyName = event.propertyName,
nonValue = !cache.hasOwnProperty(propertyName),
newValue = prototype[propertyName],
oldValue = cache[propertyName],
index = -1,
element;
while (element = elements[++index]) {
if (element.nodeType === 1) {
if (nonValue || element[propertyName] === oldValue) {
element[propertyName] = newValue;
}
}
}
cache[propertyName] = newValue;
});
prototype.constructor = Element;
if (!prototype.hasAttribute) {
// <Element>.hasAttribute
prototype.hasAttribute = function hasAttribute(name) {
return this.getAttribute(name) !== null;
};
}
// Apply Element prototype to the pre-existing DOM as soon as the body element appears.
function bodyCheck() {
if (!(loopLimit--)) clearTimeout(interval);
if (document.body && !document.body.prototype && /(complete|interactive)/.test(document.readyState)) {
shiv(document, true);
if (interval && document.body.prototype) clearTimeout(interval);
return (!!document.body.prototype);
}
return false;
}
if (!bodyCheck()) {
document.onreadystatechange = bodyCheck;
interval = setInterval(bodyCheck, 25);
}
// Apply to any new elements created after load
document.createElement = function createElement(nodeName) {
var element = nativeCreateElement(String(nodeName).toLowerCase());
return shiv(element);
};
// remove sandboxed iframe
document.removeChild(vbody);
}());
})
.call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
(function(undefined) {
// Detection from https://raw.githubusercontent.com/Financial-Times/polyfill-service/8717a9e04ac7aff99b4980fbedead98036b0929a/packages/polyfill-library/polyfills/Element/prototype/classList/detect.js
var detect = (
'document' in this && "classList" in document.documentElement && 'Element' in this && 'classList' in Element.prototype && (function () {
var e = document.createElement('span');
e.classList.add('a', 'b');
return e.classList.contains('b');
}())
);
if (detect) return
// Polyfill from https://cdn.polyfill.io/v2/polyfill.js?features=Element.prototype.classList&flags=always
(function (global) {
var dpSupport = true;
var defineGetter = function (object, name, fn, configurable) {
if (Object.defineProperty)
Object.defineProperty(object, name, {
configurable: false === dpSupport ? true : !!configurable,
get: fn
});
else object.__defineGetter__(name, fn);
};
/** Ensure the browser allows Object.defineProperty to be used on native JavaScript objects. */
try {
defineGetter({}, "support");
}
catch (e) {
dpSupport = false;
}
/** Polyfills a property with a DOMTokenList */
var addProp = function (o, name, attr) {
defineGetter(o.prototype, name, function () {
var tokenList;
var THIS = this,
/** Prevent this from firing twice for some reason. What the hell, IE. */
gibberishProperty = "__defineGetter__" + "DEFINE_PROPERTY" + name;
if(THIS[gibberishProperty]) return tokenList;
THIS[gibberishProperty] = true;
/**
* IE8 can't define properties on native JavaScript objects, so we'll use a dumb hack instead.
*
* What this is doing is creating a dummy element ("reflection") inside a detached phantom node ("mirror")
* that serves as the target of Object.defineProperty instead. While we could simply use the subject HTML
* element instead, this would conflict with element types which use indexed properties (such as forms and
* select lists).
*/
if (false === dpSupport) {
var visage;
var mirror = addProp.mirror || document.createElement("div");
var reflections = mirror.childNodes;
var l = reflections.length;
for (var i = 0; i < l; ++i)
if (reflections[i]._R === THIS) {
visage = reflections[i];
break;
}
/** Couldn't find an element's reflection inside the mirror. Materialise one. */
visage || (visage = mirror.appendChild(document.createElement("div")));
tokenList = DOMTokenList.call(visage, THIS, attr);
} else tokenList = new DOMTokenList(THIS, attr);
defineGetter(THIS, name, function () {
return tokenList;
});
delete THIS[gibberishProperty];
return tokenList;
}, true);
};
addProp(global.Element, "classList", "className");
addProp(global.HTMLElement, "classList", "className");
addProp(global.HTMLLinkElement, "relList", "rel");
addProp(global.HTMLAnchorElement, "relList", "rel");
addProp(global.HTMLAreaElement, "relList", "rel");
}(this));
}).call('object' === typeof window && window || 'object' === typeof self && self || 'object' === typeof global && global || {});
function Accordion ($module) {
this.$module = $module;
this.moduleId = $module.getAttribute('id');
this.$sections = $module.querySelectorAll('.govuk-accordion__section');
this.$openAllButton = '';
this.browserSupportsSessionStorage = helper.checkForSessionStorage();
this.controlsClass = 'govuk-accordion__controls';
this.openAllClass = 'govuk-accordion__open-all';
this.iconClass = 'govuk-accordion__icon';
this.sectionHeaderClass = 'govuk-accordion__section-header';
this.sectionHeaderFocusedClass = 'govuk-accordion__section-header--focused';
this.sectionHeadingClass = 'govuk-accordion__section-heading';
this.sectionSummaryClass = 'govuk-accordion__section-summary';
this.sectionButtonClass = 'govuk-accordion__section-button';
this.sectionExpandedClass = 'govuk-accordion__section--expanded';
}
// Initialize component
Accordion.prototype.init = function () {
// Check for module
if (!this.$module) {
return
}
this.initControls();
this.initSectionHeaders();
// See if "Open all" button text should be updated
var areAllSectionsOpen = this.checkIfAllSectionsOpen();
this.updateOpenAllButton(areAllSectionsOpen);
};
// Initialise controls and set attributes
Accordion.prototype.initControls = function () {
// Create "Open all" button and set attributes
this.$openAllButton = document.createElement('button');
this.$openAllButton.setAttribute('type', 'button');
this.$openAllButton.innerHTML = 'Open all <span class="govuk-visually-hidden">sections</span>';
this.$openAllButton.setAttribute('class', this.openAllClass);
this.$openAllButton.setAttribute('aria-expanded', 'false');
this.$openAllButton.setAttribute('type', 'button');
// Create control wrapper and add controls to it
var accordionControls = document.createElement('div');
accordionControls.setAttribute('class', this.controlsClass);
accordionControls.appendChild(this.$openAllButton);
this.$module.insertBefore(accordionControls, this.$module.firstChild);
// Handle events for the controls
this.$openAllButton.addEventListener('click', this.onOpenOrCloseAllToggle.bind(this));
};
// Initialise section headers
Accordion.prototype.initSectionHeaders = function () {
// Loop through section headers
nodeListForEach(this.$sections, function ($section, i) {
// Set header attributes
var header = $section.querySelector('.' + this.sectionHeaderClass);
this.initHeaderAttributes(header, i);
this.setExpanded(this.isExpanded($section), $section);
// Handle events
header.addEventListener('click', this.onSectionToggle.bind(this, $section));
// See if there is any state stored in sessionStorage and set the sections to
// open or closed.
this.setInitialState($section);
}.bind(this));
};
// Set individual header attributes
Accordion.prototype.initHeaderAttributes = function ($headerWrapper, index) {
var $module = this;
var $span = $headerWrapper.querySelector('.' + this.sectionButtonClass);
var $heading = $headerWrapper.querySelector('.' + this.sectionHeadingClass);
var $summary = $headerWrapper.querySelector('.' + this.sectionSummaryClass);
// Copy existing span element to an actual button element, for improved accessibility.
var $button = document.createElement('button');
$button.setAttribute('type', 'button');
$button.setAttribute('id', this.moduleId + '-heading-' + (index + 1));
$button.setAttribute('aria-controls', this.moduleId + '-content-' + (index + 1));
// Copy all attributes (https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes) from $span to $button
for (var i = 0; i < $span.attributes.length; i++) {
var attr = $span.attributes.item(i);
$button.setAttribute(attr.nodeName, attr.nodeValue);
}
$button.addEventListener('focusin', function (e) {
if (!$headerWrapper.classList.contains($module.sectionHeaderFocusedClass)) {
$headerWrapper.className += ' ' + $module.sectionHeaderFocusedClass;
}
});
$button.addEventListener('blur', function (e) {
$headerWrapper.classList.remove($module.sectionHeaderFocusedClass);
});
if (typeof ($summary) !== 'undefined' && $summary !== null) {
$button.setAttribute('aria-describedby', this.moduleId + '-summary-' + (index + 1));
}
// $span could contain HTML elements (see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content)
$button.innerHTML = $span.innerHTML;
$heading.removeChild($span);
$heading.appendChild($button);
// Add "+/-" icon
var icon = document.createElement('span');
icon.className = this.iconClass;
icon.setAttribute('aria-hidden', 'true');
$button.appendChild(icon);
};
// When section toggled, set and store state
Accordion.prototype.onSectionToggle = function ($section) {
var expanded = this.isExpanded($section);
this.setExpanded(!expanded, $section);
// Store the state in sessionStorage when a change is triggered
this.storeState($section);
};
// When Open/Close All toggled, set and store state
Accordion.prototype.onOpenOrCloseAllToggle = function () {
var $module = this;
var $sections = this.$sections;
var nowExpanded = !this.checkIfAllSectionsOpen();
nodeListForEach($sections, function ($section) {
$module.setExpanded(nowExpanded, $section);
// Store the state in sessionStorage when a change is triggered
$module.storeState($section);
});
$module.updateOpenAllButton(nowExpanded);
};
// Set section attributes when opened/closed
Accordion.prototype.setExpanded = function (expanded, $section) {
var $button = $section.querySelector('.' + this.sectionButtonClass);
$button.setAttribute('aria-expanded', expanded);
if (expanded) {
$section.classList.add(this.sectionExpandedClass);
} else {
$section.classList.remove(this.sectionExpandedClass);
}
// See if "Open all" button text should be updated
var areAllSectionsOpen = this.checkIfAllSectionsOpen();
this.updateOpenAllButton(areAllSectionsOpen);
};
// Get state of section
Accordion.prototype.isExpanded = function ($section) {
return $section.classList.contains(this.sectionExpandedClass)
};
// Check if all sections are open
Accordion.prototype.checkIfAllSectionsOpen = function () {
// Get a count of all the Accordion sections
var sectionsCount = this.$sections.length;
// Get a count of all Accordion sections that are expanded
var expandedSectionCount = this.$module.querySelectorAll('.' + this.sectionExpandedClass).length;
var areAllSectionsOpen = sectionsCount === expandedSectionCount;
return areAllSectionsOpen
};
// Update "Open all" button
Accordion.prototype.updateOpenAllButton = function (expanded) {
var newButtonText = expanded ? 'Close all' : 'Open all';
newButtonText += '<span class="govuk-visually-hidden"> sections</span>';
this.$openAllButton.setAttribute('aria-expanded', expanded);
this.$openAllButton.innerHTML = newButtonText;
};
// Check for `window.sessionStorage`, and that it actually works.
var helper = {
checkForSessionStorage: function () {
var testString = 'this is the test string';
var result;
try {
window.sessionStorage.setItem(testString, testString);
result = window.sessionStorage.getItem(testString) === testString.toString();
window.sessionStorage.removeItem(testString);
return result
} catch (exception) {
if ((typeof console === 'undefined' || typeof console.log === 'undefined')) {
console.log('Notice: sessionStorage not available.');
}
}
}
};
// Set the state of the accordions in sessionStorage
Accordion.prototype.storeState = function ($section) {
if (this.browserSupportsSessionStorage) {
// We need a unique way of identifying each content in the accordion. Since
// an `#id` should be unique and an `id` is required for `aria-` attributes
// `id` can be safely used.
var $button = $section.querySelector('.' + this.sectionButtonClass);
if ($button) {
var contentId = $button.getAttribute('aria-controls');
var contentState = $button.getAttribute('aria-expanded');
if (typeof contentId === 'undefined' && (typeof console === 'undefined' || typeof console.log === 'undefined')) {
console.error(new Error('No aria controls present in accordion section heading.'));
}
if (typeof contentState === 'undefined' && (typeof console === 'undefined' || typeof console.log === 'undefined')) {
console.error(new Error('No aria expanded present in accordion section heading.'));
}
// Only set the state when both `contentId` and `contentState` are taken from the DOM.
if (contentId && contentState) {
window.sessionStorage.setItem(contentId, contentState);
}
}
}
};
// Read the state of the accordions from sessionStorage
Accordion.prototype.setInitialState = function ($section) {
if (this.browserSupportsSessionStorage) {
var $button = $section.querySelector('.' + this.sectionButtonClass);
if ($button) {
var contentId = $button.getAttribute('aria-controls');
var contentState = contentId ? window.sessionStorage.getItem(contentId) : null;