1.0.3 • Published 2 years ago

gallium-react v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

What is this about ?

This is the frontend package for gallium-io. It is responsible for the interaction, between the WebSocket connection, between the frontend (gallium-react) and backend (gallium-io).

How to install ?

npm i gallium-react --save

How to start ?

Step 1. Start a new react project, by using the following command, npx create-react-app.

Step 2. In your App.js, start by calling the inbuilt WebSocket class supported by most browsers.

Initiate it at the imports section inside your App.js like so...

const ws = new WebSocket("ws://localhost:9876/websocket");

Note: The default route for websocket handshake, for gallium-io and gallium-react is /websocket. Also be sure to provide same url for the connection as provide during the server setup.

Step 3. After initializing the connection both in gallium-react and gallium-io, we should see

Websocket connection made

That is when we know, we can proceed forward.

WebSocket property

The only two properties that will be used in our project are

First is

ws.onmessage = function(event){
    let data = JSON.parse(event.data)
    console.log(data)
}

Second is

ws.send(JSON.stringify(obj))

This block of code can be used inside the App component. To keep a watch on the types of messages we are getting back from the server. The data is that message object.

Setting up a sample page.

For example purpose, set up a page with minimal html and css in the App.js. Here is the code...

 return (
    <div className="App">
    <button onClick={CreateARoom}>Create</button>
    <input type="text" name="room-code" id="room-code" value={roomcode} onChange={(e)=>setroomcode(e.target.value)}/>
    <button onClick={JoinARoom}>Join</button>
    <button onClick={LeaveARoom}>Leave</button>
    <p><b id="last-msg"></b></p>
    {
      info ? (<p>Joined Room: {info.room}</p>):(null) 
    }
    
    <p id = "roomId"></p>
    <label>Send message to room</label><br/>
    <input id="message-input" type="text" value={message} onChange={(e)=>setmessage(e.target.value)}/><button onClick={()=>sendMessageToRoom(roomcode)}>Send</button>

    <ul id="messages">
  {
    messagelist?.map((item,i)=>{
      return(
        <div key = {i}>{item}</div>
      )
    })
  }        
    </ul>
    </div>
  );

The messagelist is the messages we recieve that we map later.

1 - As we see we have a button called Create. That will be used to create a room in the websocket. 2 - We also have an input box. This input will be used for providing the chat room code, your about to join. 3 - We also have two buttons side by side, named Join and Leave respectively. The Join button will be used to join a chatroom once the room code is provided. And the leave button will be used to leave the room. 4 - Create the functions for the respective buttons.

Before creating the functions, we must take a look at the Hooks provided by gallium-react.

Hooks

CreateRoom({SetPassword:true,hash:'Password for room'}) - Used to create a WebSocket Room.

Options:

CreateRoom supports two options SetPassword and hash.

  • SetPassword - boolean (true or false)
  • hash - String The password for your room, if SetPassword is true.

CheckPass({room:'MyRoom'}) - Used to check password for room before joining.

Options:

  • room - String (The room code)

JoinRoom({room:'roomcode',trypass:'roompassword'}) - Used to join the room, once password is entered.

Options:

  • room - String The roomcode, which we are to join.
  • trypass - String The password for the room.

SendMessage({room:'roomcode',message:'Hello world'})

Options:

  • room - String The roomcode, which we are about to send message to.
  • message - String The message that has to be sent.

LeaveRoom({room:'roomcode'}) - Used to leave the current room your in.

Options:

  • room - String The room code for the room to leave

Object

The structure used for messages

{
    "type":"create","params":{"roomc":"at3ka09t","trypass":'thepassword'}
}

These objects are recieved on each hook call

Example:

const roomdata = JoinRoom({room:'roomcode',trypass:'thepassword'})
ws.send(JSON.stringify(roomdata))

This block of code will send the roomdata to the server. And will recieve message in the ws.onmessage.

Here is a full working App.js page

import React,{useState} from 'react';

import {CreateRoom,CheckPass,JoinRoom,SendMessage,LeaveRoom} from 'gallium-react'
const ws = new WebSocket("ws://localhost:9876/websocket");


function App() {
  const [info,setinfo] = useState({})
  const [roomcode,setroomcode] = useState('')
  const [message,setmessage] = useState('')
  const [messagelist,setmessagelist] = useState([])

  
 
  
  ws.onmessage = function(event){

    let rawData = JSON.parse(event.data)
      setroomcode(rawData.params.room)
      setinfo(rawData.params)
      
      if(rawData.type === 'check_password'){
        ActivateJoin(rawData.params.protected)
      }
      if(rawData.type === 'leave'){
        window.location.reload()
      }

      if(rawData.type === 'message'){
        let Amessage = rawData.params.message
        let cloneArray = [...messagelist]
        cloneArray.push(Amessage)
        setmessagelist(cloneArray)
      }
      
  }

  
  const CreateARoom = () =>{
      let hash = 'ageka03'
      const obj = CreateRoom({SetPassword:true,hash:hash})
      ws.send(JSON.stringify(obj))
  }
  

  const JoinARoom = () =>{
    const obj = CheckPass({room:roomcode})
    ws.send(JSON.stringify(obj))
    
  }

  const ActivateJoin = (check) =>{
    if(check){
      let password = prompt('Enter room password')
      if(password){
        let obj = JoinRoom({room:roomcode,trypass:password})
        ws.send(JSON.stringify(obj))
      }
      else{
        let obj = JoinRoom({room:roomcode})
        ws.send(JSON.stringify(obj))
      }
    }
    else{
      let obj = JoinRoom({room:roomcode})
        ws.send(JSON.stringify(obj))
    }
  }
  

  const sendMessageToRoom = () =>{
    const text = SendMessage({room:roomcode,message:message})
    ws.send(JSON.stringify(text))
  }

  const LeaveARoom = () =>{
    const obj = LeaveRoom({room:roomcode})
    ws.send(JSON.stringify(obj))
  }

  return (
    <div className="App">
    <button onClick={CreateARoom}>Create</button>
    <input type="text" name="room-code" id="room-code" value={roomcode} onChange={(e)=>setroomcode(e.target.value)}/>
    <button onClick={JoinARoom}>Join</button>
    <button onClick={LeaveARoom}>Leave</button>
    <p><b id="last-msg"></b></p>
    {
      info ? (<p>Joined Room: {info.room}</p>):(null) 
    }
    
    <p id = "roomId"></p>
    <label>Send message to room</label><br/>
    <input id="message-input" type="text" value={message} onChange={(e)=>setmessage(e.target.value)}/><button onClick={()=>sendMessageToRoom(roomcode)}>Send</button>

    <ul id="messages">
  {
    messagelist?.map((item,i)=>{
      return(
        <div key = {i}>{item}</div>
      )
    })
  }        
    </ul>
    </div>
  );
}

export default App;