Cotton code
800 lines · 36.1 KB · SwiftRaw
// The sheets over Days, each in the pen look (pen.html "Jump to a day"; the// change sheet is drawn here in its language, as Android's// `Sheets.kt`): the sheet's colour, the screen's 28 pt corner, no shadow.#if os(iOS)import SwiftUI/// Every Days panel stands on the sheet colour with the screen's corner (`LookPanel`, no system sheet),/// its grabber at the top: drag it down, or tap above, to close. The grabber/// stands in a strip of its own above the content, so nothing on the sheet/// (a month's title, a long title being changed) is ever drawn under it.extension View {    func daysSheet() -> some View {        VStack(spacing: 0) {            Capsule().fill(Pen.faint).frame(width: 36, height: 5)                .padding(.top, 6).padding(.bottom, 5)                .frame(maxWidth: .infinity)                .accessibilityHidden(true)            self        }    }}extension Pen {    /// A Days panel's colours: the sheet colour over a light scrim, the screen's corner.    static var panel: LookPanelStyle { LookPanelStyle(scrim: Color.black.opacity(0.24), ground: sheet, corner: 28) }}// MARK: - The month, for jumping/// The month (`days.month`): its name large with the year small, the weekday/// letters, each day's number with its drawn marks under it, or a dot where/// there is something else. Today is ringed in pen. A tap closes onto that day.struct DaysJumpSheet: View {    let model: DaysModel    let start: String    /// Drawn inside another sheet (a day chosen on the change sheet or When), without a grabber of its own.    var inside = false    let pick: (String) -> Void    @State private var month: String = ""    @State private var answer: DaysMonth?    var body: some View {        if inside { sheet } else { sheet.daysSheet() }    }    private var sheet: some View {        VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .center, spacing: 0) {                HStack(alignment: .lastTextBaseline, spacing: 10) {                    Text(name).font(PenType.month).foregroundStyle(Pen.ink)                    if !year.isEmpty { Text(year).font(PenType.small).foregroundStyle(Pen.quiet) }                }                .accessibilityElement(children: .combine)                .accessibilityAddTraits(.isHeader)                Spacer(minLength: 8)                arrow("‹", DaysWords.line("jump.previous")) { month = shifted(-1) }                arrow("›", DaysWords.line("jump.next")) { month = shifted(1) }            }            .padding(.top, 12)            // Always six weeks tall, the month read or not, so the height and the arrows never move.            DaysMonthGrid(model: model, month: answer, start: month.isEmpty ? start : month, pick: pick)            HStack {                Spacer()                // Today: this month again, and closed onto today.                PenChip(words: DaysWords.line("jump.today")) {                    month = String(model.today.prefix(7))                    pick(model.today)                }            }            .padding(.top, 10)            Spacer(minLength: 0)        }        .padding(.horizontal, Pen.side)        .padding(.bottom, 18)        .task(id: month) {            if month.isEmpty { month = start; return }            let asked = month            await model.attempt {                let read = try await model.book.month(asked, weekStart: model.settings.weekStart, group: model.group?.id)                // A read for a month already left is dropped, so it never draws over the one shown.                if asked == month { answer = read }            }        }    }    private var title: String { answer?.title ?? "" }    private var name: String { title.split(separator: " ").dropLast().joined(separator: " ").isEmpty ? title : title.split(separator: " ").dropLast().joined(separator: " ") }    private var year: String { title.contains(" ") ? String(title.split(separator: " ").last ?? "") : "" }    private func shifted(_ by: Int) -> String {        let cal = model.clock.calendar        var y = Int(month.prefix(4)) ?? cal.year(model.today)        var m = (Int(month.suffix(2)) ?? 1) + by        if m < 1 { m = 12; y -= 1 }        if m > 12 { m = 1; y += 1 }        return String(format: "%04d-%02d", y, m)    }    private func arrow(_ glyph: String, _ name: String, _ tap: @escaping () -> Void) -> some View {        Button(action: tap) {            Text(glyph).font(PenType.mono(24, relativeTo: .title2)).foregroundStyle(Pen.quiet)                .frame(width: 44, height: 44).contentShape(Rectangle())        }        .buttonStyle(PenPress())        .accessibilityLabel(name)    }}private struct DaysMonthGrid: View {    let model: DaysModel    let month: DaysMonth?    /// The month shown (`YYYY-MM`): its read may still be on its way.    let start: String    let pick: (String) -> Void    /// Six weeks, every month.    static let weekRows = 6    /// The month laid in six weeks of seven: blank cells before the 1st, then its days, then blanks.    static func weeks(lead: Int, days: [DaysMonthDay]) -> [[DaysMonthDay?]] {        var cells: [DaysMonthDay?] = Array(repeating: nil, count: max(0, lead)) + days.map { $0 }        cells += Array(repeating: nil, count: max(0, weekRows * 7 - cells.count))        return stride(from: 0, to: weekRows * 7, by: 7).map { Array(cells[$0..<($0 + 7)]) }    }    var body: some View {        let cal = model.clock.calendar        let days = month?.month == start ? month?.days ?? [] : []        let first = "\(start)-01"        // The week's first day is the phone's setting (kept on the phone until        // the contract names a settings method; the core answers Monday).        let weekStart = min(max(model.settings.weekStart, 1), 7)        // The core's lead for the week start asked; the phone's own count only before the read stands.        let lead = (month?.month == start ? month?.lead : nil) ?? (cal.isoWeekday(first) - weekStart + 7) % 7        let letters = (0..<7).map { i -> String in            let iso = (weekStart - 1 + i) % 7 // 0 Monday … 6 Sunday            return ["M", "T", "W", "T", "F", "S", "S"][iso]        }        let weeks = Self.weeks(lead: lead, days: days)        VStack(spacing: 8) {            HStack(spacing: 0) {                ForEach(Array(letters.enumerated()), id: \.offset) { _, letter in                    Text(letter).font(PenType.letter).foregroundStyle(Pen.faint).frame(maxWidth: .infinity)                }            }            .accessibilityHidden(true)            ForEach(Array(weeks.enumerated()), id: \.offset) { _, week in                HStack(alignment: .top, spacing: 0) {                    ForEach(0..<7, id: \.self) { i in                        Group {                            if let cell = week[i] { DaysMonthCell(model: model, cell: cell) { pick(cell.day) } } else {                                // A blank cell as tall as a day with nothing on it.                                Text(verbatim: " ").font(PenType.cell).padding(.vertical, 2)                                    .frame(maxWidth: .infinity, minHeight: 48, alignment: .top)                                    .accessibilityHidden(true)                            }                        }                        .frame(maxWidth: .infinity)                    }                }            }        }        .padding(.top, 10)    }}private struct DaysMonthCell: View {    let model: DaysModel    let cell: DaysMonthDay    let tap: () -> Void    var body: some View {        Button(action: tap) {            VStack(spacing: 1) {                Text(String(model.clock.calendar.dayOfMonth(cell.day)))                    .font(PenType.cell)                    .foregroundStyle(cell.today ? Pen.pen : Pen.ink)                    .padding(.horizontal, 6)                    .padding(.vertical, 2)                    .background {                        if cell.today {                            // `.c.today::before`: a 30×28 loose oval in pen, turned −8°.                            Ellipse().stroke(Pen.pen, lineWidth: 1.5).frame(width: 30, height: 28).rotationEffect(.degrees(-8))                        }                    }                if !cell.marks.isEmpty {                    HStack(spacing: 1) { ForEach(cell.marks.prefix(2), id: \.self) { DrawnMark(id: $0, size: 18) } }                } else if cell.other {                    QuietDot(size: 4).padding(.top, 6)                }            }            .frame(maxWidth: .infinity, minHeight: 48, alignment: .top)            .contentShape(Rectangle())        }        .buttonStyle(PenPress())        .accessibilityLabel(name)    }    private var name: String {        let date = model.clock.calendar.format(cell.day, "EEEE d MMMM", locale: .current)        if !cell.marks.isEmpty { return DaysWords.line("jump.has_mark", ["date": date, "mark": cell.marks.map(DrawnMark.name).joined(separator: ", ")]) }        if cell.other { return DaysWords.line("jump.has_things", ["date": date]) }        return date    }}/// One choice on a sheet: its words, a quiet value at the right, a dotted rule under.struct DaysChoice: View {    let words: String    let value: String?    var last = false    /// The one standing now, in pen.    var on = false    let tap: () -> Void    var body: some View {        Button(action: tap) {            VStack(spacing: 0) {                HStack {                    Text(words).font(on ? PenType.navOn : PenType.words).foregroundStyle(on ? Pen.pen : Pen.ink)                    Spacer(minLength: 8)                    if let value { Text(value).font(PenType.small).foregroundStyle(Pen.quiet) }                }                .frame(minHeight: 48)                if !last { DottedRule() }            }            .contentShape(Rectangle())        }        .buttonStyle(PenPress())        .accessibilityElement(children: .combine)        .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton)    }}// MARK: - The filter by group/// The filter's groups (`days.groups`): All, then each of the person's/// to-do groups (same-named ones as one) with its count. Choosing one shows/// only its to-dos in Days and Sometime; the choice is remembered.struct DaysGroupsSheet: View {    let model: DaysModel    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                PenFieldLabel(words: DaysWords.line("filter.title")).padding(.top, 10)                if let choices = model.groupChoices {                    DaysChoice(words: choices.all, value: String(choices.count), on: model.group == nil && model.view == nil) { model.filter(nil) }                    ForEach(Array(choices.groups.enumerated()), id: \.element.id) { at, group in                        DaysChoice(words: group.name, value: String(group.count), last: at == choices.groups.count - 1,                                   on: model.group?.id == group.id) { model.filter(group) }                    }                }                // Then, after a line, the four views (DECISIONS: Show): only these.                Rectangle().fill(Pen.rule).frame(height: 1).padding(.vertical, 10).accessibilityHidden(true)                ForEach(Array(DaysModel.views.enumerated()), id: \.element) { at, view in                    DaysChoice(words: DaysWords.line("filter.\(view)"), value: nil, last: at == DaysModel.views.count - 1,                               on: model.view == view) { model.choose(view: view) }                }            }            .padding(.horizontal, Pen.side)            .padding(.bottom, 18)        }        .daysSheet()    }}// MARK: - The one sheet to change an item/// The one sheet (`days.item`): it says whose the item is first. "Yours"/// changes anything; "From Google Calendar" keeps the time and title/// Google's (change it in Google) while the person's own mark, note, group/// and alert stick. A birthday says it is kept on the person.struct DaysChangeSheet: View {    let model: DaysModel    let row: DaysRow    @State private var item: DaysItem?    @Environment(\.openURL) private var openURL    /// A birthday's person, in Cotton People: its own link    /// (`cottonpeople://lists/person/<id>`, the dev build's `cottonpeopledev`,    /// project.yml), which People opens through the core's `link.open`.    /// Without People on the phone, it says so.    private func openPerson(_ id: String) {        #if COTTON_DEV        let scheme = "cottonpeopledev"        #else        let scheme = "cottonpeople"        #endif        guard let url = URL(string: "\(scheme)://lists/person/\(id)") else { return }        let model = model        openURL(url) { accepted in if !accepted { model.tell(DaysWords.line("change.no_people")) } }    }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                if row.whose == .birthday {                    Text(row.words).font(PenType.title).foregroundStyle(Pen.ink).padding(.top, 22)                        .accessibilityAddTraits(.isHeader)                    Text(DaysWords.line("change.birthday")).font(PenType.small).foregroundStyle(Pen.quiet)                        .padding(.top, 6).padding(.bottom, 14)                    PenButton(words: DaysWords.line("change.open_person")) {                        model.sheet = nil                        if case .person(let id) = row.opens { openPerson(id) }                    }                } else if let item {                    DaysItemForm(model: model, row: row, item: item)                }            }            .padding(.horizontal, Pen.side)            .padding(.bottom, 18)            .frame(maxWidth: .infinity, alignment: .leading)        }        .task {            guard let table = row.table, let id = row.recordId else { return }            await model.attempt { item = try await model.book.item(table: table, id: id, occurrenceAt: row.occurrenceAt) }        }        .daysSheet()    }}private struct DaysItemForm: View {    let model: DaysModel    let row: DaysRow    let item: DaysItem    @State private var title = ""    @State private var day: String?    @State private var time = ""    @State private var mark: String?    @State private var note = ""    @State private var group: String?    @State private var alert: DaysAlert?    @State private var choosingDay = false    /// The ENDS chip that stands, and a clock time picked (contract §14).    @State private var endChoice: String?    @State private var endPicked = ""    /// The people as the chips stand, the picker open, and what saving them would tell (contract §15).    @State private var chips: [DaysPerson] = []    @State private var addingPeople = false    /// The one Share sheet for this event (CONTACTS-ANSWERS 10, app days): people from the Circle are invited.    @State private var sharing = false    @State private var told: DaysTold?    /// Google refused to write with this grant (§16): the sheet stays with what was typed, the line and Connect.    @State private var needsWrite: DaysNeedsWrite?    /// The invitation's answer as it now stands, once tapped (§17).    @State private var answered: String?    /// The fields hold the item's facts from the first time the form stood,    /// and keep what the person changed when it stands again (after the    /// month): filling them on every appearance put the day back to the    /// item's and lost a title or note typed before (the owner's "changing    /// the day does not stick", DaysSheets onAppear).    @State private var filled = false    /// Delete was tapped: the sheet asks first (Delete / Keep).    @State private var asking = false    /// The marks the item's words match, best first: offered before the rest.    @State private var matches: [String] = []    @Environment(\.openURL) private var openURL    private var google: Bool { item.whose == .google }    private var cal: DaysCalendar { model.clock.calendar }    var body: some View {        if choosingDay {            // The month in this same sheet, never a sheet over a sheet.            // A day picked moves it there and saves, as a quick choice does.            DaysJumpSheet(model: model, start: String((day ?? model.today).prefix(7)), inside: true) { picked in                day = picked                choosingDay = false                save(moving: .some(picked))            }        } else if addingPeople, let people = item.people {            // Add people in this same sheet, as the month is.            DaysPeoplePicker(model: model, people: people, eventId: item.id, have: chips,                             // A pick adds the chip and goes back to the sheet, as Android's PeopleSheet (the walk, 23 Nov                             // 2026: staying left an empty picker that had to be closed by hand).                             onPick: { person in chips.append(person); addingPeople = false }, onDone: { addingPeople = false })        } else if sharing, let core = model.core, let id = row.recordId {            // Share this one event in this same sheet: the people picked from the Circle are invited.            ShareSheetView(core: core, app: "days", thing: .object(["kind": .string("event"), "id": .string(id)]), close: { sharing = false })        } else {            form        }    }    private var form: some View {        VStack(alignment: .leading, spacing: 0) {            // Whose it is, first (DECISIONS: "It says whose the item is"); an invitation says who sent it (§17).            Text((item.invitation?.says ?? (google ? DaysWords.line("change.google") : DaysWords.line("change.yours"))).uppercased())                .font(PenType.group).tracking(0.96)                .foregroundStyle(google || item.invitation != nil ? Pen.quiet : Pen.pen)                .padding(.top, 14)                .accessibilityIdentifier("days-change-whose")            if google {                // A grant that can write changes title and time at Google too (§16); a read-only one keeps them there.                Text(DaysWords.line(item.canChange.title ? "change.google_line" : "change.google_read"))                    .font(PenType.small).foregroundStyle(Pen.quiet).padding(.top, 4)            }            if let invitation = item.invitation {                DaysInvitationRow(invitation: invitation, standing: answered ?? invitation.answer) { answer($0) }            }            if item.canChange.title {                PenFieldLabel(words: DaysWords.line("change.title"))                TextField("", text: $title, axis: .vertical)                    .font(PenType.title).foregroundStyle(Pen.ink).tint(Pen.pen)                    .lineLimit(1...8)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.bottom, 6)                    .accessibilityLabel(DaysWords.line("change.title"))                DottedRule()            } else {                Text(item.words).font(PenType.title).foregroundStyle(Pen.ink).padding(.top, 10)                    .accessibilityAddTraits(.isHeader)            }            PenFieldLabel(words: DaysWords.line("change.day"))            if item.canChange.time {                // The day now, then the quick choices in one row (the core's                // `choices`, each by its line key move.<key>) and Pick a day                // last: one tap moves it, saves whatever else was changed on                // the sheet, and closes (DECISIONS: the sheet carries everything).                Text(day.map(cal.short) ?? DaysWords.line("move.sometime"))                    .font(PenType.words).foregroundStyle(Pen.ink)                    .padding(.bottom, 8)                PenFlow(spacing: 8, lineSpacing: 8) {                    ForEach(item.choices, id: \.key) { choice in                        let words = DaysWords.line("move.\(choice.key)")                        PenChip(words: words, on: choice.day == day,                                name: choice.day.map { "\(words), \(cal.short($0))" } ?? words) { save(moving: .some(choice.day)) }                    }                    PenChip(words: DaysWords.line("move.pick")) { choosingDay = true }                }            } else {                Text(fixedWhen).font(PenType.words).foregroundStyle(Pen.ink)            }            if item.canChange.time && day != nil {                PenFieldLabel(words: DaysWords.line("change.time"))                TextField("", text: $time, prompt: Text(DaysWords.line("change.no_time")).foregroundColor(Pen.faint))                    .font(PenType.words).foregroundStyle(Pen.ink).tint(Pen.pen)                    .keyboardType(.numbersAndPunctuation)                    .frame(minHeight: 44)                    .onChange(of: time) { _, now in                        let kept = String(now.filter { $0.isNumber || $0 == ":" }.prefix(5))                        if kept != now { time = kept }                    }                    .accessibilityLabel(DaysWords.line("change.time"))                DottedRule()            }            // ENDS under TIME on a timed event; PEOPLE under it on any event (contract §14, §15, §18).            if let ends = item.ends, item.canChange.time, day != nil, !time.isEmpty {                DaysEndsRow(ends: ends, chosen: $endChoice, picked: $endPicked)            }            if let people = item.people, row.kind == .event {                // Connect's notice stands over this sheet, which keeps the chips as they stand.                DaysPeopleRow(people: people, chips: $chips, onAdd: { addingPeople = true }) { connect in                    model.noticing = connect                }                if row.whose == .yours, row.recordId != nil, model.core != nil {                    PenChip(words: ShellLines.line("share", "open")) { sharing = true }                        .padding(.top, 8)                        .accessibilityIdentifier("days-share")                }            }            if item.canChange.mark {                PenFieldLabel(words: DaysWords.line("change.mark"))                DaysMarksRow(ids: DaysMarksRow.offered(model.catalogue.map(\.id), matches: matches, chosen: mark), chosen: $mark)            }            if item.canChange.group && row.kind == .todo {                PenFieldLabel(words: DaysWords.line("change.group"))                PenFlow(spacing: 8, lineSpacing: 8) {                    ForEach(groupChoices, id: \.name) { choice in                        PenChip(words: choice.name, on: group == choice.id) { group = choice.id }                    }                }            }            // The choices the core answers, the one that stands marked (an event with no alert stored stands at its            // ten minutes; No alert once drew chosen there, and reminded all the same).            if item.canChange.alert && !item.alerts.isEmpty && (row.kind == .event || !time.isEmpty) {                PenFieldLabel(words: DaysWords.line("change.alert"))                PenFlow(spacing: 8, lineSpacing: 8) {                    ForEach(item.alerts, id: \.alert) { choice in                        PenChip(words: choice.alert.words, on: alert == choice.alert) { alert = choice.alert }                    }                }            }            if item.canChange.note {                PenFieldLabel(words: DaysWords.line("change.note"))                TextField("", text: $note, prompt: Text(DaysWords.line("change.note_hint")).foregroundColor(Pen.faint), axis: .vertical)                    .font(PenType.words).foregroundStyle(Pen.ink).tint(Pen.pen)                    .frame(minHeight: 44)                    .accessibilityLabel(DaysWords.line("change.note"))                DottedRule()            }            if let told, !told.lines.isEmpty || told.blocked != nil { DaysTellLines(told: told) }            if let needsWrite {                DaysNeedsWriteLine(refused: needsWrite) { model.noticing = $0 }            }            PenFlow(spacing: 10, lineSpacing: 10) {                PenButton(words: DaysWords.line("change.save"), go: true) { save() }                if row.kind == .todo {                    PenButton(words: DaysWords.line(row.done ? "row.not_done" : "row.mark_done")) {                        model.sheet = nil                        model.tick(row)                    }                }                if google {                    PenButton(words: DaysWords.line("change.open_google")) {                        if let url = URL(string: "https://calendar.google.com/") { openURL(url) }                    }                }            }            .padding(.top, 20)            // An event from Google is deleted at Google once its grant can write (§16), so it asks as any other.            if !google || item.canChange.title { foot }        }        .onAppear {            guard !filled else { return }            filled = true            title = item.words            day = item.day            time = item.time ?? ""            mark = item.mark            note = item.note ?? ""            group = item.group            alert = item.alerts.first(where: \.on)?.alert            endChoice = item.ends?.standing            endPicked = item.end ?? ""            chips = item.people?.rows ?? []        }        .task(id: item.words) { matches = (try? await model.book.findMarks(item.words)) ?? [] }        // Before Save, when the chips changed: what saving would tell whom (contract §15 `days.tell`).        .task(id: chips.map(\.key)) {            guard let people = item.people, chips.map(\.key) != people.rows.map(\.key) else { told = nil; return }            told = try? await model.book.tell(eventId: item.id, people: chips)        }    }    /// At the foot, quieter (DECISIONS: the sheet carries everything): Drop    /// (a to-do: decided not to do it, kept under Dropped) and Delete, which    /// asks first.    @ViewBuilder    private var foot: some View {        VStack(alignment: .leading, spacing: 0) {            DottedRule().padding(.top, 22)            if asking {                Text(DaysWords.line("change.delete_ask", ["title": item.words])).font(PenType.small).foregroundStyle(Pen.ink).padding(.top, 12)                // Who is told it is off (§15): only people who were told of it.                if let tells = item.deleteTells {                    Text(tells).font(PenType.small).foregroundStyle(Pen.quiet).padding(.top, 4)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("days-change-delete-tells")                }                HStack(spacing: 18) {                    quiet(DaysWords.line("change.delete_yes"), Pen.ink) { delete() }                    quiet(DaysWords.line("change.delete_keep"), Pen.pen) { asking = false }                }            } else {                HStack(spacing: 18) {                    if row.kind == .todo { quiet(DaysWords.line("change.drop"), Pen.quiet) { drop() } }                    quiet(DaysWords.line("change.delete"), Pen.quiet) { asking = true }                }            }        }    }    private func quiet(_ words: String, _ colour: Color, _ tap: @escaping () -> Void) -> some View {        Button(action: tap) {            Text(words).font(PenType.small).foregroundStyle(colour).frame(minHeight: 44).contentShape(Rectangle())        }        .buttonStyle(PenPress())    }    private func drop() {        let id = item.id        Task {            await model.attempt {                try await model.book.drop(id, back: false)                model.tell(DaysWords.line("row.dropped", ["title": item.words]))            }            model.sheet = nil            await model.read()        }    }    private func delete() {        let table = item.table, id = item.id, occurrence = row.occurrenceAt        Task {            await model.attempt {                try await model.book.delete(table: table, id: id, occurrenceAt: occurrence)                model.tell(DaysWords.line("row.deleted", ["title": item.words]))            }            model.sheet = nil            await model.read()        }    }    private var fixedWhen: String {        var out = item.day.map(cal.short) ?? ""        if let t = item.time { out += " · \(t)" }        if let e = item.end { out += " – \(e)" }        return out    }    private var groupChoices: [(id: String?, name: String)] {        [(nil, DaysWords.line("sometime.no_group"))] + item.groups.map { ($0.id, $0.name) }    }    /// Save what changed on the sheet, and close. `moving`: a day chosen    /// (a quick choice or the month), sent with the rest.    private func save(moving: String?? = nil) {        if let moving { day = moving }        var change = DaysChange()        if item.canChange.title && title != item.words { change.title = .some(title) }        if item.canChange.time && (day != item.day || moving != nil) { change.day = .some(day) }        if item.canChange.time && time != (item.time ?? "") && (time.isEmpty || time.range(of: #"^\d{1,2}:\d{2}$"#, options: .regularExpression) != nil) {            change.time = .some(time.isEmpty ? nil : time)        }        if item.canChange.mark && mark != item.mark { change.mark = .some(mark) }        if item.canChange.note && note != (item.note ?? "") { change.note = .some(note.isEmpty ? nil : note) }        if item.canChange.group && group != item.group {            change.group = .some(group)        }        if item.canChange.alert, let alert, alert != item.alerts.first(where: \.on)?.alert { change.alert = alert }        if let ends = item.ends, item.canChange.time {            let ended = DaysEndsRow.change(ends, chosen: endChoice, picked: endPicked, end: item.end)            change.length = ended.length            change.end = ended.end        }        if let people = item.people, people.canChange, chips.map(\.key) != people.rows.map(\.key) { change.people = chips }        let table = item.table, id = item.id, occurrence = row.occurrenceAt        Task {            var waiting = false            if !change.isEmpty {                do {                    let answer = try await model.book.changed(table: table, id: id, occurrenceAt: occurrence, change)                    if let said = answer.said { model.tell(said) }                    waiting = answer.waiting                } catch {                    // Google needs permission once more (§16): nothing was saved; the sheet stays as typed.                    if let refused = DaysNeedsWrite.of(error) {                        needsWrite = refused                        return                    }                    model.tell((error as? DaysRefused)?.message ?? ActionRefused.words(for: error))                }            }            model.sheet = nil            await model.read()            if waiting { await model.sendAway() }        }    }    /// An invitation answered (§17 `days.answer`): drawn at once, then sent with the next pass.    private func answer(_ key: String) {        answered = key        let id = item.id        Task {            await model.attempt { try await model.book.answer(id, key) }            await model.read()            await model.sendAway()        }    }}// MARK: - Marks, offered/// The marks offered for an item: a sideways row, never a wall. Only marks/// that have a drawing; those the item's words match first, then the rest of/// the catalogue. "No mark" leads.struct DaysMarksRow: View {    let ids: [String]    @Binding var chosen: String?    /// `matches` first (best first), then the catalogue's order; only drawn marks; the chosen one kept.    @MainActor    static func offered(_ catalogue: [String], matches: [String], chosen: String?, drawn: @MainActor (String) -> Bool = DrawnMark.drawn) -> [String] {        var out: [String] = []        for id in matches + catalogue + [chosen].compactMap({ $0 }) where drawn(id) && !out.contains(id) { out.append(id) }        return out    }    var body: some View {        ScrollView(.horizontal) {            HStack(spacing: 8) {                PenChip(words: DaysWords.line("add.no_mark"), on: chosen == nil) { chosen = nil }                ForEach(ids, id: \.self) { id in                    DaysMarkPick(id: id, on: chosen == id) { chosen = chosen == id ? nil : id }                }            }            .padding(.vertical, 2)        }        .scrollIndicators(.hidden)        .scrollClipDisabled()    }}// MARK: - When: the pill's day and time, set by hand while adding/// When (a tap on the pill): the day as Another day offers it (with No day: a/// to-do for Sometime), then the time typed as the clock (19:00) or No time./// Set keeps both; the words that said otherwise are dropped when it is sent./// As Android's `WhenSheet`.struct DaysWhenSheet: View {    let model: DaysModel    let now: DaysPillPick    let set: (DaysPillPick) -> Void    @State private var day: String?    @State private var time = ""    @State private var picking = false    private var valid: Bool { time.isEmpty || DaysPillPick.clock(time) != nil }    var body: some View {        if picking {            DaysJumpSheet(model: model, start: String((day ?? model.today).prefix(7))) { picked in                day = picked                picking = false            }        } else {            when.daysSheet()        }    }    @ViewBuilder    private var when: some View {        let cal = model.clock.calendar        let today = model.today        let tomorrow = cal.adding(1, to: today)        let monday = cal.adding(8 - cal.isoWeekday(today), to: today)        ScrollView {            VStack(alignment: .leading, spacing: 0) {                PenFieldLabel(words: DaysWords.line("when.title")).padding(.top, 10)                Text(day.map(cal.short) ?? DaysWords.line("add.no_day"))                    .font(PenType.title).foregroundStyle(Pen.pen).padding(.bottom, 6)                PenFlow(spacing: 8, lineSpacing: 8) {                    ForEach([("move.today", today), ("move.tomorrow", tomorrow), ("move.next_week", monday)], id: \.0) { key, d in                        let words = DaysWords.line(key)                        PenChip(words: words, on: day == d, name: "\(words), \(cal.short(d))") { day = d }                    }                    PenChip(words: DaysWords.line("add.no_day"), on: day == nil) { day = nil; time = "" }                    PenChip(words: DaysWords.line("move.pick")) { picking = true }                }                PenFieldLabel(words: DaysWords.line("change.time"))                HStack(spacing: 10) {                    VStack(spacing: 0) {                        TextField("", text: $time, prompt: Text("19:00").foregroundColor(Pen.faint))                            .font(PenType.title)                            .foregroundStyle(valid ? Pen.ink : Pen.quiet)                            .tint(Pen.pen)                            .keyboardType(.numbersAndPunctuation)                            .disabled(day == nil)                            .frame(minHeight: 48)                            .onChange(of: time) { _, now in                                let kept = String(now.filter { $0.isNumber || $0 == ":" }.prefix(5))                                if kept != now { time = kept }                            }                            .accessibilityLabel(DaysWords.line("change.time"))                        DottedRule()                    }                    PenChip(words: DaysWords.line("change.no_time"), on: time.isEmpty) { time = "" }                }                PenButton(words: DaysWords.line("when.set"), go: true) {                    if valid { set(DaysPillPick(day: day, time: time.isEmpty ? nil : DaysPillPick.clock(time))) }                }                .padding(.top, 20)            }            .padding(.horizontal, Pen.side)            .padding(.bottom, 18)        }        .onAppear {            if day == nil && time.isEmpty {                day = now.day                time = now.time ?? ""            }        }    }}extension DaysAlert {    /// Its words on the sheet: "No alert", "At the time", or "N min before".    var words: String {        switch self {        case .off: return DaysWords.line("change.no_alert")        case .minutes(0): return DaysWords.line("change.alert_at")        case .minutes(let n): return DaysWords.line("change.alert_before", ["n": String(n)])        }    }}#endif