Crossmate/Views/Puzzle/PuzzleScoreboard.swift (14600B)
1import SwiftUI
2
3struct PuzzleScoreboard: View {
4 @Bindable var session: PlayerSession
5 let roster: PlayerRoster
6 var layout: Layout = .vertical
7
8 var onNudge: (() async -> Void)? = nil
9
10
11 var nudgeReadyAt: () -> Date? = { nil }
12 @Environment(PlayerPreferences.self) private var preferences
13
14 @State private var showNudgeSent = false
15
16
17
18
19
20 @State private var nudgeDeadline: Date?
21
22 enum Layout {
23
24 case vertical
25
26
27 case horizontal
28 }
29
30 private typealias Score = PuzzleGridStats.ParticipantCount
31
32 private var gridStats: PuzzleGridStats {
33 let hasRemotePlayers = roster.entries.contains { !$0.isLocal }
34 return PuzzleGridStats(
35 puzzle: session.puzzle,
36 hasRemotePlayers: hasRemotePlayers,
37 localAuthorID: roster.localAuthorID
38 ) { r, c in
39 let square = session.game.squares[r][c]
40 return PuzzleGridStats.CellState(
41 entry: square.entry,
42 mark: square.mark,
43 authorID: square.letterAuthorID
44 )
45 }
46 }
47
48 private func remainingCount(for stats: PuzzleGridStats) -> Int {
49 max(0, stats.fillableCellCount - stats.filledCellCount)
50 }
51
52 private func remainingPhrase(for stats: PuzzleGridStats) -> String {
53 switch remainingCount(for: stats) {
54 case 0:
55 return "no squares to go"
56 case 1:
57 return "1 square to go"
58 default:
59 return "\(remainingCount(for: stats)) squares to go"
60 }
61 }
62
63 private func revealedPhrase(for stats: PuzzleGridStats) -> String {
64 switch stats.revealedSquareCount {
65 case 0:
66 return "No squares revealed"
67 case 1:
68 return "1 square revealed"
69 default:
70 return "\(stats.revealedSquareCount) squares revealed"
71 }
72 }
73
74 private func progressText(for stats: PuzzleGridStats) -> String {
75 if stats.revealedSquareCount > 0 {
76 return "\(revealedPhrase(for: stats)), \(remainingPhrase(for: stats))"
77 }
78 switch remainingCount(for: stats) {
79 case 0:
80 return "No squares to go"
81 case 1:
82 return "1 square to go"
83 default:
84 return "\(remainingCount(for: stats)) squares to go"
85 }
86 }
87
88 private func scores(for stats: PuzzleGridStats) -> [Score] {
89 return ParticipantSummaries.sortedByScore(
90 stats.participantCounts(
91 entries: roster.entries,
92 localName: preferences.name,
93 localColor: preferences.color
94 ),
95 score: \.count,
96 name: \.name,
97 id: \.id
98 )
99 }
100
101 private var showsNudgeButton: Bool {
102 onNudge != nil
103 && !session.mutator.isCompleted
104 && roster.entries.contains(where: { !$0.isLocal })
105 }
106
107 var body: some View {
108 Group {
109 switch layout {
110 case .vertical:
111 verticalBody
112 case .horizontal:
113 horizontalBody
114 }
115 }
116 .onAppear { if nudgeDeadline == nil { nudgeDeadline = nudgeReadyAt() } }
117 .task(id: nudgeDeadline) { await cooldownWatch() }
118 }
119
120
121
122
123
124
125 private func cooldownWatch() async {
126 guard let deadline = nudgeDeadline else { return }
127 let delay = deadline.timeIntervalSinceNow
128 if delay > 0 {
129 try? await Task.sleep(for: .seconds(delay))
130 }
131 if nudgeDeadline == deadline { nudgeDeadline = nil }
132 }
133
134 private var verticalBody: some View {
135 let stats = gridStats
136 let scores = scores(for: stats)
137 return VStack(alignment: .leading, spacing: 12) {
138 verticalHeading
139
140 VStack(alignment: .leading, spacing: 6) {
141 ForEach(scores) { score in
142 scoreRow(score)
143 }
144
145 Text(progressText(for: stats))
146 .font(.footnote)
147 .foregroundStyle(.secondary)
148 .padding(.top, 10)
149 .frame(maxWidth: .infinity, alignment: .center)
150 }
151 }
152 .padding(.horizontal, 18)
153 .padding(.vertical, 14)
154 .frame(maxWidth: .infinity, alignment: .leading)
155 }
156
157 private var horizontalBody: some View {
158 let scores = scores(for: gridStats)
159
160
161
162
163
164
165
166
167
168
169
170
171
172 return ScrollView(.vertical, showsIndicators: false) {
173 HStack(alignment: .center, spacing: 18) {
174 playersHeading
175 FlowLayout(alignment: .leading, spacing: 18, lineSpacing: 8) {
176 ForEach(scores) { score in
177 scoreChip(score)
178 }
179 }
180 }
181 .frame(maxWidth: .infinity)
182 .padding(.horizontal, 18)
183 .padding(.vertical, 4)
184 }
185 .frame(maxHeight: .infinity)
186 .defaultScrollAnchor(.bottom)
187
188
189
190
191 .dynamicTypeSize(...DynamicTypeSize.xLarge)
192 }
193
194
195
196
197
198 @ViewBuilder
199 private var verticalHeading: some View {
200 HStack(spacing: 8) {
201 Text("Players")
202 .font(.headline)
203 if showsNudgeButton {
204 Spacer(minLength: 8)
205 nudgeButton
206 }
207 }
208 }
209
210
211
212
213 private var nudgeButton: some View {
214
215
216
217 ZStack(alignment: .trailing) {
218 Button {
219 sendNudge()
220 } label: {
221 nudgeCapsule
222 }
223 .buttonStyle(.plain)
224 .disabled(isNudgeDisabled)
225 .accessibilityLabel("Nudge Players")
226 .opacity(showNudgeSent ? 0 : 1)
227 .accessibilityHidden(showNudgeSent)
228
229 Text("Nudge Sent")
230 .font(.footnote.weight(.semibold))
231 .foregroundStyle(.secondary)
232 .opacity(showNudgeSent ? 1 : 0)
233 .accessibilityHidden(!showNudgeSent)
234 }
235 }
236
237 private var nudgeCapsule: some View {
238 HStack(spacing: 5) {
239 Image(systemName: "hand.wave")
240 Text("Nudge")
241 }
242 .font(.footnote.weight(.semibold))
243 .padding(.horizontal, 12)
244 .padding(.vertical, 4)
245 .nudgeGlass(isLabeled: true)
246 }
247
248
249
250
251
252 @ViewBuilder
253 private var playersHeading: some View {
254 if showsNudgeButton {
255
256
257
258
259 ZStack {
260 Button {
261 sendNudge()
262 } label: {
263 playersCapsule
264 }
265 .buttonStyle(.plain)
266 .disabled(isNudgeDisabled)
267 .accessibilityLabel("Nudge Players")
268 .opacity(showNudgeSent ? 0 : 1)
269 .accessibilityHidden(showNudgeSent)
270
271 Text("Nudge Sent")
272 .font(.footnote.weight(.semibold))
273 .foregroundStyle(.primary)
274 .opacity(showNudgeSent ? 1 : 0)
275 .accessibilityHidden(!showNudgeSent)
276 }
277 } else {
278
279
280
281
282 Text("Players")
283 .font(.subheadline.weight(.semibold))
284 }
285 }
286
287
288
289 private var isNudgeDisabled: Bool {
290 showNudgeSent || nudgeDeadline != nil
291 }
292
293
294
295
296
297 private func sendNudge() {
298 if let onNudge {
299 Task { await onNudge() }
300 }
301 nudgeDeadline = Date().addingTimeInterval(SessionCoordinator.nudgeCooldown)
302 withAnimation(.easeInOut(duration: 0.25)) { showNudgeSent = true }
303 Task {
304 try? await Task.sleep(for: .seconds(3))
305 withAnimation(.easeInOut(duration: 0.25)) { showNudgeSent = false }
306 }
307 }
308
309 private var playersCapsule: some View {
310 HStack(spacing: 5) {
311 Image(systemName: "hand.wave")
312 Text("Players")
313 }
314 .font(.footnote.weight(.semibold))
315 .padding(.horizontal, 12)
316 .padding(.vertical, 4)
317
318
319
320
321
322
323
324 .background(Color.white.opacity(0.6), in: Capsule())
325
326
327
328 .overlay {
329 Capsule()
330 .strokeBorder(
331 LinearGradient(
332 colors: [.white.opacity(0.4), .black.opacity(0.14)],
333 startPoint: .top,
334 endPoint: .bottom
335 ),
336 lineWidth: 0.75
337 )
338 }
339 }
340
341 private func scoreChip(_ score: Score) -> some View {
342 HStack(spacing: 6) {
343 Circle()
344 .fill(score.color?.tint ?? Color.secondary)
345 .frame(width: 8, height: 8)
346 Text(score.name)
347 .font(.subheadline)
348 .lineLimit(1)
349 Text("\(score.count)")
350 .font(.subheadline.monospacedDigit().weight(.semibold))
351 }
352 .accessibilityElement(children: .combine)
353 }
354
355 private func scoreRow(_ score: Score) -> some View {
356 HStack(spacing: 8) {
357 Circle()
358 .fill(score.color?.tint ?? Color.secondary)
359 .frame(width: 8, height: 8)
360 Text(score.name)
361 .font(.subheadline)
362 .lineLimit(1)
363 Spacer(minLength: 8)
364 Text("\(score.count)")
365 .font(.subheadline.monospacedDigit().weight(.semibold))
366 }
367 .accessibilityElement(children: .combine)
368 }
369}