App/Sources/FoldGesture.swift

main
fold/App/Sources/FoldGesture.swift history · blame · raw

36 lines · 1536 bytes

3 symbols in this file
 1import FoldFormat
 2import SwiftUI
 3
 4extension View {
 5    /// Lets a one-finger drag anywhere on the view drive the session's fold step: the moving faces
 6    /// follow the finger along their screen path, and the step completes when the finger lifts at
 7    /// t = 1. Releasing below 1 leaves the paper where it is.
 8    func foldGesture(_ session: FoldSession) -> some View {
 9        modifier(StepDragGesture(session: session, kinds: [.fold, .foldAndUnfold], begin: session.beginFoldDrag))
10    }
11}
12
13/// A one-finger drag that drives the session's step while it is one of `kinds`.
14struct StepDragGesture: ViewModifier {
15    let session: FoldSession
16    let kinds: Set<StepKind>
17    let begin: () -> Void
18    @GestureState private var isDragging = false
19
20    func body(content: Content) -> some View {
21        content
22            .gesture(drag, isEnabled: kinds.contains(session.step.kind) && !session.isLocked)
23            .onChange(of: isDragging) { _, dragging in if !dragging { session.cancelDrag() } }
24    }
25
26    /// A two-finger gesture during the drag suspends it (`FoldSession.beginOrbit()`).
27    private var drag: some Gesture {
28        DragGesture()
29            .updating($isDragging) { value, isDragging, _ in
30                if !isDragging { begin() }
31                isDragging = true
32                session.drag(translation: SIMD2(value.translation.width, value.translation.height))
33            }
34            .onEnded { value in session.endDrag(translation: SIMD2(value.translation.width, value.translation.height)) }
35    }
36}