Formatted all files with Prettier

This commit is contained in:
aronmal 2023-02-08 10:31:03 +01:00
parent 0bc2196d9f
commit ea80456a56
Signed by: aronmal
GPG key ID: 816B7707426FC612
64 changed files with 2209 additions and 1839 deletions

View file

@ -4,10 +4,10 @@ function Bluetooth() {
const [startDisabled, setStartDisabled] = useState(true) const [startDisabled, setStartDisabled] = useState(true)
const [stopDisabled, setStopDisabled] = useState(true) const [stopDisabled, setStopDisabled] = useState(true)
const deviceName = 'Chromecast Remote' const deviceName = "Chromecast Remote"
// ble UV Index // ble UV Index
const bleService = 'environmental_sensing' const bleService = "environmental_sensing"
const bleCharacteristic = 'uv_index' const bleCharacteristic = "uv_index"
// ble Battery percentage // ble Battery percentage
// const bleService = 'battery_service' // const bleService = 'battery_service'
@ -21,7 +21,7 @@ function Bluetooth() {
function isWebBluetoothEnabled() { function isWebBluetoothEnabled() {
if (!navigator.bluetooth) { if (!navigator.bluetooth) {
alert('Web Bluetooth API is not available in this browser!') alert("Web Bluetooth API is not available in this browser!")
return false return false
} }
return true return true
@ -29,51 +29,56 @@ function Bluetooth() {
function getDeviceInfo() { function getDeviceInfo() {
const options = { const options = {
// acceptAllDevices: true, // acceptAllDevices: true,
filters: [ filters: [{ name: deviceName }],
{ name: deviceName }
],
// optionalServices: ['battery_service'], // optionalServices: ['battery_service'],
} }
console.log('Requesting Bluetooth Device...') console.log("Requesting Bluetooth Device...")
return navigator.bluetooth return navigator.bluetooth
.requestDevice(options) .requestDevice(options)
.then(device => { .then((device) => {
bluetoothDeviceDetected = device bluetoothDeviceDetected = device
console.log('> Name: ' + device.name) console.log("> Name: " + device.name)
device.addEventListener('gattserverdisconnected', onDisconnected) device.addEventListener("gattserverdisconnected", onDisconnected)
}) })
.catch(error => console.log('Argh! ' + error)) .catch((error) => console.log("Argh! " + error))
} }
function read() { function read() {
if (!isWebBluetoothEnabled()) if (!isWebBluetoothEnabled()) return
return
return getDeviceInfo() return getDeviceInfo()
.then(connectGatt) .then(connectGatt)
.then(_ => { .then((_) => {
console.log('Reading UV Index...') console.log("Reading UV Index...")
return gattCharacteristic.readValue() return gattCharacteristic.readValue()
}) })
.catch(error => console.log('Waiting to start reading: ' + error)) .catch((error) => console.log("Waiting to start reading: " + error))
} }
function connectGatt() { function connectGatt() {
if (bluetoothDeviceDetected.gatt && bluetoothDeviceDetected.gatt.connected && gattCharacteristic) if (
bluetoothDeviceDetected.gatt &&
bluetoothDeviceDetected.gatt.connected &&
gattCharacteristic
)
return Promise.resolve() return Promise.resolve()
if (!bluetoothDeviceDetected || !bluetoothDeviceDetected.gatt) if (!bluetoothDeviceDetected || !bluetoothDeviceDetected.gatt)
return Promise.reject() return Promise.reject()
return bluetoothDeviceDetected.gatt.connect() return bluetoothDeviceDetected.gatt
.then(server => { .connect()
console.log('Getting GATT Service...') .then((server) => {
console.log("Getting GATT Service...")
return server.getPrimaryService(bleService) return server.getPrimaryService(bleService)
}) })
.then(service => { .then((service) => {
console.log('Getting GATT Characteristic...') console.log("Getting GATT Characteristic...")
return service.getCharacteristic(bleCharacteristic) return service.getCharacteristic(bleCharacteristic)
}) })
.then(characteristic => { .then((characteristic) => {
gattCharacteristic = characteristic gattCharacteristic = characteristic
characteristic.addEventListener('characteristicvaluechanged', handleChangedValue) characteristic.addEventListener(
"characteristicvaluechanged",
handleChangedValue
)
setStartDisabled(false) setStartDisabled(false)
setStopDisabled(true) setStopDisabled(true)
@ -82,13 +87,15 @@ function Bluetooth() {
function handleChangedValue(event: Event) { function handleChangedValue(event: Event) {
const characteristic = event.target as BluetoothRemoteGATTCharacteristic const characteristic = event.target as BluetoothRemoteGATTCharacteristic
if (!characteristic.value) { if (!characteristic.value) {
console.log('Characteristic undefined!') console.log("Characteristic undefined!")
return return
} }
const value = characteristic.value.getUint8(0) const value = characteristic.value.getUint8(0)
const now = new Date() const now = new Date()
// Output the UV Index // Output the UV Index
console.log(`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} UV Index is ${value}`) console.log(
`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} UV Index is ${value}`
)
// Output the Battery percentage // Output the Battery percentage
// console.log(`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} Battery percentage is ${value}`) // console.log(`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} Battery percentage is ${value}`)
@ -98,26 +105,26 @@ function Bluetooth() {
// console.log(`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} Manufacturer Name is ${decoder.decode(characteristic.value)}`) // console.log(`> ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()} Manufacturer Name is ${decoder.decode(characteristic.value)}`)
} }
function start() { function start() {
if (!isWebBluetoothEnabled()) if (!isWebBluetoothEnabled()) return
return gattCharacteristic
gattCharacteristic.startNotifications() .startNotifications()
.then(_ => { .then((_) => {
console.log('Start reading...') console.log("Start reading...")
setStartDisabled(true) setStartDisabled(true)
setStopDisabled(false) setStopDisabled(false)
}) })
.catch(error => console.log('[ERROR] Start: ' + error)) .catch((error) => console.log("[ERROR] Start: " + error))
} }
function stop() { function stop() {
if (!isWebBluetoothEnabled()) if (!isWebBluetoothEnabled()) return
return gattCharacteristic
gattCharacteristic.stopNotifications() .stopNotifications()
.then(_ => { .then((_) => {
console.log('Stop reading...') console.log("Stop reading...")
setStartDisabled(false) setStartDisabled(false)
setStopDisabled(true) setStopDisabled(true)
}) })
.catch(error => console.log('[ERROR] Stop: ' + error)) .catch((error) => console.log("[ERROR] Stop: " + error))
} }
function onDisconnected(event: Event) { function onDisconnected(event: Event) {
alert("Device Disconnected") alert("Device Disconnected")
@ -128,48 +135,55 @@ function Bluetooth() {
return ( return (
<div> <div>
<button <button id="read" className="bluetooth" onClick={read}>
id="read" Connect with BLE device
className="bluetooth" </button>
onClick={read}
>Connect with BLE device</button>
<button <button
id="start" id="start"
className="bluetooth" className="bluetooth"
disabled={startDisabled} disabled={startDisabled}
onClick={start} onClick={start}
>Start</button> >
Start
</button>
<button <button
id="stop" id="stop"
className="bluetooth" className="bluetooth"
disabled={stopDisabled} disabled={stopDisabled}
onClick={stop} onClick={stop}
>Stop</button> >
Stop
</button>
<p> <p>
<span <span
className="App-link" className="App-link"
onClick={() => { navigator.clipboard.writeText("chrome://flags/#enable-experimental-web-platform-features") }} onClick={() => {
navigator.clipboard.writeText(
"chrome://flags/#enable-experimental-web-platform-features"
)
}}
// target="_blank" // target="_blank"
style={{ "cursor": "pointer" }} style={{ cursor: "pointer" }}
// rel="noopener noreferrer" // rel="noopener noreferrer"
> >
Step 1 Step 1
</span> </span>{" "}
{" "}
<span <span
className="App-link" className="App-link"
onClick={() => { navigator.clipboard.writeText("chrome://flags/#enable-web-bluetooth-new-permissions-backend") }} onClick={() => {
navigator.clipboard.writeText(
"chrome://flags/#enable-web-bluetooth-new-permissions-backend"
)
}}
// target="_blank" // target="_blank"
style={{ "cursor": "pointer" }} style={{ cursor: "pointer" }}
// rel="noopener noreferrer" // rel="noopener noreferrer"
> >
Step 2 Step 2
</span> </span>
</p> </p>
</div> </div>
) )
} }
export default Bluetooth export default Bluetooth

View file

@ -1,20 +1,22 @@
import { CSSProperties, Dispatch, SetStateAction } from 'react' import { CSSProperties, Dispatch, SetStateAction } from "react"
import { borderCN, cornerCN, fieldIndex } from '../lib/utils/helpers' import { borderCN, cornerCN, fieldIndex } from "../lib/utils/helpers"
import { Position, MouseCursor } from '../interfaces/frontend' import { Position, MouseCursor } from "../interfaces/frontend"
type TilesType = { type TilesType = {
key: number, key: number
isGameTile: boolean, isGameTile: boolean
classNameString: string, classNameString: string
x: number, x: number
y: number y: number
} }
function BorderTiles({ props: { count, settingTarget, setMouseCursor, setLastLeftTile } }: { function BorderTiles({
props: { count, settingTarget, setMouseCursor, setLastLeftTile },
}: {
props: { props: {
count: number, count: number
settingTarget: (isGameTile: boolean, x: number, y: number) => void, settingTarget: (isGameTile: boolean, x: number, y: number) => void
setMouseCursor: Dispatch<SetStateAction<MouseCursor>>, setMouseCursor: Dispatch<SetStateAction<MouseCursor>>
setLastLeftTile: Dispatch<SetStateAction<Position>> setLastLeftTile: Dispatch<SetStateAction<Position>>
} }
}) { }) {
@ -26,28 +28,38 @@ function BorderTiles({ props: { count, settingTarget, setMouseCursor, setLastLef
const cornerReslt = cornerCN(count, x, y) const cornerReslt = cornerCN(count, x, y)
const borderType = cornerReslt ? cornerReslt : borderCN(count, x, y) const borderType = cornerReslt ? cornerReslt : borderCN(count, x, y)
const isGameTile = x > 0 && x < count + 1 && y > 0 && y < count + 1 const isGameTile = x > 0 && x < count + 1 && y > 0 && y < count + 1
const classNames = ['border-tile'] const classNames = ["border-tile"]
if (borderType) if (borderType) classNames.push("edge", borderType)
classNames.push('edge', borderType) if (isGameTile) classNames.push("game-tile")
if (isGameTile) const classNameString = classNames.join(" ")
classNames.push('game-tile') tilesProperties.push({
const classNameString = classNames.join(' ') key,
tilesProperties.push({ key, classNameString, isGameTile, x: x + 1, y: y + 1 }) classNameString,
isGameTile,
x: x + 1,
y: y + 1,
})
} }
} }
return (<> return (
<>
{tilesProperties.map(({ key, classNameString, isGameTile, x, y }) => { {tilesProperties.map(({ key, classNameString, isGameTile, x, y }) => {
return <div return (
<div
key={key} key={key}
className={classNameString} className={classNameString}
style={{ '--x': x, '--y': y } as CSSProperties} style={{ "--x": x, "--y": y } as CSSProperties}
onClick={() => settingTarget(isGameTile, x, y)} onClick={() => settingTarget(isGameTile, x, y)}
onMouseEnter={() => setMouseCursor({ x, y, shouldShow: isGameTile })} onMouseEnter={() =>
setMouseCursor({ x, y, shouldShow: isGameTile })
}
onMouseLeave={() => setLastLeftTile({ x, y })} onMouseLeave={() => setLastLeftTile({ x, y })}
></div> ></div>
)
})} })}
</>) </>
)
} }
export default BorderTiles export default BorderTiles

View file

@ -1,30 +1,35 @@
import React, { Dispatch, SetStateAction } from 'react' import React, { Dispatch, SetStateAction } from "react"
import { Items, Target } from '../interfaces/frontend' import { Items, Target } from "../interfaces/frontend"
import Item from './Item' import Item from "./Item"
function EventBar({ props: { setMode, setTarget } }: { function EventBar({
props: { setMode, setTarget },
}: {
props: { props: {
setMode: Dispatch<SetStateAction<number>>, setMode: Dispatch<SetStateAction<number>>
setTarget: Dispatch<SetStateAction<Target>> setTarget: Dispatch<SetStateAction<Target>>
} }
}) { }) {
const items: Items[] = [ const items: Items[] = [
{ icon: 'burger-menu', text: 'Menu' }, { icon: "burger-menu", text: "Menu" },
{ icon: 'radar', text: 'Radar scan', mode: 0, amount: 1 }, { icon: "radar", text: "Radar scan", mode: 0, amount: 1 },
{ icon: 'torpedo', text: 'Fire torpedo', mode: 1, amount: 1 }, { icon: "torpedo", text: "Fire torpedo", mode: 1, amount: 1 },
{ icon: 'scope', text: 'Fire missile', mode: 2 }, { icon: "scope", text: "Fire missile", mode: 2 },
{ icon: 'gear', text: 'Settings' } { icon: "gear", text: "Settings" },
] ]
return ( return (
<div className='event-bar'> <div className="event-bar">
{items.map((e, i) => ( {items.map((e, i) => (
<Item key={i} props={{ <Item
...e, callback: () => { key={i}
if (e.mode !== undefined) props={{
setMode(e.mode) ...e,
setTarget(e => ({ ...e, show: false })) callback: () => {
} if (e.mode !== undefined) setMode(e.mode)
}} /> setTarget((e) => ({ ...e, show: false }))
},
}}
/>
))} ))}
</div> </div>
) )

View file

@ -1,11 +1,13 @@
import Image from "next/image" import Image from "next/image"
function FogImages() { function FogImages() {
return <> return (
<Image className='fog left' src={`/fog/fog2.png`} alt={`fog1.png`} /> <>
<Image className='fog right' src={`/fog/fog2.png`} alt={`fog1.png`} /> <Image className="fog left" src={`/fog/fog2.png`} alt={`fog1.png`} />
<Image className='fog middle' src={`/fog/fog4.png`} alt={`fog4.png`} /> <Image className="fog right" src={`/fog/fog2.png`} alt={`fog1.png`} />
<Image className="fog middle" src={`/fog/fog4.png`} alt={`fog4.png`} />
</> </>
)
} }
export default FogImages export default FogImages

View file

@ -1,28 +1,22 @@
import { CSSProperties } from 'react' import { CSSProperties } from "react"
// import Bluetooth from './Bluetooth' // import Bluetooth from './Bluetooth'
import BorderTiles from './BorderTiles' import BorderTiles from "./BorderTiles"
import EventBar from './EventBar' import EventBar from "./EventBar"
// import FogImages from './FogImages' // import FogImages from './FogImages'
import HitElems from './HitElems' import HitElems from "./HitElems"
import Labeling from './Labeling' import Labeling from "./Labeling"
import Ships from './Ships' import Ships from "./Ships"
import useGameEvent from '../lib/hooks/useGameEvent' import useGameEvent from "../lib/hooks/useGameEvent"
import Targets from './Targets' import Targets from "./Targets"
function Gamefield() { function Gamefield() {
const count = 12 const count = 12
const { const { pointersProps, targetsProps, tilesProps, hits } = useGameEvent(count)
pointersProps,
targetsProps,
tilesProps,
hits
} = useGameEvent(count)
return ( return (
<div id='gamefield'> <div id="gamefield">
{/* <Bluetooth /> */} {/* <Bluetooth /> */}
<div id="game-frame" style={{ '--i': count } as CSSProperties}> <div id="game-frame" style={{ "--i": count } as CSSProperties}>
{/* Bordes */} {/* Bordes */}
<BorderTiles props={tilesProps} /> <BorderTiles props={tilesProps} />

View file

@ -1,27 +1,36 @@
import { faCrosshairs } from '@fortawesome/pro-solid-svg-icons' import { faCrosshairs } from "@fortawesome/pro-solid-svg-icons"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { CSSProperties } from 'react' import { CSSProperties } from "react"
import classNames from 'classnames' import classNames from "classnames"
import { faRadar } from '@fortawesome/pro-thin-svg-icons' import { faRadar } from "@fortawesome/pro-thin-svg-icons"
import { Target, TargetList } from '../interfaces/frontend' import { Target, TargetList } from "../interfaces/frontend"
export interface PointerProps extends Target, TargetList { export interface PointerProps extends Target, TargetList {
imply: boolean; imply: boolean
} }
function GamefieldPointer({ props: { function GamefieldPointer({
preview, props: { preview, x, y, show, type, edges, imply },
x, }: {
y, props: PointerProps
show, }) {
type, const isRadar = type === "radar"
edges, const style = !(isRadar && !edges.filter((s) => s).length)
imply ? { "--x": x, "--y": y }
} }: { props: PointerProps }) { : { "--x1": x - 1, "--x2": x + 2, "--y1": y - 1, "--y2": y + 2 }
const isRadar = type === 'radar'
const style = !(isRadar && !edges.filter(s => s).length) ? { '--x': x, '--y': y } : { '--x1': x - 1, '--x2': x + 2, '--y1': y - 1, '--y2': y + 2 }
return ( return (
<div className={classNames('hit-svg', { preview: preview }, 'target', type, { show: show }, ...edges, { imply: imply })} style={style as CSSProperties}> <div
className={classNames(
"hit-svg",
{ preview: preview },
"target",
type,
{ show: show },
...edges,
{ imply: imply }
)}
style={style as CSSProperties}
>
<FontAwesomeIcon icon={!isRadar ? faCrosshairs : faRadar} /> <FontAwesomeIcon icon={!isRadar ? faCrosshairs : faRadar} />
</div> </div>
) )

View file

@ -1,15 +1,18 @@
import classNames from 'classnames' import classNames from "classnames"
import { CSSProperties, useEffect, useMemo, useState } from 'react' import { CSSProperties, useEffect, useMemo, useState } from "react"
function Grid() { function Grid() {
function floorClient(number: number) { function floorClient(number: number) {
return Math.floor(number / 50) return Math.floor(number / 50)
} }
const [columns, setColumns] = useState(0) const [columns, setColumns] = useState(0)
const [rows, setRows] = useState(0) const [rows, setRows] = useState(0)
const [params, setParams] = useState({ columns, rows, quantity: columns * rows }) const [params, setParams] = useState({
columns,
rows,
quantity: columns * rows,
})
const [position, setPosition] = useState([0, 0]) const [position, setPosition] = useState([0, 0])
const [active, setActve] = useState(false) const [active, setActve] = useState(false)
const [count, setCount] = useState(0) const [count, setCount] = useState(0)
@ -20,7 +23,7 @@ function Grid() {
setRows(floorClient(document.body.clientHeight)) setRows(floorClient(document.body.clientHeight))
} }
handleResize() handleResize()
window.addEventListener('resize', handleResize) window.addEventListener("resize", handleResize)
}, []) }, [])
useEffect(() => { useEffect(() => {
@ -31,27 +34,24 @@ function Grid() {
}, [columns, rows]) }, [columns, rows])
const createTiles = useMemo(() => { const createTiles = useMemo(() => {
const colors = [ const colors = [
'rgb(229, 57, 53)', "rgb(229, 57, 53)",
'rgb(253, 216, 53)', "rgb(253, 216, 53)",
'rgb(244, 81, 30)', "rgb(244, 81, 30)",
'rgb(76, 175, 80)', "rgb(76, 175, 80)",
'rgb(33, 150, 243)', "rgb(33, 150, 243)",
'rgb(156, 39, 176)' "rgb(156, 39, 176)",
] ]
function createTile(index: number) { function createTile(index: number) {
const x = index % params.columns const x = index % params.columns
const y = Math.floor(index / params.columns) const y = Math.floor(index / params.columns)
const xDiff = (x - position[0]) / 20 const xDiff = (x - position[0]) / 20
const yDiff = (y - position[1]) / 20 const yDiff = (y - position[1]) / 20
const pos = (Math.sqrt(xDiff * xDiff + yDiff * yDiff)).toFixed(2) const pos = Math.sqrt(xDiff * xDiff + yDiff * yDiff).toFixed(2)
function doEffect(posX: number, posY: number) { function doEffect(posX: number, posY: number) {
if (active) if (active) return
return
setPosition([posX, posY]) setPosition([posX, posY])
setActve(true) setActve(true)
@ -64,27 +64,44 @@ function Grid() {
function pos(x: number, y: number) { function pos(x: number, y: number) {
return Math.sqrt(xDiff(x) * xDiff(x) + yDiff(y) * yDiff(y)) return Math.sqrt(xDiff(x) * xDiff(x) + yDiff(y) * yDiff(y))
} }
const diagonals = [pos(0, 0), pos(params.columns, 0), pos(0, params.rows), pos(params.columns, params.rows)] const diagonals = [
pos(0, 0),
pos(params.columns, 0),
pos(0, params.rows),
pos(params.columns, params.rows),
]
setTimeout(() => { setTimeout(() => {
setActve(false) setActve(false)
setCount(e => e + 1) setCount((e) => e + 1)
}, Math.max(...diagonals) * 1000 + 300) }, Math.max(...diagonals) * 1000 + 300)
} }
return ( return (
<div <div
key={index} key={index}
className={classNames('tile', { active: active })} className={classNames("tile", { active: active })}
style={{ '--delay': pos + 's' } as CSSProperties} style={{ "--delay": pos + "s" } as CSSProperties}
onClick={() => doEffect(x, y)} onClick={() => doEffect(x, y)}
></div> ></div>
) )
} }
return ( return (
<div id='tiles' style={{ '--columns': params.columns, '--rows': params.rows, '--bg-color-1': colors[count % colors.length], '--bg-color-2': colors[(count + 1) % colors.length] } as CSSProperties}> <div
{Array.from(Array(params.quantity), (_tile, index) => createTile(index))} id="tiles"
style={
{
"--columns": params.columns,
"--rows": params.rows,
"--bg-color-1": colors[count % colors.length],
"--bg-color-2": colors[(count + 1) % colors.length],
} as CSSProperties
}
>
{Array.from(Array(params.quantity), (_tile, index) =>
createTile(index)
)}
</div> </div>
) )
}, [params, position, active, count]) }, [params, position, active, count])

View file

@ -1,15 +1,18 @@
import classNames from 'classnames' import classNames from "classnames"
import { CSSProperties, useEffect, useMemo, useState } from 'react' import { CSSProperties, useEffect, useMemo, useState } from "react"
function Grid2() { function Grid2() {
function floorClient(number: number) { function floorClient(number: number) {
return Math.floor(number / 50) return Math.floor(number / 50)
} }
const [columns, setColumns] = useState(0) const [columns, setColumns] = useState(0)
const [rows, setRows] = useState(0) const [rows, setRows] = useState(0)
const [params, setParams] = useState({ columns, rows, quantity: columns * rows }) const [params, setParams] = useState({
columns,
rows,
quantity: columns * rows,
})
const [position, setPosition] = useState([0, 0]) const [position, setPosition] = useState([0, 0])
const [active, setActve] = useState(false) const [active, setActve] = useState(false)
const [action, setAction] = useState(false) const [action, setAction] = useState(false)
@ -21,7 +24,7 @@ function Grid2() {
setRows(floorClient(document.body.clientHeight)) setRows(floorClient(document.body.clientHeight))
} }
handleResize() handleResize()
window.addEventListener('resize', handleResize) window.addEventListener("resize", handleResize)
}, []) }, [])
useEffect(() => { useEffect(() => {
@ -32,28 +35,25 @@ function Grid2() {
}, [columns, rows]) }, [columns, rows])
const createTiles = useMemo(() => { const createTiles = useMemo(() => {
const sentences = [ const sentences = [
'Ethem ...', "Ethem ...",
'hat ...', "hat ...",
'lange ...', "lange ...",
'Hörner 🐂', "Hörner 🐂",
'Grüße von Mallorca 🌊 🦦 ☀️' "Grüße von Mallorca 🌊 🦦 ☀️",
] ]
function createTile(index: number) { function createTile(index: number) {
const x = index % params.columns const x = index % params.columns
const y = Math.floor(index / params.columns) const y = Math.floor(index / params.columns)
const xDiff = (x - position[0]) / 20 const xDiff = (x - position[0]) / 20
const yDiff = (y - position[1]) / 20 const yDiff = (y - position[1]) / 20
const pos = (Math.sqrt(xDiff * xDiff + yDiff * yDiff)).toFixed(2) const pos = Math.sqrt(xDiff * xDiff + yDiff * yDiff).toFixed(2)
function doEffect(posX: number, posY: number) { function doEffect(posX: number, posY: number) {
if (action) if (action) return
return
setPosition([posX, posY]) setPosition([posX, posY])
setActve(e => !e) setActve((e) => !e)
setAction(true) setAction(true)
function xDiff(x: number) { function xDiff(x: number) {
@ -65,32 +65,50 @@ function Grid2() {
function pos(x: number, y: number) { function pos(x: number, y: number) {
return Math.sqrt(xDiff(x) * xDiff(x) + yDiff(y) * yDiff(y)) return Math.sqrt(xDiff(x) * xDiff(x) + yDiff(y) * yDiff(y))
} }
const diagonals = [pos(0, 0), pos(params.columns, 0), pos(0, params.rows), pos(params.columns, params.rows)] const diagonals = [
pos(0, 0),
pos(params.columns, 0),
pos(0, params.rows),
pos(params.columns, params.rows),
]
setTimeout(() => { setTimeout(() => {
setAction(false) setAction(false)
if (active) if (active) setCount((e) => e + 1)
setCount(e => e + 1)
}, Math.max(...diagonals) * 1000 + 1000) }, Math.max(...diagonals) * 1000 + 1000)
} }
return ( return (
<div <div
key={index} key={index}
className={classNames('tile', (active ? 'active' : 'inactive'))} className={classNames("tile", active ? "active" : "inactive")}
style={{ '--delay': pos + 's' } as CSSProperties} style={{ "--delay": pos + "s" } as CSSProperties}
onClick={() => doEffect(x, y)} onClick={() => doEffect(x, y)}
></div> ></div>
) )
} }
return ( return (
<div id='tiles' style={{ '--columns': params.columns, '--rows': params.rows } as CSSProperties}> <div
id="tiles"
style={
{
"--columns": params.columns,
"--rows": params.rows,
} as CSSProperties
}
>
<div className="center-div"> <div className="center-div">
<h1 className={classNames('headline', (!active ? 'active' : 'inactive'))}>{sentences[count % sentences.length]}</h1> <h1
className={classNames("headline", !active ? "active" : "inactive")}
>
{sentences[count % sentences.length]}
</h1>
</div>
{Array.from(Array(params.quantity), (_tile, index) =>
createTile(index)
)}
</div> </div>
{Array.from(Array(params.quantity), (_tile, index) => createTile(index))}
</div >
) )
}, [params, position, active, action, count]) }, [params, position, active, action, count])

View file

@ -1,17 +1,22 @@
import { faBurst, faXmark } from '@fortawesome/pro-solid-svg-icons' import { faBurst, faXmark } from "@fortawesome/pro-solid-svg-icons"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { CSSProperties } from 'react' import { CSSProperties } from "react"
import { Hit } from '../interfaces/frontend' import { Hit } from "../interfaces/frontend"
function HitElems({hits}: {hits: Hit[]}) { function HitElems({ hits }: { hits: Hit[] }) {
return (
return <> <>
{hits.map(({hit, x, y}, i) => {hits.map(({ hit, x, y }, i) => (
<div key={i} className='hit-svg' style={{'--x': x, '--y': y} as CSSProperties}> <div
key={i}
className="hit-svg"
style={{ "--x": x, "--y": y } as CSSProperties}
>
<FontAwesomeIcon icon={hit ? faBurst : faXmark} /> <FontAwesomeIcon icon={hit ? faBurst : faXmark} />
</div> </div>
)} ))}
</> </>
)
} }
export default HitElems export default HitElems

View file

@ -1,17 +1,28 @@
import classNames from 'classnames' import classNames from "classnames"
import React, { CSSProperties } from 'react' import React, { CSSProperties } from "react"
function Item({ props: { icon, text, amount, callback } }: { function Item({
props: { icon, text, amount, callback },
}: {
props: { props: {
icon: string, icon: string
text: string, text: string
amount?: number, amount?: number
callback: () => void callback: () => void
} }
}) { }) {
return ( return (
<div className='item' onClick={callback}> <div className="item" onClick={callback}>
<div className={classNames('container', { amount: amount })} style={amount ? { '--amount': JSON.stringify(amount.toString()) } as CSSProperties : {}}> <div
className={classNames("container", { amount: amount })}
style={
amount
? ({
"--amount": JSON.stringify(amount.toString()),
} as CSSProperties)
: {}
}
>
<img src={`/assets/${icon}.png`} alt={`${icon}.png`} /> <img src={`/assets/${icon}.png`} alt={`${icon}.png`} />
</div> </div>
<span>{text}</span> <span>{text}</span>

View file

@ -1,30 +1,50 @@
import classNames from 'classnames' import classNames from "classnames"
import { CSSProperties } from 'react' import { CSSProperties } from "react"
import { fieldIndex } from '../lib/utils/helpers' import { fieldIndex } from "../lib/utils/helpers"
import { Field } from '../interfaces/frontend' import { Field } from "../interfaces/frontend"
function Labeling({count}: {count: number}) { function Labeling({ count }: { count: number }) {
let elems: (Field & { let elems: (Field & {
orientation: string orientation: string
})[] = [] })[] = []
for (let x = 0; x < count; x++) { for (let x = 0; x < count; x++) {
elems.push( elems.push(
// Up // Up
{field: String.fromCharCode(65+x), x: x+2, y: 1, orientation: 'up'}, { field: String.fromCharCode(65 + x), x: x + 2, y: 1, orientation: "up" },
// Left // Left
{field: (x+1).toString(), x: 1, y: x+2, orientation: 'left'}, { field: (x + 1).toString(), x: 1, y: x + 2, orientation: "left" },
// Bottom // Bottom
{field: String.fromCharCode(65+x), x: x+2, y: count+2, orientation: 'bottom'}, {
field: String.fromCharCode(65 + x),
x: x + 2,
y: count + 2,
orientation: "bottom",
},
// Right // Right
{field: (x+1).toString(), x: count+2, y: x+2, orientation: 'right'} {
field: (x + 1).toString(),
x: count + 2,
y: x + 2,
orientation: "right",
}
) )
} }
elems = elems.sort((a, b) => fieldIndex(count, a.x, a.y)-fieldIndex(count, b.x, b.y)) elems = elems.sort(
return <> (a, b) => fieldIndex(count, a.x, a.y) - fieldIndex(count, b.x, b.y)
{elems.map(({field, x, y, orientation}, i) => )
<span key={i} className={classNames('label', orientation, field)} style={{'--x': x, '--y': y} as CSSProperties}>{field}</span> return (
)} <>
{elems.map(({ field, x, y, orientation }, i) => (
<span
key={i}
className={classNames("label", orientation, field)}
style={{ "--x": x, "--y": y } as CSSProperties}
>
{field}
</span>
))}
</> </>
)
} }
export default Labeling export default Labeling

View file

@ -1,5 +1,5 @@
import classNames from 'classnames' import classNames from "classnames"
import { CSSProperties } from 'react' import { CSSProperties } from "react"
function Ships() { function Ships() {
let shipIndexes = [ let shipIndexes = [
@ -8,19 +8,27 @@ function Ships() {
{ size: 3, index: 2 }, { size: 3, index: 2 },
{ size: 3, index: 3 }, { size: 3, index: 3 },
{ size: 4, index: 1 }, { size: 4, index: 1 },
{ size: 4, index: 2 } { size: 4, index: 2 },
] ]
return <>
{shipIndexes.map(({ size, index }, i) => {
const filename = `/assets/ship_blue_${size}x${index ? '_' + index : ''}.gif`
return ( return (
<div key={i} className={classNames('ship', 's' + size)} style={{ '--x': i + 3 } as CSSProperties}> <>
{shipIndexes.map(({ size, index }, i) => {
const filename = `/assets/ship_blue_${size}x${
index ? "_" + index : ""
}.gif`
return (
<div
key={i}
className={classNames("ship", "s" + size)}
style={{ "--x": i + 3 } as CSSProperties}
>
<img src={filename} alt={filename} /> <img src={filename} alt={filename} />
</div> </div>
) )
})} })}
</> </>
)
} }
export default Ships export default Ships

View file

@ -1,5 +1,5 @@
import { useEffect } from 'react' import { useEffect } from "react"
import { io } from 'socket.io-client' import { io } from "socket.io-client"
function SocketIO() { function SocketIO() {
useEffect(() => { useEffect(() => {
@ -7,18 +7,18 @@ function SocketIO() {
}, []) }, [])
const socketInitializer = async () => { const socketInitializer = async () => {
await fetch('/api/ws') await fetch("/api/ws")
const socket = io() const socket = io()
socket.on('test2', (warst) => { socket.on("test2", (warst) => {
console.log('Test2:', warst, socket.id) console.log("Test2:", warst, socket.id)
}) })
socket.on("connect", () => { socket.on("connect", () => {
console.log(socket.connected) // true console.log(socket.connected) // true
setTimeout(() => { setTimeout(() => {
socket.emit('test', "warst") socket.emit("test", "warst")
socket.emit('test', "tsra") socket.emit("test", "tsra")
socket.emit('test', "1234") socket.emit("test", "1234")
// socket.disconnect() // socket.disconnect()
}, 1000) }, 1000)
}) })
@ -32,9 +32,7 @@ function SocketIO() {
}) })
} }
return ( return <div>SocketIO</div>
<div>SocketIO</div>
)
} }
export default SocketIO export default SocketIO

View file

@ -1,20 +1,28 @@
import React from 'react' import React from "react"
import { Target } from '../interfaces/frontend' import { Target } from "../interfaces/frontend"
import GamefieldPointer, { PointerProps } from './GamefieldPointer' import GamefieldPointer, { PointerProps } from "./GamefieldPointer"
function Targets({ props: { composeTargetTiles, target, targetPreview } }: { function Targets({
props: { composeTargetTiles, target, targetPreview },
}: {
props: { props: {
composeTargetTiles: (target: Target) => PointerProps[], composeTargetTiles: (target: Target) => PointerProps[]
target: Target, target: Target
targetPreview: Target targetPreview: Target
} }
}) { }) {
return (<> return (
<>
{[ {[
...composeTargetTiles(target).map((props, i) => <GamefieldPointer key={'t' + i} props={props} />), ...composeTargetTiles(target).map((props, i) => (
...composeTargetTiles(targetPreview).map((props, i) => <GamefieldPointer key={'p' + i} props={props} />) <GamefieldPointer key={"t" + i} props={props} />
)),
...composeTargetTiles(targetPreview).map((props, i) => (
<GamefieldPointer key={"p" + i} props={props} />
)),
]} ]}
</>) </>
)
} }
export default Targets export default Targets

View file

@ -1,7 +1,7 @@
import type { Server as HTTPServer } from 'http' import type { Server as HTTPServer } from "http"
import type { NextApiResponse } from 'next' import type { NextApiResponse } from "next"
import type { Socket as NetSocket } from 'net' import type { Socket as NetSocket } from "net"
import type { Server as IOServer } from 'socket.io' import type { Server as IOServer } from "socket.io"
interface SocketServer extends HTTPServer { interface SocketServer extends HTTPServer {
io?: IOServer | undefined io?: IOServer | undefined

View file

@ -1,27 +1,27 @@
export interface Position { export interface Position {
x: number, x: number
y: number y: number
} }
export interface Target extends Position { export interface Target extends Position {
preview: boolean, preview: boolean
show: boolean show: boolean
} }
export interface MouseCursor extends Position { export interface MouseCursor extends Position {
shouldShow: boolean shouldShow: boolean
} }
export interface TargetList extends Position { export interface TargetList extends Position {
type: string, type: string
edges: string[] edges: string[]
} }
export interface Mode { export interface Mode {
pointerGrid: any[][], pointerGrid: any[][]
type: string type: string
} }
export interface Items { export interface Items {
icon: string, icon: string
text: string, text: string
mode?: number, mode?: number
amount?: number, amount?: number
} }
export interface Field extends Position { export interface Field extends Position {
field: string field: string
@ -31,18 +31,18 @@ export interface Hit extends Position {
} }
interface fireMissile { interface fireMissile {
type: 'fireMissile', type: "fireMissile"
payload: { payload: {
x: number, x: number
y: number, y: number
hit: boolean hit: boolean
} }
} }
interface removeMissile { interface removeMissile {
type: 'removeMissile', type: "removeMissile"
payload: { payload: {
x: number, x: number
y: number, y: number
hit: boolean hit: boolean
} }
} }

View file

@ -1,22 +1,23 @@
import { Player } from "@prisma/client" import { Player } from "@prisma/client"
import bcrypt from "bcrypt" import bcrypt from "bcrypt"
export default async function checkPasswordIsValid<T>(payload: T & { player: Player, password: string }) { export default async function checkPasswordIsValid<T>(
payload: T & { player: Player; password: string }
) {
const { player, password } = payload const { player, password } = payload
// Validate for correct password // Validate for correct password
return bcrypt.compare(password, player.passwordHash) return bcrypt.compare(password, player.passwordHash).then(async (result) => {
.then(async result => {
if (!result) { if (!result) {
return Promise.reject({ return Promise.reject({
message: 'Passwords do not match!', message: "Passwords do not match!",
statusCode: 401, statusCode: 401,
solved: true, solved: true,
}) })
} }
return { return {
...payload, ...payload,
passwordIsValid: true passwordIsValid: true,
} }
}) })
} }

View file

@ -2,7 +2,9 @@ import { Token } from "@prisma/client"
import jwt from "jsonwebtoken" import jwt from "jsonwebtoken"
import jwtVerifyCatch from "../jwtVerifyCatch" import jwtVerifyCatch from "../jwtVerifyCatch"
async function checkTokenIsValid<T>(payload: T & { token: string, tokenType: Token['type'] }) { async function checkTokenIsValid<T>(
payload: T & { token: string; tokenType: Token["type"] }
) {
const { token, tokenType } = payload const { token, tokenType } = payload
// Verify the token and get the payload // Verify the token and get the payload
@ -14,11 +16,11 @@ async function checkTokenIsValid<T>(payload: T & { token: string, tokenType: Tok
return Promise.reject(jwtVerifyCatch(tokenType, err)) return Promise.reject(jwtVerifyCatch(tokenType, err))
} }
// Making sure the token data is not a string (because it should be an object) // Making sure the token data is not a string (because it should be an object)
if (typeof tokenData === 'string') { if (typeof tokenData === "string") {
return Promise.reject({ return Promise.reject({
message: tokenType + '-Token data was a string. Token: ' + token, message: tokenType + "-Token data was a string. Token: " + token,
statusCode: 401, statusCode: 401,
solved: false solved: false,
}) })
} }

View file

@ -3,8 +3,8 @@ import prisma from "../../prisma"
async function createAnonymousDB<T>(payload: T) { async function createAnonymousDB<T>(payload: T) {
const player = await prisma.player.create({ const player = await prisma.player.create({
data: { data: {
anonymous: true anonymous: true,
} },
}) })
// .catch((err: any) => { // .catch((err: any) => {
// if (err.code === 11000) { // if (err.code === 11000) {

View file

@ -1,31 +1,35 @@
import bcrypt from "bcrypt" import bcrypt from "bcrypt"
import prisma from "../../prisma" import prisma from "../../prisma"
async function createPlayerDB<T>(payload: T & { username: string, password: string }) { async function createPlayerDB<T>(
payload: T & { username: string; password: string }
) {
const { username, password } = payload const { username, password } = payload
return await prisma.player.create({ return await prisma.player
.create({
data: { data: {
username, username,
passwordHash: await bcrypt.hash(password, 10), passwordHash: await bcrypt.hash(password, 10),
anonymous: false anonymous: false,
} },
}) })
.then(player => { .then((player) => {
return { ...payload, player } return { ...payload, player }
}).catch((err: any) => { })
.catch((err: any) => {
if (err.code === 11000) { if (err.code === 11000) {
return Promise.reject({ return Promise.reject({
message: `Duplicate key error while creating Player in DB!`, message: `Duplicate key error while creating Player in DB!`,
statusCode: 409, statusCode: 409,
solved: true, solved: true,
type: 'warn' type: "warn",
}) })
} else { } else {
console.log(err) console.log(err)
return Promise.reject({ return Promise.reject({
message: `Unknown error while creating Player in DB.`, message: `Unknown error while creating Player in DB.`,
solved: false solved: false,
}) })
} }
}) })

View file

@ -5,32 +5,38 @@ import prisma from "../../prisma"
const tokenLifetime = { const tokenLifetime = {
REFRESH: 172800, REFRESH: 172800,
ACCESS: 15 ACCESS: 15,
}; }
export default async function createTokenDB<T>(payload: T & { player: Player, newTokenType: Token['type'] }) { export default async function createTokenDB<T>(
payload: T & { player: Player; newTokenType: Token["type"] }
) {
const { player, newTokenType } = payload const { player, newTokenType } = payload
// Sign a new access token // Sign a new access token
const newToken = jwt.sign({ uuid: uuidv4(), user: player.id }, process.env.ACCESS_TOKEN_SECRET as string, { expiresIn: tokenLifetime[newTokenType] }) const newToken = jwt.sign(
{ uuid: uuidv4(), user: player.id },
process.env.ACCESS_TOKEN_SECRET as string,
{ expiresIn: tokenLifetime[newTokenType] }
)
// Save token to DB // Save token to DB
const newTokenDB = await prisma.token.create({ const newTokenDB = await prisma.token.create({
data: { data: {
token: newToken, token: newToken,
type: newTokenType, type: newTokenType,
expires: new Date(Date.now() + tokenLifetime[newTokenType] + '000'), expires: new Date(Date.now() + tokenLifetime[newTokenType] + "000"),
owner: { owner: {
connect: { connect: {
id: player.id id: player.id,
} },
} },
} },
}) })
return { return {
...payload, ...payload,
newToken, newToken,
newTokenDB newTokenDB,
} }
} }

View file

@ -1,24 +1,26 @@
import { Token } from "@prisma/client" import { Token } from "@prisma/client"
import prisma from "../../prisma" import prisma from "../../prisma"
export default async function getPlayerByIdDB<T>(payload: T & { tokenDB: Token }) { export default async function getPlayerByIdDB<T>(
payload: T & { tokenDB: Token }
) {
const { tokenDB } = payload const { tokenDB } = payload
// Find Host in DB if it still exists (just to make sure) // Find Host in DB if it still exists (just to make sure)
const player = await prisma.player.findUnique({ const player = await prisma.player.findUnique({
where: { where: {
id: tokenDB.ownerId id: tokenDB.ownerId,
} },
}) })
if (!player) { if (!player) {
return Promise.reject({ return Promise.reject({
message: 'Player not found in DB!', message: "Player not found in DB!",
statusCode: 401, statusCode: 401,
solved: false solved: false,
}) })
} }
return { return {
...payload, ...payload,
player player,
} }
} }

View file

@ -1,29 +1,32 @@
import prisma from "../../prisma" import prisma from "../../prisma"
export default async function getPlayerByNameDB<T>(payload: T & { username: string }) { export default async function getPlayerByNameDB<T>(
payload: T & { username: string }
) {
const { username } = payload const { username } = payload
// Find Player in DB if it still exists (just to make sure) // Find Player in DB if it still exists (just to make sure)
const player = await Promise.any([ const player = await Promise.any([
prisma.player.findUnique({ prisma.player.findUnique({
where: { where: {
username: username username: username,
} },
}), prisma.player.findUnique({ }),
prisma.player.findUnique({
where: { where: {
email: username email: username,
} },
}) }),
]) ])
if (!player) { if (!player) {
return Promise.reject({ return Promise.reject({
message: 'Player not found in DB!', message: "Player not found in DB!",
statusCode: 401, statusCode: 401,
solved: false solved: false,
}) })
} }
return { return {
...payload, ...payload,
player player,
} }
} }

View file

@ -1,51 +1,53 @@
import { NextApiRequest, NextApiResponse } from "next" import { NextApiRequest, NextApiResponse } from "next"
import prisma from "../../prisma" import prisma from "../../prisma"
async function getTokenDB<T>(payload: T & { async function getTokenDB<T>(
payload: T & {
tokenBody: string tokenBody: string
tokenIsValid: boolean, tokenIsValid: boolean
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<any>, res: NextApiResponse<any>
}) { }
) {
const { tokenBody } = payload const { tokenBody } = payload
// Find refresh token in DB // Find refresh token in DB
const tokenDB = await prisma.token.findUnique({ const tokenDB = await prisma.token.findUnique({
where: { where: {
token: tokenBody token: tokenBody,
} },
}) })
if (!tokenDB) { if (!tokenDB) {
return Promise.reject({ return Promise.reject({
message: 'Access-Token not found in DB!', message: "Access-Token not found in DB!",
statusCode: 401, statusCode: 401,
solved: true, solved: true,
type: 'warn' type: "warn",
}) })
} }
if (tokenDB.used) { if (tokenDB.used) {
return Promise.reject({ return Promise.reject({
message: 'DBToken was already used!', message: "DBToken was already used!",
statusCode: 401, statusCode: 401,
solved: true solved: true,
}) })
} }
await prisma.token.update({ await prisma.token.update({
where: { where: {
token: tokenBody token: tokenBody,
}, },
data: { data: {
used: true used: true,
} },
}) })
// await logging('Old token has been invalidated.', ['debug'], req) // await logging('Old token has been invalidated.', ['debug'], req)
return { return {
...payload, ...payload,
tokenDB tokenDB,
} }
} }

View file

@ -7,7 +7,7 @@ async function getTokenFromBody<T>(payload: T & { req: NextApiRequest }) {
// Checking for cookie presens, because it is necessary // Checking for cookie presens, because it is necessary
if (!token) { if (!token) {
return Promise.reject({ return Promise.reject({
message: 'Unauthorized. No Access-Token.', message: "Unauthorized. No Access-Token.",
statusCode: 401, statusCode: 401,
solved: true, solved: true,
}) })

View file

@ -8,13 +8,13 @@ async function getTokenFromCookie<T>(payload: T & { req: NextApiRequest }) {
// Checking for cookie presens, because it is necessary // Checking for cookie presens, because it is necessary
if (!token) { if (!token) {
return Promise.reject({ return Promise.reject({
message: 'Unauthorized. No cookie.', message: "Unauthorized. No cookie.",
statusCode: 401, statusCode: 401,
solved: true, solved: true,
}) })
} }
return { ...payload, token, tokenType: 'REFRESH' as Token['type'] } return { ...payload, token, tokenType: "REFRESH" as Token["type"] }
} }
export default getTokenFromCookie export default getTokenFromCookie

View file

@ -1,14 +1,16 @@
import { Token } from "@prisma/client" import { Token } from "@prisma/client"
import { Logging } from "../logging" import { Logging } from "../logging"
export default async function loginCheck<T>(payload: T & { loginCheck: boolean, tokenDB: Token, tokenType: 'REFRESH' }) { export default async function loginCheck<T>(
payload: T & { loginCheck: boolean; tokenDB: Token; tokenType: "REFRESH" }
) {
const { loginCheck, tokenDB } = payload const { loginCheck, tokenDB } = payload
// True login check response // True login check response
if (loginCheck) { if (loginCheck) {
return Promise.resolve({ return Promise.resolve({
message: 'loginCheck ' + loginCheck + ' of ' + tokenDB.id, message: "loginCheck " + loginCheck + " of " + tokenDB.id,
body: { loggedIn: true }, body: { loggedIn: true },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
}) })
} }
return payload return payload

View file

@ -8,5 +8,5 @@ export default function sendError<T>(
) { ) {
// If something went wrong, let the client know with status 500 // If something went wrong, let the client know with status 500
res.status(err.statusCode ?? 500).end() res.status(err.statusCode ?? 500).end()
logging(err.message, [err.type ?? (err.solved ? 'debug' : 'error')], req) logging(err.message, [err.type ?? (err.solved ? "debug" : "error")], req)
} }

View file

@ -2,21 +2,19 @@ import { NextApiRequest, NextApiResponse } from "next"
import logging, { Logging } from "../logging" import logging, { Logging } from "../logging"
export interface Result<T> { export interface Result<T> {
message: string, message: string
statusCode?: number, statusCode?: number
body?: T, body?: T
type?: Logging[], type?: Logging[]
} }
export default function sendResponse<T>(payload: { export default function sendResponse<T>(payload: {
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T>, res: NextApiResponse<T>
result: Result<T> result: Result<T>
}) { }) {
const { req, res, result } = payload const { req, res, result } = payload
res.status(result.statusCode ?? 200) res.status(result.statusCode ?? 200)
result.body ? result.body ? res.json(result.body) : res.end()
res.json(result.body) : logging(result.message, result.type ?? ["debug"], req)
res.end()
logging(result.message, result.type ?? ['debug'], req)
} }

View file

@ -1,18 +1,33 @@
import { Token } from "@prisma/client" import { Token } from "@prisma/client"
export default async function jwtVerifyCatch( export default async function jwtVerifyCatch(
tokenType: Token['type'], tokenType: Token["type"],
err: Error err: Error
) { ) {
switch (err.message) { switch (err.message) {
case 'jwt expired': case "jwt expired":
return { message: `JWT (${tokenType}) expired!`, statusCode: 403, solved: true, type: 'warn' } return {
message: `JWT (${tokenType}) expired!`,
statusCode: 403,
solved: true,
type: "warn",
}
case 'invalid signature': case "invalid signature":
return { message: `Invalid JWT (${tokenType}) signature! Token: `, statusCode: 401, solved: true, type: 'error' } return {
message: `Invalid JWT (${tokenType}) signature! Token: `,
statusCode: 401,
solved: true,
type: "error",
}
case 'jwt must be provided': case "jwt must be provided":
return { message: `No JWT (${tokenType}) given.`, statusCode: 401, solved: true, type: 'warn' } return {
message: `No JWT (${tokenType}) given.`,
statusCode: 401,
solved: true,
type: "warn",
}
default: default:
console.log(err) console.log(err)

View file

@ -1,17 +1,17 @@
import fs from 'fs' import fs from "fs"
import colors, { Color } from 'colors' import colors, { Color } from "colors"
import { NextApiRequest } from 'next' import { NextApiRequest } from "next"
import { IncomingMessage } from 'http' import { IncomingMessage } from "http"
colors.enable() colors.enable()
const loggingTemplates: { [key: string]: LoggingType } = { const loggingTemplates: { [key: string]: LoggingType } = {
'system': ['SYSTEM', 'green'], system: ["SYSTEM", "green"],
'info.green': ['INFO', 'green'], "info.green": ["INFO", "green"],
'info.cyan': ['INFO', 'cyan'], "info.cyan": ["INFO", "cyan"],
'debug': ['Debug', 'grey'], debug: ["Debug", "grey"],
'post': ['Post', 'white'], post: ["Post", "white"],
'warn': ['WARN', 'yellow'], warn: ["WARN", "yellow"],
'error': ['ERROR', 'red'] error: ["ERROR", "red"],
} }
type LoggingType = [string, keyof Color] type LoggingType = [string, keyof Color]
@ -20,31 +20,39 @@ export type Logging = keyof typeof loggingTemplates | LoggingType
let started: boolean = false let started: boolean = false
async function logStartup() { async function logStartup() {
await fs.promises.stat('log').catch(async () => { await fs.promises.stat("log").catch(async () => {
await fs.promises.mkdir('log') await fs.promises.mkdir("log")
await logging(`Created 'log' Folder.`, ['info.cyan', 'system']) await logging(`Created 'log' Folder.`, ["info.cyan", "system"])
}) })
started = true started = true
} }
async function logging(message: string, types: Logging[], req?: NextApiRequest | IncomingMessage) { async function logging(
if (!started) message: string,
await logStartup() types: Logging[],
req?: NextApiRequest | IncomingMessage
) {
if (!started) await logStartup()
const messages = { console: message, file: message } const messages = { console: message, file: message }
types.slice().reverse().forEach(async (type) => { types
const [name, color] = typeof type === 'object' ? type : loggingTemplates[type] .slice()
.reverse()
.forEach(async (type) => {
const [name, color] =
typeof type === "object" ? type : loggingTemplates[type]
messages.console = `[${name}] `[color] + messages.console messages.console = `[${name}] `[color] + messages.console
messages.file = `[${name}] ` + messages.file messages.file = `[${name}] ` + messages.file
}) })
messages.console = `[${new Date().toString().slice(0, 33)}] ` + messages.console messages.console =
`[${new Date().toString().slice(0, 33)}] ` + messages.console
messages.file = `[${new Date().toString().slice(0, 33)}] ` + messages.file messages.file = `[${new Date().toString().slice(0, 33)}] ` + messages.file
if (req) { if (req) {
const forwardedFor: any = req.headers['x-forwarded-for'] const forwardedFor: any = req.headers["x-forwarded-for"]
const ip = (forwardedFor || '127.0.0.1, 192.168.178.1').split(',') const ip = (forwardedFor || "127.0.0.1, 192.168.178.1").split(",")
messages.console = ip[0].yellow + ' - ' + messages.console messages.console = ip[0].yellow + " - " + messages.console
messages.file = ip[0] + ' - ' + messages.file messages.file = ip[0] + " - " + messages.file
} }
await fs.promises.appendFile('log/log.txt', messages.file + '\n') await fs.promises.appendFile("log/log.txt", messages.file + "\n")
console.log(messages.console) console.log(messages.console)
} }

View file

@ -6,7 +6,9 @@ import getTokenDB from "../backend/components/getTokenDB"
import getPlayerByIdDB from "../backend/components/getPlayerByIdDB" import getPlayerByIdDB from "../backend/components/getPlayerByIdDB"
import logging from "../backend/logging" import logging from "../backend/logging"
export default async function checkIsLoggedIn(context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) { export default async function checkIsLoggedIn(
context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>
) {
const req: any = context.req const req: any = context.req
const res: any = context.res const res: any = context.res
@ -17,7 +19,11 @@ export default async function checkIsLoggedIn(context: GetServerSidePropsContext
.then(({ player }) => !!player) .then(({ player }) => !!player)
.catch(() => false) .catch(() => false)
logging('loginCheck ' + (isLoggedIn ? true : '-> loggedIn: ' + false), ['debug', 'info.cyan'], req) logging(
"loginCheck " + (isLoggedIn ? true : "-> loggedIn: " + false),
["debug", "info.cyan"],
req
)
return isLoggedIn return isLoggedIn
} }

View file

@ -1,7 +1,7 @@
export default function getAccessToken(): Promise<string> { export default function getAccessToken(): Promise<string> {
return fetch('/api/auth', { return fetch("/api/auth", {
method: 'GET', method: "GET",
}) })
.then(res => res.json()) .then((res) => res.json())
.then(res => res.newAccessToken) .then((res) => res.newAccessToken)
} }

View file

@ -1,31 +1,58 @@
import { useCallback, useEffect, useMemo, useReducer, useState } from 'react' import { useCallback, useEffect, useMemo, useReducer, useState } from "react"
import { hitReducer, initlialLastLeftTile, initlialTarget, initlialTargetPreview, initlialMouseCursor } from '../utils/helpers' import {
import { Hit, Mode, MouseCursor, Target, Position } from '../../interfaces/frontend' hitReducer,
import { PointerProps } from '../../components/GamefieldPointer' initlialLastLeftTile,
initlialTarget,
initlialTargetPreview,
initlialMouseCursor,
} from "../utils/helpers"
import {
Hit,
Mode,
MouseCursor,
Target,
Position,
} from "../../interfaces/frontend"
import { PointerProps } from "../../components/GamefieldPointer"
const modes: Mode[] = [ const modes: Mode[] = [
{ pointerGrid: Array.from(Array(3), () => Array.from(Array(3))), type: 'radar' }, {
{ pointerGrid: Array.from(Array(3), () => Array.from(Array(1))), type: 'htorpedo' }, pointerGrid: Array.from(Array(3), () => Array.from(Array(3))),
{ pointerGrid: Array.from(Array(1), () => Array.from(Array(3))), type: 'vtorpedo' }, type: "radar",
{ pointerGrid: [[{ x: 0, y: 0 }]], type: 'missile' } },
{
pointerGrid: Array.from(Array(3), () => Array.from(Array(1))),
type: "htorpedo",
},
{
pointerGrid: Array.from(Array(1), () => Array.from(Array(3))),
type: "vtorpedo",
},
{ pointerGrid: [[{ x: 0, y: 0 }]], type: "missile" },
] ]
function useGameEvent(count: number) { function useGameEvent(count: number) {
const [lastLeftTile, setLastLeftTile] = useState<Position>(initlialLastLeftTile) const [lastLeftTile, setLastLeftTile] =
useState<Position>(initlialLastLeftTile)
const [target, setTarget] = useState<Target>(initlialTarget) const [target, setTarget] = useState<Target>(initlialTarget)
const [eventReady, setEventReady] = useState(false) const [eventReady, setEventReady] = useState(false)
const [appearOK, setAppearOK] = useState(false) const [appearOK, setAppearOK] = useState(false)
const [targetPreview, setTargetPreview] = useState<Target>(initlialTargetPreview) const [targetPreview, setTargetPreview] = useState<Target>(
const [mouseCursor, setMouseCursor] = useState<MouseCursor>(initlialMouseCursor) initlialTargetPreview
)
const [mouseCursor, setMouseCursor] =
useState<MouseCursor>(initlialMouseCursor)
const [hits, DispatchHits] = useReducer(hitReducer, [] as Hit[]) const [hits, DispatchHits] = useReducer(hitReducer, [] as Hit[])
const [mode, setMode] = useState(0) const [mode, setMode] = useState(0)
const targetList = useCallback((target: Position) => { const targetList = useCallback(
(target: Position) => {
const { pointerGrid, type } = modes[mode] const { pointerGrid, type } = modes[mode]
const xLength = pointerGrid.length const xLength = pointerGrid.length
const yLength = pointerGrid[0].length const yLength = pointerGrid[0].length
const { x: targetX, y: targetY } = target const { x: targetX, y: targetY } = target
return pointerGrid.map((arr, i) => { return pointerGrid
.map((arr, i) => {
return arr.map((_, i2) => { return arr.map((_, i2) => {
const relativeX = -Math.floor(xLength / 2) + i const relativeX = -Math.floor(xLength / 2) + i
const relativeY = -Math.floor(yLength / 2) + i2 const relativeY = -Math.floor(yLength / 2) + i2
@ -36,45 +63,62 @@ function useGameEvent(count: number) {
y, y,
type, type,
edges: [ edges: [
i === 0 ? 'left' : '', i === 0 ? "left" : "",
i === xLength - 1 ? 'right' : '', i === xLength - 1 ? "right" : "",
i2 === 0 ? 'top' : '', i2 === 0 ? "top" : "",
i2 === yLength - 1 ? 'bottom' : '', i2 === yLength - 1 ? "bottom" : "",
] ],
} }
}) })
}) })
.reduce((prev, curr) => [...prev, ...curr], []) .reduce((prev, curr) => [...prev, ...curr], [])
}, [mode]) },
[mode]
)
const isHit = useCallback((x: number, y: number) => { const isHit = useCallback(
return hits.filter(h => h.x === x && h.y === y) (x: number, y: number) => {
}, [hits]) return hits.filter((h) => h.x === x && h.y === y)
},
[hits]
)
const settingTarget = useCallback((isGameTile: boolean, x: number, y: number) => { const settingTarget = useCallback(
if (!isGameTile || isHit(x, y).length) (isGameTile: boolean, x: number, y: number) => {
return if (!isGameTile || isHit(x, y).length) return
setMouseCursor(e => ({ ...e, shouldShow: false })) setMouseCursor((e) => ({ ...e, shouldShow: false }))
setTarget(t => { setTarget((t) => {
if (t.x === x && t.y === y && t.show) { if (t.x === x && t.y === y && t.show) {
DispatchHits({ type: 'fireMissile', payload: { hit: (x + y) % 2 !== 0, x, y } }) DispatchHits({
type: "fireMissile",
payload: { hit: (x + y) % 2 !== 0, x, y },
})
return { preview: false, show: false, x, y } return { preview: false, show: false, x, y }
} else { } else {
const target = { preview: false, show: true, x, y } const target = { preview: false, show: true, x, y }
const hasAnyBorder = targetList(target).filter(({ x, y }) => isBorder(x, y, count)).length const hasAnyBorder = targetList(target).filter(({ x, y }) =>
if (hasAnyBorder) isBorder(x, y, count)
return t ).length
if (hasAnyBorder) return t
return target return target
} }
}) })
}, [count, isHit, targetList]) },
[count, isHit, targetList]
)
const isSet = useCallback((x: number, y: number) => { const isSet = useCallback(
return !!targetList(target).filter(field => x === field.x && y === field.y).length && target.show (x: number, y: number) => {
}, [target, targetList]) return (
!!targetList(target).filter((field) => x === field.x && y === field.y)
.length && target.show
)
},
[target, targetList]
)
const composeTargetTiles = useCallback((target: Target): PointerProps[] => { const composeTargetTiles = useCallback(
(target: Target): PointerProps[] => {
const { preview, show } = target const { preview, show } = target
const result = targetList(target).map(({ x, y, type, edges }) => { const result = targetList(target).map(({ x, y, type, edges }) => {
return { return {
@ -84,11 +128,13 @@ function useGameEvent(count: number) {
show, show,
type, type,
edges, edges,
imply: !!isHit(x, y).length || (!!isSet(x, y) && preview) imply: !!isHit(x, y).length || (!!isSet(x, y) && preview),
} }
}) })
return result return result
}, [isHit, isSet, targetList]) },
[isHit, isSet, targetList]
)
// handle visibility and position change of targetPreview // handle visibility and position change of targetPreview
useEffect(() => { useEffect(() => {
@ -97,21 +143,37 @@ function useGameEvent(count: number) {
const hasLeft = x === lastLeftTile.x && y === lastLeftTile.y const hasLeft = x === lastLeftTile.x && y === lastLeftTile.y
const isSet = x === target.x && y === target.y && target.show const isSet = x === target.x && y === target.y && target.show
if (show && !appearOK) if (show && !appearOK) setTargetPreview((e) => ({ ...e, show: false }))
setTargetPreview(e => ({ ...e, show: false })) if (
if (!show && mouseCursor.shouldShow && eventReady && appearOK && !isHit(x, y).length && !isSet && !hasLeft) !show &&
setTargetPreview(e => ({ ...e, show: true })) mouseCursor.shouldShow &&
}, [targetPreview, mouseCursor.shouldShow, isHit, eventReady, appearOK, lastLeftTile, target]) eventReady &&
appearOK &&
!isHit(x, y).length &&
!isSet &&
!hasLeft
)
setTargetPreview((e) => ({ ...e, show: true }))
}, [
targetPreview,
mouseCursor.shouldShow,
isHit,
eventReady,
appearOK,
lastLeftTile,
target,
])
// enable targetPreview event again after 200 ms. // enable targetPreview event again after 200 ms.
useEffect(() => { useEffect(() => {
setEventReady(false) setEventReady(false)
const previewTarget = { x: mouseCursor.x, y: mouseCursor.y } const previewTarget = { x: mouseCursor.x, y: mouseCursor.y }
const hasAnyBorder = targetList(previewTarget).filter(({ x, y }) => isBorder(x, y, count)).length const hasAnyBorder = targetList(previewTarget).filter(({ x, y }) =>
if (targetPreview.show || !appearOK || hasAnyBorder) isBorder(x, y, count)
return ).length
if (targetPreview.show || !appearOK || hasAnyBorder) return
const autoTimeout = setTimeout(() => { const autoTimeout = setTimeout(() => {
setTargetPreview(e => ({ ...e, ...previewTarget })) setTargetPreview((e) => ({ ...e, ...previewTarget }))
setEventReady(true) setEventReady(true)
setAppearOK(true) setAppearOK(true)
}, 300) }, 300)
@ -120,14 +182,24 @@ function useGameEvent(count: number) {
return () => { return () => {
clearTimeout(autoTimeout) clearTimeout(autoTimeout)
} }
}, [appearOK, count, mouseCursor.x, mouseCursor.y, targetList, targetPreview.show]) }, [
appearOK,
count,
mouseCursor.x,
mouseCursor.y,
targetList,
targetPreview.show,
])
// approve targetPreview new position after 200 mil. sec. // approve targetPreview new position after 200 mil. sec.
useEffect(() => { useEffect(() => {
// early return to start cooldown only when about to show up // early return to start cooldown only when about to show up
const autoTimeout = setTimeout(() => { const autoTimeout = setTimeout(
() => {
setAppearOK(!targetPreview.show) setAppearOK(!targetPreview.show)
}, targetPreview.show ? 500 : 300) },
targetPreview.show ? 500 : 300
)
// or abort if movement is repeated early // or abort if movement is repeated early
return () => { return () => {
@ -139,7 +211,7 @@ function useGameEvent(count: number) {
tilesProps: { count, settingTarget, setMouseCursor, setLastLeftTile }, tilesProps: { count, settingTarget, setMouseCursor, setLastLeftTile },
pointersProps: { composeTargetTiles, target, targetPreview }, pointersProps: { composeTargetTiles, target, targetPreview },
targetsProps: { setMode, setTarget }, targetsProps: { setMode, setTarget },
hits hits,
} }
} }

View file

@ -1,15 +1,15 @@
// lib/prisma.ts // lib/prisma.ts
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from "@prisma/client"
let prisma: PrismaClient; let prisma: PrismaClient
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV === "production") {
prisma = new PrismaClient(); prisma = new PrismaClient()
} else { } else {
if (!global.prismaClient) { if (!global.prismaClient) {
global.prismaClient = new PrismaClient(); global.prismaClient = new PrismaClient()
} }
prisma = global.prismaClient; prisma = global.prismaClient
} }
export default prisma; export default prisma

View file

@ -1,34 +1,25 @@
import { Hit, HitDispatch } from "../../interfaces/frontend" import { Hit, HitDispatch } from "../../interfaces/frontend"
export function borderCN(count: number, x: number, y: number) { export function borderCN(count: number, x: number, y: number) {
if (x === 0) if (x === 0) return "left"
return 'left' if (y === 0) return "top"
if (y === 0) if (x === count + 1) return "right"
return 'top' if (y === count + 1) return "bottom"
if (x === count + 1) return ""
return 'right'
if (y === count + 1)
return 'bottom'
return ''
} }
export function cornerCN(count: number, x: number, y: number) { export function cornerCN(count: number, x: number, y: number) {
if (x === 0 && y === 0) if (x === 0 && y === 0) return "left-top-corner"
return 'left-top-corner' if (x === count + 1 && y === 0) return "right-top-corner"
if (x === count + 1 && y === 0) if (x === 0 && y === count + 1) return "left-bottom-corner"
return 'right-top-corner' if (x === count + 1 && y === count + 1) return "right-bottom-corner"
if (x === 0 && y === count + 1) return ""
return 'left-bottom-corner'
if (x === count + 1 && y === count + 1)
return 'right-bottom-corner'
return ''
} }
export function fieldIndex(count: number, x: number, y: number) { export function fieldIndex(count: number, x: number, y: number) {
return y * (count + 2) + x return y * (count + 2) + x
} }
export function hitReducer(formObject: Hit[], action: HitDispatch) { export function hitReducer(formObject: Hit[], action: HitDispatch) {
switch (action.type) { switch (action.type) {
case "fireMissile": {
case 'fireMissile': {
const result = [...formObject, action.payload] const result = [...formObject, action.payload]
return result return result
} }
@ -39,22 +30,22 @@ export function hitReducer(formObject: Hit[], action: HitDispatch) {
} }
export const initlialLastLeftTile = { export const initlialLastLeftTile = {
x: 0, x: 0,
y: 0 y: 0,
} }
export const initlialTarget = { export const initlialTarget = {
preview: false, preview: false,
show: false, show: false,
x: 2, x: 2,
y: 2 y: 2,
} }
export const initlialTargetPreview = { export const initlialTargetPreview = {
preview: true, preview: true,
show: false, show: false,
x: 2, x: 2,
y: 2 y: 2,
} }
export const initlialMouseCursor = { export const initlialMouseCursor = {
shouldShow: false, shouldShow: false,
x: 0, x: 0,
y: 0 y: 0,
} }

View file

@ -1,9 +1,9 @@
import '../styles/App.scss' import "../styles/App.scss"
import '../styles/grid.scss' import "../styles/grid.scss"
import '../styles/grid2.scss' import "../styles/grid2.scss"
import '../styles/homepage.scss' import "../styles/homepage.scss"
import '../styles/globals.css' import "../styles/globals.css"
import type { AppProps } from 'next/app' import type { AppProps } from "next/app"
export default function App({ Component, pageProps }: AppProps) { export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} /> return <Component {...pageProps} />

View file

@ -1,4 +1,4 @@
import { Html, Head, Main, NextScript } from 'next/document' import { Html, Head, Main, NextScript } from "next/document"
export default function Document() { export default function Document() {
return ( return (

View file

@ -17,21 +17,25 @@ export default async function auth(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse<Data> res: NextApiResponse<Data>
) { ) {
return getTokenFromCookie({ req, res, newTokenType: 'ACCESS' as Token['type'] }) return getTokenFromCookie({
req,
res,
newTokenType: "ACCESS" as Token["type"],
})
.then(checkTokenIsValid) .then(checkTokenIsValid)
.then(getTokenDB) .then(getTokenDB)
.then(getPlayerByIdDB) .then(getPlayerByIdDB)
.then(createTokenDB) .then(createTokenDB)
.then(authResponse<Data>) .then(authResponse<Data>)
.then(sendResponse<Data>) .then(sendResponse<Data>)
.catch(err => sendError(req, res, err)) .catch((err) => sendError(req, res, err))
} }
async function authResponse<T>(payload: { async function authResponse<T>(payload: {
newToken: string, newToken: string
newTokenDB: Token, newTokenDB: Token
tokenDB: Token, tokenDB: Token
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }) {
const { newToken, newTokenDB, tokenDB, req, res } = payload const { newToken, newTokenDB, tokenDB, req, res } = payload
@ -41,9 +45,13 @@ async function authResponse<T>(payload: {
req, req,
res, res,
result: { result: {
message: 'Access-Token generated: ' + newTokenDB.id + ' with Refreshtoken-Token: ' + tokenDB.id, message:
"Access-Token generated: " +
newTokenDB.id +
" with Refreshtoken-Token: " +
tokenDB.id,
body: { token: newToken }, body: { token: newToken },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
} },
} }
} }

View file

@ -16,20 +16,20 @@ export default async function data(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse<Data> res: NextApiResponse<Data>
) { ) {
return getTokenFromBody({ req, res, tokenType: 'ACCESS' as Token['type'] }) return getTokenFromBody({ req, res, tokenType: "ACCESS" as Token["type"] })
.then(checkTokenIsValid) .then(checkTokenIsValid)
.then(getTokenDB) .then(getTokenDB)
.then(getPlayerByIdDB) .then(getPlayerByIdDB)
.then(dataResponse<Data>) .then(dataResponse<Data>)
.then(sendResponse<Data>) .then(sendResponse<Data>)
.catch(err => sendError(req, res, err)) .catch((err) => sendError(req, res, err))
} }
async function dataResponse<T>(payload: { async function dataResponse<T>(payload: {
player: Player, player: Player
tokenDB: Token, tokenDB: Token
// games: Game[], // games: Game[],
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }) {
const { player, tokenDB, req, res } = payload const { player, tokenDB, req, res } = payload
@ -40,9 +40,13 @@ async function dataResponse<T>(payload: {
req, req,
res, res,
result: { result: {
message: 'Requested data of user: ' + player.id + ' with Access-Token: ' + tokenDB.id, message:
"Requested data of user: " +
player.id +
" with Access-Token: " +
tokenDB.id,
body: { games }, body: { games },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
} },
} }
} }

View file

@ -18,53 +18,61 @@ export default async function login(
res: NextApiResponse<any> res: NextApiResponse<any>
) { ) {
const { username, password } = req.body const { username, password } = req.body
return preCheck({ req, res, username, password, newTokenType: 'REFRESH' as Token['type'] }) return preCheck({
req,
res,
username,
password,
newTokenType: "REFRESH" as Token["type"],
})
.then(getPlayerByNameDB) .then(getPlayerByNameDB)
.then(checkPasswordIsValid) .then(checkPasswordIsValid)
.then(createTokenDB) .then(createTokenDB)
.then(loginResponse<Data>) .then(loginResponse<Data>)
.then(sendResponse<Data>) .then(sendResponse<Data>)
.catch(err => sendError(req, res, err)) .catch((err) => sendError(req, res, err))
} }
async function preCheck<T>(payload: T & { async function preCheck<T>(
req: NextApiRequest, payload: T & {
req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }
) {
const { req } = payload const { req } = payload
const oldRefreshToken = req.cookies.token const oldRefreshToken = req.cookies.token
// Check for old cookie, if unused invalidate it // Check for old cookie, if unused invalidate it
const oldDBToken = await prisma.token.findUnique({ const oldDBToken = await prisma.token.findUnique({
where: { where: {
token: oldRefreshToken token: oldRefreshToken,
} },
}) })
if (oldDBToken?.used) { if (oldDBToken?.used) {
await prisma.token.update({ await prisma.token.update({
where: { where: {
token: oldRefreshToken token: oldRefreshToken,
}, },
data: { data: {
used: true used: true,
} },
}) })
await logging('Old token has been invalidated.', ['debug'], req) await logging("Old token has been invalidated.", ["debug"], req)
} }
return { ...payload, noCookiePresent: true } return { ...payload, noCookiePresent: true }
} }
async function loginResponse<T>(payload: { async function loginResponse<T>(payload: {
player: Player, player: Player
passwordIsValid: boolean, passwordIsValid: boolean
refreshToken: string, refreshToken: string
refreshTokenDB: Token, refreshTokenDB: Token
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }) {
const { player, refreshToken, refreshTokenDB, req, res } = payload const { player, refreshToken, refreshTokenDB, req, res } = payload
// Set login cookie // Set login cookie
setCookie('token', refreshToken, { setCookie("token", refreshToken, {
req, req,
res, res,
maxAge: 172800000, maxAge: 172800000,
@ -78,9 +86,13 @@ async function loginResponse<T>(payload: {
req, req,
res, res,
result: { result: {
message: 'User ' + player.id + ' logged in and generated Refresh-Token: ' + refreshTokenDB.id, message:
"User " +
player.id +
" logged in and generated Refresh-Token: " +
refreshTokenDB.id,
body: { loggedIn: true }, body: { loggedIn: true },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
} },
} }
} }

View file

@ -21,27 +21,27 @@ export default async function logout(
.then(getTokenDB) .then(getTokenDB)
.then(logoutResponse<Data>) .then(logoutResponse<Data>)
.then(sendResponse<Data>) .then(sendResponse<Data>)
.catch(err => sendError(req, res, err)) .catch((err) => sendError(req, res, err))
} }
async function logoutResponse<T>(payload: { async function logoutResponse<T>(payload: {
tokenDB: Token, tokenDB: Token
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }) {
const { tokenDB, req, res } = payload const { tokenDB, req, res } = payload
// Set login cookie // Set login cookie
deleteCookie('token', { req, res }) deleteCookie("token", { req, res })
// Successfull response // Successfull response
return { return {
req, req,
res, res,
result: { result: {
message: 'User of Token ' + tokenDB.id + ' logged out.', message: "User of Token " + tokenDB.id + " logged out.",
body: { loggedOut: true }, body: { loggedOut: true },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
} },
} }
} }

View file

@ -17,12 +17,12 @@ export default async function register(
return createPlayerDB({ req, res, username, password }) return createPlayerDB({ req, res, username, password })
.then(registerResponse<Data>) .then(registerResponse<Data>)
.then(sendResponse<Data>) .then(sendResponse<Data>)
.catch(err => sendError(req, res, err)) .catch((err) => sendError(req, res, err))
} }
async function registerResponse<T>(payload: { async function registerResponse<T>(payload: {
player: Player, player: Player
req: NextApiRequest, req: NextApiRequest
res: NextApiResponse<T> res: NextApiResponse<T>
}) { }) {
const { player, req, res } = payload const { player, req, res } = payload
@ -32,10 +32,10 @@ async function registerResponse<T>(payload: {
req, req,
res, res,
result: { result: {
message: 'Player created : ' + player.id, message: "Player created : " + player.id,
statusCode: 201, statusCode: 201,
body: { registered: true }, body: { registered: true },
type: ['debug', 'info.cyan'] as Logging[] type: ["debug", "info.cyan"] as Logging[],
} },
} }
} }

View file

@ -1,18 +1,18 @@
import type { NextApiRequest } from 'next' import type { NextApiRequest } from "next"
import { Server } from 'socket.io' import { Server } from "socket.io"
import { NextApiResponseWithSocket } from '../../interfaces/NextApiSocket' import { NextApiResponseWithSocket } from "../../interfaces/NextApiSocket"
const SocketHandler = (req: NextApiRequest, res: NextApiResponseWithSocket) => { const SocketHandler = (req: NextApiRequest, res: NextApiResponseWithSocket) => {
if (res.socket.server.io) { if (res.socket.server.io) {
console.log('Socket is already running ' + req.url) console.log("Socket is already running " + req.url)
} else { } else {
console.log('Socket is initializing ' + req.url) console.log("Socket is initializing " + req.url)
const io = new Server(res.socket.server) const io = new Server(res.socket.server)
res.socket.server.io = io res.socket.server.io = io
io.on('connection', socket => { io.on("connection", (socket) => {
socket.on('input-change', msg => { socket.on("input-change", (msg) => {
socket.broadcast.emit('update-input', msg) socket.broadcast.emit("update-input", msg)
}) })
// console.log(socket.id) // console.log(socket.id)
// console.log(socket) // console.log(socket)
@ -23,7 +23,7 @@ const SocketHandler = (req: NextApiRequest, res: NextApiResponseWithSocket) => {
// ... // ...
}) })
socket.emit('test2', 'lol') socket.emit("test2", "lol")
}) })
} }
res.end() res.end()

View file

@ -1,5 +1,5 @@
import Head from 'next/head' import Head from "next/head"
import Gamefield from '../../components/Gamefield' import Gamefield from "../../components/Gamefield"
export default function Home() { export default function Home() {
return ( return (

View file

@ -1,5 +1,5 @@
import Head from 'next/head' import Head from "next/head"
import Grid from '../../components/Grid' import Grid from "../../components/Grid"
export default function Home() { export default function Home() {
return ( return (

View file

@ -1,5 +1,5 @@
import Head from 'next/head' import Head from "next/head"
import Grid2 from '../../components/Grid2' import Grid2 from "../../components/Grid2"
export default function Home() { export default function Home() {
return ( return (

View file

@ -1,48 +1,52 @@
import { faPlus, faUserPlus } from '@fortawesome/pro-solid-svg-icons' import { faPlus, faUserPlus } from "@fortawesome/pro-solid-svg-icons"
import { faEye, faLeftLong } from '@fortawesome/pro-regular-svg-icons' import { faEye, faLeftLong } from "@fortawesome/pro-regular-svg-icons"
import { faCirclePlay } from '@fortawesome/pro-thin-svg-icons' import { faCirclePlay } from "@fortawesome/pro-thin-svg-icons"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { useState } from 'react' import { useState } from "react"
export default function Home() { export default function Home() {
const [heWantsToPlay, setHeWantsToPlay] = useState(false) const [heWantsToPlay, setHeWantsToPlay] = useState(false)
return ( return (
<div id='box'> <div id="box">
<button id='navExpand'> <button id="navExpand">
<img id='burgerMenu' src='/assets/burger-menu.png' alt='Burger Menu' /> <img id="burgerMenu" src="/assets/burger-menu.png" alt="Burger Menu" />
</button> </button>
<div id='shield'> <div id="shield">
<div id='width'> <div id="width">
<h1>Leaky</h1> <h1>Leaky</h1>
<h1>Ships</h1> <h1>Ships</h1>
</div> </div>
</div> </div>
{!heWantsToPlay ? {!heWantsToPlay ? (
<> <>
<div id='videoWrapper' > <div id="videoWrapper">
<FontAwesomeIcon icon={faCirclePlay} /> <FontAwesomeIcon icon={faCirclePlay} />
</div> </div>
<button id='startButton' onClick={() => setHeWantsToPlay(true)}>START</button> <button id="startButton" onClick={() => setHeWantsToPlay(true)}>
</> : START
<div id='startBox'> </button>
<button id='back' onClick={() => setHeWantsToPlay(false)}> </>
) : (
<div id="startBox">
<button id="back" onClick={() => setHeWantsToPlay(false)}>
<FontAwesomeIcon icon={faLeftLong} /> <FontAwesomeIcon icon={faLeftLong} />
</button> </button>
<div id='sameWidth'> <div id="sameWidth">
<button className='optionButton'> <button className="optionButton">
<span>Raum erstellen</span> <span>Raum erstellen</span>
<FontAwesomeIcon icon={faPlus} /> <FontAwesomeIcon icon={faPlus} />
</button> </button>
<button className='optionButton'> <button className="optionButton">
<span>Raum beitreten</span> <span>Raum beitreten</span>
<FontAwesomeIcon icon={faUserPlus} /> <FontAwesomeIcon icon={faUserPlus} />
</button> </button>
<button className='optionButton'> <button className="optionButton">
<span>Zuschauen</span> <span>Zuschauen</span>
<FontAwesomeIcon icon={faEye} /> <FontAwesomeIcon icon={faEye} />
</button> </button>
</div> </div>
</div>} </div>
</div > )}
</div>
) )
} }

View file

@ -1,30 +1,30 @@
import { ChangeEventHandler, useEffect, useState } from 'react' import { ChangeEventHandler, useEffect, useState } from "react"
import { io } from 'socket.io-client' import { io } from "socket.io-client"
let socket: ReturnType<typeof io> let socket: ReturnType<typeof io>
const Home = () => { const Home = () => {
const [input, setInput] = useState('') const [input, setInput] = useState("")
useEffect(() => { useEffect(() => {
socketInitializer() socketInitializer()
}, []) }, [])
const socketInitializer = async () => { const socketInitializer = async () => {
await fetch('/api/ws') await fetch("/api/ws")
socket = io() socket = io()
socket.on('connect', () => { socket.on("connect", () => {
console.log('connected') console.log("connected")
}) })
socket.on('update-input', msg => { socket.on("update-input", (msg) => {
setInput(msg) setInput(msg)
}) })
} }
const onChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => { const onChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setInput(e.target.value) setInput(e.target.value)
socket.emit('input-change', e.target.value) socket.emit("input-change", e.target.value)
} }
return ( return (

View file

@ -1,4 +1,4 @@
import SocketIO from '../../components/SocketIO' import SocketIO from "../../components/SocketIO"
export default function Home() { export default function Home() {
return ( return (

View file

@ -1,5 +1,5 @@
import Head from 'next/head' import Head from "next/head"
import Link from 'next/link' import Link from "next/link"
export default function Home() { export default function Home() {
return ( return (
@ -11,12 +11,36 @@ export default function Home() {
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<main> <main>
<p><Link href='/dev/gamefield' target='_blank'>Gamefield</Link></p> <p>
<p><Link href='/dev' target='_blank'>Homepage</Link></p> <Link href="/dev/gamefield" target="_blank">
<p><Link href='/dev/grid' target='_blank'>Grid Effect</Link></p> Gamefield
<p><Link href='/dev/grid2' target='_blank'>Grid Effect with Content</Link></p> </Link>
<p><Link href='/dev/socket' target='_blank'>Socket</Link></p> </p>
<p><Link href='/dev/socketio' target='_blank'>SocketIO</Link></p> <p>
<Link href="/dev" target="_blank">
Homepage
</Link>
</p>
<p>
<Link href="/dev/grid" target="_blank">
Grid Effect
</Link>
</p>
<p>
<Link href="/dev/grid2" target="_blank">
Grid Effect with Content
</Link>
</p>
<p>
<Link href="/dev/socket" target="_blank">
Socket
</Link>
</p>
<p>
<Link href="/dev/socketio" target="_blank">
SocketIO
</Link>
</p>
</main> </main>
</> </>
) )

View file

@ -1,6 +1,6 @@
@use './mixins/display' as *; @use "./mixins/display" as *;
@use './mixins/effects' as *; @use "./mixins/effects" as *;
@import './mixins/variables'; @import "./mixins/variables";
html, html,
body, body,
@ -10,8 +10,8 @@ body,
body { body {
margin: 0; margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif; sans-serif;
} }
@ -69,15 +69,15 @@ body {
display: grid; display: grid;
align-items: center; align-items: center;
justify-items: center; justify-items: center;
grid-template-rows: .75fr repeat(12, 1fr) .75fr; grid-template-rows: 0.75fr repeat(12, 1fr) 0.75fr;
grid-template-columns: .75fr repeat(12, 1fr) .75fr; grid-template-columns: 0.75fr repeat(12, 1fr) 0.75fr;
>.label { > .label {
grid-column: var(--x); grid-column: var(--x);
grid-row: var(--y); grid-row: var(--y);
} }
>.border-tile { > .border-tile {
box-sizing: border-box; box-sizing: border-box;
border: 1px solid blue; border: 1px solid blue;
height: 100%; height: 100%;
@ -96,7 +96,7 @@ body {
box-sizing: border-box; box-sizing: border-box;
} }
>span { > span {
vertical-align: center; vertical-align: center;
user-select: none; user-select: none;
} }
@ -172,7 +172,7 @@ body {
&.preview { &.preview {
opacity: 0; opacity: 0;
@include transition(.5s); @include transition(0.5s);
} }
&.radar { &.radar {
@ -184,7 +184,7 @@ body {
&:not(.left):not(.right):not(.top):not(.bottom) { &:not(.left):not(.right):not(.top):not(.bottom) {
// border: 5px solid var(--color); // border: 5px solid var(--color);
grid-area: var(--y1) /var(--x1) /var(--y2) /var(--x2); grid-area: var(--y1) / var(--x1) / var(--y2) / var(--x2);
svg { svg {
opacity: 1; opacity: 1;
@ -207,7 +207,7 @@ body {
opacity: 1; opacity: 1;
} }
&.imply>svg { &.imply > svg {
opacity: 0; opacity: 0;
} }
@ -300,7 +300,7 @@ body {
.item { .item {
@include flex-col; @include flex-col;
align-items: center; align-items: center;
gap: .5rem; gap: 0.5rem;
width: 128px; width: 128px;
.container { .container {
@ -332,7 +332,7 @@ body {
span { span {
color: black; color: black;
font-size: .75em; font-size: 0.75em;
font-weight: bold; font-weight: bold;
} }
} }

View file

@ -1,4 +1,4 @@
@use './mixins/effects' as *; @use "./mixins/effects" as *;
#tiles { #tiles {
height: 100vh; height: 100vh;
@ -11,7 +11,7 @@
background-color: var(--bg-color-1); background-color: var(--bg-color-1);
&.active { &.active {
animation: bright .3s forwards; animation: bright 0.3s forwards;
animation-delay: var(--delay); animation-delay: var(--delay);
} }
} }
@ -23,14 +23,12 @@
} }
50% { 50% {
background-color: var(--bg-color-2); background-color: var(--bg-color-2);
filter: brightness(130%); filter: brightness(130%);
outline: 1px solid white; outline: 1px solid white;
} }
100% { 100% {
background-color: var(--bg-color-2); background-color: var(--bg-color-2);
} }
} }

View file

@ -1,4 +1,4 @@
@use './mixins/effects' as *; @use "./mixins/effects" as *;
$g1: rgb(98, 0, 234); $g1: rgb(98, 0, 234);
$g2: rgb(236, 64, 122); $g2: rgb(236, 64, 122);
@ -17,20 +17,20 @@ $g2: rgb(236, 64, 122);
&::before { &::before {
position: absolute; position: absolute;
content: ''; content: "";
background-color: rgb(20, 20, 20); background-color: rgb(20, 20, 20);
inset: 1px; inset: 1px;
} }
&.active { &.active {
opacity: 1; opacity: 1;
animation: hide .2s forwards; animation: hide 0.2s forwards;
animation-delay: var(--delay); animation-delay: var(--delay);
} }
&.inactive { &.inactive {
opacity: 0; opacity: 0;
animation: show .2s forwards; animation: show 0.2s forwards;
animation-delay: var(--delay); animation-delay: var(--delay);
} }
} }
@ -45,8 +45,8 @@ $g2: rgb(236, 64, 122);
margin: auto; margin: auto;
font-size: 5em; font-size: 5em;
background-color: rgba(20, 20, 20, 0.2); background-color: rgba(20, 20, 20, 0.2);
padding: .25em .5em; padding: 0.25em 0.5em;
border-radius: .25em; border-radius: 0.25em;
&.active { &.active {
opacity: 1; opacity: 1;

View file

@ -1,10 +1,9 @@
@use './mixins/display' as *; @use "./mixins/display" as *;
@use './mixins/effects' as *; @use "./mixins/effects" as *;
@use './mixins/CP_Font' as *; @use "./mixins/CP_Font" as *;
@import './mixins/variables'; @import "./mixins/variables";
@import url("https://fonts.googleapis.com/css2?family=Farro:wght@300;400;500;700&display=swap");
@import url('https://fonts.googleapis.com/css2?family=Farro:wght@300;400;500;700&display=swap');
#box { #box {
min-height: 100%; min-height: 100%;
@ -89,7 +88,7 @@
} }
#startButton { #startButton {
font-family: 'Farro', sans-serif; font-family: "Farro", sans-serif;
font-weight: bold; font-weight: bold;
font-size: 3em; font-size: 3em;
color: black; color: black;
@ -115,14 +114,14 @@
font-size: 3em; font-size: 3em;
color: $grayish; color: $grayish;
align-self: flex-start; align-self: flex-start;
background-color: #000C; background-color: #000c;
border: none; border: none;
border-radius: 8px; border-radius: 8px;
padding: 0 .5rem; padding: 0 0.5rem;
margin-top: -1.5rem; margin-top: -1.5rem;
width: 10rem; width: 10rem;
box-shadow: 0 0 2px 2px #fff6 inset; box-shadow: 0 0 2px 2px #fff6 inset;
border: 2px solid #000C; border: 2px solid #000c;
} }
#sameWidth { #sameWidth {
@ -137,13 +136,13 @@
align-items: center; align-items: center;
font-size: 2.5em; font-size: 2.5em;
color: $grayish; color: $grayish;
background-color: #000C; background-color: #000c;
border: none; border: none;
border-radius: 8px; border-radius: 8px;
padding: 1rem 2rem 1rem 4rem; padding: 1rem 2rem 1rem 4rem;
width: 100%; width: 100%;
box-shadow: 0 0 2px 2px #fff6 inset; box-shadow: 0 0 2px 2px #fff6 inset;
border: 2px solid #000C; border: 2px solid #000c;
&:last-child { &:last-child {
margin-top: 2rem; margin-top: 2rem;
@ -160,9 +159,7 @@
height: inherit; height: inherit;
} }
} }
} }
} }
} }
@ -173,7 +170,6 @@
width: 560px; width: 560px;
#width { #width {
h1 { h1 {
font-size: 4.5em; font-size: 4.5em;
letter-spacing: 4px; letter-spacing: 4px;
@ -210,7 +206,6 @@
width: 450px; width: 450px;
#width { #width {
h1 { h1 {
font-size: 3.6em; font-size: 3.6em;
letter-spacing: 3px; letter-spacing: 3px;
@ -254,7 +249,6 @@
width: 280px; width: 280px;
#width { #width {
h1 { h1 {
font-size: 2.2em; font-size: 2.2em;
letter-spacing: 2px; letter-spacing: 2px;
@ -292,7 +286,7 @@
margin-top: -1rem; margin-top: -1rem;
font-size: 2em; font-size: 2em;
width: 7rem; width: 7rem;
padding: .125rem; padding: 0.125rem;
} }
#sameWidth { #sameWidth {
@ -313,7 +307,6 @@
} }
} }
@media (max-width: 500px) { @media (max-width: 500px) {
#box { #box {
#videoWrapper { #videoWrapper {
@ -323,7 +316,6 @@
#startBox { #startBox {
#sameWidth { #sameWidth {
.optionButton { .optionButton {
font-size: 1.5em; font-size: 1.5em;

View file

@ -3,7 +3,6 @@
src: url("/fonts/cpfont_ote/CP Font.otf") format("opentype"); src: url("/fonts/cpfont_ote/CP Font.otf") format("opentype");
} }
@mixin CP_Font { @mixin CP_Font {
font-family: "CP_Font", sans-serif; font-family: "CP_Font", sans-serif;
} }

View file

@ -9,46 +9,142 @@
animation: appear $timing forwards; animation: appear $timing forwards;
} }
@keyframes appear { @keyframes appear {
From { from {
opacity: 0; opacity: 0;
} }
To { to {
opacity: 1; opacity: 1;
} }
} }
@mixin gradient-edge { @mixin gradient-edge {
&.left-top-corner { &.left-top-corner {
mask-image: -webkit-gradient(linear, right bottom, left top, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, right bottom, left top, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); linear,
right bottom,
left top,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
right bottom,
left top,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
} }
&.right-top-corner { &.right-top-corner {
mask-image: -webkit-gradient(linear, left bottom, right top, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, left bottom, right top, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); linear,
left bottom,
right top,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
left bottom,
right top,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
} }
&.left-bottom-corner { &.left-bottom-corner {
mask-image: -webkit-gradient(linear, right top, left bottom, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, right top, left bottom, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); linear,
right top,
left bottom,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
right top,
left bottom,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
} }
&.right-bottom-corner { &.right-bottom-corner {
mask-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, left top, right bottom, color-stop(0, rgba(0, 0, 0, 1)), color-stop(0.5, rgba(0, 0, 0, 0))); linear,
left top,
right bottom,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
left top,
right bottom,
color-stop(0, rgba(0, 0, 0, 1)),
color-stop(0.5, rgba(0, 0, 0, 0))
);
} }
&.left { &.left {
mask-image: -webkit-gradient(linear, right top, left top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, right top, left top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); linear,
right top,
left top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
right top,
left top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
} }
&.right { &.right {
mask-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); linear,
left top,
right top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
left top,
right top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
} }
&.top { &.top {
mask-image: -webkit-gradient(linear, left bottom, left top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, left bottom, left top, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); linear,
left bottom,
left top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
left bottom,
left top,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
} }
&.bottom { &.bottom {
mask-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); mask-image: -webkit-gradient(
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0))); linear,
left top,
left bottom,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
-webkit-mask-image: -webkit-gradient(
linear,
left top,
left bottom,
from(rgba(0, 0, 0, 1)),
to(rgba(0, 0, 0, 0))
);
} }
} }

View file

@ -1,3 +1,3 @@
$theme: #282c34; $theme: #282c34;
$grayish: #B1B2B5CC; $grayish: #b1b2b5cc;
$warn: #fabd04; $warn: #fabd04;