forked from uswds/uswds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
94 lines (82 loc) · 2.35 KB
/
search.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
'use strict';
const behavior = require('../utils/behavior');
const forEach = require('array-foreach');
const ignore = require('receptor/ignore');
const select = require('../utils/select');
const CLICK = require('../events').CLICK;
const PREFIX = require('../config').prefix;
const BUTTON = '.js-search-button';
const FORM = '.js-search-form';
const INPUT = '[type=search]';
const CONTEXT = 'header'; // XXX
const VISUALLY_HIDDEN = `${PREFIX}-sr-only`;
let lastButton;
const showSearch = function (event) {
toggleSearch(this, true);
lastButton = this;
};
const hideSearch = function (event) {
toggleSearch(this, false);
lastButton = undefined;
};
const getForm = button => {
const context = button.closest(CONTEXT);
return context
? context.querySelector(FORM)
: document.querySelector(FORM);
};
const toggleSearch = (button, active) => {
const form = getForm(button);
if (!form) {
throw new Error(`No ${FORM} found for search toggle in ${CONTEXT}!`);
}
button.hidden = active;
form.classList.toggle(VISUALLY_HIDDEN, !active);
if (active) {
const input = form.querySelector(INPUT);
if (input) {
input.focus();
}
// when the user clicks _outside_ of the form w/ignore(): hide the
// search, then remove the listener
const listener = ignore(form, e => {
if (lastButton) {
hideSearch.call(lastButton);
}
document.body.removeEventListener(CLICK, listener);
});
// Normally we would just run this code without a timeout, but
// IE11 and Edge will actually call the listener *immediately* because
// they are currently handling this exact type of event, so we'll
// make sure the browser is done handling the current click event,
// if any, before we attach the listener.
setTimeout(() => {
document.body.addEventListener(CLICK, listener);
}, 0);
}
};
const search = behavior({
[ CLICK ]: {
[ BUTTON ]: showSearch,
},
}, {
init: (target) => {
forEach(select(BUTTON, target), button => {
toggleSearch(button, false);
});
},
teardown: (target) => {
// forget the last button clicked
lastButton = undefined;
},
});
/**
* TODO for 2.0, remove this statement and export `navigation` directly:
*
* module.exports = behavior({...});
*/
const assign = require('object-assign');
module.exports = assign(
el => search.on(el),
search
);