Cotton code
398 lines · 19.6 KB · SwiftRaw
// FIRST OPEN, TABLES, WHERE ROOM GOES AND LEFTOVERS (data.html; Android's `Tables.kt`). Every word is the core's// `data.welcome`, `data.tables`, `data.room` or `data.leftovers`; a table's name is drawn as stored, in the mono.#if os(iOS)import CottonKitimport SwiftUI/// FIRST OPEN (data.html "First open"; `data.welcome`): what the app is, that it only looks, Keep everything already/// on with its cost, and Start, which keeps what is shown (`data.keep.set {on}`).struct DataWelcomeScreen: View {    let model: DataModel    @State private var read: DataRead<DataWelcome> = .reading    @State private var keep: Bool?    @State private var starting = false    var body: some View {        DataPage(tag: "data-welcome") {            Spacer().frame(height: 48)            switch read {            case .reading: EmptyView()            case .refused(let words): DataLead(text: words)            case .read(let a):                DataTitle(text: a.title)                DataLead(text: a.lead).padding(.top, 6)                Text(verbatim: a.onlyLooks).font(DataType.body).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.top, 16).padding(.bottom, 18)                DataRule(colour: Stone.ink, thick: true)                DataToggleRow(label: a.keep.title, on: keep ?? true, line: a.keep.costLine, strong: true, tag: "data-welcome-keep") { keep = $0 }                Text(verbatim: a.keep.offLine).font(DataType.line).foregroundStyle(Stone.quiet)                    .lineSpacing(3).fixedSize(horizontal: false, vertical: true).padding(.top, 12)            }            Spacer().frame(height: 32)            Button {                guard !starting else { return }                starting = true                let chosen = keep ?? true                Task {                    _ = try? await model.calls.keepSet(on: chosen)                    model.welcome()                }            } label: { Text(verbatim: read.answer?.start ?? DataWords.line("welcome.start")) }            .buttonStyle(DataButtonStyle(go: true))            .accessibilityIdentifier("data-start")        }        .task {            read = await DataRead.of { try await model.calls.welcome() }            // On, as the core recommends; before the server has measured the database (no cost to weigh) it stands            // on too, the owner's default.            if keep == nil, let k = read.answer?.keep { keep = k.on || k.costLine == nil }        }    }}/// TABLES (data.html "Tables"; `data.tables`): the sync line, search over table names, the thin room strip that opens/// Where room goes, the core's chips, the groups with each table's rows and room, the open lock on a table the server/// still reads, Leftovers last, and the line that says what the open lock means.struct DataTablesScreen: View {    let model: DataModel    @State private var by = "app"    @State private var q = ""    @State private var read: DataRead<DataTables> = .reading    @State private var keep: DataKeep?    @State private var reads = ReadInTurn()    @State private var keepReads = ReadInTurn()    @State private var shownAsk: String?    var body: some View {        DataPage(tag: "data-tables") {            Spacer().frame(height: 8)            HStack(alignment: .firstTextBaseline) {                DataTitle(text: read.answer?.title ?? DataWords.line("tables.title"))                if let count = read.answer?.count {                    Text(verbatim: String(count)).font(DataType.mono(16)).foregroundStyle(Stone.quiet)                        .accessibilityHidden(true)                }            }            // Where sync stands, in one quiet line; a tap opens You, where Sync stands.            SyncSeenLine(font: DataType.line, color: Stone.quiet) { SyncSeenOpens.ask() }                .frame(maxWidth: .infinity, alignment: .leading)            if let a = read.answer {                if let keep, keep.state == "filling", let progress = keep.progress {                    fillStrip(keep, progress)                } else if let first = a.firstSync {                    DataFirstSyncStrip(first: first)                }                DataSearchBox(text: $q, placeholder: a.search, tag: "data-tables-search")                if let room = a.room { roomStrip(room) }                DataChips {                    ForEach(a.chips) { chip in                        DataChip(label: chip.title, on: chip.id == by, tag: "data-tables-chip-\(chip.id)") { by = chip.id }                    }                }                ForEach(Array(a.groups.enumerated()), id: \.offset) { _, group in                    if let title = group.title { DataHeading(text: title, end: group.countLine) } else { Spacer().frame(height: 10) }                    ForEach(Array(group.tables.enumerated()), id: \.element.table) { at, t in                        DataTableRow(model: model, line: t, last: at == group.tables.count - 1)                    }                }                if let left = a.leftovers {                    Spacer().frame(height: 4)                    DataRule()                    DataListRow(title: left.title, line: left.line, chevron: true, last: true, tag: "data-tables-leftovers") { model.open(.leftovers) }                }                if let foot = a.foot {                    HStack(alignment: .top, spacing: 6) {                        DataGlyph(mark: .unlock, ink: Stone.quiet, size: 16)                        Text(verbatim: foot).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                    }                    .padding(.top, 12)                    .accessibilityElement(children: .combine)                }            } else if let words = read.refusal {                DataNotice(mark: .cloud, title: words, tag: "data-tables-refused")            } else {                DataWaiting()            }        }        .task(id: "\(by)/\(q)/\(model.revision)") {            if !q.isEmpty { try? await Task.sleep(for: .milliseconds(180)) }            guard !Task.isCancelled else { return }            let asked = "\(by)/\(q.trimmingCharacters(in: .whitespaces))"            if asked != shownAsk { shownAsk = asked; await list() } else { reads.ask { await list() } }        }        .task(id: model.revision) { keepReads.ask { if let next = try? await model.calls.keep() { keep = next } } }        // While Keep everything fills, read again every few seconds: the line at the top moves.        .task {            while !Task.isCancelled {                try? await Task.sleep(for: .seconds(4))                if keep?.state == "filling" { keepReads.ask { if let next = try? await model.calls.keep() { keep = next } } }            }        }    }    private func list() async {        let next = await DataRead.of { try await model.calls.tables(by: by, q: q.trimmingCharacters(in: .whitespaces)) }        if next.answer != nil || read.answer == nil { read = next }        model.tablesShown = true    }    /// The thin room strip: how much of the database's room is used, said and drawn; it opens Where room goes.    private func roomStrip(_ room: DataTables.Room) -> some View {        Button { model.open(.room) } label: {            VStack(alignment: .leading, spacing: 6) {                HStack(spacing: 6) {                    Text(verbatim: room.line).font(DataType.line).foregroundStyle(Stone.quiet)                        .fixedSize(horizontal: false, vertical: true)                        .frame(maxWidth: .infinity, alignment: .leading)                    Text(verbatim: room.go).font(DataType.sans(14, .semibold, .subheadline)).foregroundStyle(Stone.ink)                        .multilineTextAlignment(.trailing)                    DataGlyph(mark: .next, ink: Stone.quiet, size: 16)                }                DataWeight(share: room.share)            }            .padding(.vertical, 8)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(.top, 6)        .accessibilityElement(children: .ignore)        .accessibilityLabel([room.line, room.go].joined(separator: ", "))        .accessibilityAddTraits(.isButton)        .accessibilityIdentifier("data-room")    }    /// Keep everything filling, as one thin line atop the list; a tap opens its page.    /// (While the copy's first sync runs and no fill is under way, `DataFirstSyncStrip` stands in its place.)    private func fillStrip(_ keep: DataKeep, _ progress: DataKeep.Progress) -> some View {        Button { model.open(.keep) } label: {            VStack(alignment: .leading, spacing: 6) {                HStack {                    Text(verbatim: keep.stateLine ?? "").font(DataType.line).foregroundStyle(Stone.ink)                        .frame(maxWidth: .infinity, alignment: .leading)                    if let left = progress.leftLine { Text(verbatim: left).font(DataType.line).foregroundStyle(Stone.quiet) }                }                DataFillBar(percent: progress.percent)            }            .padding(.top, 8).padding(.bottom, 4)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityElement(children: .ignore)        .accessibilityLabel([keep.stateLine, progress.leftLine].compactMap { $0 }.joined(separator: ", "))        .accessibilityAddTraits(.isButton)        .accessibilityIdentifier("data-tables-filling")    }}/// One table on a list: its name as stored, the open lock when the server still reads it, its line and its room.struct DataTableRow: View {    let model: DataModel    let line: DataTableLine    var last = false    var body: some View {        let serverReads = line.mark == "server_reads"        let openable = line.openable != false        DataListRow(title: line.table, line: line.line, end: line.roomLine, monoTitle: true, last: last, tag: "data-table-\(line.table)",                    label: [line.table, serverReads ? DataWords.line("a11y.server_reads") : nil, line.line, line.roomLine].compactMap { $0 }.joined(separator: ", "),                    tap: openable ? { model.open(.rows(line.table)) } : nil) {            if serverReads { DataGlyph(mark: .unlock, ink: Stone.quiet, size: 15) }        }    }}/// WHERE ROOM GOES (data.html "Where room goes"; `data.room`): the file drawn as a core sample, each part beside it with/// what it is and whether it ever comes to a phone; the biggest tables with a weight line; the deleted rows waiting.struct DataRoomScreen: View {    let model: DataModel    @State private var read: DataRead<DataRoom> = .reading    @State private var reads = ReadInTurn()    @ScaledMetric(relativeTo: .body) private var sample: CGFloat = 76    var body: some View {        DataPage(tag: "data-room-page") {            DataBar(back: model.backWord) { model.back() }            DataTitle(text: read.answer?.title ?? DataWords.line("room.title"))            if let a = read.answer {                DataLead(text: a.lead)                HStack(alignment: .top, spacing: 16) {                    DataCoreSample(parts: a.parts).frame(width: min(sample, 120), height: 300)                    VStack(spacing: 0) {                        ForEach(Array(a.parts.enumerated()), id: \.element.id) { at, part in                            VStack(alignment: .leading, spacing: 2) {                                HStack(alignment: .firstTextBaseline, spacing: 8) {                                    RoundedRectangle(cornerRadius: 2).fill(DataCoreSample.colour(part.id, at))                                        .overlay(RoundedRectangle(cornerRadius: 2).strokeBorder(Stone.rule, lineWidth: 1))                                        .frame(width: 10, height: 10)                                    Text(verbatim: part.name).font(DataType.sans(16, .bold)).foregroundStyle(Stone.ink)                                        .fixedSize(horizontal: false, vertical: true)                                        .frame(maxWidth: .infinity, alignment: .leading)                                    Text(verbatim: part.sizeLine).font(DataType.mono(14)).foregroundStyle(Stone.ink)                                }                                Text(verbatim: part.line).font(DataType.line).foregroundStyle(Stone.quiet)                                    .fixedSize(horizontal: false, vertical: true)                                    .padding(.leading, 18)                            }                            .padding(.vertical, 8)                            .accessibilityElement(children: .combine)                            if at < a.parts.count - 1 { DataRule() }                        }                    }                }                .padding(.top, 18)                if !a.biggest.isEmpty {                    DataHeading(text: a.biggestTitle ?? "", end: a.biggestNote)                    ForEach(Array(a.biggest.enumerated()), id: \.offset) { at, big in                        Button { model.open(.rows(big.table)) } label: {                            VStack(alignment: .leading, spacing: 6) {                                HStack(alignment: .firstTextBaseline) {                                    Text(verbatim: big.table).font(DataType.monoName).foregroundStyle(Stone.ink)                                        .fixedSize(horizontal: false, vertical: true)                                        .frame(maxWidth: .infinity, alignment: .leading)                                    Text(verbatim: big.sizeLine).font(DataType.monoLine).foregroundStyle(Stone.quiet)                                }                                DataWeight(share: big.share).padding(.trailing, 80)                            }                            .padding(.vertical, 10)                            .contentShape(Rectangle())                        }                        .buttonStyle(.plain)                        .accessibilityElement(children: .ignore)                        .accessibilityLabel("\(big.table), \(big.sizeLine)")                        .accessibilityAddTraits(.isButton)                        .accessibilityIdentifier("data-room-table-\(big.table)")                        if at < a.biggest.count - 1 { DataRule() }                    }                }                if let deleted = a.deletedLine { DataNote(text: deleted) }                if let measured = a.measuredLine { DataNote(text: measured) }            } else if let words = read.refusal {                DataNotice(mark: .cloud, title: words, tag: "data-room-refused")            } else {                DataWaiting()            }        }        .task(id: model.revision) {            reads.ask {                let next = await DataRead.of { try await model.calls.room() }                if next.answer != nil || read.answer == nil { read = next }            }        }    }}/// The file drawn as the icon's drilled core: a rounded column split by each part's share, free room on top.struct DataCoreSample: View {    let parts: [DataRoom.Part]    static func colour(_ id: String, _ index: Int) -> Color {        switch id {        case "free": Stone.ground        case "rows": Stone.ink        case "changes": Stone.ink.opacity(0.72)        case "search": Stone.ink.opacity(0.5)        case "links": Stone.ink.opacity(0.32)        default: Stone.ink.opacity(min(0.2 + 0.1 * Double(index), 0.6))        }    }    var body: some View {        let total = max(parts.map(\.share).reduce(0, +), 0.0001)        let shape = UnevenRoundedRectangle(topLeadingRadius: 38, bottomLeadingRadius: 6, bottomTrailingRadius: 6, topTrailingRadius: 38)        GeometryReader { box in            VStack(spacing: 0) {                ForEach(Array(parts.enumerated()), id: \.element.id) { at, part in                    if part.share > 0 {                        Rectangle().fill(Self.colour(part.id, at))                            .frame(height: max(box.size.height * part.share / total, 2))                    }                }            }        }        .clipShape(shape)        .overlay(shape.strokeBorder(Stone.ink, lineWidth: 1))        .accessibilityHidden(true)    }}/// LEFTOVERS (data.html "Leftovers"; `data.leftovers`): tables no app uses, tables retired and waiting to be erased,/// and links pointing at nothing. Each opens like any other table; nothing here can be erased.struct DataLeftoversScreen: View {    let model: DataModel    @State private var read: DataRead<DataLeftovers> = .reading    @State private var reads = ReadInTurn()    var body: some View {        DataPage(tag: "data-leftovers") {            DataBar(back: model.backWord) { model.back() }            DataTitle(text: read.answer?.title ?? DataWords.line("leftovers.title"))            if let a = read.answer {                DataLead(text: a.lead)                if let none = a.none { DataNote(text: none) }                if let unused = a.unused {                    DataHeading(text: unused.title, end: unused.line)                    tables(unused.tables)                }                if let retired = a.retired {                    DataHeading(text: retired.title)                    Text(verbatim: retired.line).font(DataType.sans(15)).foregroundStyle(Stone.ink)                        .fixedSize(horizontal: false, vertical: true).padding(.top, 10)                    tables(retired.tables)                }                if let dangling = a.dangling {                    DataHeading(text: dangling.title)                    ForEach(Array(dangling.items.enumerated()), id: \.offset) { at, item in                        DataListRow(title: item.line, line: item.throughLine, lead: .broken, chevron: true, last: at == dangling.items.count - 1,                                    tag: "data-dangling-\(item.table)") { model.open(.rows(item.table)) }                    }                }                DataNote(text: a.foot)            } else if let words = read.refusal {                DataLead(text: words)            } else {                DataWaiting()            }        }        .task(id: model.revision) {            reads.ask {                let next = await DataRead.of { try await model.calls.leftovers() }                if next.answer != nil || read.answer == nil { read = next }            }        }    }    private func tables(_ list: [DataLeftovers.Table]) -> some View {        ForEach(Array(list.enumerated()), id: \.element.table) { at, t in            DataListRow(title: t.table, line: t.line, end: t.roomLine, monoTitle: true, last: at == list.count - 1, tag: "data-leftover-\(t.table)") {                model.open(.rows(t.table))            }        }    }}/// This phone's first sync (FIRST SYNC STATES), as one thin line with the count Account says and, while a pass counts,/// its bar; a tap opens You, where Sync stands. Drawn atop Tables, in place of an empty table's "No rows yet", and/// atop Lately, never as an empty or zero state.struct DataFirstSyncStrip: View {    let first: DataFirstSync    var body: some View {        Button { SyncSeenOpens.ask() } label: {            VStack(alignment: .leading, spacing: 6) {                Text(verbatim: first.said).font(DataType.line).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)                    .frame(maxWidth: .infinity, alignment: .leading)                if let percent = first.seen?.percent { DataFillBar(percent: Int(percent.rounded())) }            }            .padding(.top, 8).padding(.bottom, 4)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityElement(children: .ignore)        .accessibilityLabel(first.said)        .accessibilityAddTraits(.isButton)        .accessibilityIdentifier("data-first-sync")    }}#endif