Skip to content

Commit

Permalink
WIP: displaying game state info
Browse files Browse the repository at this point in the history
  • Loading branch information
Konrad Jamrozik committed Jul 7, 2024
1 parent 859180d commit 326b232
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 5 deletions.
7 changes: 3 additions & 4 deletions web/src/components/PersistOnExit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import {
} from '../lib/gameSession/GameSession'
import { useSettingsContext, type Settings } from '../lib/settings/Settings'

// kja this does not work reliably:
// Note: PersistOnExit does not work if the data is to be compressed, as it runs too long. See:
// https://stackoverflow.com/questions/78716366/how-much-time-do-i-have-to-save-data-to-local-storage-when-browser-visibility-ch
//
// https://developer.chrome.com/docs/web-platform/page-lifecycle-api
// > Terminated
// > A page is in the terminated state once it has started being unloaded and cleared from memory by the browser. No new tasks can start in this state, and in-progress tasks may be killed if they run too long.
// Also:
// https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API#policies_in_place_to_aid_background_page_performance
// https://developer.mozilla.org/en-US/blog/using-the-page-visibility-api/
// https://stackoverflow.com/questions/78716366/how-much-time-do-i-have-to-save-data-to-local-storage-when-browser-visibility-ch

// https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
// Worse alternative: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
Expand Down Expand Up @@ -45,5 +45,4 @@ export default function PersistOnExit(): React.JSX.Element {
return <div></div>
}

// kja add "Save on exit enabled/disabled" label
// kja add "Save game state to local storage" button
// kja implement "Save game state to local storage" button
30 changes: 29 additions & 1 deletion web/src/components/SettingsPanel/SettingsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ListItemText,
Switch,
} from '@mui/material'
import { useEffect, useState } from 'react'
import {
type GameSession,
useGameSessionContext,
Expand All @@ -19,6 +20,33 @@ 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)
}
}, [])

Check warning on line 49 in web/src/components/SettingsPanel/SettingsPanel.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'gameSession'. Either include it or remove the dependency array

function handleIntroEnabledChange(
event: React.ChangeEvent<HTMLInputElement>,
Expand Down Expand Up @@ -81,7 +109,7 @@ export function SettingsPanel(): React.JSX.Element {
<ListItem>
<ListItemText primary="Saved turn" />
<Label sx={{ minWidth: 40, marginLeft: 2, textAlign: 'center' }}>
{'0'}
{savedTurn}
</Label>
</ListItem>
<ListItem sx={{ justifyContent: 'center' }}>
Expand Down
4 changes: 4 additions & 0 deletions web/src/lib/gameSession/GameSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,10 @@ 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: 4 additions & 0 deletions web/src/lib/gameSession/GameSessionData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ 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: 15 additions & 0 deletions web/src/lib/storedData/StoredData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ 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 @@ -39,6 +40,12 @@ 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 @@ -60,6 +67,14 @@ 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 326b232

Please sign in to comment.