38: Web chat React app  r=D4nte a=D4nte

Helps with #14 

Simple web chat app. Currently using a mock for waku. Next step: Integrate waku.

Co-authored-by: Franck Royer <franck@royer.one>
Co-authored-by: Franck Royer <franck@status.im>
This commit is contained in:
bors[bot] 2021-04-21 06:13:38 +00:00 committed by GitHub
commit 9095e3f145
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 41019 additions and 0 deletions

43
.github/workflows/webchat-ci.yml vendored Normal file
View File

@ -0,0 +1,43 @@
name: Webchat CI
on:
push:
branches:
- 'main'
- 'staging'
- 'trying'
pull_request:
jobs:
build_and_test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Install NodeJS
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Cache npm cache
uses: actions/cache@v2
with:
path: ~/.npm
key: node-v1-${{ hashFiles('**/package-lock.json') }}
- name: "[js-waku] install using npm ci"
uses: bahmutov/npm-install@v1
- name: "[js-waku] build"
run: npm run build
- name: install using npm ci
uses: bahmutov/npm-install@v1
with:
working-directory: web-chat
- name: test
run: npm run test
working-directory: web-chat

73
web-chat/.cspell.json Normal file
View File

@ -0,0 +1,73 @@
{
"version": "0.1",
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/master/cspell.schema.json",
"language": "en",
"words": [
"backoff",
"backoffs",
"bitjson",
"bitauth",
"bufbuild",
"cimg",
"circleci",
"codecov",
"commitlint",
"dependabot",
"dingpu",
"Dlazy",
"Dout",
"Dscore",
"editorconfig",
"esnext",
"execa",
"exponentiate",
"fanout",
"globby",
"gossipsub",
"iasked",
"ihave",
"ihaves",
"ineed",
"iwant",
"lastpub",
"libauth",
"libp",
"mkdir",
"multiaddr",
"multiaddrs",
"multicodecs",
"mplex",
"muxed",
"muxer",
"nodekey",
"peerhave",
"prettierignore",
"protobuf",
"protoc",
"rlnrelay",
"sandboxed",
"secio",
"staticnode",
"submodule",
"submodules",
"transpiled",
"typedoc",
"unmounts",
"untracked",
"upgrader",
"waku",
"wakunode",
"websockets"
],
"flagWords": [],
"ignorePaths": [
"package.json",
"package-lock.json",
"yarn.lock",
"tsconfig.json",
"node_modules/**",
"build",
"gen",
"proto"
]
}

23
web-chat/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

3
web-chat/.prettierignore Normal file
View File

@ -0,0 +1,3 @@
# package.json is formatted by package managers, so we ignore it here
package.json
gen

46
web-chat/README.md Normal file
View File

@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

40292
web-chat/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

56
web-chat/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "web-chat",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.3",
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.22",
"@types/node": "^12.20.7",
"@types/react": "^17.0.3",
"@types/react-dom": "^17.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"typescript": "^4.2.4",
"web-vitals": "^1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test:unit": "react-scripts test",
"eject": "react-scripts eject",
"fix": "run-s fix:*",
"test": "run-s build test:*",
"test:lint": "eslint src --ext .ts",
"test:prettier": "prettier \"src/**/*.ts\" --list-different",
"test:spelling": "cspell \"{README.md,.github/*.md,src/**/*.ts}\"",
"fix:prettier": "prettier \"src/**/*.ts\" --write",
"fix:lint": "eslint src --ext .ts --fix"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"cspell": "^5.3.12",
"npm-run-all": "^4.1.5",
"prettier": "^2.2.1"
}
}

View File

@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
web-chat/src/App.css Normal file
View File

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

53
web-chat/src/App.tsx Normal file
View File

@ -0,0 +1,53 @@
import { Paper } from '@material-ui/core';
import React from 'react';
import './App.css';
import Room from './Room';
import WakuMock from './WakuMock';
import { WakuContext } from './WakuContext';
interface Props {
}
interface State {
messages: string[],
waku?: WakuMock
}
class App extends React.Component<Props, State> {
waku?: WakuMock;
constructor(props: Props) {
super(props);
this.state = {
messages: []
};
WakuMock.create().then((wakuMock) => {
this.setState({ waku: wakuMock, messages: this.state.messages });
wakuMock.on('message', (message) => {
const messages = this.state.messages.slice();
messages.push(message.message);
this.setState({ messages });
});
});
}
render() {
return (
<div className='App'>
<div className='chat-room'>
<WakuContext.Provider value={{ waku: this.state.waku }}>
<Paper >
<Room lines={this.state.messages} />
</Paper>
</WakuContext.Provider>
</div>
</div>
);
}
}
export default App;

View File

@ -0,0 +1,39 @@
import React, { ChangeEvent } from 'react';
import { TextField } from '@material-ui/core';
interface Props {
messageHandler: (msg: string) => void;
}
interface State {
inputText: string;
}
export default class MessageInput extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
inputText: ''
};
}
messageHandler(event: ChangeEvent<HTMLInputElement>) {
this.props.messageHandler(event.target.value);
}
render() {
return (
<TextField variant='outlined'
label='Send a message'
fullWidth
style={{ margin: 8 }}
margin="normal"
InputLabelProps={{
shrink: true,
}}
onChange={this.messageHandler.bind(this)}
/>
);
}
}

80
web-chat/src/Room.tsx Normal file
View File

@ -0,0 +1,80 @@
import {
Box,
Grid,
List,
ListItem,
ListItemText
} from '@material-ui/core';
import React from 'react';
import MessageInput from './MessageInput';
import Send from './Send';
interface Props {
lines: string[],
}
interface State {
messageToSend: string
}
export default class Room extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { messageToSend: '' };
}
messageHandler(msg: string) {
this.setState({ messageToSend: msg });
}
render() {
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<Box height={800} maxHeight={800}
style={{ flex: 1, maxHeight: '100%', overflow: 'scroll' }}>
<Lines messages={this.props.lines} />
</Box>
</Grid>
<Grid item xs={12}>
<Grid container spacing={2} direction='row' alignItems='center'>
<Grid item xs={11}>
<MessageInput messageHandler={this.messageHandler.bind(this)} />
</Grid>
<Grid item xs={1}>
<Send message={this.state.messageToSend} />
</Grid>
</Grid>
</Grid>
</Grid>
);
}
}
interface LinesProps {
messages: string[]
}
const Lines = (props: LinesProps) => {
const renderedLines = [];
for (const line of props.messages) {
renderedLines.push(<ListItem>
<ListItemText
primary={line}
/>
</ListItem>);
}
return (
<List dense={true}>
{renderedLines}
</List>
);
};

23
web-chat/src/Send.tsx Normal file
View File

@ -0,0 +1,23 @@
import React from 'react';
import { useWaku } from './WakuContext';
import { Button } from '@material-ui/core';
interface Props {
message: string
}
const Send = (props: Props) => {
const { waku } = useWaku();
const handleClick = async () => {
await waku!.send(props.message);
};
return (
<Button variant="contained" color="primary" size="large" onClick={handleClick}>
Send
</Button>
);
};
export default Send;

View File

@ -0,0 +1,10 @@
import { createContext, useContext } from 'react';
import WakuMock from './WakuMock';
export type WakuContextType = {
waku?: WakuMock;
// setWaku: (waku: WakuMock) => void;
};
export const WakuContext = createContext<WakuContextType>({ waku: undefined });
export const useWaku = () => useContext(WakuContext);

View File

@ -0,0 +1,30 @@
import WakuMock, { Message } from './WakuMock';
test('Messages are emitted', async () => {
const wakuMock = await WakuMock.create();
let message: Message;
wakuMock.on('message', (msg) => {
message = msg;
});
await new Promise((resolve) => setTimeout(resolve, 2000));
// @ts-ignore
expect(message.message).toBeDefined();
});
test('Messages are sent', async () => {
const wakuMock = await WakuMock.create();
const text = 'This is a message.';
let message: Message;
wakuMock.on('message', (msg) => {
message = msg;
});
await wakuMock.send(text);
// @ts-ignore
expect(message.message).toEqual(text);
});

69
web-chat/src/WakuMock.ts Normal file
View File

@ -0,0 +1,69 @@
class EventEmitter<T> {
public callbacks: { [key: string]: Array<(data: T) => void> };
constructor() {
this.callbacks = {};
}
on(event: string, cb: (data: T) => void) {
if (!this.callbacks[event]) this.callbacks[event] = [];
this.callbacks[event].push(cb);
}
emit(event: string, data: T) {
let cbs = this.callbacks[event];
if (cbs) {
cbs.forEach((cb) => cb(data));
}
}
}
export interface Message {
timestamp: Date;
handle: string;
message: string;
}
export default class WakuMock extends EventEmitter<Message> {
index: number;
intervalId?: number | NodeJS.Timeout;
private constructor() {
super();
this.index = 0;
}
public static async create(): Promise<WakuMock> {
await new Promise((resolve) => setTimeout(resolve, 500));
const wakuMock = new WakuMock();
wakuMock.startInterval();
return wakuMock;
}
public async send(message: string): Promise<void> {
const timestamp = new Date();
const handle = 'me';
this.emit('message', {
timestamp,
handle,
message,
});
}
private startInterval() {
if (this.intervalId === undefined) {
this.intervalId = setInterval(this.emitMessage.bind(this), 1000);
}
}
private emitMessage() {
const handle = 'you';
const timestamp = new Date();
this.emit('message', {
timestamp,
handle,
message: `This is message #${this.index++}.`,
});
}
}

28
web-chat/src/index.css Normal file
View File

@ -0,0 +1,28 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.room-row {
text-align: left;
margin-left: 20px;
}
.room-row:after {
clear: both;
content: "";
display: table;
}
.chat-room{
margin: 2px;
}

11
web-chat/src/index.tsx Normal file
View File

@ -0,0 +1,11 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

1
web-chat/src/react-app-env.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

26
web-chat/tsconfig.json Normal file
View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}