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.other_players.map(other => (
131 <span key={other.id}>
140 function fetch_method_json(method, api = '', data = {}) {
141 const response = fetch(api, {
144 'Content-Type': 'application/json'
146 body: JSON.stringify(data)
151 function fetch_post_json(api = '', data = {}) {
152 return fetch_method_json('POST', api, data);
155 async function fetch_put_json(api = '', data = {}) {
156 return fetch_method_json('PUT', api, data);
159 class CategoryRequest extends React.PureComponent {
162 this.category = React.createRef();
164 this.handle_change = this.handle_change.bind(this);
165 this.handle_submit = this.handle_submit.bind(this);
168 handle_change(event) {
169 const category_input = this.category.current;
170 const category = category_input.value;
172 if (/[0-9]/.test(category))
173 category_input.setCustomValidity("");
176 handle_submit(event) {
177 const form = event.currentTarget;
178 const category_input = this.category.current;
179 const category = category_input.value;
181 /* Prevent the default page-changing form-submission behavior. */
182 event.preventDefault();
184 const match = category.match(/[0-9]+/);
185 if (match === null) {
186 category_input.setCustomValidity("Category must include a number");
187 form.reportValidity();
191 fetch_post_json("prompts", {
192 items: parseInt(match[0], 10),
201 <div className="category-request">
202 <h2>Submit a Category</h2>
204 Suggest a category to play. Don't forget to include the
205 number of items for each person to submit.
208 <form onSubmit={this.handle_submit} >
209 <div className="form-field large">
213 placeholder="6 things at the beach"
216 onChange={this.handle_change}
221 <div className="form-field large">
222 <button type="submit">
233 const PromptOptions = React.memo(props => {
235 if (props.prompts.length === 0)
239 <div className="prompt-options">
240 <h2>Vote on Categories</h2>
242 Select any categories below that you'd like to play.
243 You can choose as many as you'd like.
245 {props.prompts.map(p => {
248 className="vote-button"
250 onClick={() => fetch_post_json(`vote/${p.id}`) }
253 <div className="vote-choices">
258 className="vote-choice"
272 const LetsPlay = React.memo(props => {
274 function handle_click(prompt_id) {
278 const quorum = Math.round((props.num_players + 1) / 2);
279 const max_votes = props.prompts.reduce(
280 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
282 if (max_votes < quorum)
285 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
286 const index = Math.floor(Math.random() * candidates.length);
287 const winner = candidates[index];
290 <div className="lets-play">
293 That should be enough voting. If you're not waiting for any
294 other players to join, then let's start.
297 className="lets-play"
298 onClick={() => fetch_post_json(`start/${winner.id}`) }
306 class ActivePrompt extends React.PureComponent {
310 const items = props.prompt.items;
316 this.answers = [...Array(items)].map(() => React.createRef());
317 this.handle_submit = this.handle_submit.bind(this);
320 async handle_submit(event) {
321 const form = event.currentTarget;
323 /* Prevent the default page-changing form-submission behavior. */
324 event.preventDefault();
326 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
327 answers: this.answers.map(r => r.current.value)
329 if (response.status == 200) {
330 const result = await response.json();
331 if (! result.valid) {
332 add_message("danger", result.message);
336 add_message("danger", "An error occurred submitting your answers");
340 /* Everything worked. Server is happy with our answers. */
348 if (this.state.submitted)
350 <div className="please-wait">
351 <h2>{this.props.players_answered}/
352 {this.props.players_total} players have responded</h2>
354 Please wait for the rest of the players to submit their answers.
360 <div className="active-prompt">
361 <h2>The Game of Empathy</h2>
363 Remember, you're trying to match your answers with
364 what the other players submit.
365 Give {this.props.prompt.items} answers for the following prompt:
367 <h2>{this.props.prompt.prompt}</h2>
368 <form onSubmit={this.handle_submit}>
369 {Array(this.props.prompt.items).fill(null).map((whocares,i) => {
373 className="form-field large">
379 ref={this.answers[i]}
387 className="form-field large">
388 <button type="submit">
399 class Game extends React.PureComponent {
412 set_game_info(info) {
418 set_player_info(info) {
424 set_other_player_info(info) {
425 const other_players_copy = [...this.state.other_players];
426 const idx = other_players_copy.findIndex(o => o.id === info.id);
428 other_players_copy[idx] = info;
430 other_players_copy.push(info);
433 other_players: other_players_copy
437 set_prompts(prompts) {
443 add_or_update_prompt(prompt) {
444 const prompts_copy = [...this.state.prompts];
445 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
447 prompts_copy[idx] = prompt;
449 prompts_copy.push(prompt);
452 prompts: prompts_copy
456 set_active_prompt(prompt) {
458 active_prompt: prompt
462 set_players_answered(players_answered) {
464 players_answered: players_answered
475 const state = this.state;
476 const players_total = 1 + state.other_players.length;
480 <div className="scores">
483 {state.scores.scores.map(score => {
485 <li key={score.player}>
486 {score.player}: {score.score}
491 <h2>Words submitted</h2>
493 {state.scores.words.map(word => {
497 {word.players.map(p => {
499 <span key={p}>{p}{" "}</span>
508 onClick={() => fetch_post_json('reset') }
516 if (state.active_prompt) {
518 prompt={state.active_prompt}
519 players_answered={state.players_answered}
520 players_total={players_total}
527 id={state.game_info.id}
528 url={state.game_info.url}
533 player={state.player_info}
534 other_players={state.other_players}
536 <p key="spacer"></p>,
538 key="category-request"
542 prompts={state.prompts}
546 num_players={1+state.other_players.length}
547 prompts={state.prompts}
553 ReactDOM.render(<Game
554 ref={(me) => window.game = me}
555 />, document.getElementById("empathy"));