Cotton code
509 lines · 19.7 KB · SwiftRaw
// Where Days stands (Android's `DaysState`): the place, what is over it, the// span of days read, Sometime's groups and which are open. Everything here// is what the book answered; nothing is worked out on the phone beyond which// span to ask for.//// THE BOOK: the core's `days.*` (CoreDaysBook), every method `[new]` since// days-core's f2f420f65. No made-up days stand in the app.#if os(iOS)import CottonKitimport Foundationimport Observationextension DaysSpan {    /// This entry's rows as the model draws them (ticks kept).    @MainActor func drawn(by model: DaysModel) -> DaysSpan {        guard case .day(var d) = self else { return self }        d.rows = d.rows.map(model.drawn)        return .day(d)    }    /// A to-do's tick put back as the core holds it (a refused write).    func undrawn(_ id: String, done: Bool) -> DaysSpan {        guard case .day(var d) = self else { return self }        d.rows = d.rows.map { $0.recordId == id && $0.kind == .todo ? $0.ticked(done) : $0 }        return .day(d)    }}extension DaysGroup {    @MainActor func drawn(by model: DaysModel) -> DaysGroup {        var g = self        g.rows = rows.map(model.drawn)        return g    }    func undrawn(_ id: String, done: Bool) -> DaysGroup {        var g = self        g.rows = rows.map { $0.recordId == id && $0.kind == .todo ? $0.ticked(done) : $0 }        return g    }}extension DaysRow {    func ticked(_ done: Bool) -> DaysRow {        var out = self        out.done = done        out.mark = .tick(done: done)        return out    }}/// The two places (DECISIONS: Days and Sometime, nothing else).enum DaysPlace: String, CaseIterable { case days, sometime }/// What stands over Days: one sheet at a time.enum DaysSheet: Identifiable {    /// The month, for jumping to a day (`pick`: choosing a day for something instead).    case jump(month: String, pick: ((String) -> Void)?)    /// The one sheet to change an item.    case change(DaysRow)    /// When: the pill's day and time set by hand while adding.    case when(DaysPillPick, set: (DaysPillPick) -> Void)    /// The filter's groups: All, or one group.    case groups    var id: String {        switch self {        case .jump(let month, let pick): "jump-\(month)-\(pick == nil ? "go" : "pick")"        case .change(let row): "change-\(row.key)"        case .when: "when"        case .groups: "groups"        }    }}/// What settings hold (DECISIONS: which Google calendars, alert timing, week/// start, account), kept on this phone until the contract names a settings/// method (QUESTIONS.md), as Android keeps them.struct DaysSettings: Equatable {    /// The Google calendars connected, by name (none read yet).    var calendars: [String] = []    /// The calendars the person hid from Days.    var hidden: Set<String> = []    var alert = 10    var weekStart = 1    private static var store: UserDefaults { .standard }    static func kept() -> DaysSettings {        var s = DaysSettings()        if store.object(forKey: "days.alert") != nil { s.alert = store.integer(forKey: "days.alert") }        if store.object(forKey: "days.weekStart") != nil { s.weekStart = store.integer(forKey: "days.weekStart") }        s.hidden = Set(store.stringArray(forKey: "days.hidden") ?? [])        return s    }    func keep() {        Self.store.set(alert, forKey: "days.alert")        Self.store.set(weekStart, forKey: "days.weekStart")        Self.store.set(Array(hidden).sorted(), forKey: "days.hidden")    }}@MainActor @Observablefinal class DaysModel {    static let past = 28    static let ahead = 56    /// The first read when the app opens: today and the two weeks after it,    /// one call from the phone's own copy, so today stands at once; the rest    /// of the span follows.    static let opening = 13    /// Sometime lists every to-do (DECISIONS: no "first few", no "N more"):    /// the core is asked for all of them.    static let first = 100_000    var place: DaysPlace = .days    var sheet: DaysSheet?    var settingsOpen = false    var adding = false    /// Search stands over Days (DECISIONS: the one other screen).    var finding = false    /// A row just landed on from search, marked a moment.    var marked: String?    /// Google Calendar as the core says it (`days.google`, CONTRACT §13); nil until it answers.    var google: DaysGoogle?    /// Connect tapped: its notice stands before Google's page (GOOGLE.md §4).    var noticing: DaysGoogle.Connect?    /// Disconnect tapped: it asks first.    var disconnecting: DaysGoogle.Disconnect?    @ObservationIgnored let book: any DaysBook    @ObservationIgnored let core: (any CottonCalling)?    @ObservationIgnored let clock: DaysClock    /// The span read: `from` to `to`, the past reached by scrolling up.    private(set) var from: String    private(set) var to: String    var days: [DaysSpan] = []    var known = false    var groups: [DaysGroup] = []    var catalogue: [DaysCatalogueMark] = []    var settings = DaysSettings.kept() {        didSet { settings.keep() }    }    /// The filter (DECISIONS: one filter by group): the chosen group, or nil    /// for All. Remembered on the phone until changed.    var group: DaysGroupCount? = DaysModel.keptGroup() {        didSet { DaysModel.keep(group) }    }    /// The filter's choices with their counts (`days.groups`).    var groupChoices: DaysGroups?    /// One of the four views chosen on Show (DECISIONS: Show; contract §11),    /// shown in place of the days; nil for All or a group. Remembered as a    /// group is.    var view: String? = UserDefaults.standard.string(forKey: "days.view") {        didSet { UserDefaults.standard.set(view, forKey: "days.view") }    }    /// The chosen view as the core answered it, every page read so far.    var viewed: DaysShown?    /// The four views, in Show's order.    static let views = ["late", "repeating", "dropped", "done"]    @ObservationIgnored private var viewAsked = 0    /// A day to bring into view (a jump, or one just added to).    var jumpTo: String?    /// The day at the top of the screen: where a new item lands when its words say no day.    var dayInView: String?    /// Whether today's date is on screen in Days; when it is not, the Today pill stands above the switch.    var todayShown = true    /// A quiet line said a moment at the foot (Moved to Thu 26), with what Undo does.    var said: String?    var undo: (() async -> Void)?    /// The words of the line's act when it is not Undo (Connect, when Google must be asked once more).    var actWords: String?    /// A send pass is running (§16, §17), and when the last one ended.    @ObservationIgnored var sending = false    @ObservationIgnored var sentAt: Date?    /// The to-dos ticked or unticked since the list was opened (DECISIONS:    /// nothing moves at the moment a person acts). Each is drawn at once as    /// it now is, where its row stood, and every read carries them as `keep`    /// (contract §2) until the list is next opened, the day turns or the app    /// comes back from the background.    private(set) var kept: [DaysKept] = []    /// Nothing lies after the last day read (`end`): its closing line; no read further ahead.    private(set) var end: DaysEnd?    /// Nothing lies before this day (`begins`): no read further back.    private(set) var begins: String?    /// The day the list was opened on: when it turns, what was kept is let go.    @ObservationIgnored private var openedOn: String?    /// Every read is counted, and only the newest one asked lands: an answer    /// started before a later read (a tick's, the edge's, coming back) never    /// lands after it and draws an older list.    @ObservationIgnored private var spanAsked = 0    @ObservationIgnored private var sometimeAsked = 0    /// Writes go one after another, in the order the person made them.    @ObservationIgnored private var writing: Task<Void, Never>?    init(book: any DaysBook, core: (any CottonCalling)? = nil, clock: DaysClock = .phone) {        self.book = book        self.core = core        self.clock = clock        let today = clock.today        from = clock.calendar.adding(-Self.past, to: today)        to = clock.calendar.adding(Self.ahead, to: today)    }    var today: String { clock.today }    /// Whether there is anything at all on any day read (the first day with nothing draws its own welcome).    var anything: Bool {        days.contains { if case .day(let d) = $0 { !d.rows.isEmpty } else { false } }    }    /// A first day with nothing anywhere is today alone (pen.html), not months of folded quiet days around it.    var alone: Bool { known && !anything }    var shown: [DaysSpan] {        alone ? days.filter { if case .day(let d) = $0 { d.today } else { false } } : days    }    func read() async {        if openedOn != today {            // A new day: what was kept on the old one is let go.            if openedOn != nil { kept = [] }            openedOn = today        }        if !known {            // Opening: today first, from one short read, before anything else is asked.            await attempt {                try await readSpan(from: today, to: clock.calendar.adding(Self.opening, to: today))                known = true            }        }        await attempt {            try await readSpan(from: from, to: to)            try await readSometime()            if view != nil { try await readView() }            groupChoices = try? await book.groups()            // A chosen group gone (merged or deleted): back to All.            if let chosen = group, let choices = groupChoices, !choices.groups.contains(where: { $0.id == chosen.id }) { group = nil; await read(); return }            if let chosen = group, let now = groupChoices?.groups.first(where: { $0.id == chosen.id }), now != chosen { group = now }            if catalogue.isEmpty {                catalogue = (try? await book.marks()) ?? []                DaysMarkDrawings.shared.take(catalogue)            }            known = true        }    }    /// The list opened again (Days or Sometime chosen, the app back from the    /// background): what was kept is let go, and every row stands where it    /// belongs.    func tidy() async {        // Every tick written first, so the read answers them.        await written()        kept = []        await read()    }    /// `days.span` from `from` to `to`, landing only if no later read was asked meanwhile.    private func readSpan(from asked: String, to askedTo: String) async throws {        spanAsked += 1        let mine = spanAsked        let answer = try await book.span(from: asked, to: askedTo, group: group?.id, keep: kept)        guard mine == spanAsked else { return }        days = answer.days.map { $0.drawn(by: self) }        end = answer.end        begins = answer.begins        // A fold at an edge may reach past what was asked: the next read starts past it.        if case .fold(let first)? = answer.days.first, first.from < from { from = first.from }        if case .fold(let last)? = answer.days.last, last.to > to { to = last.to }    }    private func readSometime() async throws {        sometimeAsked += 1        let mine = sometimeAsked        let answer = try await book.sometime(group: group?.id, keep: kept)        guard mine == sometimeAsked else { return }        groups = answer.map { $0.drawn(by: self) }    }    /// The chosen view's first page (`days.show`), landing only if no later read was asked.    private func readView() async throws {        guard let view else { viewed = nil; return }        viewAsked += 1        let mine = viewAsked        let answer = try await book.show(view, after: nil, keep: kept)        guard mine == viewAsked, view == self.view else { return }        viewed = answer    }    /// The next page of the view (Done is read a page at a time).    func moreOfView() async {        guard let view, let now = viewed, let next = now.next else { return }        viewAsked += 1        let mine = viewAsked        await attempt {            let page = try await book.show(view, after: next, keep: kept)            guard mine == viewAsked, view == self.view else { return }            viewed?.rows += page.rows            viewed?.next = page.next        }    }    /// A view chosen on Show (nil: back to All): the list opened afresh.    func choose(view chosen: String?) {        view = chosen        viewed = nil        if chosen != nil { group = nil }        sheet = nil        Task { await tidy() }    }    /// Bring back a dropped to-do (Dropped's own act), then the view again.    func bringBack(_ row: DaysRow) {        guard let id = row.recordId else { return }        write { [book] in try await book.drop(id, back: true) }        tell(DaysWords.line("row.brought_back", ["title": row.words]))        Task { await written(); await read() }    }    func earlier() async {        if let begins, from <= begins { return }        from = clock.calendar.adding(-Self.past, to: from)        await attempt { try await readSpan(from: from, to: to) }    }    func later() async {        // The list ends (`end`): nothing lies ahead, nothing more is read.        guard end == nil else { return }        to = clock.calendar.adding(Self.ahead, to: to)        await attempt { try await readSpan(from: from, to: to) }    }    /// Bring `day` into the span read, then into view.    func jump(_ day: String) async {        if day < from || day > to {            from = min(from, clock.calendar.adding(-Self.past, to: day))            to = max(to, clock.calendar.adding(Self.ahead, to: day))            await attempt { try await readSpan(from: from, to: to) }        }        jumpTo = day    }    /// The id of the entry holding `day`: its own, or the fold it is folded into.    func entry(holding day: String) -> String? {        if alone { return shown.first?.id }        return days.first { $0.holds(day) }?.id    }    // MARK: Acts    func tell(_ words: String, undo: (() async -> Void)? = nil) {        said = words        self.undo = undo        actWords = nil    }    /// A line at the foot with its own act in place of Undo.    func tell(_ words: String, act: String, _ run: @escaping () async -> Void) {        said = words        undo = run        actWords = act    }    /// A row as it is drawn now: a to-do ticked or unticked since the list    /// was opened shows as it now is, at once, before any answer lands.    func drawn(_ row: DaysRow) -> DaysRow {        guard row.kind == .todo, let id = row.recordId, let kept = kept.last(where: { $0.id == id }) else { return row }        return row.ticked(kept.done)    }    /// The day a row stands on in Days (nil: in Sometime, or not drawn).    private func day(of row: DaysRow) -> String? {        for entry in days {            if case .day(let d) = entry, d.rows.contains(where: { $0.key == row.key }) { return d.day }        }        return nil    }    /// Tick (or untick) a to-do: it shows at once where it stands and stays    /// there (DECISIONS: nothing moves at the moment a person acts). Nothing    /// is read after it; the write goes after any before it, so a second tap    /// always acts on what the first left.    func tick(_ row: DaysRow) {        tick(row, standing: place == .sometime ? nil : day(of: row))    }    /// Tick a row standing on `standing` (nil: Sometime): a view's or a search result's own day.    func tick(_ row: DaysRow, standing: String?) {        guard row.kind == .todo, let id = row.recordId else { return }        let done = !drawn(row).done        let stood = kept.first(where: { $0.id == id })?.day ?? standing        kept.removeAll { $0.id == id }        kept.append(DaysKept(id: id, day: stood, done: done))        // Drawn into what stands now, so the row shows it this moment.        days = days.map { $0.drawn(by: self) }        groups = groups.map { $0.drawn(by: self) }        // No "Done: … Undo" line: the row unticks where it stands, and the        // line, rising at the foot, stood over the bottom row as the next        // tap came (a tick that did not register).        write { [book] in try await book.done(id, done) } failed: { [weak self] in            // Refused: the row shows what the core holds again.            guard let self else { return }            self.kept.removeAll { $0.id == id && $0.done == done }            self.days = self.days.map { $0.undrawn(id, done: !done) }            self.groups = self.groups.map { $0.undrawn(id, done: !done) }        }    }    /// One write after another, in the order made; a refusal is said.    private func write(_ work: @escaping @Sendable () async throws -> Void, failed: @escaping @MainActor () -> Void = {}) {        let before = writing        writing = Task { @MainActor [weak self] in            await before?.value            do { try await work() } catch {                failed()                self?.tell((error as? DaysRefused)?.message ?? ActionRefused.words(for: error))            }        }    }    /// Waits for every write made so far (a test, a read that must see them).    func written() async { await writing?.value }    /// A search result tapped: search closes, and the item is brought into    /// view where it lands (its day, Sometime, or a view), marked a moment.    func land(_ listed: DaysListed) {        finding = false        switch listed.lands {        case .days(let day)?:            place = .days            Task {                await jump(day)                marked = listed.row.key            }        case .sometime?:            place = .sometime            marked = listed.row.key        case .view(let view)?:            // A dropped one lands under Dropped, chosen on Show.            choose(view: view)            marked = listed.row.key        case nil:            break        }    }    /// Show only `chosen`'s to-dos (nil: All): a list opened afresh.    func filter(_ chosen: DaysGroupCount?) {        group = chosen        view = nil        viewed = nil        sheet = nil        Task { await tidy() }    }    /// Days or Sometime chosen: that list is opened again, tidied, where it stood.    func open(_ chosen: DaysPlace) {        guard chosen != place else { return }        place = chosen        Task { await tidy() }    }    /// The filter's words: "All", or the chosen group's name.    var filterWords: String {        if let view { return viewed?.title ?? DaysWords.line("filter.\(view)") }        return group?.name ?? (groupChoices?.all ?? DaysWords.line("filter.all"))    }    private static func keptGroup() -> DaysGroupCount? {        let store = UserDefaults.standard        guard let id = store.string(forKey: "days.group") else { return nil }        return DaysGroupCount(id: id, name: store.string(forKey: "days.groupName") ?? "", count: 0)    }    private static func keep(_ group: DaysGroupCount?) {        let store = UserDefaults.standard        store.set(group?.id, forKey: "days.group")        store.set(group?.name, forKey: "days.groupName")    }    /// Back to today: the Today pill, or "Days" tapped while Days stands.    func backToToday() {        place = .days        Task { await jump(today) }    }    /// Back: the sheet, the adding bar, settings, then Sometime to Days.    @discardableResult    func back() -> Bool {        if sheet != nil { sheet = nil; return true }        if finding { finding = false; return true }        if adding { adding = false; return true }        if settingsOpen { settingsOpen = false; return true }        if place == .sometime { place = .days; return true }        return false    }    var thisMonth: String { String((dayInView ?? today).prefix(7)) }    func attempt(_ work: () async throws -> Void) async {        do { try await work() } catch { tell((error as? DaysRefused)?.message ?? ActionRefused.words(for: error)) }    }}#endif