Cotton code
65 lines · 2.6 KB · SwiftRaw
// How a face with pages of its own turns them on the deck: the deck hands a// face its move past the face's last page (`deckPassOn`).//// Where the deck reads a finger's strokes itself (Cotton's ink, decided on// lift: a letter, a scratch-out, or a straight level swipe), no face reads a// drag under the moving finger: a face with pages hands its turn up instead// (`DeckPageTurners`), and the deck gives it the swipe once the stroke ends.// The innermost face's turn is the one taken, as its drag was.import SwiftUIextension EnvironmentValues {    /// The deck's move past a face's own pages (a note's last page swiped    /// on); nil off the deck.    @Entry public var deckPassOn: ((_ forward: Bool) -> Void)? = nil    /// The deck reads every travelling stroke itself and turns a face's pages    /// on lift (`facePages`); false, each face reads its own drag.    @Entry public var deckReadsStrokes = false}/// A face's page turn, handed up to the deck that reads strokes.public struct DeckPageTurner: Equatable {    let id: UUID    /// Where the face's pages stand ("2/4"): a turner from before a turn is    /// never the one taken.    let at: String    public let turn: @MainActor (_ forward: Bool) -> Void    public static func == (a: DeckPageTurner, b: DeckPageTurner) -> Bool { a.id == b.id && a.at == b.at }}/// The page turners on the deck's front card, outermost first.public struct DeckPageTurners: PreferenceKey {    public static var defaultValue: [DeckPageTurner] { [] }    public static func reduce(value: inout [DeckPageTurner], nextValue: () -> [DeckPageTurner]) {        value.append(contentsOf: nextValue())    }}extension View {    /// A face's own pages: turned by `gesture` where faces read their own    /// drags, else handed up as `turn` for the deck's swipe on lift. Nil    /// `gesture`: the face has no pages to turn now.    public func facePages<G: Gesture>(_ gesture: G?, at: String, turn: @escaping @MainActor (_ forward: Bool) -> Void) -> some View {        modifier(FacePagesTurn(gesture: gesture, at: at, turn: turn))    }}private struct FacePagesTurn<G: Gesture>: ViewModifier {    let gesture: G?    let at: String    let turn: @MainActor (_ forward: Bool) -> Void    @Environment(\.deckReadsStrokes) private var deckReads    @State private var id = UUID()    func body(content: Content) -> some View {        if deckReads {            content.transformPreference(DeckPageTurners.self) { turners in                if gesture != nil { turners.insert(DeckPageTurner(id: id, at: at, turn: turn), at: 0) }            }        } else {            content.highPriorityGesture(gesture)        }    }}