-
-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathstudy_controller.dart
More file actions
764 lines (637 loc) · 24.2 KB
/
study_controller.dart
File metadata and controls
764 lines (637 loc) · 24.2 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
import 'dart:async';
import 'package:chessground/chessground.dart';
import 'package:collection/collection.dart';
import 'package:dartchess/dartchess.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:lichess_mobile/src/model/analysis/analysis_summary.dart';
import 'package:lichess_mobile/src/model/analysis/common_analysis_state.dart';
import 'package:lichess_mobile/src/model/analysis/server_analysis_mixin.dart';
import 'package:lichess_mobile/src/model/analysis/server_analysis_service.dart';
import 'package:lichess_mobile/src/model/auth/auth_controller.dart';
import 'package:lichess_mobile/src/model/common/chess.dart';
import 'package:lichess_mobile/src/model/common/eval.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/common/node.dart';
import 'package:lichess_mobile/src/model/common/service/move_feedback.dart';
import 'package:lichess_mobile/src/model/common/service/sound_service.dart';
import 'package:lichess_mobile/src/model/common/socket.dart';
import 'package:lichess_mobile/src/model/common/uci.dart';
import 'package:lichess_mobile/src/model/engine/evaluation_mixin.dart';
import 'package:lichess_mobile/src/model/engine/evaluation_preferences.dart';
import 'package:lichess_mobile/src/model/game/game_socket_events.dart';
import 'package:lichess_mobile/src/model/game/player.dart';
import 'package:lichess_mobile/src/model/study/study.dart';
import 'package:lichess_mobile/src/model/study/study_repository.dart';
import 'package:lichess_mobile/src/network/socket.dart';
import 'package:lichess_mobile/src/utils/rate_limit.dart';
import 'package:lichess_mobile/src/view/engine/engine_gauge.dart';
import 'package:lichess_mobile/src/widgets/pgn.dart';
part 'study_controller.freezed.dart';
typedef StudyOptions = ({StudyId id, StudyChapterId? initialChapter});
final studyControllerProvider = AsyncNotifierProvider.autoDispose
.family<StudyController, StudyState, StudyOptions>(
StudyController.new,
name: 'StudyControllerProvider',
);
enum ChapterServerAnalysisStatus { canRequest, notEnoughMoves, notWriteable, available }
class StudyController extends AsyncNotifier<StudyState>
with EngineEvaluationMixin, ServerAnalysisMixin
implements PgnTreeNotifier {
StudyController(this.options);
final StudyOptions options;
late Root _root;
Timer? _opponentFirstMoveTimer;
StreamSubscription<SocketEvent>? _socketSubscription;
final _likeDebouncer = Debouncer(const Duration(milliseconds: 500));
late SocketClient _socketClient;
@override
@protected
SocketClient get socketClient => _socketClient;
@override
@protected
Root get positionTree => _root;
@override
Future<StudyState> build() async {
ref.onDispose(() {
_opponentFirstMoveTimer?.cancel();
_socketSubscription?.cancel();
_likeDebouncer.cancel();
});
final socketPool = ref.watch(socketPoolProvider);
_socketClient = socketPool.open(Uri(path: '/study/${options.id}/socket/v6'));
final chapter = await _fetchChapter(options.id, chapterId: options.initialChapter);
_socketSubscription?.cancel();
_socketSubscription = _socketClient.stream.listen(_handleSocketEvent);
return chapter;
}
@override
void onCurrentPathEvalChanged(bool isSameEvalString) {
_refreshCurrentNode(recomputeRootView: !isSameEvalString);
}
void _refreshCurrentNode({bool recomputeRootView = false}) {
state = AsyncData(
state.requireValue.copyWith(
root: recomputeRootView ? _root.view : state.requireValue.root,
currentNode: StudyCurrentNode.fromNode(_root.nodeAt(state.requireValue.currentPath)),
),
);
}
Future<void> nextChapter() async {
if (state.hasValue) {
final chapters = state.requireValue.study.chapters;
final currentChapterIndex = chapters.indexWhere(
(chapter) => chapter.id == state.requireValue.study.chapter.id,
);
goToChapter(chapters[currentChapterIndex + 1].id);
}
}
Future<void> goToChapter(StudyChapterId chapterId) async {
await _fetchChapter(state.requireValue.study.id, chapterId: chapterId);
_ensureItsOurTurnIfGamebook();
}
Future<StudyState> _fetchChapter(StudyId id, {StudyChapterId? chapterId}) async {
final (study, analysisSummary, pgn) = await ref
.read(studyRepositoryProvider)
.getStudy(id: id, chapterId: chapterId);
final game = PgnGame.parsePgn(pgn);
final pgnHeaders = IMap(game.headers);
final rootComments = IList(game.comments.map((c) => PgnComment.fromPgn(c)));
final variant = study.chapter.setup.variant;
final orientation = study.chapter.setup.orientation;
final UserId? me = ref.read(authControllerProvider)?.user.id;
// Some studies have illegal starting positions. This is usually the case for introductory chapters.
// We do not treat this as an error, but display a static board instead.
try {
_root = Root.fromPgnGame(game);
} on PositionSetupException {
final illegalPositionState = StudyState(
myId: me,
variant: variant,
study: study,
currentPath: UciPath.empty,
isOnMainline: true,
root: null,
currentNode: StudyCurrentNode.illegalPosition(),
// EvaluationContext needs an initial posiiton, but it doesn't matter what we pass here,
// since the position is illegal and `isComputerAnalysisAllowed` is false anyway.
evaluationContext: EvaluationContext(
id: study.chapter.id,
variant: variant,
initialPosition: Variant.standard.initialPosition,
),
pgnRootComments: rootComments,
pgnHeaders: pgnHeaders,
pov: orientation,
isComputerAnalysisAllowed: false,
gamebookActive: false,
pgn: pgn,
);
state = AsyncData(illegalPositionState);
return illegalPositionState;
}
// If server analysis has already been requested for this chapter,
// assume that any comment that has an eval is actually a lichess analysis comment.
// (Note that regular comments by the study author might also exist.)
if (analysisSummary != null) {
for (final node in _root.mainline) {
final lichessCommentIndex = (node.comments ?? []).indexWhere((c) => c.eval != null);
if (lichessCommentIndex != -1) {
node.lichessAnalysisComments = [node.comments![lichessCommentIndex]];
node.comments!.removeAt(lichessCommentIndex);
}
}
}
const currentPath = UciPath.empty;
Move? lastMove;
final studyState = StudyState(
myId: me,
variant: variant,
study: study,
currentPath: currentPath,
isOnMainline: true,
root: _root.view,
currentNode: StudyCurrentNode.fromNode(_root),
evaluationContext: EvaluationContext(
id: study.chapter.id,
variant: variant,
initialPosition: _root.position,
),
pgnRootComments: rootComments,
pgnHeaders: pgnHeaders,
lastMove: lastMove,
pov: orientation,
isComputerAnalysisAllowed: study.chapter.features.computer && !study.chapter.gamebook,
gamebookActive: study.chapter.gamebook,
pgn: pgn,
analysisSummary: analysisSummary,
acplChartData: analysisSummary != null ? makeAcplChartData() : null,
);
// We need to define the state value in the build method because `requestEval` require the state
// to have a value.
state = AsyncData(studyState);
if (state.requireValue.isEngineAvailable(evaluationPrefs)) {
socketClient.firstConnection.then((_) {
requestEval();
});
}
return studyState;
}
void toggleLike() {
_likeDebouncer(() {
if (!state.hasValue) return;
final liked = state.requireValue.study.liked;
_socketClient.send('like', {'liked': !liked});
state = AsyncValue.data(
state.requireValue.copyWith(study: state.requireValue.study.copyWith(liked: !liked)),
);
});
}
void _handleSocketEvent(SocketEvent event) {
if (!state.hasValue) {
assert(false, 'received a game SocketEvent while StudyState is null');
return;
}
switch (event.topic) {
case 'liking':
final data = (event.data as Map<String, dynamic>)['l'] as Map<String, dynamic>;
final likes = data['likes'] as int;
final bool meLiked = data['me'] as bool;
state = AsyncValue.data(
state.requireValue.copyWith(
study: state.requireValue.study.copyWith(liked: meLiked, likes: likes),
),
);
}
}
// The PGNs of some gamebook studies start with the opponent's turn, so trigger their move after a delay
void _ensureItsOurTurnIfGamebook() {
_opponentFirstMoveTimer?.cancel();
if (state.requireValue.isAtStartOfChapter &&
state.requireValue.gamebookActive &&
state.requireValue.gamebookComment == null &&
state.requireValue.currentPosition != null &&
state.requireValue.currentPosition!.turn != state.requireValue.pov) {
_opponentFirstMoveTimer = Timer(const Duration(milliseconds: 750), () {
userNext();
});
}
}
void onUserMove(Move move) {
if (!state.hasValue || state.requireValue.currentPosition == null) return;
if (!state.requireValue.currentPosition!.isLegal(move)) return;
_sendMoveToSocket(move);
final (newPath, isNewNode) = _root.addMoveAt(state.requireValue.currentPath, move);
if (newPath != null) {
_setPath(newPath, shouldRecomputeRootView: isNewNode, shouldForceShowVariation: true);
}
if (state.requireValue.gamebookActive) {
final comment = state.requireValue.gamebookComment;
// If there's no explicit comment why the move was good/bad, trigger next/previous move automatically
if (comment == null) {
Timer(const Duration(milliseconds: 750), () {
if (state.requireValue.isOnMainline) {
userNext();
} else {
userPrevious();
}
});
}
}
}
void showGamebookSolution() {
onUserMove(state.requireValue.currentNode.children.first);
}
void userPrevious() {
if (state.hasValue) {
_setPath(state.requireValue.currentPath.penultimate, isNavigating: true);
}
}
void userNext() {
final state = this.state.value;
if (state!.currentNode.children.isEmpty) return;
_setPath(
state.currentPath + _root.nodeAt(state.currentPath).children.first.id,
isNavigating: true,
);
}
void jumpToNthNodeOnMainline(int n) {
UciPath path = _root.mainlinePath;
while (!path.penultimate.isEmpty) {
path = path.penultimate;
}
Node? node = _root.nodeAt(path);
int count = 0;
while (node != null && count < n) {
if (node.children.isNotEmpty) {
path = path + node.children.first.id;
node = _root.nodeAt(path);
count++;
} else {
break;
}
}
if (node != null) {
userJump(path);
}
}
void toggleBoard() {
final state = this.state.value;
if (state != null) {
this.state = AsyncValue.data(state.copyWith(pov: state.pov.opposite));
}
}
void reset() {
if (state.hasValue) {
_setPath(UciPath.empty);
_ensureItsOurTurnIfGamebook();
}
}
@override
void userJump(UciPath path) {
_setPath(path);
}
@override
void expandVariations(UciPath path) {
if (!state.hasValue) return;
final node = _root.nodeAt(path);
final childrenToShow = _root.isOnMainline(path) ? node.children.skip(1) : node.children;
for (final child in childrenToShow) {
child.isCollapsed = false;
for (final grandChild in child.children) {
grandChild.isCollapsed = false;
}
}
state = AsyncValue.data(state.requireValue.copyWith(root: _root.view));
}
@override
void collapseVariations(UciPath path) {
if (!state.hasValue) return;
final node = _root.nodeAt(path);
for (final child in node.children) {
child.isCollapsed = true;
}
state = AsyncValue.data(state.requireValue.copyWith(root: _root.view));
}
@override
void promoteVariation(UciPath path, bool toMainline) {
final state = this.state.value;
if (state == null) return;
_root.promoteAt(path, toMainline: toMainline);
this.state = AsyncValue.data(
state.copyWith(isOnMainline: _root.isOnMainline(state.currentPath), root: _root.view),
);
}
@override
void deleteFromHere(UciPath path) {
if (!state.hasValue) return;
_root.deleteAt(path);
_recordChange('deleteNode', {'path': path.value, 'jumpTo': path.penultimate.value});
_setPath(path.penultimate, shouldRecomputeRootView: true);
}
void _sendMoveToSocket(Move move) {
if (state.requireValue.isWriteable == false) return;
switch (move) {
case NormalMove():
_recordChange('anaMove', {
'orig': move.from.name,
'dest': move.to.name,
'variant': state.requireValue.variant.name,
'fen': state.requireValue.currentPosition!.fen,
'path': state.requireValue.currentPath.value,
});
case DropMove():
_recordChange('anaDrop', {
'role': move.role.name,
'pos': move.to.name,
'variant': state.requireValue.variant.name,
'fen': state.requireValue.currentPosition!.fen,
'path': state.requireValue.currentPath.value,
});
}
}
void _recordChange(String socketEvent, Map<String, dynamic> data) {
if (!state.hasValue) return;
if (state.requireValue.isWriteable == false) return;
_socketClient.send(socketEvent, {...data, 'ch': state.requireValue.study.chapter.id.value});
}
void _setPath(
UciPath path, {
bool shouldForceShowVariation = false,
bool shouldRecomputeRootView = false,
/// Whether the user is navigating through the moves (as opposed to playing a move).
bool isNavigating = false,
}) {
final state = this.state.value;
if (state == null) return;
final pathChange = state.currentPath != path;
final currentNode = _root.nodeAt(path);
bool pathWasExpanded = false;
if (pathChange) {
for (final child in currentNode.children) {
if (child.isCollapsed) {
child.isCollapsed = false;
pathWasExpanded = true;
}
}
}
// always show variation if the user plays a move
if (shouldForceShowVariation && currentNode is Branch && currentNode.isCollapsed) {
_root.updateAt(path, (node) {
if (node is Branch) node.isCollapsed = false;
});
}
// root view is only used to display move list, so we need to
// recompute the root view only when the nodelist length changes
// or a variation is hidden/shown
final rootView = shouldForceShowVariation || shouldRecomputeRootView || pathWasExpanded
? _root.view
: state.root;
final isForward = path.size > state.currentPath.size;
if (currentNode is Branch) {
// normal move feedback
if (!isNavigating && isForward) {
final isCheck = currentNode.sanMove.isCheck;
if (currentNode.sanMove.isCapture) {
ref.read(moveFeedbackServiceProvider).captureFeedback(state.variant, check: isCheck);
} else {
ref.read(moveFeedbackServiceProvider).moveFeedback(check: isCheck);
}
}
// if navigating, only sound feedback
else {
final soundService = ref.read(soundServiceProvider);
if (currentNode.sanMove.isCapture) {
soundService.play(Sound.capture);
} else {
soundService.play(Sound.move);
}
}
this.state = AsyncValue.data(
state.copyWith(
currentPath: path,
isOnMainline: _root.isOnMainline(path),
currentNode: StudyCurrentNode.fromNode(currentNode),
lastMove: currentNode.sanMove.move,
root: rootView,
),
);
} else {
this.state = AsyncValue.data(
state.copyWith(
currentPath: path,
isOnMainline: _root.isOnMainline(path),
currentNode: StudyCurrentNode.fromNode(currentNode),
lastMove: null,
root: rootView,
),
);
}
if (pathChange) {
this.state = AsyncData(this.state.requireValue.copyWith(engineInThreatMode: false));
requestEval();
}
}
@override
Future<void> onServerAnalysisEvent(ServerEvalEvent event) async {
state = AsyncData(
state.requireValue.copyWith(
acplChartData: makeAcplChartData(),
analysisSummary: event.analysis != null
? (
division: event.division != null
? Division(middlegame: event.division!.middle, endgame: event.division!.end)
: state.requireValue.analysisSummary?.division,
white: event.analysis!.white,
black: event.analysis!.black,
)
: null,
root: _root.view,
),
);
}
}
enum GamebookState { startLesson, findTheMove, correctMove, incorrectMove, lessonComplete }
@freezed
sealed class StudyState
with
_$StudyState,
AnalysisExplosionMixin,
EvaluationMixinState<StudyState>,
ServerAnalysisMixinState
implements CommonAnalysisState {
const StudyState._();
@override
ViewRoot? get analysisRoot => root;
@override
StudyState withThreatMode(bool engineInThreatMode) =>
copyWith(engineInThreatMode: engineInThreatMode);
const factory StudyState({
UserId? myId,
bool? isAdmin,
required Study study,
required String pgn,
/// The variant of the current chapter
required Variant variant,
/// Immutable view of the whole tree. Null if the chapter's starting position is illegal.
required ViewRoot? root,
/// The current node in the study tree view.
///
/// This is an immutable copy of the actual [Node] at the `currentPath`.
/// We don't want to use [Node.view] here because it'd copy the whole tree
/// under the current node and it's expensive.
required StudyCurrentNode currentNode,
/// The path to the current node in the analysis view.
required UciPath currentPath,
/// Whether the current path is on the mainline.
required bool isOnMainline,
/// The context that the local engine is initialized with.
required EvaluationContext evaluationContext,
/// The side to display the board from.
required Side pov,
/// Whether local evaluation is allowed for this study.
required bool isComputerAnalysisAllowed,
/// Whether we're currently in gamebook mode, where the user has to find the right moves.
required bool gamebookActive,
/// The PGN headers of the study chapter.
required IMap<String, String> pgnHeaders,
/// The last move played.
Move? lastMove,
/// The PGN root comments of the study
IList<PgnComment>? pgnRootComments,
@Default(false) bool engineInThreatMode,
/// Server analysis summary if a server analysis has been triggered on this chapter.
AnalysisSummary? analysisSummary,
/// Optional ACPL chart data of the game, coming from lichess server analysis.
IList<ExternalEval>? acplChartData,
}) = _StudyState;
/// Whether the current user is the owner of the study.
bool get amIOwner => myId == study.ownerId || (isAdmin == true && canIContribute);
/// The current user's member information, if available.
StudyMember? get myMember => myId != null ? study.members[myId!] : null;
/// Whether the current user can contribute to the study.
bool get canIContribute => myMember?.role == 'w';
/// Whether the study is writeable by the current user
bool get isWriteable => canIContribute && !gamebookActive;
@override
bool get alwaysRequestCloudEval => false;
/// Whether the engine is available for evaluation
@override
bool isEngineAvailable(EngineEvaluationPrefState prefs) =>
isComputerAnalysisAllowed && prefs.isEnabled;
bool get isOpeningExplorerAvailable => !gamebookActive && study.chapter.features.explorer;
bool get isServerAnalysisAllowed => !gamebookActive && study.chapter.features.computer;
ChapterServerAnalysisStatus get chapterServerAnalysisStatus {
if (analysisSummary != null) {
return ChapterServerAnalysisStatus.available;
}
if (root == null || root!.mainline.length < 4) {
return ChapterServerAnalysisStatus.notEnoughMoves;
}
if (!isWriteable) {
return ChapterServerAnalysisStatus.notWriteable;
}
return ChapterServerAnalysisStatus.canRequest;
}
@override
ServerAnalysisSource? get serverAnalysisSource =>
ServerAnalysisSource.studyChapter(studyId: study.id, chapterId: study.chapter.id);
EngineGaugeParams? engineGaugeParams(EngineEvaluationPrefState prefs) => isEngineAvailable(prefs)
? (
isLocalEngineAvailable: isEngineAvailable(prefs),
orientation: pov,
position: currentPosition!,
savedEval: currentNode.eval,
serverEval: null,
filters: (id: evaluationContext.id, path: currentPath),
)
: null;
@override
Position? get currentPosition => currentNode.position;
StudyChapter get currentChapter => study.chapter;
bool get canGoNext => currentNode.children.isNotEmpty;
bool get canGoBack => currentPath.size > UciPath.empty.size;
String get currentChapterTitle {
final index = study.getChapterIndex(currentChapter.id);
return '${index + 1}. ${study.chapters[index].name}';
}
bool get hasNextChapter => study.chapter.id != study.chapters.last.id;
bool get isAtEndOfChapter => isOnMainline && currentNode.children.isEmpty;
bool get isAtStartOfChapter => currentPath.isEmpty;
String? get gamebookComment {
final comment = (currentNode.isRoot ? pgnRootComments : currentNode.comments)
?.map((comment) => comment.text)
.nonNulls
.join('\n');
return comment?.isNotEmpty == true
? comment
: gamebookState == GamebookState.incorrectMove
? gamebookDeviationComment
: null;
}
String? get gamebookHint => study.hints.getOrNull(currentPath.size);
String? get gamebookDeviationComment => study.deviationComments.getOrNull(currentPath.size);
GamebookState get gamebookState {
if (isAtEndOfChapter) return GamebookState.lessonComplete;
final bool myTurn = currentNode.position!.turn == pov;
if (isAtStartOfChapter && !myTurn) return GamebookState.startLesson;
return myTurn
? GamebookState.findTheMove
: isOnMainline
? GamebookState.correctMove
: GamebookState.incorrectMove;
}
bool get isIntroductoryChapter => currentNode.isRoot && currentNode.children.isEmpty;
IList<PgnCommentShape> get pgnShapes => IList(
(currentNode.isRoot ? pgnRootComments : currentNode.comments)
?.map((comment) => comment.shapes)
.flattened,
);
PlayerSide get playerSide =>
gamebookActive ? (pov == Side.white ? PlayerSide.white : PlayerSide.black) : PlayerSide.both;
PlayersAnalysis? get playersAnalysis => analysisSummary != null
? (white: analysisSummary!.white, black: analysisSummary!.black)
: null;
}
@freezed
sealed class StudyCurrentNode with _$StudyCurrentNode implements AnalysisCurrentNodeInterface {
const StudyCurrentNode._();
const factory StudyCurrentNode({
// Null if the chapter's starting position is illegal.
required Position? position,
required List<Move> children,
required bool isRoot,
SanMove? sanMove,
IList<PgnComment>? startingComments,
IList<PgnComment>? comments,
IList<int>? nags,
ClientEval? eval,
}) = _StudyCurrentNode;
factory StudyCurrentNode.illegalPosition() {
return const StudyCurrentNode(position: null, children: [], isRoot: true);
}
factory StudyCurrentNode.fromNode(Node node) {
final children = node.children.map((n) => n.sanMove.move).toList();
if (node is Branch) {
return StudyCurrentNode(
sanMove: node.sanMove,
position: node.position,
isRoot: false,
children: children,
eval: node.eval,
startingComments: IList(node.startingComments),
comments: IList(node.comments),
nags: IList(node.nags),
);
} else {
return StudyCurrentNode(
position: node.position,
children: children,
eval: node.eval,
isRoot: true,
);
}
}
}