Cotton code
74 lines · 2.7 KB · SwiftRaw
// A count as the core says it (`count.words`,// `crates/cotton-ffi/src/methods/shell_lines.rs`): the number grouped, its// plural form picked by CLDR, said through a line set or a definition's// units. The app never words a count (contract 7: Swift draws).//// The core answers asynchronously and a face asks while it draws, so the// words are held here once said: the first ask sends the call and answers// nil, the answer lands as an observed change and the face draws again. The// held words are let go when the shown database changes or a sync lands,// because the database's `lines` rows may have reworded them.import CottonKitimport Foundation@MainActor@Observablepublic final class CountLines {    public static let shared = CountLines()    @ObservationIgnored private var core: (any CottonCalling)?    private var said: [String: String] = [:]    @ObservationIgnored private var asking: Set<String> = []    /// The core to ask; the words held so far are let go.    public func use(_ core: any CottonCalling) {        self.core = core        said = [:]        asking = []    }    /// The line `line` of `set` filled with the count `n` (and `fills`), the    /// form the count calls for; nil until the core has said it.    public func line(_ set: String, _ line: String, n: Int, fills: [String: String] = [:]) -> String? {        ask(Request(n: n, set: set, line: line, fills: fills.isEmpty ? nil : fills, units: nil))    }    /// The count `n` in a definition's units ("6 orders", "Sold out"); nil    /// until the core has said it.    public func units(_ units: ColumnUnits, n: Int) -> String? {        ask(Request(n: n, set: nil, line: nil, fills: nil, units: units))    }    private func ask(_ request: Request) -> String? {        guard let key = request.key else { return nil }        if let words = said[key] { return words }        guard let core, !asking.contains(key) else { return nil }        asking.insert(key)        Task { [weak self] in            let words = try? await core.call(CottonMethod.countWords, request, as: Said.self).words            guard let self else { return }            self.asking.remove(key)            if let words { self.said[key] = words }        }        return nil    }    struct Request: Encodable, Sendable {        let n: Int        let set: String?        let line: String?        let fills: [String: String]?        let units: ColumnUnits?        var key: String? {            let encoder = JSONEncoder()            encoder.outputFormatting = .sortedKeys            return (try? encoder.encode(self)).map { String(decoding: $0, as: UTF8.self) }        }    }    struct Said: Decodable, Sendable {        let words: String    }}