Lock the finished model and celebrate !11

merged merged by cmc on 2026-10-23 05:08 UTC · krz/fold:completion into main

7 files changed, +361 −19

Layout: unified · split

App/Sources/Confetti.swift added +60
@@ -0,0 +1,60 @@
1import Renderer
2import SwiftUI
3
4/// A burst of paper confetti thrown up from the middle of the view, tumbling as it falls out of
5/// the bottom over `duration` seconds from when the view appears. Pieces in the paper's colours
6/// show its front on one side and its back on the other.
7struct Confetti: View {
8 nonisolated static let duration = 2.5
9 @State private var pieces = (0..<90).map { _ in Piece() }
10 @State private var start = Date.now
11
12 var body: some View {
13 TimelineView(.animation) { timeline in
14 Canvas { context, size in
15 let elapsed = timeline.date.timeIntervalSince(start)
16 for piece in pieces { piece.draw(in: context, size: size, at: elapsed) }
17 }
18 }
19 }
20}
21
22private let front = colour(PaperRenderer.frontColour)
23private let back = colour(PaperRenderer.backColour)
24private let accents = [Color(red: 0.96, green: 0.74, blue: 0.20), Color(red: 0.16, green: 0.58, blue: 0.56),
25 Color(red: 0.26, green: 0.44, blue: 0.86)]
26
27private func colour(_ c: SIMD4<Float>) -> Color {
28 Color(red: Double(c.x), green: Double(c.y), blue: Double(c.z))
29}
30
31private struct Piece {
32 /// Where it is thrown from and its initial velocity, as fractions of the view's size.
33 let origin = SIMD2(Double.random(in: 0.35...0.65), Double.random(in: 0.3...0.4))
34 let velocity = SIMD2(Double.random(in: -0.7...0.7), Double.random(in: -1.6...(-0.8)))
35 let size = CGSize(width: Double.random(in: 6...11), height: Double.random(in: 4...9))
36 /// Radians per second in the plane of the screen and about the piece's own long axis.
37 let spin = Double.random(in: -6...6), tumble = Double.random(in: 4...10)
38 let phase = Double.random(in: 0...(2 * .pi))
39 /// One colour on each side.
40 let sides: (Color, Color) = Bool.random() ? (front, back) : { let c = accents.randomElement()!; return (c, c) }()
41
42 /// Air drag and the speed it falls at once drag has taken out the throw, per second and in
43 /// fractions of the view's height per second.
44 private static let drag = 2.5, fallSpeed = 0.6
45
46 func draw(in context: GraphicsContext, size view: CGSize, at t: Double) {
47 guard t >= 0, t < Confetti.duration else { return }
48 let slowed = (1 - exp(-Self.drag * t)) / Self.drag
49 let x = origin.x + velocity.x * slowed + 0.02 * sin(3 * t + phase)
50 let y = origin.y + (velocity.y - Self.fallSpeed) * slowed + Self.fallSpeed * t
51 let turn = cos(tumble * t + phase)
52 var piece = context
53 piece.opacity = min(1, (Confetti.duration - t) / 0.4)
54 piece.translateBy(x: x * view.width, y: y * view.height)
55 piece.rotate(by: .radians(spin * t + phase))
56 piece.scaleBy(x: 1, y: turn)
57 let rect = CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height)
58 piece.fill(Path(rect), with: .color(turn >= 0 ? sides.0 : sides.1))
59 }
60}
App/Sources/FoldGesture.swift +1 −1
@@ -17,7 +17,7 @@ private struct FoldGesture: ViewModifier {
1717 func body(content: Content) -> some View {
1818 let folds = session.step.kind == .fold || session.step.kind == .foldAndUnfold
1919 content
20 .gesture(drag, isEnabled: folds)
20 .gesture(drag, isEnabled: folds && !session.isLocked)
2121 .onChange(of: isDragging) { _, dragging in if !dragging { session.cancelDrag() } }
2222 }
2323
App/Sources/FoldSession.swift +42 −7
@@ -7,7 +7,7 @@ import simd
77
88/// One model being folded: the current step, its fold parameter `t` in 0...1, and the model
99/// view's orientation. Nothing here changes `t` on its own; the step changes only when the user
10/// completes it or opens another.
10/// completes it or opens another. Completing the last step finishes the model and locks it.
1111@MainActor @Observable
1212final class FoldSession {
1313 let model: FoldFile
@@ -19,6 +19,13 @@ final class FoldSession {
1919 var t = 0.0 {
2020 didSet { if t != oldValue { pose() } }
2121 }
22 /// Whether the last step has been completed and no drag, adjustment or other step has since
23 /// left `t` below 1.
24 private(set) var isFinished = false
25 /// Whether the finished model ignores drags and adjustment. Orbit and zoom still work.
26 private(set) var isLocked = false
27 /// How many times the model has been finished.
28 private(set) var finishCount = 0
2229 /// The unit vector from the camera's target toward its eye.
2330 var eyeDirection: SIMD3<Double> {
2431 didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } }
@@ -70,15 +77,36 @@ final class FoldSession {
7077 }
7178
7279 /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete.
73 /// After the last step the finished model stays at t = 1.
80 /// Completing the last step finishes the model at t = 1 and locks it.
7481 func completeStep() {
75 guard t == 1, step.index + 1 < model.frames.count else { return }
76 open(step: step.index + 1)
82 guard t == 1 else { return }
83 if step.index + 1 < model.frames.count {
84 open(step: step.index + 1)
85 } else if !isFinished {
86 isFinished = true
87 isLocked = true
88 finishCount += 1
89 }
90 }
91
92 /// Locks or unlocks a finished model. Unlocked, its last step can be dragged back to unfold it.
93 func toggleLock() {
94 guard isFinished else { return }
95 isLocked.toggle()
96 guard isLocked else { return }
97 if let grab { t = grab.start }
98 cancelDrag()
99 }
100
101 /// Leaves the finished state if `t` is below 1.
102 private func settle() {
103 if t < 1 { isFinished = false; isLocked = false }
77104 }
78105
79106 /// Opens step `n`, counting from 1, at t = 0, seen from its viewpoint at the default zoom. A
80 /// drag in progress no longer moves `t` or completes a step. Opening the current step leaves it
81 /// as it is. A step that cannot be read leaves the session as it is and stops a Debug build.
107 /// drag in progress no longer moves `t` or completes a step, and a finished model is no longer
108 /// finished. Opening the current step leaves it as it is. A step that cannot be read leaves the
109 /// session as it is and stops a Debug build.
82110 func open(step n: Int) {
83111 guard n != step.index else { return }
84112 cancelDrag()
@@ -101,6 +129,7 @@ final class FoldSession {
101129 fieldOfView = Self.defaultFieldOfView
102130 cachedMapping = nil
103131 if t == 0 { pose() } else { t = 0 }
132 settle()
104133 }
105134
106135 /// What maps a one-finger drag's translation to `t`.
@@ -121,6 +150,7 @@ final class FoldSession {
121150 /// Called when a one-finger drag on a fold step begins: the moving faces then follow the
122151 /// finger along `mapping`'s path.
123152 func beginFoldDrag() {
153 guard !isLocked else { return }
124154 let mapping = self.mapping
125155 beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t)))
126156 }
@@ -129,6 +159,7 @@ final class FoldSession {
129159 /// component then turns the model across its on-screen width, measured on the frame the step
130160 /// starts from, which a vertical turn-over would otherwise shrink to an edge midway.
131161 func beginReorientDrag() {
162 guard !isLocked else { return }
132163 beginDrag(.reorient(ReorientMapping(positions: interpolator.positions(at: 0), camera: camera,
133164 viewportSize: viewportSize)))
134165 }
@@ -160,10 +191,12 @@ final class FoldSession {
160191 cancelDrag()
161192 }
162193
163 /// Called when the drag ends by any means, including cancellation.
194 /// Called when the drag ends by any means, including cancellation. A finished model left below
195 /// t = 1 is no longer finished.
164196 func cancelDrag() {
165197 grab = nil
166198 isDragSuspended = false
199 settle()
167200 }
168201
169202 /// Called when a two-finger gesture begins. A drag in progress is suspended and its effect on
@@ -196,8 +229,10 @@ final class FoldSession {
196229 /// 0...1, for VoiceOver's adjustable action. Reaching 1 completes the step, as lifting the
197230 /// finger there does.
198231 func adjust(_ direction: Int) {
232 guard !isLocked else { return }
199233 let tenths = direction > 0 ? (t * 10 + 1e-9).rounded(.down) + 1 : (t * 10 - 1e-9).rounded(.up) - 1
200234 t = min(max(tenths, 0), 10) / 10
235 settle()
201236 if t == 1 { completeStep() }
202237 }
203238
App/Sources/ReorientGesture.swift +1 −1
@@ -17,7 +17,7 @@ struct ReorientGesture: ViewModifier {
1717 func body(content: Content) -> some View {
1818 let reorients = session.step.kind == .turnOver || session.step.kind == .rotate
1919 content
20 .gesture(drag, isEnabled: reorients)
20 .gesture(drag, isEnabled: reorients && !session.isLocked)
2121 .onChange(of: isDragging) { _, dragging in if !dragging { session.cancelDrag() } }
2222 }
2323
App/Sources/StepView.swift +70 −10
@@ -4,11 +4,14 @@ import SwiftUI
44
55/// One step of a model: its diagram, captioned with the step's instruction, beside the folding
66/// 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.
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.
89struct StepView: View {
910 private let title: String
1011 @State private var session: FoldSession?
1112 @State private var isShowingSteps = false
13 @State private var isCelebrating = false
14 @Environment(\.accessibilityReduceMotion) private var reduceMotion
1215 @Environment(\.horizontalSizeClass) private var horizontalSizeClass
1316 @Environment(\.verticalSizeClass) private var verticalSizeClass
1417
@@ -37,6 +40,13 @@ struct StepView: View {
3740 .navigationBarTitleDisplayMode(.inline)
3841 .toolbar {
3942 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 }
4050 ToolbarItem(placement: .topBarTrailing) {
4151 Button("Steps", systemImage: "list.number") { isShowingSteps = true }
4252 .accessibilityIdentifier("steps.button")
@@ -91,24 +101,74 @@ struct StepView: View {
91101 .foldGesture(session)
92102 .reorientGesture(session)
93103 .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
94135 .accessibilityElement()
95136 .accessibilityLabel(session.step.instruction)
96 .accessibilityValue(session.t.formatted(.percent.precision(.fractionLength(0))))
97 .accessibilityAdjustableAction { direction in
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
98144 switch direction {
99145 case .increment: session.adjust(1)
100146 case .decrement: session.adjust(-1)
101147 @unknown default: break
102148 }
103149 }
104 .accessibilityIdentifier("fold.paper")
105 .overlay(alignment: .topLeading) {
106 if Self.isUITesting {
107 foldPath(session)
108 cameraValue(session)
109 stepKind(session)
110 }
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")
111167 }
168 }
169 .allowsHitTesting(false)
170 .transition(reduceMotion ? .opacity : .identity)
171 .accessibilityIdentifier("confetti")
112172 }
113173
114174 private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting")
App/Tests/FoldSessionTests.swift +130
@@ -238,3 +238,133 @@ private func cupInView(step: Int = 1) throws -> FoldSession {
238238 #expect(!session.isDragSuspended)
239239 session.endOrbit()
240240}
241
242/// The cup at its last step, finished by a drag to the end and a lift.
243@MainActor
244private func finishedCup() throws -> FoldSession {
245 let session = try cupInView(step: 6)
246 session.beginFoldDrag()
247 session.endDrag(translation: translation(session, to: 1))
248 return session
249}
250
251@MainActor @Test func finishingTheLastStepFinishesAndLocksTheModel() throws {
252 let session = try finishedCup()
253 #expect(session.step.index == 6)
254 #expect(session.t == 1)
255 #expect(session.isFinished)
256 #expect(session.isLocked)
257 #expect(session.finishCount == 1)
258}
259
260@MainActor @Test func adjustingToTheEndOfTheLastStepFinishesTheModel() throws {
261 let session = try cup(step: 6)
262 for _ in 0..<9 { session.adjust(1) }
263 #expect(!session.isFinished)
264 session.adjust(1)
265 #expect(session.isFinished && session.isLocked)
266}
267
268@MainActor @Test func dragsAndAdjustingAreIgnoredWhileLocked() throws {
269 let session = try finishedCup()
270 session.beginFoldDrag()
271 session.drag(translation: translation(session, from: 1, to: 0.5))
272 #expect(session.t == 1)
273 session.endDrag(translation: translation(session, from: 1, to: 0.5))
274 session.beginReorientDrag()
275 session.endDrag(translation: SIMD2(-1000, 0))
276 session.adjust(-1)
277 #expect(session.t == 1)
278 #expect(session.isLocked)
279 #expect(session.finishCount == 1)
280}
281
282@MainActor @Test func unlockingThenDraggingBackUnfoldsAndLeavesTheFinishedState() throws {
283 let session = try finishedCup()
284 session.toggleLock()
285 #expect(!session.isLocked)
286 #expect(session.isFinished)
287 session.beginFoldDrag()
288 session.drag(translation: translation(session, from: 1, to: 0.5))
289 #expect(abs(session.t - 0.5) < 0.01)
290 session.endDrag(translation: translation(session, from: 1, to: 0.5))
291 #expect(abs(session.t - 0.5) < 0.01)
292 #expect(!session.isFinished)
293 #expect(!session.isLocked)
294}
295
296@MainActor @Test func foldingTheLastStepAgainFinishesAgain() throws {
297 let session = try finishedCup()
298 session.toggleLock()
299 session.adjust(-1)
300 #expect(session.t == 0.9)
301 #expect(!session.isFinished)
302 session.beginFoldDrag()
303 session.endDrag(translation: translation(session, from: 0.9, to: 1))
304 #expect(session.isFinished && session.isLocked)
305 #expect(session.finishCount == 2)
306}
307
308@MainActor @Test func liftingAtTheEndWhileFinishedAndUnlockedDoesNotFinishAgain() throws {
309 let session = try finishedCup()
310 session.toggleLock()
311 session.beginFoldDrag()
312 session.endDrag(translation: translation(session, from: 1, to: 1))
313 #expect(session.isFinished && !session.isLocked)
314 #expect(session.finishCount == 1)
315}
316
317@MainActor @Test func openingAnotherStepLeavesTheFinishedState() throws {
318 let session = try finishedCup()
319 session.open(step: 2)
320 #expect(session.step.index == 2)
321 #expect(session.t == 0)
322 #expect(!session.isFinished && !session.isLocked)
323 session.toggleLock()
324 #expect(!session.isLocked)
325}
326
327@MainActor @Test func theLockDoesNothingBeforeTheModelIsFinished() throws {
328 let session = try cup(step: 6)
329 session.t = 1
330 session.toggleLock()
331 #expect(!session.isLocked && !session.isFinished)
332}
333
334@MainActor @Test func orbitAndZoomStillChangeTheCameraWhileLocked() throws {
335 let session = try finishedCup()
336 let camera = session.camera
337 session.beginOrbit()
338 session.orbit(by: SIMD2(0.4, -0.7))
339 session.zoom(by: 2)
340 session.endOrbit()
341 #expect(session.camera.eye != camera.eye)
342 #expect(session.camera.fieldOfView != camera.fieldOfView)
343 #expect(session.t == 1 && session.isLocked)
344}
345
346@MainActor @Test func anOrbitDuringADragBackLeavesTheModelFinished() throws {
347 let session = try finishedCup()
348 session.toggleLock()
349 session.beginFoldDrag()
350 session.drag(translation: translation(session, from: 1, to: 0.7))
351 session.beginOrbit()
352 #expect(session.t == 1)
353 session.endOrbit()
354 session.endDrag(translation: translation(session, from: 1, to: 0.7))
355 #expect(session.t == 1)
356 #expect(session.isFinished && !session.isLocked)
357 #expect(session.finishCount == 1)
358}
359
360@MainActor @Test func lockingDuringADragBackReturnsTheModelToTheEnd() throws {
361 let session = try finishedCup()
362 session.toggleLock()
363 session.beginFoldDrag()
364 session.drag(translation: translation(session, from: 1, to: 0.7))
365 session.toggleLock()
366 #expect(session.t == 1)
367 #expect(session.isFinished && session.isLocked)
368 session.endDrag(translation: translation(session, from: 1, to: 0.7))
369 #expect(session.t == 1 && session.isLocked)
370}
App/UITests/CompletionTests.swift added +57
@@ -0,0 +1,57 @@
1import XCTest
2
3final class CompletionTests: XCTestCase {
4 override func setUp() {
5 continueAfterFailure = false
6 }
7
8 func testFinishingTheCupLocksItAndUnlockingLetsItUnfold() {
9 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
10 app.buttons["Cup"].tap()
11 app.buttons["steps.button"].tap()
12 app.buttons["step.6"].tap()
13 XCTAssertTrue(app.buttons["step.6"].waitForNonExistence(timeout: 5))
14 let lock = app.buttons["paper.lock"]
15 XCTAssertFalse(lock.exists)
16
17 completeCurrentFold(app)
18 let celebration = app.descendants(matching: .any)["confetti"]
19 XCTAssertTrue(celebration.waitForExistence(timeout: 2))
20 XCTAssertTrue(lock.waitForExistence(timeout: 5))
21 XCTAssertEqual(lock.label, "Unlock to unfold")
22 let paper = app.otherElements["fold.paper"]
23 XCTAssertEqual(paper.value as? String, "Folded, locked")
24 XCTAssertTrue(celebration.waitForNonExistence(timeout: 5))
25
26 dragBackHalfway(app)
27 XCTAssertEqual(paper.value as? String, "Folded, locked")
28 XCTAssertEqual(app.staticTexts["step.index"].label, "6")
29
30 lock.tap()
31 XCTAssertEqual(lock.label, "Lock")
32 XCTAssertEqual(paper.value as? String, "100%")
33 dragBackHalfway(app)
34 let value = paper.value as? String ?? ""
35 XCTAssertTrue(value.hasSuffix("%"), value)
36 XCTAssertLessThan(Int(value.dropLast()) ?? 100, 100, value)
37 XCTAssertFalse(lock.exists)
38 }
39}
40
41/// Drags the current step from the end of its path, read from `fold.path`, back to its middle.
42private func dragBackHalfway(_ app: XCUIApplication) {
43 let paper = app.otherElements["fold.paper"]
44 let marker = app.descendants(matching: .any)["fold.path"]
45 XCTAssertTrue(marker.waitForExistence(timeout: 5))
46 let samples = (marker.value as? String ?? "").split(separator: " ").map { pair in
47 let xy = pair.split(separator: ",").map { Double($0)! }
48 return CGVector(dx: xy[0], dy: xy[1])
49 }
50 let end = samples[samples.count - 1], middle = samples[samples.count / 2]
51 let size = paper.frame.size
52 let move = CGVector(dx: (middle.dx - end.dx) * size.width, dy: (middle.dy - end.dy) * size.height)
53 let inside = (0.02...0.98).contains(end.dx) && (0.02...0.98).contains(end.dy)
54 let start = paper.coordinate(withNormalizedOffset: inside ? end : CGVector(dx: 0.5, dy: 0.5))
55 start.press(forDuration: 0.1, thenDragTo: start.withOffset(move), withVelocity: .default,
56 thenHoldForDuration: 0.3)
57}