Sources/OrgstarMobile/MobileTheme.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/MobileTheme.swift history · blame · raw

183 lines · 8856 bytes

  1#if os(iOS)
  2import OrgPresentation
  3import SwiftUI
  4import UIKit
  5
  6/// Attributes for each style role, from a `ThemeSpec`, as the Mac editor's theme sets them.
  7@MainActor
  8struct MobileTheme {
  9    let spec: ThemeSpec
 10    /// The fixed-pitch font: columns, tables, code and the rest of `Presentation.isFixedPitch`.
 11    let font: UIFont
 12    /// The font for prose; `font` unless the theme names a body font.
 13    let body: UIFont
 14
 15    init(_ spec: ThemeSpec = .default) {
 16        self.spec = spec
 17        let size = CGFloat(max(6, spec.fontSize))
 18        // The theme's family when the device has it, else the monospaced system font; at the
 19        // theme's size for the default Dynamic Type size, scaled for others.
 20        let chosen = spec.font.isEmpty || UIFont.fontNames(forFamilyName: spec.font).isEmpty ? nil
 21            : UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: spec.font]), size: size)
 22        let metrics = UIFontMetrics(forTextStyle: .body)
 23        font = metrics.scaledFont(for: chosen ?? .monospacedSystemFont(ofSize: size, weight: .regular))
 24        body = switch spec.bodyFont {
 25        case "": font
 26        case "system": metrics.scaledFont(for: .systemFont(ofSize: size))
 27        case let family where !UIFont.fontNames(forFamilyName: family).isEmpty:
 28            metrics.scaledFont(for: UIFont(descriptor: UIFontDescriptor(fontAttributes: [.family: family]), size: size))
 29        default: font
 30        }
 31    }
 32
 33    /// Prose and fixed-pitch text use different fonts.
 34    var mixedPitch: Bool { body != font }
 35
 36    /// The fixed-pitch font at the size and weight of `current`.
 37    func fixedPitch(_ current: UIFont) -> UIFont {
 38        let sized = font.withSize(current.pointSize)
 39        return current.fontDescriptor.symbolicTraits.contains(.traitBold) ? Self.adding(.traitBold, to: sized) : sized
 40    }
 41
 42    /// A color that follows the appearance, or nil when the theme has none for `key`.
 43    func color(_ key: String) -> UIColor? {
 44        // As on the Mac: a key the theme has for one appearance only takes the default for the
 45        // other, except a key the system colors there.
 46        let (light, dark) = (spec.editorColor(key, dark: false), spec.editorColor(key, dark: true))
 47        if let light, let dark { return Self.dynamic(light, dark) }
 48        guard light != nil || dark != nil else { return nil }
 49        return UIColor { traits in
 50            guard let c = traits.userInterfaceStyle == .dark ? dark : light else { return Self.systemColor(key) }
 51            return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 52        }
 53    }
 54
 55    /// What the system shows for a `ThemeSpec.systemDefaults` key the theme leaves unset.
 56    static func systemColor(_ key: String) -> UIColor {
 57        switch key {
 58        case "sidebar-background", "modeline-background": .secondarySystemBackground
 59        case "agenda-background": .systemBackground
 60        case "sidebar-header", "modeline-foreground": .secondaryLabel
 61        case "accent": .systemBlue
 62        default: .label
 63        }
 64    }
 65
 66    static func dynamic(_ light: RGBA, _ dark: RGBA) -> UIColor {
 67        UIColor { traits in
 68            let c = traits.userInterfaceStyle == .dark ? dark : light
 69            return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
 70        }
 71    }
 72
 73    var foreground: UIColor { color("foreground") ?? .label }
 74
 75    /// A TODO keyword's color: its own from `[theme.todo]`, else its class's (`todo-next`,
 76    /// `todo-waiting`, `todo-cancelled`, `todo`, `done`).
 77    func keywordColor(_ keyword: String, done: Bool) -> UIColor? {
 78        if let custom = spec.todo[keyword] { return Self.dynamic(custom, custom) }
 79        return color(ThemeSpec.TodoClass.of(keyword, isDone: done).key)
 80    }
 81
 82    /// A heading's font: larger by the heading step for levels 1 to 3, bold.
 83    func headingFont(_ level: Int) -> UIFont {
 84        let size = body.pointSize + CGFloat(max(0, spec.headingSizeStep) * max(0, 4 - level))
 85        return Self.adding(.traitBold, to: body.withSize(size))
 86    }
 87
 88    static func adding(_ traits: UIFontDescriptor.SymbolicTraits, to font: UIFont) -> UIFont {
 89        guard let descriptor = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(traits)) else { return font }
 90        return UIFont(descriptor: descriptor, size: font.pointSize)
 91    }
 92
 93    var base: [NSAttributedString.Key: Any] {
 94        [.font: body, .foregroundColor: foreground, .paragraphStyle: paragraphStyle(firstLine: 0, wrapped: 0)]
 95    }
 96
 97    /// Markup hidden from view: no width, no color.
 98    var hidden: [NSAttributedString.Key: Any] {
 99        [.font: UIFont.monospacedSystemFont(ofSize: 0.01, weight: .regular), .foregroundColor: UIColor.clear]
100    }
101
102    /// Width of one column of the font.
103    var column: CGFloat {
104        ("0" as NSString).size(withAttributes: [.font: font]).width
105    }
106
107    func paragraphStyle(firstLine: Int, wrapped: Int) -> NSParagraphStyle {
108        let style = NSMutableParagraphStyle()
109        style.firstLineHeadIndent = CGFloat(firstLine) * column
110        style.headIndent = CGFloat(wrapped) * column
111        style.lineSpacing = CGFloat(max(0, spec.lineSpacing))
112        // `tab-width` 8, counted from the line's own start, past org-indent's indentation.
113        style.defaultTabInterval = 8 * column
114        style.tabStops = (1...32).map { NSTextTab(textAlignment: .left, location: style.firstLineHeadIndent + CGFloat($0 * 8) * column) }
115        return style
116    }
117
118    func apply(_ role: StyleRole, to storage: NSTextStorage, range: NSRange) {
119        func fg(_ key: String) {
120            if let color = color(key) { storage.addAttribute(.foregroundColor, value: color, range: range) }
121        }
122        func traits(_ add: UIFontDescriptor.SymbolicTraits) {
123            let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
124            storage.addAttribute(.font, value: Self.adding(add, to: current), range: range)
125        }
126        if mixedPitch, Presentation.isFixedPitch(role) {
127            let current = storage.attribute(.font, at: range.location, effectiveRange: nil) as? UIFont ?? body
128            storage.addAttribute(.font, value: fixedPitch(current), range: range)
129        }
130        switch role {
131        case .heading(let level):
132            storage.addAttribute(.font, value: headingFont(level), range: range)
133            fg("heading-\(min(max(level, 1), 8))")
134        case .leadingStars:
135            storage.addAttribute(.foregroundColor, value: UIColor.clear, range: range)
136        case .todo, .done:
137            traits(.traitBold)
138            let keyword = (storage.string as NSString).substring(with: range)
139            if let color = keywordColor(keyword, done: role == .done) { storage.addAttribute(.foregroundColor, value: color, range: range) }
140        case .priority: fg("priority")
141        case .tags: fg("tags")
142        case .comment: fg("comment")
143        case .keyword: fg("keyword")
144        case .metadata: fg("metadata")
145        case .bold: traits(.traitBold)
146        case .italic: traits(.traitItalic)
147        case .underline: storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
148        case .strikeThrough: storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: range)
149        case .verbatim, .code, .inlineSource:
150            if let background = color("inline-background") { storage.addAttribute(.backgroundColor, value: background, range: range) }
151            fg(role == .verbatim ? "verbatim" : "code")
152        case .markup, .linkMarkup: fg("markup")
153        case .blockDelimiter: fg("block-delimiter")
154        case .link:
155            storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: range)
156            fg("link")
157        case .timestamp: fg("timestamp")
158        case .footnote, .cookie, .target, .macro, .latex: fg("special")
159        case .table, .rule: fg("table")
160        case .block: break
161        case .syntax(let category):
162            if let key = category.themeKey { fg(key) }
163        }
164    }
165
166    // MARK: - SwiftUI
167
168    /// A theme color for SwiftUI views.
169    func swiftColor(_ key: String) -> Color? { color(key).map { Color(uiColor: $0) } }
170}
171extension ThemeSpec {
172    /// `accent` for `.tint`, the system's blue in an appearance the theme leaves it unset; nil
173    /// when neither appearance sets it.
174    var accentColor: Color? {
175        let (light, dark) = (light["accent"], dark["accent"])
176        guard light != nil || dark != nil else { return nil }
177        return Color(uiColor: UIColor { traits in
178            guard let c = traits.userInterfaceStyle == .dark ? dark : light else { return .systemBlue }
179            return UIColor(red: c.red, green: c.green, blue: c.blue, alpha: c.alpha)
180        })
181    }
182}
183#endif