App/Sources/StepView.swift
213 lines · 9593 bytes
7 symbols in this file
1import FoldFormat
2import Notation
3import SwiftUI
4
5/// One step of a model: its diagram, captioned with the step's instruction, beside the folding
6/// model on a regular-width screen and above it on a compact one. The Steps button lists every
7/// step, in a popover on a regular-width screen and a sheet on a compact one. Finishing the model
8/// locks it and celebrates over the paper; the lock button unlocks it to unfold.
9struct StepView: View {
10 private let title: String
11 @State private var session: FoldSession?
12 @State private var isShowingSteps = false
13 @State private var isCelebrating = false
14 @Environment(\.accessibilityReduceMotion) private var reduceMotion
15 @Environment(\.horizontalSizeClass) private var horizontalSizeClass
16 @Environment(\.verticalSizeClass) private var verticalSizeClass
17
18 /// `step` counts from 1.
19 init(model: FoldFile, step: Int) {
20 title = model.fileTitle ?? "Untitled"
21 let session = try? FoldSession(model: model, step: step)
22 if let session { ScreenshotScene.requested?.apply(to: session) }
23 _session = State(initialValue: session)
24 }
25
26 var body: some View {
27 Group {
28 if let session {
29 let sideBySide = horizontalSizeClass == .regular || verticalSizeClass == .compact
30 let layout = sideBySide ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0))
31 layout {
32 diagram(session)
33 paper(session)
34 }
35 } else {
36 ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle")
37 }
38 }
39 .navigationTitle(session.map { "Step \($0.step.index) of \($0.model.frames.count - 1)" } ?? title)
40 .navigationBarTitleDisplayMode(.inline)
41 .toolbar {
42 if let session {
43 if session.isFinished {
44 ToolbarItem(placement: .topBarTrailing) {
45 Button(session.isLocked ? "Unlock to unfold" : "Lock",
46 systemImage: session.isLocked ? "lock.fill" : "lock.open") { session.toggleLock() }
47 .accessibilityIdentifier("paper.lock")
48 }
49 }
50 ToolbarItem(placement: .topBarTrailing) {
51 Button("Steps", systemImage: "list.number") { isShowingSteps = true }
52 .accessibilityIdentifier("steps.button")
53 .popover(isPresented: $isShowingSteps) {
54 StepListView(session: session)
55 .frame(idealWidth: 360, idealHeight: 480)
56 .presentationDetents([.medium, .large])
57 .presentationDragIndicator(.visible)
58 // the paper seen through a translucent sheet fails the contrast audit
59 .presentationBackground(.background)
60 }
61 }
62 }
63 }
64 }
65
66 /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond
67 /// that, so the diagram stays in view at large text sizes.
68 private func diagram(_ session: FoldSession) -> some View {
69 GeometryReader { pane in
70 VStack(alignment: .leading, spacing: 0) {
71 DiagramCanvas(diagram: session.diagram, style: .standard)
72 .accessibilityLabel("Diagram of step \(session.step.index)")
73 ScrollView {
74 HStack(alignment: .firstTextBaseline, spacing: 12) {
75 Text("\(session.step.index)")
76 .font(.title.bold())
77 .monospacedDigit()
78 .accessibilityIdentifier("step.index")
79 Text(session.step.instruction)
80 .fixedSize(horizontal: false, vertical: true)
81 .accessibilityIdentifier("diagram.caption")
82 }
83 .frame(maxWidth: .infinity, alignment: .leading)
84 .padding()
85 }
86 .scrollBounceBehavior(.basedOnSize)
87 .frame(maxHeight: pane.size.height * Self.captionShare)
88 .fixedSize(horizontal: false, vertical: true)
89 }
90 }
91 }
92
93 private static let captionShare = 0.45
94
95 private func paper(_ session: FoldSession) -> some View {
96 PaperView(positions: session.meshPositions, mesh: session.interpolator.mesh, clusters: session.clusters,
97 camera: session.camera)
98 .onGeometryChange(for: CGSize.self) { $0.size } action: { size in
99 if size.width > 0 && size.height > 0 { session.viewportSize = SIMD2(size.width, size.height) }
100 }
101 .foldGesture(session)
102 .reorientGesture(session)
103 .orbitGesture(session)
104 // a representation, so that dropping the adjustable action when locked leaves the
105 // paper's Metal view in place
106 .accessibilityRepresentation { paperElement(session) }
107 .overlay(alignment: .topLeading) {
108 if Self.isUITesting {
109 foldPath(session)
110 cameraValue(session)
111 stepKind(session)
112 }
113 }
114 .overlay {
115 if isCelebrating && session.isFinished {
116 celebration.id(session.finishCount)
117 }
118 }
119 .sensoryFeedback(.success, trigger: session.finishCount)
120 .task(id: session.finishCount) {
121 guard session.finishCount > 0 else { return }
122 // high priority, so that the paper's value changing on an adjust does not cut it off
123 var announcement = AttributedString("\(title) folded")
124 announcement.accessibilitySpeechAnnouncementPriority = .high
125 AccessibilityNotification.Announcement(announcement).post()
126 withAnimation(.easeIn(duration: 0.6)) { isCelebrating = true }
127 do { try await Task.sleep(for: .seconds(Confetti.duration)) } catch { return }
128 withAnimation { isCelebrating = false }
129 }
130 }
131
132 @ViewBuilder
133 private func paperElement(_ session: FoldSession) -> some View {
134 let element = Color.clear
135 .accessibilityElement()
136 .accessibilityLabel(session.step.instruction)
137 .accessibilityValue(session.isLocked ? "Folded, locked"
138 : session.t.formatted(.percent.precision(.fractionLength(0))))
139 .accessibilityIdentifier("fold.paper")
140 if session.isLocked {
141 element
142 } else {
143 element.accessibilityAdjustableAction { direction in
144 switch direction {
145 case .increment: session.adjust(1)
146 case .decrement: session.adjust(-1)
147 @unknown default: break
148 }
149 }
150 }
151 }
152
153 /// Confetti over the paper, or under Reduce Motion a label that fades in and out.
154 private var celebration: some View {
155 Group {
156 if reduceMotion {
157 Text("Folded")
158 .font(.largeTitle.bold())
159 .padding(.horizontal, 24)
160 .padding(.vertical, 12)
161 .background(.regularMaterial, in: Capsule())
162 } else {
163 Confetti()
164 .clipped()
165 .accessibilityElement()
166 .accessibilityLabel("Folded")
167 }
168 }
169 .allowsHitTesting(false)
170 .transition(reduceMotion ? .opacity : .identity)
171 .accessibilityIdentifier("confetti")
172 }
173
174 private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting")
175
176 /// For UI tests: the fold path's samples, each as x,y normalised to the paper view's frame.
177 private func foldPath(_ session: FoldSession) -> some View {
178 let mapping = session.mapping, size = session.viewportSize
179 let value = mapping.path.map { p in
180 String(format: "%.5f,%.5f", p.x / size.x, p.y / size.y)
181 }.joined(separator: " ")
182 return Color.clear
183 .frame(width: 1, height: 1)
184 .allowsHitTesting(false)
185 .accessibilityElement()
186 .accessibilityValue(value)
187 .accessibilityIdentifier("fold.path")
188 }
189
190 /// For UI tests: the step's kind, as in `krz:step`.
191 private func stepKind(_ session: FoldSession) -> some View {
192 Color.clear
193 .frame(width: 1, height: 1)
194 .allowsHitTesting(false)
195 .accessibilityElement()
196 .accessibilityValue(session.step.kind.rawValue)
197 .accessibilityIdentifier("step.kind")
198 }
199
200 /// For UI tests: the camera's eye, up and field of view, to 3 decimals.
201 private func cameraValue(_ session: FoldSession) -> some View {
202 let camera = session.camera
203 let value = [camera.eye, camera.up].map { v in
204 String(format: "%.3f,%.3f,%.3f", v.x, v.y, v.z)
205 }.joined(separator: " ") + String(format: " %.3f", camera.fieldOfView)
206 return Color.clear
207 .frame(width: 1, height: 1)
208 .allowsHitTesting(false)
209 .accessibilityElement()
210 .accessibilityValue(value)
211 .accessibilityIdentifier("paper.camera")
212 }
213}