Crossmate/Views/Puzzle/GridView.swift (40632B)
1import SwiftUI
2
3struct GridView: View {
4 @Bindable var session: PlayerSession
5 let roster: PlayerRoster
6
7
8
9 let revealConfirmation: RevealConfirmation
10 let showsSharedAnnotations: Bool
11
12
13
14 var showsPeerCursors: Bool = true
15
16
17
18
19
20
21 var replayFrame: ReplayFrame? = nil
22
23 private let spacing: CGFloat = 1
24
25
26
27 @State private var gridSize: CGSize = .zero
28
29
30
31 @State private var decorationImages: [String: Image] = [:]
32
33 var body: some View {
34 let width = session.puzzle.width
35 let height = session.puzzle.height
36 let replayCells = replayFrame?.cells
37 let isReplaying = replayFrame != nil
38 let replayCursor = replayFrame?.cursor
39
40
41
42
43 let showsCanonicalRebus = !isReplaying && session.game.completionState == .solved
44
45
46
47 let showsRemoteTints = showsSharedAnnotations && showsPeerCursors && !isReplaying
48
49
50 let authorTintByID: [String: Color] = (showsSharedAnnotations || isReplaying)
51 ? Dictionary(
52 roster.entries.map { ($0.authorID, $0.color.tint) },
53 uniquingKeysWith: { first, _ in first }
54 )
55 : [:]
56
57
58
59 let playheadTint: Color? = replayFrame?.cursorAuthorID
60 .flatMap { id in roster.entries.first { $0.authorID == id } }
61 .map { $0.color.selectionFill }
62 let patternPalette = CrossRefPattern.allCases
63 let cellGroups = session.puzzle.cellGroups
64
65
66
67
68
69
70 let cellModel: [CellDraw] = (0..<(width * height)).map { index in
71 let r = index / width
72 let c = index % width
73 let cell = session.puzzle.cells[r][c]
74 let visibleDecorations = session.puzzle.decorations[GridPosition(row: r, col: c)]?
75 .filter { $0.isVisible(solved: showsCanonicalRebus) } ?? []
76 guard !cell.isBlock else {
77 return CellDraw(row: r, col: c, isBlock: true, special: nil,
78 crossRef: nil, entry: "", isPencil: false,
79 triangle: nil, authorTint: nil,
80 decorations: visibleDecorations)
81 }
82 let pos = GridPosition(row: r, col: c)
83 let square = session.game.squares[r][c]
84
85
86 let replayCell = replayCells?[pos]
87 let entry = isReplaying ? (replayCell?.letter ?? "") : square.entry
88 let displayEntry = canonicalRebusFill(for: cell, when: showsCanonicalRebus) ?? entry
89 let mark = isReplaying ? (replayCell?.mark ?? .none) : square.mark
90 let letterAuthorID = isReplaying ? replayCell?.cellAuthorID : square.letterAuthorID
91 let triangle: TriangleKind? = mark.isRevealed
92 ? .revealed
93 : (mark.isCheckedWrong ? .wrong : nil)
94 return CellDraw(
95 row: r,
96 col: c,
97 isBlock: false,
98 special: cell.special,
99 crossRef: cellGroups[pos].map { patternPalette[$0 % patternPalette.count] },
100 entry: displayEntry,
101 isPencil: mark.isPencil,
102 triangle: triangle,
103 authorTint: entry.isEmpty ? nil : letterAuthorID.flatMap { authorTintByID[$0] },
104 decorations: visibleDecorations
105 )
106 }
107
108
109
110
111
112
113
114
115
116 PuzzleGridLayerLayout(columns: width, rows: height, spacing: spacing) {
117 GridBackdrop(puzzle: session.puzzle, spacing: spacing)
118 AuthorTintsLayer(cells: cellModel, columns: width, rows: height, spacing: spacing)
119 if showsRemoteTints {
120 RemoteCursorTints(roster: roster, puzzle: session.puzzle, spacing: spacing)
121 }
122 LocalCursorTints(
123 session: session,
124 spacing: spacing,
125 isReplaying: isReplaying,
126 replayCursor: replayCursor,
127 replayPlayheadTint: playheadTint
128 )
129 if !isReplaying {
130 RecentChangeBorders(session: session, roster: roster, spacing: spacing)
131 }
132 PuzzleCellsLayer(
133 cells: cellModel,
134 columns: width,
135 rows: height,
136 spacing: spacing,
137 decorationImages: decorationImages
138 )
139 }
140
141
142
143
144 .contentShape(Rectangle())
145 .onTapGesture(coordinateSpace: .local) { location in
146 guard !isReplaying, gridSize != .zero else { return }
147 let geometry = PuzzleGridGeometry(
148 size: gridSize, columns: width, rows: height, spacing: spacing
149 )
150 if let (r, c) = geometry.cell(at: location) {
151 session.select(row: r, col: c)
152 }
153 }
154 .onGeometryChange(for: CGSize.self) { $0.size } action: { gridSize = $0 }
155
156
157
158
159 .task(id: session.mutator.gameID) {
160 decorationImages = DecorationImages.decode(session.puzzle.decorations)
161 }
162
163
164 .puzzleGridAccessibility(
165 session: session,
166 roster: roster,
167 revealConfirmation: revealConfirmation,
168 showsSharedAnnotations: showsSharedAnnotations,
169 isReplaying: isReplaying,
170 gridSize: gridSize,
171 spacing: spacing
172 )
173 }
174
175
176
177
178
179 private func canonicalRebusFill(for cell: Puzzle.Cell, when isSolved: Bool) -> String? {
180 guard isSolved, let solution = cell.solution, solution.count > 1 else { return nil }
181 return solution
182 }
183
184}
185
186
187
188
189
190private enum TriangleKind {
191 case revealed
192 case wrong
193}
194
195
196
197
198private struct CellDraw {
199 let row: Int
200 let col: Int
201 let isBlock: Bool
202 let special: Puzzle.Special?
203 let crossRef: CrossRefPattern?
204 let entry: String
205 let isPencil: Bool
206 let triangle: TriangleKind?
207
208
209
210
211 let authorTint: Color?
212
213
214
215
216
217 let decorations: [Puzzle.Decoration]
218}
219
220
221
222
223
224
225
226private struct AuthorTintsLayer: View {
227 let cells: [CellDraw]
228 let columns: Int
229 let rows: Int
230 let spacing: CGFloat
231
232 var body: some View {
233 Canvas { context, size in
234 let geometry = PuzzleGridGeometry(
235 size: size, columns: columns, rows: rows, spacing: spacing
236 )
237 guard geometry.cellSize > 0 else { return }
238 for cell in cells {
239 guard let tint = cell.authorTint else { continue }
240 context.fill(
241 Path(geometry.cellRect(row: cell.row, col: cell.col)),
242 with: .color(tint.opacity(PlayerColor.authorTintOpacity))
243 )
244 }
245 }
246 .allowsHitTesting(false)
247 }
248}
249
250
251
252
253
254
255
256
257
258private struct PuzzleCellsLayer: View {
259 let cells: [CellDraw]
260 let columns: Int
261 let rows: Int
262 let spacing: CGFloat
263
264 var decorationImages: [String: Image] = [:]
265 @Environment(\.colorScheme) private var colorScheme
266
267
268
269
270 private let baseFontSize: CGFloat = 34
271
272 var body: some View {
273 Canvas { context, size in
274 let geometry = PuzzleGridGeometry(
275 size: size, columns: columns, rows: rows, spacing: spacing
276 )
277 guard geometry.cellSize > 0 else { return }
278
279
280
281
282 var glyphCache: [String: (text: GraphicsContext.ResolvedText, size: CGSize)] = [:]
283 var decorationTextCache:
284 [String: (text: GraphicsContext.ResolvedText, size: CGSize)] = [:]
285
286
287 var imageCache: [String: GraphicsContext.ResolvedImage] = [:]
288
289
290
291
292 for cell in cells where !cell.decorations.isEmpty {
293 drawDecorations(
294 cell,
295 in: geometry.cellRect(row: cell.row, col: cell.col),
296 textCache: &decorationTextCache,
297 cache: &imageCache,
298 context: context
299 )
300 }
301
302 for cell in cells where !cell.isBlock {
303 let rect = geometry.cellRect(row: cell.row, col: cell.col)
304
305 if cell.special == .shaded {
306 context.fill(Path(rect), with: .color(.black.opacity(0.22)))
307 }
308 if let crossRef = cell.crossRef {
309 drawCrossRef(crossRef, in: rect, row: cell.row, col: cell.col, context: context)
310 }
311 if cell.special == .circled {
312 context.stroke(
313 Path(ellipseIn: rect.insetBy(dx: 1.5, dy: 1.5)),
314 with: .color(.black.opacity(0.55)),
315 lineWidth: 1
316 )
317 }
318 if !cell.entry.isEmpty {
319 drawLetter(cell, in: rect, cache: &glyphCache, context: context)
320 }
321 if let triangle = cell.triangle {
322 let side = min(rect.width, rect.height) * 0.3
323 var path = Path()
324 path.move(to: CGPoint(x: rect.maxX - side, y: rect.minY))
325 path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
326 path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY + side))
327 path.closeSubpath()
328 context.fill(path, with: .color(triangle == .revealed ? .yellow : .red))
329 }
330 }
331 }
332 }
333
334
335
336
337
338
339
340
341
342
343 private func drawDecorations(
344 _ cell: CellDraw,
345 in rect: CGRect,
346 textCache: inout [String: (text: GraphicsContext.ResolvedText, size: CGSize)],
347 cache: inout [String: GraphicsContext.ResolvedImage],
348 context: GraphicsContext
349 ) {
350 for decoration in cell.decorations {
351 switch decoration.content {
352 case .mark(let special) where decoration.phase == .after:
353 switch special {
354 case .shaded:
355 context.fill(Path(rect), with: .color(.black.opacity(0.22)))
356 case .circled:
357 context.stroke(
358 Path(ellipseIn: rect.insetBy(dx: 1.5, dy: 1.5)),
359 with: .color(.black.opacity(0.55)),
360 lineWidth: 1
361 )
362 }
363 case .mark:
364 continue
365 case .color(.background, let light, let dark):
366 guard let color = Puzzle.Decoration.Content.color(
367 light: light, dark: dark, for: colorScheme
368 ) else {
369 continue
370 }
371 context.fill(Path(rect), with: .color(color))
372 case .color:
373 continue
374 case .text(let value):
375 let key = "\(value)|\(cell.isBlock)"
376 let resolved: GraphicsContext.ResolvedText
377 let natural: CGSize
378 if let hit = textCache[key] {
379 resolved = hit.text
380 natural = hit.size
381 } else {
382 let text = context.resolve(
383 Text(value)
384 .font(
385 .system(
386 size: baseFontSize * 0.8,
387 weight: .semibold,
388 design: .rounded
389 )
390 )
391 .foregroundStyle(cell.isBlock ? Color.white : Color.black)
392 )
393 let measured = text.measure(
394 in: CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
395 )
396 textCache[key] = (text, measured)
397 resolved = text
398 natural = measured
399 }
400 guard natural.width > 0, natural.height > 0 else { continue }
401 let availableWidth = rect.width - 4
402 let scale = min(1, availableWidth / natural.width, rect.height / natural.height)
403 context.drawLayer { layer in
404 layer.translateBy(x: rect.midX, y: rect.midY)
405 layer.scaleBy(x: scale, y: scale)
406 layer.draw(resolved, at: .zero, anchor: .center)
407 }
408 case .data(_, _, let payload):
409 guard let image = decorationImages[payload] else { continue }
410 let resolved: GraphicsContext.ResolvedImage
411 if let hit = cache[payload] {
412 resolved = hit
413 } else {
414 resolved = context.resolve(image)
415 cache[payload] = resolved
416 }
417 context.draw(resolved, in: rect)
418 }
419 }
420 }
421
422
423 private func foregroundOverride(for cell: CellDraw) -> Color? {
424 for decoration in cell.decorations {
425 guard case .color(.foreground, let light, let dark) = decoration.content,
426 let color = Puzzle.Decoration.Content.color(
427 light: light, dark: dark, for: colorScheme
428 ) else {
429 continue
430 }
431 return color
432 }
433 return nil
434 }
435
436
437
438
439
440
441 private func drawLetter(
442 _ cell: CellDraw,
443 in rect: CGRect,
444 cache: inout [String: (text: GraphicsContext.ResolvedText, size: CGSize)],
445 context: GraphicsContext
446 ) {
447 let foreground = foregroundOverride(for: cell)
448
449
450
451 let key = "\(cell.entry)|\(cell.isPencil)|\(foreground.map(String.init(describing:)) ?? "")"
452 let resolved: GraphicsContext.ResolvedText
453 let natural: CGSize
454 if let hit = cache[key] {
455 resolved = hit.text
456 natural = hit.size
457 } else {
458 let color: Color = foreground ?? (cell.isPencil ? .black.opacity(0.5) : .black)
459 let text = context.resolve(
460 Text(cell.entry)
461 .font(.system(size: baseFontSize, weight: .semibold, design: .rounded))
462 .foregroundStyle(color)
463 )
464 let measured = text.measure(in: CGSize(width: CGFloat.infinity, height: CGFloat.infinity))
465 cache[key] = (text, measured)
466 resolved = text
467 natural = measured
468 }
469 guard natural.width > 0, natural.height > 0 else { return }
470 let availableWidth = rect.width - 4
471 let scale = min(1, availableWidth / natural.width, rect.height / natural.height)
472 context.drawLayer { layer in
473 layer.translateBy(x: rect.midX, y: rect.midY)
474 layer.scaleBy(x: scale, y: scale)
475 layer.draw(resolved, at: .zero, anchor: .center)
476 }
477 }
478
479
480
481
482
483 private func drawCrossRef(
484 _ pattern: CrossRefPattern,
485 in rect: CGRect,
486 row: Int,
487 col: Int,
488 context: GraphicsContext
489 ) {
490 let ink = Color.black.opacity(0.20)
491 let localRect = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
492 func stroke(_ slope: CrossRefLines.Slope) {
493 let path = CrossRefLines(slope: slope, row: row, col: col, spacing: spacing)
494 .path(in: localRect)
495 var layer = context
496 layer.clip(to: Path(rect))
497 layer.translateBy(x: rect.minX, y: rect.minY)
498 layer.stroke(path, with: .color(ink), lineWidth: 1)
499 }
500 switch pattern {
501 case .diagonalDown: stroke(.down)
502 case .diagonalUp: stroke(.up)
503 case .crosshatch: stroke(.down); stroke(.up)
504 case .horizontal: stroke(.horizontal)
505 case .vertical: stroke(.vertical)
506 }
507 }
508}
509
510
511
512private enum PuzzleGridMetrics {
513 static func cellSize(
514 for proposal: ProposedViewSize,
515 columns: Int,
516 rows: Int,
517 spacing: CGFloat
518 ) -> CGFloat {
519 cellSize(
520 availableWidth: proposal.width,
521 availableHeight: proposal.height,
522 columns: columns,
523 rows: rows,
524 spacing: spacing
525 )
526 }
527
528 static func cellSize(
529 availableWidth: CGFloat?,
530 availableHeight: CGFloat?,
531 columns: Int,
532 rows: Int,
533 spacing: CGFloat
534 ) -> CGFloat {
535 let cols = CGFloat(columns)
536 let rs = CGFloat(rows)
537 let width = availableWidth ?? .infinity
538 let height = availableHeight ?? .infinity
539 let widthBased = width.isFinite
540 ? (width - spacing * (cols + 1)) / cols
541 : .infinity
542 let heightBased = height.isFinite
543 ? (height - spacing * (rs + 1)) / rs
544 : .infinity
545 return max(0, min(widthBased, heightBased))
546 }
547}
548
549
550
551
552
553
554private struct PuzzleGridLayerLayout: Layout {
555 let columns: Int
556 let rows: Int
557 let spacing: CGFloat
558
559 func sizeThatFits(
560 proposal: ProposedViewSize,
561 subviews: Subviews,
562 cache: inout ()
563 ) -> CGSize {
564 let cellSize = PuzzleGridMetrics.cellSize(
565 for: proposal,
566 columns: columns,
567 rows: rows,
568 spacing: spacing
569 )
570 let width = cellSize * CGFloat(columns) + spacing * CGFloat(columns + 1)
571 let height = cellSize * CGFloat(rows) + spacing * CGFloat(rows + 1)
572 return CGSize(width: width, height: height)
573 }
574
575 func placeSubviews(
576 in bounds: CGRect,
577 proposal: ProposedViewSize,
578 subviews: Subviews,
579 cache: inout ()
580 ) {
581 guard let cellGrid = subviews.last else { return }
582 let geometry = PuzzleGridGeometry(
583 size: bounds.size,
584 columns: columns,
585 rows: rows,
586 spacing: spacing
587 )
588 let layerProposal = ProposedViewSize(width: bounds.width, height: bounds.height)
589 for subview in subviews.dropLast() {
590 subview.place(
591 at: CGPoint(x: bounds.minX, y: bounds.minY),
592 anchor: .topLeading,
593 proposal: layerProposal
594 )
595 }
596
597
598 let cellGridRect = geometry.gridRect.offsetBy(dx: bounds.minX, dy: bounds.minY)
599 cellGrid.place(
600 at: cellGridRect.origin,
601 anchor: .topLeading,
602 proposal: ProposedViewSize(width: cellGridRect.width, height: cellGridRect.height)
603 )
604 }
605}
606
607
608
609
610
611
612
613
614
615struct PuzzleGridGeometry {
616 let cellSize: CGFloat
617 let spacing: CGFloat
618 let gridSize: CGSize
619 private let columns: Int
620 private let rows: Int
621 private let originX: CGFloat
622 private let originY: CGFloat
623
624 init(size: CGSize, columns: Int, rows: Int, spacing: CGFloat) {
625 let cellSize = PuzzleGridMetrics.cellSize(
626 for: ProposedViewSize(width: size.width, height: size.height),
627 columns: columns,
628 rows: rows,
629 spacing: spacing
630 )
631 let gridWidth = cellSize * CGFloat(columns) + spacing * CGFloat(columns + 1)
632 let gridHeight = cellSize * CGFloat(rows) + spacing * CGFloat(rows + 1)
633 self.cellSize = cellSize
634 self.spacing = spacing
635 self.columns = columns
636 self.rows = rows
637 self.gridSize = CGSize(width: gridWidth, height: gridHeight)
638 self.originX = (size.width - gridWidth) / 2
639 self.originY = (size.height - gridHeight) / 2
640 }
641
642 var gridRect: CGRect {
643 CGRect(origin: CGPoint(x: originX, y: originY), size: gridSize)
644 }
645
646 func cellRect(row: Int, col: Int) -> CGRect {
647 CGRect(
648 x: originX + spacing + CGFloat(col) * (cellSize + spacing),
649 y: originY + spacing + CGFloat(row) * (cellSize + spacing),
650 width: cellSize,
651 height: cellSize
652 )
653 }
654
655
656
657
658
659
660
661 func cell(at point: CGPoint) -> (row: Int, col: Int)? {
662 guard gridRect.contains(point) else { return nil }
663 let stride = cellSize + spacing
664 guard stride > 0 else { return nil }
665 let col = min(max(Int((point.x - originX - spacing) / stride), 0), columns - 1)
666 let row = min(max(Int((point.y - originY - spacing) / stride), 0), rows - 1)
667 return (row, col)
668 }
669}
670
671
672
673
674
675
676
677private struct GridBackdrop: View {
678 let puzzle: Puzzle
679 let spacing: CGFloat
680
681 var body: some View {
682 Canvas { context, size in
683 let geometry = PuzzleGridGeometry(
684 size: size,
685 columns: puzzle.width,
686 rows: puzzle.height,
687 spacing: spacing
688 )
689 context.fill(Path(geometry.gridRect), with: .color(.black))
690 for r in 0..<puzzle.height {
691 for c in 0..<puzzle.width where !puzzle.cells[r][c].isBlock {
692 context.fill(Path(geometry.cellRect(row: r, col: c)), with: .color(.white))
693 }
694 }
695 }
696 .allowsHitTesting(false)
697 }
698}
699
700
701
702
703
704
705
706private struct RemoteCursorTints: View {
707 let roster: PlayerRoster
708 let puzzle: Puzzle
709 let spacing: CGFloat
710
711 var body: some View {
712 let tints = remoteTrackTints()
713 Canvas { context, size in
714 guard !tints.isEmpty else { return }
715 let geometry = PuzzleGridGeometry(
716 size: size,
717 columns: puzzle.width,
718 rows: puzzle.height,
719 spacing: spacing
720 )
721 for (pos, color) in tints {
722 context.fill(Path(geometry.cellRect(row: pos.row, col: pos.col)), with: .color(color))
723 }
724 }
725 .allowsHitTesting(false)
726 }
727
728
729
730 private func remoteTrackTints() -> [GridPosition: Color] {
731 var tint: [GridPosition: (Date, Color)] = [:]
732 for (_, sel) in roster.remoteSelections {
733 for cell in puzzle.wordCells(
734 atRow: sel.row, col: sel.col, direction: sel.direction
735 ) {
736 let pos = GridPosition(row: cell.row, col: cell.col)
737 if tint[pos].map({ $0.0 < sel.updatedAt }) ?? true {
738 tint[pos] = (sel.updatedAt, sel.color.selectionFill)
739 }
740 }
741 }
742 return tint.mapValues { $0.1 }
743 }
744}
745
746
747
748
749
750
751
752
753
754private struct LocalCursorTints: View {
755 let session: PlayerSession
756 let spacing: CGFloat
757 let isReplaying: Bool
758 let replayCursor: GridPosition?
759 let replayPlayheadTint: Color?
760
761 @Environment(PlayerPreferences.self) private var preferences
762
763 var body: some View {
764 let fills = cellFills()
765 let borders = isReplaying ? [] : relatedBorderCells()
766 let borderColor = preferences.color.highlightFill
767
768
769
770
771
772 let selectedCell: GridPosition? = isReplaying
773 ? nil
774 : GridPosition(row: session.selectedRow, col: session.selectedCol)
775 Canvas { context, size in
776 guard !fills.isEmpty || !borders.isEmpty else { return }
777 let geometry = PuzzleGridGeometry(
778 size: size,
779 columns: session.puzzle.width,
780 rows: session.puzzle.height,
781 spacing: spacing
782 )
783 if let pos = selectedCell {
784 context.fill(
785 Path(geometry.cellRect(row: pos.row, col: pos.col)),
786 with: .color(.white)
787 )
788 }
789 for (pos, color) in fills {
790 context.fill(Path(geometry.cellRect(row: pos.row, col: pos.col)), with: .color(color))
791 }
792 for pos in borders {
793
794
795 let rect = geometry.cellRect(row: pos.row, col: pos.col).insetBy(dx: 1.5, dy: 1.5)
796 context.stroke(Path(rect), with: .color(borderColor), lineWidth: 3)
797 }
798 }
799 .allowsHitTesting(false)
800 }
801
802
803
804
805 private func cellFills() -> [GridPosition: Color] {
806 if isReplaying {
807 guard let replayCursor, let replayPlayheadTint else { return [:] }
808 return [replayCursor: replayPlayheadTint]
809 }
810 let color = preferences.color
811 var fills: [GridPosition: Color] = [:]
812 for cell in session.puzzle.wordCells(
813 atRow: session.selectedRow,
814 col: session.selectedCol,
815 direction: session.direction
816 ) {
817 fills[GridPosition(row: cell.row, col: cell.col)] = color.highlightFill
818 }
819 fills[GridPosition(row: session.selectedRow, col: session.selectedCol)] = color.selectionFill
820 return fills
821 }
822
823 private func relatedBorderCells() -> [GridPosition] {
824 Array(session.puzzle.relatedCells(
825 atRow: session.selectedRow,
826 col: session.selectedCol,
827 direction: session.direction
828 ))
829 }
830}
831
832
833
834
835
836
837
838
839private struct RecentChangeBorders: View {
840 let session: PlayerSession
841 let roster: PlayerRoster
842 let spacing: CGFloat
843
844
845
846 @State private var shown: [GridPosition: Color] = [:]
847 @State private var visible = false
848
849 var body: some View {
850 Canvas { context, size in
851 guard !shown.isEmpty else { return }
852 let geometry = PuzzleGridGeometry(
853 size: size,
854 columns: session.puzzle.width,
855 rows: session.puzzle.height,
856 spacing: spacing
857 )
858 for (pos, color) in shown {
859 let rect = geometry.cellRect(row: pos.row, col: pos.col)
860 let path = Path(rect.insetBy(dx: 1.5, dy: 1.5))
861 context.stroke(
862 path,
863 with: .color(color.opacity(0.10)),
864 lineWidth: 6
865 )
866 context.stroke(
867 path,
868 with: .color(color.opacity(0.30)),
869 lineWidth: 2
870 )
871 }
872 }
873 .opacity(visible ? 1 : 0)
874 .animation(.easeOut(duration: 0.45), value: visible)
875 .allowsHitTesting(false)
876 .onAppear { apply(session.recentChanges) }
877 .onChange(of: session.recentChanges) { _, changes in apply(changes) }
878 }
879
880 private func apply(_ changes: [GridPosition: String]) {
881 if changes.isEmpty {
882
883
884 visible = false
885 Task {
886 try? await Task.sleep(for: .milliseconds(500))
887 if session.recentChanges.isEmpty { shown = [:] }
888 }
889 } else {
890 shown = resolve(changes)
891 visible = true
892 }
893 }
894
895
896
897
898 private func resolve(_ changes: [GridPosition: String]) -> [GridPosition: Color] {
899 let colorByAuthor = Dictionary(
900 roster.entries.map { ($0.authorID, $0.color.tint) },
901 uniquingKeysWith: { first, _ in first }
902 )
903 let width = session.puzzle.width
904 let height = session.puzzle.height
905 var result: [GridPosition: Color] = [:]
906 for (pos, authorID) in changes {
907 guard pos.row >= 0, pos.row < height, pos.col >= 0, pos.col < width else { continue }
908 guard !session.puzzle.cells[pos.row][pos.col].isBlock else { continue }
909 result[pos] = colorByAuthor[authorID] ?? Color.secondary
910 }
911 return result
912 }
913}