Cotton code
456 lines · 19.8 KB · SwiftRaw
// COTTON ALBUMS' LOOK (assets/design/albums/albums.html, Olive, the drawn page's tokens; DECISIONS "Icon and colour"):// the family's current language as Comms, Secrets, Sites and Data draw it: one paper by day, Night by dark, one ink// that marks only where to act, Instrument Sans, thin rules and space; no cards, shadows or gradients. A line that// stays (the pass, the Bin, a result) stands in a band: a 2 pt ink rule over it, a hairline under it. Until the core// answers `look {app: "albums"}`, the colours are the drawn page's Olive, by day and by night.#if os(iOS)import CottonKitimport CottonWritingimport SwiftUIimport UIKit@MainActorenum Olive {    static var look: LookModel { LookModel.standing("albums") }    private static var night: Bool { LookAppearance.shared.systemDark }    private static func token(_ name: String, _ day: UInt32, _ dark: UInt32) -> Color { look.colour(name, night ? dark : day) }    static var ground: Color { token("ground", 0xF2F1EA, 0x161612) }    static var ink: Color { token("ink", 0x1F2018, 0xE9E9DF) }    static var quiet: Color { token("quiet", 0x5B5D50, 0xA6A797) }    /// Never for words that must be read.    static var faint: Color { token("faint", 0x8E9083, 0x6F7064) }    static var rule: Color { token("rule", 0xD6D5CA, 0x2C2D25) }    /// Where to act: the one filled button of a screen, and nothing else.    static var accent: Color { token("accent", 0x5E6A1A, 0xC3CF6E) }    static var onAccent: Color { token("on_accent", 0xFFFFFF, 0x1A1D08) }    /// The paper a print is mounted on: a kept shot's corner, a photo still loading.    static var print: Color { token("print", 0xFFFFFF, 0x25261E) }    /// Behind a sheet.    static var veil: Color { ink.opacity(look.groundIsLight ? 0.24 : 0.55) }    static var well: Color { ink.opacity(look.groundIsLight ? 0.07 : 0.12) }    static let side: CGFloat = 22}/// Instrument Sans (SIL OFL, `assets/fonts/look`), following Look's size and face and the phone's text size; figures in/// the family's mono so a column of sizes lines up.@MainActorenum AlbumsType {    /// `upTo` caps how far the phone's text size grows it (UIFontMetrics reads the phone's setting, not SwiftUI's    /// dynamicTypeSize): for words that must fit a fixed place, the tabs and the size on a tile.    static func sans(_ size: CGFloat, _ weight: UIFont.Weight = .regular, _ style: UIFont.TextStyle = .body, upTo: CGFloat? = nil) -> Font {        let look = Olive.look        let scaled = size * look.scale        if look.face != LookFaces.own {            return Font(WritingFonts.font(LookFaces.drawn(look.face, own: "sans"), size: scaled, weight: weight))        }        let metrics = UIFontMetrics(forTextStyle: style), font = DataFonts.ui(.sans, scaled, weight)        return Font(upTo.map { metrics.scaledFont(for: font, maximumPointSize: $0 * look.scale) } ?? metrics.scaledFont(for: font))    }    static func mono(_ size: CGFloat, _ style: UIFont.TextStyle = .subheadline, upTo: CGFloat? = nil) -> Font {        let metrics = UIFontMetrics(forTextStyle: style), font = DataFonts.ui(.mono, size * Olive.look.scale, .regular)        return Font(upTo.map { metrics.scaledFont(for: font, maximumPointSize: $0 * Olive.look.scale) } ?? metrics.scaledFont(for: font))    }    static var title: Font { sans(31, .bold, .largeTitle) }    static var name: Font { sans(17, .semibold) }    static var line: Font { sans(14, .regular, .subheadline) }    static var body: Font { sans(16, .regular, .callout) }    static var lead: Font { sans(17, .regular, .body) }    static var heading: Font { sans(14, .semibold, .subheadline) }    static var bandHead: Font { sans(16, .bold, .callout) }    static var small: Font { sans(13, .regular, .footnote) }    static var button: Font { sans(17, .bold) }    static var act: Font { sans(15, .bold, .subheadline) }    static var tab: Font { sans(15, .regular, .subheadline) }    /// Counts and sizes at a row's end.    static var figure: Font { mono(15) }}enum AlbumsWords {    /// A line from the albums line set (the owner's words; the core's once ALBUMS CORE 1 lands).    static func line(_ path: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("albums", path, fills) }    static func looking(_ total: Int) -> String { line("pass.head", ["n": total.formatted()]) }    static var fillIn: String { line("pass.fill") }    /// Keep's words. In them "Cotton" is his Cotton space, where every app keeps its files, never this app: the line    /// set says a family app's name in place of Cotton (`ShellLines.said`), so Keep says it back.    static func keep(_ path: String, _ fills: [String: String] = [:]) -> String {        let name = ShellLines.speaker ?? "Cotton Albums"        return line("keep.\(path)", fills).replacingOccurrences(of: name, with: "Cotton")    }    static func keeping(_ n: Int) -> String { keep("continued_title", ["n": n.formatted()]) }    static var keepingLine: String { keep("continued_line") }    /// Sizes: one decimal GB, MB under a GB; "about" when estimated.    static func size(_ bytes: Int64, exact: Bool = true) -> String {        let gb = Double(bytes) / 1_000_000_000        let said = gb >= 1 ? line("size_gb", ["n": String(format: "%.1f", gb)])            : line("size_mb", ["n": String(format: "%.0f", max(Double(bytes) / 1_000_000, bytes > 0 ? 1 : 0))])        return exact ? said : line("about", ["size": said])    }}// MARK: - Parts/// A screen's title, large, in ink.struct AlbumsTitle: View {    let text: String    var body: some View {        Text(verbatim: text)            .font(AlbumsType.title)            .foregroundStyle(Olive.ink)            .fixedSize(horizontal: false, vertical: true)            .accessibilityAddTraits(.isHeader)            .frame(maxWidth: .infinity, alignment: .leading)    }}struct AlbumsRule: View {    var body: some View { Rectangle().fill(Olive.rule).frame(height: 1) }}/// A section's small heading ("From Photos", "Found so far"), with what it offers at its end.struct AlbumsHeading<End: View>: View {    let text: String    @ViewBuilder var end: () -> End    @Environment(\.dynamicTypeSize) private var size    var body: some View {        // The largest sizes: its act goes under the heading.        let layout = size.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: .leading, spacing: 6)) : AnyLayout(HStackLayout(alignment: .firstTextBaseline))        layout {            Text(verbatim: text).font(AlbumsType.heading).foregroundStyle(Olive.quiet).accessibilityAddTraits(.isHeader)                .fixedSize(horizontal: false, vertical: true)            if !size.isAccessibilitySize { Spacer(minLength: 10) }            end()        }        .padding(.top, 22).padding(.bottom, 6)    }}extension AlbumsHeading where End == EmptyView {    init(_ text: String) { self.init(text: text) { EmptyView() } }}/// A line that stays: a 2 pt ink rule over it, a hairline under it. The pass, the Bin's line on Tidy, a set's result.struct AlbumsBand<End: View, Below: View>: View {    let head: String?    var lines: [String] = []    var soft = false    @ViewBuilder var end: () -> End    @ViewBuilder var below: () -> Below    @Environment(\.dynamicTypeSize) private var size    var body: some View {        // The largest sizes: its act goes under the words.        let layout = size.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: .leading, spacing: 10)) : AnyLayout(HStackLayout(alignment: .center, spacing: 12))        VStack(alignment: .leading, spacing: 0) {            Rectangle().fill(soft ? Olive.rule : Olive.ink).frame(height: soft ? 1 : 2)            VStack(alignment: .leading, spacing: 3) {                layout {                    VStack(alignment: .leading, spacing: 3) {                        if let head {                            Text(verbatim: head).font(AlbumsType.bandHead).foregroundStyle(Olive.ink)                                .fixedSize(horizontal: false, vertical: true)                        }                        ForEach(lines, id: \.self) { line in                            Text(verbatim: line).font(AlbumsType.line).foregroundStyle(Olive.quiet)                                .fixedSize(horizontal: false, vertical: true)                        }                    }                    .frame(maxWidth: .infinity, alignment: .leading)                    end()                }                below()            }            .padding(.vertical, 12)            AlbumsRule()        }    }}extension AlbumsBand where End == EmptyView, Below == EmptyView {    init(head: String?, lines: [String] = [], soft: Bool = false) {        self.init(head: head, lines: lines, soft: soft, end: { EmptyView() }, below: { EmptyView() })    }}extension AlbumsBand where Below == EmptyView {    init(head: String?, lines: [String] = [], soft: Bool = false, @ViewBuilder end: @escaping () -> End) {        self.init(head: head, lines: lines, soft: soft, end: end, below: { EmptyView() })    }}/// The honest thin line: what is done of the whole, in ink over the rule; quiet while paused.struct AlbumsProgressBar: View {    let fraction: Double    var paused = false    var body: some View {        GeometryReader { geo in            ZStack(alignment: .leading) {                Capsule().fill(Olive.rule)                Capsule().fill(paused ? Olive.quiet : Olive.ink).frame(width: max(3, geo.size.width * min(1, max(0, fraction))))            }        }        .frame(height: 3)        .padding(.top, 9)        .accessibilityHidden(true)    }}/// The one filled button of a screen.struct AlbumsMainButtonStyle: ButtonStyle {    @Environment(\.isEnabled) private var enabled    func makeBody(configuration: Configuration) -> some View {        configuration.label            .font(AlbumsType.button)            .foregroundStyle(Olive.onAccent)            .multilineTextAlignment(.center)            .padding(.horizontal, 16).padding(.vertical, 6)            .frame(maxWidth: .infinity, minHeight: 52)            .background(RoundedRectangle(cornerRadius: 16).fill(Olive.accent))            .opacity(configuration.isPressed ? 0.75 : enabled ? 1 : 0.45)    }}/// A full-width button outlined in ink (Not now, Turn on faces, Keep all 25); `quiet` outlines it in the rule.struct AlbumsOutlineButtonStyle: ButtonStyle {    var quiet = false    @Environment(\.isEnabled) private var enabled    func makeBody(configuration: Configuration) -> some View {        configuration.label            .font(quiet ? AlbumsType.sans(17, .semibold) : AlbumsType.button)            .foregroundStyle(Olive.ink)            .multilineTextAlignment(.center)            .padding(.horizontal, 16).padding(.vertical, 6)            .frame(maxWidth: .infinity, minHeight: 52)            .background(RoundedRectangle(cornerRadius: 16).stroke(quiet ? Olive.rule : Olive.ink, lineWidth: 1.5))            .contentShape(RoundedRectangle(cornerRadius: 16))            .opacity(configuration.isPressed ? 0.6 : enabled ? 1 : 0.45)    }}/// A small outlined act on a row or a band (Keep, Delete, Yes).struct AlbumsPillStyle: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label            .font(AlbumsType.act)            .foregroundStyle(Olive.ink)            .lineLimit(1)            .padding(.horizontal, 14).padding(.vertical, 6)            .frame(minHeight: 36)            .background(RoundedRectangle(cornerRadius: 12).stroke(Olive.ink, lineWidth: 1.5))            .contentShape(Rectangle())            .padding(.vertical, 4)            .opacity(configuration.isPressed ? 0.6 : 1)    }}/// A word that acts, bold in ink (Select, Bring back 19, Name, Undo).struct AlbumsActStyle: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label            .font(AlbumsType.act)            .foregroundStyle(Olive.ink)            .frame(minHeight: 44)            .contentShape(Rectangle())            .opacity(configuration.isPressed ? 0.6 : 1)    }}/// A round outlined button at a title's end (the plus on Albums, ··· on an album).struct AlbumsRoundButton: View {    let symbol: String    let label: String    let tag: String    let tap: () -> Void    var body: some View {        Button(action: tap) {            Image(systemName: symbol).font(.system(size: 17, weight: .regular)).foregroundStyle(Olive.ink)                .frame(width: 40, height: 40)                .overlay(Circle().stroke(Olive.ink, lineWidth: 1.5))                .frame(width: 44, height: 44)                .contentShape(Circle())        }        .buttonStyle(.plain)        .accessibilityLabel(label)        .accessibilityIdentifier(tag)    }}/// A back bar: chevron and where it returns to; something at its end (Select, 1 of 1,912).struct AlbumsBar<End: View>: View {    let back: String    let tap: () -> Void    @ViewBuilder var end: () -> End    var body: some View {        HStack {            Button(action: tap) {                HStack(spacing: 2) {                    Image(systemName: "chevron.left").font(.system(size: 17, weight: .regular))                    Text(verbatim: back).font(AlbumsType.body)                }                .foregroundStyle(Olive.ink)                .frame(minHeight: 44)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("albums-back")            Spacer()            end()        }        .padding(.horizontal, Olive.side)        .frame(minHeight: 44)    }}extension AlbumsBar where End == EmptyView {    init(back: String, tap: @escaping () -> Void) { self.init(back: back, tap: tap) { EmptyView() } }}/// A row of a list: a cover, its name and line, what it counts at the end; a chevron when it opens.struct AlbumsListRow: View {    var cover: String?    var symbol: String?    let title: String    var line: String?    var end: String?    var opens = true    var dim = false    let tag: String    var tap: (() -> Void)?    @Environment(\.dynamicTypeSize) private var size    var body: some View {        Button { tap?() } label: {            VStack(spacing: 0) {                HStack(spacing: 12) {                    if size.isAccessibilitySize {                        // The largest sizes: the name takes the width, and what it counts goes under it.                        VStack(alignment: .leading, spacing: 2) {                            Text(verbatim: title).font(AlbumsType.name).foregroundStyle(Olive.ink)                                .fixedSize(horizontal: false, vertical: true)                            if let line {                                Text(verbatim: line).font(AlbumsType.line).foregroundStyle(Olive.quiet)                                    .fixedSize(horizontal: false, vertical: true)                            }                            if let end { Text(verbatim: end).font(AlbumsType.figure).foregroundStyle(Olive.quiet) }                        }                        .frame(maxWidth: .infinity, alignment: .leading)                    } else {                        row                    }                    if opens, tap != nil {                        Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(Olive.quiet)                    }                }                .padding(.vertical, 10)                .opacity(dim ? 0.45 : 1)                AlbumsRule()            }            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .disabled(tap == nil)        .accessibilityElement(children: .combine)        .accessibilityIdentifier(tag)    }    @ViewBuilder private var row: some View {                    if let cover {                        AlbumsTile(id: cover, side: 52).clipShape(RoundedRectangle(cornerRadius: 9))                    } else if let symbol {                        Image(systemName: symbol).font(.system(size: 19, weight: .light)).foregroundStyle(Olive.ink).frame(width: 30)                    } else if dim {                        RoundedRectangle(cornerRadius: 9).fill(Olive.well).frame(width: 52, height: 52)                    }                    VStack(alignment: .leading, spacing: 2) {                        Text(verbatim: title).font(AlbumsType.name).foregroundStyle(Olive.ink)                            .fixedSize(horizontal: false, vertical: true)                        if let line {                            Text(verbatim: line).font(AlbumsType.line).foregroundStyle(Olive.quiet)                                .fixedSize(horizontal: false, vertical: true)                        }                    }                    .frame(maxWidth: .infinity, alignment: .leading)                    if let end { Text(verbatim: end).font(AlbumsType.figure).foregroundStyle(Olive.quiet).lineLimit(1).layoutPriority(1) }    }}/// A short line that rises at the foot and goes by itself, with Undo when there is one.struct AlbumsToast: View {    let words: String    var undo: String?    var tapUndo: (() -> Void)?    var body: some View {        HStack(spacing: 14) {            Text(verbatim: words).font(AlbumsType.body).foregroundStyle(Olive.ground).fixedSize(horizontal: false, vertical: true)            if let undo, let tapUndo {                Button(undo, action: tapUndo)                    .font(AlbumsType.act)                    .foregroundStyle(Olive.ground)                    .underline()                    .frame(minHeight: 44)                    .accessibilityIdentifier("albums-undo")            }        }        .padding(.horizontal, 18).padding(.vertical, 10)        .background(RoundedRectangle(cornerRadius: 16).fill(Olive.ink))        .accessibilityElement(children: .contain)        .accessibilityIdentifier("albums-toast")    }}/// The empty screen, as the family draws one: a plain heading and one line.struct AlbumsEmpty: View {    let title: String    let line: String    var body: some View {        VStack(alignment: .leading, spacing: 6) {            Text(verbatim: title).font(AlbumsType.name).foregroundStyle(Olive.ink)            Text(verbatim: line).font(AlbumsType.body).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true)        }        .padding(.top, 24)        .frame(maxWidth: .infinity, alignment: .leading)        .accessibilityElement(children: .combine)        .accessibilityIdentifier("albums-empty")    }}/// The photo corner (the app's mark): a solid triangle over the outlined corner of a print.struct AlbumsCornerMark: View {    var size: CGFloat = 64    var body: some View {        Canvas { context, box in            let s = box.width            var print = Path()            print.addRoundedRect(in: CGRect(x: s * 0.22, y: s * 0.22, width: s * 0.78, height: s * 0.78), cornerSize: CGSize(width: s * 0.08, height: s * 0.08))            context.fill(print, with: .color(Olive.print))            var edge = Path()            edge.move(to: CGPoint(x: s * 0.22, y: s)); edge.addLine(to: CGPoint(x: s * 0.22, y: s * 0.22)); edge.addLine(to: CGPoint(x: s, y: s * 0.22))            context.stroke(edge, with: .color(Olive.ink), lineWidth: s * 0.06)            var corner = Path()            corner.move(to: CGPoint(x: 0, y: 0)); corner.addLine(to: CGPoint(x: s * 0.62, y: 0)); corner.addLine(to: CGPoint(x: 0, y: s * 0.62)); corner.closeSubpath()            context.fill(corner, with: .color(Olive.accent))        }        .frame(width: size, height: size)        .accessibilityHidden(true)    }}/// The look-only build's one quiet line, where an act would stand.struct AlbumsLookOnlyLine: View {    var body: some View {        Text(verbatim: AlbumsWords.line("look_only.line"))            .font(AlbumsType.line).foregroundStyle(Olive.quiet)            .fixedSize(horizontal: false, vertical: true)            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.vertical, 10)            .accessibilityIdentifier("albums-look-only")    }}#endif