forked from rotemmiz/react-native-sample-app-movies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchScreen.js
372 lines (331 loc) · 9.74 KB
/
SearchScreen.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
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
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
ActivityIndicator,
ListView,
Platform,
StyleSheet,
Text,
View,
} = ReactNative;
var TimerMixin = require('react-timer-mixin');
var invariant = require('fbjs/lib/invariant');
var dismissKeyboard = require('dismissKeyboard');
var MovieCell = require('./MovieCell');
var MovieScreen = require('./MovieScreen');
var SearchBar = require('SearchBar');
/**
* This is for demo purposes only, and rate limited.
* In case you want to use the Rotten Tomatoes' API on a real app you should
* create an account at http://developer.rottentomatoes.com/
*/
var API_URL = 'http://api.rottentomatoes.com/api/public/v1.0/';
var API_KEYS = [
'7waqfqbprs7pajbz28mqf6vz',
// 'y4vwv8m33hed9ety83jmv52f', Fallback api_key
];
// Results should be cached keyed by the query
// with values of null meaning "being fetched"
// and anything besides null and undefined
// as the result of a valid query
var resultsCache = {
dataForQuery: {},
nextPageNumberForQuery: {},
totalForQuery: {},
};
var LOADING = {};
var SearchScreen = React.createClass({
mixins: [TimerMixin],
timeoutID: (null: any),
getInitialState: function() {
return {
isLoading: false,
isLoadingTail: false,
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
filter: '',
queryNumber: 0,
};
},
componentDidMount: function() {
this.searchMovies('');
},
_urlForQueryAndPage: function(query: string, pageNumber: number): string {
var apiKey = API_KEYS[this.state.queryNumber % API_KEYS.length];
if (query) {
return (
API_URL + 'movies.json?apikey=' + apiKey + '&q=' +
encodeURIComponent(query) + '&page_limit=20&page=' + pageNumber
);
} else {
// With no query, load latest movies
return (
API_URL + 'lists/movies/in_theaters.json?apikey=' + apiKey +
'&page_limit=20&page=' + pageNumber
);
}
},
searchMovies: function(query: string) {
this.timeoutID = null;
this.setState({filter: query});
var cachedResultsForQuery = resultsCache.dataForQuery[query];
if (cachedResultsForQuery) {
if (!LOADING[query]) {
this.setState({
dataSource: this.getDataSource(cachedResultsForQuery),
isLoading: false
});
} else {
this.setState({isLoading: true});
}
return;
}
LOADING[query] = true;
resultsCache.dataForQuery[query] = null;
this.setState({
isLoading: true,
queryNumber: this.state.queryNumber + 1,
isLoadingTail: false,
});
fetch(this._urlForQueryAndPage(query, 1))
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
throw new Error('responseData is:' + responseData);
}
LOADING[query] = false;
resultsCache.totalForQuery[query] = responseData.total;
resultsCache.dataForQuery[query] = responseData.movies;
resultsCache.nextPageNumberForQuery[query] = 2;
if (this.state.filter !== query) {
// do not update state if the query is stale
return;
}
this.setState({
isLoading: false,
dataSource: this.getDataSource(responseData.movies),
});
})
.catch((error) => {
LOADING[query] = false;
resultsCache.dataForQuery[query] = undefined;
this.setState({
dataSource: this.getDataSource([]),
isLoading: false,
});
})
.done();
},
hasMore: function(): boolean {
var query = this.state.filter;
if (!resultsCache.dataForQuery[query]) {
return true;
}
return (
resultsCache.totalForQuery[query] !==
resultsCache.dataForQuery[query].length
);
},
onEndReached: function() {
var query = this.state.filter;
if (!this.hasMore() || this.state.isLoadingTail) {
// We're already fetching or have all the elements so noop
return;
}
if (LOADING[query]) {
return;
}
LOADING[query] = true;
this.setState({
queryNumber: this.state.queryNumber + 1,
isLoadingTail: true,
});
var page = resultsCache.nextPageNumberForQuery[query];
invariant(page != null, 'Next page number for "%s" is missing', query);
fetch(this._urlForQueryAndPage(query, page))
.then((response) => response.json())
.catch((error) => {
console.error(error);
LOADING[query] = false;
this.setState({
isLoadingTail: false,
});
})
.then((responseData) => {
var moviesForQuery = resultsCache.dataForQuery[query].slice();
LOADING[query] = false;
// We reached the end of the list before the expected number of results
if (!responseData.movies) {
resultsCache.totalForQuery[query] = moviesForQuery.length;
} else {
for (var i in responseData.movies) {
moviesForQuery.push(responseData.movies[i]);
}
resultsCache.dataForQuery[query] = moviesForQuery;
resultsCache.nextPageNumberForQuery[query] += 1;
}
if (this.state.filter !== query) {
// do not update state if the query is stale
return;
}
this.setState({
isLoadingTail: false,
dataSource: this.getDataSource(resultsCache.dataForQuery[query]),
});
})
.done();
},
getDataSource: function(movies: Array<any>): ListView.DataSource {
return this.state.dataSource.cloneWithRows(movies);
},
selectMovie: function(movie: Object) {
if (Platform.OS === 'ios') {
this.props.navigator.push({
title: movie.title,
component: MovieScreen,
passProps: {movie},
});
} else {
dismissKeyboard();
this.props.navigator.push({
title: movie.title,
name: 'movie',
movie: movie,
});
}
},
onSearchChange: function(event: Object) {
var filter = event.nativeEvent.text.toLowerCase();
this.clearTimeout(this.timeoutID);
this.timeoutID = this.setTimeout(() => this.searchMovies(filter), 100);
},
renderFooter: function() {
if (!this.hasMore() || !this.state.isLoadingTail) {
return <View style={styles.scrollSpinner} />;
}
return <ActivityIndicator style={styles.scrollSpinner} />;
},
renderSeparator: function(
sectionID: number | string,
rowID: number | string,
adjacentRowHighlighted: boolean
) {
var style = styles.rowSeparator;
if (adjacentRowHighlighted) {
style = [style, styles.rowSeparatorHide];
}
return (
<View key={'SEP_' + sectionID + '_' + rowID} style={style}/>
);
},
renderRow: function(
movie: Object,
sectionID: number | string,
rowID: number | string,
highlightRowFunc: (sectionID: ?number | string, rowID: ?number | string) => void,
) {
return (
<MovieCell
key={movie.id}
onSelect={() => this.selectMovie(movie)}
onHighlight={() => highlightRowFunc(sectionID, rowID)}
onUnhighlight={() => highlightRowFunc(null, null)}
movie={movie}
/>
);
},
render: function() {
var content = this.state.dataSource.getRowCount() === 0 ?
<NoMovies
filter={this.state.filter}
isLoading={this.state.isLoading}
/> :
<ListView
ref="listview"
renderSeparator={this.renderSeparator}
dataSource={this.state.dataSource}
renderFooter={this.renderFooter}
renderRow={this.renderRow}
onEndReached={this.onEndReached}
automaticallyAdjustContentInsets={false}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps={true}
showsVerticalScrollIndicator={false}
/>;
return (
<View style={styles.container}>
<SearchBar
onSearchChange={this.onSearchChange}
isLoading={this.state.isLoading}
onFocus={() =>
this.refs.listview && this.refs.listview.getScrollResponder().scrollTo({ x: 0, y: 0 })}
/>
<View style={styles.separator} />
{content}
</View>
);
},
});
class NoMovies extends React.Component {
render() {
var text = '';
if (this.props.filter) {
text = `No results for "${this.props.filter}"`;
} else if (!this.props.isLoading) {
// If we're looking at the latest movies, aren't currently loading, and
// still have no results, show a message
text = 'No movies found';
}
return (
<View style={[styles.container, styles.centerText]}>
<Text style={styles.noMoviesText}>{text}</Text>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
centerText: {
alignItems: 'center',
},
noMoviesText: {
marginTop: 80,
color: '#888888',
},
separator: {
height: 1,
backgroundColor: '#eeeeee',
},
scrollSpinner: {
marginVertical: 20,
},
rowSeparator: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
height: 1,
marginLeft: 4,
},
rowSeparatorHide: {
opacity: 0.0,
},
});
module.exports = SearchScreen;