Skip to content

Commit

Permalink
fix & simplify handling of saved turn by moving it to GameSession
Browse files Browse the repository at this point in the history
  • Loading branch information
Konrad Jamrozik committed Jul 7, 2024
1 parent 326b232 commit bff8a78
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 53 deletions.
29 changes: 1 addition & 28 deletions web/src/components/SettingsPanel/SettingsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,6 @@ import { Label } from '../utilities/Label'
export function SettingsPanel(): React.JSX.Element {
const settings: Settings = useSettingsContext()
const gameSession: GameSession = useGameSessionContext()
const [savedTurn, setSavedTurn] = useState(
gameSession.getSavedTurnNoUnsafe() ?? 'N/A',
)

// kja also need to setSavedTurn every time it is changed in local storage,
// e.g. when game is reset or when "save game data" button is pressed.
// I feel the 'savedTurn' should become a property of GameSession.

useEffect(() => {
function handleVisibilityChange(): void {
if (document.visibilityState === 'visible') {
console.log(
`SettingsPanel: Visibility state 'visible' event triggered.`,
)
setSavedTurn(gameSession.getSavedTurnNoUnsafe() ?? 'N/A')
}
}

document.addEventListener('visibilitychange', handleVisibilityChange)

// This is a clean-up function per:
// https://react.dev/reference/react/useEffect#connecting-to-an-external-system
// https://react.dev/learn/synchronizing-with-effects#unmount
return (): void => {
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
}, [])

function handleIntroEnabledChange(
event: React.ChangeEvent<HTMLInputElement>,
Expand Down Expand Up @@ -109,7 +82,7 @@ export function SettingsPanel(): React.JSX.Element {
<ListItem>
<ListItemText primary="Saved turn" />
<Label sx={{ minWidth: 40, marginLeft: 2, textAlign: 'center' }}>
{savedTurn}
{gameSession.savedTurn ?? 'N/A'}
</Label>
</ListItem>
<ListItem sx={{ justifyContent: 'center' }}>
Expand Down
19 changes: 13 additions & 6 deletions web/src/lib/gameSession/GameSession.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/max-params */
/* eslint-disable max-lines */
/* eslint-disable @typescript-eslint/parameter-properties */
import _ from 'lodash'
Expand Down Expand Up @@ -39,9 +40,12 @@ export function useGameSession(storedData: StoredData): GameSession {
)
const [loading, setLoading] = useState<boolean>(false)
const [error, setError] = useState<string>()
const [savedTurn, setSavedTurn] = useState<number | undefined>(
data.turns.at(-1)?.StartState.Timeline.CurrentTurn,
)

console.log(
`render useGameSession. Elapsed: ${measureTiming()}. data: '${Md5.hashStr(JSON.stringify(data))}', loading: '${loading}', error: '${error}'`,
`render useGameSession. Elapsed: ${measureTiming()}. data: '${Md5.hashStr(JSON.stringify(data))}', loading: '${loading}', error: '${error}', savedTurn: '${savedTurn}'`,
)

useEffect(() => {
Expand All @@ -57,6 +61,8 @@ export function useGameSession(storedData: StoredData): GameSession {
setLoading,
error,
setError,
savedTurn,
setSavedTurn,
)
}

Expand All @@ -72,6 +78,10 @@ export class GameSession {
private readonly setError: React.Dispatch<
React.SetStateAction<string | undefined>
>,
public readonly savedTurn: number | undefined,
private readonly setSavedTurn: React.Dispatch<
React.SetStateAction<number | undefined>
>,
) {
this.data = data
}
Expand Down Expand Up @@ -178,9 +188,9 @@ export class GameSession {
/* c8 ignore stop */
this.data.resetCurrentTurn()
}

public resetGame(): void {
this.data.resetData()
this.setSavedTurn(undefined)
this.setError(undefined)
}

Expand Down Expand Up @@ -361,6 +371,7 @@ export class GameSession {

public persistOnExit(): void {
this.data.persistOnExit()
this.setSavedTurn(this.getCurrentTurnNoUnsafe())
}

public getSize(): number {
Expand All @@ -376,10 +387,6 @@ export class GameSession {
return this.data.getCompressionEnabled()
}

public getSavedTurnNoUnsafe(): number | undefined {
return this.data.getSavedTurnNoUnsafe()
}

private async applyPlayerAction(
playerActionPayload: PlayerActionPayload,
): Promise<boolean> {
Expand Down
4 changes: 0 additions & 4 deletions web/src/lib/gameSession/GameSessionData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,6 @@ export class GameSessionData {
return this.storedData.getCompressionEnabled(JSON.stringify(this._data))
}

public getSavedTurnNoUnsafe(): number | undefined {
return this.storedData.getSavedTurnNoUnsafe()
}

private setData(data: GameSessionDataType): void {
GameSessionData.verify(data.turns)
// Uncomment to persist game session data on every update.
Expand Down
15 changes: 0 additions & 15 deletions web/src/lib/storedData/StoredData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ export class StoredData {
public resetGameSessionData(): void {
this.removeFromLocalStorage('gameSessionData')
localStorage.removeItem('gameSessionData_persisted_timestamp')
localStorage.removeItem('gameSessionData_turnNo')
}

public persistGameSessionData(newGameSessionData: GameSessionDataType): void {
Expand All @@ -40,12 +39,6 @@ export class StoredData {
`gameSessionData_persisted_timestamp`,
new Date().toLocaleString(),
)
localStorage.setItem(
`gameSessionData_turnNo`,
newGameSessionData.turns
.at(-1)!
.StartState.Timeline.CurrentTurn.toString(),
)
this.data = { ...this.data, gameSessionData: newGameSessionData }
}

Expand All @@ -67,14 +60,6 @@ export class StoredData {
return json.length >= 4_999_000
}

public getSavedTurnNoUnsafe(): number | undefined {
const turnNo = localStorage.getItem('gameSessionData_turnNo')
if (_.isNil(turnNo)) {
return undefined
}
return _.parseInt(turnNo)
}

// eslint-disable-next-line max-statements
private setInLocalStorage<T extends StoredDataTypeName>(
key: T,
Expand Down

0 comments on commit bff8a78

Please sign in to comment.