Skip to content

Commit

Permalink
General code improvement
Browse files Browse the repository at this point in the history
- Functional components
- Single socket connection
- 0 lines of css
- Split util functions to dedicated file
- Other minor changes
  • Loading branch information
arthurfiorette committed Mar 30, 2021
1 parent 1f29bbf commit 252f7e1
Show file tree
Hide file tree
Showing 16 changed files with 108 additions and 166 deletions.
3 changes: 0 additions & 3 deletions web/src/app/app.css

This file was deleted.

14 changes: 0 additions & 14 deletions web/src/app/app.tsx

This file was deleted.

7 changes: 1 addition & 6 deletions web/src/components/accounts/account.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { PencilFill, Power } from 'react-bootstrap-icons';
import { login, logout } from '../../services/accounts';
import { fetchSteamUserImage } from './util';

export default function Account({ account }: any) {
const name = account.login.username;
Expand Down Expand Up @@ -38,9 +39,3 @@ function ProfilePhoto({ account }: any) {
/>
);
}

// TODO: Fetch user profile photo correctly
function fetchSteamUserImage(): string {
// Default steam profile photo
return 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b5/b5bd56c1aa4644a474a2e4972be27ef9e82e517e_full.jpg';
}
61 changes: 22 additions & 39 deletions web/src/components/accounts/index.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,31 @@
import React, { Component, Fragment } from 'react';
import AccountDisplay from './account';
import React, { useState, useEffect, Fragment } from 'react';
import Account from './account';
import { Offcanvas, Button } from './offcanvas';
import { AccountOptions, getAccounts } from '../../services/accounts';

interface DisplayState {
accounts: AccountOptions[];
}

export default class Display extends Component<any, DisplayState> {
id = 'displayOffcanvas';

constructor(props: any) {
super(props);
export default function Accounts() {
const [accounts, setAccounts] = useState<AccountOptions[]>([]);
const id = 'displayOffcanvas';

useEffect(() => {
getAccounts()
.then((resp) => resp.data.response)
.then((accounts: AccountOptions[]) => this.setState({ accounts }));
}
.then((accounts: AccountOptions[]) => setAccounts(accounts));
}, []);

private renderAccounts() {
if (this.state == null) {
return 'Loading...';
} else {
return this.state.accounts.map((acc) => <AccountDisplay account={acc} />);
}
}

private addAccount = (account: AccountOptions) => {
this.setState({ accounts: [...this.state.accounts, account] });
};

render() {
return (
<Fragment>
<div id="accounts">
<div id="list" className="overflow-auto p-1" style={{ maxHeight: 'calc(50vh - 60px)' }}>
{this.renderAccounts()}
</div>
</div>
<div className="d-flex mt-2 justify-content-center">
<Button id={this.id} message="Create a new account" />
<Offcanvas id={this.id} onFormEntry={this.addAccount} />
return (
<Fragment>
<div id="accounts">
<div id="list" className="overflow-auto p-1" style={{ maxHeight: 'calc(50vh - 60px)' }}>
{accounts.map((acc) => (
<Account account={acc} />
))}
</div>
</Fragment>
);
}
</div>
<div className="d-flex mt-2 justify-content-center">
<Button id={id} message="Create a new account" />
<Offcanvas id={id} onFormEntry={(acc: AccountOptions) => setAccounts([...accounts, acc])} />
</div>
</Fragment>
);
}
4 changes: 4 additions & 0 deletions web/src/components/accounts/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// TODO: Fetch user profile photo correctly
export function fetchSteamUserImage() {
return 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b5/b5bd56c1aa4644a474a2e4972be27ef9e82e517e_full.jpg'; // Default steam profile photo
}
60 changes: 12 additions & 48 deletions web/src/components/logs/index.tsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,17 @@
import React, { Component, createRef } from 'react';
import io from 'socket.io-client';
import React, { useEffect, useState, Fragment } from 'react';
import Log from './log';
import socket from '../../services/socket';

interface LogsState {
logs: JSX.Element[];
}

export default class Logs extends Component<any, LogsState> {
socket = io('ws://localhost:1228');
export default function Logs() {
let [logs, setLogs] = useState<JSX.Element[]>([]);

constructor(props: any) {
super(props);
this.state = { logs: [] };
this.openSocket();
}

private openSocket() {
this.socket.on('log', (msg: any) => {
let { logs } = this.state;
if (logs.length == 50) logs = logs.slice(1, 50);
logs.push(createLog(msg));
this.setState({ logs });
useEffect(() => {
socket.on('log', (log: any) => {
if (logs.length >= 50) logs = logs.slice(1, 50);
logs.push(<Log log={log} />);
setLogs(logs);
});
}

render() {
return <div className="logger">{this.state.logs}</div>;
}
}

function createLog({ message, level, timestamp }: any) {
return (
<div>
<span className={`pe-3 text-${getColor(level)}`}>{new Date(timestamp).toLocaleTimeString()}</span>
<span className="text-wrap text-muted mw-100">{message}</span>
</div>
);
}
}, []);

function getColor(level: string) {
switch (level) {
case 'warn':
return 'warning';
case 'info':
return 'info';
case 'debug':
return 'dark';
case 'error':
return 'danger';
default:
return 'secondary';
}
return <Fragment>{logs}</Fragment>;
}
11 changes: 11 additions & 0 deletions web/src/components/logs/log.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';
import { getColor } from './util';

export default function Log({ message, level, timestamp }: any) {
return (
<div>
<span className={`pe-3 text-${getColor(level)}`}>{new Date(timestamp).toLocaleTimeString()}</span>
<span className="text-wrap text-muted mw-100">{message}</span>
</div>
);
}
14 changes: 14 additions & 0 deletions web/src/components/logs/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function getColor(level: string) {
switch (level) {
case 'warn':
return 'warning';
case 'info':
return 'info';
case 'debug':
return 'dark';
case 'error':
return 'danger';
default:
return 'secondary';
}
}
17 changes: 0 additions & 17 deletions web/src/components/registerAccount.tsx

This file was deleted.

34 changes: 10 additions & 24 deletions web/src/components/trades/index.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
import React, { Component, createRef } from 'react';
import { Item as IItem } from './util';
import React, { useEffect, useState, Fragment } from 'react';
import Trade from './trade';
import io from 'socket.io-client';
import socket from '../../services/socket';

interface LogsState {
trades: JSX.Element[];
}

export default class Trades extends Component<any, LogsState> {
socket = io('ws://localhost:1228');

constructor(props: any) {
super(props);
this.state = { trades: [] };
this.openSocket();
}
export default function Trades() {
let [trades, setTrades] = useState<JSX.Element[]>([]);

private openSocket() {
this.socket.on('trade', (trade: any) => {
let { trades } = this.state;
if (trades.length == 50) trades = trades.slice(1, 50);
useEffect(() => {
socket.on('trade', (trade: any) => {
if (trades.length >= 50) trades = trades.slice(1, 50);
trades.push(<Trade trade={trade} />);
this.setState({ trades });
setTrades(trades);
});
}
}, []);

render() {
return this.state.trades;
}
return <Fragment>{trades}</Fragment>;
}
8 changes: 2 additions & 6 deletions web/src/components/trades/item.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React from 'react';
import { Item as IItem, getItemName } from './util';
import { Item, getItemName, getImageUrl } from './util';
import { GiftFill } from 'react-bootstrap-icons';

export default function ItemFrame({ item, received }: { item: IItem; received: boolean }) {
export default function ItemFrame({ item, received }: { item: Item; received: boolean }) {
const name = getItemName(item);
return (
<img
Expand All @@ -21,7 +21,3 @@ export default function ItemFrame({ item, received }: { item: IItem; received: b
export function EmptyItemFrame() {
return <GiftFill className="alert shadow-sm border-2 alert-secondary text-secondary p-1 m-1" height="50px" width="50px" />;
}

function getImageUrl({ icon_url }: IItem) {
return `https://steamcommunity-a.akamaihd.net/economy/image/${icon_url}`;
}
4 changes: 4 additions & 0 deletions web/src/components/trades/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ export function getItemName({ market_name, market_hash_name, name }: Item) {
if (isEmpty(market_name)) return market_name;
return name;
}

export function getImageUrl({ icon_url }: Item) {
return `https://steamcommunity-a.akamaihd.net/economy/image/${icon_url}`;
}
File renamed without changes.
14 changes: 11 additions & 3 deletions web/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import React from 'react';
import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';

import App from './app/app';
import Header from './header';
import Main from './main';

ReactDOM.render(<App />, document.getElementById('app'));
const element = (
<Fragment>
<Header />
<Main />
</Fragment>
);

ReactDOM.render(element, document.getElementById('app'));
12 changes: 6 additions & 6 deletions web/src/app/main.tsx → web/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from 'react';

import InfoBox from '../components/infoBox';
import Logs from '../components/logs';
import Account from '../components/accounts';
import Trades from '../components/trades';
import InfoBox from './components/infoBox';
import Logs from './components/logs';
import Account from './components/accounts';
import Trades from './components/trades';

export default function Main() {
return (
Expand All @@ -27,9 +27,9 @@ export default function Main() {

function Column({ size, title, children }: any) {
return (
<div className={`col-${size} mt-3`}>
<section className={`col-${size} mt-3`}>
<InfoBox title={title}>{children}</InfoBox>
</div>
</section>
);
}

Expand Down
11 changes: 11 additions & 0 deletions web/src/services/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import io from 'socket.io-client';

const socket = io('ws://localhost:1228');

socket.on('connect_error', (err: any) =>
alert(
`Oops! Occurred and error and we are disconnected from the app socket: ${err.message}. Make sure you started the all this app correctly.`
)
);

export default socket;

0 comments on commit 252f7e1

Please sign in to comment.