1 function undisplay(element) {
2 element.style.display="none";
5 function add_message(severity, message) {
6 message = `<div class="message ${severity}" onclick="undisplay(this)">
7 <span class="hide-button" onclick="undisplay(this.parentElement)">×</span>
10 const message_area = document.getElementById('message-area');
11 message_area.insertAdjacentHTML('beforeend', message);
14 /*********************************************************
15 * Handling server-sent event stream *
16 *********************************************************/
18 const events = new EventSource("events");
20 events.onerror = function(event) {
21 if (event.target.readyState === EventSource.CLOSED) {
23 add_message("danger", "Connection to server lost.");
28 events.addEventListener("game-info", event => {
29 const info = JSON.parse(event.data);
31 window.game.set_game_info(info);
34 events.addEventListener("player-info", event => {
35 const info = JSON.parse(event.data);
37 window.game.set_player_info(info);
40 events.addEventListener("player-enter", event => {
41 const info = JSON.parse(event.data);
43 window.game.set_other_player_info(info);
46 events.addEventListener("player-update", event => {
47 const info = JSON.parse(event.data);
49 if (info.id === window.game.state.player_info.id)
50 window.game.set_player_info(info);
52 window.game.set_other_player_info(info);
55 events.addEventListener("game-state", event => {
56 const state = JSON.parse(event.data);
58 window.game.set_prompts(state.prompts);
60 window.game.set_active_prompt(state.active_prompt);
62 window.game.set_scores(state.scores);
65 events.addEventListener("prompt", event => {
66 const prompt = JSON.parse(event.data);
68 window.game.add_or_update_prompt(prompt);
71 events.addEventListener("start", event => {
72 const prompt = JSON.parse(event.data);
74 window.game.set_active_prompt(prompt);
77 events.addEventListener("answered", event => {
78 const players_answered = JSON.parse(event.data);
80 window.game.set_players_answered(players_answered);
83 events.addEventListener("scores", event => {
84 const scores = JSON.parse(event.data);
86 window.game.set_scores(scores);
89 /*********************************************************
90 * Game and supporting classes *
91 *********************************************************/
93 function copy_to_clipboard(id)
95 const tmp = document.createElement("input");
96 tmp.setAttribute("value", document.getElementById(id).innerHTML);
97 document.body.appendChild(tmp);
99 document.execCommand("copy");
100 document.body.removeChild(tmp);
103 const GameInfo = React.memo(props => {
108 <div className="game-info">
109 <span className="game-id">{props.id}</span>
111 Share this link to invite friends:{" "}
112 <span id="game-share-url">{props.url}</span>
116 onClick={() => copy_to_clipboard('game-share-url')}
122 const PlayerInfo = React.memo(props => {
123 if (! props.player.id)
127 <div className="player-info">
128 <span className="players-header">Players: </span>
130 {props.player.score > 0 ? ` (${props.player.score})` : ""}
131 {props.other_players.map(other => (
132 <span key={other.id}>
135 {other.score > 0 ? ` (${other.score})` : ""}
142 function fetch_method_json(method, api = '', data = {}) {
143 const response = fetch(api, {
146 'Content-Type': 'application/json'
148 body: JSON.stringify(data)
153 function fetch_post_json(api = '', data = {}) {
154 return fetch_method_json('POST', api, data);
157 async function fetch_put_json(api = '', data = {}) {
158 return fetch_method_json('PUT', api, data);
161 class CategoryRequest extends React.PureComponent {
164 this.category = React.createRef();
166 this.handle_change = this.handle_change.bind(this);
167 this.handle_submit = this.handle_submit.bind(this);
170 handle_change(event) {
171 const category_input = this.category.current;
172 const category = category_input.value;
174 if (/[0-9]/.test(category))
175 category_input.setCustomValidity("");
178 handle_submit(event) {
179 const form = event.currentTarget;
180 const category_input = this.category.current;
181 const category = category_input.value;
183 /* Prevent the default page-changing form-submission behavior. */
184 event.preventDefault();
186 const match = category.match(/[0-9]+/);
187 if (match === null) {
188 category_input.setCustomValidity("Category must include a number");
189 form.reportValidity();
193 fetch_post_json("prompts", {
194 items: parseInt(match[0], 10),
203 <div className="category-request">
204 <h2>Submit a Category</h2>
206 Suggest a category to play. Don't forget to include the
207 number of items for each person to submit.
210 <form onSubmit={this.handle_submit} >
211 <div className="form-field large">
215 placeholder="6 things at the beach"
218 onChange={this.handle_change}
223 <div className="form-field large">
224 <button type="submit">
235 const PromptOptions = React.memo(props => {
237 if (props.prompts.length === 0)
241 <div className="prompt-options">
242 <h2>Vote on Categories</h2>
244 Select any categories below that you'd like to play.
245 You can choose as many as you'd like.
247 {props.prompts.map(p => {
250 className="vote-button"
252 onClick={() => fetch_post_json(`vote/${p.id}`) }
255 <div className="vote-choices">
260 className="vote-choice"
274 const LetsPlay = React.memo(props => {
276 function handle_click(prompt_id) {
280 const quorum = Math.round((props.num_players + 1) / 2);
281 const max_votes = props.prompts.reduce(
282 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
284 if (max_votes < quorum)
287 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
288 const index = Math.floor(Math.random() * candidates.length);
289 const winner = candidates[index];
292 <div className="lets-play">
295 That should be enough voting. If you're not waiting for any
296 other players to join, then let's start.
299 className="lets-play"
300 onClick={() => fetch_post_json(`start/${winner.id}`) }
308 class ActivePrompt extends React.PureComponent {
312 const items = props.prompt.items;
318 this.answers = [...Array(items)].map(() => React.createRef());
319 this.handle_submit = this.handle_submit.bind(this);
322 async handle_submit(event) {
323 const form = event.currentTarget;
325 /* Prevent the default page-changing form-submission behavior. */
326 event.preventDefault();
328 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
329 answers: this.answers.map(r => r.current.value)
331 if (response.status == 200) {
332 const result = await response.json();
333 if (! result.valid) {
334 add_message("danger", result.message);
338 add_message("danger", "An error occurred submitting your answers");
342 /* Everything worked. Server is happy with our answers. */
350 if (this.state.submitted)
352 <div className="please-wait">
353 <h2>{this.props.players_answered}/
354 {this.props.players_total} players have responded</h2>
356 Please wait for the rest of the players to submit their answers.
362 <div className="active-prompt">
363 <h2>The Game of Empathy</h2>
365 Remember, you're trying to match your answers with
366 what the other players submit.
367 Give {this.props.prompt.items} answers for the following prompt:
369 <h2>{this.props.prompt.prompt}</h2>
370 <form onSubmit={this.handle_submit}>
371 {[...Array(this.props.prompt.items)].map((whocares,i) => {
375 className="form-field large">
381 ref={this.answers[i]}
389 className="form-field large">
390 <button type="submit">
401 class Game extends React.PureComponent {
414 set_game_info(info) {
420 set_player_info(info) {
426 set_other_player_info(info) {
427 const other_players_copy = [...this.state.other_players];
428 const idx = other_players_copy.findIndex(o => o.id === info.id);
430 other_players_copy[idx] = info;
432 other_players_copy.push(info);
435 other_players: other_players_copy
439 set_prompts(prompts) {
445 add_or_update_prompt(prompt) {
446 const prompts_copy = [...this.state.prompts];
447 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
449 prompts_copy[idx] = prompt;
451 prompts_copy.push(prompt);
454 prompts: prompts_copy
458 set_active_prompt(prompt) {
460 active_prompt: prompt
464 set_players_answered(players_answered) {
466 players_answered: players_answered
477 const state = this.state;
478 const players_total = 1 + state.other_players.length;
482 <div className="scores">
485 {state.scores.scores.map(score => {
487 <li key={score.player}>
488 {score.player}: {score.score}
493 <h2>Words submitted</h2>
495 {state.scores.words.map(word => {
499 {word.players.map(p => {
501 <span key={p}>{p}{" "}</span>
510 onClick={() => fetch_post_json('reset') }
518 if (state.active_prompt) {
520 prompt={state.active_prompt}
521 players_answered={state.players_answered}
522 players_total={players_total}
529 id={state.game_info.id}
530 url={state.game_info.url}
535 player={state.player_info}
536 other_players={state.other_players}
538 <p key="spacer"></p>,
540 key="category-request"
544 prompts={state.prompts}
548 num_players={1+state.other_players.length}
549 prompts={state.prompts}
555 ReactDOM.render(<Game
556 ref={(me) => window.game = me}
557 />, document.getElementById("empathy"));