-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
183 lines (156 loc) · 5.04 KB
/
index.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
const UID = window.shortid.generate;
const {BrowserRouter, Route, NavLink} = window.ReactRouterDOM;
const {kebabcase, sortby} = window.lodash;
let sortBy = sortby;
const DATA = {
"characters": [{
"name": "Luke Skywalker",
"url": "https://swapi.co/api/people/1/"
}, {
"name": "Darth Vader",
"url": "https://swapi.co/api/people/4/"
}, {
"name": "Obi-wan Kenobi",
"url": "https://swapi.co/api/people/unknown/" // TODO: get the ID
}, {
"name": "R2-D2",
"url": "https://swapi.co/api/people/2/" // id 2 is C-3PO!
}]
};
const ROMANS = {
1: 'I',
2: 'II',
3: 'III',
4: 'IV',
5: 'V',
6: 'VI',
7: 'VII'
};
function App () {
let characterLinks = DATA.characters.reduce((links, character) => {
let id = parseId(character.url);
let slug = kebabcase(character.name);
return links.concat({
name: character.name,
path: id && `/${id}/${slug}`
});
}, []);
return (
<BrowserRouter>
<main className="Main">
<header className="Header">
<h1 className="Brand">SWDB</h1>
</header>
<div className="Main__content">
<section className="Characters">
<h2 className="Heading">Choose a Character</h2>
<ul className="CharacterList">
{characterLinks.map(props => <Character key={UID()} {...props} />)}
</ul>
</section>
<Route path="/:id/:slug" component={MovieList} location={location} key={location.key} />
</div>
</main>
</BrowserRouter>
);
}
function Character ({name, path}) {
var className = 'CharacterList__item Character';
if (!path) className += ' Character--error';
return (
<li className={className}>
{path
? <NavLink className="Character__link" activeClassName="Character__link--active" to={path}>{name}</NavLink>
: name}
</li>
);
}
class MovieList extends React.Component {
constructor () {
super();
this.state = {
characters: {},
movies: {}
};
this.getMovies.bind(this);
}
getMovies (characterId) {
var movieIds;
// fetch list of films for character, then fetch data for each film
fetch('https://swapi.co/api/people/' + characterId + '/')
.then(res => res.json())
.then(data => {
movieIds = data.films.map(url => parseId(url));
let requests = data.films
// only fetch films if they haven't been already
.filter(url => !Object.keys(this.state.movies).includes(parseId(url)))
.map(url => fetch(url).then(res => res.json()));
if (requests) {
document.body.classList.add('is-loading');
return Promise.all(requests);
} else {
return Promise.all();
}
})
.then(data => {
document.body.classList.remove('is-loading');
let movies = Object.assign({},
this.state.movies,
data.reduce((movies, movie) => {
movies[parseId(movie.url)] = {
title: movie.title,
releaseDate: movie.release_date,
openingCrawl: movie.opening_crawl,
episodeId: movie.episode_id
};
return movies;
}, {})
);
// sort movies by episode # (API order seems arbitrary)
let movieIdsByEpisode = sortBy(movieIds, id => movies[id].episodeId);
// data is fetched once, then cached in component state
this.setState({
characters: Object.assign(this.state.characters, {
[characterId]: {
name: DATA.characters.find(c => parseId(c.url) === characterId).name,
movies: movieIdsByEpisode
}
}),
movies
});
})
.catch(alert);
}
render () {
let {id} = this.props.match.params;
if (!id || !parseInt(id, 10)) return null; // CodePen's own router supplying a 'boomerang' value sometimes?
if (!this.state.characters[id]) {
this.getMovies(id);
return null; // intentionally optimistic loader
}
let {name, movies} = this.state.characters[id];
let movieData = movies.map(id => this.state.movies[id]);
return (
<section className="MovieList">
{movieData.map(props => <Movie key={UID()} {...props} />)}
</section>
);
}
}
function Movie ({title, releaseDate, episodeId}) {
// PST timezone offset avoids inconsistencies due to local tz conversion
let formattedReleaseDate = dateFns.format(releaseDate + 'T00:00:00−7:00', 'dddd, MMMM D YYYY');
return (
<section className={`MovieList__item Movie Movie--episode-${episodeId}`}>
<h3 className="Movie__title">{title}</h3>
<h4 className="Movie__episode" title={"Episode " + episodeId}>{ROMANS[episodeId]}</h4>
<time className="Movie__release" dateTime={releaseDate}>{formattedReleaseDate}</time>
</section>
);
}
function parseId (url) {
return url.split('/').find(segment => parseInt(segment, 10));
}
document.addEventListener('DOMContentLoaded', () => {
window.ReactDOM.render(<App />, document.getElementById('root'));
});