/
SearchApp.jsx
391 lines (345 loc) · 10.9 KB
/
SearchApp.jsx
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
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import { fetchSearchResults } from '../actions';
import { formatResponseString } from '../utils';
import recordEvent from '../../../platform/monitoring/record-event';
import { replaceWithStagingDomain } from '../../../platform/utilities/environment/stagingDomains';
import { focusElement } from 'platform/utilities/ui';
import DowntimeNotification, {
externalServices,
} from '../../../platform/monitoring/DowntimeNotification';
import LoadingIndicator from '@department-of-veterans-affairs/formation-react/LoadingIndicator';
import IconSearch from '@department-of-veterans-affairs/formation-react/IconSearch';
import Pagination from '@department-of-veterans-affairs/formation-react/Pagination';
import AlertBox from '@department-of-veterans-affairs/formation-react/AlertBox';
import SearchBreadcrumbs from '../components/SearchBreadcrumbs';
const SCREENREADER_FOCUS_CLASSNAME = 'sr-focus';
class SearchApp extends React.Component {
static propTypes = {
search: PropTypes.shape({
results: PropTypes.array,
}).isRequired,
fetchSearchResults: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
let userInputFromAddress = '';
let page;
if (this.props.router.location.query) {
userInputFromAddress = this.props.router.location.query.query;
page = this.props.router.location.query.page;
}
this.state = {
userInput: userInputFromAddress,
currentResultsQuery: userInputFromAddress,
page,
};
if (!userInputFromAddress) {
window.location.href = '/';
}
}
componentDidMount() {
// If there's data in userInput, it must have come from the address bar, so we immediately hit the API.
const { userInput, page } = this.state;
if (userInput) {
this.props.fetchSearchResults(userInput, page);
}
}
componentDidUpdate(prevProps) {
const hasNewResults =
prevProps.search.loading && !this.props.search.loading;
if (hasNewResults) {
const shouldFocusOnResults = this.props.search.searchesPerformed > 1;
if (shouldFocusOnResults) {
focusElement(`.${SCREENREADER_FOCUS_CLASSNAME}`);
}
}
}
handlePageChange = page => {
this.setState({ page }, () => this.handleSearch());
};
handleSearch = e => {
if (e) e.preventDefault();
const { userInput, currentResultsQuery, page } = this.state;
const queryChanged = userInput !== currentResultsQuery;
const nextPage = queryChanged ? 1 : page;
// Update URL
this.props.router.push({
pathname: '',
query: {
query: userInput,
page: nextPage,
},
});
// Fetch new results
this.props.fetchSearchResults(userInput, nextPage);
// Update query is necessary
if (queryChanged) {
this.setState({ currentResultsQuery: userInput, page: 1 });
}
};
handleInputChange = event => {
this.setState({
userInput: event.target.value,
});
};
renderResults() {
const { loading, errors } = this.props.search;
const hasErrors = !!(errors && errors.length > 0);
const nonBlankUserInput =
this.state.userInput &&
this.state.userInput.replace(/\s/g, '').length > 0;
// Reusable search input
const searchInput = (
<form onSubmit={this.handleSearch} className="va-flex search-box">
<input
type="text"
name="query"
aria-label="Enter the word or phrase you'd like to search for"
value={this.state.userInput}
onChange={this.handleInputChange}
/>
<button type="submit" disabled={!nonBlankUserInput}>
<IconSearch color="#fff" />
<span>Search</span>
</button>
</form>
);
if (hasErrors && !loading) {
return (
<div className="usa-width-three-fourths medium-8 small-12 columns error">
<AlertBox
status="error"
headline="Your search didn't go through"
content="We’re sorry. Something went wrong on our end, and your search didn't go through. Please try again."
/>
{searchInput}
</div>
);
}
return (
<div>
{searchInput}
{this.renderResultsCount()}
<hr />
{this.renderRecommendedResults()}
{this.renderResultsList()}
<hr id="hr-search-bottom" />
{this.renderResultsFooter()}
</div>
);
}
renderRecommendedResults() {
const { loading, recommendedResults } = this.props.search;
if (!loading && recommendedResults && recommendedResults.length > 0) {
return (
<div>
<h4 className={SCREENREADER_FOCUS_CLASSNAME}>
Our Top Recommendations for You
</h4>
<ul className="results-list">
{recommendedResults.map(r =>
this.renderWebResult(r, 'description', true),
)}
</ul>
<hr />
</div>
);
}
return null;
}
renderResultsCount() {
const {
currentPage,
perPage,
totalPages,
totalEntries,
loading,
} = this.props.search;
let resultRangeEnd = currentPage * perPage;
if (currentPage === totalPages) {
resultRangeEnd = totalEntries;
}
const resultRangeStart = (currentPage - 1) * perPage + 1;
if (loading || !totalEntries) return null;
/* eslint-disable prettier/prettier */
return (
<p aria-live="polite" aria-relevant="additions text">
Showing{' '}
{totalEntries === 0 ? '0' : `${resultRangeStart}-${resultRangeEnd}`} of{' '}
{totalEntries} results
<span className="usa-sr-only">
{' '}
for "{this.props.router.location.query.query}"
</span>
</p>
);
/* eslint-enable prettier/prettier */
}
renderResultsList() {
const { results, loading } = this.props.search;
if (loading) {
return <LoadingIndicator message="Loading results..." />;
}
if (results && results.length > 0) {
return (
<ul className="results-list">
{results.map(r => this.renderWebResult(r))}
</ul>
);
}
return (
<p>
Sorry, no results found. Try again using different (or fewer) words.
</p>
);
}
/* eslint-disable react/no-danger */
renderWebResult(result, snippetKey = 'snippet', isBestBet = false) {
const strippedTitle = formatResponseString(result.title, true);
return (
<li key={result.url} className="result-item">
<a
className={`result-title ${SCREENREADER_FOCUS_CLASSNAME}`}
href={replaceWithStagingDomain(result.url)}
onClick={
isBestBet
? () =>
recordEvent({
event: 'nav-searchresults',
'nav-path': `Recommended Results -> ${strippedTitle}`,
})
: null
}
>
<h5
dangerouslySetInnerHTML={{
__html: strippedTitle,
}}
/>
</a>
<p className="result-url">{replaceWithStagingDomain(result.url)}</p>
<p
className="result-desc"
dangerouslySetInnerHTML={{
__html: formatResponseString(result[snippetKey]),
}}
/>
</li>
);
}
/* eslint-enable react/no-danger */
renderResultsFooter() {
const { currentPage, totalPages } = this.props.search;
return (
<div className="va-flex results-footer">
<span className="powered-by">Powered by Search.gov</span>
<Pagination
onPageSelect={this.handlePageChange}
page={currentPage}
pages={totalPages}
maxPageListLength={5}
/>
</div>
);
}
render() {
return (
<div className="search-app">
<SearchBreadcrumbs query={this.props.search.query} />
<div className="row">
<div className="columns">
<h2>Search VA.gov</h2>
</div>
</div>
<div className="row">
<div className="usa-width-three-fourths medium-8 small-12 columns">
<DowntimeNotification
appTitle="Search App"
dependencies={[externalServices.search]}
>
{this.renderResults()}
</DowntimeNotification>
</div>
<div className="usa-width-one-fourth medium-4 small-12 columns sidebar">
<h4 className="highlight">More VA Search Tools</h4>
<ul>
<li>
<a
href="https://www.index.va.gov/search/va/bva.jsp"
onClick={() =>
recordEvent({
event: 'nav-searchresults',
'nav-path':
'More VA Search Tools -> Look up BVA decisions',
})
}
>
Look up Board of Veterans' Appeals (BVA) decisions
</a>
</li>
<li>
<a
href="https://www.index.va.gov/search/va/va_adv_search.jsp?SQ=www.benefits.va.gov/warms"
onClick={() =>
recordEvent({
event: 'nav-searchresults',
'nav-path':
'More VA Search Tools -> Search VA reference materials',
})
}
>
Search VA reference materials (WARMS)
</a>
</li>
<li>
<a
href="https://www.index.va.gov/search/va/va_adv_search.jsp?SQ=www.va.gov/vaforms,www.va.gov/vapubs,www.va.gov/vhapublications,www.vba.va.gov/pubs/forms"
onClick={() =>
recordEvent({
event: 'nav-searchresults',
'nav-path':
'More VA Search Tools -> Find VA forms and publications',
})
}
>
Find VA forms and publications
</a>
</li>
<li>
<a
href="https://www.vacareers.va.gov/job-search/index.asp"
onClick={() =>
recordEvent({
event: 'nav-searchresults',
'nav-path':
'More VA Search Tools -> Explore and apply for open VA jobs',
})
}
>
Explore and apply for open VA jobs
</a>
</li>
</ul>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { search } = state;
return { search };
}
const mapDispatchToProps = {
fetchSearchResults,
};
const SearchAppContainer = withRouter(
connect(
mapStateToProps,
mapDispatchToProps,
)(SearchApp),
);
export default SearchAppContainer;