Files
lichtkasten/Sources/Lichtkasten/Views/CodesWindow.swift
T

191 lines
8.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import LichtkastenCore
/// PM "Code Replacement" – but with teams stored in the app:
/// left the teams (enable checkbox like PM's file list), right the players of the selected team.
struct CodesWindow: View {
@EnvironmentObject var state: AppState
@State private var selectedTeam: UUID?
@State private var selectedRows: Set<UUID> = []
@State private var newCode = ""
@State private var newText = ""
@State private var test = "w10 trifft gegen h10, "
@State private var search = ""
private var teamIndex: Int? { state.codeLibrary.sets.firstIndex { $0.id == selectedTeam } }
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Diese Teams werden für Code-Ersetzungen verwendet. Bei doppelten Codes gewinnt das obere Team.")
.font(.callout).foregroundStyle(.secondary)
HSplitView {
teamList.frame(minWidth: 300, idealWidth: 360)
playerTable.frame(minWidth: 420)
}
.frame(minHeight: 320)
optionsRow
testRow
}
.padding(16)
.onAppear { if selectedTeam == nil { selectedTeam = state.codeLibrary.sets.first?.id } }
}
// MARK: Teams (PM file list)
private var teamList: some View {
VStack(spacing: 6) {
List(selection: $selectedTeam) {
ForEach($state.codeLibrary.sets) { $set in
HStack {
Toggle("", isOn: $set.enabled).toggleStyle(.checkbox).labelsHidden()
.help("Aktiv (PM: Enable)")
VStack(alignment: .leading, spacing: 1) {
Text(set.name).lineLimit(1)
Text(set.sourcePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "manuell")
.font(.caption2).foregroundStyle(.secondary).lineLimit(1)
}
Spacer()
Text("\(set.entries.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
}
.tag(set.id)
.contextMenu {
Button("Neue Spieler aus TXT nachladen …") { state.importCodeFiles(into: set.id) }
Button("Im Finder zeigen") {
if let p = set.sourcePath { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: p)]) }
}.disabled(set.sourcePath == nil)
Button("Löschen", role: .destructive) { remove(set.id) }
}
}
.onMove { state.codeLibrary.sets.move(fromOffsets: $0, toOffset: $1) }
}.scrollContentBackground(.hidden).background(LK.deep)
HStack(spacing: 6) {
Button("Hinzufügen …") { state.importCodeFiles() }
.help("TXT-Dateien als Teams importieren (wie PM „Add…“)")
Button("Neues Team") {
let s = CodeSet(name: "Neues Team")
state.codeLibrary.sets.append(s)
selectedTeam = s.id
}
Button("Entfernen") { if let id = selectedTeam { remove(id) } }.disabled(selectedTeam == nil)
Spacer()
Button("Alle neu laden") { state.reloadAllCodes() }
.help("Liest die TXT-Dateien erneut – nur neue Spieler kommen hinzu")
}
.controlSize(.small)
}
}
// MARK: Players of the selected team
@ViewBuilder
private var playerTable: some View {
if let i = teamIndex {
VStack(alignment: .leading, spacing: 6) {
HStack {
TextField("Teamname", text: $state.codeLibrary.sets[i].name).font(.headline).textFieldStyle(.roundedBorder)
Button("TXT nachladen …") { state.importCodeFiles(into: state.codeLibrary.sets[i].id) }
.help("Neue Spieler aus einer TXT hinzufügen – vorhandene bleiben unverändert")
}
TextField("Suchen", text: $search).textFieldStyle(.roundedBorder)
HStack {
Text("Code").frame(width: 90, alignment: .leading)
Text("Ersetzung (weitere Spalten mit „ | “ trennen)")
}
.font(.caption.bold())
List(selection: $selectedRows) {
ForEach($state.codeLibrary.sets[i].entries) { $e in
if search.isEmpty || e.code.localizedCaseInsensitiveContains(search)
|| e.columns.joined().localizedCaseInsensitiveContains(search) {
HStack {
TextField("", text: $e.code).frame(width: 90)
TextField("", text: Binding(get: { e.columns.joined(separator: " | ") },
set: { e.columns = $0.components(separatedBy: " | ") }))
}
.tag(e.id)
}
}
}.scrollContentBackground(.hidden).background(LK.deep)
// Quick add (e.g. a new player during the game)
HStack {
TextField("w23", text: $newCode).frame(width: 90).textFieldStyle(.roundedBorder)
TextField("Vorname Nachname (VfL Wolfsburg, 23)", text: $newText).textFieldStyle(.roundedBorder)
.onSubmit(addPlayer)
Button("Hinzufügen", action: addPlayer).disabled(newCode.isEmpty || newText.isEmpty)
Button {
state.codeLibrary.sets[i].entries.removeAll { selectedRows.contains($0.id) }
selectedRows = []
} label: { Image(systemName: "minus") }
.disabled(selectedRows.isEmpty)
.help("Ausgewählte Spieler löschen")
}
HStack {
Spacer()
Button("Als TXT exportieren …") { export(state.codeLibrary.sets[i]) }.controlSize(.small)
}
}
.padding(.leading, 8)
} else {
Text("Team auswählen oder hinzufügen").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
// MARK: Options (PM bottom row)
private var optionsRow: some View {
HStack(spacing: 16) {
Toggle("TXT-Dateien automatisch neu laden, wenn sie sich ändern", isOn: $state.codeLibrary.autoReload)
Spacer()
Toggle("Codes ohne Trennzeichen (w10 + Leertaste)", isOn: $state.codeLibrary.bareCodes)
HStack(spacing: 4) {
Text("Trennzeichen:")
TextField("", text: Binding(get: { state.codeLibrary.delimiter },
set: { if let c = $0.last { state.codeLibrary.delimiter = String(c) } }))
.frame(width: 28)
.textFieldStyle(.roundedBorder)
}
HStack(spacing: 4) {
Text("Standard-Ersetzung:")
TextField("", text: $state.codeLibrary.defaultReplacement).frame(width: 140).textFieldStyle(.roundedBorder)
}
}
.font(.callout)
}
private var testRow: some View {
HStack {
Text("Test:").foregroundStyle(.secondary)
CodeTextField(text: $test, codes: state.codes)
.frame(height: 24)
Text("Tippe z. B. „w10“ + Leertaste oder „\(state.codeLibrary.delimiter)w10\(state.codeLibrary.delimiter)“")
.font(.caption).foregroundStyle(.secondary)
}
}
// MARK: Actions
private func addPlayer() {
guard let i = teamIndex, !newCode.isEmpty, !newText.isEmpty else { return }
let r = state.codeLibrary.sets[i].merge([CodeEntry(code: newCode.trimmingCharacters(in: .whitespaces),
columns: newText.components(separatedBy: " | "))])
if r.added == 0 {
state.alert = AppAlert(title: "Code existiert schon", message: "„\(newCode)“ ist in diesem Team bereits vergeben.")
return
}
newCode = ""; newText = ""
}
private func remove(_ id: UUID) {
state.codeLibrary.sets.removeAll { $0.id == id }
if selectedTeam == id { selectedTeam = state.codeLibrary.sets.first?.id }
}
private func export(_ set: CodeSet) {
let p = NSSavePanel()
p.nameFieldStringValue = set.name + ".txt"
guard p.runModal() == .OK, let url = p.url else { return }
let text = set.entries.map { ([$0.code] + $0.columns).joined(separator: "\t") }.joined(separator: "\n") + "\n"
try? text.write(to: url, atomically: true, encoding: .utf8)
}
}