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);
64 window.game.set_ambiguities(state.ambiguities);
67 events.addEventListener("prompt", event => {
68 const prompt = JSON.parse(event.data);
70 window.game.add_or_update_prompt(prompt);
73 events.addEventListener("start", event => {
74 const prompt = JSON.parse(event.data);
76 window.game.set_active_prompt(prompt);
79 events.addEventListener("answered", event => {
80 const players_answered = JSON.parse(event.data);
82 window.game.set_players_answered(players_answered);
85 events.addEventListener("ambiguities", event => {
86 const ambiguities = JSON.parse(event.data);
88 window.game.set_ambiguities(ambiguities);
91 events.addEventListener("judged", event => {
92 const players_judged = JSON.parse(event.data);
94 window.game.set_players_judged(players_judged);
97 events.addEventListener("scores", event => {
98 const scores = JSON.parse(event.data);
100 window.game.set_scores(scores);
103 /*********************************************************
104 * Game and supporting classes *
105 *********************************************************/
107 function copy_to_clipboard(id)
109 const tmp = document.createElement("input");
110 tmp.setAttribute("value", document.getElementById(id).innerHTML);
111 document.body.appendChild(tmp);
113 document.execCommand("copy");
114 document.body.removeChild(tmp);
117 const GameInfo = React.memo(props => {
122 <div className="game-info">
123 <span className="game-id">{props.id}</span>
125 Share this link to invite friends:{" "}
126 <span id="game-share-url">{props.url}</span>
130 onClick={() => copy_to_clipboard('game-share-url')}
136 const PlayerInfo = React.memo(props => {
137 if (! props.player.id)
141 <div className="player-info">
142 <span className="players-header">Players: </span>
144 {props.player.score > 0 ? ` (${props.player.score})` : ""}
145 {props.other_players.map(other => (
146 <span key={other.id}>
149 {other.score > 0 ? ` (${other.score})` : ""}
156 function fetch_method_json(method, api = '', data = {}) {
157 const response = fetch(api, {
160 'Content-Type': 'application/json'
162 body: JSON.stringify(data)
167 function fetch_post_json(api = '', data = {}) {
168 return fetch_method_json('POST', api, data);
171 async function fetch_put_json(api = '', data = {}) {
172 return fetch_method_json('PUT', api, data);
175 class CategoryRequest extends React.PureComponent {
178 this.category = React.createRef();
180 this.handle_change = this.handle_change.bind(this);
181 this.handle_submit = this.handle_submit.bind(this);
184 handle_change(event) {
185 const category_input = this.category.current;
186 const category = category_input.value;
188 if (/[0-9]/.test(category))
189 category_input.setCustomValidity("");
192 handle_submit(event) {
193 const form = event.currentTarget;
194 const category_input = this.category.current;
195 const category = category_input.value;
197 /* Prevent the default page-changing form-submission behavior. */
198 event.preventDefault();
200 const match = category.match(/[0-9]+/);
201 if (match === null) {
202 category_input.setCustomValidity("Category must include a number");
203 form.reportValidity();
207 fetch_post_json("prompts", {
208 items: parseInt(match[0], 10),
217 <div className="category-request">
218 <h2>Submit a Category</h2>
220 Suggest a category to play. Don't forget to include the
221 number of items for each person to submit.
224 <form onSubmit={this.handle_submit} >
225 <div className="form-field large">
229 placeholder="6 things at the beach"
232 onChange={this.handle_change}
237 <div className="form-field large">
238 <button type="submit">
249 const PromptOptions = React.memo(props => {
251 if (props.prompts.length === 0)
255 <div className="prompt-options">
256 <h2>Vote on Categories</h2>
258 Select any categories below that you'd like to play.
259 You can choose as many as you'd like.
261 {props.prompts.map(p => {
264 className="vote-button"
266 onClick={() => fetch_post_json(`vote/${p.id}`) }
269 <div className="vote-choices">
274 className="vote-choice"
288 const LetsPlay = React.memo(props => {
290 function handle_click(prompt_id) {
294 const quorum = Math.round((props.num_players + 1) / 2);
295 const max_votes = props.prompts.reduce(
296 (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
298 if (max_votes < quorum)
301 const candidates = props.prompts.filter(p => p.votes.length >= quorum);
302 const index = Math.floor(Math.random() * candidates.length);
303 const winner = candidates[index];
306 <div className="lets-play">
309 That should be enough voting. If you're not waiting for any
310 other players to join, then let's start.
313 className="lets-play"
314 onClick={() => fetch_post_json(`start/${winner.id}`) }
322 class Ambiguities extends React.PureComponent {
328 word_groups: props.words.map(word => [word]),
334 async handle_submit() {
335 const response = await fetch_post_json(
336 `judging/${this.props.prompt.id}`,{
337 word_groups: this.state.word_groups
341 if (response.status === 200) {
342 const result = await response.json();
343 if (! result.valid) {
344 add_message("danger", result.message);
348 add_message("danger", "An error occurred submitting your answers");
358 if (this.state.selected == word) {
359 /* Second click on same word removes the word from the group. */
360 const new_groups = this.state.word_groups.filter(
361 group => (! group.includes(this.state.selected)) || (group.length > 1)).map(
363 return group.filter(w => w !== this.state.selected);
368 word_groups: [...new_groups, [word]]
370 } else if (this.state.selected) {
371 /* Click of a second word groups the two together. */
372 const new_groups = this.state.word_groups.filter(
373 group => (! group.includes(word)) || (group.length > 1)).map(
375 if (group.includes(this.state.selected)) {
376 if (! group.includes(word))
377 return [...group, word];
381 return group.filter(w => w !== word);
387 word_groups: new_groups
390 /* First click of a word selects it. */
398 if (this.state.submitted)
400 <div className="please-wait">
401 <h2>{this.props.players_judged}/
402 {this.props.players_total} players have responded</h2>
404 Please wait for the rest of the players to complete judging.
409 const btn_class = "ambiguity-button";
410 const btn_selected_class = btn_class + " selected";
413 <div className="ambiguities">
414 <h2>Judging Answers</h2>
416 Click on each pair of answers that should be scored as equivalent,
417 (and click any word twice to split it out from a group). Remember,
418 what goes around comes around, so it's best to be generous when
421 {this.state.word_groups.map(word_group => {
424 className="ambiguity-group"
427 {word_group.map(word => {
430 className={this.state.selected === word ?
431 btn_selected_class : btn_class }
433 onClick={() => this.handle_click(word)}
443 Click here when done judging:<br/>
445 onClick={() => this.handle_submit()}
455 class ActivePrompt extends React.PureComponent {
459 const items = props.prompt.items;
465 this.answers = [...Array(items)].map(() => React.createRef());
466 this.handle_submit = this.handle_submit.bind(this);
469 async handle_submit(event) {
470 const form = event.currentTarget;
472 /* Prevent the default page-changing form-submission behavior. */
473 event.preventDefault();
475 const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
476 answers: this.answers.map(r => r.current.value)
478 if (response.status === 200) {
479 const result = await response.json();
480 if (! result.valid) {
481 add_message("danger", result.message);
485 add_message("danger", "An error occurred submitting your answers");
489 /* Everything worked. Server is happy with our answers. */
497 if (this.state.submitted)
499 <div className="please-wait">
500 <h2>{this.props.players_answered}/
501 {this.props.players_total} players have responded</h2>
503 Please wait for the rest of the players to submit their answers.
509 <div className="active-prompt">
510 <h2>The Game of Empathy</h2>
512 Remember, you're trying to match your answers with
513 what the other players submit.
514 Give {this.props.prompt.items} answers for the following prompt:
516 <h2>{this.props.prompt.prompt}</h2>
517 <form onSubmit={this.handle_submit}>
518 {[...Array(this.props.prompt.items)].map((whocares,i) => {
522 className="form-field large">
528 ref={this.answers[i]}
536 className="form-field large">
537 <button type="submit">
548 class Game extends React.PureComponent {
563 set_game_info(info) {
569 set_player_info(info) {
575 set_other_player_info(info) {
576 const other_players_copy = [...this.state.other_players];
577 const idx = other_players_copy.findIndex(o => o.id === info.id);
579 other_players_copy[idx] = info;
581 other_players_copy.push(info);
584 other_players: other_players_copy
588 set_prompts(prompts) {
594 add_or_update_prompt(prompt) {
595 const prompts_copy = [...this.state.prompts];
596 const idx = prompts_copy.findIndex(p => p.id === prompt.id);
598 prompts_copy[idx] = prompt;
600 prompts_copy.push(prompt);
603 prompts: prompts_copy
607 set_active_prompt(prompt) {
609 active_prompt: prompt
613 set_players_answered(players_answered) {
615 players_answered: players_answered
619 set_ambiguities(ambiguities) {
621 ambiguities: ambiguities
625 set_players_judged(players_judged) {
627 players_judged: players_judged
638 const state = this.state;
639 const players_total = 1 + state.other_players.length;
643 <div className="scores">
646 {state.scores.scores.map(score => {
648 <li key={score.player}>
649 {score.player}: {score.score}
654 <h2>Words submitted</h2>
656 {state.scores.words.map(word => {
660 {word.players.map(p => {
662 <span key={p}>{p}{" "}</span>
671 onClick={() => fetch_post_json('reset') }
679 if (state.ambiguities){
681 prompt={state.active_prompt}
682 words={state.ambiguities}
683 players_judged={state.players_judged}
684 players_total={players_total}
688 if (state.active_prompt) {
690 prompt={state.active_prompt}
691 players_answered={state.players_answered}
692 players_total={players_total}
699 id={state.game_info.id}
700 url={state.game_info.url}
705 player={state.player_info}
706 other_players={state.other_players}
708 <p key="spacer"></p>,
710 key="category-request"
714 prompts={state.prompts}
718 num_players={1+state.other_players.length}
719 prompts={state.prompts}
725 ReactDOM.render(<Game
726 ref={(me) => window.game = me}
727 />, document.getElementById("empathy"));