File size: 1,912 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import page from '@automattic/calypso-router';
import { map } from 'lodash';
import PropTypes from 'prop-types';
import { stringify } from 'qs';
import { Component } from 'react';
import EmptyContent from 'calypso/components/empty-content';
import SearchCard from 'calypso/components/search-card';
import { addQueryArgs } from 'calypso/lib/url';
import DocsSelectorsResult from './result';

export default class DocsSelectorsSearch extends Component {
	static propTypes = {
		search: PropTypes.string,
	};

	state = {};

	componentDidMount() {
		this.request( this.props.search );
	}

	componentDidUpdate( prevProps ) {
		if ( prevProps.search !== this.props.search ) {
			this.request( this.props.search );
		}
	}

	request = async ( search ) => {
		const query = stringify( { search } );

		try {
			const res = await fetch( `/devdocs/service/selectors?${ query }` );
			if ( res.ok ) {
				const results = await res.json();
				this.setState( { results } );
			}
		} catch ( error ) {
			// Do nothing.
		}
	};

	onSearch( search ) {
		page( addQueryArgs( { search }, '/devdocs/selectors' ) );
	}

	render() {
		const { search } = this.props;
		const { results } = this.state;

		return (
			<div>
				<SearchCard
					// eslint-disable-next-line jsx-a11y/no-autofocus
					autoFocus
					placeholder="Search selectors…"
					analyticsGroup="Docs"
					initialValue={ search }
					delaySearch
					onSearch={ this.onSearch }
				/>
				{ results && ! results.length && (
					<EmptyContent title="No selectors found" line="Try another search query" />
				) }
				<ul className="docs-selectors__results">
					{ map( results, ( { item: { name, description, tags } } ) => (
						<li key={ name }>
							<DocsSelectorsResult
								{ ...{ name, description, tags } }
								url={ addQueryArgs( { search }, `/devdocs/selectors/${ name }` ) }
							/>
						</li>
					) ) }
				</ul>
			</div>
		);
	}
}