@seriousgaming/sdk-tools 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +4055 -2646
- package/dist/client.js +807 -172
- package/dist/core/session-host.d.ts +4 -2
- package/dist/core/settings-locks.d.ts +27 -2
- package/dist/dev/console/assets/{index-DEV8N0na.js → index-BVF8exas.js} +22 -22
- package/dist/dev/console/index.html +1 -1
- package/dist/dev/public-origins.d.ts +61 -0
- package/dist/dev/routes.d.ts +4 -0
- package/dist/dev/shell.d.ts +32 -4
- package/dist/dev/view/batch.d.ts +7 -1
- package/dist/docs/ai-agents.md +5 -0
- package/dist/docs/api/index.md +1 -1
- package/dist/docs/api/sdk-tools-client.md +1 -0
- package/dist/docs/api/sdk.md +79 -2
- package/dist/docs/changelog-0.x.md +2 -2
- package/dist/docs/changelog.md +62 -4
- package/dist/docs/cli-and-dev-server.md +58 -0
- package/dist/docs/cli-error-codes.md +39 -36
- package/dist/docs/cli-reference.md +68 -21
- package/dist/docs/concepts/terminology.md +1 -1
- package/dist/docs/environment-variables.md +10 -5
- package/dist/docs/guides/ai-facilitation.md +2 -0
- package/dist/docs/guides/capabilities.md +4 -0
- package/dist/docs/guides/designing-a-game.md +2 -0
- package/dist/docs/guides/designing-screens.md +133 -0
- package/dist/docs/guides/endpoints.md +4 -2
- package/dist/docs/guides/engine-testing.md +6 -2
- package/dist/docs/guides/engine.md +2 -0
- package/dist/docs/guides/file-handling.md +116 -22
- package/dist/docs/guides/games.md +3 -1
- package/dist/docs/guides/global-settings.md +2 -0
- package/dist/docs/guides/guide.md +2 -0
- package/dist/docs/guides/hooks.md +2 -0
- package/dist/docs/guides/index.md +9 -0
- package/dist/docs/guides/internationalization.md +2 -0
- package/dist/docs/guides/llm-integration.md +5 -3
- package/dist/docs/guides/multi-team-games.md +3 -1
- package/dist/docs/guides/patterns.md +2 -0
- package/dist/docs/guides/presentation.md +1 -1
- package/dist/docs/guides/production-constraints.md +2 -0
- package/dist/docs/guides/scenario-editor.md +3 -1
- package/dist/docs/guides/scenarios.md +15 -3
- package/dist/docs/guides/session-game-flow.md +365 -0
- package/dist/docs/guides/session-hooks.md +205 -0
- package/dist/docs/guides/session.md +27 -565
- package/dist/docs/guides/settings.md +64 -2
- package/dist/docs/guides/setup.md +3 -1
- package/dist/docs/guides/speech-generation.md +2 -0
- package/dist/docs/guides/starter-game.md +61 -21
- package/dist/docs/guides/testing.md +2 -0
- package/dist/docs/guides/tick-controller.md +3 -1
- package/dist/docs/guides/type-safety.md +2 -0
- package/dist/docs/guides/ui-files-and-llms.md +328 -0
- package/dist/docs/guides/ui-participants.md +281 -0
- package/dist/docs/guides/ui-styling.md +263 -0
- package/dist/docs/guides/ui-ticks.md +247 -0
- package/dist/docs/guides/ui.md +11 -1092
- package/dist/docs/guides/upgrading.md +2 -0
- package/dist/docs/guides/validators.md +64 -4
- package/dist/docs/guides/waiting-room.md +1 -1
- package/dist/docs/index.md +2 -1
- package/dist/docs/page-index.md +145 -0
- package/dist/docs/recipes/adapt-a-game-for-walkthroughs.md +1 -1
- package/dist/docs/recipes/adapt-ui-for-observers.md +1 -1
- package/dist/docs/recipes/create-presentation.md +11 -0
- package/dist/docs/recipes/create-scenario-editor.md +1 -0
- package/dist/docs/recipes/create-session-ui.md +2 -1
- package/dist/docs/recipes/create-setup.md +1 -0
- package/dist/docs/recipes/create-user-interface.md +1 -0
- package/dist/docs/recipes/create-waiting-room-ui.md +1 -0
- package/dist/docs/recipes/design-state-for-concurrent-writes.md +1 -1
- package/dist/docs/recipes/fix-duplicate-packages.md +2 -2
- package/dist/docs/recipes/index.md +3 -0
- package/dist/docs/recipes/screenshot-a-surface.md +80 -0
- package/dist/docs/recipes/test-a-multi-role-game.md +1 -1
- package/dist/docs/recipes/upload-and-display-files.md +7 -7
- package/dist/docs/recipes/use-request-tick.md +2 -2
- package/dist/docs/recipes/validate-scenarios.md +4 -1
- package/dist/execution/config-resolver.d.ts +4 -1
- package/dist/execution/endpoint-runner.d.ts +6 -0
- package/dist/execution/logic-calls.d.ts +7 -2
- package/dist/execution/scenario-gates.d.ts +21 -1
- package/dist/guide/settings.d.ts +1 -1
- package/dist/host.js +64 -2
- package/dist/runtime/manifest-version.d.ts +1 -1
- package/dist/runtime.js +7 -2
- package/dist/storage/asset-resolver.d.ts +24 -1
- package/dist/storage/blob-store.d.ts +7 -0
- package/dist/templates/package/CLAUDE.md.template +14 -5
- package/dist/templates/package/DESIGN.md.liquid +39 -7
- package/dist/templates/package/README.md.liquid +1 -1
- package/dist/templates/package/claude/rules/workflow-create-user-interface.md +1 -1
- package/dist/templates/package/pnpm-workspace.yaml.template +13 -0
- package/dist/templates/starter-game/capabilities/pacing/capability.sdk.json +18 -0
- package/dist/templates/starter-game/package.json +2 -0
- package/dist/templates/starter-game/presentation/defaults.ts +52 -0
- package/dist/templates/starter-game/presentation/index.html +20 -0
- package/dist/templates/starter-game/presentation/presentation.sdk.json +10 -0
- package/dist/templates/starter-game/presentation/src/App.tsx +55 -0
- package/dist/templates/starter-game/presentation/src/Band.tsx +40 -0
- package/dist/templates/starter-game/presentation/src/Slides.tsx +415 -0
- package/dist/templates/starter-game/presentation/src/WeatherIcon.tsx +21 -0
- package/dist/templates/starter-game/presentation/src/i18n.ts +88 -0
- package/dist/templates/starter-game/presentation/src/main.tsx +15 -0
- package/dist/templates/starter-game/presentation/src/stalls.test.ts +196 -0
- package/dist/templates/starter-game/presentation/src/stalls.ts +199 -0
- package/dist/templates/starter-game/presentation/types.ts +94 -0
- package/dist/templates/starter-game/seriousgaming.sdk.json +2 -1
- package/dist/templates/starter-game/session/defaults.ts +6 -0
- package/dist/templates/starter-game/session/index.html +1 -1
- package/dist/templates/starter-game/session/session.sdk.json +2 -2
- package/dist/templates/starter-game/session/src/App.test.tsx +436 -115
- package/dist/templates/starter-game/session/src/App.tsx +372 -222
- package/dist/templates/starter-game/session/src/JoinCodes.tsx +184 -0
- package/dist/templates/starter-game/session/src/ManagePanel.tsx +188 -0
- package/dist/templates/starter-game/session/src/Results.tsx +340 -0
- package/dist/templates/starter-game/session/src/SessionBar.tsx +179 -0
- package/dist/templates/starter-game/session/src/SessionPanels.tsx +105 -0
- package/dist/templates/starter-game/session/src/SidePanel.tsx +89 -0
- package/dist/templates/starter-game/session/src/StallCard.tsx +253 -0
- package/dist/templates/starter-game/session/src/TopBar.tsx +36 -0
- package/dist/templates/starter-game/session/src/i18n.ts +91 -24
- package/dist/templates/starter-game/session/src/status.ts +28 -0
- package/dist/templates/starter-game/session/types.ts +8 -2
- package/dist/templates/starter-game/shared/Awning.tsx +31 -0
- package/dist/templates/starter-game/shared/HostLogo.test.tsx +38 -0
- package/dist/templates/starter-game/shared/HostLogo.tsx +48 -0
- package/dist/templates/starter-game/shared/StallIcons.tsx +83 -0
- package/dist/templates/starter-game/shared/days.ts +11 -0
- package/dist/templates/starter-game/shared/format.test.ts +13 -0
- package/dist/templates/starter-game/{ui/src → shared}/format.ts +1 -1
- package/dist/templates/starter-game/testing/e2e/game.spec.ts +42 -8
- package/dist/templates/starter-game/ui/defaults.ts +3 -0
- package/dist/templates/starter-game/ui/src/App.test.tsx +197 -29
- package/dist/templates/starter-game/ui/src/App.tsx +176 -99
- package/dist/templates/starter-game/ui/src/DayBar.test.tsx +50 -7
- package/dist/templates/starter-game/ui/src/DayBar.tsx +96 -38
- package/dist/templates/starter-game/ui/src/DaysTable.tsx +69 -0
- package/dist/templates/starter-game/ui/src/FirstDay.tsx +37 -0
- package/dist/templates/starter-game/ui/src/Header.tsx +257 -0
- package/dist/templates/starter-game/ui/src/Lesson.tsx +63 -0
- package/dist/templates/starter-game/ui/src/MakeRow.tsx +98 -71
- package/dist/templates/starter-game/ui/src/Notices.tsx +59 -0
- package/dist/templates/starter-game/ui/src/PastDay.tsx +88 -0
- package/dist/templates/starter-game/ui/src/Section.tsx +26 -26
- package/dist/templates/starter-game/ui/src/ThemeToggle.tsx +25 -11
- package/dist/templates/starter-game/ui/src/TodayPanel.test.tsx +37 -33
- package/dist/templates/starter-game/ui/src/TodayPanel.tsx +66 -52
- package/dist/templates/starter-game/ui/src/WeatherCard.tsx +47 -0
- package/dist/templates/starter-game/ui/src/WeekOver.tsx +145 -0
- package/dist/templates/starter-game/ui/src/YesterdayPanel.tsx +65 -114
- package/dist/templates/starter-game/ui/src/days.ts +58 -0
- package/dist/templates/starter-game/ui/src/i18n.ts +86 -32
- package/dist/templates/starter-game/ui/src/test-helpers.ts +1 -0
- package/dist/templates/starter-game/ui/src/theme.ts +8 -8
- package/dist/templates/starter-game/ui/types.ts +6 -0
- package/dist/templates/starter-game/ui/ui.sdk.json +1 -1
- package/dist/templates/starter-game/validators/daylimit/defaults.ts +13 -0
- package/dist/templates/starter-game/validators/daylimit/logic/logic.test.ts +20 -0
- package/dist/templates/starter-game/validators/daylimit/logic/logic.ts +23 -0
- package/dist/templates/starter-game/validators/daylimit/types.ts +23 -0
- package/dist/templates/starter-game/validators/daylimit/validator.sdk.json +10 -0
- package/dist/templates/starter-game/waiting_room/src/App.test.tsx +83 -5
- package/dist/templates/starter-game/waiting_room/src/App.tsx +262 -119
- package/dist/templates/starter-game/waiting_room/src/i18n.ts +8 -4
- package/dist/utils/error-codes.d.ts +12 -0
- package/dist/utils/local-refs.d.ts +40 -0
- package/dist/utils/schema-members.d.ts +19 -0
- package/package.json +11 -4
- package/dist/templates/starter-game/session/src/Section.tsx +0 -37
- package/dist/templates/starter-game/session/src/TeamDoor.tsx +0 -96
- package/dist/templates/starter-game/session/src/format.ts +0 -8
- package/dist/templates/starter-game/ui/src/HistoryPanel.test.tsx +0 -74
- package/dist/templates/starter-game/ui/src/HistoryPanel.tsx +0 -120
- package/dist/templates/starter-game/ui/src/HostLogo.test.tsx +0 -25
- package/dist/templates/starter-game/ui/src/HostLogo.tsx +0 -38
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
# Ticks and the timer in user interfaces
|
|
2
|
+
|
|
3
|
+
How a game UI ends a round and shows the time left: requesting a tick, awaiting a write or tick and handling a `MutationError`, and driving a countdown from the tick timer.
|
|
4
|
+
|
|
5
|
+
It is part of [Building user interfaces](./ui.md), which covers creating the surface and reading and writing context.
|
|
6
|
+
|
|
7
|
+
**Keywords:** requestTick, tick, end round, MutationError, MutationOutcome, await setData, tick timer, countdown, nextTickAt, pause, resume, simulated game time
|
|
8
|
+
|
|
9
|
+
## Requesting a tick
|
|
10
|
+
|
|
11
|
+
User interfaces advance the game to the next tick using the `requestTick` callback. This is how games provide their 'Submit' control. There is no built-in next tick button, so every game that ticks manually needs one of these.
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { useUserInterfaceCallbacks } from '@seriousgaming/sdk/ui';
|
|
15
|
+
|
|
16
|
+
function DecisionPanel() {
|
|
17
|
+
const callbacks = useUserInterfaceCallbacks();
|
|
18
|
+
|
|
19
|
+
const handleSubmit = () => {
|
|
20
|
+
callbacks.requestTick?.();
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
return (
|
|
24
|
+
<button onClick={handleSubmit}>
|
|
25
|
+
Submit Decision
|
|
26
|
+
</button>
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
During development, the dev drawer (press the backtick key) also has a developer-only **Tick** button, so you can advance the game before your control exists.
|
|
32
|
+
|
|
33
|
+
See [Host controls](./games.md#host-controls) for what the host renders and what is left to your game.
|
|
34
|
+
|
|
35
|
+
### Combining setData with requestTick
|
|
36
|
+
|
|
37
|
+
A common pattern is to update context and immediately request a tick: for example, a 'Start exercise' button that sets an initial value and advances the game:
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
const handleStart = () => {
|
|
41
|
+
setData({ exercise: { Started: true } });
|
|
42
|
+
callbacks.requestTick?.();
|
|
43
|
+
};
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
This works correctly: the `setData` change is merged into context immediately, and the tick that follows will see `Started: true` when the engine runs. However, there is a brief intermediate state that is worth understanding:
|
|
47
|
+
|
|
48
|
+
1. **`setData` merges immediately**: the local UI and all connected UIs see `Started: true` right away
|
|
49
|
+
2. **`requestTick` is asynchronous**: the tick message is sent to the host, which queues and executes the tick. This takes a few milliseconds
|
|
50
|
+
3. **Between steps 1 and 2**, UIs see the `setData` change but the engine has not yet run. If the engine computes derived values (e.g. a status message based on `Started`), the UI will briefly show the raw `setData` values without the engine-computed results
|
|
51
|
+
4. **After the tick completes**, the host broadcasts updated context to all UIs. This overwrites the intermediate state with the fully computed post-tick values
|
|
52
|
+
|
|
53
|
+
In most cases this intermediate state is invisible to the participant, because the tick completes in milliseconds. But if your UI derives display values from both `setData` fields and engine-computed fields, you may see a brief flicker. Two strategies to handle this:
|
|
54
|
+
|
|
55
|
+
**Option A: UI-level loading state**: set a local loading flag before requesting the tick, and clear it when new context arrives:
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
const [ticking, setTicking] = useState(false);
|
|
59
|
+
|
|
60
|
+
const handleStart = () => {
|
|
61
|
+
setData({ exercise: { Started: true } });
|
|
62
|
+
setTicking(true);
|
|
63
|
+
callbacks.requestTick?.();
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Clear on next context push (setData from host resets the component)
|
|
67
|
+
useEffect(() => {
|
|
68
|
+
setTicking(false);
|
|
69
|
+
}, [data]);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Option B: Drive display from engine-computed values only**: if possible, have your UI read from the engine's output capability rather than from the raw `setData` input. The engine output is only updated after the tick, so there is no intermediate state.
|
|
73
|
+
|
|
74
|
+
### Awaiting state changes
|
|
75
|
+
|
|
76
|
+
`setData` and `requestTick` each return a promise, as do a session UI's `undoTick` and `resetGame` and a setup screen or scenario editor's `updateSettings`. It resolves once the operation has committed (a `setData` once the write is persisted, a `requestTick` once that tick has finished and context is updated) and rejects with a `MutationError` when it fails. The error's `outcome` is a discriminated union you can branch on:
|
|
77
|
+
|
|
78
|
+
- `conflict`: the write lost a race with a tick, and the runtime retried it itself and gave up. A person may try again; your code never retries it on its own
|
|
79
|
+
- `superseded`: what the operation addressed has already moved on because somebody else did the same thing, such as a tick button pressed twice. Terminal but not a failure: the state is what the caller asked for
|
|
80
|
+
- `validation-rejected`: a validator rejected the write; `outcome.rejections` carries the same detail delivered to `useUserInterfaceValidationRejections`
|
|
81
|
+
- `denied`: the operation was not permitted (for example, a write of a capability this UI does not declare in `writes`)
|
|
82
|
+
- `tick-failed`: the tick could not run (tick limit reached, game complete, or the executor threw)
|
|
83
|
+
- `error`: anything else unexpected
|
|
84
|
+
|
|
85
|
+
The list is closed, so a `switch` over `outcome.kind` can be exhaustive. A kind a later release adds reaches only a game that declares the feature that adds it in `requires`; any other game is told `error`.
|
|
86
|
+
|
|
87
|
+
Reach for `useMutationReporter` rather than branching by hand. It awaits the write, tracks whether one is in flight, and hands you the failure to render:
|
|
88
|
+
|
|
89
|
+
```tsx
|
|
90
|
+
import { useMutationReporter } from '@seriousgaming/sdk/ui';
|
|
91
|
+
|
|
92
|
+
const { run, pending, failure, dismiss } = useMutationReporter();
|
|
93
|
+
|
|
94
|
+
<Button disabled={pending} onClick={() => run(() => setData({ exercise: { Revenue: 100 } }))}>
|
|
95
|
+
{t('save')}
|
|
96
|
+
</Button>;
|
|
97
|
+
{
|
|
98
|
+
failure && (
|
|
99
|
+
<Alert
|
|
100
|
+
onClose={dismiss}
|
|
101
|
+
action={failure.retry && <Button onClick={failure.retry}>{t('tryAgain')}</Button>}
|
|
102
|
+
>
|
|
103
|
+
{t('saveFailed')}
|
|
104
|
+
</Alert>
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`setData` also resolves with which tick the write landed in. If a participant submits as the tick is being processed the write commits into the next one, and `reporter.late` says so, carrying both the tick composed against and the tick committed into. That is not a failure (the write is in), but nothing else on screen distinguishes it from a decision that arrived in time.
|
|
110
|
+
|
|
111
|
+
**The host retries; your surface never does.** A runtime using optimistic concurrency retries a losing write itself before it reports one, so a `conflict` reaching a surface is a write the host has already retried and given up on, and a surface must never retry it automatically. What a person can do is try again, so on a `conflict` (and only then) `failure.retry` is set: it runs the same operation again, resolving as `run` does. Put it behind a 'Try again' button, as the snippet above does, and never call it from an effect or a timer.
|
|
112
|
+
|
|
113
|
+
Ignoring the returned promise still compiles, but it is a hazard rather than a convenience: the local view merges the change the moment it is sent, so a refused write leaves the participant looking at a decision the game never received. A no-floating-promises lint rule may start flagging unawaited calls; route them through `run` rather than marking them with `void`.
|
|
114
|
+
|
|
115
|
+
> Note: against a hosted runtime that does not yet send the correlated acknowledgement, an awaited mutation stays pending until the connection resets. The dev server always responds, so promises settle promptly in local development.
|
|
116
|
+
|
|
117
|
+
## Displaying the tick timer
|
|
118
|
+
|
|
119
|
+
When a game uses an automatic [tick controller](./tick-controller.md), the host pushes the current schedule to every UI via the `useUserInterfaceTimer` hook, as a `TimerState`. Use this when you want your UI to show its own countdown: for example, a circular progress bar in the corner of a Decisions panel, or a floating 'Next tick in 12s' badge on a results screen.
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import { useUserInterfaceTimer } from '@seriousgaming/sdk/ui';
|
|
123
|
+
|
|
124
|
+
function NextTickBadge() {
|
|
125
|
+
const { enabled, paused, nextTickAt, intervalMs } = useUserInterfaceTimer();
|
|
126
|
+
|
|
127
|
+
if (!enabled || nextTickAt === null) {
|
|
128
|
+
return null; // manual game, or no tick currently scheduled
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const remainingMs = nextTickAt - Date.now();
|
|
132
|
+
return <span>Next tick in {Math.ceil(remainingMs / 1000)}s</span>;
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The fields are those of [`TimerState`](../api/sdk-ui.md#timerstate), the one timer shape every surface reads. Durations are milliseconds and end in `Ms`; timestamps are milliseconds since the epoch, in `Date.now()` space, and end in `At`. Which field to reach for:
|
|
137
|
+
|
|
138
|
+
- **`enabled`** is false for a manual-tick game, or once the controller stops scheduling: hide the countdown
|
|
139
|
+
- **`nextTickAt - Date.now()`** is the time left, and **`intervalMs`** the length of the window, for a progress bar. Both are `null` when nothing is scheduled
|
|
140
|
+
- **`paused`** and **`pausedAt`** say whether, and since when, the host has paused ticking
|
|
141
|
+
- **`extendedMs`** is how far a facilitator has moved the current deadline (negative when pulled in), reset with each new tick. Read it to say 'extended by 2m' rather than inferring that from a moved `nextTickAt`
|
|
142
|
+
- **`scheduleStartedAt`** and **`pausedMs`** drive a [simulated game clock](#simulated-game-time)
|
|
143
|
+
|
|
144
|
+
The hook always returns a value: there is no 'loading' state. Before any timer message has arrived, and for games that don't use a tick controller at all, it returns a disabled timer: `enabled` and `paused` false, every timestamp and `intervalMs` `null`, and `pausedMs` and `extendedMs` 0. The `enabled` check is enough to hide the countdown for manual games without any extra branching.
|
|
145
|
+
|
|
146
|
+
### Driving the countdown
|
|
147
|
+
|
|
148
|
+
The hook only fires when the _schedule_ changes: typically once per tick (when the next interval is computed) plus pause/resume events. It does **not** push a new value every second. UIs that want a live ticking countdown must run their own loop locally:
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
import { useUserInterfaceTimer } from '@seriousgaming/sdk/ui';
|
|
152
|
+
import { useEffect, useState } from 'react';
|
|
153
|
+
|
|
154
|
+
function NextTickCountdown() {
|
|
155
|
+
const { enabled, paused, nextTickAt, intervalMs } = useUserInterfaceTimer();
|
|
156
|
+
const [remainingMs, setRemainingMs] = useState(() =>
|
|
157
|
+
nextTickAt === null ? 0 : Math.max(0, nextTickAt - Date.now())
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
useEffect(() => {
|
|
161
|
+
if (!enabled || nextTickAt === null) {
|
|
162
|
+
setRemainingMs(0);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (paused) {
|
|
166
|
+
// Hold the displayed value steady while paused.
|
|
167
|
+
setRemainingMs(Math.max(0, nextTickAt - Date.now()));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
let raf = 0;
|
|
171
|
+
const loop = () => {
|
|
172
|
+
setRemainingMs(Math.max(0, nextTickAt - Date.now()));
|
|
173
|
+
raf = requestAnimationFrame(loop);
|
|
174
|
+
};
|
|
175
|
+
raf = requestAnimationFrame(loop);
|
|
176
|
+
return () => cancelAnimationFrame(raf);
|
|
177
|
+
}, [enabled, paused, nextTickAt]);
|
|
178
|
+
|
|
179
|
+
if (!enabled || nextTickAt === null) return null;
|
|
180
|
+
|
|
181
|
+
const seconds = Math.ceil(remainingMs / 1000);
|
|
182
|
+
const progress = intervalMs ? 1 - remainingMs / intervalMs : 0;
|
|
183
|
+
return (
|
|
184
|
+
<div>
|
|
185
|
+
<span>{seconds}s</span>
|
|
186
|
+
<progress value={progress} max={1} />
|
|
187
|
+
</div>
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
This pattern is deliberate: by keeping the per-frame state inside one leaf component, only that component re-renders 60 times a second, and the rest of your UI is untouched. If you instead put the live remaining time into a context or shared state, every consumer of that context would re-render on every frame, which can quickly become expensive in a non-trivial UI.
|
|
193
|
+
|
|
194
|
+
### How `nextTickAt` and clocks interact
|
|
195
|
+
|
|
196
|
+
`nextTickAt` is an absolute timestamp in the **same clock-space as `Date.now()`**, so consumer code never needs to compute clock offsets: just subtract. The host is responsible for stamping it in a clock the consumer will recognise:
|
|
197
|
+
|
|
198
|
+
- For dev-server-hosted games (the default), the dev server, the console and your iframe all share `Date.now()`, so `nextTickAt` is correct as-is
|
|
199
|
+
- For cross-machine deployments, hosts rely on NTP-synced wall clocks. NTP keeps machines within tens of milliseconds of each other, well below the granularity of a second-level countdown
|
|
200
|
+
|
|
201
|
+
The wrapper does not attempt to re-translate `nextTickAt` on receipt. With only the value and the receiver's `Date.now()` it cannot distinguish 'the host's clock is N ms ahead of mine' from 'this message has been sitting around for N ms', and getting that wrong is exactly how a stored timer state replayed to a remounted iframe would drift. Trusting the timestamp verbatim is what makes the countdown stay accurate when the iframe is remounted.
|
|
202
|
+
|
|
203
|
+
### Pause and resume
|
|
204
|
+
|
|
205
|
+
When the host pauses the timer (e.g. via the dev server's pause button: see [Pausing, resuming and extending](./tick-controller.md#pausing-resuming-and-extending) in the tick controller guide), the hook returns `{ enabled: true, paused: true, nextTickAt: null, intervalMs: null }`. The `nextTickAt: null` tells you there is no scheduled fire-time to count down toward; freeze your displayed value rather than letting it tick to zero. When the host resumes, a new schedule is pushed and the countdown picks up from the new `nextTickAt`.
|
|
206
|
+
|
|
207
|
+
If you want the displayed value to _freeze_ at the moment of pause (rather than disappear), capture the last non-null `nextTickAt` in a ref:
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
const lastScheduledRef = useRef<number | null>(null);
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
if (nextTickAt !== null) lastScheduledRef.current = nextTickAt;
|
|
213
|
+
}, [nextTickAt]);
|
|
214
|
+
|
|
215
|
+
const displayTick = nextTickAt ?? lastScheduledRef.current;
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Simulated game time
|
|
219
|
+
|
|
220
|
+
If your game compresses real time into simulated time (e.g. 1 real second = 1 simulated hour), you need a clock that advances with wall time but freezes during pauses. The `pausedAt`, `pausedMs`, and `scheduleStartedAt` fields make this possible without any client-side persistence:
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
import { useUserInterfaceTimer } from '@seriousgaming/sdk/ui';
|
|
224
|
+
|
|
225
|
+
const COMPRESSION = 3600; // 1 real second = 1 simulated hour
|
|
226
|
+
|
|
227
|
+
function SimulatedClock() {
|
|
228
|
+
const { scheduleStartedAt, pausedMs, pausedAt } = useUserInterfaceTimer();
|
|
229
|
+
|
|
230
|
+
if (scheduleStartedAt === null) return null;
|
|
231
|
+
|
|
232
|
+
// Effective elapsed time = wall time minus all pauses (completed + current)
|
|
233
|
+
const effectiveElapsedMs =
|
|
234
|
+
(Date.now() - scheduleStartedAt)
|
|
235
|
+
- pausedMs
|
|
236
|
+
- (pausedAt ? Date.now() - pausedAt : 0);
|
|
237
|
+
|
|
238
|
+
const simMinutes = Math.floor((effectiveElapsedMs * COMPRESSION) / 60_000);
|
|
239
|
+
const hours = Math.floor(simMinutes / 60);
|
|
240
|
+
const mins = simMinutes % 60;
|
|
241
|
+
return <span>{hours}h {mins}m</span>;
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
`pausedMs` accumulates the duration of all _completed_ pauses. It does not include the pause currently in progress, which is derived live from `pausedAt`. This avoids the host having to push updates during a pause while still giving clients a fully accurate value at any instant.
|
|
246
|
+
|
|
247
|
+
Both `pausedMs` and `scheduleStartedAt` reset when the tick controller disables ticking (returns `enabled: false` or `null`). They are **not** reset when the game reaches max ticks or is marked complete, so UIs can still display the final session time after the game ends.
|