Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[client] improve entity details show/hide #1898

Merged
merged 4 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions client/src/dojo/modelManager/TileManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getDirectionBetweenAdjacentHexes,
getNeighborHexes,
ID,
Position,
RealmLevels,
ResourcesIds,
StructureType,
Expand Down Expand Up @@ -296,15 +297,12 @@ export class TileManager {
});
};

placeStructure = async (entityId: ID, structureType: StructureType, hexCoords: HexPosition) => {
placeStructure = async (entityId: ID, structureType: StructureType, coords: Position) => {
if (structureType == StructureType.Hyperstructure) {
await this.setup.systemCalls.create_hyperstructure({
signer: this.setup.network.burnerManager.account!,
creator_entity_id: entityId,
coords: {
x: hexCoords.col,
y: hexCoords.row,
},
coords,
});
}
};
Expand Down
43 changes: 26 additions & 17 deletions client/src/three/scenes/Worldmap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { HexPosition, SceneName } from "@/types";
import { Position } from "@/types/Position";
import { FELT_CENTER } from "@/ui/config";
import { UNDEFINED_STRUCTURE_ENTITY_ID } from "@/ui/constants";
import { View } from "@/ui/modules/navigation/LeftNavigationModule";
import { getWorldPositionForHex } from "@/ui/utils/utils";
import { BiomeType, getNeighborOffsets, ID } from "@bibliothecadao/eternum";
import { throttle } from "lodash";
Expand All @@ -21,7 +22,6 @@ import Minimap from "../components/Minimap";
import { SelectedHexManager } from "../components/SelectedHexManager";
import { StructureManager } from "../components/StructureManager";
import { StructurePreview } from "../components/StructurePreview";
import { LocationManager } from "../helpers/LocationManager";
import { ArmySystemUpdate, TileSystemUpdate } from "../systems/types";
import { HexagonScene } from "./HexagonScene";
import { HEX_SIZE, PREVIEW_BUILD_COLOR_INVALID } from "./constants";
Expand Down Expand Up @@ -240,31 +240,40 @@ export default class WorldmapScene extends HexagonScene {
return !isStructure && isExplored && !isOcean;
}

protected onHexagonDoubleClick(hexCoords: HexPosition) {
const position = new Position({ x: hexCoords.col, y: hexCoords.row });
const isBattle = this.battleManager.battles.hasByPosition(position);
if (isBattle) return;
const url = position.toHexLocationUrl();
LocationManager.updateUrl(url);
}
protected onHexagonDoubleClick(hexCoords: HexPosition) {}

protected onHexagonClick(hexCoords: HexPosition | null) {
if (!hexCoords) {
return;
}
if (!hexCoords) return;

const buildingType = this.structurePreview?.getPreviewStructure();

if (buildingType && this._canBuildStructure(hexCoords)) {
const normalizedHexCoords = { col: hexCoords.col + FELT_CENTER, row: hexCoords.row + FELT_CENTER };
this.tileManager.placeStructure(this.structureEntityId, buildingType.type, normalizedHexCoords);
this.clearEntitySelection();
this.handleStructurePlacement(hexCoords);
} else {
const position = getWorldPositionForHex(hexCoords);
this.handleHexSelection(hexCoords);
}
}

protected handleStructurePlacement(hexCoords: HexPosition) {
const buildingType = this.structurePreview?.getPreviewStructure();
if (!buildingType) return;

const contractHexPosition = new Position({ x: hexCoords.col, y: hexCoords.row }).getContract();
this.tileManager.placeStructure(this.structureEntityId, buildingType.type, contractHexPosition);
this.clearEntitySelection();
}

protected handleHexSelection(hexCoords: HexPosition) {
const contractHexPosition = new Position({ x: hexCoords.col, y: hexCoords.row }).getContract();
const position = getWorldPositionForHex(hexCoords);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding a comment here to explain the new behavior of showing entity details on the second click of the same hex.

Suggested change
const position = getWorldPositionForHex(hexCoords);
const position = getWorldPositionForHex(hexCoords);
// If the same hex is clicked again, show entity details

if (contractHexPosition.x !== this.state.selectedHex?.col || contractHexPosition.y !== this.state.selectedHex.row) {
this.selectedHexManager.setPosition(position.x, position.z);
this.state.setSelectedHex({
col: hexCoords.col + FELT_CENTER,
row: hexCoords.row + FELT_CENTER,
col: contractHexPosition.x,
row: contractHexPosition.y,
});
} else {
this.state.setLeftNavigationView(View.EntityView);
}
}

Expand Down
51 changes: 34 additions & 17 deletions client/src/ui/components/structures/worldmap/StructureCard.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { configManager } from "@/dojo/setup";
import { useDojo } from "@/hooks/context/DojoContext";
import { ArmyInfo, getArmyByEntityId } from "@/hooks/helpers/useArmies";
import { useQuery } from "@/hooks/helpers/useQuery";
import { useStructureAtPosition } from "@/hooks/helpers/useStructures";
import useUIStore from "@/hooks/store/useUIStore";
import { Position } from "@/types/Position";
Expand All @@ -10,9 +11,10 @@ import { ResourceIcon } from "@/ui/elements/ResourceIcon";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/elements/Tabs";
import { getTotalTroops } from "@/ui/modules/military/battle-view/BattleHistory";
import { currencyFormat, formatNumber } from "@/ui/utils/utils";
import { EternumGlobalConfig, ID, ResourcesIds } from "@bibliothecadao/eternum";
import { ID, ResourcesIds } from "@bibliothecadao/eternum";
import { useComponentValue } from "@dojoengine/react";
import { getEntityIdFromKeys } from "@dojoengine/utils";
import clsx from "clsx";
import { ArrowRight } from "lucide-react";
import { useMemo, useState } from "react";
import { ResourceExchange } from "../../hyperstructures/ResourceExchange";
Expand All @@ -30,10 +32,31 @@ export const StructureCard = ({
const [showMergeTroopsPopup, setShowMergeTroopsPopup] = useState<boolean>(false);
const structure = useStructureAtPosition(position.getContract());

const { handleUrlChange } = useQuery();

const goToHexView = () => {
const url = position.toHexLocationUrl();
handleUrlChange(url);
};

return (
Boolean(structure) && (
<div className={`px-2 py-2 ${className}`}>
Structure
<div className="flex flex-row">
Structure
<div className="ml-2">
<Button
variant="outline"
size="xs"
className={clsx("self-center")}
onClick={() => {
goToHexView();
}}
>
{"View"}
</Button>
</div>
</div>
{!showMergeTroopsPopup && (
<StructureListItem
structure={structure!}
Expand Down Expand Up @@ -180,7 +203,7 @@ const TroopExchange = ({
const totalTroopsReceiver = useMemo(() => {
return (
BigInt(Object.values(attackerArmyTroops || {}).reduce((a, b) => Number(a) + Number(b), 0)) /
BigInt(EternumGlobalConfig.resources.resourcePrecision)
BigInt(configManager.getResourcePrecision())
);
}, [attackerArmyTroops]);

Expand Down Expand Up @@ -213,10 +236,9 @@ const TroopExchange = ({
const fromArmy = transferDirection === "to" ? getArmy(giverArmyEntityId) : takerArmy || getArmy(protector!.army_id);
const toArmy = transferDirection === "to" ? takerArmy || getArmy(protector!.army_id) : getArmy(giverArmyEntityId);
const transferedTroops = {
knight_count: troopsGiven[ResourcesIds.Knight] * BigInt(EternumGlobalConfig.resources.resourceMultiplier),
paladin_count: troopsGiven[ResourcesIds.Paladin] * BigInt(EternumGlobalConfig.resources.resourceMultiplier),
crossbowman_count:
troopsGiven[ResourcesIds.Crossbowman] * BigInt(EternumGlobalConfig.resources.resourceMultiplier),
knight_count: troopsGiven[ResourcesIds.Knight] * BigInt(configManager.getResourcePrecision()),
paladin_count: troopsGiven[ResourcesIds.Paladin] * BigInt(configManager.getResourcePrecision()),
crossbowman_count: troopsGiven[ResourcesIds.Crossbowman] * BigInt(configManager.getResourcePrecision()),
};
await army_merge_troops({
signer: account,
Expand Down Expand Up @@ -270,17 +292,15 @@ const TroopExchange = ({
<p
className={`${
transferDirection === "to" &&
troopsGiven[Number(resourceId)] * BigInt(EternumGlobalConfig.resources.resourceMultiplier) !== 0n
troopsGiven[Number(resourceId)] * BigInt(configManager.getResourcePrecision()) !== 0n
? "text-red"
: ""
}`}
>
{transferDirection === "to"
? `[${currencyFormat(
Number(
amount -
troopsGiven[Number(resourceId)] *
BigInt(EternumGlobalConfig.resources.resourceMultiplier),
amount - troopsGiven[Number(resourceId)] * BigInt(configManager.getResourcePrecision()),
),
0,
)}]`
Expand All @@ -291,7 +311,7 @@ const TroopExchange = ({
{transferDirection === "to" && (
<NumberInput
className="col-span-3 rounded-lg"
max={Number(amount) / EternumGlobalConfig.resources.resourceMultiplier}
max={Number(amount) / configManager.getResourcePrecision()}
min={0}
step={100}
value={Number(troopsGiven[Number(resourceId)])}
Expand Down Expand Up @@ -331,18 +351,15 @@ const TroopExchange = ({
<p
className={`${
transferDirection === "from" &&
troopsGiven[Number(resourceId)] * BigInt(EternumGlobalConfig.resources.resourceMultiplier) !==
0n
troopsGiven[Number(resourceId)] * BigInt(configManager.getResourcePrecision()) !== 0n
? "text-red"
: ""
}`}
>
{transferDirection === "from"
? `[${currencyFormat(
Number(
amount -
troopsGiven[Number(resourceId)] *
BigInt(EternumGlobalConfig.resources.resourceMultiplier),
amount - troopsGiven[Number(resourceId)] * BigInt(configManager.getResourcePrecision()),
),
0,
)}]`
Expand Down
36 changes: 36 additions & 0 deletions client/src/ui/elements/KeyBoardKey.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export const KeyBoardKey = ({
keyName,
invertColors,
size = "sm",
bounce = true,
className,
}: {
keyName: string;
invertColors?: boolean;
size?: "sm" | "md" | "lg";
bounce?: boolean;
className?: string;
}) => {
const sizeClasses = {
sm: "w-4 h-4 text-xxs",
md: "w-5 h-5 text-xs",
lg: "w-6 h-6 text-sm",
};

return (
<span
className={`
font-bold rounded
flex items-center justify-center
border-2 shadow-lg
${sizeClasses[size]}
${invertColors ? "text-black border-black" : "text-gold border-gold"}
${bounce ? "animate-bounce" : ""}
transition-all duration-200 hover:scale-110
${className || ""}
`}
>
{keyName.toUpperCase()}
</span>
);
};
38 changes: 29 additions & 9 deletions client/src/ui/modules/navigation/LeftNavigationModule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import { useEntitiesUtils } from "@/hooks/helpers/useEntities";
import { MarketModal } from "@/ui/components/trading/MarketModal";
import { BuildingThumbs, MenuEnum } from "@/ui/config";
import { BaseContainer } from "@/ui/containers/BaseContainer";
import { KeyBoardKey } from "@/ui/elements/KeyBoardKey";
import clsx from "clsx";
import { motion } from "framer-motion";
import { Suspense, lazy, useMemo, useState } from "react";
import { Suspense, lazy, useEffect, useMemo, useState } from "react";
import {
construction,
military,
Expand Down Expand Up @@ -93,19 +94,38 @@ export const LeftNavigationModule = () => {
[structureInfo],
);

useEffect(() => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good addition of the key press event listener for the 'E' key. This implements the requirement to show entity details when 'E' is pressed.

const handleKeyPress = (event: KeyboardEvent) => {
switch (event.key.toLowerCase()) {
case "e":
setView(view === View.EntityView ? View.None : View.EntityView);
break;
}
};

window.addEventListener("keydown", handleKeyPress);

return () => {
window.removeEventListener("keydown", handleKeyPress);
};
}, [view, setView, toggleModal]);

const navigation = useMemo(() => {
const baseNavigation = [
{
name: MenuEnum.entityDetails,
button: (
<CircleButton
image={BuildingThumbs.hex}
tooltipLocation="top"
label="Details"
active={view === View.EntityView}
size="xl"
onClick={() => setView(view === View.EntityView ? View.None : View.EntityView)}
/>
<div className="relative">
<CircleButton
image={BuildingThumbs.hex}
tooltipLocation="top"
label="Details"
active={view === View.EntityView}
size="xl"
onClick={() => setView(view === View.EntityView ? View.None : View.EntityView)}
/>
<KeyBoardKey invertColors={view === View.EntityView} className="absolute top-1 right-1" keyName="E" />
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice addition of the KeyBoardKey component to visually indicate the 'E' shortcut for entity details.

</div>
),
},
{
Expand Down
Loading