summaryrefslogtreecommitdiff
path: root/server/PORTING.md
blob: cc5bdc2e16d09f4dfffc346be04b11971eac122e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# Phase 1 Porting Conventions

This document defines the exact rules for porting the reference app's game engine
(`FrosthavenAssistant/frosthaven_assistant/lib/` — **read-only**) into this package
(`server/lib/core/`). Every file in `lib/core/` and `test/` must follow these rules.

## 1. Path and import mapping

| Reference (`package:frosthaven_assistant/...`) | New (`package:x_haven_server/...`) |
|---|---|
| `lib/Model/<x>.dart` | `lib/core/models/<x>.dart` |
| `lib/Resource/state/game_state.dart` (+ part files) | `lib/core/state/game_state.dart` (+ part files, **same part structure**) |
| `lib/Resource/state/<x>.dart` (part files) | `lib/core/state/<x>.dart` |
| `lib/Resource/<x>_methods.dart` (part files) | `lib/core/methods/<x>_methods.dart` |
| `lib/Resource/commands/<x>.dart` | `lib/core/commands/<x>.dart` |
| `lib/Resource/line_builder/<x>.dart` | `lib/core/line_builder/<x>.dart` |
| `lib/Resource/<x>.dart` (top-level) | `lib/core/<x>.dart` |
| `lib/l10n/<x>.dart` | `lib/core/l10n/<x>.dart` |
| `lib/services/service_locator.dart` | `lib/core/service_locator.dart` |
| `lib/services/translation_service.dart` | `lib/core/translation_service.dart` |

Import rewrites (apply to every ported file):

- `package:frosthaven_assistant/Resource/...` → `package:x_haven_server/core/...`
  (`Resource/state/x.dart` → `core/state/x.dart`, `Resource/commands/x.dart` →
  `core/commands/x.dart`, `Model/x.dart` → `core/models/x.dart`, `l10n/x.dart` →
  `core/l10n/x.dart`)
- `package:flutter/foundation.dart`, `package:flutter/material.dart`,
  `package:flutter/widgets.dart`, `package:flutter/cupertino.dart`,
  `package:flutter/services.dart` → **delete** (and delete the symbols they
  provide: `ValueNotifier`, `ValueListenable`, `ChangeNotifier`, `kDebugMode`,
  `debugPrint`, `rootBundle`, `WidgetsFlutterBinding`, `@immutable`)
- `package:shared_preferences/shared_preferences.dart` → **delete** (see §6)
- `dart:developer` (`log`) → `package:logging` (`Logger`), keep the messages
- `../../services/service_locator.dart` → the ported `package:x_haven_server/core/service_locator.dart`

**Part files keep their part structure exactly.** `core/state/game_state.dart`
declares the same 18 `part` directives as the reference (the 7 `*_methods.dart`
files now live in `core/methods/` — part paths become
`part '../methods/character_methods.dart'` etc.). Part files start with
`part of 'game_state.dart';` unchanged. Part files share the library's imports,
so the main `game_state.dart` import list must keep everything the parts use.

## 2. ValueNotifier / ChangeNotifier removal

The server has no local observers — state goes out over the network later.
Conversion rules (apply everywhere, including in part files and commands):

- `final _x = ValueNotifier<T>(v);` + `ValueListenable<T> get x => _x;`
  → `T _x = v;` + `T get x => _x;`
- `final x = ValueNotifier<T>(v);` (public field, e.g. in `Settings`,
  `ActionHandler`) → `T x = v;`
- Reads: `x.value` → `x`, `_x.value` → `_x`
- Writes: `_x.value = v` → `_x = v`, `x.value = v` → `x = v`
- `ValueNotifier<ElementState>` values inside `Map<Elements, ...>` → plain
  `ElementState`
- `elementStateFor(Elements e)` returns `ElementState`, not a listenable
- `ChangeNotifier` subclasses: drop `extends ChangeNotifier`, drop
  `notifyListeners()` calls and `addListener`/`removeListener` from UI code.
  `CardStack` becomes a plain class (its `notifyListeners()` calls are deleted).
- `ListUpdateNotifier` is deleted; `ActionHandler.updateList` is deleted and its
  `notify()` call sites become `gameState.notifyListeners()`.
- `GameState` gains a minimal observer hook (used by the network layer in
  Phase 2, harmless now):
  ```dart
  final List<void Function()> _listeners = [];
  void addListener(void Function() listener) => _listeners.add(listener);
  void removeListener(void Function() listener) => _listeners.remove(listener);
  void notifyListeners() => [..._listeners].forEach((l) => l());
  ```
  Keep `_notifyCurrentList()` (it does real note-row reflow) — it now ends with
  `notifyListeners()`. Keep `notifyAllMonsterInstances()`; the per-item
  `_notifyMonsterInstances()` / `_notifySummonList()` calls become no-op stubs
  (keep the method bodies empty with a `// UI-only in the reference app` comment,
  or delete the calls — but do NOT delete the `notifyAllMonsterInstances` loop).
- `GameState.pendingAutoAddDialog` → plain `List<RoomMonsterData>?`
- `GameState.currentListNotifier` → **deleted** (UI-only); keep the
  `currentList` getter returning `BuiltList.of(_currentList)`.
- `built_collection` stays (`BuiltList`/`BuiltMap`/`BuiltSet` getters unchanged).

## 3. What is kept verbatim

- **All public API signatures** of commands, state classes, and method classes —
  constructor argument order (positional vs named), parameter names, method
  names — so the ported test suite works with minimal edits. Example:
  `AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1)` keeps its
  positional constructor.
- `Command` abstract class and the `_StateModifier` capability token (they live
  in `game_state.dart` as in the reference).
- All `toJson()` / `toString()` / `fromJson` / `updateFromJson` serialization
  code — this is the wire/snapshot format. Do not rename keys.
- `GameSaveState` structure and behavior, including the quirk that
  `GameState.load()` appends a (possibly empty) save state
  (`gameSaveStates.length` grows by 2 across `save()` + `load()`).
- `ActionHandler` history semantics: 250-deep undo, command + description +
  save-state lists, redo truncation, `getCurrent()`, `resetCommandHistory()`,
  `clearLocalCommands()`, `insertReceivedDescription`.
- `GameEvent` sealed hierarchy + `toJsonString` — unchanged.
- `describe()` strings still come from `commandL10n` (ported, see §5).
- `enums.dart` — port as-is (no flutter deps).

## 4. What is stripped

- **UI calls inside engine code:**
  - `MainList.scrollToTop()` (in `draw_command.dart`, `next_round_command.dart`,
    `scenario_methods.dart`) → delete the call and the import.
  - `Future.delayed(Duration(milliseconds: 600), () { _gameState.updateList.notify(); MainList.scrollToTop(); })`
    blocks → delete entirely (draw_command, next_round_command).
  - `WidgetsFlutterBinding.ensureInitialized()` → delete.
- **Network-awareness in `ActionHandler` / `Settings`:** the
  `isServer` / `isClient` branching in `ActionHandler.action/undo/redo` is
  removed — the new server is *always* the server. There is no
  `Communication`, `Network`, or `Client` object. `Settings` drops the
  `server`, `client`, `lastKnownConnection`, `lastKnownPort`,
  `lastKnownHostIP`, `connectClientOnStartup` fields and the `init()`/
  `setFullscreen()`/window-manager code.
  - `ActionHandler` constructor: `ActionHandler({required GameState gameState})`.
  - After executing a command (and after undo/redo), instead of the network
    send, call an optional hook so the Phase 2 layer can broadcast:
    ```dart
    /// Set by the network layer (Phase 2); null in tests.
    void Function(int index, String description, String eventJson)? onAction;
    ```
  - `Settings.loadSave/saveState/deleteSave/loadCharacterSave/saveCharacterState/
    deleteCharacterSave` and the `saves` / `characterSaves` maps stay (plain
    `Map<String, String>` now).
- **Disk persistence via `shared_preferences`** → replaced by `SaveStore` (§6).
  `Settings` disk persistence is dropped entirely for now (Phase 6); keep
  `toString()` and add `loadFromData(String json)` with the same field parsing
  as the reference `loadFromDisk` (minus network fields).
- **`app_constants.dart` and `scaling.dart` are NOT ported in Phase 1**
  (pure UI). Remove the `setMaxWidth()` call from Settings.
- `ui_utils.dart` is ported **minimally**: only `reducePowerEnabled()`
  (reads `settings.powerMode`), used by `line_builder`.
- `theme_switcher.dart` — not ported (UI).
- `translation_service.dart` is ported with **disk loading** of
  `server/assets/i18n/<locale>.json` (see `game_data.dart` for the disk
  pattern); drop `ChangeNotifier` + `updateAllUI` calls.

## 5. l10n and `commandL10n`

- Port `lib/l10n/app_localizations*.dart` to `core/l10n/` as generated pure-Dart
  files. The per-locale files are copied essentially verbatim (they are string
  classes; keep the `initializeMessages` functions and `intl` usage).
- `app_localizations.dart`: keep the `AppLocalizations` class, the
  `AppLocalizationsEn`/`...De` etc. classes, `supportedLocales`, and
  `lookupAppLocalizations(Locale)`. **Delete** the `LocalizationsDelegate`,
  `WidgetsBinding`, `AppLocalizations.of(context)` machinery.
- `dart:ui`'s `Locale` is not available in pure Dart — define it once in
  `core/l10n/app_localizations.dart`:
  ```dart
  class Locale {
    const Locale(this.languageCode, [this.countryCode]);
    final String languageCode;
    final String? countryCode;
    @override
    String toString() => countryCode == null ? languageCode : '$languageCode-$countryCode';
  }
  ```
  and use it in `lookupAppLocalizations`.
- `commands/command_l10n.dart` ports as in the reference (reads
  `getIt<Settings>().locale`, falls back to English) but uses the local `Locale`.

## 6. Save store (replaces shared_preferences)

New file `core/save_store.dart`:

```dart
/// Persistent store for the authoritative game-state snapshot.
abstract class SaveStore {
  String? read();
  void write(String data);
  void clear();
}

class InMemorySaveStore implements SaveStore { ... }  // plain String?

class FileSaveStore implements SaveStore {           // sync file under saves/
  FileSaveStore(String directory) : _file = File(p.join(directory, 'game.json'));
  void write(String data) => _file.writeAsString(data, flush: true);
  String? read() => _file.existsSync() ? _file.readAsStringSync() : null;
  void clear() { if (_file.existsSync()) _file.deleteSync(); }
}
```

- `GameSaveState.saveToDisk` / `loadFromDisk` become **synchronous**
  (`void`), reading/writing through `getIt<SaveStore>()`.
  (`GameState.save()` / `load()` remain sync as in the reference — in the
  reference these were fire-and-forget async prefs writes; the sync file store
  preserves observable behavior and is what Phase 2 needs: save-before-broadcast.)
- Tests register `InMemorySaveStore`; `bin/main.dart` registers
  `FileSaveStore('saves')`.

## 7. `GameData` — disk-based

`GameData.loadData(String root)` keeps its signature (`root` is a directory
path, e.g. `'assets/testData/'` in tests, `'assets/data/'` in production) but
reads with `dart:io` instead of `rootBundle`:

- `rootBundle.loadString('${root}summons.json')` → `File(p.join(root, 'summons.json')).readAsString()`
- same for `${root}editions/editions.json` and `${root}rooms/$campaign.json`
- drop `evict(...)` / `cache: false` (file reads are fresh every time)
- `modelData` → plain `Map<String, CampaignModel> modelData = {}`

## 8. `service_locator.dart`

```dart
final getIt = GetIt.instance;

void setupCore({SaveStore? saveStore, Settings? settings, GameData? gameData, GameState? gameState}) {
  getIt.unregister... // not needed — keep the simple version:
}
```

Keep the reference shape but register only what exists server-side:

```dart
void setupCore({SaveStore? saveStore}) {
  getIt.registerLazySingleton<SaveStore>(() => saveStore ?? InMemorySaveStore());
  getIt.registerLazySingleton<GameData>(() => GameData());
  getIt.registerLazySingleton<Settings>(() => Settings());
  getIt.registerLazySingleton<GameState>(() => GameState());
  getIt.registerLazySingleton<TranslationService>(() => TranslationService());
}
```

(`GameState()` constructs its own `ActionHandler` — see the ported
`game_state.dart` constructor: `GameState({Settings? settings})`.)

Tests may call `setupCore()` once in `setUpAll` and then re-register singletons
between tests if a test file needs fresh state — port test files keep whatever
pattern the reference tests use (`setupGetIt()` → `setupCore()`).

## 8b. line_builder — Phase 1 scope

The reference `line_builder/` produces Flutter widgets (`RichText`,
`AnimatedText`, `BoxDecoration`) to render ability lines in the app. The web
client re-implements that rendering in Phase 4. In Phase 1, only the
**game-logic** parts are ported to `core/line_builder/`:

- `stat_applier.dart` — ported in full (pure logic: `applyMonsterStats` and
  friends return `List<String>`, resolved against game state).
- `line_builder.dart` — minimal port: the `LineBuilder` class with the
  `tokens` map, `isElement(String)`, and any other pure-logic helpers that
  `stat_applier.dart` needs. Do NOT port the widget-building methods
  (`createLines`, `createAbilityText`, padding/margin metrics).
- `line_styles.dart`, `token_applier.dart`, `frosthaven_converter.dart` —
  **not ported** (pure UI styling/rendering).

Corresponding tests: port `stat_applier_test.dart` and the `isElement` group
of `line_builder_test.dart`; skip the widget/metrics tests
(`token_applier_test.dart`, `frosthaven_converter_test.dart`,
`should_animate_line_test.dart`, `TextStyle`-metric groups).

## 9. Commands and the command registry (new)

- Every command file ports with its exact API (see §3).
- **New file** `core/commands/command_registry.dart` (written last, after all
  commands exist): a wire-name → constructor map used by the Phase 2 network
  layer.

```dart
/// One entry: wire name, arg parsing/validation, and command construction.
class CommandDescriptor {
  const CommandDescriptor(this.name, this.construct);
  final String name; // e.g. 'draw', 'addMonster', 'changeHealth'
  final Command Function(GameState gameState, Map<String, dynamic> args) construct;
}

class CommandRegistryError implements Exception { final String message; ... }

Command buildCommand(String name, Map<String, dynamic> args, GameState gameState);
// throws CommandRegistryError with a human-readable message for unknown
// names or invalid/missing args.
String commandName(Command command); // reverse lookup (for describe/tests)
```

Wire names: camelCase of the class name minus the `Command` suffix
(`DrawCommand` → `draw`, `AddMonsterCommand` → `addMonster`,
`ChangeHealthCommand` → `changeHealth`; acronym runs lower-cased in full,
e.g. `ChangeXPCommand` → `changeXP`). Args: the command's constructor
parameters by name; positional-arg commands map positional args from a
`List`-free convention: pass them as named keys in the same order as the
positional parameters (e.g. `AddCharacterCommand(id, edition, display, level)`
→ `{'id': ..., 'edition': ..., 'display': ..., 'level': ...}`).
Every parameter type must be one of: `int`, `bool`, `String`, `double`,
`List<String>`, `List<int>`, `List<bool>`, `Map<String, dynamic>`,
`String?`, `int?`, `bool?`, `double?`, `List<int>?`, `List<bool>?`, `Map<String,int>`,
or another constructor argument. If a command takes a constructor param that is
not JSON-serializable, flag it in the report (do not invent a workaround).

## 10. Tests

- `package:flutter_test` → `package:test`; `testWidgets` → `test`.
- `test/command/test_helpers.dart` is rewritten (provided in this repo):
  - `setUpGame()` → `setupCore(saveStore: InMemorySaveStore())`,
    `gameState = getIt<GameState>()`, `gameState.init()`,
    `await getIt<GameData>().loadData('assets/testData/')`, `gameState.load()`.
  - keep `checkSaveState()` and `checkNoSideEffects()` as-is (uses `json_diff`).
  - drop `testApp()`, `ignoreOverflowErrors()`, `SharedPreferences`,
    `TestWidgetsFlutterBinding`, l10n delegates.
- Engine tests (everything under `test/command/` and the non-UI tests under
  `test/resource/`) port 1:1 otherwise: same assertions, same command
  invocations. Only import paths, `.value` removals, and the helpers import
  change.
- UI tests (`test/Layout/`, `test/widget/`, most `test/services/`) are **not**
  ported in Phase 1.

## 11. Style

- `dart format` (default page width 80) on all new files.
- Lints per `analysis_options.yaml` (`unawaited_futures`,
  `avoid_dynamic_calls`, `prefer_final_locals`) — the CI script
  (`scripts/ci.sh`) runs `dart analyze` and must be warning-free.
- Keep the reference app's doc comments where they explain behavior.
- Do not add behavior. Do not "improve" the ported logic. Mechanical
  translation only, plus the explicit conversions in this document.