Files
notifications-admin/app/assets/javascripts/liveSearch.js
T

89 lines
2.0 KiB
JavaScript
Raw Normal View History

(function(Modules) {
"use strict";
2020-09-16 22:01:36 +01:00
let state;
let normalize = (string) => string.toLowerCase().replace(/ /g,'');
2020-09-16 22:01:36 +01:00
let resultsSummary = (num) => {
if (num === 0) {
return "no results";
} else {
return num + (num === 1 ? " result" : " results");
}
};
2020-09-16 22:01:36 +01:00
let filter = ($searchBox, $searchLabel, $liveRegion, $targets) => () => {
let query = normalize($searchBox.val());
2020-09-16 22:01:36 +01:00
let results = 0;
$targets.each(function() {
2018-11-22 17:57:05 +00:00
let content = $('.live-search-relevant', this).text() || $(this).text();
2020-09-16 22:01:36 +01:00
let isMatch = normalize(content).indexOf(normalize(query)) > -1;
2018-12-05 11:24:16 +00:00
if ($(this).has(':checked').length) {
$(this).show();
2020-09-16 22:01:36 +01:00
results++;
2018-12-05 11:24:16 +00:00
return;
}
if (query == '') {
$(this).css('display', '');
2020-09-16 22:01:36 +01:00
results++;
return;
}
2020-09-16 22:01:36 +01:00
$(this).toggle(isMatch);
if (isMatch) { results++; }
});
2020-09-16 22:01:36 +01:00
if (state === 'loaded') {
if (query !== '') {
$searchBox.attr('aria-label', $searchLabel.text().trim() + ', ' + resultsSummary(results));
}
state = 'active';
} else {
$searchBox.removeAttr('aria-label');
$liveRegion.text(resultsSummary(results));
}
2018-12-21 14:37:01 +00:00
// make sticky JS recalculate its cache of the element's position
// because live search can change the height document
if ('stickAtBottomWhenScrolling' in GOVUK) {
GOVUK.stickAtBottomWhenScrolling.recalculate();
}
};
Modules.LiveSearch = function() {
this.start = function(component) {
let $component = $(component);
let $searchBox = $('input', $component);
2020-09-16 22:01:36 +01:00
let $searchLabel = $('label', $component);
let $liveRegion = $('.live-search__status', $component);
let filterFunc = filter(
$searchBox,
2020-09-16 22:01:36 +01:00
$searchLabel,
$liveRegion,
$($component.data('targets'))
);
2020-09-16 22:01:36 +01:00
state = 'loaded';
$searchBox.on('keyup input', filterFunc);
filterFunc();
};
};
})(window.GOVUK.Modules);