Cotton code
322 lines · 13.6 KB · SwiftRaw
// An app with its own look (Notes, Chat) raises what a system sheet or a// confirmation dialog once carried in a PANEL of its own colours: a scrim over// the screen, the app's ground rising from the bottom with its corner, closed// by a tap on the scrim, a drag down, or the panel's own controls. No sheets// (NoBottomSheetsTests) and no system dialogs (CardGuardTests), as Vault does// with VaultPanel. Home's tools open cards instead (`cottonCard`).//// The panel sets `closeCard`, so a view inside closes it the way a card's// content does (`CardClosing.close`).#if os(iOS)import SwiftUIimport UIKit/// The colours a panel is drawn in: the app's own.struct LookPanelStyle {    var scrim: Color    var ground: Color    var corner: CGFloat = 16    /// How far the panel floats clear of the screen's sides and foot, rounded    /// all round (Words' panels); 0 rises from the foot, rounded at the top.    var inset: CGFloat = 0}extension View {    /// Raises `content` in a panel of `style` while `isPresented` is true.    /// `tall` lets it rise to the top of the screen (a list, a form). `name`    /// is what VoiceOver calls the panel as it comes in (its title).    func lookPanel<Content: View>(        isPresented: Binding<Bool>,        style: LookPanelStyle,        tall: Bool = false,        name: String? = nil,        @ViewBuilder content: @escaping () -> Content    ) -> some View {        overlay {            if isPresented.wrappedValue {                LookPanel(style: style, tall: tall, name: name, close: { isPresented.wrappedValue = false }, content: content)            }        }        .animation(.easeOut(duration: 0.2), value: isPresented.wrappedValue)    }    /// The same panel while `item` is set.    func lookPanel<Item, Content: View>(        item: Binding<Item?>,        style: LookPanelStyle,        tall: Bool = false,        name: String? = nil,        @ViewBuilder content: @escaping (Item) -> Content    ) -> some View {        overlay {            if let shown = item.wrappedValue {                LookPanel(style: style, tall: tall, name: name, close: { item.wrappedValue = nil }, content: { content(shown) })            }        }        .animation(.easeOut(duration: 0.2), value: item.wrappedValue != nil)    }    /// A question or a choice in a panel of `style`: each choice is a row in    /// its colour; a tap on the scrim answers none.    func lookAsk(        isPresented: Binding<Bool>,        style: LookPanelStyle,        font: Font,        message: String? = nil,        messageColour: Color,        choices: [LookChoice],        name: String? = nil    ) -> some View {        lookPanel(isPresented: isPresented, style: style, name: name) {            LookAskRows(font: font, message: message, messageColour: messageColour, choices: choices)        }    }}/// One answer a `lookAsk` offers.struct LookChoice: Identifiable {    let id: String    let label: String    let colour: Color    let act: () -> Void}private struct LookPanel<Content: View>: View {    let style: LookPanelStyle    let tall: Bool    var name: String? = nil    let close: @MainActor @Sendable () -> Void    @ViewBuilder let content: () -> Content    /// Whether it floats clear of the edges (`LookPanelStyle.inset`).    private var floats: Bool { style.inset > 0 }    var body: some View {        ZStack(alignment: .bottom) {            style.scrim.ignoresSafeArea().onTapGesture(perform: close).accessibilityHidden(true)                .transition(.opacity)            content()                .environment(\.closeCard, close)                .frame(maxWidth: .infinity, maxHeight: tall ? .infinity : nil, alignment: .top)                .background(                    UnevenRoundedRectangle(topLeadingRadius: style.corner, bottomLeadingRadius: floats ? style.corner : 0,                                           bottomTrailingRadius: floats ? style.corner : 0, topTrailingRadius: style.corner,                                           style: .continuous)                        .fill(style.ground)                        .ignoresSafeArea(edges: floats ? [] : .bottom)                )                .lookPanelPull(close: close)                .padding(.horizontal, style.inset)                .padding(.bottom, style.inset)                .padding(.top, 48)                .transition(.move(edge: .bottom))        }        // The panel stands alone for VoiceOver (modal), named by its title, its        // rows inside it (the VoiceOver walk, 21 Nov 2026: an Alert with no name).        .modifier(LookPanelName(name: name))        .accessibilityAddTraits(.isModal)        .accessibilityAction(.escape, close)    }}extension View {    /// The panel's pull, on a panel an app draws in its own shape (Notes'    /// acts, its tag picker, Info): a pull down on any part of this view    /// closes it, as a LookPanel's does, and it says a panel stands    /// (`LookPanelUp`), as a LookPanel does.    func lookPanelPull(close: @escaping @MainActor () -> Void) -> some View {        modifier(LookPanelPulled(close: close))    }}/// The pull, with the frame it reads its own lists inside.private struct LookPanelPulled: ViewModifier {    let close: @MainActor () -> Void    /// Where the panel stands in the window, so its pull reads only its own lists.    @State private var frame: CGRect = .zero    func body(content: Content) -> some View {        content            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame = $0 }            // The panel's whole ground is its own to the window's hit test: a tap on its title or blank            // ground lands on the panel, never on what stands under it. Words' tag picker over a note let such            // a tap fall through to the note's text view (the hit test answered WritingTextView), which the            // keyboard rule took for a tap into a field, so the keyboard stayed (NotesKeyboardTests, 23 Nov            // 2026). SwiftUI's own shapes do not answer UIKit's hit test; a plain view behind the panel does.            // Rows, buttons and fields over it keep their taps; the rule's tap and the pull still see it.            .background(LookPanelGround())            .gesture(LookPanelPull(panel: frame, close: close))            .preference(key: LookPanelUp.self, value: true)    }}/// A plain, clear view the panel stands on, so the window's hit test answers the panel at its blank ground.private struct LookPanelGround: UIViewRepresentable {    func makeUIView(context: Context) -> UIView {        let view = UIView()        view.backgroundColor = .clear        view.isAccessibilityElement = false        return view    }    func updateUIView(_ view: UIView, context: Context) {}}/// The panel's name for VoiceOver, where its caller gives one.private struct LookPanelName: ViewModifier {    let name: String?    func body(content: Content) -> some View {        // The name is the panel's own: on a bare container a label reaches every row inside, and each choice was read        // as the panel's title (Export's three choices each read "Export", 24 Nov 2026).        if let name, !name.isEmpty {            content.accessibilityElement(children: .contain).accessibilityLabel(Text(verbatim: name))        } else {            content        }    }}/// A pull down closes the panel, on any part of it: its title, its rows/// once they stand at their top, its blank ground. A list scrolled down/// takes a pull back up its rows first, and only a pull that starts with/// them at the top closes (as Android's sheets, ef5f548097). SwiftUI's drag/// on the panel never saw a pull on a list, so a list at its top bounced and/// the panel stayed. UIKit's pan runs beside the list's own; a tap on a row/// or a button is untouched.private struct LookPanelPull: UIGestureRecognizerRepresentable {    /// The panel's frame in the window: a list is the panel's only if it stands inside it.    let panel: CGRect    let close: @MainActor () -> Void    /// How far down a pull closes, and how much more down than sideways it runs.    static let closes: CGFloat = 60    /// A pull that starts low on the panel (its last row, a foot of the    /// screen's height above the edge) cannot run 60 points before the edge    /// stops it: it closes once it has run this share of the room it had    /// (ChatWarmPanelsTests, 21 Nov 2026: Mute's last row on a person's page, Save on a    /// group's Rename, stayed open under a pull), as does a quick flick down.    static let shareOfTheRoom: CGFloat = 0.6    static let leastPull: CGFloat = 20    static let flick: CGFloat = 900    func makeUIGestureRecognizer(context: Context) -> UIPanGestureRecognizer {        let pan = UIPanGestureRecognizer()        // A finger that moves takes back the press it began on, as a scroll        // does: a sideways swipe across an act (Delete) never runs it.        pan.cancelsTouchesInView = true        pan.delaysTouchesBegan = false        pan.delaysTouchesEnded = false        pan.delegate = context.coordinator        context.coordinator.panel = panel        return pan    }    func updateUIGestureRecognizer(_ pan: UIPanGestureRecognizer, context: Context) {        context.coordinator.panel = panel    }    func handleUIGestureRecognizerAction(_ pan: UIPanGestureRecognizer, context: Context) {        switch pan.state {        case .began:            // The list under the finger, if any, and whether it stood at its top.            let start = pan.location(in: pan.view)            let hit = pan.view?.hitTest(start, with: nil)            context.coordinator.atTop = Self.list(above: hit, inside: context.coordinator.panel).map(Self.atTop) ?? true            // The room below the finger: a pull runs no further than the screen's edge.            let moved = pan.translation(in: pan.view)            context.coordinator.room = (pan.view?.bounds.maxY ?? .greatestFiniteMagnitude) - (start.y - moved.y)        case .ended:            let moved = pan.translation(in: pan.view)            let speed = pan.velocity(in: pan.view).y            guard context.coordinator.atTop, moved.y > abs(moved.x) * 1.5,                  Self.pullCloses(moved: moved.y, room: context.coordinator.room, speed: speed) else { return }            close()        default:            break        }    }    func makeCoordinator(converter: CoordinateSpaceConverter) -> Coordinator { Coordinator() }    /// The nearest vertical scroll view holding `view` that stands inside the    /// panel. The window's hit test can answer a list under the panel (the    /// screen's own, scrolled down), which drew no part of it: Days' month,    /// which has no list of its own, stayed open under a pull while Days    /// stood scrolled down to today (DaysPanelTests).    static func list(above view: UIView?, inside panel: CGRect) -> UIScrollView? {        var current = view        while let one = current {            if let scroll = one as? UIScrollView, scroll.contentSize.height > 0, scroll.alwaysBounceHorizontal == false,               scroll.contentSize.width <= scroll.bounds.width + 1,               panel.isEmpty || panel.insetBy(dx: -2, dy: -2).contains(scroll.convert(scroll.bounds, to: nil)) { return scroll }            current = one.superview        }        return nil    }    /// Whether a pull down `moved` points, with `room` below where it began and    /// ending at `speed` points a second, is far or quick enough to close.    static func pullCloses(moved: CGFloat, room: CGFloat, speed: CGFloat) -> Bool {        guard moved > leastPull else { return false }        return moved > min(closes, room * shareOfTheRoom) || speed > flick    }    static func atTop(_ scroll: UIScrollView) -> Bool {        scroll.contentOffset.y <= -scroll.adjustedContentInset.top + 1    }    final class Coordinator: NSObject, UIGestureRecognizerDelegate {        var atTop = true        var room: CGFloat = .greatestFiniteMagnitude        var panel: CGRect = .zero        func gestureRecognizer(_ gesture: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }    }}private struct LookAskRows: View {    let font: Font    let message: String?    let messageColour: Color    let choices: [LookChoice]    @Environment(\.closeCard) private var close    var body: some View {        VStack(spacing: 0) {            if let message, !message.isEmpty {                Text(verbatim: message).font(font).foregroundStyle(messageColour)                    .multilineTextAlignment(.center)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.horizontal, 24).padding(.vertical, 18)            }            ForEach(choices) { choice in                Button {                    close?()                    choice.act()                } label: {                    Text(verbatim: choice.label).font(font).foregroundStyle(choice.colour)                        .frame(maxWidth: .infinity, minHeight: 52)                        .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityIdentifier("look-ask-\(choice.id)")            }        }        .padding(.top, 8)        .padding(.bottom, 12)    }}#endif// Outside the iOS guard: ShellCardsAbove reads it, and it builds on the Mac too.import SwiftUI/// Whether a panel stands below, for a root that draws over its screens/// (Chat's Chats / Calls / You pill): a panel raised from inside a screen/// would otherwise stand under it, its rows covered (owner, Chat build 13).struct LookPanelUp: PreferenceKey {    static let defaultValue = false    static func reduce(value: inout Bool, nextValue: () -> Bool) { value = value || nextValue() }}