euchre-live

Euchre web-app for the socially distant family
git clone git://git.alexkarle.com/euchre-live.git
Log | Files | Refs | README | LICENSE

app.js (7427B) [raw]


      1 import "carbon-components/css/carbon-components.css";
      2 import './app.css';
      3 import React from 'react';
      4 import ReactDOM from 'react-dom';
      5 import Lobby from './components/Lobby';
      6 import CardTable from './components/CardTable';
      7 import { w3cwebsocket as W3CWebSocket } from 'websocket';
      8 
      9 // const client = new W3CWebSocket('ws://localhost:3000/play');
     10 let client = null;
     11 let socketAddr, tablesAddr;
     12 // additional fakeClient sockets, only used on tableDebug
     13 let fc1, fc2, fc3 = null;
     14 
     15 
     16 const tableDebug = false;
     17 
     18 class App extends React.Component {
     19 
     20     constructor(props) {
     21         super(props);
     22         const initialName = tableDebug ? 'Alex' : '';
     23         const initialTable = tableDebug ? ('periodic-'+Math.floor(Math.random() * 100)) : '';
     24         this.state = {
     25             playerName: initialName,
     26             tableName: initialTable,
     27             showTable: false,
     28             uniqueError: false,
     29             firstMsg: null,
     30             tableList: []
     31         };
     32         const host = window.location.host;
     33         if (window.location.protocol === 'https:') {
     34             socketAddr = 'wss://' + host + '/play';
     35             tablesAddr = 'https://' + host + '/tables';
     36         } else {
     37             socketAddr = 'ws://' + host + '/play';
     38             tablesAddr = 'http://' + host + '/tables';
     39         }
     40         if (tableDebug) { 
     41             client = new W3CWebSocket(socketAddr);
     42             client.onmessage = (event) => this.processResponse(event);
     43             this.pingTimer = setInterval(() => { this.sendPing(); }, 5000);
     44             // on tableDebug send join plus add 3 fakeClient players that join+sit
     45             fc1 = new W3CWebSocket(socketAddr);
     46             fc2 = new W3CWebSocket(socketAddr);
     47             fc3 = new W3CWebSocket(socketAddr);
     48             // wait 1 second so sockets establish connection
     49             setTimeout(()=>{
     50                 this.setFakeGame(initialName, initialTable);
     51             }, 1000);
     52         }
     53     }
     54 
     55     componentDidMount () {
     56         this.fetchTables();
     57     }
     58 
     59     sendPing = () => {
     60         if (client) {
     61             client.send(JSON.stringify({action:'ping'}));
     62         }
     63     }
     64 
     65     fetchTables = () => {
     66         fetch (tablesAddr).then ((response) => {
     67             if (response.ok){
     68                 response.json().then((data) => {
     69                     console.log(data);
     70                     this.setState({
     71                         tableList: data.tables
     72                     });
     73                 });
     74             } else {
     75                 console.log('BadResponse:', response);
     76             }
     77         }).catch ((error) => {
     78             console.log('Caught error:', error);
     79         });
     80     }
     81 
     82     setPlayerName = name => {
     83         this.setState({
     84             playerName: name,
     85             uniqueError: false
     86         });
     87     }
     88 
     89     // need to only showTable if no user-not-unique
     90     // only process incoming if we're waiting to join table
     91     // on joinTable success get first 'lobby' phase, put msg on
     92     //  CardTable.firstMsg prop for table init
     93     processResponse = event => {
     94         const {showTable} = this.state;
     95         if (!showTable){
     96             let msg = JSON.parse(event.data);
     97             if (msg) {
     98                 if ('pong' != msg.msg_type){
     99                     // console.log('App procResp');
    100                     if (msg.msg_type == 'game_state'){
    101                         //replace w switch if more than one needed
    102                         // if (msg.game && msg.game.phase == 'lobby'){
    103                             //set firstMsg, then set showTable
    104                             // console.log('App.procResp: set firstMsg & showTable');
    105                             this.setState({
    106                                 firstMsg: msg
    107                             }, () => {
    108                                 this.setState({
    109                                     showTable: true
    110                                 })
    111                             });
    112                         // };
    113                     } else if (msg.msg_type == 'error'){
    114                         if (msg.msg && msg.msg.includes('Username not unique')){
    115                             // show confirm-force
    116                             // console.log('NOT UNIQUE!!');
    117                             this.setState({
    118                                 uniqueError: true
    119                             });
    120                         }
    121                     }
    122                 }
    123             }
    124         }
    125     }
    126     
    127     exitTable = () => {
    128         client.onmessage = (event) => this.processResponse(event);
    129         this.setState({
    130             tableName: '',
    131             showTable: false,
    132             firstMsg: null
    133         }, () => {
    134             client.send(JSON.stringify({
    135                 action:'leave_table'
    136             }));
    137         });
    138     }
    139 
    140     joinTable = tableInfo => {
    141         let clientConnectTimeout = 0;
    142         if (client == null){
    143             client = new W3CWebSocket(socketAddr);
    144             client.onmessage = (event) => this.processResponse(event);
    145             this.pingTimer = setInterval(() => { this.sendPing(); }, 5000);
    146             clientConnectTimeout = 1000;
    147         }
    148         const tableName = tableInfo.table;
    149         if (!tableName || tableName == ''){
    150             console.log('Empty table name!!');
    151         };
    152         setTimeout(()=>{
    153             this.setState( {
    154                     tableName: tableName,
    155                     showTable: false
    156             }, () => {
    157                 if (tableName && tableName != ''){
    158                     tableInfo.action = 'join_table';
    159                     client.send(JSON.stringify(tableInfo));    
    160                 }
    161             });
    162         }, clientConnectTimeout);
    163     }
    164 
    165     createTable = tableObj => {
    166         console.log('App.createTable:', tableObj);
    167     }
    168 
    169     setFakeGame = (initialName, initialTable) => {
    170         client.send(JSON.stringify({ action:'join_table', player_name: initialName, table: initialTable }));
    171         fc1.send(JSON.stringify({ action:'join_table', player_name: 'Betty', table: initialTable }));
    172         fc2.send(JSON.stringify({ action:'join_table', player_name: 'CJ', table: initialTable }));
    173         fc3.send(JSON.stringify({ action:'join_table', player_name: 'Dana', table: initialTable }));
    174         fc1.send(JSON.stringify({ action:'take_seat', seat: 0 }));
    175         fc2.send(JSON.stringify({ action:'take_seat', seat: 1 }));
    176         fc3.send(JSON.stringify({ action:'take_seat', seat: 2 }));
    177     }
    178 
    179     render () {
    180         const {showTable, playerName, tableName, firstMsg, uniqueError, tableList} = this.state;
    181         return (
    182             <div id="top-app">
    183                 {!showTable && (
    184                     <Lobby
    185                         setName={this.setPlayerName}
    186                         joinTable={this.joinTable}
    187                         name={playerName}
    188                         uniqueError={uniqueError}
    189                         tableList={tableList}
    190                         refreshTables={this.fetchTables}
    191                         createTable={this.createTable}
    192                     />
    193                 )}
    194                 {showTable && (
    195                     <CardTable
    196                         exitTable={this.exitTable}
    197                         name={playerName}
    198                         tableName={tableName}
    199                         firstMsg={firstMsg}
    200                         client={client}
    201                     />
    202                 )}
    203             </div>
    204         );
    205     };
    206 }
    207 
    208 ReactDOM.render( <App />, document.getElementById('content'));