Skip to content

Commit

Permalink
fix(online): [fixes #442] Show correct peer cow state (#445)
Browse files Browse the repository at this point in the history
* fix(online): [closes #422] show offered cows with accurate label and value
* test(cows): validate price/value display
* refactor(types): define CowCardProps
* refactor(types): fix CowCard type errors
* refactor(types): fix CowCard Subheader type errors
  • Loading branch information
jeremyckahn authored Aug 27, 2023
1 parent 81e1c52 commit 7cbbf1a
Show file tree
Hide file tree
Showing 6 changed files with 177 additions and 99 deletions.
100 changes: 72 additions & 28 deletions src/components/CowCard/CowCard.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/** @typedef {import('../../handlers/ui-events')['default']} farmhand.uiHandlers */
/** @typedef {import('../../components/Farmhand/Farmhand').farmhand.state} farmhand.state */
/** @typedef {import('../../components/Farmhand/Farmhand').default} Farmhand */
/** @typedef {import('../../index').farmhand.cow} farmhand.cow */
/** @typedef {import('../../index').farmhand.cowBreedingPen} farmhand.cowBreedingPen */
import React, { useEffect, useRef, useState } from 'react'

import { array, bool, func, number, object, string } from 'prop-types'
Expand Down Expand Up @@ -35,42 +40,78 @@ const genderIcons = {
[genders.MALE]: faMars,
}

export const CowCard = ({
allowCustomPeerCowNames,
cow,
cowBreedingPen,
cowIdOfferedForTrade,
cowInventory,
debounced,
handleCowAutomaticHugChange,
handleCowBreedChange,
handleCowHugClick,
handleCowOfferClick,
handleCowPurchaseClick,
handleCowWithdrawClick,
handleCowSellClick,
handleCowTradeClick,
id,
inventory,
isCowOfferedForTradeByPeer,
isSelected,
isOnline,
money,
purchasedCowPen,
/**
* @typedef {{
* allowCustomPeerCowNames: boolean,
* cow: farmhand.cow,
* cowBreedingPen: farmhand.cowBreedingPen,
* cowInventory: farmhand.state['cowInventory'],
* cowIdOfferedForTrade: farmhand.cow['id'],
* debounced: Farmhand['handlers']['debounced'],
* handleCowAutomaticHugChange: farmhand.uiHandlers['handleCowAutomaticHugChange'],
* handleCowBreedChange: farmhand.uiHandlers['handleCowBreedChange'],
* handleCowHugClick: farmhand.uiHandlers['handleCowHugClick'],
* handleCowOfferClick: farmhand.uiHandlers['handleCowOfferClick'],
* handleCowPurchaseClick: farmhand.uiHandlers['handleCowPurchaseClick'],
* handleCowWithdrawClick: farmhand.uiHandlers['handleCowWithdrawClick'],
* handleCowSellClick: farmhand.uiHandlers['handleCowSellClick'],
* handleCowTradeClick: farmhand.uiHandlers['handleCowTradeClick'],
* id: farmhand.state['id'],
* inventory: farmhand.state['inventory'],
* isCowOfferedForTradeByPeer: boolean,
* isSelected: boolean,
* isOnline: boolean,
* money: farmhand.state['money'],
* purchasedCowPen: farmhand.state['purchasedCowPen'],
* huggingMachinesRemain?: boolean,
* }} CowCardProps
*/

huggingMachinesRemain = areHuggingMachinesInInventory(inventory),
}) => {
export const CowCard = (
/**
* @type CowCardProps
*/
{
allowCustomPeerCowNames,
cow,
cowBreedingPen,
cowIdOfferedForTrade,
cowInventory,
debounced,
handleCowAutomaticHugChange,
handleCowBreedChange,
handleCowHugClick,
handleCowOfferClick,
handleCowPurchaseClick,
handleCowWithdrawClick,
handleCowSellClick,
handleCowTradeClick,
id,
inventory,
isCowOfferedForTradeByPeer,
isSelected,
isOnline,
money,
purchasedCowPen,

huggingMachinesRemain = areHuggingMachinesInInventory(inventory),
}
) => {
const cowDisplayName = getCowDisplayName(cow, id, allowCustomPeerCowNames)

const [displayName, setDisplayName] = useState(cowDisplayName)
const [cowImage, setCowImage] = useState(pixel)
const cardRef = useRef()
const scrollAnchorRef = useRef()

// @see https://github.com/microsoft/TypeScript/issues/27387#issuecomment-659671940
const cardRef = useRef(/** @type {Element|null} */ (null))
const scrollAnchorRef = useRef(/** @type {HTMLAnchorElement|null} */ (null))

const isCowPurchased =
!!cowInventory.find(({ id }) => id === cow.id) &&
!isCowOfferedForTradeByPeer
const cowValue = getCowValue(cow, isCowPurchased)

// cow.originalOwnerId is only an empty string when it is for sale.
const cowValue = getCowValue(cow, cow.originalOwnerId !== '')
const cowCanBeTradedAway =
isOnline && !isCowInBreedingPen(cow, cowBreedingPen)
const canCowBeTradedFor = Boolean(
Expand Down Expand Up @@ -181,7 +222,7 @@ export const CowCard = ({
disabled:
cowValue > money ||
cowInventory.length >=
PURCHASEABLE_COW_PENS.get(purchasedCowPen).cows,
(PURCHASEABLE_COW_PENS.get(purchasedCowPen)?.cows ?? 0),
onClick: () => handleCowPurchaseClick(cow),
variant: 'contained',
}}
Expand Down Expand Up @@ -308,6 +349,9 @@ CowCard.propTypes = {
purchasedCowPen: number.isRequired,
}

/**
* @param {CowCardProps} props
*/
export default function Consumer(props) {
return (
<FarmhandContext.Consumer>
Expand Down
74 changes: 54 additions & 20 deletions src/components/CowCard/Subheader/Subheader.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/** @typedef {import('../../../components/Farmhand/Farmhand').farmhand.state} farmhand.state */
/** @typedef {import('../../../index').farmhand.cow} farmhand.cow */
/** @typedef {import('../CowCard').CowCardProps} CowCardProps */
import React from 'react'
import { array, bool, func, object, string } from 'prop-types'
import Checkbox from '@material-ui/core/Checkbox'
Expand Down Expand Up @@ -26,37 +29,66 @@ import './Subheader.sass'

// The extra 0.5 is for rounding up to the next full heart. This allows a fully
// happy cow to have full hearts on the beginning of a new day.
/**
* @param {number} heartIndex
* @param {number} numberOfFullHearts
*/
const isHeartFull = (heartIndex, numberOfFullHearts) =>
heartIndex + 0.5 < numberOfFullHearts

const getCowMapById = memoize(cowInventory =>
cowInventory.reduce((acc, cow) => {
acc[cow.id] = cow
return acc
}, {})
const getCowMapById = memoize(
/**
* @param {farmhand.state['cowInventory']} cowInventory
*/
cowInventory =>
cowInventory.reduce((acc, cow) => {
acc[cow.id] = cow
return acc
}, {})
)

const Subheader = ({
canCowBeTradedFor,
cow,
cowBreedingPen,
cowIdOfferedForTrade,
cowInventory,
cowValue,
handleCowAutomaticHugChange,
handleCowBreedChange,
huggingMachinesRemain,
id: playerId,
isCowPurchased,
}) => {
/**
* @typedef {Pick<
* CowCardProps,
* 'cow' |
* 'cowBreedingPen' |
* 'cowIdOfferedForTrade' |
* 'cowInventory' |
* 'handleCowAutomaticHugChange' |
* 'handleCowBreedChange' |
* 'huggingMachinesRemain' |
* 'id'
* > & {
* canCowBeTradedFor: boolean,
* cowValue: number,
* isCowPurchased: boolean,
* }} SubheaderProps
*/

const Subheader = (
/** @type {SubheaderProps} */
{
canCowBeTradedFor,
cow,
cowBreedingPen,
cowIdOfferedForTrade,
cowInventory,
cowValue,
handleCowAutomaticHugChange,
handleCowBreedChange,
huggingMachinesRemain,
id: playerId,
isCowPurchased,
}
) => {
const numberOfFullHearts = cow.happiness * 10
const isInBreedingPen = isCowInBreedingPen(cow, cowBreedingPen)
const isRoomInBreedingPen =
cowBreedingPen.cowId1 === null || cowBreedingPen.cowId2 === null
const isThisCowOfferedForTrade = cowIdOfferedForTrade === cow.id

const mateId = cowBreedingPen.cowId1 ?? cowBreedingPen.cowId2
const mate = getCowMapById(cowInventory)[mateId]
const mate = getCowMapById(cowInventory)[mateId ?? '']
const isEligibleToBreed = cow.gender !== mate?.gender

const canBeMovedToBreedingPen =
Expand All @@ -80,7 +112,9 @@ const Subheader = ({
)}
<p>Color: {COW_COLOR_NAMES[cow.color]}</p>
<p>
{isCowPurchased ? 'Value' : 'Price'}: {moneyString(cowValue)}
{/* cow.originalOwnerId is only an empty string when it is for sale. */}
{cow.originalOwnerId === '' ? 'Price' : 'Value'}:{' '}
{moneyString(cowValue)}
</p>
<p>Weight: {getCowWeight(cow)} lbs.</p>
{(isCowPurchased || canCowBeTradedFor) && (
Expand Down
50 changes: 32 additions & 18 deletions src/components/CowCard/Subheader/Subheader.test.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import React from 'react'
import { render } from '@testing-library/react'
import { render, screen } from '@testing-library/react'

import { generateCow } from '../../../utils'
import { cowColors } from '../../../enums'
import { getCowStub } from '../../../test-utils/stubs/cowStub'
import { moneyString } from '../../../utils/moneyString'

import Subheader from './Subheader'

const COW_VALUE = 1000

describe('Subheader', () => {
let baseProps

beforeEach(() => {
jest.spyOn(Math, 'random').mockReturnValue(0)
baseProps = {
canCowBeTradedFor: false,
cow: generateCow({
color: cowColors.WHITE,
happiness: 0,
name: '',
baseWeight: 100,
}),
cow: getCowStub(),
cowBreedingPen: { cowId1: null, cowId2: null, daysUntilBirth: -1 },
cowIdOfferedForTrade: '',
cowInventory: [],
cowValue: 1000,
cowValue: COW_VALUE,
huggingMachinesRemain: false,
id: '',
isCowPurchased: false,
Expand Down Expand Up @@ -52,11 +49,8 @@ describe('Subheader', () => {
<Subheader
{...{
...baseProps,
cow: generateCow({
color: cowColors.WHITE,
cow: getCowStub({
happiness: 0.5,
name: '',
baseWeight: 100,
}),
isCowPurchased: true,
}}
Expand All @@ -71,11 +65,8 @@ describe('Subheader', () => {
<Subheader
{...{
...baseProps,
cow: generateCow({
color: cowColors.WHITE,
cow: getCowStub({
happiness: 1,
name: '',
baseWeight: 100,
}),
isCowPurchased: true,
}}
Expand All @@ -86,4 +77,27 @@ describe('Subheader', () => {
})
})
})

describe('price/value display', () => {
test('displays price for cows that can be purchased', () => {
render(
<Subheader {...baseProps} cow={getCowStub({ originalOwnerId: '' })} />
)

const price = screen.getByText(`Price: ${moneyString(COW_VALUE)}`)
expect(price).toBeInTheDocument()
})

test('displays value for cows that have been purchased', () => {
render(
<Subheader
{...baseProps}
cow={getCowStub({ originalOwnerId: 'abc123' })}
/>
)

const value = screen.getByText(`Value: ${moneyString(COW_VALUE)}`)
expect(value).toBeInTheDocument()
})
})
})
9 changes: 5 additions & 4 deletions src/handlers/ui-events.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* @typedef {import("../index").farmhand.item} item
* @typedef {import("../index").farmhand.keg} keg
* @typedef {import("../index").farmhand.cow} farmhand.cow
*/
import { saveAs } from 'file-saver'
import window from 'global/window'
Expand Down Expand Up @@ -110,15 +111,15 @@ export default {
},

/**
* @param {external:React.SyntheticEvent} e
* @param {React.SyntheticEvent} e
* @param {farmhand.cow} cow
*/
handleCowAutomaticHugChange({ target: { checked } }, cow) {
this.changeCowAutomaticHugState(cow, checked)
},

/**
* @param {external:React.SyntheticEvent} e
* @param {React.SyntheticEvent} e
* @param {farmhand.cow} cow
*/
handleCowBreedChange({ target: { checked } }, cow) {
Expand Down Expand Up @@ -147,7 +148,7 @@ export default {
},

/**
* @param {external:React.SyntheticEvent} e
* @param {React.SyntheticEvent} e
* @param {farmhand.cow} cow
*/
handleCowNameInputChange({ target: { value } }, cow) {
Expand All @@ -163,7 +164,7 @@ export default {
},

/**
* @param {external:React.SyntheticEvent} e
* @param {React.SyntheticEvent} e
*/
handleViewChange({ target: { value } }) {
this.setState({ stageFocus: value })
Expand Down
Loading

0 comments on commit 7cbbf1a

Please sign in to comment.