SPB Git

Repository Public License

Components+FamilyA.swift 11.9 KB 240 lines swift

1import AppKit2import CoreImage3import PrismCore4import PrismLogicRuntime5import PrismObjectModel6import SwiftUI78/// Renderers of catalog family A: layout, display, text and feedback.9struct FamilyAComponents: View {10    static let types: Set<String> = FamilyALayout.types.union(FamilyADisplay.types).union(FamilyAText.types).union(FamilyAFeedback.types)11    let o: PrismObject1213    var body: some View {14        if FamilyALayout.types.contains(o.type) { FamilyALayout(o: o) }15        else if FamilyADisplay.types.contains(o.type) { FamilyADisplay(o: o) }16        else if FamilyAText.types.contains(o.type) { FamilyAText(o: o) }17        else if FamilyAFeedback.types.contains(o.type) { FamilyAFeedback(o: o) }18        else { UnknownComponent(o: o) }19    }20}2122/// Prop readers shared by the family A views.23@MainActor24enum FA {25    /// A list prop, fixed or computed.26    static func list(_ runtime: AppRuntime, _ value: JSONValue?) -> [JSONValue] { runtime.resolve(value).arrayValue ?? [] }2728    /// A text field of a list item; a plain (non-object) item answers for `plainAs`.29    static func field(_ runtime: AppRuntime, _ item: JSONValue, _ key: String, plainAs fallbackKey: String = "") -> String {30        if item.objectValue == nil { return key == fallbackKey ? item.displayString : "" }31        return item[key].map { runtime.string($0) } ?? ""32    }3334    /// The tone of a component, or `fallback` when it sets none.35    static func tone(_ runtime: AppRuntime, _ o: PrismObject, default fallback: String = "neutral") -> String {36        let tone = runtime.string(o.props["tone"])37        return tone.isEmpty ? fallback : tone38    }3940    /// Whether an event has actions; controls without any are shown disabled.41    static func connected(_ o: PrismObject, _ event: String) -> Bool { !(o.events[event] ?? []).isEmpty }4243    /// The title of a child panel: its `name`, or its id.44    static func childTitle(_ runtime: AppRuntime, _ id: String) -> String {45        runtime.blueprint.object(id).map { $0.name.isEmpty ? $0.id : $0.name } ?? id46    }4748    static func alignment(_ name: String?) -> Alignment {49        switch name {50        case "topLeading": .topLeading51        case "top": .top52        case "topTrailing": .topTrailing53        case "leading": .leading54        case "trailing": .trailing55        case "bottomLeading": .bottomLeading56        case "bottom": .bottom57        case "bottomTrailing": .bottomTrailing58        default: .center59        }60    }6162    static func font(_ style: String?) -> Font {63        switch style {64        case "caption": .caption65        case "callout": .callout66        case "headline": .headline67        case "title": .title268        case "largeTitle": .largeTitle69        default: .body70        }71    }72}7374extension PrismTheme {75    /// Fill color for marks (rings, tiles, dots): neutral means the app's accent.76    func mark(_ tone: String) -> Color { tone.isEmpty || tone == "neutral" ? accent : color(tone) }77}7879/// Pure text helpers of family A, kept apart from the views so they can be tested.80enum FamilyAFormat {81    /// Up to two initials of a name: "Ada Lovelace" gives "AL".82    static func initials(_ name: String) -> String {83        let words = name.split(whereSeparator: { $0.isWhitespace || $0 == "-" || $0 == "_" || $0 == "." }).prefix(2)84        return words.compactMap { $0.first.map { String($0).uppercased() } }.joined()85    }8687    /// A signed change: 0.124 gives "+12.4%" as a percentage, "+0.12" as a number.88    static func delta(_ value: Double, percent: Bool, locale: Locale) -> String {89        let v = value.isFinite ? value : 090        if percent { return v.formatted(.percent.precision(.fractionLength(0...1)).sign(strategy: .always(includingZero: false)).locale(locale)) }91        return v.formatted(.number.precision(.fractionLength(0...2)).sign(strategy: .always(includingZero: false)).locale(locale))92    }9394    /// The tone of a change: good news is green, bad news red, no change neutral.95    static func trendTone(delta: Double, positiveIsGood: Bool) -> String {96        if delta == 0 || !delta.isFinite { return "neutral" }97        return (delta > 0) == positiveIsGood ? "success" : "danger"98    }99100    /// One SF Symbol per star, rounding the value to the nearest half.101    static func stars(value: Double, max: Int) -> [String] {102        let count = Swift.min(Swift.max(max, 1), 10)103        let halves = ((value.isFinite ? value : 0) * 2).rounded() / 2104        return (0..<count).map { i in halves >= Double(i) + 1 ? "star.fill" : halves >= Double(i) + 0.5 ? "star.leadinghalf.filled" : "star" }105    }106107    /// The text of a counter pill: values above `max` read "99+".108    static func counter(_ count: Int, max: Int) -> String { max > 0 && count > max ? "\(max)+" : "\(count)" }109110    /// Where `value` sits between `min` and `max`, clamped to 0…1.111    static func fraction(_ value: Double, min lower: Double, max upper: Double) -> Double {112        guard value.isFinite, upper > lower else { return 0 }113        return Swift.min(Swift.max((value - lower) / (upper - lower), 0), 1)114    }115116    /// The glyph printed on a keycap for a key name such as `cmd`, `shift` or `k`.117    static func keycap(_ key: String) -> String {118        let name = key.trimmingCharacters(in: .whitespaces)119        switch name.lowercased() {120        case "cmd", "command", "⌘": return "⌘"121        case "shift", "⇧": return "⇧"122        case "opt", "option", "alt", "⌥": return "⌥"123        case "ctrl", "control", "⌃": return "⌃"124        case "return", "enter": return "↩"125        case "delete", "backspace": return "⌫"126        case "esc", "escape": return "⎋"127        case "tab": return "⇥"128        case "space": return "Space"129        case "up": return "↑"130        case "down": return "↓"131        case "left": return "←"132        case "right": return "→"133        default: return name.count == 1 ? name.uppercased() : name134        }135    }136137    /// The spoken name of a key, for VoiceOver.138    static func keyName(_ key: String) -> String {139        let cap = keycap(key)140        let names = ["⌘": "Command", "⇧": "Shift", "⌥": "Option", "⌃": "Control", "↩": "Return", "⌫": "Delete", "⎋": "Escape", "⇥": "Tab",141                     "↑": "Up Arrow", "↓": "Down Arrow", "←": "Left Arrow", "→": "Right Arrow"]142        return names[cap] ?? cap143    }144145    /// Inline Markdown (bold, italic, code, links, strikethrough) as attributed text; invalid Markdown is shown as typed.146    static func markdown(_ source: String) -> AttributedString {147        let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)148        return (try? AttributedString(markdown: source, options: options)) ?? AttributedString(source)149    }150}151152/// The only way family A leaves the app: opening a web address in the default browser.153enum FamilyALink {154    /// The URL if it is a plain http or https address with a host and no embedded credentials; nil for anything else.155    static func sanitized(_ raw: String) -> URL? {156        let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)157        guard let parts = URLComponents(string: text), let scheme = parts.scheme?.lowercased(), scheme == "http" || scheme == "https",158              let host = parts.host, !host.isEmpty, parts.user == nil, parts.password == nil else { return nil }159        return parts.url160    }161162    /// Opens an accepted URL and returns true; refuses everything else without calling the opener.163    @MainActor164    @discardableResult165    static func open(_ raw: String, with opener: (URL) -> Bool = { NSWorkspace.shared.open($0) }) -> Bool {166        guard let url = sanitized(raw) else { return false }167        return opener(url)168    }169}170171/// QR code generation with CoreImage.172enum FamilyAQR {173    /// A QR code, or nil when there is nothing to encode: one pixel per module, or each module enlarged to a whole number174    /// of pixels until the side reaches `minimumSide`, so the edges stay sharp at any display size.175    static func image(_ text: String, correction: String = "M", minimumSide: Int = 0) -> CGImage? {176        guard !text.isEmpty, let data = text.data(using: .utf8), let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }177        filter.setValue(data, forKey: "inputMessage")178        filter.setValue(["L", "M", "Q", "H"].contains(correction) ? correction : "M", forKey: "inputCorrectionLevel")179        guard let output = filter.outputImage, !output.extent.isEmpty else { return nil }180        guard let modules = CIContext(options: [.useSoftwareRenderer: true]).createCGImage(output, from: output.extent) else { return nil }181        let factor = min(max(Int((Double(minimumSide) / Double(modules.width)).rounded(.up)), 1), 64)182        guard factor > 1 else { return modules }183        let side = modules.width * factor184        guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return modules }185        context.interpolationQuality = .none186        context.draw(modules, in: CGRect(x: 0, y: 0, width: side, height: side))187        return context.makeImage() ?? modules188    }189}190191/// Date maths of the clock and countdown components.192enum FamilyATime {193    struct Remaining: Equatable {194        var days: Int, hours: Int, minutes: Int, seconds: Int195        var isOver: Bool { days == 0 && hours == 0 && minutes == 0 && seconds == 0 }196    }197198    /// Parses `YYYY-MM-DD` (local midnight), an ISO 8601 datetime with a zone, or `YYYY-MM-DDTHH:MM[:SS]` in local time.199    static func target(_ raw: String, timeZone: TimeZone = .current) -> Date? {200        let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)201        let numbers = text.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) }202        guard text.count >= 10, numbers.count >= 3 else { return nil }203        var calendar = Calendar(identifier: .gregorian)204        calendar.timeZone = timeZone205        if text.count == 10 {206            let parts = text.split(separator: "-", omittingEmptySubsequences: false)207            let day = DateComponents(year: numbers[0], month: numbers[1], day: numbers[2])208            guard parts.count == 3, parts[0].count == 4, day.isValidDate(in: calendar) else { return nil }209            return calendar.date(from: day)210        }211        let iso = ISO8601DateFormatter()212        for options: ISO8601DateFormatter.Options in [[.withInternetDateTime], [.withInternetDateTime, .withFractionalSeconds]] {213            iso.formatOptions = options214            if let date = iso.date(from: text) { return date }215        }216        let separator = text[text.index(text.startIndex, offsetBy: 10)]217        guard separator == "T" || separator == " ", (5...6).contains(numbers.count), text.count <= 19 else { return nil }218        let moment = DateComponents(year: numbers[0], month: numbers[1], day: numbers[2], hour: numbers[3], minute: numbers[4], second: numbers.count > 5 ? numbers[5] : 0)219        guard moment.isValidDate(in: calendar) else { return nil }220        return calendar.date(from: moment)221    }222223    /// Whole days, hours, minutes and seconds left; all zero once the target has passed.224    static func remaining(from now: Date, to target: Date) -> Remaining {225        let total = max(0, Int(target.timeIntervalSince(now).rounded(.up)))226        return Remaining(days: total / 86_400, hours: total % 86_400 / 3_600, minutes: total % 3_600 / 60, seconds: total % 60)227    }228229    /// The clock face text for a format name.230    static func clock(_ date: Date, format: String, timeZone: TimeZone, locale: Locale) -> String {231        let base = Date.FormatStyle(locale: locale, timeZone: timeZone)232        switch format {233        case "time": return date.formatted(base.hour().minute())234        case "date": return date.formatted(base.weekday(.wide).month(.wide).day().year())235        case "dateTime": return date.formatted(base.month(.abbreviated).day().year().hour().minute())236        default: return date.formatted(base.hour().minute().second())237        }238    }239}240
Files main
Menu

Theme