diff --git a/.env b/.env index 951db6b..98ae12d 100644 --- a/.env +++ b/.env @@ -1 +1,2 @@ -VITE_API_ENDPOINT=/api \ No newline at end of file +VITE_API_ENDPOINT=/api +VITE_BASE= \ No newline at end of file diff --git a/ci/.drone.yml b/ci/.drone.yml index 8b7058d..a282766 100644 --- a/ci/.drone.yml +++ b/ci/.drone.yml @@ -36,6 +36,7 @@ steps: - chmod +x /tmp/moshell_setup.sh - echo n | /tmp/moshell_setup.sh - echo "VITE_API_ENDPOINT=/IQBall/$DRONE_BRANCH/public/api" >> .env.PROD + - echo "VITE_BASE=/IQBall/$DRONE_BRANCH/public" >> .env.PROD - - /root/.local/bin/moshell ci/build_react.msh diff --git a/ci/build_react.msh b/ci/build_react.msh index 32a5923..3d3a8f0 100755 --- a/ci/build_react.msh +++ b/ci/build_react.msh @@ -9,8 +9,6 @@ val drone_branch = std::env("DRONE_BRANCH").unwrap() val base = "/IQBall/$drone_branch/public" npm run build -- --base=$base --mode PROD -npm run build -- --base=/IQBall/public --mode PROD - // Read generated mappings from build val result = $(jq -r 'to_entries|map(.key + " " +.value.file)|.[]' dist/manifest.json) val mappings = $result.split('\n') diff --git a/ci/deploy.sh b/ci/deploy.sh index b870658..19aa768 100644 --- a/ci/deploy.sh +++ b/ci/deploy.sh @@ -4,6 +4,9 @@ mkdir ~/.ssh echo "$SERVER_PRIVATE_KEY" > ~/.ssh/id_rsa chmod 0600 ~/.ssh chmod 0500 ~/.ssh/id_rsa* -ssh -p 80 -o 'StrictHostKeyChecking=no' iqball@maxou.dev mkdir -p /server/nginx/IQBall/$DRONE_BRANCH -rsync -avz -e "ssh -p 80 -o 'StrictHostKeyChecking=no'" --delete /outputs/* iqball@maxou.dev:/server/nginx/IQBall/$DRONE_BRANCH -ssh -p 80 -o 'StrictHostKeyChecking=no' iqball@maxou.dev "chmod 770 /server/nginx/IQBall/$DRONE_BRANCH; chgrp www-data /server/nginx/IQBall/$DRONE_BRANCH" \ No newline at end of file + +SERVER_ROOT=/srv/www/IQBall + +ssh -p 80 -o 'StrictHostKeyChecking=no' iqball@maxou.dev mkdir -p $SERVER_ROOT/$DRONE_BRANCH +rsync -avz -e "ssh -p 80 -o 'StrictHostKeyChecking=no'" --delete /outputs/* iqball@maxou.dev:$SERVER_ROOT/$DRONE_BRANCH +ssh -p 80 -o 'StrictHostKeyChecking=no' iqball@maxou.dev "chmod 777 $SERVER_ROOT/$DRONE_BRANCH" \ No newline at end of file diff --git a/front/Constants.ts b/front/Constants.ts index 76b37c2..013db50 100644 --- a/front/Constants.ts +++ b/front/Constants.ts @@ -2,3 +2,8 @@ * This constant defines the API endpoint. */ export const API = import.meta.env.VITE_API_ENDPOINT + +/** + * This constant defines the base app's endpoint. + */ +export const BASE = import.meta.env.VITE_BASE diff --git a/front/assets/basketball_court.svg b/front/assets/court/court.svg similarity index 98% rename from front/assets/basketball_court.svg rename to front/assets/court/court.svg index e0df003..e01fd58 100644 --- a/front/assets/basketball_court.svg +++ b/front/assets/court/court.svg @@ -1,7 +1,8 @@ diff --git a/front/assets/court/half_court.svg b/front/assets/court/half_court.svg new file mode 100644 index 0000000..8e7640e --- /dev/null +++ b/front/assets/court/half_court.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/front/assets/icon/ball.svg b/front/assets/icon/ball.svg new file mode 100644 index 0000000..6351088 --- /dev/null +++ b/front/assets/icon/ball.svg @@ -0,0 +1,62 @@ + + + + +Created by potrace 1.15, written by Peter Selinger 2001-2017 + + + + + + + + + + + + diff --git a/front/components/editor/BallPiece.tsx b/front/components/editor/BallPiece.tsx new file mode 100644 index 0000000..baaba70 --- /dev/null +++ b/front/components/editor/BallPiece.tsx @@ -0,0 +1,21 @@ +import React, { RefObject } from "react" + +import "../../style/ball.css" + +import Ball from "../../assets/icon/ball.svg?react" +import Draggable from "react-draggable" + +export interface BallPieceProps { + onDrop: () => void + pieceRef: RefObject +} + +export function BallPiece({ onDrop, pieceRef }: BallPieceProps) { + return ( + +
+ +
+ + ) +} diff --git a/front/components/editor/BasketCourt.tsx b/front/components/editor/BasketCourt.tsx index 115c41b..6229afd 100644 --- a/front/components/editor/BasketCourt.tsx +++ b/front/components/editor/BasketCourt.tsx @@ -1,25 +1,32 @@ import CourtSvg from "../../assets/basketball_court.svg?react" import "../../style/basket_court.css" -import { useRef } from "react" +import { RefObject, useRef } from "react" import CourtPlayer from "./CourtPlayer" import { Player } from "../../tactic/Player" export interface BasketCourtProps { players: Player[] onPlayerRemove: (p: Player) => void + onBallDrop: (ref: HTMLDivElement) => void onPlayerChange: (p: Player) => void + courtImage: string + courtRef: RefObject } export function BasketCourt({ players, onPlayerRemove, + onBallDrop, onPlayerChange, + courtImage, + courtRef, }: BasketCourtProps) { - const divRef = useRef(null) - return ( -
- +
+ {"court"} {players.map((player) => { return ( onPlayerRemove(player)} - parentRef={divRef} + onBallDrop={onBallDrop} + parentRef={courtRef} /> ) })} diff --git a/front/components/editor/CourtPlayer.tsx b/front/components/editor/CourtPlayer.tsx index 12083d3..6aebdcb 100644 --- a/front/components/editor/CourtPlayer.tsx +++ b/front/components/editor/CourtPlayer.tsx @@ -1,6 +1,7 @@ import { RefObject, useRef, useState } from "react" import "../../style/player.css" import RemoveIcon from "../../assets/icon/remove.svg?react" +import { BallPiece } from "./BallPiece" import Draggable from "react-draggable" import { PlayerPiece } from "./PlayerPiece" import { Player } from "../../tactic/Player" @@ -10,6 +11,7 @@ export interface PlayerProps { player: Player onChange: (p: Player) => void onRemove: () => void + onBallDrop: (ref: HTMLDivElement) => void parentRef: RefObject } @@ -20,12 +22,15 @@ export default function CourtPlayer({ player, onChange, onRemove, + onBallDrop, parentRef, }: PlayerProps) { const pieceRef = useRef(null) + const ballPiece = useRef(null) const x = player.rightRatio const y = player.bottomRatio + const hasBall = player.hasBall return (
{ @@ -65,8 +73,18 @@ export default function CourtPlayer({ className="player-selection-tab-remove" onClick={onRemove} /> + {hasBall && ( + onBallDrop(ballPiece.current!)} + pieceRef={ballPiece} + /> + )}
- +
diff --git a/front/components/editor/PlayerPiece.tsx b/front/components/editor/PlayerPiece.tsx index 69b38c2..e725d31 100644 --- a/front/components/editor/PlayerPiece.tsx +++ b/front/components/editor/PlayerPiece.tsx @@ -2,9 +2,20 @@ import React from "react" import "../../style/player.css" import { Team } from "../../tactic/Team" -export function PlayerPiece({ team, text }: { team: Team; text: string }) { +export interface PlayerPieceProps { + team: Team + text: string + hasBall: boolean +} + +export function PlayerPiece({ team, text, hasBall }: PlayerPieceProps) { + let className = `player-piece ${team}` + if (hasBall) { + className += ` player-piece-has-ball` + } + return ( -
+

{text}

) diff --git a/front/components/editor/SavingState.tsx b/front/components/editor/SavingState.tsx index df03628..68c2285 100644 --- a/front/components/editor/SavingState.tsx +++ b/front/components/editor/SavingState.tsx @@ -4,6 +4,10 @@ export interface SaveState { } export class SaveStates { + static readonly Guest: SaveState = { + className: "save-state-guest", + message: "you are not connected, your changes will not be saved.", + } static readonly Ok: SaveState = { className: "save-state-ok", message: "saved", diff --git a/front/style/ball.css b/front/style/ball.css new file mode 100644 index 0000000..c14c196 --- /dev/null +++ b/front/style/ball.css @@ -0,0 +1,11 @@ +.ball * { + fill: #c5520d; +} + +.ball-div, +.ball { + pointer-events: all; + width: 20px; + height: 20px; + cursor: pointer; +} diff --git a/front/style/basket_court.css b/front/style/basket_court.css index c001cc0..92a520c 100644 --- a/front/style/basket_court.css +++ b/front/style/basket_court.css @@ -1,11 +1,16 @@ #court-container { display: flex; + align-content: center; + align-items: center; + justify-content: center; + height: 100%; background-color: var(--main-color); } #court-svg { - margin: 5%; + margin: 35px 0 35px 0; + height: 87%; user-select: none; -webkit-user-drag: none; } diff --git a/front/style/colors.css b/front/style/colors.css deleted file mode 100644 index 3c17a25..0000000 --- a/front/style/colors.css +++ /dev/null @@ -1,11 +0,0 @@ -:root { - --main-color: #ffffff; - --second-color: #ccde54; - - --background-color: #d2cdd3; - - --selected-team-primarycolor: #ffffff; - --selected-team-secondarycolor: #000000; - - --selection-color: #3f7fc4; -} diff --git a/front/style/editor.css b/front/style/editor.css index d832fc3..8f0adf4 100644 --- a/front/style/editor.css +++ b/front/style/editor.css @@ -1,4 +1,4 @@ -@import "colors.css"; +@import "theme/default.css"; #main-div { display: flex; @@ -49,7 +49,11 @@ } .player-piece.opponents { - background-color: #f59264; + background-color: var(--player-opponents-color); +} + +.player-piece.allies { + background-color: var(--player-allies-color); } #court-div { @@ -63,7 +67,8 @@ } #court-div-bounds { - width: 60%; + padding: 20px 20px 20px 20px; + height: 75%; } .react-draggable { @@ -85,6 +90,7 @@ color: green; } -.save-state-saving { +.save-state-saving, +.save-state-guest { color: gray; } diff --git a/front/style/new_tactic_panel.css b/front/style/new_tactic_panel.css new file mode 100644 index 0000000..ff6a07e --- /dev/null +++ b/front/style/new_tactic_panel.css @@ -0,0 +1,122 @@ +#panel-root { + width: 100%; + height: 100%; + + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + align-content: center; +} + +#panel-top { + font-family: var(--text-main-font); +} + +#panel-choices { + width: 100%; + height: 100%; + + display: flex; + justify-content: center; + align-items: center; + align-content: center; + + background-color: var(--editor-court-selection-background); +} + +#panel-buttons { + width: 75%; + height: 20%; + display: flex; + justify-content: space-evenly; + align-items: stretch; + align-content: center; +} + +.court-kind-button { + position: relative; + + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + align-content: center; + + cursor: pointer; + + transition: scale 0.5s ease-out; + width: auto; +} + +.court-kind-button-bottom, +.court-kind-button-top { + border: solid; + border-color: var(--border-color); +} +.court-kind-button-bottom { + display: flex; + justify-content: center; + align-items: center; + align-content: center; + + height: 25%; + width: 100%; + + background-color: var(--editor-court-selection-buttons); + border-radius: 0 0 20px 20px; + border-width: 3px; +} + +.court-kind-button-top { + height: 30%; + background-color: var(--main-color); + border-radius: 20px 20px 0 0; + border-width: 3px 3px 0 3px; +} + +.court-kind-button:hover { + scale: 1.1; +} + +.court-kind-button-top, +.court-kind-button-image-div { + overflow: hidden; + display: flex; + height: 100%; + width: 100%; + justify-content: center; + align-items: center; + align-content: center; +} + +.court-kind-button-image { + height: 100%; + width: 150px; + user-select: none; + -webkit-user-drag: none; +} + +.court-kind-button-image-div { + height: 100%; + + padding: 0 10px 0 10px; + background-color: var(--second-color); +} + +.court-kind-button-name, +.court-kind-button-details { + user-select: none; + font-family: var(--text-main-font); +} + +.court-kind-button-details { + position: absolute; + z-index: -1; + top: 0; + transition: top 1s; +} + +.court-kind-button:hover .court-kind-button-details { + top: -20px; +} diff --git a/front/style/player.css b/front/style/player.css index 7bea36e..81a6b7e 100644 --- a/front/style/player.css +++ b/front/style/player.css @@ -23,9 +23,7 @@ on the court. background-color: var(--selected-team-primarycolor); color: var(--selected-team-secondarycolor); - border-width: 2px; border-radius: 100px; - border-style: solid; width: 20px; height: 20px; @@ -38,21 +36,29 @@ on the court. user-select: none; } +.player-piece-has-ball { + border-width: 2px; + border-style: solid; + border-color: var(--player-piece-ball-border-color); +} + .player-selection-tab { - display: flex; + display: none; position: absolute; - margin-bottom: 10%; + margin-bottom: -20%; justify-content: center; - visibility: hidden; - width: 100%; + width: fit-content; transform: translateY(-20px); } .player-selection-tab-remove { + visibility: hidden; pointer-events: all; - height: 25%; + width: 25px; + height: 17px; + justify-content: center; } .player-selection-tab-remove * { @@ -67,7 +73,7 @@ on the court. } .player:focus-within .player-selection-tab { - visibility: visible; + display: flex; } .player:focus-within .player-piece { diff --git a/front/style/theme/default.css b/front/style/theme/default.css new file mode 100644 index 0000000..12c4452 --- /dev/null +++ b/front/style/theme/default.css @@ -0,0 +1,23 @@ +@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@300;400&display=swap"); +:root { + --main-color: #ffffff; + --second-color: #e8e8e8; + + --background-color: #d2cdd3; + + --selected-team-primarycolor: #ffffff; + --selected-team-secondarycolor: #000000; + --player-allies-color: #64e4f5; + --player-opponents-color: #f59264; + + --buttons-shadow-color: #a8a8a8; + + --selection-color: #3f7fc4; + + --border-color: #ffffff; + + --editor-court-selection-background: #5f8fee; + --editor-court-selection-buttons: #acc4f3; + + --text-main-font: "Roboto", sans-serif; +} diff --git a/front/tactic/Ball.ts b/front/tactic/Ball.ts new file mode 100644 index 0000000..443e4f9 --- /dev/null +++ b/front/tactic/Ball.ts @@ -0,0 +1,11 @@ +export interface Ball { + /** + * Percentage of the player's position to the bottom (0 means top, 1 means bottom, 0.5 means middle) + */ + bottom_percentage: number + + /** + * Percentage of the player's position to the right (0 means left, 1 means right, 0.5 means middle) + */ + right_percentage: number +} diff --git a/front/tactic/Player.ts b/front/tactic/Player.ts index 6530612..553b85e 100644 --- a/front/tactic/Player.ts +++ b/front/tactic/Player.ts @@ -1,6 +1,7 @@ import { Team } from "./Team" export interface Player { + id: string /** * the player's team * */ @@ -20,4 +21,6 @@ export interface Player { * Percentage of the player's position to the right (0 means left, 1 means right, 0.5 means middle) */ rightRatio: number + + hasBall: boolean } diff --git a/front/views/Editor.tsx b/front/views/Editor.tsx index dddf5cc..5c10f64 100644 --- a/front/views/Editor.tsx +++ b/front/views/Editor.tsx @@ -10,9 +10,13 @@ import "../style/editor.css" import TitleInput from "../components/TitleInput" import { BasketCourt } from "../components/editor/BasketCourt" +import plainCourt from "../assets/court/court.svg" +import halfCourt from "../assets/court/half_court.svg" + import { Rack } from "../components/Rack" import { PlayerPiece } from "../components/editor/PlayerPiece" +import { BallPiece } from "../components/editor/BallPiece" import { Player } from "../tactic/Player" import { Tactic, TacticContent } from "../tactic/Tactic" import { fetchAPI } from "../Fetcher" @@ -27,10 +31,21 @@ const ERROR_STYLE: CSSProperties = { borderColor: "red", } +const GUEST_MODE_CONTENT_STORAGE_KEY = "guest_mode_content" +const GUEST_MODE_TITLE_STORAGE_KEY = "guest_mode_title" + export interface EditorViewProps { tactic: Tactic - onContentChange: (tactic: TacticContent) => Promise + onContentChange: (tactic: TacticContent) => Promise onNameChange: (name: string) => Promise + courtType: "PLAIN" | "HALF" +} + +export interface EditorProps { + id: number + name: string + content: string + courtType: "PLAIN" | "HALF" } /** @@ -41,41 +56,65 @@ interface RackedPlayer { key: string } -export default function Editor({ - id, - name, - content, -}: { - id: number - name: string - content: string -}) { +export default function Editor({ id, name, courtType, content }: EditorProps) { + const isInGuestMode = id == -1 + + const storage_content = localStorage.getItem(GUEST_MODE_CONTENT_STORAGE_KEY) + const editorContent = + isInGuestMode && storage_content != null ? storage_content : content + + const storage_name = localStorage.getItem(GUEST_MODE_TITLE_STORAGE_KEY) + const editorName = + isInGuestMode && storage_name != null ? storage_name : name + return ( - fetchAPI(`tactic/${id}/save`, { content }).then((r) => r.ok) - } - onNameChange={(name: string) => - fetchAPI(`tactic/${id}/edit/name`, { name }).then((r) => r.ok) - } + tactic={{ + name: editorName, + id, + content: JSON.parse(editorContent), + }} + onContentChange={async (content: TacticContent) => { + if (isInGuestMode) { + localStorage.setItem( + GUEST_MODE_CONTENT_STORAGE_KEY, + JSON.stringify(content), + ) + return SaveStates.Guest + } + return fetchAPI(`tactic/${id}/save`, { content }).then((r) => + r.ok ? SaveStates.Ok : SaveStates.Err, + ) + }} + onNameChange={async (name: string) => { + if (isInGuestMode) { + localStorage.setItem(GUEST_MODE_TITLE_STORAGE_KEY, name) + return true //simulate that the name has been changed + } + return fetchAPI(`tactic/${id}/edit/name`, { name }).then( + (r) => r.ok, + ) + }} + courtType={courtType} /> ) } function EditorView({ - tactic: { name, content: initialContent }, + tactic: { id, name, content: initialContent }, onContentChange, onNameChange, + courtType, }: EditorViewProps) { - const [style, setStyle] = useState({}) + const isInGuestMode = id == -1 + + const [titleStyle, setTitleStyle] = useState({}) const [content, setContent, saveState] = useContentState( initialContent, - (content) => - onContentChange(content).then((success) => - success ? SaveStates.Ok : SaveStates.Err, - ), + isInGuestMode ? SaveStates.Guest : SaveStates.Ok, + onContentChange, ) + const [allies, setAllies] = useState( getRackPlayers(Team.Allies, content.players), ) @@ -83,6 +122,12 @@ function EditorView({ getRackPlayers(Team.Opponents, content.players), ) + const [showBall, setShowBall] = useState( + content.players.find((p) => p.hasBall) == undefined, + ) + + const ballPiece = useRef(null) + const courtDivContentRef = useRef(null) const canDetach = (ref: HTMLDivElement) => { @@ -109,35 +154,65 @@ function EditorView({ players: [ ...content.players, { + id: "player-" + content.players.length, team: element.team, role: element.key, rightRatio: x, bottomRatio: y, + hasBall: false, }, ], } }) } + const onBallDrop = (ref: HTMLDivElement) => { + const ballBounds = ref.getBoundingClientRect() + let ballAssigned = false + + setContent((content) => { + const players = content.players.map((player) => { + if (ballAssigned) { + return { ...player, hasBall: false } + } + const playerBounds = document + .getElementById(player.id)! + .getBoundingClientRect() + const doesOverlap = !( + ballBounds.top > playerBounds.bottom || + ballBounds.right < playerBounds.left || + ballBounds.bottom < playerBounds.top || + ballBounds.left > playerBounds.right + ) + if (doesOverlap) { + ballAssigned = true + } + return { ...player, hasBall: doesOverlap } + }) + setShowBall(!ballAssigned) + return { players: players } + }) + } + return (
- LEFT +
{ onNameChange(new_name).then((success) => { - setStyle(success ? {} : ERROR_STYLE) + setTitleStyle(success ? {} : ERROR_STYLE) }) }} />
-
RIGHT
+
@@ -148,9 +223,22 @@ function EditorView({ canDetach={canDetach} onElementDetached={onPieceDetach} render={({ team, key }) => ( - + )} /> + + {showBall && ( + onBallDrop(ballPiece.current!)} + pieceRef={ballPiece} + /> + )} + ( - + )} />
-
+
{ setContent((content) => ({ players: toSplicedPlayers( @@ -191,6 +289,9 @@ function EditorView({ case Team.Allies: setter = setAllies } + if (player.hasBall) { + setShowBall(true) + } setter((players) => [ ...players, { @@ -220,26 +321,30 @@ function getRackPlayers(team: Team, players: Player[]): RackedPlayer[] { function useContentState( initialContent: S, + initialSaveState: SaveState, saveStateCallback: (s: S) => Promise, ): [S, Dispatch>, SaveState] { const [content, setContent] = useState(initialContent) - const [savingState, setSavingState] = useState(SaveStates.Ok) + const [savingState, setSavingState] = useState(initialSaveState) - const setContentSynced = useCallback((newState: SetStateAction) => { - setContent((content) => { - const state = - typeof newState === "function" - ? (newState as (state: S) => S)(content) - : newState - if (state !== content) { - setSavingState(SaveStates.Saving) - saveStateCallback(state) - .then(setSavingState) - .catch(() => setSavingState(SaveStates.Err)) - } - return state - }) - }, [saveStateCallback]) + const setContentSynced = useCallback( + (newState: SetStateAction) => { + setContent((content) => { + const state = + typeof newState === "function" + ? (newState as (state: S) => S)(content) + : newState + if (state !== content) { + setSavingState(SaveStates.Saving) + saveStateCallback(state) + .then(setSavingState) + .catch(() => setSavingState(SaveStates.Err)) + } + return state + }) + }, + [saveStateCallback], + ) return [content, setContentSynced, savingState] } diff --git a/front/views/NewTacticPanel.tsx b/front/views/NewTacticPanel.tsx new file mode 100644 index 0000000..bd9badb --- /dev/null +++ b/front/views/NewTacticPanel.tsx @@ -0,0 +1,64 @@ +import "../style/theme/default.css" +import "../style/new_tactic_panel.css" + +import plainCourt from "../assets/court/court.svg" +import halfCourt from "../assets/court/half_court.svg" +import { BASE } from "../Constants" + +export default function NewTacticPanel() { + return ( +
+
+

Select a basket court

+
+
+
+ + +
+
+
+ ) +} + +function CourtKindButton({ + name, + image, + details, + redirect, +}: { + name: string + image: string + details: string + redirect: string +}) { + return ( +
(location.href = BASE + redirect)}> +
{details}
+
+
+ {name} +
+
+
+

{name}

+
+
+ ) +} diff --git a/front/views/Visualizer.tsx b/front/views/Visualizer.tsx index 541da09..5b09115 100644 --- a/front/views/Visualizer.tsx +++ b/front/views/Visualizer.tsx @@ -1,6 +1,6 @@ import React, { CSSProperties, useState } from "react" import "../style/visualizer.css" -import Court from "../assets/basketball_court.svg" +import Court from "../assets/court/court.svg" export default function Visualizer({ id, name }: { id: number; name: string }) { const [style, setStyle] = useState({}) diff --git a/public/index.php b/public/index.php index 278e7f1..58a78a4 100644 --- a/public/index.php +++ b/public/index.php @@ -19,6 +19,7 @@ use IQBall\App\Session\SessionHandle; use IQBall\App\ViewHttpResponse; use IQBall\Core\Action; use IQBall\Core\Connection; +use IQBall\Core\Data\CourtType; use IQBall\Core\Gateway\AccountGateway; use IQBall\Core\Gateway\MemberGateway; use IQBall\Core\Gateway\TacticInfoGateway; @@ -84,11 +85,17 @@ function getRoutes(): AltoRouter { $ar->map("GET", "/", Action::auth(fn(SessionHandle $s) => getUserController()->home($s))); $ar->map("GET", "/home", Action::auth(fn(SessionHandle $s) => getUserController()->home($s))); $ar->map("GET", "/settings", Action::auth(fn(SessionHandle $s) => getUserController()->settings($s))); + $ar->map("GET", "/disconnect", Action::auth(fn(MutableSessionHandle $s) => getUserController()->disconnect($s))); + //tactic-related $ar->map("GET", "/tactic/[i:id]/view", Action::auth(fn(int $id, SessionHandle $s) => getVisualizerController()->openVisualizer($id, $s))); $ar->map("GET", "/tactic/[i:id]/edit", Action::auth(fn(int $id, SessionHandle $s) => getEditorController()->openEditor($id, $s))); - $ar->map("GET", "/tactic/new", Action::auth(fn(SessionHandle $s) => getEditorController()->createNew($s))); + // don't require an authentication to run this action. + // If the user is not connected, the tactic will never save. + $ar->map("GET", "/tactic/new", Action::noAuth(fn() => getEditorController()->createNew())); + $ar->map("GET", "/tactic/new/plain", Action::noAuth(fn(SessionHandle $s) => getEditorController()->createNewOfKind(CourtType::plain(), $s))); + $ar->map("GET", "/tactic/new/half", Action::noAuth(fn(SessionHandle $s) => getEditorController()->createNewOfKind(CourtType::half(), $s))); //team-related $ar->map("GET", "/team/new", Action::auth(fn(SessionHandle $s) => getTeamController()->displayCreateTeam($s))); diff --git a/sql/setup-tables.sql b/sql/setup-tables.sql index ebde8b2..ae5a478 100644 --- a/sql/setup-tables.sql +++ b/sql/setup-tables.sql @@ -16,35 +16,36 @@ CREATE TABLE Account CREATE TABLE Tactic ( id integer PRIMARY KEY AUTOINCREMENT, - name varchar NOT NULL, - creation_date timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, - owner integer NOT NULL, - content varchar DEFAULT '{"players": []}' NOT NULL, + name varchar NOT NULL, + creation_date timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, + owner integer NOT NULL, + content varchar DEFAULT '{"players": []}' NOT NULL, + court_type varchar CHECK ( court_type IN ('HALF', 'PLAIN')) NOT NULL, FOREIGN KEY (owner) REFERENCES Account ); CREATE TABLE FormEntries ( - name varchar, - description varchar + name varchar NOT NULL, + description varchar NOT NULL ); CREATE TABLE Team ( - id integer PRIMARY KEY AUTOINCREMENT, - name varchar, - picture varchar, - main_color varchar, - second_color varchar + id integer PRIMARY KEY AUTOINCREMENT NOT NULL, + name varchar NOT NULL, + picture varchar NOT NULL, + main_color varchar NOT NULL, + second_color varchar NOT NULL ); CREATE TABLE Member ( - id_team integer, - id_user integer, - role text CHECK (role IN ('Coach', 'Player')), + id_team integer NOT NULL, + id_user integer NOT NULL, + role text CHECK (role IN ('COACH', 'PLAYER')) NOT NULL, FOREIGN KEY (id_team) REFERENCES Team (id), FOREIGN KEY (id_user) REFERENCES Account (id) ); diff --git a/src/Api/API.php b/src/Api/API.php index f79e1b5..da00749 100644 --- a/src/Api/API.php +++ b/src/Api/API.php @@ -19,7 +19,7 @@ class API { if ($response instanceof JsonHttpResponse) { header('Content-type: application/json'); echo $response->getJson(); - } else if (get_class($response) != HttpResponse::class) { + } elseif (get_class($response) != HttpResponse::class) { throw new Exception("API returned unknown Http Response"); } } diff --git a/src/App/Controller/AuthController.php b/src/App/Controller/AuthController.php index dfc5f52..cd89d11 100644 --- a/src/App/Controller/AuthController.php +++ b/src/App/Controller/AuthController.php @@ -64,14 +64,6 @@ class AuthController { */ public function login(array $request, MutableSessionHandle $session): HttpResponse { $fails = []; - $request = HttpRequest::from($request, $fails, [ - "password" => [Validators::lenBetween(6, 256)], - "email" => [Validators::email(), Validators::lenBetween(5, 256)], - ]); - if (!empty($fails)) { - return ViewHttpResponse::twig("display_login.html.twig", ['fails' => $fails]); - } - $account = $this->model->login($request['email'], $request['password'], $fails); if (!empty($fails)) { return ViewHttpResponse::twig("display_login.html.twig", ['fails' => $fails]); diff --git a/src/App/Controller/EditorController.php b/src/App/Controller/EditorController.php index d2a2bc4..3bbbe61 100644 --- a/src/App/Controller/EditorController.php +++ b/src/App/Controller/EditorController.php @@ -5,9 +5,11 @@ namespace IQBall\App\Controller; use IQBall\App\Session\SessionHandle; use IQBall\App\Validator\TacticValidator; use IQBall\App\ViewHttpResponse; +use IQBall\Core\Data\CourtType; use IQBall\Core\Data\TacticInfo; use IQBall\Core\Http\HttpCodes; use IQBall\Core\Model\TacticModel; +use IQBall\Core\Validation\ValidationFail; class EditorController { private TacticModel $model; @@ -25,16 +27,43 @@ class EditorController { "id" => $tactic->getId(), "name" => $tactic->getName(), "content" => $tactic->getContent(), + "courtType" => $tactic->getCourtType()->name(), + ]); + } + + public function createNew(): ViewHttpResponse { + return ViewHttpResponse::react("views/NewTacticPanel.tsx", []); + } + + /** + * @return ViewHttpResponse the editor view for a test tactic. + */ + private function openTestEditor(CourtType $courtType): ViewHttpResponse { + return ViewHttpResponse::react("views/Editor.tsx", [ + "id" => -1, //-1 id means that the editor will not support saves + "name" => TacticModel::TACTIC_DEFAULT_NAME, + "content" => '{"players": []}', + "courtType" => $courtType->name(), ]); } /** * creates a new empty tactic, with default name + * If the given session does not contain a connected account, + * open a test editor. * @param SessionHandle $session + * @param CourtType $type * @return ViewHttpResponse the editor view */ - public function createNew(SessionHandle $session): ViewHttpResponse { - $tactic = $this->model->makeNewDefault($session->getAccount()->getId()); + public function createNewOfKind(CourtType $type, SessionHandle $session): ViewHttpResponse { + + $action = $session->getAccount(); + + if ($action == null) { + return $this->openTestEditor($type); + } + + $tactic = $this->model->makeNewDefault($session->getAccount()->getId(), $type); return $this->openEditorFor($tactic); } @@ -55,6 +84,4 @@ class EditorController { return $this->openEditorFor($tactic); } - - } diff --git a/src/App/Controller/UserController.php b/src/App/Controller/UserController.php index d6f9f89..5ce1318 100644 --- a/src/App/Controller/UserController.php +++ b/src/App/Controller/UserController.php @@ -2,8 +2,10 @@ namespace IQBall\App\Controller; +use IQBall\App\Session\MutableSessionHandle; use IQBall\App\Session\SessionHandle; use IQBall\App\ViewHttpResponse; +use IQBall\Core\Http\HttpResponse; use IQBall\Core\Model\TacticModel; class UserController { @@ -33,4 +35,9 @@ class UserController { return ViewHttpResponse::twig("account_settings.twig", []); } + public function disconnect(MutableSessionHandle $session): HttpResponse { + $session->destroy(); + return HttpResponse::redirect("/"); + } + } diff --git a/src/App/Controller/VisualizerController.php b/src/App/Controller/VisualizerController.php index 271c4e9..631468e 100644 --- a/src/App/Controller/VisualizerController.php +++ b/src/App/Controller/VisualizerController.php @@ -20,7 +20,7 @@ class VisualizerController { } /** - * opens a visualisation page for the tactic specified by its identifier in the url. + * Opens a visualisation page for the tactic specified by its identifier in the url. * @param int $id * @param SessionHandle $session * @return HttpResponse diff --git a/src/App/Session/MutableSessionHandle.php b/src/App/Session/MutableSessionHandle.php index 9ef23c0..14871b6 100644 --- a/src/App/Session/MutableSessionHandle.php +++ b/src/App/Session/MutableSessionHandle.php @@ -17,4 +17,6 @@ interface MutableSessionHandle extends SessionHandle { * @param Account $account update the session's account */ public function setAccount(Account $account): void; + + public function destroy(): void; } diff --git a/src/App/Session/PhpSessionHandle.php b/src/App/Session/PhpSessionHandle.php index 9a08e47..cea20a6 100644 --- a/src/App/Session/PhpSessionHandle.php +++ b/src/App/Session/PhpSessionHandle.php @@ -31,4 +31,8 @@ class PhpSessionHandle implements MutableSessionHandle { public function setInitialTarget(?string $url): void { $_SESSION["target"] = $url; } + + public function destroy(): void { + session_destroy(); + } } diff --git a/src/App/Views/display_login.html.twig b/src/App/Views/display_login.html.twig index cdc11a5..c609537 100644 --- a/src/App/Views/display_login.html.twig +++ b/src/App/Views/display_login.html.twig @@ -40,18 +40,6 @@ border-radius: 5px; } - input[type="submit"] { - background-color: #007bff; - color: #fff; - padding: 10px 20px; - border: none; - border-radius: 5px; - cursor: pointer; - } - - input[type="submit"]:hover { - background-color: #0056b3; - } .error-messages { color: #ff331a; @@ -68,6 +56,31 @@ ; } {% endfor %} + + .inscr { + font-size: small; + } + + #buttons{ + display: flex; + justify-content: center; + padding: 10px 20px; + + } + + .button{ + background-color: #007bff; + color: #fff; + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; + } + + .button:hover{ + background-color: #0056b3; + } +
@@ -76,21 +89,19 @@
{% for name in fails %} - + {% endfor %} - -
-
- -
+ Vous n'avez pas de compte ? +

+
+ +
- - \ No newline at end of file diff --git a/src/App/Views/display_register.html.twig b/src/App/Views/display_register.html.twig index 8649de8..38bdb43 100644 --- a/src/App/Views/display_register.html.twig +++ b/src/App/Views/display_register.html.twig @@ -40,23 +40,11 @@ border-radius: 5px; } - input[type="submit"] { - background-color: #007bff; - color: #fff; - padding: 10px 20px; - border: none; - border-radius: 5px; - cursor: pointer; - } - .error-messages { color: #ff331a; font-style: italic; } - input[type="submit"]:hover { - background-color: #0056b3; - } {% for err in fails %} .form-group @@ -69,6 +57,31 @@ } {% endfor %} + .inscr{ + font-size: small; + text-align: right; + } + + #buttons{ + display: flex; + justify-content: center; + padding: 10px 20px; + + } + + .button{ + background-color: #007bff; + color: #fff; + padding: 10px 20px; + border: none; + border-radius: 5px; + cursor: pointer; + } + + .button:hover{ + background-color: #0056b3; + } + @@ -87,12 +100,13 @@ - + Vous avez déjà un compte ? +
-
- +
+
diff --git a/src/App/Views/home.twig b/src/App/Views/home.twig index 5d9e8ae..7d8430e 100644 --- a/src/App/Views/home.twig +++ b/src/App/Views/home.twig @@ -50,6 +50,7 @@ +

IQ Ball

diff --git a/src/Core/Data/CourtType.php b/src/Core/Data/CourtType.php new file mode 100755 index 0000000..caad45c --- /dev/null +++ b/src/Core/Data/CourtType.php @@ -0,0 +1,61 @@ + self::COURT_HALF) { + throw new InvalidArgumentException("Valeur du rôle invalide"); + } + $this->value = $val; + } + + public static function plain(): CourtType { + return new CourtType(CourtType::COURT_PLAIN); + } + + public static function half(): CourtType { + return new CourtType(CourtType::COURT_HALF); + } + + public function name(): string { + switch ($this->value) { + case self::COURT_HALF: + return "HALF"; + case self::COURT_PLAIN: + return "PLAIN"; + } + die("unreachable"); + } + + public static function fromName(string $name): ?CourtType { + switch ($name) { + case "HALF": + return CourtType::half(); + case "PLAIN": + return CourtType::plain(); + default: + return null; + } + } + + public function isPlain(): bool { + return ($this->value == self::COURT_PLAIN); + } + + public function isHalf(): bool { + return ($this->value == self::COURT_HALF); + } + +} diff --git a/src/Core/Data/MemberRole.php b/src/Core/Data/MemberRole.php index 41b6b71..9606c0b 100755 --- a/src/Core/Data/MemberRole.php +++ b/src/Core/Data/MemberRole.php @@ -35,18 +35,18 @@ final class MemberRole { public function name(): string { switch ($this->value) { case self::ROLE_COACH: - return "Coach"; + return "COACH"; case self::ROLE_PLAYER: - return "Player"; + return "PLAYER"; } die("unreachable"); } public static function fromName(string $name): ?MemberRole { switch ($name) { - case "Coach": + case "COACH": return MemberRole::coach(); - case "Player": + case "PLAYER": return MemberRole::player(); default: return null; diff --git a/src/Core/Data/TacticInfo.php b/src/Core/Data/TacticInfo.php index 2565f93..c3b8667 100644 --- a/src/Core/Data/TacticInfo.php +++ b/src/Core/Data/TacticInfo.php @@ -7,7 +7,7 @@ class TacticInfo { private string $name; private int $creationDate; private int $ownerId; - + private CourtType $courtType; private string $content; /** @@ -15,13 +15,15 @@ class TacticInfo { * @param string $name * @param int $creationDate * @param int $ownerId + * @param CourtType $type * @param string $content */ - public function __construct(int $id, string $name, int $creationDate, int $ownerId, string $content) { + public function __construct(int $id, string $name, int $creationDate, int $ownerId, CourtType $type, string $content) { $this->id = $id; $this->name = $name; $this->ownerId = $ownerId; $this->creationDate = $creationDate; + $this->courtType = $type; $this->content = $content; } @@ -47,6 +49,10 @@ class TacticInfo { return $this->ownerId; } + public function getCourtType(): CourtType { + return $this->courtType; + } + /** * @return int */ diff --git a/src/Core/Gateway/TacticInfoGateway.php b/src/Core/Gateway/TacticInfoGateway.php index 6b66f2c..67cffc4 100644 --- a/src/Core/Gateway/TacticInfoGateway.php +++ b/src/Core/Gateway/TacticInfoGateway.php @@ -3,6 +3,7 @@ namespace IQBall\Core\Gateway; use IQBall\Core\Connection; +use IQBall\Core\Data\CourtType; use IQBall\Core\Data\TacticInfo; use PDO; @@ -33,7 +34,8 @@ class TacticInfoGateway { $row = $res[0]; - return new TacticInfo($id, $row["name"], strtotime($row["creation_date"]), $row["owner"], $row['content']); + $type = CourtType::fromName($row['court_type']); + return new TacticInfo($id, $row["name"], strtotime($row["creation_date"]), $row["owner"], $type, $row['content']); } @@ -57,14 +59,16 @@ class TacticInfoGateway { /** * @param string $name * @param int $owner + * @param CourtType $type * @return int inserted tactic id */ - public function insert(string $name, int $owner): int { + public function insert(string $name, int $owner, CourtType $type): int { $this->con->exec( - "INSERT INTO Tactic(name, owner) VALUES(:name, :owner)", + "INSERT INTO Tactic(name, owner, court_type) VALUES(:name, :owner, :court_type)", [ ":name" => [$name, PDO::PARAM_STR], ":owner" => [$owner, PDO::PARAM_INT], + ":court_type" => [$type->name(), PDO::PARAM_STR], ] ); return intval($this->con->lastInsertId()); @@ -99,5 +103,4 @@ class TacticInfoGateway { ]); return $stmnt->rowCount() == 1; } - } diff --git a/src/Core/Model/AuthModel.php b/src/Core/Model/AuthModel.php index a6ada53..e8710c0 100644 --- a/src/Core/Model/AuthModel.php +++ b/src/Core/Model/AuthModel.php @@ -63,16 +63,10 @@ class AuthModel { */ public function login(string $email, string $password, array &$failures): ?Account { $hash = $this->gateway->getHash($email); - if ($hash == null) { - $failures[] = new FieldValidationFail("email", "l'addresse email n'est pas connue."); + if ($hash == null or (!password_verify($password, $hash))) { + $failures[] = new ValidationFail("email","Adresse email ou mot de passe invalide"); return null; } - - if (!password_verify($password, $hash)) { - $failures[] = new FieldValidationFail("password", "Mot de passe invalide."); - return null; - } - return $this->gateway->getAccountFromMail($email); } diff --git a/src/Core/Model/TacticModel.php b/src/Core/Model/TacticModel.php index 136b27d..51e5eb8 100644 --- a/src/Core/Model/TacticModel.php +++ b/src/Core/Model/TacticModel.php @@ -2,6 +2,7 @@ namespace IQBall\Core\Model; +use IQBall\Core\Data\CourtType; use IQBall\Core\Data\TacticInfo; use IQBall\Core\Gateway\TacticInfoGateway; use IQBall\Core\Validation\ValidationFail; @@ -23,20 +24,22 @@ class TacticModel { * creates a new empty tactic, with given name * @param string $name * @param int $ownerId + * @param CourtType $type * @return TacticInfo */ - public function makeNew(string $name, int $ownerId): TacticInfo { - $id = $this->tactics->insert($name, $ownerId); + public function makeNew(string $name, int $ownerId, CourtType $type): TacticInfo { + $id = $this->tactics->insert($name, $ownerId, $type); return $this->tactics->get($id); } /** * creates a new empty tactic, with a default name * @param int $ownerId + * @param CourtType $type * @return TacticInfo|null */ - public function makeNewDefault(int $ownerId): ?TacticInfo { - return $this->makeNew(self::TACTIC_DEFAULT_NAME, $ownerId); + public function makeNewDefault(int $ownerId, CourtType $type): ?TacticInfo { + return $this->makeNew(self::TACTIC_DEFAULT_NAME, $ownerId, $type); } /**