Cotton code
549 lines · 20.1 KB · SwiftRaw
// THE CORE'S ANSWERS, READ (assets/design/days/CONTRACT.md). Days decides// nothing: each type here is one shape the contract names, read as it comes,// so the screens draw what the core said and nothing they worked out// themselves. The same shapes as Android's `days/book/Answers.kt`.import Foundation/// A row's mark (contract §1): never empty.enum DaysMark: Equatable, Hashable, Sendable {    /// The pen circle to tick, on every to-do.    case tick(done: Bool)    /// A drawn mark from the catalogue, by its id.    case drawn(String)    /// The small quiet dot: a row with no mark.    case dot}/// What tapping a row opens (contract §1 `opens`).enum DaysOpens: Equatable, Hashable, Sendable {    case event(id: String, occurrenceAt: String?)    case todo(id: String)    case person(String)    case nothing}enum DaysWhose: String, Equatable, Sendable {    case yours, google, birthday    init(_ said: String?) { self = DaysWhose(rawValue: said ?? "") ?? .yours }}enum DaysKind: String, Equatable, Sendable {    case event, todo, birthday    init(_ said: String?) { self = DaysKind(rawValue: said ?? "") ?? .event }}/// One row on a day or in Sometime (contract §1).struct DaysRow: Equatable, Hashable, Identifiable, Sendable {    var key: String    var kind: DaysKind    var time: String?    var end: String?    var mark: DaysMark    /// A to-do's drawn mark, beside its tick (the contract's open point): drawn by nothing yet.    var drawnMark: String?    var words: String    var suffix: String?    var done: Bool    var whose: DaysWhose    var opens: DaysOpens    var id: String { key }    static func == (a: DaysRow, b: DaysRow) -> Bool { a.key == b.key && a.done == b.done && a.words == b.words && a.mark == b.mark && a.suffix == b.suffix && a.time == b.time }    func hash(into hasher: inout Hasher) { hasher.combine(key) }    /// The row's table, for `days.done`, `days.move`, `days.change`; none for a birthday.    var table: String? {        switch opens {        case .event: "event"        case .todo: "todo"        default: nil        }    }    /// The row's record id; none for a birthday.    var recordId: String? {        switch opens {        case .event(let id, _): id        case .todo(let id): id        default: nil        }    }    /// Whether its day is the person's to change: their own (a Google event's day is Google's).    var movable: Bool { whose == .yours && recordId != nil }    var occurrenceAt: String? {        if case .event(_, let at) = opens { return at }        return nil    }}/// One entry of `days.span`: a day with its rows, or a run of quiet days folded into one line.enum DaysSpan: Equatable, Identifiable, Sendable {    case day(DaysDay)    case fold(DaysFold)    var id: String {        switch self {        case .day(let day): day.day        case .fold(let fold): "fold:\(fold.from)"        }    }    /// Whether [day] is this entry: its own, or folded into it.    func holds(_ day: String) -> Bool {        switch self {        case .day(let one): one.day == day        case .fold(let fold): day >= fold.from && day <= fold.to        }    }}struct DaysDay: Equatable, Sendable {    var day: String    var number: String    var weekday: String    var month: String    var today: Bool    var rows: [DaysRow]}struct DaysFold: Equatable, Sendable {    var from: String    var to: String    var count: Int    var words: String}/// `days.span`'s answer.struct DaysSpanAnswer: Equatable, Sendable {    var today: String    var days: [DaysSpan]    /// Nothing lies after the last day answered (contract §2, The end): the    /// list's closing line, and no read further ahead.    var end: DaysEnd?    /// Nothing at all lies before this day (contract §2, The beginning): no read further back.    var begins: String?}/// The end of the list (`end`): the last day with a row (or today), and the closing line.struct DaysEnd: Equatable, Sendable {    var after: String    var words: String}/// A to-do the person ticked or unticked since the list was opened (contract/// §2, Keep): it stays on the day its row stood on (nil: Sometime), done or/// not as it now is, until the list is next opened.struct DaysKept: Equatable, Sendable {    var id: String    var day: String?    var done: Bool    /// As `keep` sends it: `{ id, day }`.    var json: [String: Any] { ["id": id, "day": day.map { $0 as Any } ?? NSNull()] }}/// One group of Sometime (contract §5): every to-do of it, no "first few".struct DaysGroup: Equatable, Identifiable, Sendable {    var groupId: String?    var name: String    var count: Int    var rows: [DaysRow]    var id: String { groupId ?? "no-group" }}/// `days.groups` (contract §5b): the filter's choices, same-named groups as one.struct DaysGroups: Equatable, Sendable {    /// The filter's word with no group chosen ("All").    var all: String    /// Every open to-do.    var count: Int    var groups: [DaysGroupCount]}struct DaysGroupCount: Equatable, Identifiable, Sendable {    var id: String    var name: String    var count: Int}/// `days.month` (contract §6).struct DaysMonth: Equatable, Sendable {    var month: String    var title: String    var weekStart: Int    /// Blank cells before the 1st in a week starting on `weekStart` (the core's; nil from an older core).    var lead: Int?    /// Always six.    var weeks: Int = 6    var days: [DaysMonthDay]}struct DaysMonthDay: Equatable, Hashable, Sendable {    var day: String    var marks: [String]    var other: Bool    var today: Bool}/// A stretch of the words read as the day or the time (`said`), for underlining.struct DaysSaid: Equatable, Sendable {    var from: Int    var to: Int    var what: String}/// `days.read_line` (contract §7): what the words say, for the pill.struct DaysReadLine: Equatable, Sendable {    var title: String    var day: String?    var time: String?    var end: String?    var kind: DaysKind    var pill: String?    var marks: [String]    var said: [DaysSaid]    static let empty = DaysReadLine(title: "", day: nil, time: nil, end: nil, kind: .todo, pill: nil, marks: [], said: [])}/// What may be changed on an item's sheet (`canChange`).struct DaysCanChange: Equatable, Sendable {    var title = false, time = false, mark = false, note = false, group = false, alert = false}/// `days.item` (contract §3): the one sheet's facts.struct DaysItem: Equatable, Sendable {    var table: String    var id: String    var whose: DaysWhose    var words: String    var day: String?    var time: String?    var end: String?    var mark: String?    var note: String?    /// A to-do's group (the first that holds it), read through `groups.list`.    var group: String?    /// An event's alert choices (`alerts`), the one that stands `on`; empty for a to-do.    var alerts: [DaysAlertChoice] = []    var done: Bool    var repeats: Bool    var canChange: DaysCanChange    var says: String?    /// The person's to-do groups to choose from on the sheet, in their order.    var groups: [DaysGroupChoice] = []    /// The quick day row (`choices`, contract §3): Today, Tomorrow, Next    /// week, Sometime (a to-do), each labelled by its line key `move.<key>`.    var choices: [DaysDayChoice] = []    /// A timed event's end chips (`ends`, contract §14); nil on an all-day event, a to-do, or a core without them.    var ends: DaysEnds?    /// An event's people (`people`, contract §15); nil on a to-do or a core without them.    var people: DaysPeople?    /// An invitation received (`invitation`, contract §17): who sent it and the three answers.    var invitation: DaysInvitation?    /// Who Delete tells (`deleteTells`, contract §15): "Priya and Akash are told it is off."    var deleteTells: String?}/// An event's alert as the core answers and takes it (contract §3): No alert/// (`"none"`, which never reminds) or minutes before it starts.enum DaysAlert: Hashable, Sendable {    case off    case minutes(Int)    init?(_ value: Any?) {        if let word = value as? String {            guard word == "none" else { return nil }            self = .off        } else if let number = value as? NSNumber {            self = .minutes(number.intValue)        } else {            return nil        }    }    /// As `days.change` takes it.    var json: Any {        switch self {        case .off: return "none"        case .minutes(let n): return n        }    }}/// One alert the sheet offers (`days.item` alerts): the alert, and whether it is the one that stands.struct DaysAlertChoice: Equatable, Sendable {    var alert: DaysAlert    var on: Bool}/// One quick day choice on the sheet: its key and the day it moves to (nil: Sometime).struct DaysDayChoice: Equatable, Sendable {    var key: String    var day: String?}/// A to-do group offered on the sheet (`groups.list`).struct DaysGroupChoice: Equatable, Sendable {    var id: String    var name: String}/// What `days.add` made: its table and id, and the day and time it landed on./// Why Days asks leave to notify, before iOS asks (`leave` beside `request_notifications`; lines `days.json`).struct DaysLeave: Equatable, Sendable, Identifiable {    var title: String?    var body: String    var go: String    var notNow: String?    var id: String { body }}/// The leave asked, held for the screen: the book is made before the screen it speaks to.@MainActor @Observablefinal class DaysLeaveAsking {    var asking: DaysLeave?}struct DaysAdded: Equatable, Sendable {    var table: String    var id: String    var day: String?    var time: String?}/// One mark of the catalogue (`days.marks`): its id, its words per language,/// and its drawing as pen strokes (SVG paths on a 24 by 24 square).struct DaysCatalogueMark: Equatable, Sendable {    var id: String    var words: [String: [String]]    var strokes: [String] = []}/// What `days.change` is given: only the fields that changed; a `nil` inside clears that field.struct DaysChange: Equatable, Sendable {    var title: String??    var day: String??    var time: String??    var mark: String??    var note: String??    var group: String??    /// The alert chosen; the sheet never clears it (`"none"` is No alert).    var alert: DaysAlert?    /// The end as a length after the start, or No end (contract §14).    var length: DaysLength?    /// The end picked as a clock time (contract §14: at or before the start is the next day).    var end: String?    /// The whole new list of people, the chips as they stand (contract §15).    var people: [DaysPerson]?    var isEmpty: Bool {        title == nil && day == nil && time == nil && mark == nil && note == nil && group == nil && alert == nil && length == nil && end == nil            && people == nil    }    /// The fields as the contract sends them, an explicit null where one is cleared.    var json: [String: Any] {        var out: [String: Any] = [:]        func put<T>(_ key: String, _ value: T??) {            guard let value else { return }            out[key] = value.map { $0 as Any } ?? NSNull()        }        put("title", title); put("day", day); put("time", time); put("mark", mark)        put("note", note)        if let alert { out["alert"] = alert.json }        if let length { out["length"] = length.json }        if let end { out["end"] = end }        if let people { out["people"] = people.map(\.json) }        return out    }}/// A row of a view or of search (contract §11, §12): a row with its day.struct DaysListed: Equatable, Identifiable, Sendable {    var row: DaysRow    /// `YYYY-MM-DD`, or nil: no day (Sometime).    var day: String?    /// The day in words ("Sun 25 Oct", "Sometime").    var dayWords: String    /// A repeating item's rhythm in words ("Every Monday"), in Repeating.    var rhythm: String?    var dropped: Bool    /// Where a tap on a search result lands.    var lands: DaysLands?    var id: String { row.key }}/// Where a search result takes the person (contract §12 `lands`).enum DaysLands: Equatable, Sendable {    case days(String)    case sometime    case view(String)}/// `days.show` (contract §11): one of the four views, read a page at a time.struct DaysShown: Equatable, Sendable {    var view: String    var title: String    var rows: [DaysListed]    var empty: String?    /// The cursor for the page after; nil at the end.    var next: String?}/// `days.find` (contract §12): Coming, then Before.struct DaysFound: Equatable, Sendable {    var coming: [DaysListed]    var before: [DaysListed]    /// "Nothing found for “words”.", or nil (nothing typed yet, or something found).    var empty: String?    static let none = DaysFound(coming: [], before: [], empty: nil)}// MARK: - Reading the core's JSON/// The contract's shapes read from a decoded JSON object, as Android reads them.enum DaysRead {    typealias Object = [String: Any]    static func s(_ o: Object, _ key: String) -> String? { o[key] as? String }    static func i(_ o: Object, _ key: String) -> Int? { (o[key] as? NSNumber)?.intValue }    static func b(_ o: Object, _ key: String) -> Bool { (o[key] as? Bool) ?? ((o[key] as? NSNumber)?.boolValue ?? false) }    static func o(_ o: Object, _ key: String) -> Object? { o[key] as? Object }    static func objects(_ o: Object, _ key: String) -> [Object] { (o[key] as? [Any])?.compactMap { $0 as? Object } ?? [] }    static func strings(_ o: Object, _ key: String) -> [String] { (o[key] as? [Any])?.compactMap { $0 as? String } ?? [] }    static func mark(_ m: Object?) -> DaysMark {        switch m.flatMap({ s($0, "kind") }) {        case "tick": .tick(done: b(m!, "done"))        case "drawn": s(m!, "id").map(DaysMark.drawn) ?? .dot        default: .dot        }    }    static func opens(_ x: Object?) -> DaysOpens {        guard let x else { return .nothing }        if let person = s(x, "person") { return .person(person) }        switch s(x, "sheet") {        case "event": return s(x, "id").map { .event(id: $0, occurrenceAt: s(x, "occurrenceAt")) } ?? .nothing        case "todo": return s(x, "id").map { .todo(id: $0) } ?? .nothing        default: return .nothing        }    }    static func row(_ x: Object) -> DaysRow {        DaysRow(            key: s(x, "key") ?? "", kind: DaysKind(s(x, "kind")), time: s(x, "time"), end: s(x, "end"),            mark: mark(o(x, "mark")), drawnMark: s(x, "drawnMark"), words: s(x, "words") ?? "",            suffix: s(x, "suffix"), done: b(x, "done"), whose: DaysWhose(s(x, "whose")), opens: opens(o(x, "opens")))    }    static func span(_ x: Object) -> DaysSpanAnswer {        let days: [DaysSpan] = objects(x, "days").compactMap { entry in            if let fold = o(entry, "fold") {                guard let from = s(fold, "from"), let to = s(fold, "to") else { return nil }                return .fold(DaysFold(from: from, to: to, count: i(fold, "count") ?? 0, words: s(fold, "words") ?? ""))            }            guard let day = s(entry, "day") else { return nil }            return .day(DaysDay(day: day, number: s(entry, "number") ?? "", weekday: s(entry, "weekday") ?? "",                                month: s(entry, "month") ?? "", today: b(entry, "today"), rows: objects(entry, "rows").map(row)))        }        let end = o(x, "end").flatMap { e in s(e, "after").map { DaysEnd(after: $0, words: s(e, "words") ?? "") } }        return DaysSpanAnswer(today: s(x, "today") ?? "", days: days, end: end, begins: s(x, "begins"))    }    /// The groups in the core's order: the answer itself a list, or under `groups`.    static func groups(_ any: Any) -> [DaysGroup] {        let list = (any as? [Any]) ?? ((any as? Object)?["groups"] as? [Any]) ?? []        return list.compactMap { $0 as? Object }.map { g in            DaysGroup(groupId: s(g, "id"), name: s(g, "name") ?? "", count: i(g, "count") ?? 0,                      rows: objects(g, "rows").map(row))        }    }    static func groupCounts(_ x: Object) -> DaysGroups {        DaysGroups(all: s(x, "all") ?? "", count: i(x, "count") ?? 0,                   groups: objects(x, "groups").compactMap { g in                       guard let id = s(g, "id") else { return nil }                       return DaysGroupCount(id: id, name: s(g, "name") ?? "", count: i(g, "count") ?? 0)                   })    }    static func month(_ x: Object) -> DaysMonth {        DaysMonth(month: s(x, "month") ?? "", title: s(x, "title") ?? "", weekStart: i(x, "weekStart") ?? 1,                  lead: i(x, "lead"), weeks: i(x, "weeks") ?? 6,                  days: objects(x, "days").map { DaysMonthDay(day: s($0, "day") ?? "", marks: strings($0, "marks"), other: b($0, "other"), today: b($0, "today")) })    }    static func readLine(_ x: Object) -> DaysReadLine {        DaysReadLine(            title: s(x, "title") ?? "", day: s(x, "day"), time: s(x, "time"), end: s(x, "end"), kind: DaysKind(s(x, "kind")),            pill: s(x, "pill"), marks: strings(x, "marks"),            said: objects(x, "said").compactMap { one in                guard let from = i(one, "from"), let to = i(one, "to") else { return nil }                return DaysSaid(from: from, to: to, what: s(one, "what") ?? "")            })    }    static func item(table: String, id: String, _ x: Object) -> DaysItem {        let can = o(x, "canChange") ?? [:]        return DaysItem(            table: table, id: id, whose: DaysWhose(s(x, "whose")), words: s(x, "words") ?? "",            day: s(x, "day"), time: s(x, "time"), end: s(x, "end"), mark: s(x, "mark"), note: s(x, "note"),            // `group` is `{ id, name }` (an older core answered the id alone).            group: s(x, "group") ?? o(x, "group").flatMap { s($0, "id") },            alerts: objects(x, "alerts").compactMap { c in DaysAlert(c["alert"]).map { DaysAlertChoice(alert: $0, on: b(c, "on")) } },            done: b(x, "done"), repeats: b(x, "repeats"),            // A to-do's group is changed through `groups.*` until `days.change` takes it (CONTRACT §3).            canChange: DaysCanChange(title: b(can, "title"), time: b(can, "time"), mark: b(can, "mark"),                                     note: b(can, "note"), group: table == "todo", alert: b(can, "alert")),            says: s(x, "says"),            choices: objects(x, "choices").compactMap { c in s(c, "key").map { DaysDayChoice(key: $0, day: s(c, "day")) } },            ends: ends(o(x, "ends")), people: people(o(x, "people")),            invitation: invitation(o(x, "invitation")), deleteTells: s(x, "deleteTells"))    }    static func added(_ x: Object) -> DaysAdded? {        guard let table = s(x, "table"), let id = s(x, "id") else { return nil }        return DaysAdded(table: table, id: id, day: s(x, "day"), time: s(x, "time"))    }    static func listed(_ x: Object) -> DaysListed {        var lands: DaysLands?        if let l = o(x, "lands") {            switch s(l, "place") {            case "days": lands = s(l, "day").map(DaysLands.days)            case "sometime": lands = .sometime            case "show": lands = s(l, "view").map(DaysLands.view)            default: lands = nil            }        }        return DaysListed(row: row(x), day: s(x, "day"), dayWords: s(x, "dayWords") ?? "", rhythm: s(x, "rhythm"),                          dropped: b(x, "dropped"), lands: lands)    }    static func shown(_ x: Object) -> DaysShown {        DaysShown(view: s(x, "view") ?? "", title: s(x, "title") ?? "", rows: objects(x, "rows").map(listed),                  empty: s(x, "empty"), next: s(x, "next"))    }    static func found(_ x: Object) -> DaysFound {        DaysFound(coming: objects(x, "coming").map(listed), before: objects(x, "before").map(listed), empty: s(x, "empty"))    }    static func catalogue(_ any: Any) -> [DaysCatalogueMark] {        let list = (any as? [Any]) ?? ((any as? Object)?["marks"] as? [Any]) ?? []        return list.compactMap { $0 as? Object }.compactMap { m in            guard let id = s(m, "id") else { return nil }            let words = (o(m, "words") ?? [:]).mapValues { ($0 as? [Any])?.compactMap { $0 as? String } ?? [] }            return DaysCatalogueMark(id: id, words: words, strokes: strings(m, "strokes"))        }    }}