Cotton code
408 lines · 17.8 KB · SwiftRaw
// LOOK, ONE SCREEN FOR EVERY APP (owner, 23 Nov 2026; assets/design/shared/DECISIONS.md "Look").// Built once and fed each app's papers, inks, faces and preview; drawn in the// app's own look (`LookSkin`). Top to foot: the live preview, Paper in two rows// (FEEDBACK-4 A1: "When the phone is light", the papers as they are then, and// "When the phone is dark", as they are then; one ringed in// each row, each row opening on its chosen paper with the next peeking), Ink, Text// (the faces, each in its own face, and the size), the app's More, and Reset to// default, small at the foot, which the app asks in its own look.// The choices, their bounds, their defaults and every word are the core's `look`// answer (`LookModel.swift`); this screen only draws them and says what was tapped.#if os(iOS)import CottonWritingimport SwiftUI/// What one app offers and what stands chosen, as its core answered.struct LookChoices: Equatable {    /// One appearance of a paper: what its swatch is drawn in.    struct Half: Equatable {        var ground: Color        var text: Color        var accent: Color        var rule: Color    }    struct Paper: Equatable, Identifiable {        var id: String        var name: String        var light: Half        var dark: Half    }    struct Ink: Equatable, Identifiable {        var id: String        var name: String        var light: Color        var dark: Color    }    struct Face: Equatable, Identifiable {        var id: String        var name: String    }    struct Size: Equatable {        var value: Double        var label: String    }    struct Chosen: Equatable {        var light: String        var dark: String        var ink: String?        var face: String        var size: Double    }    var papers: [Paper]    var inks: [Ink]    var faces: [Face]    var sizes: [Size]    var chosen: Chosen    /// The core's answer, as the screen reads it: each half's ground, words, ink and rule from the app's own tokens.    init(_ answer: LookAnswer) {        func half(_ t: [String: String]) -> Half {            func colour(_ keys: String...) -> Color { Color(uiColor: LookAnswer.ui(keys.lazy.compactMap { t[$0] }.first ?? "#808080")) }            return Half(ground: colour("ground", "sheet"), text: colour("text", "ink"), accent: colour("accent"), rule: colour("rule", "line"))        }        papers = answer.papers.map { Paper(id: $0.id, name: $0.name, light: half($0.light), dark: half($0.dark)) }        inks = answer.inks.map { Ink(id: $0.id, name: $0.name, light: Color(uiColor: LookAnswer.ui($0.light)), dark: Color(uiColor: LookAnswer.ui($0.dark))) }        faces = answer.faces.map { Face(id: $0.id, name: $0.name) }        sizes = answer.sizes.map { Size(value: $0.value, label: $0.label) }        chosen = Chosen(light: answer.light, dark: answer.dark, ink: answer.ink, face: answer.face, size: answer.size)    }}/// One tap on the screen, for the app to write through its core.enum LookPick: Equatable {    case paper(String, dark: Bool)    case ink(String)    case face(String)    case size(Double)}enum LookMetrics {    static let tileHeight: CGFloat = 84    /// A paper tile's width such that whole tiles and about half the next stand in `visible`.    static func tileWidth(visible: CGFloat, spacing: CGFloat) -> CGFloat {        let natural: CGFloat = 88        let whole = max(1, ((visible + spacing) / (natural + spacing) - 0.45).rounded())        return min(112, max(72, (visible - whole * spacing) / (whole + 0.45)))    }}/// The screen's words, the core's `look` set as its answer says them.struct LookWords {    var paper: String    var light: String    var dark: String    /// The two paper rows' headings ("When the phone is light", "When the phone is dark").    var whenLight: String    var whenDark: String    var ink: String    var text: String    var size: String    var smaller: String    var larger: String    var more: String    var reset: String    init(_ answer: LookAnswer) {        paper = answer.word("paper"); light = answer.word("light"); dark = answer.word("dark"); ink = answer.word("ink")        whenLight = answer.word("when_light"); whenDark = answer.word("when_dark")        text = answer.word("text"); size = answer.word("size"); smaller = answer.word("smaller"); larger = answer.word("larger")        more = answer.word("more"); reset = answer.word("reset")    }}/// The app's look the screen is drawn in.struct LookSkin {    var ground: Color    var ink: Color    var quiet: Color    var accent: Color    var onAccent: Color    var sheet: Color    var rule: Color    /// The app's own face at a size and weight.    var font: (CGFloat, Font.Weight) -> Font    /// A face the screen offers, at a size: each chip is set in its own face.    var face: (String, CGFloat) -> Font}struct LookScreen<Preview: View, More: View>: View {    let choices: LookChoices    let words: LookWords    let skin: LookSkin    /// The page's side margin: the paper row runs past it to the screen's edge, so the next card peeks there.    var gutter: CGFloat = 20    let choose: (LookPick) -> Void    let reset: () -> Void    /// The app's real content drawn in the paper of an appearance (dark or not), the ink, the face and the size chosen.    @ViewBuilder var preview: (_ dark: Bool) -> Preview    @ViewBuilder var more: () -> More    @Environment(\.colorScheme) private var scheme    /// The appearance the preview shows: the phone's, until a half is tapped.    @State private var showing: Bool?    /// The page's width inside its margins, measured.    @State private var rowWidth: CGFloat = 0    private var dark: Bool { showing ?? (scheme == .dark) }    var body: some View {        VStack(alignment: .leading, spacing: 22) {            preview(dark)                .frame(maxWidth: .infinity, alignment: .leading)                .accessibilityElement(children: .combine)                .accessibilityIdentifier("look-preview")                .accessibilityValue(Text(verbatim: dark ? words.dark : words.light))            section(words.whenLight) { papers(dark: false) }            section(words.whenDark) { papers(dark: true) }            if !choices.inks.isEmpty { section(words.ink) { inks } }            section(words.text) { text }            more()            resetButton        }        #if COTTON_DEV        // The face every screen of the app now draws its words in, as the font the phone resolves for it (its        // PostScript name; `own` for the app's own face): a test reads it, as no test can read a drawn font.        .overlay(alignment: .topLeading) {            Color.clear.frame(width: 1, height: 1)                .accessibilityElement()                .accessibilityIdentifier("look-drawn-face")                .accessibilityValue(Text(verbatim: drawnFace))        }        #endif    }    #if COTTON_DEV    /// The probe's value: the face's PostScript name, or the app's own face's id (not words a person reads).    private var drawnFace: String {        let own = LookFaces.own        return choices.chosen.face == own ? own : WritingFonts.font(LookFaces.drawn(choices.chosen.face, own: "sans"), size: 17).fontName    }    #endif    private func section<Content: View>(_ title: String, @ViewBuilder _ content: () -> Content) -> some View {        VStack(alignment: .leading, spacing: 10) {            Text(verbatim: title).font(skin.font(14, .semibold)).foregroundStyle(skin.quiet)                .accessibilityAddTraits(.isHeader)            content()        }    }    // MARK: Paper    /// The papers as they are in one appearance, one tile each, the chosen one ringed.    private func papers(dark: Bool) -> some View {        // The row runs from the page's margin to the screen's edge, so the next tile peeks there.        let width = LookMetrics.tileWidth(visible: rowWidth > 0 ? rowWidth + gutter : 353, spacing: 14)        let chosen = dark ? choices.chosen.dark : choices.chosen.light        return ScrollViewReader { reader in            ScrollView(.horizontal, showsIndicators: false) {                HStack(alignment: .top, spacing: 14) {                    ForEach(choices.papers) { paper in                        let on = chosen == paper.id                        VStack(alignment: .leading, spacing: 6) {                            tile(paper, dark: dark, on: on, width: width)                            Text(verbatim: paper.name).font(skin.font(14, on ? .bold : .regular)).foregroundStyle(on ? skin.ink : skin.quiet)                                .lineLimit(1).minimumScaleFactor(0.7)                                .padding(.leading, 4)                                .accessibilityHidden(true)                        }                        .frame(width: width + 8, alignment: .leading)                        .id(paper.id)                    }                }                .padding(.horizontal, gutter - 4)                .padding(.vertical, 2)            }            .padding(.horizontal, -gutter)            .onAppear { reader.scrollTo(chosen, anchor: .center) }            .accessibilityIdentifier("look-papers-\(dark ? "dark" : "light")")        }        .frame(maxWidth: .infinity)        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { rowWidth = $0 }    }    private func tile(_ paper: LookChoices.Paper, dark: Bool, on: Bool, width: CGFloat) -> some View {        let half = dark ? paper.dark : paper.light        return Button {            showing = dark            if !on { choose(.paper(paper.id, dark: dark)) }        } label: {            // A page in miniature: a heading, two lines of words and a stroke of the ink.            VStack(alignment: .leading, spacing: 7) {                Capsule().fill(half.text).frame(width: width * 0.45, height: 6)                Capsule().fill(half.text.opacity(0.55)).frame(height: 3)                Capsule().fill(half.text.opacity(0.55)).frame(width: width * 0.4, height: 3)                Capsule().fill(half.accent).frame(width: 18, height: 4)            }            .padding(10)            .frame(width: width, height: LookMetrics.tileHeight, alignment: .topLeading)            .background(RoundedRectangle(cornerRadius: 12).fill(half.ground))            .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(half.rule, lineWidth: 0.5))            .padding(4)            // The ring stands on the screen's ground in the screen's ink, so it shows whatever the paper.            .overlay(RoundedRectangle(cornerRadius: 15).strokeBorder(on ? skin.accent : Color.clear, lineWidth: 2.5))            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: paper.name))        .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)        .accessibilityIdentifier("look-paper-\(dark ? "dark" : "light")-\(paper.id)")    }    // MARK: Ink    private var inks: some View {        HStack(spacing: 14) {            ForEach(choices.inks) { ink in                let on = choices.chosen.ink == ink.id                let colour = dark ? ink.dark : ink.light                Button { if !on { choose(.ink(ink.id)) } } label: {                    VStack(spacing: 6) {                        Circle().fill(colour).frame(width: 30, height: 30)                            .padding(4)                            .overlay(Circle().strokeBorder(on ? skin.accent : Color.clear, lineWidth: 2.5))                        Text(verbatim: ink.name).font(skin.font(13, on ? .bold : .regular)).foregroundStyle(on ? skin.ink : skin.quiet)                            .lineLimit(1).minimumScaleFactor(0.6)                    }                    .frame(minWidth: 52, minHeight: 44)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityLabel(Text(verbatim: ink.name))                .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                .accessibilityIdentifier("look-ink-\(ink.id)")            }        }    }    // MARK: Text    private var text: some View {        VStack(alignment: .leading, spacing: 14) {            SearchWrapLayout(spacing: 8, lineSpacing: 8) {                ForEach(choices.faces) { face in                    let on = choices.chosen.face == face.id                    Button { if !on { choose(.face(face.id)) } } label: {                        Text(verbatim: face.name).font(skin.face(face.id, 16))                            .foregroundStyle(on ? skin.onAccent : skin.ink)                            .padding(.horizontal, 14).padding(.vertical, 9)                            .background(Capsule().fill(on ? skin.accent : skin.sheet))                            .fixedSize()                    }                    .buttonStyle(.plain)                    .accessibilityLabel(Text(verbatim: face.name))                    .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                    .accessibilityIdentifier("look-face-\(face.id)")                }            }            sizeRow        }    }    private var sizeRow: some View {        let sizes = choices.sizes        let at = sizes.firstIndex { abs($0.value - choices.chosen.size) < 1e-6 }        let label = at.map { sizes[$0].label } ?? ""        return HStack(spacing: 8) {            Text(verbatim: words.size).font(skin.font(15, .regular)).foregroundStyle(skin.ink)            Spacer(minLength: 8)            sizeKey(small: true, to: at.flatMap { $0 > 0 ? sizes[$0 - 1].value : nil })            Text(verbatim: label).font(skin.font(16, .semibold)).foregroundStyle(skin.ink)                .monospacedDigit().lineLimit(1).minimumScaleFactor(0.6).frame(minWidth: 30)                .accessibilityIdentifier("look-size-value")            sizeKey(small: false, to: at.flatMap { $0 < sizes.count - 1 ? sizes[$0 + 1].value : nil })        }        .accessibilityElement(children: .contain)    }    private func sizeKey(small: Bool, to next: Double?) -> some View {        Button { if let next { choose(.size(next)) } } label: {            // A mark, not words: it keeps to its circle at any text size.            Text(verbatim: "A").font(skin.face(choices.chosen.face, small ? 13 : 21))                .lineLimit(1).minimumScaleFactor(0.3)                .foregroundStyle(skin.ink.opacity(next != nil ? 1 : 0.35))                .frame(width: small ? 22 : 30, height: 30)                .frame(width: 44, height: 44).background(Circle().fill(skin.sheet))        }        .buttonStyle(.plain)        .disabled(next == nil)        .accessibilityLabel(Text(verbatim: small ? words.smaller : words.larger))        .accessibilityIdentifier(small ? "look-size-smaller" : "look-size-larger")    }    // MARK: Reset    private var resetButton: some View {        Button(action: reset) {            Text(verbatim: words.reset).font(skin.font(14, .medium)).foregroundStyle(skin.quiet)                .underline()                .frame(maxWidth: .infinity, minHeight: 44)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(.top, 8)        .accessibilityIdentifier("look-reset")    }}#endif#if os(iOS)import UIKit/// A preview's styled words, whole at any text size: a text view that neither scrolls nor takes a touch, measured at the/// width it is given (a label under-measured the last line at the largest text and cut it short).struct LookSampleText: UIViewRepresentable {    let text: NSAttributedString    func makeUIView(context: Context) -> UITextView {        let view = UITextView()        view.isEditable = false        view.isSelectable = false        view.isScrollEnabled = false        view.backgroundColor = .clear        view.textContainerInset = .zero        view.textContainer.lineFragmentPadding = 0        view.isUserInteractionEnabled = false        view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)        return view    }    func updateUIView(_ view: UITextView, context: Context) {        if view.attributedText != text { view.attributedText = text }    }    func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextView, context: Context) -> CGSize? {        let width = proposal.width ?? 320        let fitted = uiView.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude))        return CGSize(width: width, height: ceil(fitted.height))    }}/// iPhone only (owner, 23 Nov 2026; shared/DECISIONS.md "Look"): the home-screen icon follows the ink. Each app/// carries one alternate icon per ink but its default, named after its primary icon and the ink (`AppIconNotesRed`,/// `AppIconNotesDevRed`); the default ink is the primary icon. iOS says its own line when the icon changes.@MainActorenum LookIcon {    private static var icons: [String: Any]? { Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any] }    private static var primary: String? { (icons?["CFBundlePrimaryIcon"] as? [String: Any])?["CFBundleIconName"] as? String }    private static var alternates: Set<String> { Set(((icons?["CFBundleAlternateIcons"] as? [String: Any]) ?? [:]).keys) }    /// The icon this ink stands for: nil (the primary) for the default ink, else the ink's own set where the app carries one.    static func name(for ink: String?, defaultInk: String) -> String? {        guard let ink, ink != defaultInk, let primary else { return nil }        let name = primary + ink.prefix(1).uppercased() + ink.dropFirst()        return alternates.contains(name) ? name : nil    }    /// Sets the icon for `ink`, when it is not already the one standing.    static func follow(_ ink: String?, defaultInk: String) {        let app = UIApplication.shared        guard app.supportsAlternateIcons else { return }        let wanted = name(for: ink, defaultInk: defaultInk)        guard app.alternateIconName != wanted else { return }        app.setAlternateIconName(wanted) { _ in }    }}#endif