forked from hannalaakso/webpack-govuk-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrollup-bundle.js
552 lines (467 loc) · 20.6 KB
/
rollup-bundle.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
/**
* 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 Accordion ($module) {
this.$module = $module;
this.moduleId = $module.getAttribute('id');
this.$sections = $module.querySelectorAll('.govuk-accordion__section');
this.$showAllButton = '';
this.browserSupportsSessionStorage = helper.checkForSessionStorage();
this.controlsClass = 'govuk-accordion__controls';
this.showAllClass = 'govuk-accordion__show-all';
this.showAllTextClass = 'govuk-accordion__show-all-text';
this.sectionExpandedClass = 'govuk-accordion__section--expanded';
this.sectionButtonClass = 'govuk-accordion__section-button';
this.sectionHeaderClass = 'govuk-accordion__section-header';
this.sectionHeadingClass = 'govuk-accordion__section-heading';
this.sectionHeadingTextClass = 'govuk-accordion__section-heading-text';
this.sectionHeadingTextFocusClass = 'govuk-accordion__section-heading-text-focus';
this.sectionShowHideToggleClass = 'govuk-accordion__section-toggle';
this.sectionShowHideToggleFocusClass = 'govuk-accordion__section-toggle-focus';
this.sectionShowHideTextClass = 'govuk-accordion__section-toggle-text';
this.upChevronIconClass = 'govuk-accordion-nav__chevron';
this.downChevronIconClass = 'govuk-accordion-nav__chevron--down';
this.sectionSummaryClass = 'govuk-accordion__section-summary';
this.sectionSummaryFocusClass = 'govuk-accordion__section-summary-focus';
}
// Initialize component
Accordion.prototype.init = function () {
// Check for module
if (!this.$module) {
return
}
this.initControls();
this.initSectionHeaders();
// See if "Show all sections" button text should be updated
var areAllSectionsOpen = this.checkIfAllSectionsOpen();
this.updateShowAllButton(areAllSectionsOpen);
};
// Initialise controls and set attributes
Accordion.prototype.initControls = function () {
// Create "Show all" button and set attributes
this.$showAllButton = document.createElement('button');
this.$showAllButton.setAttribute('type', 'button');
this.$showAllButton.setAttribute('class', this.showAllClass);
this.$showAllButton.setAttribute('aria-expanded', 'false');
// Create icon, add to element
var $icon = document.createElement('span');
$icon.classList.add(this.upChevronIconClass);
this.$showAllButton.appendChild($icon);
// Create control wrapper and add controls to it
var $accordionControls = document.createElement('div');
$accordionControls.setAttribute('class', this.controlsClass);
$accordionControls.appendChild(this.$showAllButton);
this.$module.insertBefore($accordionControls, this.$module.firstChild);
// Build additional wrapper for Show all toggle text and place after icon
var $wrappershowAllText = document.createElement('span');
$wrappershowAllText.classList.add(this.showAllTextClass);
this.$showAllButton.appendChild($wrappershowAllText);
// Handle click events on the show/hide all button
this.$showAllButton.addEventListener('click', this.onShowOrHideAllToggle.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.constructHeaderMarkup($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));
};
Accordion.prototype.constructHeaderMarkup = function ($headerWrapper, index) {
var $span = $headerWrapper.querySelector('.' + this.sectionButtonClass);
var $heading = $headerWrapper.querySelector('.' + this.sectionHeadingClass);
var $summary = $headerWrapper.querySelector('.' + this.sectionSummaryClass);
// Create a button element that will replace the '.govuk-accordion__section-button' span
var $button = document.createElement('button');
$button.setAttribute('type', 'button');
$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);
// Add all attributes but not ID as this is being added to
// the section heading ($headingText)
if (attr.nodeName !== 'id') {
$button.setAttribute(attr.nodeName, attr.nodeValue);
}
}
// Create container for heading text so it can be styled
var $headingText = document.createElement('span');
$headingText.classList.add(this.sectionHeadingTextClass);
// Copy the span ID to the heading text to allow it to be referenced by `aria-labelledby` on the
// hidden content area without "Show this section"
$headingText.id = $span.id;
// Create an inner heading text container to limit the width of the focus state
var $headingTextFocus = document.createElement('span');
$headingTextFocus.classList.add(this.sectionHeadingTextFocusClass);
$headingText.appendChild($headingTextFocus);
// span could contain HTML elements (see https://www.w3.org/TR/2011/WD-html5-20110525/content-models.html#phrasing-content)
$headingTextFocus.innerHTML = $span.innerHTML;
// Create container for show / hide icons and text.
var $showToggle = document.createElement('span');
$showToggle.classList.add(this.sectionShowHideToggleClass);
// Tell Google not to index the 'show' text as part of the heading
// For the snippet to work with JavaScript, it must be added before adding the page element to the
// page's DOM. See https://developers.google.com/search/docs/advanced/robots/robots_meta_tag#data-nosnippet-attr
$showToggle.setAttribute('data-nosnippet', '');
// Create an inner container to limit the width of the focus state
var $showToggleFocus = document.createElement('span');
$showToggleFocus.classList.add(this.sectionShowHideToggleFocusClass);
$showToggle.appendChild($showToggleFocus);
// Create wrapper for the show / hide text. Append text after the show/hide icon
var $showToggleText = document.createElement('span');
var $icon = document.createElement('span');
$icon.classList.add(this.upChevronIconClass);
$showToggleFocus.appendChild($icon);
$showToggleText.classList.add(this.sectionShowHideTextClass);
$showToggleFocus.appendChild($showToggleText);
// Append elements to the button:
// 1. Heading text
// 2. Punctuation
// 3. (Optional: Summary line followed by punctuation)
// 4. Show / hide toggle
$button.appendChild($headingText);
$button.appendChild(this.getButtonPunctuationEl());
// If summary content exists add to DOM in correct order
if (typeof ($summary) !== 'undefined' && $summary !== null) {
// Create a new `span` element and copy the summary line content from the original `div` to the
// new `span`
// This is because the summary line text is now inside a button element, which can only contain
// phrasing content
var $summarySpan = document.createElement('span');
// Create an inner summary container to limit the width of the summary focus state
var $summarySpanFocus = document.createElement('span');
$summarySpanFocus.classList.add(this.sectionSummaryFocusClass);
$summarySpan.appendChild($summarySpanFocus);
// Get original attributes, and pass them to the replacement
for (var j = 0, l = $summary.attributes.length; j < l; ++j) {
var nodeName = $summary.attributes.item(j).nodeName;
var nodeValue = $summary.attributes.item(j).nodeValue;
$summarySpan.setAttribute(nodeName, nodeValue);
}
// Copy original contents of summary to the new summary span
$summarySpanFocus.innerHTML = $summary.innerHTML;
// Replace the original summary `div` with the new summary `span`
$summary.parentNode.replaceChild($summarySpan, $summary);
$button.appendChild($summarySpan);
$button.appendChild(this.getButtonPunctuationEl());
}
$button.appendChild($showToggle);
$heading.removeChild($span);
$heading.appendChild($button);
};
// 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.onShowOrHideAllToggle = 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.updateShowAllButton(nowExpanded);
};
// Set section attributes when opened/closed
Accordion.prototype.setExpanded = function (expanded, $section) {
var $icon = $section.querySelector('.' + this.upChevronIconClass);
var $showHideText = $section.querySelector('.' + this.sectionShowHideTextClass);
var $button = $section.querySelector('.' + this.sectionButtonClass);
var $newButtonText = expanded ? 'Hide' : 'Show';
// Build additional copy of "this section" for assistive technology and place inside toggle link
var $visuallyHiddenText = document.createElement('span');
$visuallyHiddenText.classList.add('govuk-visually-hidden');
$visuallyHiddenText.innerHTML = ' this section';
$showHideText.innerHTML = $newButtonText;
$showHideText.appendChild($visuallyHiddenText);
$button.setAttribute('aria-expanded', expanded);
// Swap icon, change class
if (expanded) {
$section.classList.add(this.sectionExpandedClass);
$icon.classList.remove(this.downChevronIconClass);
} else {
$section.classList.remove(this.sectionExpandedClass);
$icon.classList.add(this.downChevronIconClass);
}
// See if "Show all sections" button text should be updated
var areAllSectionsOpen = this.checkIfAllSectionsOpen();
this.updateShowAllButton(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 "Show all sections" button
Accordion.prototype.updateShowAllButton = function (expanded) {
var $showAllIcon = this.$showAllButton.querySelector('.' + this.upChevronIconClass);
var $showAllText = this.$showAllButton.querySelector('.' + this.showAllTextClass);
var newButtonText = expanded ? 'Hide all sections' : 'Show all sections';
this.$showAllButton.setAttribute('aria-expanded', expanded);
$showAllText.innerHTML = newButtonText;
// Swap icon, toggle class
if (expanded) {
$showAllIcon.classList.remove(this.downChevronIconClass);
} else {
$showAllIcon.classList.add(this.downChevronIconClass);
}
};
// 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;
if (contentState !== null) {
this.setExpanded(contentState === 'true', $section);
}
}
}
};
/**
* Create an element to improve semantics of the section button with punctuation
* @return {object} DOM element
*
* Used to add pause (with a comma) for assistive technology.
* Example: [heading]Section A ,[pause] Show this section.
* https://accessibility.blog.gov.uk/2017/12/18/what-working-on-gov-uk-navigation-taught-us-about-accessibility/
*
* Adding punctuation to the button can also improve its general semantics by dividing its contents
* into thematic chunks.
* See https://github.com/alphagov/govuk-frontend/issues/2327#issuecomment-922957442
*/
Accordion.prototype.getButtonPunctuationEl = function () {
var $punctuationEl = document.createElement('span');
$punctuationEl.classList.add('govuk-visually-hidden', 'govuk-accordion__section-heading-divider');
$punctuationEl.innerHTML = ', ';
return $punctuationEl
};
function CharacterCount ($module) {
this.$module = $module;
this.$textarea = $module.querySelector('.govuk-js-character-count');
if (this.$textarea) {
this.$countMessage = document.getElementById(this.$textarea.id + '-info');
}
}
CharacterCount.prototype.defaults = {
characterCountAttribute: 'data-maxlength',
wordCountAttribute: 'data-maxwords'
};
// Initialize component
CharacterCount.prototype.init = function () {
// Check for module
var $module = this.$module;
var $textarea = this.$textarea;
var $countMessage = this.$countMessage;
if (!$textarea || !$countMessage) {
return
}
// We move count message right after the field
// Kept for backwards compatibility
$textarea.insertAdjacentElement('afterend', $countMessage);
// Read options set using dataset ('data-' values)
this.options = this.getDataset($module);
// Determine the limit attribute (characters or words)
var countAttribute = this.defaults.characterCountAttribute;
if (this.options.maxwords) {
countAttribute = this.defaults.wordCountAttribute;
}
// Save the element limit
this.maxLength = $module.getAttribute(countAttribute);
// Check for limit
if (!this.maxLength) {
return
}
// Remove hard limit if set
$module.removeAttribute('maxlength');
// When the page is restored after navigating 'back' in some browsers the
// state of the character count is not restored until *after* the DOMContentLoaded
// event is fired, so we need to sync after the pageshow event in browsers
// that support it.
if ('onpageshow' in window) {
window.addEventListener('pageshow', this.sync.bind(this));
} else {
window.addEventListener('DOMContentLoaded', this.sync.bind(this));
}
this.sync();
};
CharacterCount.prototype.sync = function () {
this.bindChangeEvents();
this.updateCountMessage();
};
// Read data attributes
CharacterCount.prototype.getDataset = function (element) {
var dataset = {};
var attributes = element.attributes;
if (attributes) {
for (var i = 0; i < attributes.length; i++) {
var attribute = attributes[i];
var match = attribute.name.match(/^data-(.+)/);
if (match) {
dataset[match[1]] = attribute.value;
}
}
}
return dataset
};
// Counts characters or words in text
CharacterCount.prototype.count = function (text) {
var length;
if (this.options.maxwords) {
var tokens = text.match(/\S+/g) || []; // Matches consecutive non-whitespace chars
length = tokens.length;
} else {
length = text.length;
}
return length
};
// Bind input propertychange to the elements and update based on the change
CharacterCount.prototype.bindChangeEvents = function () {
var $textarea = this.$textarea;
$textarea.addEventListener('keyup', this.checkIfValueChanged.bind(this));
// Bind focus/blur events to start/stop polling
$textarea.addEventListener('focus', this.handleFocus.bind(this));
$textarea.addEventListener('blur', this.handleBlur.bind(this));
};
// Speech recognition software such as Dragon NaturallySpeaking will modify the
// fields by directly changing its `value`. These changes don't trigger events
// in JavaScript, so we need to poll to handle when and if they occur.
CharacterCount.prototype.checkIfValueChanged = function () {
if (!this.$textarea.oldValue) this.$textarea.oldValue = '';
if (this.$textarea.value !== this.$textarea.oldValue) {
this.$textarea.oldValue = this.$textarea.value;
this.updateCountMessage();
}
};
// Update message box
CharacterCount.prototype.updateCountMessage = function () {
var countElement = this.$textarea;
var options = this.options;
var countMessage = this.$countMessage;
// Determine the remaining number of characters/words
var currentLength = this.count(countElement.value);
var maxLength = this.maxLength;
var remainingNumber = maxLength - currentLength;
// Set threshold if presented in options
var thresholdPercent = options.threshold ? options.threshold : 0;
var thresholdValue = maxLength * thresholdPercent / 100;
if (thresholdValue > currentLength) {
countMessage.classList.add('govuk-character-count__message--disabled');
// Ensure threshold is hidden for users of assistive technologies
countMessage.setAttribute('aria-hidden', true);
} else {
countMessage.classList.remove('govuk-character-count__message--disabled');
// Ensure threshold is visible for users of assistive technologies
countMessage.removeAttribute('aria-hidden');
}
// Update styles
if (remainingNumber < 0) {
countElement.classList.add('govuk-textarea--error');
countMessage.classList.remove('govuk-hint');
countMessage.classList.add('govuk-error-message');
} else {
countElement.classList.remove('govuk-textarea--error');
countMessage.classList.remove('govuk-error-message');
countMessage.classList.add('govuk-hint');
}
// Update message
var charVerb = 'remaining';
var charNoun = 'character';
var displayNumber = remainingNumber;
if (options.maxwords) {
charNoun = 'word';
}
charNoun = charNoun + ((remainingNumber === -1 || remainingNumber === 1) ? '' : 's');
charVerb = (remainingNumber < 0) ? 'too many' : 'remaining';
displayNumber = Math.abs(remainingNumber);
countMessage.innerHTML = 'You have ' + displayNumber + ' ' + charNoun + ' ' + charVerb;
};
CharacterCount.prototype.handleFocus = function () {
// Check if value changed on focus
this.valueChecker = setInterval(this.checkIfValueChanged.bind(this), 1000);
};
CharacterCount.prototype.handleBlur = function () {
// Cancel value checking on blur
clearInterval(this.valueChecker);
};
var $accordion = document.querySelector('[data-module="govuk-accordion"]');
if ($accordion) {
new Accordion($accordion).init();
}
var $characterCount = document.querySelector('[data-module="govuk-character-count"]');
if ($characterCount) {
new CharacterCount($characterCount).init();
}
require('./main.js');