Cotton code
468 lines · 19.1 KB · SwiftRaw
// Cotton Story's look, "Ink" (assets/design/story/DECISIONS.md, gate 3, and// ink.html, which is the specification): a cool pale ground, dark navy ink,// one ballpoint blue, a typewriter face for titles and a clean monospace for// everything else, thin dotted rules, outlined capsules. No cards, shadows,// gradients or textures. Every Story screen draws from this file alone, so a// value here is ink.html's `:root` or one of its rules, by name.#if os(iOS)import CoreTextimport CottonPaperimport CottonWritingimport SwiftUIimport UIKit/// ink.html's `:root` colours.@MainActorenum Ink {    private static var look: LookModel { LookModel.standing("story") }    // ink.html's `:root`, as the person's Look stands (shared/DECISIONS.md "Look"): the chosen paper's half for the    // phone's appearance, in the chosen ink (`LookModel`); before the core has ever answered, ink.html's own.    static var ground: Color { look.colour("sheet", 0xEEEDF5) }    static var under: Color { look.colour("ground", 0xE9E8F1) }    static var ink: Color { look.colour("ink", 0x161A3A) }    static var quiet: Color { look.colour("quiet", 0x5D6183) }    static var rule: Color { look.colour("rule", 0x9A9DBB) }    /// The ink: the ballpoint blue by default.    static var blue: Color { look.colour("accent", 0x1F3FE0) }    static var blueSoft: Color { look.colour("accent_soft", 0xDFE3FB) }    static var onBlue: Color { look.colour("on_accent", 0xFFFFFF) }    static let gutter: CGFloat = 20    /// The outline every pill, chip and face is drawn with (`1.5px solid`).    static let stroke: CGFloat = 1.5}extension Color {    init(ink hex: UInt32) {        self.init(red: Double((hex >> 16) & 0xFF) / 255, green: Double((hex >> 8) & 0xFF) / 255, blue: Double(hex & 0xFF) / 255)    }}/// The two faces, SIL OFL, from CottonPaper's fonts (the same files Android/// ships), registered once for the process. A build with no resources draws/// the system's monospace instead; the app always has them.enum InkFonts {    static let files = ["CourierPrime-Regular", "IBMPlexMono-Regular", "IBMPlexMono-Medium", "IBMPlexMono-SemiBold", "IBMPlexMono-Italic"]    /// Each file's PostScript name as CoreText read it, once.    private static let registered: [String: String] = {        var names: [String: String] = [:]        for file in files {            guard let url = CottonFonts.file(file, extension: "ttf") else { continue }            _ = CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)            if let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor],               let first = descriptors.first,               let name = CTFontDescriptorCopyAttribute(first, kCTFontNameAttribute) as? String {                names[file] = name            }        }        return names    }()    static func register() { _ = registered }    static func name(_ file: String) -> String? { registered[file] }}/// ink.html's type, by rule. Every size scales with the phone's text size/// (`relativeTo`), so larger text grows the screen rather than clipping it.@MainActorenum InkType {    enum Weight { case regular, medium, semibold, italic }    /// `--title`, Courier Prime.    static func title(_ size: CGFloat, relativeTo style: Font.TextStyle = .largeTitle) -> Font {        let size = size * LookModel.standing("story").scale        return face("CourierPrime-Regular", size, style) ?? .system(size: size, design: .monospaced)    }    /// `--mono`, IBM Plex Mono.    /// The words' face at `size`, as Look stands: the chosen size's share of it, and IBM Plex Mono unless another face is    /// chosen (then that face, scaled with the phone's text size). Titles stay Courier Prime.    static func mono(_ size: CGFloat, _ weight: Weight = .regular, relativeTo style: Font.TextStyle = .body) -> Font {        let look = LookModel.standing("story")        let size = size * look.scale        if look.face != "own" {            let drawn = LookFaces.drawn(look.face, own: "mono")            let font = WritingFonts.font(drawn, size: size, weight: weight == .semibold ? .semibold : weight == .medium ? .medium : .regular,                                         italic: weight == .italic)            return Font(font)        }        return own(size, weight, relativeTo: style)    }    /// IBM Plex Mono itself, whatever Look's face.    static func own(_ size: CGFloat, _ weight: Weight = .regular, relativeTo style: Font.TextStyle = .body) -> Font {        let file = switch weight {        case .regular: "IBMPlexMono-Regular"        case .medium: "IBMPlexMono-Medium"        case .semibold: "IBMPlexMono-SemiBold"        case .italic: "IBMPlexMono-Italic"        }        if let font = face(file, size, style) { return font }        let system = Font.system(size: size, weight: weight == .semibold ? .semibold : weight == .medium ? .medium : .regular, design: .monospaced)        return weight == .italic ? system.italic() : system    }    private static func face(_ file: String, _ size: CGFloat, _ style: Font.TextStyle) -> Font? {        InkFonts.register()        return InkFonts.name(file).map { Font.custom($0, size: size, relativeTo: style) }    }    // ink.html's rules, by selector.    /// `h1`: the script's title on its home.    static var h1: Font { title(46) }    /// `h1 span`: the chevron beside the title.    static var h1Mark: Font { title(22, relativeTo: .title2) }    /// `.empty .big`: the one sentence an empty screen says.    static var big: Font { title(28, relativeTo: .title) }    /// `.count`, `.why`: the count line, an empty screen's sentence.    static var count: Font { mono(13, relativeTo: .subheadline) }    /// `.who`: a cast name.    static var castName: Font { mono(12, relativeTo: .caption) }    /// `.face`: an initial in a big face.    static var initial: Font { title(26, relativeTo: .title) }    /// `.line .face`: an initial in a speaker's face.    static var smallInitial: Font { title(15, relativeTo: .body) }    /// `.pill`.    static var pill: Font { mono(13, relativeTo: .subheadline) }    /// `.sc .n`: a scene's number.    static var sceneNumber: Font { mono(18, relativeTo: .title3) }    /// `.sc b`: a scene's place and time.    static var sceneTitle: Font { mono(15, .semibold, relativeTo: .headline) }    /// `.sc .len`: a scene's length.    static var sceneLength: Font { mono(12.5, relativeTo: .footnote) }    /// `.sc p`: the line that tells a scene apart.    static var scenePreview: Font { mono(13, relativeTo: .subheadline) }    /// `.bar b`: a scene's title in its top bar.    static var barTitle: Font { mono(15, .semibold, relativeTo: .headline) }    /// `.slug`: the standard heading.    static var slug: Font { mono(12, relativeTo: .caption) }    /// `.action`, `.say .tx`.    static var line: Font { mono(14.5, relativeTo: .body) }    /// `.say .nm`: the speaker's name.    static var speaker: Font { mono(11.5, relativeTo: .caption2) }    /// `.say .dir`: a direction.    static var direction: Font { mono(12.5, .italic, relativeTo: .footnote) }    /// `.chip`.    static var chip: Font { mono(12.5, relativeTo: .footnote) }    /// `.btn`.    static var button: Font { mono(14, relativeTo: .body) }    /// `body`: ordinary words.    static var body: Font { mono(14, relativeTo: .body) }    /// `.cap`: a section's small capitals.    static var caption: Font { mono(12, relativeTo: .caption) }}// MARK: - The pieces every screen is built from/// ink.html's `.sc` rule: `1.5px dotted var(--rule)`.struct InkRule: View {    var body: some View {        Line()            .stroke(Ink.rule, style: StrokeStyle(lineWidth: Ink.stroke, lineCap: .round, dash: [0.1, 3.5]))            .frame(height: Ink.stroke)            .accessibilityHidden(true)    }    private struct Line: Shape {        func path(in rect: CGRect) -> Path {            var path = Path()            path.move(to: CGPoint(x: rect.minX + 0.75, y: rect.midY))            path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))            return path        }    }}/// `.pill`: an outlined capsule that opens a view.struct InkPill: View {    let words: String    let action: () -> Void    var body: some View {        Button(action: action) {            Text(words)                .font(InkType.pill)                .foregroundStyle(Ink.ink)                .padding(.vertical, 7)                .padding(.horizontal, 15)                .overlay(Capsule().strokeBorder(Ink.ink, lineWidth: Ink.stroke))                .contentShape(Capsule())        }        .buttonStyle(InkPress())    }}/// A chip's rules, not looks.enum InkChipKnobs {    /// The least a chip's words are drawn at, as a share of their size, to stay on one line.    static let least: CGFloat = 0.5}/// `.chip` and `.chip.on`.struct InkChip<Label: View>: View {    let on: Bool    @ViewBuilder let label: () -> Label    var body: some View {        label()            .font(InkType.chip)            // One line, drawn smaller rather than broken: at the largest text            // on an iPhone SE the speaker chip read "Charact / er" (launch-ios            // walk, 22 Nov 2026).            .lineLimit(1)            .minimumScaleFactor(InkChipKnobs.least)            .foregroundStyle(on ? Ink.blue : Ink.ink)            .padding(.vertical, 4)            .padding(.horizontal, 11)            .background(Capsule().fill(on ? Ink.blueSoft : .clear))            .overlay(Capsule().strokeBorder(on ? Ink.blue : Ink.ink, lineWidth: Ink.stroke))            .contentShape(Capsule())    }}/// `.btn` (blue, the one main act) and `.btn.ghost` (outlined).struct InkButton: View {    let words: String    var ghost = false    let action: () -> Void    var body: some View {        Button(action: action) {            Text(words)                .font(InkType.button)                .foregroundStyle(ghost ? Ink.ink : .white)                .padding(.vertical, 11)                .padding(.horizontal, 18)                .background(Capsule().fill(ghost ? .clear : Ink.blue))                .overlay { if ghost { Capsule().strokeBorder(Ink.ink, lineWidth: Ink.stroke) } }                .contentShape(Capsule())        }        .buttonStyle(InkPress())    }}/// `.fab`: the round blue "+".struct InkPlus: View {    let label: String    let action: () -> Void    var body: some View {        Button(action: action) {            Image(systemName: "plus")                .font(.system(size: 24, weight: .regular))                .foregroundStyle(.white)                .frame(width: 58, height: 58)                .background(Circle().fill(Ink.blue))                .contentShape(Circle())        }        .buttonStyle(InkPress())        .accessibilityLabel(label)    }}/// `.face`: a character in a thin circle, their picture if there is one,/// else their initial in blue (which must still look finished).struct InkFace: View {    let initial: String    var picture: UIImage?    var size: CGFloat = 70    private var big: Bool { size >= 50 }    var body: some View {        ZStack {            if let picture {                Image(uiImage: picture)                    .resizable()                    .scaledToFill()                    .blendMode(.multiply)            } else {                Text(initial)                    .font(big ? InkType.initial : InkType.smallInitial)                    .foregroundStyle(Ink.blue)                    .minimumScaleFactor(0.5)                    .lineLimit(1)            }        }        .frame(width: size, height: size)        .clipShape(Circle())        .overlay(Circle().strokeBorder(Ink.ink, lineWidth: big ? Ink.stroke : 1.2))    }}/// The small glyph buttons in a top bar (`.icons`, `.bar` ‹ ▤ ⋯), drawn in/// ink at 20 pt with a 44 pt target.struct InkGlyph: View {    let symbol: String    let label: String    let action: () -> Void    var body: some View {        Button(action: action) {            Image(systemName: symbol)                .font(.system(size: 19, weight: .regular))                .foregroundStyle(Ink.ink)                .frame(minWidth: 44, minHeight: 44)                .contentShape(Rectangle())        }        .buttonStyle(InkPress())        .accessibilityLabel(label)    }}/// A press dims; nothing grows, glows or shadows.struct InkPress: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? 0.55 : 1)    }}/// A sheet's own top: its title in the typewriter face and a ✕.struct InkSheetTop: View {    let title: String    let close: String    let dismiss: () -> Void    var body: some View {        HStack(alignment: .firstTextBaseline) {            Text(title)                .font(InkType.title(28, relativeTo: .title))                .foregroundStyle(Ink.ink)                .accessibilityAddTraits(.isHeader)            Spacer(minLength: 12)            InkGlyph(symbol: "xmark", label: close, action: dismiss)        }    }}extension View {    /// The Ink ground under a whole screen, the keyboard's area included.    func inkGround() -> some View {        background(Ink.ground.ignoresSafeArea())            .foregroundStyle(Ink.ink)            .tint(Ink.blue)    }}#endif#if os(iOS)/// ink.html's `h1`: the script's title in Courier Prime at 46 points on a/// 430-point-wide screen (scaled to this phone's width and text size), lines/// set 0.98 of the size apart, then the quiet `›` after the last word. SwiftUI/// cannot set a line height under the font's own, so the words are broken/// into lines here and stacked at that pitch.struct InkTitle: View {    let words: String    /// The phone's width, which the size is scaled by.    let screen: CGFloat    @State private var width: CGFloat = 0    static let size: CGFloat = 46    static let drawnWidth: CGFloat = 430    static let lineHeight: CGFloat = 0.98    var body: some View {        let scaled = UIFontMetrics(forTextStyle: .largeTitle).scaledValue(for: Self.size * min(max(screen, 320), Self.drawnWidth) / Self.drawnWidth)        let font = { (size: CGFloat) in InkFonts.name("CourierPrime-Regular").flatMap { UIFont(name: $0, size: size) } ?? .monospacedSystemFont(ofSize: size, weight: .regular) }        // At a large text size a plain word ("Monsoon") was wider than the        // line and broke between its letters: the title is drawn smaller        // until its longest word fits, and broken only past that (launch-ios        // walk, 22 Nov 2026).        let markAt = { (size: CGFloat) in InkFonts.name("CourierPrime-Regular").flatMap { UIFont(name: $0, size: size * 22 / 46) } ?? .monospacedSystemFont(ofSize: size * 22 / 46, weight: .regular) }        let longest = Self.longestWord(words, face: font(scaled), mark: markAt(scaled))        let size = Self.fitted(scaled, longest: longest, width: width)        let face = font(size)        let mark = markAt(size)        let lines = Self.wrap(words, face: face, mark: mark, width: width)        VStack(alignment: .leading, spacing: size * Self.lineHeight - face.lineHeight) {            ForEach(Array(lines.enumerated()), id: \.offset) { at, line in                if at == lines.count - 1 {                    Text(line).font(Font(face as CTFont)).foregroundColor(Ink.ink)                        + Text(" ›").font(Font(mark as CTFont)).foregroundColor(Ink.quiet)                } else {                    Text(line).font(Font(face as CTFont)).foregroundColor(Ink.ink)                }            }        }        .tracking(-0.01 * size)        // A line the measure got a hair wrong wraps rather than clips.        .fixedSize(horizontal: false, vertical: true)        .frame(maxWidth: .infinity, alignment: .leading)        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 }        .accessibilityElement(children: .ignore)        .accessibilityLabel(words)    }    /// The widest word of a title, the last one with its `›` beside it.    static func longestWord(_ words: String, face: UIFont, mark: UIFont) -> CGFloat {        var widths = words.split(separator: " ").map { (String($0) as NSString).size(withAttributes: [.font: face]).width }        if !widths.isEmpty { widths[widths.count - 1] += (" ›" as NSString).size(withAttributes: [.font: mark]).width }        return widths.max() ?? 0    }    /// The least a title is drawn at, as a share of its size, so its longest    /// word fits on a line; a word wider still is broken between letters.    static let leastScale: CGFloat = 0.55    /// The size at which a title whose longest word measures `longest` at    /// `size` fits a line of `width`: `size` when it already fits.    static func fitted(_ size: CGFloat, longest: CGFloat, width: CGFloat) -> CGFloat {        guard width > 0, longest > width else { return size }        return max(size * Self.leastScale, (size * width / longest * 0.98).rounded(.down))    }    /// Greedy word wrap: as many words a line as fit, the last line leaving    /// room for the `›`. A word wider than the line (a long name, or a    /// title in a script written without spaces) is broken between its    /// letters, so the whole title always shows.    static func wrap(_ words: String, face: UIFont, mark: UIFont, width: CGFloat) -> [String] {        let measure = { (text: String, font: UIFont) in (text as NSString).size(withAttributes: [.font: font]).width }        let spaced = words.split(separator: " ").map(String.init)        guard width > 0, !spaced.isEmpty else { return [words] }        let all = spaced.flatMap { word in measure(word, face) <= width ? [word] : broken(word, width: width) { measure($0, face) } }        let markWidth = measure(" ›", mark)        var lines: [String] = []        var current = ""        for word in all {            let trial = current.isEmpty ? word : current + " " + word            if current.isEmpty || measure(trial, face) <= width {                current = trial            } else {                lines.append(current)                current = word            }        }        if measure(current, face) + markWidth > width, let space = current.lastIndex(of: " ") {            lines.append(String(current[..<space]))            current = String(current[current.index(after: space)...])        }        lines.append(current)        return lines    }    /// A word too wide for a line, in pieces that each fit, broken between    /// whole letters (graphemes), never inside one.    static func broken(_ word: String, width: CGFloat, measure: (String) -> CGFloat) -> [String] {        var pieces: [String] = []        var piece = ""        for letter in word {            let trial = piece + String(letter)            if !piece.isEmpty, measure(trial) > width {                pieces.append(piece)                piece = String(letter)            } else {                piece = trial            }        }        if !piece.isEmpty { pieces.append(piece) }        return pieces    }}/// An Ink panel's colours (`LookPanel`, no system sheet): Ink's ground over a light scrim, the screen's corner.extension Ink {    static var panel: LookPanelStyle { LookPanelStyle(scrim: Color.black.opacity(0.24), ground: ground, corner: 28) }}#endif