// 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)importCottonKitimportFoundationimportObservationextensionDaysSpan {/// This entry's rows as the model draws them (ticks kept). @MainActor func drawn(by model: DaysModel) -> DaysSpan {guardcase .day(var d) = selfelse { returnself } 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 {guardcase .day(var d) = selfelse { returnself } d.rows = d.rows.map { $0.recordId == id && $0.kind == .todo ? $0.ticked(done) : $0 }return .day(d) }}extensionDaysGroup { @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 }}extensionDaysRow {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).enumDaysPlace: String, CaseIterable { case days, sometime }/// What stands over Days: one sheet at a time.enumDaysSheet: 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 groupsvar id: String {switchself {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.structDaysSettings: 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 = 10var weekStart = 1privatestaticvar store: UserDefaults { .standard }staticfunc 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 @ObservablefinalclassDaysModel {staticlet past = 28staticlet 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.staticlet opening = 13/// Sometime lists every to-do (DECISIONS: no "first few", no "N more"):/// the core is asked for all of them.staticlet first = 100_000var place: DaysPlace = .daysvar sheet: DaysSheet?var settingsOpen = falsevar 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: Stringprivate(set) var to: Stringvar days: [DaysSpan] = []var known = falsevar 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.staticlet views = ["late", "repeating", "dropped", "done"] @ObservationIgnored privatevar 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 privatevar 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 privatevar spanAsked = 0 @ObservationIgnored privatevar sometimeAsked = 0/// Writes go one after another, in the order the person made them. @ObservationIgnored privatevar writing: Task<Void, Never>?init(book: any DaysBook, core: (any CottonCalling)? = nil, clock: DaysClock = .phone) {self.book = bookself.core = coreself.clock = clocklet 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 { ifcase .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 { ifcase .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 {tryawait readSpan(from: today, to: clock.calendar.adding(Self.opening, to: today)) known = true } }await attempt {tryawait readSpan(from: from, to: to)tryawait readSometime()if view != nil { tryawait readView() } groupChoices = try? await book.groups()// A chosen group gone (merged or deleted): back to All.iflet chosen = group, let choices = groupChoices, !choices.groups.contains(where: { $0.id == chosen.id }) { group = nil; await read(); return }iflet 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.privatefunc readSpan(from asked: String, to askedTo: String) asyncthrows { spanAsked += 1let mine = spanAskedlet answer = tryawait 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.ifcase .fold(let first)? = answer.days.first, first.from < from { from = first.from }ifcase .fold(let last)? = answer.days.last, last.to > to { to = last.to } }privatefunc readSometime() asyncthrows { sometimeAsked += 1let mine = sometimeAskedlet answer = tryawait 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.privatefunc readView() asyncthrows {guardlet view else { viewed = nil; return } viewAsked += 1let mine = viewAskedlet answer = tryawait 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 {guardlet view, let now = viewed, let next = now.next else { return } viewAsked += 1let mine = viewAskedawait attempt {let page = tryawait 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 = nilif chosen != nil { group = nil } sheet = nilTask { await tidy() } }/// Bring back a dropped to-do (Dropped's own act), then the view again.func bringBack(_ row: DaysRow) {guardlet id = row.recordId else { return } write { [book] intryawait book.drop(id, back: true) } tell(DaysWords.line("row.brought_back", ["title": row.words]))Task { await written(); await read() } }func earlier() async {iflet begins, from <= begins { return } from = clock.calendar.adding(-Self.past, to: from)await attempt { tryawait readSpan(from: from, to: to) } }func later() async {// The list ends (`end`): nothing lies ahead, nothing more is read.guard end == nilelse { return } to = clock.calendar.adding(Self.ahead, to: to)await attempt { tryawait 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 { tryawait 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: Actsfunc tell(_ words: String, undo: (() async -> Void)? = nil) { said = wordsself.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).privatefunc day(of row: DaysRow) -> String? {for entry in days {ifcase .day(let d) = entry, d.rows.contains(where: { $0.key == row.key }) { return d.day } }returnnil }/// 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).donelet 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] intryawait book.done(id, done) } failed: { [weakself] in// Refused: the row shows what the core holds again.guardletselfelse { 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.privatefunc write(_ work: @escaping @Sendable () asyncthrows -> Void, failed: @escaping @MainActor () -> Void = {}) {let before = writing writing = Task { @MainActor [weakself] inawait before?.valuedo { tryawait 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 = falseswitch listed.lands {case .days(let day)?: place = .daysTask {await jump(day) marked = listed.row.key }case .sometime?: place = .sometime marked = listed.row.keycase .view(let view)?:// A dropped one lands under Dropped, chosen on Show. choose(view: view) marked = listed.row.keycasenil:break } }/// Show only `chosen`'s to-dos (nil: All): a list opened afresh.func filter(_ chosen: DaysGroupCount?) { group = chosen view = nil viewed = nil sheet = nilTask { await tidy() } }/// Days or Sometime chosen: that list is opened again, tidied, where it stood.funcopen(_ chosen: DaysPlace) {guard chosen != place else { return } place = chosenTask { await tidy() } }/// The filter's words: "All", or the chosen group's name.var filterWords: String {iflet view { return viewed?.title ?? DaysWords.line("filter.\(view)") }return group?.name ?? (groupChoices?.all ?? DaysWords.line("filter.all")) }privatestaticfunc keptGroup() -> DaysGroupCount? {let store = UserDefaults.standardguardlet id = store.string(forKey: "days.group") else { returnnil }returnDaysGroupCount(id: id, name: store.string(forKey: "days.groupName") ?? "", count: 0) }privatestaticfunc 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 = .daysTask { await jump(today) } }/// Back: the sheet, the adding bar, settings, then Sometime to Days. @discardableResultfunc back() -> Bool {if sheet != nil { sheet = nil; returntrue }if finding { finding = false; returntrue }if adding { adding = false; returntrue }if settingsOpen { settingsOpen = false; returntrue }if place == .sometime { place = .days; returntrue }returnfalse }var thisMonth: String { String((dayInView ?? today).prefix(7)) }func attempt(_ work: () asyncthrows -> Void) async {do { tryawait work() } catch { tell((error as? DaysRefused)?.message ?? ActionRefused.words(for: error)) } }}#endif