Cotton code
527 lines · 23.5 KB · SwiftRaw
// DAYS (pen.html "Days"): the continuous list of days, opening on today; the// past by scrolling up. Each day its big numeral (today's in pen blue,// circled by hand), the weekday and month small at the right, a dotted rule,// then its rows; a run of quiet days is one thin line. Every row the same// (DECISIONS "One rule"): a time or nothing, a mark, the words with the quiet// suffix. As Android's `DaysList.kt` and `Rows.kt`.#if os(iOS)import SwiftUIimport UIKit/// What the person does to a row: two gestures only (DECISIONS, 21 Nov/// 2026): tap the circle, tap the row. Everything else is scrolling.struct DaysRowActs {    var tick: (DaysRow) -> Void    var open: (DaysRow) -> Void}/// Where the day at the top of the list stood when last seen, so a read that/// changes what is above it can put it back. Not observed: it changes as the/// list scrolls, and only a read's landing looks at it.@MainActorfinal class DaysTopMark {    var day: String?    var y: CGFloat = 0}struct DaysListView: View {    @Bindable var model: DaysModel    let acts: DaysRowActs    let onConnect: (() -> Void)?    @Environment(BootModel.self) private var boot: BootModel?    @State private var top = DaysTopMark()    /// Reads at the edges wait until the list has opened on today.    @State private var opened = false    /// The entry a jump (or the opening) brought to the top, held there while    /// reads still arriving change the list above it; let go a moment later,    /// or as soon as the person scrolls. One scroll, never a second.    @State private var holding: String?    @State private var letGo: Task<Void, Never>?    /// The list's frame and today's date's, in the window: the Today pill    /// stands while the date is off screen, however long today is.    @State private var viewport: CGRect = .zero    @State private var edge = DaysEdge.middle    @State private var todayDate: CGRect?    /// The list's scroll, driven only to keep the day in view where it stood    /// when a read changes what is above it (never bound to an entry).    @State private var position = ScrollPosition(idType: String.self)    @State private var offset: CGFloat = 0    /// A read just changed the list: the day in view, and where it stood.    @State private var keep: (day: String, y: CGFloat)?    @State private var interacting = false    var body: some View {        ScrollViewReader { reader in            ScrollView {                LazyVStack(alignment: .leading, spacing: 0) {                    ForEach(Array(model.shown.enumerated()), id: \.element.id) { at, span in                        entry(span, at: at)                            .id(span.id)                    }                    // The list ends (contract §2, The end): one quiet closing                    // line after the last item, the core's words, nothing after.                    if let end = model.end, !model.alone {                        Text(end.words)                            .font(PenType.fold)                            .foregroundStyle(Pen.quiet)                            .padding(.top, DaysSpace.foldAbove)                            .frame(maxWidth: .infinity, alignment: .leading)                            .accessibilityIdentifier("days-end")                    }                }                .padding(.horizontal, Pen.side)                .padding(.top, 4)                .padding(.bottom, 110)                // Hidden behind Sometime, its rows are out of the screen                // reader's reach (hiding the list from outside left them in).                .accessibilityHidden(model.place != .days || model.view != nil || model.finding)            }            .scrollPosition($position)            .scrollIndicators(.hidden)            .onScrollGeometryChange(for: CGFloat.self) { $0.contentOffset.y + $0.contentInsets.top } action: { _, y in offset = y }            // The past and the days ahead are read as the list nears its top            // or its end, once per approach: never by a row merely made (a            // lazy row is made off screen, and an accessibility read makes            // them all, so reading on each row's appearing ran the list into            // the past, read after read, far from today).            .onScrollGeometryChange(for: DaysEdge.self) { geometry in                let y = geometry.contentOffset.y + geometry.contentInsets.top                let end = geometry.contentSize.height - geometry.containerSize.height - y                return y < DaysEdge.near ? .top : end < DaysEdge.near ? .end : .middle            } action: { _, now in                edge = now                read(at: now)            }            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in                viewport = frame                seeToday()            }            .onScrollPhaseChange { _, phase in                interacting = phase != .idle                if phase == .interacting {                    keep = nil                    release()                }            }            // Open on today, once the first read stands; then on any day jumped to.            .onChange(of: model.known) { _, known in                guard known, !opened, let today = todayId else { return }                hold(today, reader)            }            .onChange(of: model.jumpTo) { _, day in                guard let day else { return }                model.jumpTo = nil                guard let id = model.entry(holding: day) else { return }                hold(id, reader)            }            // A read arriving while a jump is held keeps the jumped-to day where            // it was put; any other keeps the day in view where it stood.            .onChange(of: model.days) { _, _ in                if let holding {                    reader.scrollTo(holding, anchor: .top)                } else if let day = model.dayInView, top.day == day {                    keep = (day, top.y)                }            }            .onAppear {                if model.known, !opened, let today = todayId { hold(today, reader) }            }            // A row landed on from search: once its day stands, the row itself into view.            .onChange(of: model.marked) { _, key in                guard let key, model.place == .days else { return }                Task { @MainActor in                    try? await Task.sleep(for: .milliseconds(250))                    withAnimation(.easeOut(duration: 0.25)) { reader.scrollTo(key, anchor: .center) }                }            }        }    }    /// The entry standing at the top of the list is the day in view (a fold:    /// its first day). Read from where each entry stands, never by a scroll    /// position bound to the entry: an entry is a whole day, and a read    /// arriving while the person stood far down a long today (another device    /// syncing, the app coming back) put that day's date back at the top,    /// throwing them back up the list.    private func see(_ day: String, at frame: CGRect) {        let top = viewport.minY + 1        if frame.minY <= top && frame.maxY > top && model.dayInView != day { model.dayInView = day }    }    /// Today's date on screen or not: the Today pill stands while it is not.    /// The date itself, not today's whole entry: a long today stood mostly    /// off screen with its date at the top, and the pill showed over it.    private func seeToday() {        let shown = todayDate.map { $0.maxY > viewport.minY && $0.minY < viewport.maxY } ?? false        if model.todayShown != shown { model.todayShown = shown }    }    private var todayId: String? {        model.shown.first { if case .day(let d) = $0 { d.today } else { false } }?.id    }    /// Put `id` at the top at once (no animation over rows not yet measured)    /// and hold it there while the reads settle.    private func hold(_ id: String, _ reader: ScrollViewProxy) {        holding = id        reader.scrollTo(id, anchor: .top)        letGo?.cancel()        letGo = Task { @MainActor in            try? await Task.sleep(for: .milliseconds(900))            guard !Task.isCancelled else { return }            release()        }    }    private func release() {        let first = !opened        letGo?.cancel()        letGo = nil        holding = nil        opened = true        // Opened near an edge: read past it once now, as the person would on reaching it.        if first { read(at: edge) }    }    /// Reads past the edge the list has come to.    private func read(at edge: DaysEdge) {        guard opened, holding == nil, !model.alone else { return }        switch edge {        case .top: Task { await model.earlier() }        case .end: Task { await model.later() }        case .middle: break        }    }    /// The space above an entry: the first stands near the top; a date has    /// the wide gap before it, a fold sits centred in that gap.    private func above(_ at: Int) -> CGFloat {        if at == 0 { return DaysSpace.first }        if case .fold = model.shown[at] { return DaysSpace.foldAbove }        if case .fold = model.shown[at - 1] { return DaysSpace.afterFold }        return DaysSpace.betweenDays    }    @ViewBuilder    private func entry(_ span: DaysSpan, at: Int) -> some View {        switch span {        case .fold(let fold):            Text(fold.words)                .font(PenType.fold)                .foregroundStyle(Pen.quiet)                .padding(.top, above(at))                .frame(maxWidth: .infinity, alignment: .leading)                .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { see(fold.from, at: $0) }        case .day(let day):            VStack(alignment: .leading, spacing: 0) {                DaysDateHeading(day: day, above: above(at)) {                    model.sheet = .jump(month: String(day.day.prefix(7)), pick: nil)                }                .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in                    guard day.today else { return }                    todayDate = frame                    seeToday()                }                .onDisappear {                    guard day.today else { return }                    todayDate = nil                    seeToday()                }                ForEach(day.rows) { row in DaysRowView(row: model.drawn(row), acts: acts, marked: model.marked == row.key).id(row.key) }                if day.today && day.rows.isEmpty {                    // While a signed-in phone's first pull runs: the one quiet line, never "Nothing on today."                    if let bringing = boot?.home?.bringing {                        LoadingLine(bringing: bringing, ink: Pen.quiet, font: PenType.words)                            .padding(.top, 6).padding(.bottom, 4)                            .accessibilityIdentifier("days-bringing")                    } else if model.alone {                        DaysFirstDay(onAdd: { model.adding = true }, onConnect: onConnect)                    } else {                        Text(DaysWords.line("empty.today"))                            .font(PenType.words)                            .foregroundStyle(Pen.quiet)                            .padding(.vertical, DaysSpace.row)                    }                }            }            .frame(maxWidth: .infinity, alignment: .leading)            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in                see(day.day, at: frame)                if model.dayInView == day.day { top.day = day.day; top.y = frame.minY }                if let kept = keep, kept.day == day.day {                    keep = nil                    let moved = frame.minY - kept.y                    if abs(moved) > 1, !interacting, holding == nil { position.scrollTo(y: max(0, offset + moved)) }                }            }        }    }}/// Where the list stands: near its top (the past is read), near its end/// (the days ahead are read), or between.enum DaysEdge: Equatable {    case top, middle, end    /// How near an edge, in points, a read is asked.    static let near: CGFloat = 600}/// Which day a row belongs to, unmistakable (the owner's first use): the/// dotted rule sits directly under the date, the rows close under it, and/// the space before the next date is more than twice the space between two/// rows of a day; a fold sits centred in that space. Every row, one line or/// several, has the same space to its neighbours.enum DaysSpace {    /// Above and below a row's words: two rows of a day stand 2 × this apart.    static let row: CGFloat = 11    /// Under the date's digits, to the dotted rule.    static let toRule: CGFloat = 6    /// Under the dotted rule, to the first row's own space.    static let underRule: CGFloat = 2    /// Above a date that follows a day: with the last row's own space and the    /// numeral's, 51 pt from the last words to the next date (two rows: 22).    static let betweenDays: CGFloat = 36    /// A fold, centred in the gap between the day before and the date after.    static let foldAbove: CGFloat = 22    static let afterFold: CGFloat = 29    /// The first entry, at the top of the list.    static let first: CGFloat = 6}/// A day's heading (`.day`): the numeral at 58, today's in pen and circled by/// hand; the weekday and month at 14 at the right; a dotted rule directly/// under it. A tap on the date opens the jump sheet.struct DaysDateHeading: View {    let day: DaysDay    var above: CGFloat = DaysSpace.betweenDays    let tap: () -> Void    @Environment(\.dynamicTypeSize) private var size    private var colour: Color { day.today ? Pen.pen : Pen.ink }    var body: some View {        let trim = PenMetrics.numeralTrim(size)        VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .center) {                Button(action: tap) {                    Text(day.number)                        .font(PenType.numeral)                        .kerning(-0.02 * 58)                        .foregroundStyle(colour)                        .padding(.leading, 2)                        .padding(.trailing, 10)                        .padding(.vertical, 4)                        .overlay {                            if day.today {                                HandCircle().stroke(Pen.pen, style: StrokeStyle(lineWidth: 1.6, lineCap: .round))                                    .padding(.top, trim.top * 0.6)                                    .padding(.bottom, trim.bottom * 0.6)                            }                        }                        // The font's own space above the digits and under them, taken off,                        // so the rule sits directly under the date.                        .padding(.top, -trim.top)                        .padding(.bottom, -trim.bottom)                        .contentShape(Rectangle())                }                .buttonStyle(PenPress())                .accessibilityLabel(name)                .accessibilityAddTraits(.isHeader)                Spacer(minLength: 12)                // Each a word on its own line, drawn smaller rather than broken:                // at the largest text on an iPhone SE "November" broke into                // "Novembe / r" (launch-ios walk, 22 Nov 2026).                VStack(alignment: .trailing, spacing: 0) {                    Text(day.weekday).lineLimit(1).minimumScaleFactor(DaysKnobs.dayWordLeast)                    Text(day.month).lineLimit(1).minimumScaleFactor(DaysKnobs.dayWordLeast)                }                .font(PenType.weekday)                .foregroundStyle(colour)                .multilineTextAlignment(.trailing)                .accessibilityHidden(true)            }            .padding(.top, above)            .padding(.bottom, DaysSpace.toRule)            DottedRule()        }        .padding(.bottom, DaysSpace.underRule)    }    private var name: String {        let date = "\(day.weekday) \(day.number) \(day.month)"        let jump = DaysWords.line("jump.big_date", ["date": date])        return day.today ? DaysWords.line("a11y.today", ["date": date]) + ". " + jump : jump    }}/// One row, every row the same: a time or nothing, a mark, the words with/// the quiet suffix. The mark column is never empty. Two gestures only/// (DECISIONS, 21 Nov 2026): tap the circle (or the time beside it) to tick a/// to-do, tap the words to change it. No swipe and no hold: they fought the/// list's scrolling, and a row could stay half swiped. A row of several lines/// has its mark on the first line and its suffix on the last.struct DaysRowView: View {    let row: DaysRow    let acts: DaysRowActs    /// Landed on from search: marked a moment in the pen's soft blue.    var marked = false    @Environment(\.dynamicTypeSize) private var size    private var todo: Bool { row.kind == .todo }    var body: some View {        line            .background(marked ? Pen.penSoft : Color.clear)            .animation(.easeOut(duration: 0.4), value: marked)            .accessibilityElement(children: .ignore)            .accessibilityLabel(described)            .accessibilityHint(DaysWords.line("row.change", ["title": row.words]))            .accessibilityAddTraits(.isButton)            .accessibilityAction { acts.open(row) }            .accessibilityActions {                if todo && row.recordId != nil {                    Button(row.done ? DaysWords.line("row.untick", ["title": row.words]) : DaysWords.line("row.tick", ["title": row.words])) { acts.tick(row) }                }            }    }    private var line: some View {        HStack(alignment: .firstTextBaseline, spacing: 6) {            // The time and the mark: for a to-do, one target to tick, wider than the circle alone.            HStack(alignment: .firstTextBaseline, spacing: 6) {                DaysTimeColumn(time: row.time)                MarkView(mark: row.mark)                    .frame(width: 26, height: 26)                    // The mark's middle on the middle of the first line's capitals.                    .alignmentGuide(.firstTextBaseline) { d in d[VerticalAlignment.center] + PenMetrics.wordsMiddle(size) }            }            .padding(.vertical, DaysSpace.row)            .contentShape(Rectangle())            .onTapGesture { if todo { acts.tick(row) } else { acts.open(row) } }            words                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)                .padding(.vertical, DaysSpace.row)                .contentShape(Rectangle())                .onTapGesture { acts.open(row) }        }    }    /// The words, crossed through once done, the suffix quiet after them    /// (`.w small`), held to the last word so it never stands alone on a line.    private var words: some View {        var text = Text(row.words)            .font(PenType.words)            .foregroundStyle(row.done ? Pen.faint : Pen.ink)            .strikethrough(row.done, color: Pen.faint)        if let suffix = row.suffix {            let kept = suffix.replacingOccurrences(of: " ", with: "\u{00A0}")            text = text + Text("\u{00A0}\u{00A0}") + Text(kept).font(PenType.suffix).foregroundStyle(Pen.faint)        }        return text.lineSpacing(15 * 0.45 - 4).fixedSize(horizontal: false, vertical: true)    }    private var described: String {        var out = ""        if let time = row.time { out += time + ", " }        out += row.words        if let suffix = row.suffix { out += ", " + suffix }        if todo { out += ", " + DaysWords.line(row.done ? "a11y.done" : "a11y.todo") }        if case .drawn(let id) = row.mark { out += ", " + DrawnMark.name(id) }        return out    }}/// The time column: as wide as "22:00" in the time's own face at the phone's/// text size (and never narrower than pen.html's 52), so no time is clipped.struct DaysTimeColumn: View {    let time: String?    var body: some View {        ZStack(alignment: .leading) {            Text(verbatim: "22:00").hidden()            Text(verbatim: time ?? "").foregroundStyle(Pen.quiet)        }        .font(PenType.time)        .lineLimit(1)        .fixedSize()        .frame(minWidth: 52, alignment: .leading)        .accessibilityHidden(true)    }}/// A first day with nothing on it (pen.html): the welcome under today, Add something and Connect Google Calendar.struct DaysFirstDay: View {    let onAdd: () -> Void    /// Only while no Google calendar is connected (`days.google`'s connect); nil otherwise.    let onConnect: (() -> Void)?    var body: some View {        VStack(alignment: .leading, spacing: 12) {            Text(DaysWords.line("empty.today")).font(PenType.words).foregroundStyle(Pen.ink)            // The calendar is offered in words only while it can be connected.            Text(DaysWords.line(onConnect == nil ? "empty.line_alone" : "empty.line")).font(PenType.small).foregroundStyle(Pen.quiet)            PenFlow(spacing: 10, lineSpacing: 10) {                PenButton(words: DaysWords.line("empty.add"), go: true, tap: onAdd)                if let onConnect {                    PenButton(words: DaysWords.line("empty.connect"), tap: onConnect)                        .accessibilityIdentifier("days-first-connect")                }            }        }        .padding(.top, 28)        .padding(.bottom, 10)    }}/// SOMETIME (pen.html "Sometime"): every to-do with no day, all of them,/// under the person's groups in their order, each group a heading with its/// count ("No group" where the core puts it, last). The list is lazy, so/// thousands of rows scroll smoothly. Nothing here ever alerts; there are no/// shelves and no "N more".struct DaysSometimeView: View {    @Bindable var model: DaysModel    let acts: DaysRowActs    var body: some View {        if model.known && model.groups.isEmpty {            VStack(alignment: .leading, spacing: 12) {                Text(DaysWords.line("empty.sometime")).font(PenType.words).foregroundStyle(Pen.ink)                Text(DaysWords.line("empty.sometime_line")).font(PenType.small).foregroundStyle(Pen.quiet)            }            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)            .padding(.horizontal, Pen.side)            .padding(.vertical, 28)        } else {            ScrollViewReader { reader in            ScrollView {                LazyVStack(alignment: .leading, spacing: 0) {                    ForEach(Array(model.groups.enumerated()), id: \.element.id) { at, group in                        Section {                            ForEach(group.rows) { row in DaysRowView(row: model.drawn(row), acts: acts, marked: model.marked == row.key).id("\(group.id)/\(row.key)") }                        } header: {                            PenGroupHeading(name: group.name, count: String(group.count), first: at == 0)                                .padding(.top, at == 0 ? 0 : DaysSpace.betweenDays - 16)                        }                    }                }                .padding(.horizontal, Pen.side)                .padding(.top, 4)                .padding(.bottom, 110)                .accessibilityHidden(model.place != .sometime || model.view != nil || model.finding)            }            .scrollIndicators(.hidden)            // A to-do landed on from search: into view, under its first group.            .onChange(of: model.marked) { _, key in                guard let key, model.place == .sometime,                      let group = model.groups.first(where: { $0.rows.contains { $0.key == key } }) else { return }                withAnimation(.easeOut(duration: 0.25)) { reader.scrollTo("\(group.id)/\(key)", anchor: .center) }            }            }        }    }}#endif