Commit 726a503fa7

726a503fa793a769d0ef7ab3ef8815e61806dd29

parent: a11f067734

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 20:11 UTC

Step list and dragging back (Task 14b) (!8)

- Step list on demand: the toolbar "Steps" button opens every step's number and instruction, as a popover on iPad and a sheet on iPhone, scrolled to the current step. Choosing a step opens it at its start; choosing the current step leaves it alone. The title reads "Step n of N".
- `FoldSession.open(step:)` resets t, the camera, the diagram and the mapping, and cancels any drag in progress.
- The fold drag crosses axis windows and non-rigid phases in both directions. The drag carries a `FoldParameterMapping.Position` (t and segment), so a retraced stretch keeps its segment. A fold-and-unfold stays one way at its peak, because its return half is the unfold. The 0.5-point end tolerance applies at t = 1 only.
- The plan gains Task 14b.

Verification:
- `swift test --package-path Packages/FoldKit` passes.
- `xcodebuild … -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`: 20 unit and 19 UI tests pass, including the accessibility audits with the list open.
- FoldGestureTests with `-test-iterations 30`: 60/60 pass.

Closes #9

Layout: unified · split

App/Sources/FoldSession.swift +22 −11
@@ -7,7 +7,7 @@ import simd
7 7
8/// One model being folded: the current step, its fold parameter `t` in 0...1, and the model 8/// One model being folded: the current step, its fold parameter `t` in 0...1, and the model
9/// view's orientation. Nothing here changes `t` on its own; the step changes only when the user 9/// view's orientation. Nothing here changes `t` on its own; the step changes only when the user
10/// completes it. 10/// completes it or opens another.
11@MainActor @Observable 11@MainActor @Observable
12final class FoldSession { 12final class FoldSession {
13 let model: FoldFile 13 let model: FoldFile
@@ -70,16 +70,24 @@ final class FoldSession {
70 } 70 }
71 71
72 /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete. 72 /// 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, as it does when the next step cannot 73 /// After the last step the finished model stays at t = 1.
74 /// be read, which stops a Debug build.
75 func completeStep() { 74 func completeStep() {
76 guard t == 1, step.index + 1 < model.frames.count else { return } 75 guard t == 1, step.index + 1 < model.frames.count else { return }
76 open(step: step.index + 1)
77 }
78
79 /// 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.
82 func open(step n: Int) {
83 guard n != step.index else { return }
84 cancelDrag()
77 let next: FoldStep, nextOrder: LayerOrder 85 let next: FoldStep, nextOrder: LayerOrder
78 do { 86 do {
79 next = try readStep(step.index + 1, in: model) 87 next = try readStep(n, in: model)
80 nextOrder = try LayerOrder.active(for: next, in: model) 88 nextOrder = try LayerOrder.active(for: next, in: model)
81 } catch { 89 } catch {
82 assertionFailure("step \(step.index + 1) of \(model.fileTitle ?? "?"): \(error)") 90 assertionFailure("step \(n) of \(model.fileTitle ?? "?"): \(error)")
83 return 91 return
84 } 92 }
85 step = next 93 step = next
@@ -92,12 +100,13 @@ final class FoldSession {
92 up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye) 100 up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye)
93 fieldOfView = Self.defaultFieldOfView 101 fieldOfView = Self.defaultFieldOfView
94 cachedMapping = nil 102 cachedMapping = nil
95 t = 0 103 if t == 0 { pose() } else { t = 0 }
96 } 104 }
97 105
98 /// What maps a one-finger drag's translation to `t`. 106 /// What maps a one-finger drag's translation to `t`.
99 private enum DragMapping { 107 private enum DragMapping {
100 case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>) 108 /// `position` is where the latest movement left the drag on the path.
109 case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>, position: FoldParameterMapping.Position)
101 case reorient(ReorientMapping) 110 case reorient(ReorientMapping)
102 } 111 }
103 112
@@ -113,7 +122,7 @@ final class FoldSession {
113 /// finger along `mapping`'s path. 122 /// finger along `mapping`'s path.
114 func beginFoldDrag() { 123 func beginFoldDrag() {
115 let mapping = self.mapping 124 let mapping = self.mapping
116 beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t))) 125 beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t)))
117 } 126 }
118 127
119 /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal 128 /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal
@@ -133,9 +142,11 @@ final class FoldSession {
133 func drag(translation: SIMD2<Double>) { 142 func drag(translation: SIMD2<Double>) {
134 guard let grab, !isDragSuspended else { return } 143 guard let grab, !isDragSuspended else { return }
135 switch grab.mapping { 144 switch grab.mapping {
136 case let .fold(mapping, grabbedAt): 145 case let .fold(mapping, grabbedAt, position):
137 t = mapping.parameter(grabbedAt: grabbedAt, translation: translation, 146 let next = mapping.position(grabbedAt: grabbedAt, translation: translation,
138 current: mapping.isDegenerate ? grab.start : t) 147 current: mapping.isDegenerate ? mapping.position(at: grab.start) : position)
148 self.grab?.mapping = .fold(mapping, grabbedAt: grabbedAt, position: next)
149 t = next.t
139 case let .reorient(mapping): 150 case let .reorient(mapping):
140 t = mapping.parameter(translation: translation.x, current: grab.start) 151 t = mapping.parameter(translation: translation.x, current: grab.start)
141 } 152 }
App/Sources/StepListView.swift added +53
@@ -0,0 +1,53 @@
1import Folding
2import SwiftUI
3
4/// Every step of the session's model by number and instruction, the current one checked and
5/// scrolled into view. Choosing a step opens it at its start; choosing the current step leaves it
6/// as it is. Either closes the list.
7struct StepListView: View {
8 let session: FoldSession
9 private let steps: [FoldStep]
10 @Environment(\.dismiss) private var dismiss
11
12 init(session: FoldSession) {
13 self.session = session
14 steps = (try? readSteps(session.model)) ?? []
15 }
16
17 var body: some View {
18 VStack(spacing: 0) {
19 Text("Steps")
20 .font(.headline)
21 .accessibilityAddTraits(.isHeader)
22 .padding()
23 ScrollViewReader { proxy in
24 List(steps, id: \.index, rowContent: row)
25 .listStyle(.plain)
26 .onAppear { proxy.scrollTo(session.step.index) }
27 }
28 }
29 }
30
31 private func row(_ step: FoldStep) -> some View {
32 let isCurrent = step.index == session.step.index
33 return Button {
34 session.open(step: step.index)
35 dismiss()
36 } label: {
37 HStack(alignment: .firstTextBaseline, spacing: 12) {
38 Text("\(step.index)")
39 .font(.headline)
40 .monospacedDigit()
41 Text(step.instruction)
42 .frame(maxWidth: .infinity, alignment: .leading)
43 Image(systemName: "checkmark")
44 .fontWeight(.semibold)
45 .opacity(isCurrent ? 1 : 0)
46 }
47 }
48 .foregroundStyle(.primary)
49 .accessibilityLabel("Step \(step.index), \(step.instruction)")
50 .accessibilityAddTraits(isCurrent ? .isSelected : [])
51 .accessibilityIdentifier("step.\(step.index)")
52 }
53}
App/Sources/StepView.swift +20 −2
@@ -3,10 +3,12 @@ import Notation
3import SwiftUI 3import SwiftUI
4 4
5/// One step of a model: its diagram, captioned with the step's instruction, beside the folding 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. 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.
7struct StepView: View { 8struct StepView: View {
8 private let title: String 9 private let title: String
9 @State private var session: FoldSession? 10 @State private var session: FoldSession?
11 @State private var isShowingSteps = false
10 @Environment(\.horizontalSizeClass) private var horizontalSizeClass 12 @Environment(\.horizontalSizeClass) private var horizontalSizeClass
11 @Environment(\.verticalSizeClass) private var verticalSizeClass 13 @Environment(\.verticalSizeClass) private var verticalSizeClass
12 14
@@ -31,8 +33,24 @@ struct StepView: View {
31 ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle") 33 ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle")
32 } 34 }
33 } 35 }
34 .navigationTitle(title) 36 .navigationTitle(session.map { "Step \($0.step.index) of \($0.model.frames.count - 1)" } ?? title)
35 .navigationBarTitleDisplayMode(.inline) 37 .navigationBarTitleDisplayMode(.inline)
38 .toolbar {
39 if let session {
40 ToolbarItem(placement: .topBarTrailing) {
41 Button("Steps", systemImage: "list.number") { isShowingSteps = true }
42 .accessibilityIdentifier("steps.button")
43 .popover(isPresented: $isShowingSteps) {
44 StepListView(session: session)
45 .frame(idealWidth: 360, idealHeight: 480)
46 .presentationDetents([.medium, .large])
47 .presentationDragIndicator(.visible)
48 // the paper seen through a translucent sheet fails the contrast audit
49 .presentationBackground(.background)
50 }
51 }
52 }
53 }
36 } 54 }
37 55
38 /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond 56 /// The caption takes the height it needs up to `captionShare` of the pane, and scrolls beyond
App/Tests/FoldSessionTests.swift +78
@@ -160,3 +160,81 @@ private func cupInView(step: Int = 1) throws -> FoldSession {
160 #expect(!session.isDragSuspended) 160 #expect(!session.isDragSuspended)
161 session.endOrbit() 161 session.endOrbit()
162} 162}
163
164@MainActor @Test func openingAStepStartsItFromTheFrameBeforeIt() throws {
165 let session = try cup()
166 session.orbit(by: SIMD2(0.4, -0.7))
167 session.zoom(by: 2)
168 session.t = 0.6
169 session.open(step: 4)
170 let fresh = try cup(step: 4)
171 #expect(session.step.index == 4)
172 #expect(session.t == 0)
173 #expect(session.camera.eye == fresh.camera.eye)
174 #expect(session.camera.up == fresh.camera.up)
175 #expect(session.camera.fieldOfView == fresh.camera.fieldOfView)
176 #expect(session.diagram == fresh.diagram)
177 #expect(session.meshPositions == fresh.meshPositions)
178}
179
180@MainActor @Test func openingAnEarlierStepGoesBackToItsStart() throws {
181 let session = try cup(step: 4)
182 session.t = 1
183 session.completeStep()
184 session.open(step: 2)
185 #expect(session.step.index == 2)
186 #expect(session.t == 0)
187 #expect(session.meshPositions == (try cup(step: 2)).meshPositions)
188}
189
190@MainActor @Test func openingTheCurrentStepLeavesItAlone() throws {
191 let session = try cup(step: 3)
192 session.orbit(by: SIMD2(0.4, -0.7))
193 session.t = 0.4
194 let camera = session.camera
195 session.open(step: 3)
196 #expect(session.step.index == 3)
197 #expect(session.t == 0.4)
198 #expect(session.camera.eye == camera.eye)
199}
200
201@MainActor @Test func aDragBackTakesTheFoldBackToItsStart() throws {
202 let session = try cupInView()
203 session.beginFoldDrag()
204 session.drag(translation: translation(session, to: 0.7))
205 session.drag(translation: translation(session, to: 0.3))
206 #expect(abs(session.t - 0.3) < 0.01)
207 session.endDrag(translation: .zero)
208 #expect(session.step.index == 1)
209 #expect(session.t == 0)
210}
211
212@MainActor @Test func openingAStepFromTheStartOfAnotherShowsTheNewStep() throws {
213 let session = try cup()
214 session.open(step: 4)
215 #expect(session.meshPositions == (try cup(step: 4)).meshPositions)
216}
217
218@MainActor @Test func openingAStepDuringADragLeavesTheNewStepAlone() throws {
219 let session = try cupInView()
220 session.beginFoldDrag()
221 let end = translation(session, to: 1)
222 session.drag(translation: translation(session, to: 0.5))
223 session.open(step: 4)
224 session.drag(translation: end)
225 session.endDrag(translation: end)
226 #expect(session.step.index == 4)
227 #expect(session.t == 0)
228}
229
230@MainActor @Test func anOrbitAfterOpeningAStepDuringADragLeavesTAlone() throws {
231 let session = try cupInView()
232 session.t = 0.2
233 session.beginFoldDrag()
234 session.drag(translation: translation(session, from: 0.2, to: 0.6))
235 session.open(step: 4)
236 session.beginOrbit()
237 #expect(session.t == 0)
238 #expect(!session.isDragSuspended)
239 session.endOrbit()
240}
App/UITests/AccessibilityAuditTests.swift +12 −5
@@ -1,9 +1,10 @@
1import XCTest 1import XCTest
2 2
3/// Opens every step of the cup by the labels VoiceOver sees and runs Xcode's accessibility audit 3/// Opens the step list and every step of the cup by the labels VoiceOver sees and runs Xcode's
4/// on each screen, at the default text size and at the largest accessibility size. Also checks 4/// accessibility audit on each screen, at the default text size and at the largest accessibility
5/// that two-finger gestures on the paper change the view without advancing the fold or touching 5/// size. Also checks that two-finger gestures on the paper change the view without advancing the
6/// the diagram. XCUITest has no two-finger drag, so a pinch and a rotation stand in for it. 6/// fold or touching the diagram. XCUITest has no two-finger drag, so a pinch and a rotation stand
7/// in for it.
7final class AccessibilityAuditTests: XCTestCase { 8final class AccessibilityAuditTests: XCTestCase {
8 static let largestText = "UICTContentSizeCategoryAccessibilityXXXL" 9 static let largestText = "UICTContentSizeCategoryAccessibilityXXXL"
9 /// Elements that exist only under `-UITesting`. 10 /// Elements that exist only under `-UITesting`.
@@ -59,7 +60,8 @@ final class AccessibilityAuditTests: XCTestCase {
59 60
60 // MARK: - Helpers 61 // MARK: - Helpers
61 62
62 /// The model list, then every step of the cup, each advanced by the user's own drag. 63 /// The model list, the cup's step list, then every step of the cup, each advanced by the user's
64 /// own drag.
63 private func everyScreen(textSize: String?) throws { 65 private func everyScreen(textSize: String?) throws {
64 sizeName = textSize == nil ? "default" : "largest" 66 sizeName = textSize == nil ? "default" : "largest"
65 let app = XCUIApplication() 67 let app = XCUIApplication()
@@ -70,6 +72,11 @@ final class AccessibilityAuditTests: XCTestCase {
70 app.buttons["Cup"].tap() 72 app.buttons["Cup"].tap()
71 let index = app.staticTexts["step.index"] 73 let index = app.staticTexts["step.index"]
72 XCTAssertTrue(index.waitForExistence(timeout: 5)) 74 XCTAssertTrue(index.waitForExistence(timeout: 5))
75 app.buttons["steps.button"].tap()
76 XCTAssertTrue(app.buttons["step.1"].waitForExistence(timeout: 5))
77 try audit(app, "step list")
78 app.buttons["step.1"].tap()
79 XCTAssertTrue(app.buttons["step.1"].waitForNonExistence(timeout: 5))
73 while true { 80 while true {
74 let step = index.label 81 let step = index.label
75 try audit(app, "step \(step)") 82 try audit(app, "step \(step)")
App/UITests/StepListTests.swift added +72
@@ -0,0 +1,72 @@
1import XCTest
2
3final class StepListTests: XCTestCase {
4 override func setUp() {
5 continueAfterFailure = false
6 }
7
8 func testTheStepListOpensAChosenStepAtItsStart() {
9 let app = XCUIApplication(); app.launch()
10 app.buttons["Cup"].tap()
11 app.buttons["steps.button"].tap()
12 app.buttons["step.5"].tap()
13 XCTAssertEqual(app.staticTexts["step.index"].label, "5")
14 XCTAssertEqual(app.otherElements["fold.paper"].value as? String, "0%")
15 }
16
17 func testTheStepListNamesEveryStep() {
18 let app = XCUIApplication(); app.launch()
19 app.buttons["Cup"].tap()
20 let caption = app.staticTexts["diagram.caption"].label
21 app.buttons["steps.button"].tap()
22 let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'step.'"))
23 XCTAssertTrue(rows.firstMatch.waitForExistence(timeout: 5))
24 XCTAssertEqual(rows.count, 6)
25 for n in 1...6 {
26 let label = app.buttons["step.\(n)"].label
27 XCTAssertTrue(label.hasPrefix("Step \(n), "), label)
28 XCTAssertGreaterThan(label.count, "Step \(n), ".count)
29 }
30 XCTAssertEqual(app.buttons["step.1"].label, "Step 1, \(caption)")
31 XCTAssertTrue(app.buttons["step.1"].isSelected)
32 XCTAssertFalse(app.buttons["step.2"].isSelected)
33 XCTAssertTrue(app.staticTexts["Steps"].exists)
34 }
35
36 func testTheStepListOpensScrolledToTheCurrentStep() {
37 // at the largest text size the cup's six rows do not fit the sheet
38 let app = XCUIApplication()
39 app.launchArguments = ["-UIPreferredContentSizeCategoryName", AccessibilityAuditTests.largestText]
40 app.launch()
41 app.buttons["Cup"].tap()
42 app.buttons["steps.button"].tap()
43 XCTAssertTrue(app.buttons["step.1"].waitForExistence(timeout: 5))
44 let last = app.buttons["step.6"]
45 for _ in 0..<8 where !(last.exists && last.isHittable) { app.collectionViews.firstMatch.swipeUp() }
46 last.tap()
47 XCTAssertTrue(last.waitForNonExistence(timeout: 5))
48 app.buttons["steps.button"].tap()
49 let row = app.buttons["step.6"]
50 XCTAssertTrue(row.waitForExistence(timeout: 5))
51 XCTAssertTrue(row.isHittable)
52 XCTAssertFalse(app.buttons["step.1"].isHittable)
53 }
54
55 func testChoosingTheCurrentStepClosesTheListAndLeavesTheFoldAlone() {
56 let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch()
57 app.buttons["Cup"].tap()
58 dragCurrentFold(app, to: 0.5)
59 let released = app.otherElements["fold.paper"].value as? String
60 app.buttons["steps.button"].tap()
61 app.buttons["step.1"].tap()
62 XCTAssertTrue(app.buttons["step.1"].waitForNonExistence(timeout: 5))
63 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
64 XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released)
65 }
66
67 func testTheTitleCountsTheSteps() {
68 let app = XCUIApplication(); app.launch()
69 app.buttons["Cup"].tap()
70 XCTAssertTrue(app.navigationBars["Step 1 of 6"].waitForExistence(timeout: 5))
71 }
72}
Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift +103 −26
@@ -19,11 +19,20 @@ public struct FoldParameterMapping: Sendable {
19 /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere. 19 /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere.
20 public let isDegenerate: Bool 20 public let isDegenerate: Bool
21 21
22 /// Where a drag is on the path: its parameter and the segment it is in. At a boundary `t`
23 /// alone does not say which: a drag that reaches a boundary has crossed it.
24 public struct Position: Sendable, Equatable {
25 public let t: Double
26 let segment: Int
27 }
28
22 /// The search polyline: `path`'s samples with the segment boundaries added. 29 /// The search polyline: `path`'s samples with the segment boundaries added.
23 private let ts: [Double] 30 private let ts: [Double]
24 private let points: [SIMD2<Double>] 31 private let points: [SIMD2<Double>]
25 /// Index ranges of `ts` searched one at a time, in order. 32 /// Index ranges of `ts`, one per segment, in order.
26 private let segments: [ClosedRange<Int>] 33 private let segments: [ClosedRange<Int>]
34 /// Per segment, whether a drag can cross back over its start: not at a fold-and-unfold's peak.
35 private let reversible: [Bool]
27 36
28 private static let samples = 129 37 private static let samples = 129
29 private static let minimumLength = 8.0 38 private static let minimumLength = 8.0
@@ -34,12 +43,12 @@ public struct FoldParameterMapping: Sendable {
34 private static let preference = 0.5 43 private static let preference = 0.5
35 /// How far past the best point so far the search continues, in points. 44 /// How far past the best point so far the search continues, in points.
36 private static let slack = 8.0 45 private static let slack = 8.0
37 /// How near its segment's end, along the path, a point counts as the end, in points. 46 /// How near the path's end, measured along it, a point counts as the end, in points.
38 private static let endTolerance = 0.5 47 private static let endTolerance = 0.5
39 48
40 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) { 49 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) {
41 var followed: [(faces: [Int], window: ClosedRange<Double>)] 50 var followed: [(faces: [Int], window: ClosedRange<Double>)]
42 var boundaries: Set<Double> = [0, 1] 51 var boundaries: Set<Double> = [0, 1], peaks: Set<Double> = []
43 if step.nonRigid, let pop = step.pop { 52 if step.nonRigid, let pop = step.pop {
44 followed = step.axes.map { (Array($0.movingFaces), 0...1) } 53 followed = step.axes.map { (Array($0.movingFaces), 0...1) }
45 boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound]) 54 boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound])
@@ -47,11 +56,12 @@ public struct FoldParameterMapping: Sendable {
47 followed = step.axes.map { (Array($0.movingFaces), $0.window) } 56 followed = step.axes.map { (Array($0.movingFaces), $0.window) }
48 for w in step.axes.map(\.window) { 57 for w in step.axes.map(\.window) {
49 boundaries.formUnion([w.lowerBound, w.upperBound]) 58 boundaries.formUnion([w.lowerBound, w.upperBound])
50 if step.kind == .foldAndUnfold { boundaries.insert((w.lowerBound + w.upperBound) / 2) } 59 if step.kind == .foldAndUnfold { peaks.insert((w.lowerBound + w.upperBound) / 2) }
51 } 60 }
52 } 61 }
53 if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] } 62 if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] }
54 let bounds = boundaries.sorted() 63 let bounds = boundaries.union(peaks).sorted()
64 reversible = bounds.dropLast().map { $0 > 0 && !peaks.contains($0) }
55 65
56 let n = Double(Self.samples - 1) 66 let n = Double(Self.samples - 1)
57 let grid = (0..<Self.samples).map { Double($0) / n } 67 let grid = (0..<Self.samples).map { Double($0) / n }
@@ -98,36 +108,102 @@ public struct FoldParameterMapping: Sendable {
98 return points[i] + u * (points[i + 1] - points[i]) 108 return points[i] + u * (points[i + 1] - points[i])
99 } 109 }
100 110
101 /// The parameter, in 0...1, whose point of `path` is nearest `grabbedAt + translation`, where 111 /// The position at `t`, clamped to 0...1; at a boundary, in the later segment.
102 /// `grabbedAt` is `point(at:)` of t when the drag began. The search walks the path outward from 112 public func position(at t: Double) -> Position {
103 /// `current`, within the segment `current` is in, the later one at a boundary. Segments are one 113 let t = min(max(t, 0), 1)
104 /// way: once `current` reaches a segment's end, the segments before it are not searched again. 114 return Position(t: t, segment: segments.lastIndex { ts[$0.lowerBound] <= t }!)
105 /// A point within half a point of its segment's end, measured along the path, is the end, so a 115 }
106 /// segment whose path turns back at its end can be finished. 116
117 /// The parameter `position(grabbedAt:translation:current:)` gives from `position(at: current)`.
118 public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double {
119 position(grabbedAt: grabbedAt, translation: translation, current: position(at: current)).t
120 }
121
122 /// The position whose point of `path` is nearest `grabbedAt + translation`, where `grabbedAt`
123 /// is `point(at:)` of t when the drag began.
124 ///
125 /// The search walks the path outward from `current` within its segment. It also searches the
126 /// segment beyond a boundary when `current` is within one sample of the boundary, or when the
127 /// nearest point is the boundary itself, so that the finger has reached it. A neighbour's point
128 /// is taken only if strictly nearer. So where the path doubles back on screen at a boundary, a
129 /// finger moving along the retraced stretch stays in the segment the drag is in, and changes
130 /// segment only at the turnaround. A drag that reaches a boundary crosses it, so the next
131 /// movement along a retraced stretch continues into the segment beyond. Boundaries are crossed
132 /// both ways, except a fold-and-unfold's peak, which is crossed only forward. A point within
133 /// half a point of the path's end, measured along the path, is the end.
107 /// 134 ///
108 /// When the path is degenerate the drag's downward component advances the fold over 160 135 /// When the path is degenerate the drag's downward component advances the fold over 160
109 /// points from `current`, which is then the parameter when the drag began. 136 /// points from `current`, which is then the position when the drag began.
110 public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double { 137 public func position(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Position) -> Position {
111 let current = min(max(current, 0), 1) 138 if isDegenerate { return position(at: current.t + translation.y / Self.fallbackThrow) }
112 if isDegenerate { return min(max(current + translation.y / Self.fallbackThrow, 0), 1) }
113 139
114 let target = grabbedAt + translation 140 let target = grabbedAt + translation
115 let segment = segments.last { ts[$0.lowerBound] <= current }! 141 let s = current.segment
116 // the polyline edge from point i to point i + 1 holding current 142 // the polyline edge from point i to point i + 1 holding current
117 var start = segment.lowerBound 143 var start = segments[s].lowerBound
118 while start + 1 < segment.upperBound && ts[start + 1] <= current { start += 1 } 144 while start + 1 < segments[s].upperBound && ts[start + 1] <= current.t { start += 1 }
119 145
120 func nearest(onEdge i: Int) -> (edge: Int, u: Double, distance: Double) { 146 let own = nearest(target, in: s, from: start, directions: [1, -1])
147 var best = own
148 for direction in [1, -1] {
149 let edge = direction > 0 ? segments[s].upperBound - 1 : segments[s].lowerBound + 1
150 var near = direction > 0 ? current.t >= ts[edge] : current.t <= ts[edge]
151 var from = own
152 while near || from.toBoundary(direction) == 0 {
153 let n = from.segment + direction
154 guard n >= 0 && n < segments.count && (direction > 0 || reversible[from.segment]) else { break }
155 let candidate = nearest(target, in: n, from: direction > 0 ? segments[n].lowerBound : segments[n].upperBound - 1,
156 directions: [direction])
157 guard candidate.distance < best.distance else { break }
158 best = candidate
159 from = candidate
160 near = false
161 }
162 }
163
164 if best.segment == segments.count - 1 && best.toBoundary(1) <= Self.endTolerance {
165 return Position(t: 1, segment: best.segment)
166 }
167 let t = (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1]
168 var segment = best.segment
169 if t != current.t {
170 if best.toBoundary(1) == 0 && segment + 1 < segments.count {
171 segment += 1
172 } else if best.toBoundary(-1) == 0 && reversible[segment] {
173 segment -= 1
174 }
175 }
176 return Position(t: t, segment: segment)
177 }
178
179 /// A point of the search polyline: `u` of the way along edge `edge` of segment `segment`.
180 private struct Nearest {
181 let segment: Int
182 let edge: Int
183 let u: Double
184 let distance: Double
185 /// Distance along the path to the segment's end (`direction` 1) or start (−1).
186 let toEnd: Double
187 let toStart: Double
188
189 func toBoundary(_ direction: Int) -> Double { direction > 0 ? toEnd : toStart }
190 }
191
192 /// The point of segment `s` nearest `target`, walking outward from edge `start` in each of
193 /// `directions` until an edge is `slack` farther than the best so far.
194 private func nearest(_ target: SIMD2<Double>, in s: Int, from start: Int, directions: [Int]) -> Nearest {
195 let segment = segments[s]
196 func onEdge(_ i: Int) -> (edge: Int, u: Double, distance: Double) {
121 let a = points[i], d = points[i + 1] - points[i] 197 let a = points[i], d = points[i + 1] - points[i]
122 let lengthSquared = dot(d, d) 198 let lengthSquared = dot(d, d)
123 let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0 199 let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0
124 return (i, u, distance(a + u * d, target)) 200 return (i, u, distance(a + u * d, target))
125 } 201 }
126 var best = nearest(onEdge: start) 202 var best = onEdge(start)
127 for direction in [1, -1] { 203 for direction in directions {
128 var i = start + direction 204 var i = start + direction
129 while i >= segment.lowerBound && i < segment.upperBound { 205 while i >= segment.lowerBound && i < segment.upperBound {
130 let candidate = nearest(onEdge: i) 206 let candidate = onEdge(i)
131 if candidate.distance < best.distance { 207 if candidate.distance < best.distance {
132 best = candidate 208 best = candidate
133 } else if candidate.distance > best.distance + Self.slack { 209 } else if candidate.distance > best.distance + Self.slack {
@@ -136,10 +212,11 @@ public struct FoldParameterMapping: Sendable {
136 i += direction 212 i += direction
137 } 213 }
138 } 214 }
139 let end = segment.upperBound 215 let length = distance(points[best.edge], points[best.edge + 1])
140 var toEnd = (1 - best.u) * distance(points[best.edge], points[best.edge + 1]) 216 var toEnd = (1 - best.u) * length, toStart = best.u * length
141 for i in best.edge + 1 ..< end { toEnd += distance(points[i], points[i + 1]) } 217 for i in best.edge + 1 ..< segment.upperBound { toEnd += distance(points[i], points[i + 1]) }
142 return toEnd <= Self.endTolerance ? ts[end] : (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1] 218 for i in segment.lowerBound ..< best.edge { toStart += distance(points[i], points[i + 1]) }
219 return Nearest(segment: s, edge: best.edge, u: best.u, distance: best.distance, toEnd: toEnd, toStart: toStart)
143 } 220 }
144} 221}
145 222
Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift +64
@@ -126,3 +126,67 @@ import Testing
126 let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak) 126 let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak)
127 #expect(abs(back - 0.6) < 0.01) 127 #expect(abs(back - 0.6) < 0.01)
128} 128}
129
130/// The mapping for the reverse fixture's non-rigid step, seen from above.
131private func reverseMapping() throws -> FoldParameterMapping {
132 let file = try compiled("reverse")
133 return FoldParameterMapping(file: file, step: try readSteps(file)[1],
134 camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
135 viewportSize: SIMD2(800, 600))
136}
137
138@Test func aNonRigidStepCanBeDraggedBackThroughItsPhases() throws {
139 // the pop's path starts back along the open's, so dragging back passes that turnaround too
140 let m = try reverseMapping()
141 var t = 0.0
142 for p in m.path.dropFirst() { t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) }
143 #expect(t == 1)
144 for p in m.path.reversed().dropFirst() {
145 let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
146 #expect(next <= t + 1e-9)
147 t = next
148 }
149 #expect(t < 0.01)
150}
151
152@Test func aFoldAndUnfoldStillUnfoldsAfterItsPeak() throws {
153 // past the peak the return half retraces the outbound half, so moving toward the start unfolds
154 let m = try mapping("quarters.fold", step: 1)
155 var t = 0.0
156 for p in m.path[1...80] { t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) }
157 #expect(abs(t - 0.625) < 0.01)
158 for p in m.path[0..<48].reversed() {
159 let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
160 #expect(next >= t - 1e-9)
161 t = next
162 }
163 #expect(t == 1)
164}
165
166@Test func aStaggeredStepCanBeDraggedBackPastItsWindowBoundary() throws {
167 // seen from above, the second window's path retraces the first's, so samples 63 and 65 are one
168 // screen point and only the drag's position says which window it is in
169 let m = try mapping("letter-staggered.fold", step: 1)
170 var position = m.position(at: 0)
171 for k in Array(1...96) + Array((0..<96).reversed()) {
172 position = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: position)
173 #expect(abs(position.t - Double(k) / 128) < 0.01, "sample \(k)")
174 }
175}
176
177@Test func aDragOnARetracedStretchStaysInItsPhase() throws {
178 // the pop's samples 44...54 lie within half a point of the open's path; a finger there stays
179 // in the phase the drag is in until it reaches the turnaround
180 let m = try reverseMapping()
181 let phases = try readSteps(compiled("reverse"))[1].pop!.phases
182 var opening = m.position(at: 0)
183 for k in 1...36 { opening = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: opening) }
184 var popping = opening
185 for k in 37...54 { popping = m.position(grabbedAt: m.path[0], translation: m.path[k] - m.path[0], current: popping) }
186 #expect(popping.t > phases.lowerBound)
187 for k in 44...54 {
188 let p = m.path[k] - m.path[0]
189 #expect(m.position(grabbedAt: m.path[0], translation: p, current: opening).t < phases.lowerBound, "sample \(k)")
190 #expect(m.position(grabbedAt: m.path[0], translation: p, current: popping).t > phases.lowerBound, "sample \(k)")
191 }
192}
docs/superpowers/plans/2026-10-19-fold.md +76 −3
@@ -119,7 +119,7 @@ Done once, before Task 0.
119 119
1201. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`. 1201. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`.
1212. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request. 1212. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request.
1223. Work is batched into eight merge requests, each with one gitbay issue: 1223. Work is batched into nine merge requests, each with one gitbay issue:
123 123
124 | Batch | Tasks | Branch | 124 | Batch | Tasks | Branch |
125 |---|---|---| 125 |---|---|---|
@@ -130,6 +130,7 @@ Done once, before Task 0.
130 | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` | 130 | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` |
131 | E | 9–10 — diagram, renderer | `diagram-and-renderer` | 131 | E | 9–10 — diagram, renderer | `diagram-and-renderer` |
132 | F | 11–14 — the app | `app` | 132 | F | 11–14 — the app | `app` |
133 | F2 | 14b — step list, dragging back | `step-access` |
133 | G | 15 — crane, sampan, box | `models` | 134 | G | 15 — crane, sampan, box | `models` |
134 135
135 Batches A and A2 merge alone, since Tasks 0 and 0b can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source <branch> --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`. 136 Batches A and A2 merge alone, since Tasks 0 and 0b can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source <branch> --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`.
@@ -2060,6 +2061,80 @@ git commit -m "Orbit and zoom, accessibility pass and release assets"
2060 2061
2061--- 2062---
2062 2063
2064### Task 14b: The step list and dragging back
2065
2066**Files:**
2067- Create: `App/Sources/StepListView.swift`
2068- Modify: `App/Sources/StepView.swift`, `App/Sources/FoldSession.swift`
2069- Modify: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift`
2070- Test: `App/UITests/StepListTests.swift`, `App/Tests/FoldSessionTests.swift`, `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift`, `App/UITests/AccessibilityAuditTests.swift`
2071
2072**Interfaces:**
2073- Consumes: Tasks 11–14.
2074- Produces:
2075 - `struct StepListView: View` — every step's number and `instruction`, the current one marked
2076 - `func (FoldSession).open(step: Int)` — step counted from 1; loads that step at *t* = 0 with the camera at its viewpoint, as completing the step before it does
2077
2078**The step list.** A toolbar button (`steps.button`, label "Steps") opens the list on demand: a popover on iPad, a sheet on iPhone. The navigation title reads "Step n of N"; `step.index` stays the bare number. Choosing a step opens it at its start, frame n − 1, whatever was folded before; choosing the current step closes the list and leaves *t* alone. Nothing about the list advances *t*.
2079
2080**Dragging back.** A step's segments — axis windows and non-rigid phases — are crossed in both directions: the search runs outward from `current` across segment boundaries, so dragging the flap back takes *t* back through earlier windows and phases to 0. Where the path doubles back on screen at a boundary (a non-rigid step's open and pop), the segment *t* is in is kept until the finger leaves the overlap, so a finger moving along the retraced stretch neither jumps ahead nor falls back. The 0.5-point end tolerance applies at *t* = 1 only. A `foldAndUnfold` stays one way at its peak: its return half passes through the same poses as its outbound half, so dragging back after the peak is the unfold.
2081
2082- [ ] **Step 1: Write the failing tests**
2083
2084```swift
2085// FoldParameterTests
2086@Test func aStaggeredStepCanBeDraggedBackPastItsWindowBoundary() throws {
2087 // follow letter-staggered's samples to t = 0.75, then back to 0: t tracks k/128 both ways
2088}
2089
2090@Test func aNonRigidStepCanBeDraggedBackThroughItsPhases() throws {
2091 // follow the reverse fixture's samples to t = 1, then back: t never increases, and ends below 0.01
2092}
2093
2094@Test func aFoldAndUnfoldStillUnfoldsAfterItsPeak() throws {
2095 // quarters step 1: past 0.5, dragging back toward the start goes to 1
2096}
2097```
2098
2099```swift
2100// StepListTests
2101func testTheStepListOpensAChosenStepAtItsStart() {
2102 let app = XCUIApplication(); app.launch()
2103 app.buttons["Cup"].tap()
2104 app.buttons["steps.button"].tap()
2105 app.buttons["step.5"].tap()
2106 XCTAssertEqual(app.staticTexts["step.index"].label, "5")
2107 XCTAssertEqual(app.otherElements["fold.paper"].value as? String, "0%")
2108}
2109
2110func testTheStepListNamesEveryStep() {
2111 // six rows for the cup, each labelled with its number and instruction
2112}
2113```
2114
2115`FoldSessionTests` covers `open(step:)` (the camera resets, *t* is 0, the diagram is step n's) and choosing the current step. The accessibility audit opens the list at both text sizes.
2116
2117- [ ] **Step 2: Run tests to verify they fail**
2118
2119Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro,OS=26.5' test`
2120Expected: FAIL.
2121
2122- [ ] **Step 3: Implement the step list, `open(step:)` and two-way segments**
2123
2124- [ ] **Step 4: Run tests to verify they pass**
2125
2126Run: as above, then `-only-testing:FoldUITests/FoldGestureTests -test-iterations 100`.
2127Expected: PASS.
2128
2129- [ ] **Step 5: Commit**
2130
2131```bash
2132git add App Packages
2133git commit -m "Step list and dragging back across segments"
2134```
2135
2136---
2137
2063### Task 15: The crane, the sampan and the box 2138### Task 15: The crane, the sampan and the box
2064 2139
2065**Files:** 2140**Files:**
@@ -2155,8 +2230,6 @@ git commit -m "The crane, the sampan and the box"
2155 2230
2156## Open before Task 15 2231## Open before Task 15
2157 2232
2158- **Reaching an earlier or chosen step.** The app starts each model at step 1 and has no step list; the spec leaves its form open (a visible strip or revealed on demand). On the crane, revisiting a step means refolding from the start.
2159- **Dragging back past a peak, phase or window.** A fold-and-unfold cannot be dragged back once past its peak, a reverse fold past its open phase, or a staggered step past an internal window end, although the spec's first goal says a step can be folded "and back".
2160- **Multi-axis steps in the app.** The fold drag's path joins each segment's followed centroid end to end, so on a multi-axis step it can leave the paper view; a short window nested inside a long one falls back to a vertical drag while the paper moves; non-rigid steps follow the axis with the most travel per phase, untested until one ships. Check all three on the crane. The catalogue gate exercises `FoldParameterMapping` on every step but not `ReorientMapping`. 2233- **Multi-axis steps in the app.** The fold drag's path joins each segment's followed centroid end to end, so on a multi-axis step it can leave the paper view; a short window nested inside a long one falls back to a vertical drag while the paper moves; non-rigid steps follow the axis with the most travel per phase, untested until one ships. Check all three on the crane. The catalogue gate exercises `FoldParameterMapping` on every step but not `ReorientMapping`.
2161- On device: the fold drag's 0.5-point end tolerance is about 14° on the cup's shortest iPhone paths; check it against "the last 10° completes itself". Check that a late second finger orbits rather than folds. Measure the session and mapping build times on the crane. 2234- On device: the fold drag's 0.5-point end tolerance is about 14° on the cup's shortest iPhone paths; check it against "the last 10° completes itself". Check that a late second finger orbits rather than folds. Measure the session and mapping build times on the crane.
2162 2235