# gallium-react

> A frontend library for gallium-io

Latest version **1.0.3** (published 2022-04-11) · ISC license · 0 weekly downloads

## Install

```sh
npm install gallium-react
pnpm add gallium-react
yarn add gallium-react
bun add gallium-react
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.3 |
| Published | 2022-04-11 |
| First published | 2022-04-09 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Unpacked size | 8.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Maintainers | abhinaviswierd |
| Keywords | react, gallium-io, websocket |

## Links

- npm: https://www.npmjs.com/package/gallium-react
- Repository: https://github.com/Abhinav1190P/Gallium-project
- Homepage: https://github.com/Abhinav1190P/Gallium-project#readme
- Issues: https://github.com/Abhinav1190P/Gallium-project/issues
- npm.io page: https://npm.io/package/gallium-react

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 1.0.3 (latest) — 2022-04-11
- 1.0.1 — 2022-04-10
- 1.0.0 — 2022-04-09

## README

# 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;

```

---
_Source: https://npm.io/package/gallium-react · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
