chessbaseLinux/iosApp/ChessPenguin/GameView.swift
2026-12-01 00:56:28 +03:00

346 lines
12 KiB
Swift

import SwiftUI
struct GameView: View {
@EnvironmentObject private var model: AppModel
@Environment(\.dismiss) private var dismiss
@State private var place: Int
@State private var loadState = GameLoadState<GameData>()
@State private var current = 0
@State private var flipped = false
init(startPlace: Int) {
_place = State(initialValue: startPlace)
}
private var shownGame: GameData? {
loadState.loadedPlace == place ? loadState.game : nil
}
private var currentNode: MoveNode? {
guard let shownGame, shownGame.nodes.indices.contains(current) else { return nil }
return shownGame.nodes[current]
}
var body: some View {
VStack(spacing: 0) {
if let game = shownGame {
PlayerBar(game: game, white: flipped)
BoardView(
node: currentNode ?? game.nodes.first,
flipped: flipped,
description: boardDescription
)
PlayerBar(game: game, white: !flipped)
if let node = currentNode, node.children.count > 1 {
ForkBar(nodes: node.children.compactMap { child in
let id = Int(child)
return game.nodes.indices.contains(id) ? game.nodes[id] : nil
}, onMove: go)
}
NotationView(game: game, current: current, onMove: go)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.layoutPriority(1)
} else if loadState.loadedPlace == place, let failure = loadState.failure {
ErrorMessage(title: L10n.gameFailed, detail: failure) {
Task { await load() }
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
VStack(spacing: 12) {
ProgressView()
Text(L10n.reading).foregroundStyle(Theme.onSurfaceVariant)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.background(Theme.background)
.background { GameKeyboardCommands(perform: perform) }
.safeAreaInset(edge: .bottom) {
MoveControls(
canBack: currentNode?.parent != nil,
canForward: currentNode?.children.isEmpty == false,
onFlip: { flipped.toggle() },
onBack: stepBack,
onForward: stepForward,
onStart: { go(to: 0) },
onEnd: goToEnd
)
}
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
VStack(spacing: 0) {
Text(eventTitle).font(.headline).lineLimit(1)
Text(L10n.gameOf(place + 1, model.totalGames))
.font(.caption.monospacedDigit())
.foregroundStyle(Theme.onSurfaceVariant)
}
}
ToolbarItemGroup(placement: .navigationBarTrailing) {
Button { show(place - 1) } label: {
Image(systemName: "chevron.left")
}
.disabled(place <= 0)
.accessibilityLabel(L10n.previousGame)
Button { Task { await showNext() } } label: {
Image(systemName: "chevron.right")
}
.disabled(place + 1 >= model.totalGames)
.accessibilityLabel(L10n.nextGame)
}
}
.task(id: place) { await load() }
}
private var eventTitle: String {
if let game = shownGame {
let event = joinedKnown([game.tag("Event"), game.tag("Date").flatMap(pgnYear)])
if !event.isEmpty { return event }
if let site = known(game.tag("Site") ?? "") { return site }
}
return L10n.classics
}
private var boardDescription: String {
guard let node = currentNode, current != 0 else { return L10n.boardStart }
var description = L10n.boardAfter(moveLabel(node))
switch BoardEnding(rawValue: node.end) {
case .checkmate: description += " · \(L10n.checkmate)"
case .stalemate: description += " · \(L10n.stalemate)"
case nil: break
}
return description
}
private func load() async {
let requestedPlace = place
loadState.begin()
do {
let loaded = try await model.game(atPlace: requestedPlace)
guard !Task.isCancelled, place == requestedPlace else { return }
guard loadState.succeed(requestedPlace: requestedPlace, currentPlace: place, game: loaded) else { return }
current = 0
model.lastOpened = requestedPlace
} catch {
guard !Task.isCancelled, place == requestedPlace else { return }
loadState.fail(requestedPlace: requestedPlace, currentPlace: place, message: error.localizedDescription)
}
}
private func showNext() async {
guard let request = nextGameRequest(
fromPlace: place,
totalGames: model.totalGames,
loadedRows: model.rows.count
) else { return }
if request.needsNextPage {
await model.loadNextPage()
}
guard !Task.isCancelled, place == request.fromPlace else { return }
show(request.toPlace)
}
private func show(_ newPlace: Int) {
guard newPlace >= 0, newPlace < model.totalGames, model.rows.indices.contains(newPlace) else { return }
place = newPlace
model.lastOpened = newPlace
}
private func go(to id: Int) {
guard let game = shownGame, game.nodes.indices.contains(id) else { return }
current = id
}
private func stepBack() {
guard let parent = currentNode?.parent else { return }
go(to: Int(parent))
}
private func stepForward() {
guard let child = currentNode?.children.first else { return }
go(to: Int(child))
}
private func goToEnd() {
guard let game = shownGame else { return }
var at = current
var visited: Set<Int> = [at]
for _ in 0..<game.nodes.count {
guard game.nodes.indices.contains(at), let child = game.nodes[at].children.first else { break }
let next = Int(child)
guard game.nodes.indices.contains(next), !visited.contains(next) else { break }
at = next
visited.insert(next)
}
go(to: at)
}
private func perform(_ command: GameCommand) {
switch command {
case .previousMove: stepBack()
case .nextMove: stepForward()
case .startOfLine: go(to: 0)
case .endOfLine: goToEnd()
case .flip: flipped.toggle()
case .back: dismiss()
}
}
}
private struct GameKeyboardCommands: View {
let perform: (GameCommand) -> Void
var body: some View {
Group {
Button { perform(gameCommand(for: .leftArrow)) } label: { EmptyView() }
.keyboardShortcut(.leftArrow, modifiers: [])
Button { perform(gameCommand(for: .rightArrow)) } label: { EmptyView() }
.keyboardShortcut(.rightArrow, modifiers: [])
Button { perform(gameCommand(for: .shiftLeftArrow)) } label: { EmptyView() }
.keyboardShortcut(.leftArrow, modifiers: .shift)
Button { perform(gameCommand(for: .shiftRightArrow)) } label: { EmptyView() }
.keyboardShortcut(.rightArrow, modifiers: .shift)
Button { perform(gameCommand(for: .f)) } label: { EmptyView() }
.keyboardShortcut("f", modifiers: [])
Button { perform(gameCommand(for: .escape)) } label: { EmptyView() }
.keyboardShortcut(.escape, modifiers: [])
}
.frame(width: 0, height: 0)
.opacity(0)
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
private func moveLabel(_ node: MoveNode) -> String {
let number = node.white ? "\(node.moveNumber)." : "\(node.moveNumber)…"
return number + node.san + node.nagSymbols
}
private struct PlayerBar: View {
let game: GameData
let white: Bool
var body: some View {
let name = white ? game.tag("White") : game.tag("Black")
let elo = white ? game.tag("WhiteElo") : game.tag("BlackElo")
let knownName = known(name ?? "")
HStack(spacing: 8) {
SideDisc(white: white)
Text(knownName ?? (white ? L10n.white : L10n.black))
.font(.subheadline.weight(knownName == nil ? .regular : .medium))
.foregroundStyle(knownName == nil ? Theme.onSurfaceVariant : Theme.onSurface)
.lineLimit(1)
.frame(maxWidth: .infinity, alignment: .leading)
if let elo = knownElo(elo ?? "") {
Text(elo).font(.subheadline.monospacedDigit()).foregroundStyle(Theme.onSurfaceVariant)
}
Text(sideResult(game.result, white: white) ?? "")
.font(.subheadline.monospacedDigit())
.foregroundStyle(Theme.onSurfaceVariant)
.frame(width: 24)
}
.padding(.horizontal, 16)
.frame(minHeight: 36)
}
}
private struct ForkBar: View {
let nodes: [MoveNode]
let onMove: (Int) -> Void
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
Text(L10n.nextMoves).font(.subheadline).foregroundStyle(Theme.onSurfaceVariant)
ForEach(Array(nodes.enumerated()), id: \.element.id) { offset, node in
Button(moveLabel(node)) { onMove(Int(node.id)) }
.buttonStyle(.bordered)
.tint(offset == 0 ? Theme.primary : Theme.onSurfaceVariant)
}
}
.padding(.horizontal, 16)
}
.frame(height: 48)
}
}
private struct MoveControls: View {
let canBack: Bool
let canForward: Bool
let onFlip: () -> Void
let onBack: () -> Void
let onForward: () -> Void
let onStart: () -> Void
let onEnd: () -> Void
var body: some View {
VStack(spacing: 0) {
Divider().background(Theme.outlineVariant)
HStack(spacing: 0) {
Button(action: onFlip) {
VStack(spacing: 2) {
Image(systemName: "arrow.up.arrow.down")
Text(L10n.flip).font(.caption2)
}
.frame(maxWidth: .infinity, minHeight: 56)
}
.accessibilityLabel(L10n.flip)
LongPressControl(
icon: "play.fill",
label: L10n.moveBack,
hint: L10n.moveBackHint,
longLabel: L10n.toStart,
enabled: canBack,
mirrored: true,
action: onBack,
longAction: onStart
)
LongPressControl(
icon: "play.fill",
label: L10n.moveForward,
hint: L10n.moveForwardHint,
longLabel: L10n.toEnd,
enabled: canForward,
mirrored: false,
action: onForward,
longAction: onEnd
)
}
.frame(height: 64)
}
.background(Theme.container.ignoresSafeAreaEdges(.bottom))
}
}
private struct LongPressControl: View {
let icon: String
let label: String
let hint: String
let longLabel: String
let enabled: Bool
let mirrored: Bool
let action: () -> Void
let longAction: () -> Void
var body: some View {
Image(systemName: icon)
.font(.title2)
.scaleEffect(x: mirrored ? -1 : 1)
.foregroundStyle(enabled ? Theme.onSurface : Theme.onSurface.opacity(0.38))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.contentShape(Rectangle())
.gesture(
LongPressGesture(minimumDuration: 0.45)
.onEnded { _ in longAction() }
.exclusively(before: TapGesture().onEnded { _ in action() })
)
.disabled(!enabled)
.accessibilityElement(children: .ignore)
.accessibilityLabel(label)
.accessibilityHint(hint)
.accessibilityAddTraits(.isButton)
.accessibilityAction(named: Text(longLabel), longAction)
}
}