-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathnvuiView.ts
More file actions
717 lines (684 loc) · 25.4 KB
/
nvuiView.ts
File metadata and controls
717 lines (684 loc) · 25.4 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
import { Chessground as makeChessground } from '@lichess-org/chessground';
import { COLORS } from 'chessops';
import { lichessRules } from 'chessops/compat';
import { parseFen } from 'chessops/fen';
import { makeSan } from 'chessops/san';
import { charToRole, opposite, parseUci } from 'chessops/util';
import { setupPosition } from 'chessops/variant';
import { defined } from 'lib';
import { throttle } from 'lib/async';
import { view as cevalView, renderEval } from 'lib/ceval';
import { renderChat } from 'lib/chat/renderChat';
import type { Player } from 'lib/game';
import { plyToTurn } from 'lib/game/chess';
import {
renderSan,
renderPieces,
renderBoard,
renderMainline,
renderComments,
boardCommandsHandler,
selectionHandler,
arrowKeyHandler,
positionJumpHandler,
pieceJumpingHandler,
castlingFlavours,
inputToMove,
lastCapturedCommandHandler,
type DropMove,
possibleMovesHandler,
renderPockets,
pocketsStr,
leaveSquareHandler,
} from 'lib/nvui/chess';
import { commands, boardCommands, addBreaks } from 'lib/nvui/command';
import { scanDirectionsHandler } from 'lib/nvui/directionScan';
import { liveText } from 'lib/nvui/notify';
import { renderSetting } from 'lib/nvui/setting';
import { pubsub } from 'lib/pubsub';
import { ops, path as treePath } from 'lib/tree/tree';
import type { ClientEval, PvData } from 'lib/tree/types';
import { type VNode, type LooseVNodes, type VNodeChildren, hl, bind, noTrans } from 'lib/view';
import { text as xhrText } from 'lib/xhr';
import type { AnalyseNvuiContext } from '../analyse.nvui';
import { next, prev } from '../control';
import type AnalyseCtrl from '../ctrl';
import explorerView from '../explorer/explorerView';
import { makeConfig as makeCgConfig } from '../ground';
import type { AnalyseData } from '../interfaces';
import { clickHook, currentLineIndex, renderCurrentNode } from '../nvuiUtil';
import { renderRetro } from '../retrospect/nvuiRetroView';
import { view as chapterEditFormView } from '../study/chapterEditForm';
import { view as chapterNewFormView } from '../study/chapterNewForm';
import { playersView } from '../study/relay/relayPlayers';
import { showInfo as tourOverview } from '../study/relay/relayTourView';
import renderClocks from '../view/clocks';
import { renderResult, viewContext, type RelayViewContext } from '../view/components';
const throttled = (sound: string) => throttle(100, () => site.sound.play(sound));
const selectSound = throttled('select');
const borderSound = throttled('outOfBound');
const errorSound = throttled('error');
export function initNvui(ctx: AnalyseNvuiContext): void {
const { ctrl, notify } = ctx;
pubsub.on('analysis.server.progress', (data: AnalyseData) => {
if (data.analysis && !data.analysis.partial) notify.set('Server-side analysis complete');
});
site.mousetrap.unbind('c');
site.mousetrap.bind('c', () => notify.set(renderEvalAndDepth(ctrl)));
}
export function renderNvui(ctx: AnalyseNvuiContext): VNode {
const { ctrl, deps, notify, moveStyle, pieceStyle, prefixStyle, positionStyle, boardStyle } = ctx;
const d = ctrl.data,
style = moveStyle.get(),
clocks = renderClocks(ctrl, ctrl.path),
pockets = ctrl.node.crazy?.pockets;
ctrl.chessground = makeChessground(document.createElement('div'), {
...makeCgConfig(ctrl),
animation: { enabled: false },
drawable: { enabled: false },
coordinates: false,
});
return hl('main.analyse', [
hl('div.nvui', [
studyDetails(ctrl),
hl('h2', i18n.nvui.gameInfo),
...COLORS.map(color => hl('p', [`${i18n.site[color]}: `, renderPlayer(ctrl, playerByColor(d, color))])),
hl('p', `${i18n.site[d.game.rated ? 'rated' : 'casual']} ${d.game.perf || d.game.variant.name}`),
d.clock ? hl('p', `Clock: ${d.clock.initial / 60} + ${d.clock.increment}`) : null,
hl('h2', i18n.nvui.moveList),
hl('p.moves', { attrs: { role: 'log', 'aria-live': 'off' } }, renderCurrentLine(ctx)),
!ctrl.study?.practice && [
hl(
'button',
{
attrs: { 'aria-pressed': `${ctrl.explorer.enabled()}` },
hook: bind('click', _ => ctrl.explorer.toggle(), ctrl.redraw),
},
i18n.site.openingExplorerAndTablebase,
),
explorerView(ctrl),
],
hl('h2', i18n.nvui.pieces),
renderPieces(ctrl.chessground.state.pieces, style),
pockets && hl('h2', i18n.nvui.pockets),
pockets && renderPockets(pockets),
renderAriaResult(ctrl),
hl('h2', i18n.nvui.lastMove),
!ctrl.retro && liveText(renderCurrentNode(ctx), 'polite', 'p.position.lastMove'),
clocks &&
hl('div.clocks', [
hl('h2', i18n.site.clock),
hl('div.clocks', [hl('div.topc', clocks[0]), hl('div.botc', clocks[1])]),
]),
hl('h2', i18n.nvui.inputForm),
hl(
'form#move-form',
{
hook: {
insert(vnode) {
const $form = $(vnode.elm as HTMLFormElement),
$input = $form.find('.move').val('');
$form.on('submit', onSubmit(ctx, $input));
},
},
},
[
hl('label', [
i18n.nvui.inputForm,
hl('input.move.mousetrap', {
attrs: { name: 'move', type: 'text', autocomplete: 'off' },
}),
]),
],
),
notify.render(),
renderRetro(ctx),
!ctrl.retro && [
hl('h2', i18n.site.computerAnalysis),
cevalView.renderCeval(ctrl), // beware unsolicted redraws hosing the screen reader
cevalView.renderPvs(ctrl),
renderAcpl(ctx) || requestAnalysisBtn(ctx),
],
hl('h2', i18n.site.board),
hl(
'div.board',
{
hook: {
insert: el => boardEventsHook(ctx, el.elm as HTMLElement),
update: (_, vnode) => boardEventsHook(ctx, vnode.elm as HTMLElement),
},
},
renderBoard(
ctrl.chessground.state.pieces,
ctrl.data.game.variant.key === 'racingKings' ? 'white' : ctrl.bottomColor(),
pieceStyle.get(),
prefixStyle.get(),
positionStyle.get(),
boardStyle.get(),
),
),
hl('div.boardstatus', { attrs: { 'aria-live': 'polite', 'aria-atomic': 'true' } }, ''),
hl('div.content', {
hook: {
insert: vnode => {
const root = $(vnode.elm as HTMLElement);
root.append($('.blind-content').removeClass('none'));
root.find('.copy-pgn').on('click', function (this: HTMLElement) {
navigator.clipboard.writeText(this.dataset.pgn!).then(() => {
notify.set(i18n.nvui.copiedToClipboard('PGN'));
});
});
root.find('.copy-fen').on('click', function (this: HTMLElement) {
const fen = document.querySelector<HTMLInputElement>('.analyse__underboard__fen input')?.value;
if (fen) {
navigator.clipboard.writeText(fen).then(() => {
notify.set(i18n.nvui.copiedToClipboard('FEN'));
});
}
});
},
},
}),
hl('h2', i18n.site.advancedSettings),
hl('label', ['Move notation', renderSetting(moveStyle, ctrl.redraw)]),
hl('h3', 'Board settings'),
hl('label', ['Piece style', renderSetting(pieceStyle, ctrl.redraw)]),
hl('label', ['Piece prefix style', renderSetting(prefixStyle, ctrl.redraw)]),
hl('label', ['Show position', renderSetting(positionStyle, ctrl.redraw)]),
hl('label', ['Board layout', renderSetting(boardStyle, ctrl.redraw)]),
hl('h2', i18n.site.keyboardShortcuts),
hl(
'p',
[
'Use arrow keys to navigate in the game.',
`l: ${i18n.site.toggleLocalAnalysis}`,
`z: ${i18n.site.toggleAllAnalysis}`,
`space: ${i18n.site.playComputerMove}`,
'c: announce computer evaluation',
`x: ${i18n.site.showThreat}`,
].reduce(addBreaks, []),
),
boardCommands(),
hl('h2', i18n.nvui.inputFormCommandList),
hl(
'p',
[
'Type these commands in the command input.',
...inputCommands
.filter(c => !c.invalid?.(ctrl))
.flatMap(command => [noTrans(`${command.cmd}: `), command.help]),
].reduce<VNodeChildren[]>(
(acc, curr, i) => (i % 2 !== 0 ? addBreaks(acc, curr) : acc.concat(curr)),
[],
),
),
hl('h2', 'Chat'),
ctrl.chatCtrl && renderChat(ctrl.chatCtrl),
deps && ctrl.study?.relay && tourDetails(ctx),
]),
]);
}
function boardEventsHook(
{ ctrl, pieceStyle, prefixStyle, moveStyle, notify }: AnalyseNvuiContext,
el: HTMLElement,
): void {
const $board = $(el);
// Remove old handlers before rebinding (important on re-render)
$board.off('.nvui');
const steps = () => ctrl.tree.getNodeList(ctrl.path);
const fenSteps = () => steps().map(step => step.fen);
const opponentColor = () => (ctrl.node.ply % 2 === 0 ? 'black' : 'white');
$board.on('blur', 'button', e => {
leaveSquareHandler($board.find('button'))(e);
});
$board.on('click', 'button', e => {
selectionHandler(opponentColor)(e);
});
$board.on('keydown', 'button', (e: KeyboardEvent) => {
if (e.shiftKey && e.key.match(/^[ad]$/i)) jumpMoveOrLine(ctrl)(e);
else if (e.key.match(/^x$/i))
scanDirectionsHandler(ctrl.bottomColor(), ctrl.chessground.state.pieces, moveStyle.get())(e);
else if (['o', 'l', 't'].includes(e.key)) boardCommandsHandler()(e);
else if (e.key.startsWith('Arrow')) arrowKeyHandler(ctrl.bottomColor(), borderSound)(e);
else if (e.key === 'c') lastCapturedCommandHandler(fenSteps, pieceStyle.get(), prefixStyle.get())();
else if (e.key === 'i') {
e.preventDefault();
document.querySelector<HTMLElement>('input.move')?.focus();
} else if (e.key === 'f') {
if (ctrl.data.game.variant.key !== 'racingKings') {
notify.set('Flipping the board');
setTimeout(() => ctrl.flip(), 1000);
}
} else if (e.code.match(/^Digit([1-8])$/)) positionJumpHandler()(e);
else if (e.key.match(/^[kqrbnp]$/i)) pieceJumpingHandler(selectSound, errorSound)(e);
else if (e.key.toLowerCase() === 'm')
possibleMovesHandler(ctrl.turnColor(), ctrl.chessground, ctrl.data.game.variant.key, ctrl.nodeList)(e);
else if (e.key.toLowerCase() === 'v') notify.set(renderEvalAndDepth(ctrl));
else if (e.key === 'G') ctrl.playBestMove();
else if (e.key === 'g') notify.set(renderBestMove({ ctrl, moveStyle } as AnalyseNvuiContext));
});
}
function renderEvalAndDepth(ctrl: AnalyseCtrl): string {
if (ctrl.threatMode()) return `${evalInfo(ctrl.node.threat)} ${depthInfo(ctrl.node.threat, false)}`;
const evs = { client: ctrl.getNode().ceval, server: ctrl.getNode().eval },
bestEv = cevalView.getBestEval(ctrl);
const evalStr = evalInfo(bestEv);
return !evalStr ? noEvalStr(ctrl) : `${evalStr} ${depthInfo(evs.client, !!evs.client?.cloud)}`;
}
const evalInfo = (bestEv: EvalScore | undefined): string =>
defined(bestEv?.cp)
? renderEval(bestEv.cp).replace('-', '−')
: defined(bestEv?.mate)
? `mate in ${Math.abs(bestEv.mate)} for ${bestEv.mate > 0 ? 'white' : 'black'}`
: '';
const depthInfo = (clientEv: ClientEval | undefined, isCloud: boolean): string =>
clientEv ? `${i18n.site.depthX(clientEv.depth || 0)} ${isCloud ? 'Cloud' : ''}` : '';
const noEvalStr = (ctrl: AnalyseCtrl) =>
!ctrl.isCevalAllowed()
? 'local evaluation not allowed'
: !ctrl.cevalEnabled()
? 'local evaluation not enabled'
: '';
function renderBestMove({ ctrl, moveStyle }: AnalyseNvuiContext): string {
const noEvalMsg = noEvalStr(ctrl);
if (noEvalMsg) return noEvalMsg;
const node = ctrl.node,
setup = parseFen(node.fen).unwrap();
let pvs: PvData[] = [];
if (ctrl.threatMode() && node.threat) {
pvs = node.threat.pvs;
setup.turn = opposite(setup.turn);
if (setup.turn === 'white') setup.fullmoves += 1;
} else if (node.ceval) pvs = node.ceval.pvs;
const pos = setupPosition(lichessRules(ctrl.ceval.opts.variant.key), setup);
if (pos.isOk && pvs.length > 0 && pvs[0].moves.length > 0) {
const uci = pvs[0].moves[0];
const san = makeSan(pos.unwrap(), parseUci(uci)!);
return renderSan(san, uci, moveStyle.get());
}
return '';
}
function renderAriaResult(ctrl: AnalyseCtrl): VNode[] {
const result = renderResult(ctrl);
const res = result.length ? result : i18n.site.none;
return [
hl('h2', i18n.nvui.gameStatus),
hl('div', { attrs: { role: 'status', 'aria-live': 'assertive', 'aria-atomic': 'true' } }, res),
];
}
function renderCurrentLine({ ctrl, moveStyle }: AnalyseNvuiContext) {
if (ctrl.path.length === 0) return renderMainline(ctrl.mainline, ctrl.path, moveStyle.get(), !ctrl.retro);
else {
const futureNodes = ctrl.node.children.length > 0 ? ops.mainlineNodeList(ctrl.node.children[0]) : [];
return renderMainline(ctrl.nodeList.concat(futureNodes), ctrl.path, moveStyle.get(), !ctrl.retro);
}
}
function onSubmit(ctx: AnalyseNvuiContext, $input: Cash) {
const { ctrl, notify } = ctx;
return (e: SubmitEvent) => {
e.preventDefault();
const input = castlingFlavours(($input.val() as string).trim());
// Allow commands with/without a leading '/'
const command = getCommand(input) || getCommand(input.slice(1));
if (command && !command.invalid?.(ctrl)) command.cb(ctx, input);
else {
const move = inputToMove(input, ctrl.node.fen, ctrl.chessground);
const isDrop = (u?: string | DropMove) => !!(u && typeof u !== 'string');
const isInvalidDrop = (d: DropMove) =>
!ctrl.crazyValid(d.role, d.key) || ctrl.chessground.state.pieces.has(d.key);
const isInvalidCrazy = isDrop(move) && isInvalidDrop(move);
if (!move || isInvalidCrazy) notify.set(`Invalid move: ${input}`);
else sendMove(move, ctrl);
}
$input.val('');
};
}
type Command = 'b' | 'p' | 's' | 'eval' | 'best' | 'prev' | 'next' | 'prev line' | 'next line' | 'pocket';
type InputCommand = {
cmd: Command;
help: VNode | string;
cb: (ctrl: AnalyseNvuiContext, input: string) => void;
invalid?: (ctrl: AnalyseCtrl) => boolean;
};
const inputCommands: InputCommand[] = [
{
cmd: 'b',
help: commands().board.help,
cb: ({ ctrl, notify, moveStyle }, input) =>
notify.set(commands().board.apply(input, ctrl.chessground.state.pieces, moveStyle.get()) || ''),
},
{
cmd: 'p',
help: commands().piece.help,
cb: ({ ctrl, notify, moveStyle }, input) =>
notify.set(
commands().piece.apply(input, ctrl.chessground.state.pieces, moveStyle.get()) ||
`Bad input: ${input}. Exptected format: ${commands().piece.help}`,
),
},
{
cmd: 's',
help: commands().scan.help,
cb: ({ ctrl, notify, moveStyle }, input) =>
notify.set(
commands().scan.apply(input, ctrl.chessground.state.pieces, moveStyle.get()) ||
`Bad input: ${input}. Exptected format: ${commands().scan.help}`,
),
},
{
cmd: 'eval',
help: noTrans("announce last move's computer evaluation"),
cb: ({ ctrl, notify }) => notify.set(renderEvalAndDepth(ctrl)),
},
{
cmd: 'best',
help: noTrans('announce the top engine move'),
cb: ctx => ctx.notify.set(renderBestMove(ctx)),
},
{
cmd: 'prev',
help: noTrans('return to the previous move'),
cb: ({ ctrl }) => doAndRedraw(ctrl, prev),
},
{ cmd: 'next', help: noTrans('go to the next move'), cb: ({ ctrl }) => doAndRedraw(ctrl, next) },
{
cmd: 'prev line',
help: noTrans('switch to the previous variation'),
cb: ({ ctrl }) => doAndRedraw(ctrl, jumpPrevLine),
},
{
cmd: 'next line',
help: noTrans('switch to the next variation'),
cb: ({ ctrl }) => doAndRedraw(ctrl, jumpNextLine),
},
{
cmd: 'pocket',
help: noTrans('Read out pockets for white or black. Example: "pocket black"'),
cb: ({ ctrl, notify }, input) => {
const pockets = ctrl.node.crazy?.pockets;
const color = input.split(' ')?.[1]?.trim();
return notify.set(
pockets
? color
? pocketsStr(color === 'white' ? pockets[0] : pockets[1]) || i18n.site.none
: 'Expected format: pocket [white|black]'
: 'Command only available in crazyhouse',
);
},
invalid: ctrl => ctrl.data.game.variant.key !== 'crazyhouse',
},
];
const getCommand = (input: string) => {
const split = input.split(' ');
const firstWordLowerCase = split[0].toLowerCase();
return (
inputCommands.find(c => c.cmd === input.toLowerCase()) ||
inputCommands.find(c => split.length !== 1 && c.cmd === firstWordLowerCase)
); // 'next line' should not be interpreted as 'next'
};
function sendMove(uciOrDrop: string | DropMove, ctrl: AnalyseCtrl) {
if (typeof uciOrDrop === 'string')
ctrl.sendMove(
uciOrDrop.slice(0, 2) as Key,
uciOrDrop.slice(2, 4) as Key,
undefined,
charToRole(uciOrDrop.slice(4)),
);
else if (ctrl.crazyValid(uciOrDrop.role, uciOrDrop.key)) ctrl.sendNewPiece(uciOrDrop.role, uciOrDrop.key);
}
function renderAcpl({ ctrl, moveStyle }: AnalyseNvuiContext): LooseVNodes {
const analysis = ctrl.data.analysis;
if (!analysis || ctrl.retro) return undefined;
const analysisGlyphs = ['?!', '?', '??'];
const analysisNodes = ctrl.mainline.filter(n => n.glyphs?.find(g => analysisGlyphs.includes(g.symbol)));
const res: Array<VNode> = [];
COLORS.forEach(color => {
res.push(hl('h3', `${color} player: ${analysis[color].acpl} ${i18n.site.averageCentipawnLoss}`));
res.push(
hl(
'select',
{
hook: bind(
'change',
e => ctrl.jumpToMain(parseInt((e.target as HTMLSelectElement).value)),
ctrl.redraw,
),
},
analysisNodes
.filter(n => (n.ply % 2 === 1) === (color === 'white'))
.map(node =>
hl(
'option',
{ attrs: { value: node.ply, selected: node.ply === ctrl.node.ply } },
[
plyToTurn(node.ply),
renderSan(node.san, node.uci, moveStyle.get()),
renderComments(node, moveStyle.get()),
].join(' '),
),
),
),
);
});
return res;
}
const requestAnalysisBtn = ({ ctrl, notify, analysisInProgress }: AnalyseNvuiContext) => {
if (ctrl.ongoing || ctrl.synthetic || ctrl.hasFullComputerAnalysis()) return;
return analysisInProgress()
? hl('p', 'Server-side analysis in progress')
: hl(
'button.request-analysis',
clickHook(() =>
xhrText(`/${ctrl.data.game.id}/request-analysis`, { method: 'post' }).then(
() => {
analysisInProgress(true);
notify.set('Server-side analysis in progress');
},
() => notify.set('Cannot run server-side analysis'),
),
),
i18n.site.requestAComputerAnalysis,
);
};
const renderPlayer = (ctrl: AnalyseCtrl, player: Player): LooseVNodes =>
player.ai ? i18n.site.aiNameLevelAiLevel('Stockfish', player.ai) : userHtml(ctrl, player);
function userHtml(ctrl: AnalyseCtrl, player: Player) {
const d = ctrl.data,
user = player.user,
perf = user ? user.perfs[d.game.perf] : null,
rating = player.rating ? player.rating : perf && perf.rating,
rd = player.ratingDiff,
ratingDiff = rd ? (rd > 0 ? '+' + rd : rd < 0 ? '−' + -rd : '') : '';
const studyPlayers = ctrl.study && renderStudyPlayer(ctrl, player.color);
return user
? hl('span', [
hl(
'a',
{ attrs: { href: '/@/' + user.username } },
user.title ? `${user.title} ${user.username}` : user.username,
),
rating ? ` ${rating}` : ``,
' ' + ratingDiff,
])
: studyPlayers || hl('span', i18n.site.anonymous);
}
function renderStudyPlayer(ctrl: AnalyseCtrl, color: Color): VNode | undefined {
const player = ctrl.study?.currentChapter().players?.[color];
const keys = [
['name', i18n.site.name],
['title', 'title'],
['rating', i18n.site.rating],
['fed', 'fed'],
['team', 'team'],
] as const;
return (
player &&
hl(
'span',
keys
.reduce<string[]>(
(strs, [key, i18n]) =>
player[key]
? strs.concat(`${i18n}: ${key === 'fed' ? player[key].i18nName : player[key]}`)
: strs,
[],
)
.join(' '),
)
);
}
const playerByColor = (d: AnalyseData, color: Color): Player =>
color === d.player.color ? d.player : d.opponent;
const jumpNextLine = (ctrl: AnalyseCtrl) => jumpLine(ctrl, 1);
const jumpPrevLine = (ctrl: AnalyseCtrl) => jumpLine(ctrl, -1);
function jumpLine(ctrl: AnalyseCtrl, delta: number) {
const { i, of } = currentLineIndex(ctrl);
if (of === 1) return;
const newI = (i + delta + of) % of;
const prevPath = treePath.init(ctrl.path);
const prevNode = ctrl.tree.nodeAtPath(prevPath);
const newPath = prevPath + prevNode.children[newI].id;
ctrl.userJumpIfCan(newPath);
}
const redirectToSelectedHook = bind('change', (e: InputEvent) => {
const target = e.target as HTMLSelectElement;
const selectedOption = target.options[target.selectedIndex];
const url = selectedOption.getAttribute('url');
if (url) window.location.href = url;
});
function tourDetails({ ctrl, deps }: AnalyseNvuiContext): VNode[] {
const ctx: RelayViewContext = { ...viewContext(ctrl, deps), allowVideo: false } as RelayViewContext;
const tour = ctx.relay.data.tour;
ctx.relay.redraw = ctrl.redraw;
return [
hl('h1', 'Tour details'),
hl('h2', 'Overview'),
hl('div', tourOverview(tour.info, tour.dates)),
hl('h2', 'Players'),
hl(
'button.tournament-players',
clickHook(() => ctx.relay.tab('players'), ctrl.redraw),
'Load player list',
),
hl('div', ctx.relay.tab() === 'players' && playersView(ctx.relay.players)),
];
}
function studyDetails(ctrl: AnalyseCtrl) {
const study = ctrl.study;
const relayGroups = study?.relay?.data.group;
const relayRounds = study?.relay?.data.rounds;
const tour = study?.relay?.data.tour;
const hash = window.location.hash;
return (
study &&
hl('div.study-details', [
hl('h2', 'Study details'),
hl('span', `Title: ${study.data.name}. By: ${study.data.ownerId}`),
hl('br'),
relayGroups &&
hl(
'div.relay-groups',
hl('label', [
'Current group:',
hl(
'select',
{
attrs: { autofocus: hash === '#group-select' },
hook: redirectToSelectedHook,
},
relayGroups.tours.map(t =>
hl(
'option',
{ attrs: { selected: t.id === tour?.id, url: `/broadcast/-/${t.id}#group-select` } },
t.name,
),
),
),
]),
),
tour &&
relayRounds &&
hl(
'div.relay-rounds',
hl('label', [
'Current round:',
hl(
'select',
{
attrs: { autofocus: hash === '#round-select' },
hook: redirectToSelectedHook,
},
relayRounds.map(r =>
hl(
'option',
{
attrs: {
selected: r.id === study.data.id,
url: `/broadcast/${tour.slug}/${r.slug}/${r.id}#round-select`,
},
},
study.relay?.round.name,
),
),
),
]),
),
hl('div.chapters', [
hl('label', [
'Current chapter:',
hl(
'select',
{
attrs: { id: 'chapter-select' },
hook: bind('change', (e: InputEvent) => {
const target = e.target as HTMLSelectElement;
const selectedOption = target.options[target.selectedIndex];
const chapterId = selectedOption.getAttribute('chapterId');
study.setChapter(chapterId!);
}),
},
study.chapters.list
.all()
.map((ch, i) =>
hl(
'option',
{ attrs: { selected: ch.id === study.currentChapter().id, chapterId: ch.id } },
`${i + 1}. ${ch.name}`,
),
),
),
]),
study.members.canContribute()
? hl('div.buttons', [
hl(
'button.edit-chapter',
clickHook(() => study.chapters.editForm.toggle(study.currentChapter()), ctrl.redraw),
[
'Edit current chapter',
study.chapters.editForm.current() && chapterEditFormView(study.chapters.editForm),
],
),
hl(
'button.create-chapter',
clickHook(() => study.chapters.newForm.toggle(), ctrl.redraw),
[
'Add new chapter',
study.chapters.newForm.isOpen() ? chapterNewFormView(study.chapters.newForm) : undefined,
],
),
])
: undefined,
]),
])
);
}
const doAndRedraw = (ctrl: AnalyseCtrl, fn: (ctrl: AnalyseCtrl) => void): void => {
fn(ctrl);
ctrl.redraw();
};
function jumpMoveOrLine(ctrl: AnalyseCtrl) {
return (e: KeyboardEvent) => {
if (e.key === 'A') doAndRedraw(ctrl, e.altKey ? jumpPrevLine : prev);
else if (e.key === 'D') doAndRedraw(ctrl, e.altKey ? jumpNextLine : next);
};
}