SPB Git

Repository Public License

Components+FamilyBLogic.swift 26.4 KB 608 lines swift

1import Foundation2import PrismCore3import PrismLogicRuntime4import PrismObjectModel56// The window-free logic of catalog family B. Everything here is a plain value or a pure function so the tests can drive it.78extension JSONValue {9    /// A number stored as an integer when it has no fractional part.10    static func fbNumber(_ d: Double) -> JSONValue {11        guard d.isFinite else { return .int(0) }12        return d.rounded() == d && abs(d) < 9e15 ? .int(Int(d)) : .double(d)13    }14}1516/// Bounds and step of a numeric control.17struct FBBounds: Equatable, Sendable {18    var lo: Double19    var hi: Double20    var step: Double2122    /// Reads `min` / `max` / `step`, repairing a range that is empty or reversed.23    init(_ props: [String: JSONValue], lo: Double = 0, hi: Double = 100, step: Double = 1) {24        let l = props["min"]?.doubleValue ?? lo25        let h = props["max"]?.doubleValue ?? hi26        let s = props["step"]?.doubleValue ?? step27        self.init(lo: l, hi: h, step: s)28    }2930    init(lo: Double, hi: Double, step: Double) {31        self.lo = lo.isFinite ? lo : 032        self.hi = hi.isFinite && hi > self.lo ? hi : self.lo + 133        self.step = step.isFinite && step > 0 ? min(step, self.hi - self.lo) : 134    }3536    func clamp(_ v: Double) -> Double { Swift.min(Swift.max(v.isFinite ? v : lo, lo), hi) }3738    /// The nearest step from `lo`, inside the bounds, without binary noise such as 0.30000000000000004.39    func snap(_ v: Double) -> Double {40        let snapped = lo + ((clamp(v) - lo) / step).rounded() * step41        return clamp((snapped * 1e9).rounded() / 1e9)42    }4344    func fraction(_ v: Double) -> Double { (clamp(v) - lo) / (hi - lo) }45    func value(fraction f: Double) -> Double { snap(lo + Swift.min(Swift.max(f, 0), 1) * (hi - lo)) }46}4748enum FBValidate {49    /// One `@`, a local part without spaces, and a dotted domain ending in two or more letters.50    static func email(_ raw: String) -> Bool {51        let s = raw.trimmingCharacters(in: .whitespaces)52        let parts = s.split(separator: "@", omittingEmptySubsequences: false)53        guard parts.count == 2, !parts[0].isEmpty, s.count <= 254, !s.contains(where: { $0.isWhitespace }) else { return false }54        let local = parts[0], domain = parts[1]55        guard !local.hasPrefix("."), !local.hasSuffix("."), !local.contains("..") else { return false }56        let labels = domain.split(separator: ".", omittingEmptySubsequences: false)57        guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty && !$0.hasPrefix("-") && !$0.hasSuffix("-") && $0.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" } }) else { return false }58        guard let tld = labels.last, tld.count >= 2, tld.allSatisfy(\.isLetter) else { return false }59        return true60    }6162    /// The URL if the text is an absolute http or https address with a host; nothing else is ever opened.63    static func webURL(_ raw: String) -> URL? {64        let s = raw.trimmingCharacters(in: .whitespacesAndNewlines)65        guard !s.isEmpty, !s.contains(where: { $0.isWhitespace }), let c = URLComponents(string: s), let scheme = c.scheme?.lowercased(),66              scheme == "http" || scheme == "https", let host = c.host, !host.isEmpty, c.user == nil, c.password == nil else { return nil }67        return c.url68    }6970    /// A web address a person would accept: http(s) and a dotted host (or localhost).71    static func url(_ raw: String) -> Bool {72        guard let host = webURL(raw)?.host else { return false }73        return host == "localhost" || (host.contains(".") && !host.hasPrefix(".") && !host.hasSuffix("."))74    }7576    /// 7 to 15 digits, with an optional leading `+` and the usual separators.77    static func phone(_ raw: String) -> Bool {78        let s = raw.trimmingCharacters(in: .whitespaces)79        guard !s.isEmpty else { return false }80        let body = s.hasPrefix("+") ? s.dropFirst() : Substring(s)81        guard body.allSatisfy({ $0.isASCII && ($0.isNumber || " -.()".contains($0)) }) else { return false }82        let digits = body.filter(\.isNumber).count83        return (7...15).contains(digits)84    }8586    /// A plain decimal number; accepts a comma as the decimal separator.87    static func number(_ raw: String) -> Double? {88        let s = raw.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")89        guard !s.isEmpty, s.allSatisfy({ $0.isASCII && ($0.isNumber || $0 == "." || $0 == "-" || $0 == "+") }), let d = Double(s), d.isFinite else { return nil }90        return d91    }9293    /// A percentage inside the bounds; a trailing `%` is tolerated.94    static func percent(_ raw: String, min lo: Double = 0, max hi: Double = 100) -> Double? {95        var s = raw.trimmingCharacters(in: .whitespaces)96        if s.hasSuffix("%") { s = String(s.dropLast()) }97        guard let d = number(s), d >= lo, d <= hi else { return nil }98        return d99    }100101    enum Kind: String, Sendable { case email, url, phone }102103    /// The inline message for a malformed value; nil while the field is empty or valid.104    static func message(_ kind: Kind, _ text: String) -> String? {105        guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }106        switch kind {107        case .email: return email(text) ? nil : "Enter an email address like name@example.com."108        case .url: return url(text) ? nil : "Enter a web address starting with http:// or https://."109        case .phone: return phone(text) ? nil : "Enter a phone number with 7 to 15 digits."110        }111    }112}113114enum FBTime {115    /// `MM:SS`, or `H:MM:SS` from one hour.116    static func clock(_ seconds: Int) -> String {117        let s = max(seconds, 0)118        return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s % 3600 / 60, s % 60) : String(format: "%02d:%02d", s / 60, s % 60)119    }120121    /// Stopwatch reading with tenths: `MM:SS.t`.122    static func stopwatch(_ elapsed: Double) -> String {123        let tenths = Int((max(elapsed, 0) * 10).rounded(.down))124        return clock(tenths / 10) + "." + String(tenths % 10)125    }126127    static func hhmm(hour: Int, minute: Int) -> String { String(format: "%02d:%02d", min(max(hour, 0), 23), min(max(minute, 0), 59)) }128129    static func parseHHmm(_ text: String) -> (hour: Int, minute: Int)? {130        let parts = text.trimmingCharacters(in: .whitespaces).split(separator: ":")131        guard parts.count >= 2, let h = Int(parts[0]), let m = Int(parts[1]), (0...23).contains(h), (0...59).contains(m) else { return nil }132        return (h, m)133    }134}135136enum FBColor {137    static func hex(red: Double, green: Double, blue: Double) -> String {138        func c(_ v: Double) -> Int { Int((min(max(v, 0), 1) * 255).rounded()) }139        return String(format: "#%02X%02X%02X", c(red), c(green), c(blue))140    }141142    /// `#RRGGBB` in upper case, or nil when the text is not a six-digit hex color.143    static func normalized(_ raw: String) -> String? {144        let s = raw.trimmingCharacters(in: .whitespaces)145        let body = s.hasPrefix("#") ? String(s.dropFirst()) : s146        guard body.count == 6, body.allSatisfy(\.isHexDigit) else { return nil }147        return "#" + body.uppercased()148    }149150    static let presets = ["#FF3B30", "#FF9500", "#FFCC00", "#34C759", "#00C7BE", "#007AFF", "#5856D6", "#AF52DE", "#FF2D55", "#8E8E93", "#1C1C1E", "#FFFFFF"]151}152153enum FBPin {154    /// Keeps the first `length` digits of whatever was typed or pasted.155    static func sanitize(_ raw: String, length: Int) -> String { String(raw.filter { $0.isASCII && $0.isNumber }.prefix(max(length, 1))) }156    static func isComplete(_ value: String, length: Int) -> Bool { value.count == max(length, 1) && value.allSatisfy { $0.isASCII && $0.isNumber } }157}158159enum FBTags {160    /// The list with the tag added, or nil when it is empty or already present (case-insensitive).161    static func adding(_ raw: String, to tags: [String]) -> [String]? {162        let tag = raw.trimmingCharacters(in: .whitespacesAndNewlines)163        guard !tag.isEmpty, !tags.contains(where: { $0.caseInsensitiveCompare(tag) == .orderedSame }) else { return nil }164        return tags + [tag]165    }166167    static func toggling(_ option: String, in selected: [String], order: [String]) -> [String] {168        var out = selected169        if let i = out.firstIndex(of: option) { out.remove(at: i) } else { out.append(option) }170        // Keep the options' own order so the stored list is stable whatever the click order.171        return out.sorted { (order.firstIndex(of: $0) ?? .max) < (order.firstIndex(of: $1) ?? .max) }172    }173}174175enum FBSuggest {176    /// Options matching the text: prefix matches first, then substring matches; an exact match needs no suggestion.177    static func filter(_ options: [String], text: String, limit: Int = 6) -> [String] {178        let q = text.trimmingCharacters(in: .whitespaces).lowercased()179        guard !q.isEmpty else { return [] }180        let candidates = options.filter { $0.lowercased() != q }181        let prefix = candidates.filter { $0.lowercased().hasPrefix(q) }182        let inside = candidates.filter { !$0.lowercased().hasPrefix(q) && $0.lowercased().contains(q) }183        return Array((prefix + inside).prefix(max(limit, 1)))184    }185186    /// Recent terms with the new one first, without duplicates, capped.187    static func remember(_ term: String, in recent: [String], max cap: Int = 5) -> [String] {188        let t = term.trimmingCharacters(in: .whitespaces)189        guard !t.isEmpty else { return recent }190        return Array(([t] + recent.filter { $0.caseInsensitiveCompare(t) != .orderedSame }).prefix(max(cap, 1)))191    }192193    /// Items whose title contains every word of the query.194    static func commands(_ items: [JSONValue], query: String) -> [JSONValue] {195        let words = query.lowercased().split(whereSeparator: \.isWhitespace)196        guard !words.isEmpty else { return items }197        return items.filter { item in198            let title = (item["title"]?.stringValue ?? "").lowercased()199            return words.allSatisfy { title.contains($0) }200        }201    }202}203204enum FBKeypad {205    static let keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", "⌫"]206207    /// The text after a key press. Keys: digits, `.`, `⌫` (delete) and `C` (clear).208    static func press(_ text: String, key: String, decimal: Bool = true, maxLength: Int = 12) -> String {209        switch key {210        case "C": return ""211        case "⌫": return String(text.dropLast())212        case ".":213            guard decimal, !text.contains("."), text.count < maxLength else { return text }214            return text.isEmpty ? "0." : text + "."215        default:216            guard key.count == 1, let c = key.first, c.isASCII, c.isNumber, text.count < maxLength else { return text }217            return text == "0" ? key : text + key218        }219    }220}221222enum FBDial {223    /// The knob sweeps 270°, from 135° (bottom left) clockwise to 405° (bottom right), in screen coordinates.224    static let startAngle = 135.0225    static let sweep = 270.0226227    /// Fraction of the sweep for a point relative to the knob's centre.228    static func fraction(dx: Double, dy: Double) -> Double {229        var angle = atan2(dy, dx) * 180 / .pi230        if angle < 0 { angle += 360 }231        var along = angle - startAngle232        if along < 0 { along += 360 }233        // The 90° gap at the bottom snaps to the nearest end.234        if along > sweep { return along - sweep < (360 - sweep) / 2 ? 1 : 0 }235        return along / sweep236    }237}238239/// A four-function calculator, key by key.240struct CalculatorEngine: Equatable, Sendable {241    private(set) var display = "0"242    private(set) var isError = false243    private var accumulator: Double?244    private var pending: String?245    private var typing = false246247    static let keys = ["C", "±", "%", "÷", "7", "8", "9", "×", "4", "5", "6", "−", "1", "2", "3", "+", "0", ".", "⌫", "="]248249    var value: Double { Double(display) ?? 0 }250    /// The operator waiting for its second operand, for the display.251    var pendingOperator: String? { pending }252253    static func format(_ v: Double) -> String {254        guard v.isFinite else { return "Error" }255        if v.rounded() == v && abs(v) < 1e15 { return String(Int(v)) }256        return String(format: "%.10g", v)257    }258259    private static func apply(_ op: String, _ a: Double, _ b: Double) -> Double? {260        switch op {261        case "+": a + b262        case "−", "-": a - b263        case "×", "*": a * b264        case "÷", "/": b == 0 ? nil : a / b265        default: nil266        }267    }268269    private mutating func show(_ result: Double?) {270        if let result, result.isFinite { display = Self.format(result) } else {271            display = "Error"; isError = true; accumulator = nil; pending = nil272        }273        typing = false274    }275276    mutating func press(_ key: String) {277        if key == "C" { self = CalculatorEngine(); return }278        if isError { self = CalculatorEngine() }279        switch key {280        case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":281            if !typing { display = key; typing = true } else if display == "0" { display = key } else if display.count < 15 { display += key }282        case ".":283            if !typing { display = "0."; typing = true } else if !display.contains(".") { display += "." }284        case "+", "−", "-", "×", "*", "÷", "/":285            if let a = accumulator, let op = pending, typing {286                show(Self.apply(op, a, value))287                if isError { return }288            }289            accumulator = value; pending = key; typing = false290        case "=":291            guard let a = accumulator, let op = pending else { typing = false; return }292            show(Self.apply(op, a, value))293            accumulator = nil; pending = nil294        case "±": if value != 0 { display = display.hasPrefix("-") ? String(display.dropFirst()) : "-" + display }295        case "%": show(value / 100)296        case "⌫":297            guard typing else { return }298            display = String(display.dropLast())299            if display.isEmpty || display == "-" { display = "0" }300        default: break301        }302    }303304    /// Presses each key in turn; handy for tests and for pasted input.305    mutating func press(keys: [String]) { for k in keys { press(k) } }306}307308struct StopwatchState: Equatable, Sendable {309    private(set) var accumulated: Double = 0310    private(set) var startedAt: Date?311312    var isRunning: Bool { startedAt != nil }313    func elapsed(at now: Date) -> Double { accumulated + (startedAt.map { max(now.timeIntervalSince($0), 0) } ?? 0) }314    mutating func start(at now: Date) { if startedAt == nil { startedAt = now } }315    mutating func stop(at now: Date) { accumulated = elapsed(at: now); startedAt = nil }316    mutating func reset() { accumulated = 0; startedAt = nil }317}318319struct CountdownState: Equatable, Sendable {320    private(set) var duration: Int321    private(set) var remaining: Int322323    init(duration: Int) {324        self.duration = min(max(duration, 1), 359_999)325        remaining = self.duration326    }327328    var fraction: Double { Double(remaining) / Double(duration) }329    var isFinished: Bool { remaining == 0 }330331    /// Counts down; returns true on the tick that reaches zero.332    mutating func tick(_ seconds: Int = 1) -> Bool {333        guard remaining > 0, seconds > 0 else { return false }334        remaining = max(remaining - seconds, 0)335        return remaining == 0336    }337338    mutating func reset() { remaining = duration }339    mutating func setDuration(_ seconds: Int) { self = CountdownState(duration: seconds) }340}341342/// Work / break cycles: a long break after every `cyclesBeforeLongBreak` work sessions.343struct PomodoroMachine: Equatable, Sendable {344    enum Phase: String, Sendable { case work, shortBreak, longBreak }345346    let work: Int347    let shortBreak: Int348    let longBreak: Int349    let cyclesBeforeLongBreak: Int350    private(set) var phase = Phase.work351    private(set) var remaining: Int352    private(set) var completedCycles = 0353354    /// Durations are in seconds.355    init(work: Int = 1500, shortBreak: Int = 300, longBreak: Int = 900, cyclesBeforeLongBreak: Int = 4) {356        self.work = max(work, 1); self.shortBreak = max(shortBreak, 1); self.longBreak = max(longBreak, 1)357        self.cyclesBeforeLongBreak = max(cyclesBeforeLongBreak, 1)358        remaining = self.work359    }360361    func duration(of phase: Phase) -> Int {362        switch phase { case .work: work; case .shortBreak: shortBreak; case .longBreak: longBreak }363    }364365    var fraction: Double { Double(remaining) / Double(duration(of: phase)) }366367    private mutating func finishPhase() -> Bool {368        let finishedWork = phase == .work369        if finishedWork {370            completedCycles += 1371            phase = completedCycles % cyclesBeforeLongBreak == 0 ? .longBreak : .shortBreak372        } else {373            phase = .work374        }375        remaining = duration(of: phase)376        return finishedWork377    }378379    /// Advances the clock; returns how many work sessions finished during these seconds.380    mutating func tick(_ seconds: Int = 1) -> Int {381        var left = max(seconds, 0), finished = 0382        while left > 0 {383            let step = min(left, remaining)384            remaining -= step; left -= step385            if remaining == 0, finishPhase() { finished += 1 }386        }387        return finished388    }389390    /// Ends the current phase now; returns true when it was a work session.391    mutating func skip() -> Bool { finishPhase() }392393    mutating func reset() { self = PomodoroMachine(work: work, shortBreak: shortBreak, longBreak: longBreak, cyclesBeforeLongBreak: cyclesBeforeLongBreak) }394}395396/// Calendar-day arithmetic on ISO `YYYY-MM-DD` strings, independent of the time zone.397enum FBDay {398    private static var utc: Calendar {399        var cal = Calendar(identifier: .gregorian)400        cal.timeZone = TimeZone(identifier: "UTC")!401        return cal402    }403404    static func iso(year: Int, month: Int, day: Int) -> String { String(format: "%04d-%02d-%02d", year, month, day) }405406    /// The first ten characters when they are a real date.407    static func normalized(_ text: String) -> String? {408        let s = String(text.prefix(10))409        return s.count == 10 && DateCoding.date(from: s) != nil ? s : nil410    }411412    static func parts(_ iso: String) -> (year: Int, month: Int, day: Int)? {413        guard let s = normalized(iso) else { return nil }414        let p = s.split(separator: "-").compactMap { Int($0) }415        return p.count == 3 ? (p[0], p[1], p[2]) : nil416    }417418    static func adding(_ days: Int, to iso: String) -> String {419        guard let date = DateCoding.date(from: iso), let moved = utc.date(byAdding: .day, value: days, to: date) else { return iso }420        return DateCoding.string(from: moved, timeZone: TimeZone(identifier: "UTC")!)421    }422423    /// 1 = Sunday … 7 = Saturday.424    static func weekday(_ iso: String) -> Int { DateCoding.date(from: iso).map { utc.component(.weekday, from: $0) } ?? 1 }425426    /// The first day of the week containing the date.427    static func weekStart(_ iso: String, firstWeekday: Int = 1) -> String {428        adding(-((weekday(iso) - firstWeekday + 7) % 7), to: iso)429    }430431    static func daysInMonth(year: Int, month: Int) -> Int {432        guard let date = utc.date(from: DateComponents(year: year, month: month, day: 1)) else { return 30 }433        return utc.range(of: .day, in: .month, for: date)?.count ?? 30434    }435436    static func shiftMonth(year: Int, month: Int, by delta: Int) -> (year: Int, month: Int) {437        let index = year * 12 + (month - 1) + delta438        return (Int((Double(index) / 12).rounded(.down)), ((index % 12) + 12) % 12 + 1)439    }440}441442/// The cells of a month view: leading blanks, the days, trailing blanks up to whole weeks.443struct MonthGrid: Equatable, Sendable {444    let year: Int445    let month: Int446    let cells: [Int?]447448    init(year: Int, month: Int, firstWeekday: Int = 1) {449        self.year = year; self.month = min(max(month, 1), 12)450        let lead = (FBDay.weekday(FBDay.iso(year: year, month: self.month, day: 1)) - firstWeekday + 7) % 7451        var cells: [Int?] = Array(repeating: nil, count: lead) + (1...FBDay.daysInMonth(year: year, month: self.month)).map { Optional($0) }452        while cells.count % 7 != 0 { cells.append(nil) }453        self.cells = cells454    }455456    var weeks: Int { cells.count / 7 }457    func iso(_ day: Int) -> String { FBDay.iso(year: year, month: month, day: day) }458}459460enum FBRecords {461    /// Rows grouped by the calendar day found in a column; rows without a valid date are left out.462    static func byDay(_ rows: [[String: JSONValue]], column: String) -> [String: [[String: JSONValue]]] {463        var out: [String: [[String: JSONValue]]] = [:]464        for row in rows { if let day = FBDay.normalized(row[column]?.displayString ?? "") { out[day, default: []].append(row) } }465        return out466    }467468    struct Day: Equatable, Sendable {469        var day: String470        var rows: [[String: JSONValue]]471    }472473    /// Agenda order: today and later, soonest first; then, if asked, past days, most recent first.474    static func agenda(_ rows: [[String: JSONValue]], column: String, today: String, includePast: Bool, limit: Int = 50) -> [Day] {475        let groups = byDay(rows, column: column)476        let upcoming = groups.keys.filter { $0 >= today }.sorted()477        let past = includePast ? groups.keys.filter { $0 < today }.sorted(by: >) : []478        var out: [Day] = [], left = max(limit, 1)479        for day in upcoming + past where left > 0 {480            let rows = Array((groups[day] ?? []).prefix(left))481            left -= rows.count482            out.append(Day(day: day, rows: rows))483        }484        return out485    }486487    /// Kanban columns: the preferred order first, then every other value found, with a blank column last when needed.488    static func columns(preferred: [String], values: [String]) -> [String] {489        var seen = Set<String>(), out: [String] = []490        for v in preferred + values.filter({ !$0.isEmpty }) where seen.insert(v).inserted { out.append(v) }491        if values.contains("") && !seen.contains("") { out.append("") }492        return out493    }494495    static func grouped(_ rows: [[String: JSONValue]], by column: String) -> [String: [[String: JSONValue]]] {496        Dictionary(grouping: rows) { $0[column]?.displayString ?? "" }497    }498499    /// How many rows fall on each day.500    static func counts(_ rows: [[String: JSONValue]], column: String) -> [String: Int] { byDay(rows, column: column).mapValues(\.count) }501502    /// 0 (none) to 4 (the busiest), for the heat grid.503    static func level(_ count: Int, max top: Int) -> Int {504        guard count > 0, top > 0 else { return 0 }505        return min(max(Int((Double(count) / Double(top) * 4).rounded(.up)), 1), 4)506    }507508    /// Week columns ending with the week of `end`; days after `end` are nil.509    static func heatWeeks(end: String, weeks: Int, firstWeekday: Int = 1) -> [[String?]] {510        let count = min(max(weeks, 1), 53)511        let lastStart = FBDay.weekStart(end, firstWeekday: firstWeekday)512        return (0..<count).map { w in513            let start = FBDay.adding(-7 * (count - 1 - w), to: lastStart)514            return (0..<7).map { d in515                let day = FBDay.adding(d, to: start)516                return day <= end ? day : nil517            }518        }519    }520}521522struct TreeRow: Equatable, Identifiable, Sendable {523    var id: String524    var title: String525    var icon: String?526    var depth: Int527    var hasChildren: Bool528}529530enum FBTree {531    /// The visible rows of an outline, depth first; children of collapsed nodes are skipped.532    static func flatten(_ items: [JSONValue], expanded: Set<String>, depth: Int = 0, path: String = "") -> [TreeRow] {533        guard depth < 12 else { return [] }534        var out: [TreeRow] = []535        for (index, item) in items.enumerated() {536            let id = item["id"]?.displayString.isEmpty == false ? item["id"]!.displayString : path + String(index)537            let children = item["children"]?.arrayValue ?? []538            out.append(TreeRow(id: id, title: item["title"]?.displayString ?? id, icon: item["icon"]?.stringValue, depth: depth, hasChildren: !children.isEmpty))539            if !children.isEmpty && expanded.contains(id) { out += flatten(children, expanded: expanded, depth: depth + 1, path: id + ".") }540        }541        return out542    }543544    /// Ids of every node that has children.545    static func parents(_ items: [JSONValue], depth: Int = 0, path: String = "") -> Set<String> {546        guard depth < 12 else { return [] }547        var out = Set<String>()548        for (index, item) in items.enumerated() {549            let children = item["children"]?.arrayValue ?? []550            guard !children.isEmpty else { continue }551            let id = item["id"]?.displayString.isEmpty == false ? item["id"]!.displayString : path + String(index)552            out.insert(id)553            out.formUnion(parents(children, depth: depth + 1, path: id + "."))554        }555        return out556    }557}558559enum FBPagination {560    /// Page numbers to show around the current page; nil marks a gap.561    static func window(page: Int, count: Int, radius: Int = 1) -> [Int?] {562        let total = max(count, 1), current = min(max(page, 1), total)563        guard total > 5 + radius * 2 else { return (1...total).map { Optional($0) } }564        var out: [Int?] = [1]565        let lo = max(current - radius, 2), hi = min(current + radius, total - 1)566        if lo > 2 { out.append(nil) }567        out += (lo...hi).map { Optional($0) }568        if hi < total - 1 { out.append(nil) }569        out.append(total)570        return out571    }572573    static func clamp(_ page: Int, count: Int) -> Int { min(max(page, 1), max(count, 1)) }574}575576enum FBDrawing {577    /// Strokes as stored in state: a list of strokes, each a list of `[x, y]` points.578    static func decode(_ value: JSONValue) -> [[CGPoint]] {579        (value.arrayValue ?? []).map { stroke in580            (stroke.arrayValue ?? []).compactMap { p in581                guard let x = p[0]?.doubleValue, let y = p[1]?.doubleValue else { return nil }582                return CGPoint(x: x, y: y)583            }584        }585    }586587    static func encode(_ strokes: [[CGPoint]]) -> JSONValue {588        .array(strokes.map { stroke in .array(stroke.map { .array([.fbNumber(round1($0.x)), .fbNumber(round1($0.y))]) }) })589    }590591    static func round1(_ v: CGFloat) -> Double { (Double(v) * 10).rounded() / 10 }592593    /// Drops points closer than `tolerance` to the previous kept one, so a slow drag does not flood the state.594    static func thinned(_ points: [CGPoint], tolerance: CGFloat = 1.5) -> [CGPoint] {595        var out: [CGPoint] = []596        for p in points {597            if let last = out.last, abs(last.x - p.x) < tolerance, abs(last.y - p.y) < tolerance { continue }598            out.append(p)599        }600        if let last = points.last, out.last != last { out.append(last) }601        return out602    }603}604605enum FBWizard {606    static func clamp(_ step: Int, count: Int) -> Int { min(max(step, 0), max(count - 1, 0)) }607}608
Files main
Menu

Theme