File size: 6,222 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
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
import clsx from 'clsx';
import { find, groupBy, isEqual, partition, property } from 'lodash';
import { Fragment, Component } from 'react';
import ReactDOM from 'react-dom';
import Item from './item';

/**
 * Style depenedencies
 */
import './style.scss';

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};

type Suggestion = { name: string; label: string; category?: string };

type CategorizedSuggestions = {
	category?: string;
	categoryKey: string;
	suggestions: ( Suggestion & {
		originalIndex: number;
		index: number;
	} )[];
}[];

interface Props {
	query: string;
	suggestions: Suggestion[];
	suggest: ( suggestion: Suggestion, index: number ) => void;
	railcar?: unknown;
	title: string;
	className?: string;
	onSuggestionItemMount?: ( arg: { suggestionIndex: number; index: number } ) => void;
}

interface State {
	lastSuggestions: null | Suggestion[];
	suggestionPosition: number;
}

class Suggestions extends Component< Props, State > {
	static defaultProps = {
		query: '',
		onSuggestionItemMount: noop,
	};

	state = {
		lastSuggestions: null,
		suggestionPosition: 0,
	};

	refsCollection: Record< string, HTMLButtonElement | null > = {};

	static getDerivedStateFromProps( props: Props, state: State ): State | null {
		if ( isEqual( props.suggestions, state.lastSuggestions ) ) {
			return null;
		}

		return {
			lastSuggestions: props.suggestions,
			suggestionPosition: 0,
		};
	}

	getSuggestionsCount = (): number => this.props.suggestions.length;

	getOriginalIndexFromPosition = ( index: number ): number =>
		this.getCategories().reduce( ( foundIndex, category ) => {
			if ( foundIndex !== -1 ) {
				return foundIndex;
			}

			const suggestion = find( category.suggestions, { index } );
			return suggestion ? suggestion.originalIndex : -1;
		}, -1 );

	suggest = ( originalIndex: number ): void =>
		this.props.suggest( this.props.suggestions[ originalIndex ], originalIndex );

	moveSelectionDown = (): void => {
		const position = ( this.state.suggestionPosition + 1 ) % this.getSuggestionsCount();
		const element = ReactDOM.findDOMNode( this.refsCollection[ 'suggestion_' + position ] );
		if ( element instanceof Element ) {
			element.scrollIntoView( { block: 'nearest' } );
		}

		this.changePosition( position );
	};

	moveSelectionUp = (): void => {
		const position =
			( this.state.suggestionPosition - 1 + this.getSuggestionsCount() ) %
			this.getSuggestionsCount();
		const element = ReactDOM.findDOMNode( this.refsCollection[ 'suggestion_' + position ] );
		if ( element instanceof Element ) {
			element.scrollIntoView( { block: 'nearest' } );
		}

		this.changePosition( position );
	};

	changePosition = ( position: number ): void =>
		this.setState( {
			suggestionPosition: position,
		} );

	handleKeyEvent = ( event: KeyboardEvent ): void => {
		if ( this.getSuggestionsCount() === 0 ) {
			return;
		}

		switch ( event.key ) {
			case 'ArrowDown':
				this.moveSelectionDown();
				event.preventDefault();
				break;

			case 'ArrowUp':
				this.moveSelectionUp();
				event.preventDefault();
				break;

			case 'Enter':
				this.state.suggestionPosition >= 0 &&
					this.suggest( this.getOriginalIndexFromPosition( this.state.suggestionPosition ) );
				break;
		}
	};

	handleMouseDown = ( originalIndex: number ): void => {
		this.suggest( originalIndex );
	};

	handleMouseOver = ( suggestionPosition: number ): void => this.setState( { suggestionPosition } );

	getCategories(): CategorizedSuggestions {
		// We need to remember the original index of the suggestion according to the
		// `suggestions` prop for tracks and firing callbacks.
		const withOriginalIndex = this.props.suggestions.map( ( suggestion, originalIndex ) => ( {
			...suggestion,
			// this will be updated later on in this function
			index: originalIndex,
			originalIndex,
		} ) );

		const [ withCategory, withoutCategory ] = partition(
			withOriginalIndex,
			( suggestion ) => !! suggestion.category
		);

		// For all intents and purposes `groupBy` keeps the order stable
		// https://github.com/lodash/lodash/issues/2212
		const byCategory = groupBy( withCategory, property( 'category' ) );

		const categories: CategorizedSuggestions = Object.entries( byCategory ).map(
			( [ category, suggestions ] ) => ( {
				category,
				categoryKey: category,
				suggestions,
			} )
		);

		// Add uncategorised suggestions to the front, they always appear at
		// the top of the list.
		categories.unshift( {
			categoryKey: '## Uncategorized ##',
			suggestions: withoutCategory,
		} );

		let order = 0;
		for ( const category of categories ) {
			for ( const suggestion of category.suggestions ) {
				suggestion.index = order++;
			}
		}

		return categories;
	}

	render() {
		const { query, className, title } = this.props;
		const containerClass = clsx( 'suggestions', className );

		if ( ! this.getSuggestionsCount() ) {
			return null;
		}

		return (
			<div className={ containerClass }>
				{ title ? <div className="suggestions__title">{ title }</div> : null }
				{ this.getCategories().map( ( { category, categoryKey, suggestions }, categoryIndex ) => (
					<Fragment key={ categoryKey }>
						{ ! categoryIndex ? null : (
							<div className="suggestions__category-heading">{ category }</div>
						) }
						{ suggestions.map( ( { index, label, originalIndex } ) => (
							// The parent component should handle key events and forward them to
							// this component. See ./README.md for details.
							// eslint-disable-next-line jsx-a11y/mouse-events-have-key-events
							<Item
								key={ originalIndex }
								hasHighlight={ index === this.state.suggestionPosition }
								query={ query }
								onMount={ () =>
									this.props.onSuggestionItemMount?.( {
										suggestionIndex: originalIndex,
										index,
									} )
								}
								onMouseDown={ () => this.handleMouseDown( originalIndex ) }
								onMouseOver={ () => this.handleMouseOver( index ) }
								label={ label }
								ref={ ( suggestion ) => {
									this.refsCollection[ 'suggestion_' + index ] = suggestion;
								} }
							/>
						) ) }
					</Fragment>
				) ) }
			</div>
		);
	}
}

export default Suggestions;