Define the move_on button after the still_waiting component
[lmno.games] / empathy / empathy.jsx
1 const MAX_PROMPT_ITEMS = 20;
2
3 function undisplay(element) {
4   element.style.display="none";
5 }
6
7 function add_message(severity, message) {
8   message = `<div class="message ${severity}" onclick="undisplay(this)">
9 <span class="hide-button" onclick="undisplay(this.parentElement)">&times;</span>
10 ${message}
11 </div>`;
12   const message_area = document.getElementById('message-area');
13   message_area.insertAdjacentHTML('beforeend', message);
14 }
15
16 /*********************************************************
17  * Handling server-sent event stream                     *
18  *********************************************************/
19
20 const events = new EventSource("events");
21
22 events.onerror = function(event) {
23   if (event.target.readyState === EventSource.CLOSED) {
24     setTimeout(() => {
25       add_message("danger", "Connection to server lost.");
26     }, 1000);
27   }
28 };
29
30 events.addEventListener("game-info", event => {
31   const info = JSON.parse(event.data);
32
33   window.game.set_game_info(info);
34 });
35
36 events.addEventListener("player-info", event => {
37   const info = JSON.parse(event.data);
38
39   window.game.set_player_info(info);
40 });
41
42 events.addEventListener("player-enter", event => {
43   const info = JSON.parse(event.data);
44
45   window.game.set_other_player_info(info);
46 });
47
48 events.addEventListener("player-exit", event => {
49   const info = JSON.parse(event.data);
50
51   window.game.remove_player(info);
52 });
53
54 events.addEventListener("player-update", event => {
55   const info = JSON.parse(event.data);
56
57   if (info.id === window.game.state.player_info.id)
58     window.game.set_player_info(info);
59   else
60     window.game.set_other_player_info(info);
61 });
62
63 events.addEventListener("game-state", event => {
64   const state = JSON.parse(event.data);
65
66   window.game.reset_game_state();
67
68   window.game.set_prompts(state.prompts);
69
70   window.game.set_active_prompt(state.active_prompt);
71
72   window.game.set_players_answered(state.players_answered);
73
74   window.game.set_players_answering(state.players_answering);
75
76   window.game.set_answering_idle(state.answering_idle);
77
78   window.game.set_end_answers(state.end_answers);
79
80   window.game.set_ambiguities(state.ambiguities);
81
82   window.game.set_players_judged(state.players_judged);
83
84   window.game.set_players_judging(state.players_judging);
85
86   window.game.set_judging_idle(state.judging_idle);
87
88   window.game.set_end_judging(state.end_judging);
89
90   window.game.set_scores(state.scores);
91
92   window.game.set_new_game_votes(state.new_game_votes);
93
94   window.game.state_ready();
95 });
96
97 events.addEventListener("prompt", event => {
98   const prompt = JSON.parse(event.data);
99
100   window.game.add_or_update_prompt(prompt);
101 });
102
103 events.addEventListener("start", event => {
104   const prompt = JSON.parse(event.data);
105
106   window.game.set_active_prompt(prompt);
107 });
108
109 events.addEventListener("player-answered", event => {
110   const player = JSON.parse(event.data);
111
112   window.game.set_player_answered(player);
113 });
114
115 events.addEventListener("player-answering", event => {
116   const player = JSON.parse(event.data);
117
118   window.game.set_player_answering(player);
119 });
120
121 events.addEventListener("answering-idle", event => {
122   const value = JSON.parse(event.data);
123
124   window.game.set_answering_idle(value);
125 });
126
127 events.addEventListener("vote-end-answers", event => {
128   const player = JSON.parse(event.data);
129
130   window.game.set_player_vote_end_answers(player);
131 });
132
133 events.addEventListener("unvote-end-answers", event => {
134   const player = JSON.parse(event.data);
135
136   window.game.set_player_unvote_end_answers(player);
137 });
138
139 events.addEventListener("ambiguities", event => {
140   const ambiguities = JSON.parse(event.data);
141
142   window.game.set_ambiguities(ambiguities);
143 });
144
145 events.addEventListener("player-judged", event => {
146   const player = JSON.parse(event.data);
147
148   window.game.set_player_judged(player);
149 });
150
151 events.addEventListener("player-judging", event => {
152   const player = JSON.parse(event.data);
153
154   window.game.set_player_judging(player);
155 });
156
157 events.addEventListener("judging-idle", event => {
158   const value = JSON.parse(event.data);
159
160   window.game.set_judging_idle(value);
161 });
162
163 events.addEventListener("vote-end-judging", event => {
164   const player = JSON.parse(event.data);
165
166   window.game.set_player_vote_end_judging(player);
167 });
168
169 events.addEventListener("unvote-end-judging", event => {
170   const player = JSON.parse(event.data);
171
172   window.game.set_player_unvote_end_judging(player);
173 });
174
175 events.addEventListener("scores", event => {
176   const scores = JSON.parse(event.data);
177
178   window.game.set_scores(scores);
179 });
180
181 events.addEventListener("vote-new-game", event => {
182   const player = JSON.parse(event.data);
183
184   window.game.set_player_vote_new_game(player);
185 });
186
187 events.addEventListener("unvote-new-game", event => {
188   const player = JSON.parse(event.data);
189
190   window.game.set_player_unvote_new_game(player);
191 });
192
193 /*********************************************************
194  * Game and supporting classes                           *
195  *********************************************************/
196
197 function copy_to_clipboard(id)
198 {
199   const tmp = document.createElement("input");
200   tmp.setAttribute("value", document.getElementById(id).innerHTML);
201   document.body.appendChild(tmp);
202   tmp.select();
203   document.execCommand("copy");
204   document.body.removeChild(tmp);
205 }
206
207 const GameInfo = React.memo(props => {
208   if (! props.id)
209     return null;
210
211   return (
212     <div className="game-info">
213       <span className="game-id">{props.id}</span>
214       {" "}
215       Share this link to invite friends:{" "}
216       <span id="game-share-url">{props.url}</span>
217       {" "}
218       <button
219         className="inline"
220         onClick={() => copy_to_clipboard('game-share-url')}
221       >Copy Link</button>
222     </div>
223   );
224 });
225
226 const PlayerInfo = React.memo(props => {
227   if (! props.player.id)
228     return null;
229
230   const all_players = [props.player, ...props.other_players];
231
232   const sorted_players = all_players.sort((a,b) => {
233     return b.score - a.score;
234   });
235
236   const names_and_scores = sorted_players.map(player => {
237     if (player.score)
238       return `${player.name} (${player.score})`;
239     else
240       return player.name;
241   }).join(', ');
242
243   return (
244     <div className="player-info">
245       <span className="players-header">Players: </span>
246       <span>{names_and_scores}</span>
247     </div>
248   );
249 });
250
251 function fetch_method_json(method, api = '', data = {}) {
252   const response = fetch(api, {
253     method: method,
254     headers: {
255       'Content-Type': 'application/json'
256     },
257     body: JSON.stringify(data)
258   });
259   return response;
260 }
261
262 function fetch_post_json(api = '', data = {}) {
263   return fetch_method_json('POST', api, data);
264 }
265
266 async function fetch_put_json(api = '', data = {}) {
267   return fetch_method_json('PUT', api, data);
268 }
269
270 class CategoryRequest extends React.PureComponent {
271   constructor(props) {
272     super(props);
273     this.category = React.createRef();
274
275     this.handle_change = this.handle_change.bind(this);
276     this.handle_submit = this.handle_submit.bind(this);
277   }
278
279   handle_change(event) {
280     const category_input = this.category.current;
281     const category = category_input.value;
282
283     const match = category.match(/[0-9]+/);
284     if (match) {
285       const num_items = parseInt(match[0], 10);
286       if (num_items > 0 && num_items <= MAX_PROMPT_ITEMS)
287         category_input.setCustomValidity("");
288     }
289   }
290
291   async handle_submit(event) {
292     const form = event.currentTarget;
293     const category_input = this.category.current;
294     const category = category_input.value;
295
296     /* Prevent the default page-changing form-submission behavior. */
297     event.preventDefault();
298
299     const match = category.match(/[0-9]+/);
300     if (match === null) {
301       category_input.setCustomValidity("Category must include a number");
302       form.reportValidity();
303       return;
304     }
305
306     const num_items = parseInt(match[0], 10);
307
308     if (num_items > MAX_PROMPT_ITEMS) {
309       category_input.setCustomValidity(`Maximum number of items is ${MAX_PROMPT_ITEMS}`);
310       form.reportValidity();
311       return;
312     }
313
314     if (num_items < 1) {
315       category_input.setCustomValidity("Category must require at least one item.");
316       form.reportValidity();
317       return;
318     }
319
320     const response = await fetch_post_json("prompts", {
321       items: num_items,
322       prompt: category
323     });
324
325     if (response.status === 200) {
326       const result = await response.json();
327       if (! result.valid) {
328         add_message("danger", result.message);
329         return;
330       }
331     } else {
332       add_message("danger", "An error occurred submitting your category");
333     }
334
335     form.reset();
336   }
337
338   render() {
339     return (
340       <div className="category-request">
341         <h2>Submit a Category</h2>
342         <p>
343           Suggest a category to play. Don't forget to include the
344           number of items for each person to submit.
345         </p>
346
347         <form onSubmit={this.handle_submit} >
348           <div className="form-field large">
349             <input
350               type="text"
351               id="category"
352               placeholder="6 things at the beach"
353               required
354               autoComplete="off"
355               onChange={this.handle_change}
356               ref={this.category}
357             />
358           </div>
359
360           <div className="form-field large">
361             <button type="submit">
362               Send
363             </button>
364           </div>
365
366         </form>
367       </div>
368     );
369   }
370 }
371
372 const PromptOption = React.memo(props => {
373
374   const prompt = props.prompt;
375
376   if (prompt.votes_against.find(v => v === props.player.name))
377     return false;
378
379   return (
380     <button
381       className="vote-button"
382       key={prompt.id}
383       onClick={() => fetch_post_json(`vote/${prompt.id}`) }
384     >
385       <span
386         className="hide-button"
387         onClick={(event) => {
388           event.stopPropagation();
389           fetch_post_json(`vote_against/${prompt.id}`);
390         }}
391       >
392         &times;
393       </span>
394       {prompt.prompt}
395       <div className="vote-choices">
396         {prompt.votes.map(v => {
397           return (
398             <div
399               key={v}
400               className="vote-choice"
401             >
402               {v}
403             </div>
404           );
405         })}
406       </div>
407     </button>
408   );
409 });
410
411 const PromptOptions = React.memo(props => {
412
413   if (props.prompts.length === 0)
414     return null;
415
416   return (
417     <div className="prompt-options">
418       <h2>Vote on Categories</h2>
419       <p>
420         Select any categories below that you'd like to play.
421         You can choose as many as you'd like.
422       </p>
423       {props.prompts.map(
424         prompt => <PromptOption
425                     key={prompt.id}
426                     prompt={prompt}
427                     player={props.player}
428                   />
429       )}
430     </div>
431   );
432 });
433
434 const LetsPlay = React.memo(props => {
435
436   const quorum = Math.round((props.num_players + 1) / 2);
437   const max_votes = props.prompts.reduce(
438     (max_so_far, v) => Math.max(max_so_far, v.votes.length), 0);
439
440   if (max_votes < quorum)
441     return null;
442
443   const candidates = props.prompts.filter(p => p.votes.length >= quorum);
444   const index = Math.floor(Math.random() * candidates.length);
445   const winner = candidates[index];
446
447   return (
448     <div className="lets-play">
449       <h2>Let's Play</h2>
450       <p>
451         That should be enough voting. If you're not waiting for any
452         other players to join, then let's start.
453       </p>
454       <button
455         className="lets-play"
456         onClick={() => fetch_post_json(`start/${winner.id}`) }
457       >
458         Start Game
459       </button>
460     </div>
461   );
462 });
463
464 class Ambiguities extends React.PureComponent {
465
466   constructor(props) {
467     super(props);
468
469     function canonize(word) {
470       return word.replace(/((a|an|the) )?(.*?)s?$/i, '$3');
471     }
472
473     const word_sets = [];
474
475     for (let word of props.words) {
476       const word_canon = canonize(word);
477       let found_match = false;
478       for (let set of word_sets) {
479         const set_canon = canonize(set.values().next().value);
480         if (word_canon === set_canon) {
481           set.add(word);
482           found_match = true;;
483           break;
484         }
485       }
486       if (! found_match) {
487         const set = new Set();
488         set.add(word);
489         word_sets.push(set);
490       }
491     }
492
493     this.state = {
494       word_sets: word_sets,
495       selected: null,
496       starred: null
497     };
498
499     this.submitted = false;
500     this.judging_sent_recently = false;
501   }
502
503   async handle_submit() {
504
505     /* Don't submit a second time. */
506     if (this.submitted)
507       return;
508
509     const response = await fetch_post_json(
510       `judged/${this.props.prompt.id}`,{
511         word_groups: this.state.word_sets.map(set => Array.from(set)),
512         kudos: this.state.starred ? Array.from(this.state.starred) : null
513       }
514     );
515
516     if (response.status === 200) {
517       const result = await response.json();
518       if (! result.valid) {
519         add_message("danger", result.message);
520         return;
521       }
522     } else {
523       add_message("danger", "An error occurred submitting the results of your judging");
524       return;
525     }
526
527     this.submitted = true;
528   }
529
530   handle_click(word) {
531
532     /* Let the server know we are doing some judging, (but rate limit
533      * this so we don't send a "judging" notification more frquently
534      * than necessary.
535      */
536     if (! this.judging_sent_recently) {
537       fetch_post_json(`judging/${this.props.prompt.id}`);
538       this.judging_sent_recently = true;
539       setTimeout(() => { this.judging_sent_recently = false; }, 1000);
540     }
541
542     if (this.state.selected == word) {
543       /* Second click on same word removes the word from the group. */
544       const idx = this.state.word_sets.findIndex(s => s.has(word));
545       const set = this.state.word_sets[idx];
546       if (set.size === 1) {
547         /* When the word is already alone, there's nothing to do but
548          * to un-select it. */
549         this.setState({
550           selected: null
551         });
552         return;
553       }
554
555       const new_set = new Set([...set].filter(w => w !== word));
556       this.setState({
557         selected: null,
558         word_sets: [...this.state.word_sets.slice(0, idx),
559                     new_set,
560                     new Set().add(word),
561                     ...this.state.word_sets.slice(idx+1)]
562       });
563     } else if (this.state.selected) {
564       /* Click of a second word groups the two together. */
565       const idx1 = this.state.word_sets.findIndex(s => s.has(this.state.selected));
566       const idx2 = this.state.word_sets.findIndex(s => s.has(word));
567       const set1 = this.state.word_sets[idx1];
568       const set2 = this.state.word_sets[idx2];
569       const new_set = new Set([...set2, ...set1]);
570       if (idx1 < idx2) {
571         this.setState({
572           selected: null,
573           word_sets: [...this.state.word_sets.slice(0, idx1),
574                       ...this.state.word_sets.slice(idx1 + 1, idx2),
575                       new_set,
576                       ...this.state.word_sets.slice(idx2 + 1)]
577         });
578       } else {
579         this.setState({
580           selected: null,
581           word_sets: [...this.state.word_sets.slice(0, idx2),
582                       new_set,
583                       ...this.state.word_sets.slice(idx2 + 1, idx1),
584                       ...this.state.word_sets.slice(idx1 + 1)]
585         });
586       }
587     } else {
588       /* First click of a word selects it. */
589       this.setState({
590         selected: word
591       });
592     }
593   }
594
595   render() {
596     let move_on_button = null;
597
598     if (this.props.idle) {
599       move_on_button = (
600         <button
601           className="vote-button"
602           onClick={() => fetch_post_json(`end-judging/${this.props.prompt.id}`) }
603         >
604           Move On Without Their Input
605           <div className="vote-choices">
606             {[...this.props.votes].map(v => {
607               return (
608                 <div
609                   key={v}
610                   className="vote-choice"
611                 >
612                   {v}
613                   </div>
614               );
615             })}
616           </div>
617         </button>
618       );
619     }
620
621     let still_waiting = null;
622     const judging_players = Object.keys(this.props.players_judging);
623     if (judging_players.length) {
624       still_waiting = (
625         <div>
626           <p>
627             Still waiting for the following player
628             {judging_players.length > 1 ? 's' : '' }
629             :
630           </p>
631           <ul>
632             {judging_players.map(player => {
633               return (
634                 <li
635                   key={player}
636                 >
637                   {player}{' '}
638                   <span className=
639                   {this.props.players_judging[player].active ?
640                    "typing active"
641                    :
642                    "typing idle"}>
643                     <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
644                   </span>
645                 </li>
646               );
647             })}
648           </ul>
649         </div>
650       );
651     }
652
653     if (this.props.players_judged.has(this.props.player.name)) {
654       return (
655         <div className="please-wait">
656           <h2>Submission received</h2>
657           <p>
658             The following players have completed judging:{' '}
659             {[...this.props.players_judged].join(', ')}
660           </p>
661           {still_waiting}
662           {move_on_button}
663
664         </div>
665       );
666     }
667
668     const btn_class = "ambiguity-button";
669     const btn_selected_class = btn_class + " selected";
670
671     return (
672       <div className="ambiguities">
673         <h2>Judging Answers</h2>
674         <p>
675           Click on each pair of answers that should be scored as equivalent,
676           (and click any word twice to split it out from a group). Remember,
677           what goes around comes around, so it's best to be generous when
678           judging.
679         </p>
680         <h2>{this.props.prompt.prompt}</h2>
681         {this.state.word_sets.map(set => {
682           return (
683             <div
684               className="ambiguity-group"
685               key={Array.from(set)[0]}
686             >
687               {Array.from(set).map(word => {
688                 return (
689                   <button
690                     className={this.state.selected === word ?
691                                btn_selected_class : btn_class }
692                     key={word}
693                     onClick={() => this.handle_click(word)}
694                   >
695                     {word}
696                   </button>
697                 );
698               })}
699               <span
700                 className={this.state.starred === set ?
701                            "star-button selected" : "star-button"
702                           }
703                 onClick={(event) => {
704                   event.stopPropagation();
705                   this.setState({
706                     starred: set
707                   });
708                 }}
709               >
710               {this.state.starred === set ?
711                '★' : '☆'
712               }
713               </span>
714             </div>
715           );
716         })}
717         <p>
718           Click here when done judging:<br/>
719           <button
720             onClick={() => this.handle_submit()}
721           >
722             Send
723           </button>
724         </p>
725       </div>
726     );
727   }
728 }
729
730 class ActivePrompt extends React.PureComponent {
731
732   constructor(props) {
733     super(props);
734     const items = props.prompt.items;
735
736     this.submitted = false;
737
738     this.answers = [...Array(items)].map(() => React.createRef());
739     this.answering_sent_recently = false;
740
741     this.handle_submit = this.handle_submit.bind(this);
742     this.handle_change = this.handle_change.bind(this);
743   }
744
745   handle_change(event) {
746     /* We don't care (or even look) at what the player is typing at
747      * this point. We simply want to be informed that the player _is_
748      * typing so that we can tell the server (which will tell other
749      * players) that there is activity here.
750      */
751
752     /* Rate limit so that we don't send an "answering" notification
753      * more frequently than necessary.
754      */
755     if (! this.answering_sent_recently) {
756       fetch_post_json(`answering/${this.props.prompt.id}`);
757       this.answering_sent_recently = true;
758       setTimeout(() => { this.answering_sent_recently = false; }, 1000);
759     }
760   }
761
762   async handle_submit(event) {
763     const form = event.currentTarget;
764
765     /* Prevent the default page-changing form-submission behavior. */
766     event.preventDefault();
767
768     /* And don't submit a second time. */
769     if (this.submitted)
770       return;
771
772     const response = await fetch_post_json(`answer/${this.props.prompt.id}`, {
773       answers: this.answers.map(r => r.current.value)
774     });
775     if (response.status === 200) {
776       const result = await response.json();
777       if (! result.valid) {
778         add_message("danger", result.message);
779         return;
780       }
781     } else {
782       add_message("danger", "An error occurred submitting your answers");
783       return;
784     }
785
786     /* Everything worked. Server is happy with our answers. */
787     form.reset();
788     this.submitted = true;
789   }
790
791   render() {
792
793     let still_waiting = null;
794     const answering_players = Object.keys(this.props.players_answering);;
795     if (answering_players.length) {
796       still_waiting = (
797         <div>
798           <p>
799             Still waiting for the following player
800             {answering_players.length > 1 ? 's' : ''}
801             :
802           </p>
803           <ul>
804             {answering_players.map(player => {
805               return (
806                 <li
807                   key={player}
808                 >
809                   {player}{' '}
810                   <span className=
811                   {this.props.players_answering[player].active ?
812                    "typing active"
813                    :
814                    "typing idle"}>
815                     <span>{'.'}</span><span>{'.'}</span><span>{'.'}</span>
816                   </span>
817                 </li>
818               );
819             })}
820           </ul>
821         </div>
822       );
823     }
824
825     let move_on_button = null;
826     if (this.props.idle) {
827       move_on_button =(
828         <button
829           className="vote-button"
830           onClick={() => fetch_post_json(`end-answers/${this.props.prompt.id}`) }
831         >
832           Move On Without Their Answers
833           <div className="vote-choices">
834             {[...this.props.votes].map(v => {
835               return (
836                 <div
837                   key={v}
838                   className="vote-choice"
839                 >
840                   {v}
841                 </div>
842               );
843             })}
844           </div>
845         </button>
846       );
847     }
848
849     if (this.props.players_answered.has(this.props.player.name)) {
850       return (
851         <div className="please-wait">
852           <h2>Submission received</h2>
853           <p>
854             The following players have submitted their answers:{' '}
855             {[...this.props.players_answered].join(', ')}
856           </p>
857           {still_waiting}
858           {move_on_button}
859
860         </div>
861       );
862     }
863
864     return (
865       <div className="active-prompt">
866         <h2>The Game of Empathy</h2>
867         <p>
868           Remember, you're trying to match your answers with
869           what the other players submit.
870           Give {this.props.prompt.items} answer
871           {this.props.prompt.items > 1 ? 's' : ''} for the following prompt:
872         </p>
873         <h2>{this.props.prompt.prompt}</h2>
874         <form onSubmit={this.handle_submit}>
875           {[...Array(this.props.prompt.items)].map((whocares,i) => {
876             return (
877               <div
878                 key={i}
879                 className="form-field large">
880                 <input
881                   type="text"
882                   name={`answer_${i}`}
883                   required
884                   autoComplete="off"
885                   onChange={this.handle_change}
886                   ref={this.answers[i]}
887                 />
888               </div>
889             );
890           })}
891
892           <div
893             key="submit-button"
894             className="form-field large">
895             <button type="submit">
896               Send
897             </button>
898           </div>
899
900         </form>
901       </div>
902     );
903   }
904 }
905
906 class Game extends React.PureComponent {
907   constructor(props) {
908     super(props);
909     this.state = {
910       game_info: {},
911       player_info: {},
912       other_players: [],
913       prompts: [],
914       active_prompt: null,
915       players_answered: new Set(),
916       players_answering: {},
917       answering_idle: false,
918       end_answers_votes: new Set(),
919       ambiguities: null,
920       players_judged: new Set(),
921       players_judging: {},
922       judging_idle: false,
923       end_judging_votes: new Set(),
924       scores: null,
925       new_game_votes: new Set(),
926       ready: false
927     };
928   }
929
930   set_game_info(info) {
931     this.setState({
932       game_info: info
933     });
934   }
935
936   set_player_info(info) {
937     this.setState({
938       player_info: info
939     });
940   }
941
942   set_other_player_info(info) {
943     const other_players_copy = [...this.state.other_players];
944     const idx = other_players_copy.findIndex(o => o.id === info.id);
945     if (idx >= 0) {
946       other_players_copy[idx] = info;
947     } else {
948       other_players_copy.push(info);
949     }
950     this.setState({
951       other_players: other_players_copy
952     });
953   }
954
955   remove_player(info) {
956     this.setState({
957       other_players: this.state.other_players.filter(o => o.id !== info.id)
958     });
959   }
960
961   reset_game_state() {
962     this.setState({
963       prompts: [],
964       active_prompt: null,
965       players_answered: new Set(),
966       players_answering: {},
967       answering_idle: false,
968       end_answers_votes: new Set(),
969       ambiguities: null,
970       players_judged: new Set(),
971       players_judging: {},
972       judging_idle: false,
973       end_judging_votes: new Set(),
974       scores: null,
975       new_game_votes: new Set(),
976       ready: false
977     });
978   }
979
980   set_prompts(prompts) {
981     this.setState({
982       prompts: prompts
983     });
984   }
985
986   add_or_update_prompt(prompt) {
987     const prompts_copy = [...this.state.prompts];
988     const idx = prompts_copy.findIndex(p => p.id === prompt.id);
989     if (idx >= 0) {
990       prompts_copy[idx] = prompt;
991     } else {
992       prompts_copy.push(prompt);
993     }
994     this.setState({
995       prompts: prompts_copy
996     });
997   }
998
999   set_active_prompt(prompt) {
1000     this.setState({
1001       active_prompt: prompt
1002     });
1003   }
1004
1005   set_players_answered(players) {
1006     this.setState({
1007       players_answered: new Set(players)
1008     });
1009   }
1010
1011   set_player_answered(player) {
1012     const new_players_answering = {...this.state.players_answering};
1013     delete new_players_answering[player];
1014
1015     this.setState({
1016       players_answered: new Set([...this.state.players_answered, player]),
1017       players_answering: new_players_answering
1018     });
1019   }
1020
1021   set_players_answering(players) {
1022     const players_answering = {};
1023     for (let player of players) {
1024       players_answering[player] = {active: false};
1025     }
1026     this.setState({
1027       players_answering: players_answering
1028     });
1029   }
1030
1031   set_player_answering(player) {
1032     /* Set the player as actively answering now. */
1033     this.setState({
1034       players_answering: {
1035         ...this.state.players_answering,
1036         [player]: {active: true}
1037       }
1038     });
1039     /* And arrange to have them marked idle very shortly.
1040      *
1041      * Note: This timeout is intentionally very, very short. We only
1042      * need it long enough that the browser has latched onto the state
1043      * change to "active" above. We actually use a CSS transition
1044      * delay to control the user-perceptible length of time after
1045      * which an active player appears inactive.
1046      */
1047     setTimeout(() => {
1048       this.setState({
1049         players_answering: {
1050           ...this.state.players_answering,
1051           [player]: {active: false}
1052         }
1053       });
1054     }, 100);
1055   }
1056
1057   set_answering_idle(value) {
1058     this.setState({
1059       answering_idle: value
1060     });
1061   }
1062
1063   set_end_answers(players) {
1064     this.setState({
1065       end_answers_votes: new Set(players)
1066     });
1067   }
1068
1069   set_player_vote_end_answers(player) {
1070     this.setState({
1071       end_answers_votes: new Set([...this.state.end_answers_votes, player])
1072     });
1073   }
1074
1075   set_player_unvote_end_answers(player) {
1076     this.setState({
1077       end_answers_votes: new Set([...this.state.end_answers_votes].filter(p => p !== player))
1078     });
1079   }
1080
1081   set_ambiguities(ambiguities) {
1082     this.setState({
1083       ambiguities: ambiguities
1084     });
1085   }
1086
1087   set_players_judged(players) {
1088     this.setState({
1089       players_judged: new Set(players)
1090     });
1091   }
1092
1093   set_player_judged(player) {
1094     const new_players_judging = {...this.state.players_judging};
1095     delete new_players_judging[player];
1096
1097     this.setState({
1098       players_judged: new Set([...this.state.players_judged, player]),
1099       players_judging: new_players_judging
1100     });
1101   }
1102
1103   set_players_judging(players) {
1104     const players_judging = {};
1105     for (let player of players) {
1106       players_judging[player] = {active: false};
1107     }
1108     this.setState({
1109       players_judging: players_judging
1110     });
1111   }
1112
1113   set_player_judging(player) {
1114     /* Set the player as actively judging now. */
1115     this.setState({
1116       players_judging: {
1117         ...this.state.players_judging,
1118         [player]: {active: true}
1119       }
1120     });
1121     /* And arrange to have them marked idle very shortly.
1122      *
1123      * Note: This timeout is intentionally very, very short. We only
1124      * need it long enough that the browser has latched onto the state
1125      * change to "active" above. We actually use a CSS transition
1126      * delay to control the user-perceptible length of time after
1127      * which an active player appears inactive.
1128      */
1129     setTimeout(() => {
1130       this.setState({
1131         players_judging: {
1132           ...this.state.players_judging,
1133           [player]: {active: false}
1134         }
1135       });
1136     }, 100);
1137
1138   }
1139
1140   set_judging_idle(value) {
1141     this.setState({
1142       judging_idle: value
1143     });
1144   }
1145
1146   set_end_judging(players) {
1147     this.setState({
1148       end_judging_votes: new Set(players)
1149     });
1150   }
1151
1152   set_player_vote_end_judging(player) {
1153     this.setState({
1154       end_judging_votes: new Set([...this.state.end_judging_votes, player])
1155     });
1156   }
1157
1158   set_player_unvote_end_judging(player) {
1159     this.setState({
1160       end_judging_votes: new Set([...this.state.end_judging_votes].filter(p => p !== player))
1161     });
1162   }
1163
1164   set_scores(scores) {
1165     this.setState({
1166       scores: scores
1167     });
1168   }
1169
1170   set_new_game_votes(players) {
1171     this.setState({
1172       new_game_votes: new Set(players)
1173     });
1174   }
1175
1176   set_player_vote_new_game(player) {
1177     this.setState({
1178       new_game_votes: new Set([...this.state.new_game_votes, player])
1179     });
1180   }
1181
1182   set_player_unvote_new_game(player) {
1183     this.setState({
1184       new_game_votes: new Set([...this.state.new_game_votes].filter(p => p !== player))
1185     });
1186   }
1187
1188   state_ready() {
1189     this.setState({
1190       ready: true
1191     });
1192   }
1193
1194   render() {
1195     const state = this.state;
1196     const players_total = 1 + state.other_players.length;
1197
1198     if (state.scores) {
1199
1200       let perfect_score = 0;
1201       for (let i = 0;
1202            i < state.active_prompt.items &&
1203            i < state.scores.words.length;
1204            i++)
1205       {
1206         perfect_score += state.scores.words[i].players.length;
1207       }
1208
1209       return (
1210         <div className="scores">
1211           <h2>{state.active_prompt.prompt}</h2>
1212           <h2>Scores</h2>
1213           <ul>
1214             {state.scores.scores.map(score => {
1215               let perfect = null;
1216               if (score.score == perfect_score) {
1217                 perfect = <span className="label">Perfect!</span>;
1218               }
1219               return (
1220                 <li key={score.players[0]}>
1221                   {score.players.join("/")}: {score.score} {perfect}
1222                 </li>
1223               );
1224             })}
1225           </ul>
1226           <h2>Words submitted</h2>
1227           <ul>
1228             {state.scores.words.map(word => {
1229               return (
1230                 <li key={word.word}>
1231                   {word.word} ({word.players.length}): {word.players.join(', ')}
1232                 </li>
1233               );
1234             })}
1235           </ul>
1236           <button
1237             className="vote-button"
1238             onClick={() => fetch_post_json(`new-game/${state.active_prompt.id}`) }
1239           >
1240             New Game
1241             <div className="vote-choices">
1242               {[...state.new_game_votes].map(v => {
1243                 return (
1244                   <div
1245                     key={v}
1246                     className="vote-choice"
1247                   >
1248                     {v}
1249                   </div>
1250                 );
1251               })}
1252             </div>
1253           </button>
1254         </div>
1255       );
1256     }
1257
1258     if (state.ambiguities){
1259       return <Ambiguities
1260                prompt={state.active_prompt}
1261                words={state.ambiguities}
1262                player={state.player_info}
1263                players_judged={state.players_judged}
1264                players_judging={state.players_judging}
1265                idle={state.judging_idle}
1266                votes={state.end_judging_votes}
1267              />;
1268     }
1269
1270     if (state.active_prompt) {
1271       return <ActivePrompt
1272                prompt={state.active_prompt}
1273                player={state.player_info}
1274                players_answered={state.players_answered}
1275                players_answering={state.players_answering}
1276                idle={state.answering_idle}
1277                votes={state.end_answers_votes}
1278              />;
1279     }
1280
1281     if (! state.ready)
1282       return null;
1283
1284     return [
1285       <GameInfo
1286         key="game-info"
1287         id={state.game_info.id}
1288         url={state.game_info.url}
1289       />,
1290       <PlayerInfo
1291         key="player-info"
1292         game={this}
1293         player={state.player_info}
1294         other_players={state.other_players}
1295       />,
1296       <p key="spacer"></p>,
1297       <CategoryRequest
1298         key="category-request"
1299       />,
1300       <PromptOptions
1301         key="prompts"
1302         prompts={state.prompts}
1303         player={state.player_info}
1304       />,
1305       <LetsPlay
1306         key="lets-play"
1307         num_players={1+state.other_players.length}
1308         prompts={state.prompts}
1309       />
1310     ];
1311   }
1312 }
1313
1314 ReactDOM.render(<Game
1315                   ref={(me) => window.game = me}
1316                 />, document.getElementById("empathy"));