返回 CodeWhale
CodewhalePetView.swift
根目录 / pet / swift / CodewhalePetView.swift
1 // CodewhalePetView.swift — the native iOS/macOS renderer for the pet.
2 //
3 // The view owns no simulation: the caller steps `sim` (e.g. from a
4 // TimelineView's onChange or a CADisplayLink) and passes the `PetState` that
5 // produced the frame — the same contract the ratatui widget and the Compose
6 // renderer use. Rendering is one Canvas pass:
7 //
8 // * filled dot per particle, colour and alpha from sim.frame
9 // * hollow frames stroke the dots instead of filling them
10 // * a `.sensoryFeedback` is deliberately NOT used for state — the label row
11 // carries the non-colour cue ("tool · strike · unobserved")
12 //
13 // Reduced motion: when `accessibilityReduceMotion` is on, step the sim with
14 // motion: false — the same reduced-motion contract as every other port.
15 // Requires iOS 15+ / macOS 12+ (SwiftUI Canvas).
16
17 import SwiftUI
18
19 public struct CodewhalePetView: View {
20 public let sim: PetSim
21 public let state: PetState
22 @Environment(\.accessibilityReduceMotion) private var reduceMotion
23
24 public init(sim: PetSim, state: PetState) {
25 self.sim = sim
26 self.state = state
27 }
28
29 public var body: some View {
30 VStack(spacing: 0) {
31 Canvas { ctx, size in
32 let lay = petLayout(w: size.width, h: size.height, state: state)
33 let f = sim.frame
34 let color = Color(red: f.r / 255, green: f.g / 255, blue: f.b / 255)
35 let d = lay.dot
36 for (i, q) in sim.p.enumerated() {
37 let px = lay.ox + q.x * lay.scale * lay.flipX
38 let py = lay.oy + q.y * lay.scale
39 let rect = CGRect(x: px - d / 2, y: py - d / 2, width: d, height: d)
40 let dot = Path(ellipseIn: rect)
41 if f.hollow {
42 ctx.stroke(dot, with: .color(color.opacity(f.alpha)), lineWidth: 1)
43 } else {
44 ctx.fill(dot, with: .color(color.opacity(f.alpha)))
45 }
46 _ = i
47 }
48 }
49 .accessibilityLabel(Text(petA11yLabel(sim: sim, state: state)))
50 Text("\(sim.frame.channel) · \(sim.frame.arch)\(sim.frame.hollow ? " · unobserved" : "")")
51 .font(.caption.monospaced())
52 .foregroundStyle(.secondary)
53 }
54 }
55 }
56
57 /// VoiceOver gets the semantic frame, not "a whale animation".
58 public func petA11yLabel(sim: PetSim, state: PetState) -> String {
59 let f = sim.frame
60 var parts = ["Codewhale pet", f.channel, f.arch]
61 if f.hollow { parts.append("unobserved") }
62 if state.lit < 0.5 { parts.append("dozing") }
63 if f.channel == "human" && !f.hollow && state.attention > 0.5 { parts.append("awaiting input") }
64 return parts.joined(separator: ", ")
65 }
66
66 lines Plain Text