Commit 30cbc803de

30cbc803de990e1d9c7a9499fde2646ace9b60c6

parent: 60b5dd6bdd

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 04:41 UTC

Lock the finished model and celebrate

Closes #10

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 +34 −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
@@ -17,8 +17,18 @@ final class FoldSession {
1717 private var order: LayerOrder
1818
1919 var t = 0.0 {
20 didSet { if t != oldValue { pose() } }
20 didSet {
21 guard t != oldValue else { return }
22 if t < 1 { isFinished = false; isLocked = false }
23 pose()
24 }
2125 }
26 /// Whether the last step has been completed and `t` has stayed at 1 since.
27 private(set) var isFinished = false
28 /// Whether the finished model ignores drags and adjustment. Orbit and zoom still work.
29 private(set) var isLocked = false
30 /// How many times the model has been finished.
31 private(set) var finishCount = 0
2232 /// The unit vector from the camera's target toward its eye.
2333 var eyeDirection: SIMD3<Double> {
2434 didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } }
@@ -70,15 +80,29 @@ final class FoldSession {
7080 }
7181
7282 /// 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.
83 /// Completing the last step finishes the model at t = 1 and locks it.
7484 func completeStep() {
75 guard t == 1, step.index + 1 < model.frames.count else { return }
76 open(step: step.index + 1)
85 guard t == 1 else { return }
86 if step.index + 1 < model.frames.count {
87 open(step: step.index + 1)
88 } else if !isFinished {
89 isFinished = true
90 isLocked = true
91 finishCount += 1
92 }
93 }
94
95 /// Locks or unlocks a finished model. Unlocked, its last step can be dragged back to unfold it.
96 func toggleLock() {
97 guard isFinished else { return }
98 isLocked.toggle()
99 if isLocked { cancelDrag() }
77100 }
78101
79102 /// 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.
103 /// drag in progress no longer moves `t` or completes a step, and a finished model is no longer
104 /// finished. Opening the current step leaves it as it is. A step that cannot be read leaves the
105 /// session as it is and stops a Debug build.
82106 func open(step n: Int) {
83107 guard n != step.index else { return }
84108 cancelDrag()
@@ -121,6 +145,7 @@ final class FoldSession {
121145 /// Called when a one-finger drag on a fold step begins: the moving faces then follow the
122146 /// finger along `mapping`'s path.
123147 func beginFoldDrag() {
148 guard !isLocked else { return }
124149 let mapping = self.mapping
125150 beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t)))
126151 }
@@ -129,6 +154,7 @@ final class FoldSession {
129154 /// component then turns the model across its on-screen width, measured on the frame the step
130155 /// starts from, which a vertical turn-over would otherwise shrink to an edge midway.
131156 func beginReorientDrag() {
157 guard !isLocked else { return }
132158 beginDrag(.reorient(ReorientMapping(positions: interpolator.positions(at: 0), camera: camera,
133159 viewportSize: viewportSize)))
134160 }
@@ -196,6 +222,7 @@ final class FoldSession {
196222 /// 0...1, for VoiceOver's adjustable action. Reaching 1 completes the step, as lifting the
197223 /// finger there does.
198224 func adjust(_ direction: Int) {
225 guard !isLocked else { return }
199226 let tenths = direction > 0 ? (t * 10 + 1e-9).rounded(.down) + 1 : (t * 10 - 1e-9).rounded(.up) - 1
200227 t = min(max(tenths, 0), 10) / 10
201228 if t == 1 { completeStep() }
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 +67 −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,71 @@ 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 AccessibilityNotification.Announcement("\(title) folded").post()
123 withAnimation(.easeIn(duration: 0.6)) { isCelebrating = true }
124 do { try await Task.sleep(for: .seconds(Confetti.duration)) } catch { return }
125 withAnimation { isCelebrating = false }
126 }
127 }
128
129 @ViewBuilder
130 private func paperElement(_ session: FoldSession) -> some View {
131 let element = Color.clear
94132 .accessibilityElement()
95133 .accessibilityLabel(session.step.instruction)
96 .accessibilityValue(session.t.formatted(.percent.precision(.fractionLength(0))))
97 .accessibilityAdjustableAction { direction in
134 .accessibilityValue(session.isLocked ? "Folded, locked"
135 : session.t.formatted(.percent.precision(.fractionLength(0))))
136 .accessibilityIdentifier("fold.paper")
137 if session.isLocked {
138 element
139 } else {
140 element.accessibilityAdjustableAction { direction in
98141 switch direction {
99142 case .increment: session.adjust(1)
100143 case .decrement: session.adjust(-1)
101144 @unknown default: break
102145 }
103146 }
104 .accessibilityIdentifier("fold.paper")
105 .overlay(alignment: .topLeading) {
106 if Self.isUITesting {
107 foldPath(session)
108 cameraValue(session)
109 stepKind(session)
110 }
147 }
148 }
149
150 /// Confetti over the paper, or under Reduce Motion a label that fades in.
151 private var celebration: some View {
152 Group {
153 if reduceMotion {
154 Text("Folded")
155 .font(.largeTitle.bold())
156 .padding(.horizontal, 24)
157 .padding(.vertical, 12)
158 .background(.regularMaterial, in: Capsule())
159 } else {
160 Confetti()
161 .clipped()
162 .accessibilityElement()
163 .accessibilityLabel("Folded")
111164 }
165 }
166 .allowsHitTesting(false)
167 .transition(.opacity)
168 .accessibilityIdentifier("confetti")
112169 }
113170
114171 private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting")
App/Tests/FoldSessionTests.swift +104
@@ -238,3 +238,107 @@ 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 #expect(!session.isFinished)
291 #expect(!session.isLocked)
292 session.endDrag(translation: translation(session, from: 1, to: 0.5))
293 #expect(!session.isFinished)
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}
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}