You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Application-Web/src/pages/Editor.tsx

1023 lines
33 KiB

import {
CSSProperties,
Dispatch,
RefObject,
SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react"
import "../style/editor.css"
import TitleInput from "../components/TitleInput"
import PlainCourt from "../assets/court/full_court.svg?react"
import HalfCourt from "../assets/court/half_court.svg?react"
import { BallPiece } from "../components/editor/BallPiece"
import { Rack } from "../components/Rack"
import { PlayerPiece } from "../components/editor/PlayerPiece"
import {
CourtType,
StepContent,
StepInfoNode,
TacticComponent,
TacticInfo,
} from "../model/tactic/Tactic"
import { fetchAPI, fetchAPIGet } from "../Fetcher"
import SavingState, {
SaveState,
SaveStates,
} from "../components/editor/SavingState"
import { BALL_TYPE } from "../model/tactic/CourtObjects"
import { CourtAction } from "../components/editor/CourtAction"
import { ActionPreview, BasketCourt } from "../components/editor/BasketCourt"
import { overlaps } from "../geo/Box"
import {
dropBallOnComponent,
getComponentCollided,
getRackPlayers,
moveComponent,
placeBallAt,
placeObjectAt,
placePlayerAt,
removeBall,
updateComponent,
} from "../editor/TacticContentDomains"
import {
BallState,
Player,
PlayerInfo,
PlayerLike,
PlayerTeam,
} from "../model/tactic/Player"
import { RackedCourtObject, RackedPlayer } from "../editor/RackedItems"
import CourtPlayer from "../components/editor/CourtPlayer"
import {
createAction,
getActionKind,
isActionValid,
removeAction,
} from "../editor/ActionsDomains"
import ArrowAction from "../components/actions/ArrowAction"
import { middlePos, Pos, ratioWithinBase } from "../geo/Pos"
import { Action, ActionKind } from "../model/tactic/Action"
import BallAction from "../components/actions/BallAction"
import {
changePlayerBallState,
computePhantomPositioning,
getOrigin,
removePlayer,
} from "../editor/PlayerDomains"
import { CourtBall } from "../components/editor/CourtBall"
import { useNavigate, useParams } from "react-router-dom"
import { DEFAULT_TACTIC_NAME } from "./NewTacticPage.tsx"
import StepsTree from "../components/editor/StepsTree"
import { addStepNode, removeStepNode } from "../editor/StepsDomain"
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: TacticInfo
onContentChange: (tactic: StepContent) => Promise<SaveState>
onNameChange: (name: string) => Promise<boolean>
}
interface TacticDto {
id: number
name: string
courtType: CourtType
content: { components: TacticComponent[] }
root: StepInfoNode
}
interface EditorPageProps {
guestMode: boolean
}
export default function EditorPage({ guestMode }: EditorPageProps) {
const [tactic, setTactic] = useState<TacticDto | null>(() => {
if (guestMode) {
return {
id: -1,
courtType: "PLAIN",
content: { components: [] },
name: DEFAULT_TACTIC_NAME,
root: { id: 1, children: [] },
}
}
return null
})
const { tacticId: idStr } = useParams()
const id = guestMode ? -1 : parseInt(idStr!)
const navigation = useNavigate()
useEffect(() => {
if (guestMode) return
async function initialize() {
const infoResponsePromise = fetchAPIGet(`tactics/${id}`)
const treeResponsePromise = fetchAPIGet(`tactics/${id}/tree`)
const contentResponsePromise = fetchAPIGet(`tactics/${id}/steps/1`)
const infoResponse = await infoResponsePromise
const treeResponse = await treeResponsePromise
const contentResponse = await contentResponsePromise
if (
infoResponse.status == 401 ||
treeResponse.status == 401 ||
contentResponse.status == 401
) {
navigation("/login")
return
}
const { name, courtType } = await infoResponse.json()
const content = await contentResponse.json()
const { root } = await treeResponse.json()
setTactic({ id, name, courtType, content, root })
}
initialize()
}, [guestMode, id, idStr, navigation])
if (tactic) {
return (
<Editor
id={id}
initialStepsNode={tactic.root}
courtType={tactic.courtType}
initialStepContent={tactic.content}
initialName={tactic.name}
initialStepId={1}
/>
)
}
return <EditorLoadingScreen />
}
function EditorLoadingScreen() {
return <div>Loading Editor, please wait...</div>
}
export interface EditorProps {
id: number
initialName: string
courtType: "PLAIN" | "HALF"
initialStepContent: StepContent
initialStepId: number
initialStepsNode: StepInfoNode
}
function Editor({
id,
initialName,
courtType,
initialStepContent,
initialStepId,
initialStepsNode,
}: EditorProps) {
const isInGuestMode = id == -1
const navigate = useNavigate()
const storageContent = localStorage.getItem(GUEST_MODE_CONTENT_STORAGE_KEY)
const stepInitialContent = {
...(isInGuestMode && storageContent != null
? JSON.parse(storageContent)
: initialStepContent),
}
const storage_name = localStorage.getItem(GUEST_MODE_TITLE_STORAGE_KEY)
const editorName =
isInGuestMode && storage_name != null ? storage_name : initialName
const [stepId, setStepId] = useState(initialStepId)
const [stepContent, setStepContent, saveState] = useContentState(
stepInitialContent,
isInGuestMode ? SaveStates.Guest : SaveStates.Ok,
useMemo(
() =>
debounceAsync(async (content: StepContent) => {
if (isInGuestMode) {
localStorage.setItem(
GUEST_MODE_CONTENT_STORAGE_KEY,
JSON.stringify(content),
)
return SaveStates.Guest
}
const response = await fetchAPI(
`tactics/${id}/steps/${stepId}`,
{
content: {
components: content.components,
},
},
"PUT",
)
return response.ok ? SaveStates.Ok : SaveStates.Err
}, 250),
[id, isInGuestMode, stepId],
),
)
return (
<EditorView
tactic={{
name: editorName,
id,
courtType,
rootStepNode: initialStepsNode,
}}
currentStepContent={stepContent}
currentStepId={stepId}
setCurrentStepContent={(content) => setStepContent(content, true)}
courtType={courtType}
saveState={saveState}
onContentChange={async (content: StepContent) => {
if (isInGuestMode) {
localStorage.setItem(
GUEST_MODE_CONTENT_STORAGE_KEY,
JSON.stringify(content),
)
return SaveStates.Guest
}
const response = await fetchAPI(
`tactics/${id}/steps/1`,
{ content },
"PUT",
)
if (response.status == 401) {
navigate("/login")
}
return response.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
}
const response = await fetchAPI(
`tactics/${id}/name`,
{ name },
"PUT",
)
if (response.status == 401) {
navigate("/login")
}
return response.ok
}}
selectStep={async (step) => {
const response = await fetchAPIGet(`tactics/${id}/steps/${step}`)
if (!response.ok)
return null
setStepId(step)
setStepContent({ ...await response.json() }, false)
}}
onAddStep={async (parent) => {
const response = await fetchAPI(`tactics/${id}/steps`, {
parentId: parent.id,
})
if (!response.ok) return null
const { stepId } = await response.json()
return { id: stepId, children: [] }
}}
onRemoveStep={async (step) => {
const response = await fetchAPI(
`tactics/${id}/steps/${step.id}`,
{},
"DELETE",
)
return response.ok
}}
/>
)
}
export interface EditorViewProps {
tactic: TacticInfo
currentStepContent: StepContent
currentStepId: number
saveState: SaveState
setCurrentStepContent: Dispatch<SetStateAction<StepContent>>
selectStep: (stepId: number) => void
onNameChange: (name: string) => Promise<boolean>
onRemoveStep: (step: StepInfoNode) => Promise<boolean>
onAddStep: (parent: StepInfoNode) => Promise<StepInfoNode | null>
courtType: "PLAIN" | "HALF"
}
function EditorView({
tactic: { name, rootStepNode: initialStepsNode },
setCurrentStepContent: setContent,
currentStepContent: content,
saveState,
onNameChange,
selectStep,
onRemoveStep,
onAddStep,
courtType,
}: EditorViewProps) {
const [titleStyle, setTitleStyle] = useState<CSSProperties>({})
const [rootStepsNode, setRootStepsNode] = useState(initialStepsNode)
const [allies, setAllies] = useState(() =>
getRackPlayers(PlayerTeam.Allies, content.components),
)
const [opponents, setOpponents] = useState(() =>
getRackPlayers(PlayerTeam.Opponents, content.components),
)
const [objects, setObjects] = useState<RackedCourtObject[]>(() =>
isBallOnCourt(content) ? [] : [{ key: "ball" }],
)
const [previewAction, setPreviewAction] = useState<ActionPreview | null>(
null,
)
const [isStepsTreeVisible, setStepsTreeVisible] = useState(false)
const courtRef = useRef<HTMLDivElement>(null)
const setComponents = (action: SetStateAction<TacticComponent[]>) => {
setContent((c) => ({
...c,
components:
typeof action == "function" ? action(c.components) : action,
}))
}
const courtBounds = useCallback(
() => courtRef.current!.getBoundingClientRect(),
[courtRef],
)
useEffect(() => {
setObjects(isBallOnCourt(content) ? [] : [{ key: "ball" }])
}, [setObjects, content])
const insertRackedPlayer = (player: Player) => {
let setter
switch (player.team) {
case PlayerTeam.Opponents:
setter = setOpponents
break
case PlayerTeam.Allies:
setter = setAllies
}
if (player.ballState == BallState.HOLDS_BY_PASS) {
setObjects([{ key: "ball" }])
}
setter((players) => [
...players,
{
team: player.team,
pos: player.role,
key: player.role,
},
])
}
const doRemovePlayer = useCallback(
(component: PlayerLike) => {
setContent((c) => removePlayer(component, c))
if (component.type == "player") insertRackedPlayer(component)
},
[setContent],
)
const doMoveBall = useCallback(
(newBounds: DOMRect, from?: PlayerLike) => {
setContent((content) => {
if (from) {
content = changePlayerBallState(
from,
BallState.NONE,
content,
)
}
content = placeBallAt(newBounds, courtBounds(), content)
return content
})
},
[courtBounds, setContent],
)
const validatePlayerPosition = useCallback(
(player: PlayerLike, info: PlayerInfo, newPos: Pos) => {
setContent((content) =>
moveComponent(
newPos,
player,
info,
courtBounds(),
content,
(content) => {
if (player.type === "player") insertRackedPlayer(player)
return removePlayer(player, content)
},
),
)
},
[courtBounds, setContent],
)
const renderAvailablePlayerActions = useCallback(
(info: PlayerInfo, player: PlayerLike) => {
let canPlaceArrows: boolean
if (player.type == "player") {
canPlaceArrows =
player.path == null ||
player.actions.findIndex(
(p) => p.type != ActionKind.SHOOT,
) == -1
} else {
const origin = getOrigin(player, content.components)
const path = origin.path!
// phantoms can only place other arrows if they are the head of the path
canPlaceArrows =
path.items.indexOf(player.id) == path.items.length - 1
if (canPlaceArrows) {
// and if their only action is to shoot the ball
const phantomActions = player.actions
canPlaceArrows =
phantomActions.length == 0 ||
phantomActions.findIndex(
(c) => c.type != ActionKind.SHOOT,
) == -1
}
}
return [
canPlaceArrows && (
<CourtPlayerArrowAction
key={1}
player={player}
isInvalid={previewAction?.isInvalid ?? false}
setPreviewAction={setPreviewAction}
playerInfo={info}
content={content}
courtRef={courtRef}
setContent={setContent}
/>
),
(info.ballState === BallState.HOLDS_ORIGIN ||
info.ballState === BallState.PASSED_ORIGIN) && (
<BallAction
key={2}
onDrop={(ballBounds) => {
doMoveBall(ballBounds, player)
}}
/>
),
]
},
[content, doMoveBall, previewAction?.isInvalid, setContent],
)
const renderPlayer = useCallback(
(component: PlayerLike) => {
let info: PlayerInfo
const isPhantom = component.type == "phantom"
if (isPhantom) {
const origin = getOrigin(component, content.components)
info = {
id: component.id,
team: origin.team,
role: origin.role,
pos: computePhantomPositioning(
component,
content,
courtBounds(),
),
ballState: component.ballState,
}
} else {
info = component
}
return (
<CourtPlayer
key={component.id}
className={isPhantom ? "phantom" : "player"}
playerInfo={info}
onPositionValidated={(newPos) =>
validatePlayerPosition(component, info, newPos)
}
onRemove={() => doRemovePlayer(component)}
courtRef={courtRef}
availableActions={() =>
renderAvailablePlayerActions(info, component)
}
/>
)
},
[
content.components,
doRemovePlayer,
renderAvailablePlayerActions,
validatePlayerPosition,
],
)
const doDeleteAction = useCallback(
(_: Action, idx: number, origin: TacticComponent) => {
setContent((content) => removeAction(origin, idx, content))
},
[setContent],
)
const doUpdateAction = useCallback(
(component: TacticComponent, action: Action, actionIndex: number) => {
setContent((content) =>
updateComponent(
{
...component,
actions: component.actions.toSpliced(
actionIndex,
1,
action,
),
},
content,
),
)
},
[setContent],
)
const renderComponent = useCallback(
(component: TacticComponent) => {
if (component.type == "player" || component.type == "phantom") {
return renderPlayer(component)
}
if (component.type == BALL_TYPE) {
return (
<CourtBall
key="ball"
ball={component}
onPosValidated={doMoveBall}
onRemove={() => {
setContent((content) => removeBall(content))
setObjects((objects) => [
...objects,
{ key: "ball" },
])
}}
/>
)
}
throw new Error("unknown tactic component " + component)
},
[renderPlayer, doMoveBall, setContent],
)
const renderActions = useCallback(
(component: TacticComponent) =>
component.actions.map((action, i) => {
return (
<CourtAction
key={"action-" + component.id + "-" + i}
action={action}
origin={component.id}
courtRef={courtRef}
isInvalid={false}
onActionDeleted={() => {
doDeleteAction(action, i, component)
}}
onActionChanges={(action) =>
doUpdateAction(component, action, i)
}
/>
)
}),
[doDeleteAction, doUpdateAction],
)
return (
<div id="main-div">
<div id="topbar-div">
<div id="topbar-left">
<SavingState state={saveState} />
</div>
<div id="title-input-div">
<TitleInput
style={titleStyle}
default_value={name}
onValidated={useCallback(
(new_name) => {
onNameChange(new_name).then((success) => {
setTitleStyle(success ? {} : ERROR_STYLE)
})
},
[onNameChange],
)}
/>
</div>
<div id="topbar-right">
<button onClick={() => setStepsTreeVisible((b) => !b)}>
STEPS
</button>
</div>
</div>
<div id="editor-div">
<div id="content-div">
<div id="racks">
<PlayerRack
id={"allies"}
objects={allies}
setObjects={setAllies}
setComponents={setComponents}
courtRef={courtRef}
/>
<Rack
id={"objects"}
objects={objects}
onChange={setObjects}
canDetach={useCallback(
(div) =>
overlaps(
courtBounds(),
div.getBoundingClientRect(),
),
[courtBounds],
)}
onElementDetached={useCallback(
(r, e: RackedCourtObject) =>
setContent((content) =>
placeObjectAt(
r.getBoundingClientRect(),
courtBounds(),
e,
content,
),
),
[courtBounds, setContent],
)}
render={renderCourtObject}
/>
<PlayerRack
id={"opponents"}
objects={opponents}
setObjects={setOpponents}
setComponents={setComponents}
courtRef={courtRef}
/>
</div>
<div id="court-div">
<div id="court-div-bounds">
<BasketCourt
components={content.components}
courtImage={<Court courtType={courtType} />}
courtRef={courtRef}
previewAction={previewAction}
renderComponent={renderComponent}
renderActions={renderActions}
/>
</div>
</div>
</div>
<EditorStepsTree
isVisible={isStepsTreeVisible}
root={rootStepsNode}
onAddChildren={useCallback(
async (parent) => {
const addedNode = await onAddStep(parent)
if (addedNode == null) {
console.error(
"could not add step : onAddStep returned null node",
)
return
}
setRootStepsNode((root) =>
addStepNode(root, parent, addedNode),
)
},
[onAddStep],
)}
onRemoveNode={useCallback(
async (removed) => {
const isOk = await onRemoveStep(removed)
if (isOk)
setRootStepsNode(
(root) => removeStepNode(root, removed)!,
)
},
[onRemoveStep],
)}
onStepSelected={useCallback(
(node) => selectStep(node.id),
[selectStep],
)}
/>
</div>
</div>
)
}
interface EditorStepsTreeProps {
isVisible: boolean
root: StepInfoNode
onAddChildren: (parent: StepInfoNode) => void
onRemoveNode: (node: StepInfoNode) => void
onStepSelected: (node: StepInfoNode) => void
}
function EditorStepsTree({
isVisible,
root,
onAddChildren,
onRemoveNode,
onStepSelected,
}: EditorStepsTreeProps) {
return (
<div
id="steps-div"
style={{
transform: isVisible ? "translateX(0)" : "translateX(100%)",
}}>
<StepsTree
root={root}
onStepSelected={onStepSelected}
onAddChildren={onAddChildren}
onRemoveNode={onRemoveNode}
/>
</div>
)
}
interface PlayerRackProps {
id: string
objects: RackedPlayer[]
setObjects: (state: RackedPlayer[]) => void
setComponents: (
f: (components: TacticComponent[]) => TacticComponent[],
) => void
courtRef: RefObject<HTMLDivElement>
}
function PlayerRack({
id,
objects,
setObjects,
courtRef,
setComponents,
}: PlayerRackProps) {
const courtBounds = useCallback(
() => courtRef.current!.getBoundingClientRect(),
[courtRef],
)
return (
<Rack
id={id}
objects={objects}
onChange={setObjects}
canDetach={useCallback(
(div) => overlaps(courtBounds(), div.getBoundingClientRect()),
[courtBounds],
)}
onElementDetached={useCallback(
(r, e: RackedPlayer) =>
setComponents((components) => [
...components,
placePlayerAt(
r.getBoundingClientRect(),
courtBounds(),
e,
),
]),
[courtBounds, setComponents],
)}
render={useCallback(
({ team, key }: { team: PlayerTeam; key: string }) => (
<PlayerPiece
team={team}
text={key}
key={key}
hasBall={false}
/>
),
[],
)}
/>
)
}
interface CourtPlayerArrowActionProps {
playerInfo: PlayerInfo
player: PlayerLike
isInvalid: boolean
content: StepContent
setContent: (state: SetStateAction<StepContent>) => void
setPreviewAction: (state: SetStateAction<ActionPreview | null>) => void
courtRef: RefObject<HTMLDivElement>
}
function CourtPlayerArrowAction({
playerInfo,
player,
isInvalid,
content,
setContent,
setPreviewAction,
courtRef,
}: CourtPlayerArrowActionProps) {
const courtBounds = useCallback(
() => courtRef.current!.getBoundingClientRect(),
[courtRef],
)
return (
<ArrowAction
key={1}
onHeadMoved={(headPos) => {
const arrowHeadPos = middlePos(headPos)
const targetIdx = getComponentCollided(
headPos,
content.components,
)
const target = content.components[targetIdx]
setPreviewAction((action) => ({
...action!,
segments: [
{
next: ratioWithinBase(arrowHeadPos, courtBounds()),
},
],
type: getActionKind(target, playerInfo.ballState).kind,
isInvalid:
!overlaps(headPos, courtBounds()) ||
!isActionValid(player, target, content.components),
}))
}}
onHeadPicked={(headPos) => {
;(document.activeElement as HTMLElement).blur()
setPreviewAction({
origin: playerInfo.id,
type: getActionKind(null, playerInfo.ballState).kind,
target: ratioWithinBase(headPos, courtBounds()),
segments: [
{
next: ratioWithinBase(
middlePos(headPos),
courtBounds(),
),
},
],
isInvalid: false,
})
}}
onHeadDropped={(headRect) => {
if (isInvalid) {
setPreviewAction(null)
return
}
setContent((content) => {
let { createdAction, newContent } = createAction(
player,
courtBounds(),
headRect,
content,
)
if (createdAction.type == ActionKind.SHOOT) {
const targetIdx = newContent.components.findIndex(
(c) => c.id == createdAction.target,
)
newContent = dropBallOnComponent(
targetIdx,
newContent,
false,
)
const ballState =
player.ballState === BallState.HOLDS_ORIGIN
? BallState.PASSED_ORIGIN
: BallState.PASSED
newContent = updateComponent(
{
...(newContent.components.find(
(c) => c.id == player.id,
)! as PlayerLike),
ballState,
},
newContent,
)
}
return newContent
})
setPreviewAction(null)
}}
/>
)
}
function isBallOnCourt(content: StepContent) {
return (
content.components.findIndex(
(c) =>
((c.type === "player" || c.type === "phantom") &&
(c.ballState === BallState.HOLDS_ORIGIN ||
c.ballState === BallState.PASSED_ORIGIN)) ||
c.type === BALL_TYPE,
) != -1
)
}
function renderCourtObject(courtObject: RackedCourtObject) {
if (courtObject.key == "ball") {
return <BallPiece />
}
throw new Error("unknown racked court object " + courtObject.key)
}
function Court({ courtType }: { courtType: string }) {
return (
<div id="court-image-div">
{courtType == "PLAIN" ? (
<PlainCourt id="court-image" />
) : (
<HalfCourt id="court-image" />
)}
</div>
)
}
function debounceAsync<A, B>(
f: (args: A) => Promise<B>,
delay = 1000,
): (args: A) => Promise<B> {
let task = 0
return (args: A) => {
clearTimeout(task)
return new Promise((resolve, reject) => {
task = setTimeout(() => f(args).then(resolve).catch(reject), delay)
})
}
}
function useContentState<S>(
initialContent: S,
initialSaveState: SaveState,
saveStateCallback: (s: S) => Promise<SaveState>,
): [
S,
(newState: SetStateAction<S>, callSaveCallback: boolean) => void,
SaveState,
] {
const [content, setContent] = useState(initialContent)
const [savingState, setSavingState] = useState(initialSaveState)
const setContentSynced = useCallback(
(newState: SetStateAction<S>, callSaveCallback: boolean) => {
setContent((content) => {
const state =
typeof newState === "function"
? (newState as (state: S) => S)(content)
: newState
if (state !== content && callSaveCallback) {
setSavingState(SaveStates.Saving)
saveStateCallback(state)
.then(setSavingState)
.catch(() => setSavingState(SaveStates.Err))
}
return state
})
},
[saveStateCallback],
)
return [content, setContentSynced, savingState]
}