Refactored App component in front. Implemented pnpm workspaces. Separated messages types into package

This commit is contained in:
2021-09-04 19:16:22 +03:00
parent 0328b4d3d1
commit 8be147c3b8
36 changed files with 152 additions and 81 deletions

2
apps/back/.env.example Normal file
View File

@@ -0,0 +1,2 @@
DATABASE_URL="postgresql://"
PORT=8081

3
apps/back/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
certs/
src/db/config.ts
.env

20
apps/back/package.json Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "@roomruler/back",
"version": "0.0.0",
"scripts": {
"build": "tsc --build",
"start": "node dist/index.js"
},
"devDependencies": {
"@types/ws": "^7.4.7",
"typescript": "^4.4.2"
},
"dependencies": {
"@roomruler/messages": "workspace:^0.0.0",
"pg": "^8.7.1",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.2.37",
"ws": "^8.2.1"
},
"private": "true"
}

View File

@@ -0,0 +1 @@
export const idMsgTypes = ["freed", "occupied"] as const;

View File

@@ -0,0 +1,6 @@
export const config = {
host: "",
username: "",
password: "",
database: "",
};

29
apps/back/src/db/index.ts Normal file
View File

@@ -0,0 +1,29 @@
import { Connection, createConnection } from "typeorm";
import fs from "fs";
import { Room } from "./model";
import { config } from "./config";
export { Room };
export const connect = () =>
createConnection({
...config,
type: "cockroachdb",
port: 26257,
ssl: {
ca: fs.readFileSync("certs/cc-ca.crt").toString(),
},
synchronize: true,
logging: false,
entities: [Room],
});
export const getRoomList = (connection: Connection) =>
connection.manager.find(Room);
export const updateFree = (
connection: Connection,
id: number,
value: boolean
) => connection.manager.update(Room, id, { free: value });

27
apps/back/src/db/model.ts Normal file
View File

@@ -0,0 +1,27 @@
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export abstract class Room {
@PrimaryGeneratedColumn()
abstract id: number;
@Column({
length: 100,
})
abstract title: string;
@Column()
abstract free: boolean;
@Column()
abstract x: number;
@Column()
abstract y: number;
@Column()
abstract width: number;
@Column()
abstract height: number;
}

46
apps/back/src/index.ts Normal file
View File

@@ -0,0 +1,46 @@
import "reflect-metadata";
import { Server, OPEN } from "ws";
import { connect, getRoomList, updateFree } from "./db";
import { isMessage, isUpdateMessage } from "@roomruler/messages";
const main = async () => {
const connection = await connect();
const wss = new Server(
{
port: Number.parseInt(process.env.PORT || "") || 8081,
},
() => console.log(`Started server on ${process.env.PORT || 8081}`)
);
wss.on("connection", async (wsc, req) => {
console.log("New user connected from " + req.socket.remoteAddress);
wsc.send(JSON.stringify(await getRoomList(connection)));
wsc.on("message", async (data) => {
console.log("Got message from " + req.socket.remoteAddress);
try {
const message: unknown = JSON.parse(data.toString());
if (!isMessage(message)) throw new Error("Message corrupted");
if (isUpdateMessage(message)) {
console.log(
`Processing message of \"${message.type}\" type from ${req.socket.remoteAddress}`
);
const { id, value } = message.args;
await updateFree(connection, id, value);
wss.clients.forEach((client) => {
if (client.readyState === OPEN)
client.send(JSON.stringify(message));
});
}
} catch (err) {
console.log("Error processing message", err);
}
});
});
};
main();

9
apps/back/tsconfig.json Normal file
View File

@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist"
},
"references": [{ "path": "../../packages/messages/tsconfig.json" }]
}

13
apps/front/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>roomruler</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

21
apps/front/package.json Normal file
View File

@@ -0,0 +1,21 @@
{
"name": "@roomruler/front",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"start": "vite",
"build": "vite build"
},
"devDependencies": {
"@types/react-dom": "^17.0.9",
"typescript": "^4.4.2",
"vite": "^2.5.3"
},
"dependencies": {
"@material-ui/core": "^4.12.3",
"immer": "^9.0.6",
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"private": "true"
}

50
apps/front/src/App.tsx Normal file
View File

@@ -0,0 +1,50 @@
import { useEffect, useRef, useState } from "react";
import { makeStyles, Grid, useTheme } from "@material-ui/core";
import { RoomContextProvider, useRoomContext } from "./context";
import { BuildingPlan } from "./components/BuildingPlan";
import { RoomList } from "./components/RoomList";
import { AppTheme } from "./theme";
import { Header } from "./components/Header";
const useStyles = makeStyles((theme) => ({
root: {
padding: theme.spacing(10, 2, 2, 2),
height: "100vh",
"& > div > *": {
height: "100%",
},
},
}));
export const App = () => {
const theme = useTheme();
const classes = useStyles();
const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 });
const planContainer = useRef<HTMLDivElement>(null);
useEffect(() => {
if (planContainer.current)
setCanvasSize({
w: planContainer.current.clientWidth - theme.spacing(2),
h: planContainer.current.clientHeight - theme.spacing(1),
});
}, [planContainer.current]);
return (
<AppTheme>
<RoomContextProvider>
<Header />
<Grid className={classes.root} container>
<Grid ref={planContainer} item xs={9}>
<BuildingPlan width={canvasSize.w} height={canvasSize.h} />
</Grid>
<Grid item xs={3}>
<RoomList />
</Grid>
</Grid>
</RoomContextProvider>
</AppTheme>
);
};

View File

@@ -0,0 +1,69 @@
import { useTheme } from "@material-ui/core";
import { useCallback } from "react";
import { useRoomContext } from "../context";
import { RoomDisplay } from "../types/room";
import { Canvas } from "./Canvas";
export type BuildingPlanProps = { width?: number; height?: number };
const getRoomByCoord = (x: number, y: number, map: RoomDisplay[]) => {
for (let i = 0; i < map.length; i++) {
const { coordinates, size } = map[i];
if (
x >= coordinates.x &&
x <= coordinates.x + size.w &&
y >= coordinates.y &&
y <= coordinates.y + size.h
)
return i;
}
return -1;
};
export const BuildingPlan = ({ width, height }: BuildingPlanProps) => {
const { state, toggleFree } = useRoomContext();
const theme = useTheme();
const draw = useCallback(
(ctx: CanvasRenderingContext2D) => {
// Text styles
ctx.font = `${theme.typography.h6.fontSize} ${theme.typography.h6.fontFamily}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
state.map.map(({ coordinates, size, title }, index) => {
// Draw room rectangle
const { free } = state.char[index];
ctx.fillStyle = free
? theme.palette.success.main
: theme.palette.grey[500];
ctx.fillRect(coordinates.x, coordinates.y, size.w, size.h);
// Draw its number
ctx.fillStyle = free
? theme.palette.success.contrastText
: theme.palette.getContrastText(theme.palette.grey[500]);
ctx.fillText(
`${title}`,
coordinates.x + size.w / 2,
coordinates.y + size.h / 2
);
});
},
[state.char, state.map]
);
const clickCb = (x: number, y: number) => {
const index = getRoomByCoord(x, y, state.map);
if (index >= 0) toggleFree(index);
};
return (
<>
<Canvas clickCb={clickCb} height={height} width={width} draw={draw} />
</>
);
};

View File

@@ -0,0 +1,68 @@
import { HTMLProps, useEffect, useRef, MouseEvent, useCallback } from "react";
export type DrawFT = (ctx: CanvasRenderingContext2D) => void;
export type ClickCb = (x: number, y: number) => void;
export type CanvasProps = HTMLProps<HTMLCanvasElement> & {
draw: DrawFT;
clickCb: ClickCb;
width?: number;
height?: number;
};
export const useCanvas = (
draw: DrawFT,
clickCb: ClickCb,
width?: number,
height?: number
) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) throw new Error("Canvas ref not set");
const context = canvas.getContext("2d");
if (!context) throw new Error("Couldn't get canvas context");
draw(context);
}, [draw, width, height]);
const onClick = useCallback(
(event: MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) throw new Error("Canvas ref not set");
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
clickCb(x, y);
},
[canvasRef.current]
);
return { canvasRef, onClick };
};
export const Canvas = ({
draw,
clickCb,
width,
height,
...props
}: CanvasProps) => {
const { canvasRef, onClick } = useCanvas(draw, clickCb, width, height);
return (
<canvas
onClick={onClick}
width={width}
height={height}
ref={canvasRef}
{...props}
/>
);
};

View File

@@ -0,0 +1,9 @@
import { AppBar, Toolbar, Typography } from "@material-ui/core";
export const Header = () => (
<AppBar>
<Toolbar>
<Typography variant="h6">roomruler</Typography>
</Toolbar>
</AppBar>
);

View File

@@ -0,0 +1,101 @@
import {
Paper,
List,
ListItem,
ListItemIcon,
ListItemText,
Typography,
makeStyles,
InputLabel,
Select,
Box,
} from "@material-ui/core";
import { ChangeEvent, useState } from "react";
import { useRoomContext } from "../context";
import { FilterState } from "../types/ui";
const useStyles = makeStyles((theme) => ({
drawer: {
width: "100%",
height: `calc(100% - ${theme.spacing(1)}px)`,
padding: theme.spacing(2),
},
filterBox: {
display: "flex",
alignItems: "center",
gap: theme.spacing(1),
},
indicatorContainer: {
minWidth: theme.spacing(3),
},
indicator: {
width: theme.spacing(2),
height: theme.spacing(2),
borderRadius: "100%",
},
free: {
background: theme.palette.success.main,
},
busy: {
background: theme.palette.grey[500],
},
}));
export const RoomList = () => {
const classes = useStyles();
const { state } = useRoomContext();
const [filter, setFilter] = useState(FilterState.ALL);
const handleFilterChange = (
event: ChangeEvent<{ name?: string; value: unknown }>
) => {
if (event.target && typeof event.target.value === "string")
setFilter(Number.parseInt(event.target.value));
};
return (
<Paper className={classes.drawer}>
<Typography variant="h6">Class room avaliability status</Typography>
<Box className={classes.filterBox}>
<InputLabel htmlFor="filter">Filter</InputLabel>
<Select
native
value={filter}
onChange={handleFilterChange}
inputProps={{
name: "filter",
id: "filter",
}}
>
<option value={FilterState.ALL}>All</option>
<option value={FilterState.FREE}>Free</option>
<option value={FilterState.BUSY}>Busy</option>
</Select>
</Box>
<List>
{state.map.map(({ title }, index) => {
if (filter === FilterState.FREE && !state.char[index].free) return "";
else if (filter === FilterState.BUSY && state.char[index].free)
return "";
else
return (
<ListItem key={title} disableGutters>
<ListItemIcon className={classes.indicatorContainer}>
<div
className={`${classes.indicator} ${
state.char[index].free ? classes.free : classes.busy
}`}
/>
</ListItemIcon>
<ListItemText primary={title} />
</ListItem>
);
})}
</List>
</Paper>
);
};

View File

@@ -0,0 +1,40 @@
import { ContextData } from "./types/context";
import { PeriodFormat } from "./types/time";
export const lessonPeriods: readonly PeriodFormat[] = [
"8:30-9:10",
"9:20-10:00",
"10:15-10:55",
"11:10-11:50",
"12:00-12:40",
"12:50-13:30",
] as const;
export const WeekDays = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
] as const;
// It will look like Windows 11 logo, lol
export const defaultState: ContextData = {
map: [
{ x: 5, y: 5 },
{ x: 110, y: 5 },
{ x: 5, y: 110 },
{ x: 110, y: 110 },
].map((coordinates, index) => ({
coordinates,
size: { w: 100, h: 100 },
title: index + 1,
})),
char: Array(4)
.fill(0)
.map(() => ({
free: true,
})),
};

View File

@@ -0,0 +1,33 @@
import produce from "immer";
import { createContext, FC, useContext, useState } from "react";
import { defaultState } from "./constants";
import { ContextData, ContextValue } from "./types/context";
const Context = createContext<ContextValue | undefined>(undefined);
export const RoomContextProvider: FC = ({ children }) => {
const [state, setState] = useState<ContextData>(defaultState);
const toggleFree = (index: number) =>
setState(
produce((draft) => {
draft.char[index].free = !draft.char[index].free;
})
);
return (
<Context.Provider value={{ state, toggleFree }}>
{children}
</Context.Provider>
);
};
export const useRoomContext = () => {
const context = useContext(Context);
if (!context)
throw new Error("useRoomContext must be used within RoomContextProvider");
return context;
};

5
apps/front/src/index.tsx Normal file
View File

@@ -0,0 +1,5 @@
import ReactDOM from "react-dom";
import { App } from "./App";
ReactDOM.render(<App />, document.getElementById("root"));

28
apps/front/src/theme.tsx Normal file
View File

@@ -0,0 +1,28 @@
import {
createTheme,
CssBaseline,
ThemeProvider,
useMediaQuery,
} from "@material-ui/core";
import { FC, useMemo } from "react";
export const AppTheme: FC = ({ children }) => {
const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
const theme = useMemo(
() =>
createTheme({
palette: {
type: prefersDarkMode ? "dark" : "light",
},
}),
[prefersDarkMode]
);
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
};

View File

@@ -0,0 +1,11 @@
import { RoomDisplay, RoomState } from "./room";
export interface ContextData {
map: RoomDisplay[];
char: RoomState[];
}
export type ContextValue = {
state: ContextData;
toggleFree: (index: number) => void;
};

View File

@@ -0,0 +1,9 @@
export interface RoomDisplay {
coordinates: { x: number; y: number };
size: { w: number; h: number };
title: string | number;
}
export interface RoomState {
free: boolean;
}

View File

@@ -0,0 +1,5 @@
import { WeekDays } from "../constants";
export type PeriodFormat = `${number}:${number}-${number}:${number}`;
export type WeekDay = typeof WeekDays[number];

View File

@@ -0,0 +1,5 @@
export enum FilterState {
ALL,
FREE,
BUSY,
}

8
apps/front/tsconfig.json Normal file
View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "es6",
"module": "ESNext",
"jsx": "react-jsx"
}
}

View File

@@ -0,0 +1,7 @@
import { defineConfig } from "vite";
export default defineConfig({
esbuild: {
jsxInject: `import React from "react"`,
},
});