Cotton code
304 lines · 13.3 KB · SwiftRaw
// The instant print: the object a PHOTOGRAPH is, on paper.//// A person, a place, a picture, a map, a screenshot — anything the app has a// picture of is the same physical object, a print in a white card frame with the// wide margin at the bottom and the name written across it. One object, so a// person's grid, a photo library and a map thumbnail are three sizes of one// design rather than three designs.//// THE FRAME IS DRAWN, NOT PHOTOGRAPHED. It is `PaperShape` filled with the// print's own warm white and the grain tile at a whisper — a print frame is// smooth card, not fibre, so it takes far less of the tile than a sheet does.// The reason it is drawn is the reason the paper is: a print holds a photo of// any aspect, and a photographed frame can only hold the aspect it was shot at.//// IT NEVER FETCHES. The photo slot takes a view and draws it; whoever has the// bytes hands them in. A print with nothing in it draws its window, which is// visibly a window rather than a grey photograph pretending to load.import SwiftUI/// How big a print is, and what it is for.public enum PrintSize: String, CaseIterable, Sendable {    /// A grid of people, or a photo library. Square photo, caption written.    case grid    /// A row's thumbnail — a message thread, a call, a search result. Square,    /// far too small for handwriting, so no caption is set.    case thumb    /// The print at the top of a person's own page. Landscape, caption written.    case hero    /// The photo window's proportion, width ÷ height.    public func photoAspect(in scale: ThemeScale) -> CGFloat {        switch self {        case .grid, .thumb: return 1        case .hero: return InstantPrintKnobs.instantPrintHeroAspect        }    }    /// Whether a caption is set at all at this size.    public var setsCaption: Bool {        switch self {        case .grid, .hero: return true        case .thumb: return false        }    }    /// The side a screen lays this print at when it has no column to fit it to,    /// in the caller's worn theme.    public func suggestedWidth(in scale: ThemeScale) -> CGFloat {        switch self {        case .grid: return InstantPrintKnobs.instantPrintGridSuggestedWidth        case .thumb: return InstantPrintKnobs.instantPrintThumbSuggestedWidth        case .hero: return InstantPrintKnobs.instantPrintHeroSuggestedWidth        }    }}// The frame's own geometry is every number a fraction of the print's width —// the caps' rule, which is why a print reads the same at 28pt and at 280pt. The// print reads them off the worn theme (`instant_print_margin`,// `instant_print_bottom_margin`).public struct InstantPrint<Photo: View>: View {    @Environment(\.theme) private var theme    /// A list's print: its resting lift is a kept picture.    @Environment(\.paperSurfaceImages) private var listRow    private let seed: String    private let caption: String?    private let captionGlyph: String?    private let captionDetail: String?    /// The detail's ink: pencil, or red pencil for a birthday's words.    private let captionDetailInk: PaperInk    private let size: PrintSize    /// The window's proportion the caller asked for, before the theme clamps it.    private let photoAspect: CGFloat?    private let tilts: Bool    private let photo: Photo    /// - Parameters:    ///   - captionGlyph: a small SF Symbol written in the margin before the    ///     caption, in the same pencil — a film's play mark beside its length.    ///   - captionDetail: a second, smaller word after the caption, in    ///     pencil — the time where a person is. The    ///     caption keeps its size first; the detail gives way.    ///   - photoAspect: the window's proportion (width ÷ height) when the    ///     picture's own shape matters more than the size's — the one print on    ///     a photo's own page. Clamped to 3:4…4:3 so a panorama still reads as    ///     a print. `nil` takes the size's.    ///   - tilts: `false` for a print laid square — a contact sheet's    ///     neighbour, a print a person is about to zoom into.    public init(        seed: String,        caption: String? = nil,        captionGlyph: String? = nil,        captionDetail: String? = nil,        captionDetailInk: PaperInk = .pencil,        size: PrintSize = .grid,        photoAspect: CGFloat? = nil,        tilts: Bool = true,        @ViewBuilder photo: () -> Photo    ) {        self.seed = seed        self.caption = caption        self.captionGlyph = captionGlyph        self.captionDetail = captionDetail        self.captionDetailInk = captionDetailInk        self.size = size        self.photoAspect = photoAspect        self.tilts = tilts        self.photo = photo()    }    /// The window's proportion: the caller's, clamped to the theme's range, or    /// the size's own.    private var aspect: CGFloat {        photoAspect.map { min(InstantPrintKnobs.instantPrintAspectMax, max(InstantPrintKnobs.instantPrintAspectMin, $0)) }            ?? size.photoAspect(in: theme.scale)    }    public var body: some View {        GeometryReader { geo in            let width = geo.size.width            let window = PrintFrame.window(width: width, aspect: aspect)            VStack(spacing: 0) {                photo                    .frame(width: window.width, height: window.height)                    // A filled picture is laid out past its window and only                    // painted inside it: the window is all of it that is                    // touched and read out (walker294 row 95).                    .clipped()                    .contentShape(.interaction, Rectangle())                    .contentShape(.accessibility, Rectangle())                    .background(theme.printWindow)                    .padding(.top, window.minY)                if size.setsCaption, let caption {                    let type = min(                        InstantPrintKnobs.instantPrintCaptionMax,                        max(InstantPrintKnobs.instantPrintCaptionMin, width * InstantPrintKnobs.instantPrintCaptionSize)                    )                    Group {                        if let captionDetail {                            captionWithDetail(caption, captionDetail, type: type)                        } else {                            captionLine(caption, type: type)                        }                    }                    .frame(maxWidth: window.width)                    .frame(maxHeight: .infinity)                }            }            .frame(width: width, height: printHeight(forWidth: width), alignment: .top)            .background {                ZStack {                    PaperShape(edge: .cut, seed: seed, theme: theme).fill(theme.printFrame)                    if theme.texture.grain {                        PaperGrainFill(strength: PaperGrain.onPrintFrame)                            .clipShape(PaperShape(edge: .cut, seed: seed, theme: theme))                    }                    if theme.outlinesObjects {                        PaperShape(edge: .cut, seed: seed, theme: theme)                            .strokeBorder(theme.colors.hairline.color, lineWidth: theme.scale.hairline)                    }                }                .compositingGroup()            }        }        .aspectRatio(printRatio, contentMode: .fit)        // The print is the card it draws, touched and read out: never the        // picture laid past its window, which stood a film's Play button        // over the page's Close (walker294 row 95).        .contentShape(.interaction, Rectangle())        .contentShape(.accessibility, Rectangle())        .compositingGroup()        // A list's print casts its lift from a kept picture        // (`PaperRestingShadow`), never blurred again as the list scrolls.        .background {            if keptLift { PaperRestingShadow(edge: .cut, seed: seed, fill: theme.printFrame) }        }        .rotationEffect(.degrees(tilts ? theme.tilt(seed: seed) : 0))        .modifier(PaperLift(shadow: keptLift ? .none : .resting))    }    /// The resting lift is the kept picture: on a list's print, on the phone    /// (the Mac's hover grows the lift live).    private var keptLift: Bool {        #if os(iOS)        listRow        #else        false        #endif    }    /// The caption as every print writes it: the glyph, then the words,    /// shrinking to 60% before the end is cut.    private func captionLine(_ caption: String, type: CGFloat) -> some View {        HStack(spacing: type * InstantPrintKnobs.instantPrintCaptionGap) {            if let captionGlyph {                Image(systemName: captionGlyph)                    .font(theme.type.interface((type * InstantPrintKnobs.instantPrintCaptionGlyphSize)))                    .foregroundStyle(theme.print(.pencil))                    .blendMode(theme.printBlend)            }            Text(caption)                .paperHand(type)                .lineLimit(1)        }    }    /// The caption with its detail after it — WHOLE, or not at all. The pair    /// is tried at the caption's size and then smaller, down to the same 60%    /// floor; when even that does not hold both, the detail is left off and    /// the caption is written alone, because a cut-off time ("11:…") is worse    /// than none and a name squeezed out by a time is worse still.    private func captionWithDetail(_ caption: String, _ detail: String, type: CGFloat) -> some View {        ViewThatFits(in: .horizontal) {            ForEach(                [CGFloat(1), InstantPrintKnobs.instantPrintCaptionStepScale, InstantPrintKnobs.instantPrintCaptionMinScale]                    .filter { $0 == 1 || type * $0 >= theme.scale[.typeCaptionSize] },                id: \.self            ) { scale in                HStack(alignment: .firstTextBaseline, spacing: type * scale * InstantPrintKnobs.instantPrintCaptionGap) {                    Text(caption).paperHand(type * scale).lineLimit(1).fixedSize()                    Text(detail)                        .paperHand(type * scale * InstantPrintKnobs.instantPrintCaptionDetailSize, ink: captionDetailInk)                        .lineLimit(1).fixedSize()                }            }            captionLine(caption, type: type)        }    }    /// The whole print's height for a width — the window plus its three margins.    private func printHeight(forWidth width: CGFloat) -> CGFloat {        PrintFrame.card(width: width, aspect: aspect, setsCaption: size.setsCaption).height    }    private var printRatio: CGFloat {        1 / (printHeight(forWidth: 1))    }}/// The print's geometry as values: the card it draws and the photo window in/// it, in the print's own coordinates. A test holds the rule that the window/// lies inside the card without drawing a pixel.enum PrintFrame {    /// The whole card a print `width` across draws: the window plus its three    /// margins, the bottom one wide when a caption is set.    public static func card(width: CGFloat, aspect: CGFloat, setsCaption: Bool) -> CGRect {        let margin = width * InstantPrintKnobs.instantPrintMargin        let bottom = setsCaption ? width * InstantPrintKnobs.instantPrintBottomMargin : margin        return CGRect(x: 0, y: 0, width: width, height: margin + (width - (margin + margin)) / aspect + bottom)    }    /// The photo window: a margin in from the card's top and sides, at the    /// window's proportion.    public static func window(width: CGFloat, aspect: CGFloat) -> CGRect {        let margin = width * InstantPrintKnobs.instantPrintMargin        let inner = width - (margin + margin)        return CGRect(x: margin, y: margin, width: inner, height: inner / aspect)    }}/// A print with no picture yet — the window, and nothing pretending to be a/// photograph in it.public struct EmptyPrint: View {    @Environment(\.theme) private var theme    private let seed: String    private let caption: String?    private let size: PrintSize    public init(seed: String, caption: String? = nil, size: PrintSize = .grid) {        self.seed = seed        self.caption = caption        self.size = size    }    public var body: some View {        InstantPrint(seed: seed, caption: caption, size: size) {            Rectangle().fill(theme.printWindow)        }    }}/// The sizes, counts and timings InstantPrint draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum InstantPrintKnobs {    static let instantPrintAspectMax: CGFloat = 1.3333333333333333    static let instantPrintAspectMin: CGFloat = 0.75    static let instantPrintBottomMargin: CGFloat = 0.215    static let instantPrintCaptionDetailSize: CGFloat = 0.8    static let instantPrintCaptionGap: CGFloat = 0.3    static let instantPrintCaptionGlyphSize: CGFloat = 0.55    static let instantPrintCaptionMax: CGFloat = 17    static let instantPrintCaptionMin: CGFloat = 11    static let instantPrintCaptionMinScale: CGFloat = 0.6    static let instantPrintCaptionSize: CGFloat = 0.115    static let instantPrintCaptionStepScale: CGFloat = 0.8    static let instantPrintGridSuggestedWidth: CGFloat = 150    static let instantPrintHeroAspect: CGFloat = 1.3333333333333333    static let instantPrintHeroSuggestedWidth: CGFloat = 280    static let instantPrintMargin: CGFloat = 0.062    static let instantPrintThumbSuggestedWidth: CGFloat = 28}