Cotton code
685 lines · 33.9 KB · SwiftRaw
// A TABLE'S ROWS, ONE ROW, AND THE LINK AND PICTURE SHEETS (data.html; Android's `Rows.kt`). Every row's words come// from the table's own `slip`, said by the core; each field is drawn as its kind asks; As stored types each value out// as it really sits in the row. Read only: nothing on these screens edits or erases.#if os(iOS)import CottonKitimport QuickLookimport SwiftUIimport UIKit/// A TABLE'S ROWS (data.html "A table's rows"; `data.rows`): the table's name as stored, how many rows and who uses it,/// what sort and dates are set, then the rows under their months, each a short sentence with its date at the end; Show/// more asks the next page (`after`); the table's own search (`q`). The (i) opens About. An empty table names the app/// that would fill it. A phone without the key draws the locked list, as the server holds it.struct DataRowsScreen: View {    let model: DataModel    let table: String    @State private var head: DataRows?    @State private var groups: [DataRows.Group] = []    @State private var after: JSONValue?    @State private var more = false    @State private var loading = false    @State private var refused: String?    @State private var q = ""    @State private var placeholder: String?    @State private var reads = ReadInTurn()    /// The search the rows shown answer.    @State private var searched: String?    private var asked: String? {        let t = q.trimmingCharacters(in: .whitespaces)        return t.count >= 2 ? t : nil    }    var body: some View {        DataPage(tag: "data-rows") {            DataBar(back: model.backWord, tap: { model.back() }) {                Button { model.open(.about(table)) } label: { DataGlyph(mark: .info, size: 22).frame(minWidth: 44, minHeight: 44) }                    .buttonStyle(.plain)                    .accessibilityLabel(DataWords.line("a11y.about"))                    .accessibilityIdentifier("data-rows-about")            }            DataTitle(text: table, mono: true)            if let h = head {                DataLead(text: h.lead)                if let hint = placeholder, h.sealedView != true {                    DataSearchBox(text: $q, placeholder: hint, tag: "data-rows-search")                }                // What is set, always said: the sort and the dates.                if h.sortLine != nil || h.dateLine != nil {                    DataChips {                        if let sort = h.sortLine { DataChip(label: sort, on: false, mark: .sort) }                        if let date = h.dateLine { DataChip(label: date, on: false, mark: .calendar) }                    }                }                if h.sealedView == true {                    locked(h)                } else {                    // In this phone's first sync an empty table says its rows are coming, never that it has none.                    if let first = h.firstSync, groups.isEmpty {                        DataFirstSyncStrip(first: first)                    } else if let empty = h.empty {                        emptyState(empty)                    }                    ForEach(Array(groups.enumerated()), id: \.offset) { _, group in                        DataHeading(text: group.title, end: String(group.count))                        ForEach(Array(group.rows.enumerated()), id: \.offset) { at, row in                            DataListRow(title: row.title, line: row.line, end: row.when, monoEnd: false, last: at == group.rows.count - 1,                                        tag: "data-row-\(row.id)") {                                model.open(.row(table: row.table ?? table, id: row.id, trail: []))                            }                        }                    }                    if more {                        Button { Task { await page(after) } } label: { Text(verbatim: DataWords.line("rows.more")) }                            .buttonStyle(DataButtonStyle())                            .disabled(loading)                            .padding(.top, 14)                            .accessibilityIdentifier("data-rows-more")                    }                    if let refused { DataNote(text: refused) }                    if let foot = h.foot { DataNote(text: foot) }                }            } else if let refused {                DataFailed(words: refused, tag: "data-rows-refused") { reads.ask { await page(nil) } }            } else {                // Asked and not yet answered: said at once, never a page with its title alone.                DataWaiting(words: DataWords.line("rows.loading"), tag: "data-rows-loading")            }        }        .task(id: "\(model.revision)/\(asked ?? "")") {            if asked != nil { try? await Task.sleep(for: .milliseconds(220)) }            guard !Task.isCancelled else { return }            // A new search asks at once; a move of the database asks once the read out has landed (`ReadInTurn`).            if asked != searched { searched = asked; await page(nil) } else { reads.ask { await page(nil) } }        }    }    private func page(_ next: JSONValue?) async {        loading = true        defer { loading = false }        do {            let a = try await model.calls.rows(table, q: asked, after: next)            refused = nil            if next == nil { head = a; groups = [] }            if let hint = a.search { placeholder = hint }            // A month that runs across two pages is one group.            for g in a.groups {                if let last = groups.last, last.title == g.title {                    groups[groups.count - 1].rows += g.rows                    groups[groups.count - 1].count += g.count                } else {                    groups.append(g)                }            }            after = a.after            more = a.more == true        } catch {            refused = DataModel.words(error)        }    }    private func emptyState(_ empty: DataRows.Empty) -> some View {        VStack(alignment: .leading, spacing: 6) {            DataGlyph(mark: .table, ink: Stone.faint, size: 40).padding(.top, 48)            Text(verbatim: empty.title).font(DataType.sans(21, .bold, .title3)).foregroundStyle(Stone.ink)                .fixedSize(horizontal: false, vertical: true).padding(.top, 6)            Text(verbatim: empty.body).font(DataType.body).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)            if let act = empty.act {                Button { model.open(.columns(table)) } label: {                    HStack(spacing: 4) {                        Text(verbatim: act).font(DataType.sans(16, .semibold))                        DataGlyph(mark: .next, size: 16)                    }                    .foregroundStyle(Stone.ink)                    .frame(minHeight: 44).contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityIdentifier("data-rows-columns")            }        }    }    /// LOCKED (data.html "Sealed rows, phone locked"): the rows as the server holds them, and Unlock. The ways in    /// (Approve, a recovery code) are the shell's own, standing over every app while the key is missing.    @ViewBuilder private func locked(_ h: DataRows) -> some View {        if let l = h.locked { DataNotice(mark: .lock, title: l.title, line: l.line, tag: "data-rows-locked") }        let rows = h.rows ?? []        ForEach(Array(rows.enumerated()), id: \.offset) { at, r in            let second = [r.clearLine, r.pointsLine].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " \u{B7} ")            Button {                if let id = r.id { model.open(.row(table: table, id: id, trail: [])) }            } label: {                VStack(alignment: .leading, spacing: 2) {                    HStack(alignment: .firstTextBaseline) {                        Text(verbatim: r.madeLine).font(DataType.mono(15)).foregroundStyle(Stone.ink)                            .fixedSize(horizontal: false, vertical: true)                            .frame(maxWidth: .infinity, alignment: .leading)                        if let size = r.sizeLine { Text(verbatim: size).font(DataType.sans(13, .regular, .footnote)).foregroundStyle(Stone.quiet) }                    }                    if !second.isEmpty {                        Text(verbatim: second).font(DataType.monoLine).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                    }                }                .padding(.vertical, 11)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .disabled(r.id == nil)            .accessibilityElement(children: .ignore)            .accessibilityLabel([r.madeLine, r.sizeLine, r.clearLine, r.pointsLine].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", "))            .accessibilityAddTraits(r.id == nil ? [] : .isButton)            .accessibilityIdentifier("data-rows-locked-row")            if at < rows.count - 1 { DataRule() }        }        if let l = h.locked {            if let sizes = l.sizes { DataNote(text: sizes) }            if let unlock = l.unlock {                Button { model.changed() } label: { DataMarkedLabel(words: unlock, mark: .lock) }                    .buttonStyle(DataButtonStyle(go: true))                    .padding(.top, 18)                    .accessibilityIdentifier("data-rows-unlock")            }            if let noKey = l.noKeyLine { DataNote(text: noKey).padding(.top, 2) }        }    }}/// ONE ROW (data.html "One row, every field"; `data.row`): the trail of rows followed to reach it, its title and how it/// came to be, then every field, each kind drawn its own way, the column as stored small above and its type in quiet/// words; the rows that point here; who changes it. AS STORED (`data.stored`) types each field out as it sits, then/// Plain words turns it back. A phone without the key sees the server's facts about the row, and nothing sealed.struct DataRowScreen: View {    let model: DataModel    let table: String    let id: String    let trail: [DataStep]    @State private var read: DataRead<DataRow> = .reading    @State private var reads = ReadInTurn()    @State private var stored: DataStored?    @State private var asStored = false    private var steps: [DataStep] { read.answer?.trail ?? trail }    var body: some View {        DataPage(tag: "data-row-page") {            // Back says where it goes: the row before on the trail, else the table.            let backTo = steps.count >= 2 ? steps[steps.count - 2].name : table            DataBar(back: backTo, tap: { model.back() }) {                if let word = read.answer?.stored {                    storedPill(word)                }            }            if steps.count > 1 { DataTrail(model: model, steps: steps) }            switch read {            case .reading:                DataTitle(text: table, mono: true)                DataWaiting(tag: "data-row-loading")            case .refused(let words):                DataTitle(text: table, mono: true)                DataFailed(words: words, tag: "data-row-refused") { read = .reading; reads.ask { await load() } }            case .read(let a):                if a.sealedView == true { sealed(a) } else { open(a) }            }        }        .task(id: model.revision) { reads.ask { await load() } }    }    private func load() async {        let next = await DataRead.of { try await model.calls.row(table, id: id, trail: trail) }        if next.answer != nil || read.answer == nil { read = next }    }    private func storedPill(_ word: String) -> some View {        let label = asStored ? (stored?.plain ?? word) : word        return Button {            if asStored { asStored = false; return }            Task {                if stored == nil {                    do { stored = try await model.calls.stored(table, id: id) } catch { model.tell(DataModel.words(error)); return }                }                asStored = true            }        } label: {            Text(verbatim: label).font(DataType.sans(14, .semibold, .subheadline))                .foregroundStyle(asStored ? Stone.ground : Stone.ink)                .lineLimit(1).minimumScaleFactor(0.6)                .padding(.horizontal, 10).padding(.vertical, 5)                .background(RoundedRectangle(cornerRadius: 10).fill(asStored ? Stone.ink : .clear))                .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(asStored ? Stone.ink : Stone.rule, lineWidth: 1))                .frame(minHeight: 44).contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityAddTraits(asStored ? .isSelected : [])        .accessibilityIdentifier("data-stored")    }    @ViewBuilder private func open(_ a: DataRow) -> some View {        DataTitle(text: a.title)        if let lead = a.lead { DataLead(text: lead) }        Spacer().frame(height: 8)        let fields = a.fields ?? []        let byColumn = Dictionary((stored?.fields ?? []).map { ($0.column, $0.stored) }, uniquingKeysWith: { first, _ in first })        ForEach(Array(fields.enumerated()), id: \.element.column) { at, f in            DataFieldView(model: model, table: table, id: id, field: f, stored: asStored ? byColumn[f.column] : nil, index: at, trail: steps)            DataRule()        }        // As stored also shows any column the definition no longer names, exactly as it sits.        if asStored, let stored {            ForEach(stored.fields.filter { s in !fields.contains { $0.column == s.column } }, id: \.column) { s in                VStack(alignment: .leading, spacing: 4) {                    Text(verbatim: s.column).font(DataType.monoLine).foregroundStyle(Stone.quiet)                    DataTypeOut(text: s.stored)                }                .padding(.vertical, 12)                DataRule()            }        }        let points = a.pointsHere ?? []        if !points.isEmpty {            DataHeading(text: a.pointsTitle ?? DataWords.line("row.points_here"), end: String(points.reduce(0) { $0 + $1.count }))            ForEach(Array(points.enumerated()), id: \.offset) { _, p in                HStack(spacing: 6) {                    DataTableTag(name: p.table)                    Text(verbatim: p.throughLine).font(DataType.line).foregroundStyle(Stone.quiet)                        .fixedSize(horizontal: false, vertical: true)                        .frame(maxWidth: .infinity, alignment: .leading)                    Text(verbatim: String(p.count)).font(DataType.line).foregroundStyle(Stone.quiet)                }                .padding(.top, 12).padding(.bottom, 4)                .accessibilityElement(children: .combine)                DataRule()                ForEach(Array(p.rows.enumerated()), id: \.offset) { at, r in                    DataListRow(title: r.title, chevron: true, last: at == p.rows.count - 1, tag: "data-points-\(r.id)") {                        model.open(.row(table: r.table, id: r.id, trail: steps))                    }                }            }        }        if let note = a.severalNote { DataNote(text: note) }        if let foot = a.foot { DataNote(text: foot, center: true).padding(.top, 8) }    }    /// A SEALED ROW, KEY MISSING (data.html): every fact the server holds, in words. The ways in are the shell's own.    @ViewBuilder private func sealed(_ a: DataRow) -> some View {        DataTitle(text: a.title)        if let band = a.band { DataNotice(mark: .lock, title: band.title, line: band.line, tag: "data-row-locked") }        let facts = a.facts ?? []        let monoLabels = Set(["missing.table", "missing.row", "missing.version", "missing.clear"].map { DataWords.line($0) })        ForEach(Array(facts.enumerated()), id: \.offset) { at, f in            DataFlow(spacing: 10, lineSpacing: 4) {                Text(verbatim: f.label).font(DataType.sans(15)).foregroundStyle(Stone.quiet)                Text(verbatim: f.value).font(monoLabels.contains(f.label) ? DataType.mono(15) : DataType.sans(15)).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)            }            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.vertical, 11)            .accessibilityElement(children: .combine)            .accessibilityIdentifier("data-row-fact")            if at < facts.count - 1 { DataRule() }        }    }}/// The trail above the title (`book › The Salt Monsoon › author › Meera Joshi`): each step goes back to it.struct DataTrail: View {    let model: DataModel    let steps: [DataStep]    var body: some View {        DataFlow(spacing: 4, lineSpacing: 2) {            DataTableTag(name: steps.first?.table ?? "")            ForEach(Array(steps.enumerated()), id: \.offset) { at, step in                let here = at == steps.count - 1                if here {                    Text(verbatim: step.name).font(DataType.sans(14, .semibold, .subheadline)).foregroundStyle(Stone.ink)                        .fixedSize(horizontal: false, vertical: true)                } else {                    Button { model.back(steps.count - 1 - at) } label: {                        HStack(spacing: 4) {                            Text(verbatim: step.name).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                            DataGlyph(mark: .next, ink: Stone.faint, size: 14)                        }                        .frame(minHeight: 32).contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityLabel(step.name)                    .accessibilityIdentifier("data-trail-\(at)")                }            }        }        .frame(maxWidth: .infinity, alignment: .leading)        .padding(.top, 2)    }}/// One field, drawn as its kind asks (DECISIONS "One row"); `stored`, the value as it sits, typed out in its place.struct DataFieldView: View {    let model: DataModel    let table: String    let id: String    let field: DataField    let stored: String?    let index: Int    let trail: [DataStep]    var body: some View {        VStack(alignment: .leading, spacing: 4) {            HStack(alignment: .firstTextBaseline, spacing: 8) {                Text(verbatim: field.column).font(DataType.monoLine).foregroundStyle(Stone.quiet)                    .fixedSize(horizontal: false, vertical: true)                    .frame(maxWidth: .infinity, alignment: .leading)                Text(verbatim: field.typeLine).font(DataType.sans(13, .regular, .footnote)).foregroundStyle(Stone.quiet)                    .multilineTextAlignment(.trailing)            }            .accessibilityElement(children: .combine)            if let stored {                DataTypeOut(text: stored, wait: 0.04 * Double(index))            } else if field.empty {                Text(verbatim: field.valueLine).font(DataType.body).foregroundStyle(Stone.faint)            } else {                value            }        }        .padding(.vertical, 12)        .accessibilityIdentifier("data-field-\(field.column)")    }    @ViewBuilder private var value: some View {        let words = field.valueLine        switch field.kind {        case "link": link(words)        case "amount": DataAmount(value: words)        case "date", "time":            Text(verbatim: words).font(DataType.sans(17)).foregroundStyle(Stone.ink).fixedSize(horizontal: false, vertical: true)            if let sub = field.sub { Text(verbatim: sub).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true) }        case "choice":            Text(verbatim: words).font(DataType.sans(16, .semibold)).foregroundStyle(Stone.ink)                .padding(.horizontal, 8).padding(.vertical, 2)                .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Stone.ink, lineWidth: 1.5))            if let sub = field.sub { Text(verbatim: sub).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 2) }        case "bool":            HStack(spacing: 8) {                DataGlyph(mark: .tick, size: 18)                Text(verbatim: [words, field.sub].compactMap { $0 }.joined(separator: ", ")).font(DataType.sans(17)).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)            }            .accessibilityElement(children: .combine)        case "several":            DataFlow(spacing: 8, lineSpacing: 6) {                ForEach(Array((field.items ?? [words]).enumerated()), id: \.offset) { _, item in                    Text(verbatim: item).font(DataType.sans(15)).foregroundStyle(Stone.ink)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.horizontal, 9).padding(.vertical, 2)                        .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Stone.rule, lineWidth: 1))                }            }        case "url":            Button { model.sheet = .link(table: table, id: id, column: field.column) } label: {                HStack(spacing: 8) {                    Text(verbatim: words).font(DataType.sans(17, .medium)).underline().foregroundStyle(Stone.ink)                        .fixedSize(horizontal: false, vertical: true)                        .frame(maxWidth: .infinity, alignment: .leading)                    DataGlyph(mark: .open, size: 18)                }                .frame(minHeight: 44).contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("data-url-\(field.column)")        case "place": DataReference(mark: .pin, name: words)        case "photo", "file":            DataReference(mark: field.kind == "photo" ? .photo : .file, name: words, line: field.sub, open: DataWords.line("media.open")) {                model.sheet = .media(table: table, id: id, column: field.column)            }            .accessibilityIdentifier("data-media-\(field.column)")        case "long": DataLong(value: words, folded: field.folded)        case "number", "bytes", "account":            Text(verbatim: words).font(DataType.mono(17)).foregroundStyle(Stone.ink).fixedSize(horizontal: false, vertical: true)        default:            Text(verbatim: words).font(DataType.sans(17)).foregroundStyle(Stone.ink).fixedSize(horizontal: false, vertical: true)                .textSelection(.enabled)        }    }    /// A link: the name, underlined, with its table; one that holds several, each name its own.    @ViewBuilder private func link(_ words: String) -> some View {        let target = field.link?.table ?? ""        if let one = field.link?.id {            Button { model.open(.row(table: target, id: one, trail: trail)) } label: {                DataFlow(spacing: 6, lineSpacing: 4) {                    Text(verbatim: words).font(DataType.sans(17, .semibold)).underline().foregroundStyle(Stone.ink)                        .fixedSize(horizontal: false, vertical: true)                    DataTableTag(name: target)                }                .frame(minHeight: 44, alignment: .leading).contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityElement(children: .ignore)            .accessibilityLabel("\(words), \(target)")            .accessibilityAddTraits(.isButton)            .accessibilityIdentifier("data-link-\(field.column)")        } else {            let ids = field.link?.ids ?? []            let names = field.items ?? []            DataFlow(spacing: 8, lineSpacing: 6) {                ForEach(Array(ids.enumerated()), id: \.offset) { at, rid in                    let name = at < names.count ? names[at] : rid                    Button { model.open(.row(table: target, id: rid, trail: trail)) } label: {                        Text(verbatim: name).font(DataType.sans(16, .semibold)).underline().foregroundStyle(Stone.ink)                            .fixedSize(horizontal: false, vertical: true)                            .frame(minHeight: 36).contentShape(Rectangle())                    }                    .buttonStyle(.plain)                }                DataTableTag(name: target)            }        }    }}/// An amount in the mono, its smaller part (paise, cents) set smaller, as the drawing shows ₹ 499.00.struct DataAmount: View {    let value: String    var body: some View {        let dot = value.lastIndex(of: ".")        let tail = dot.map { String(value[value.index(after: $0)...]) } ?? ""        let split = dot != nil && dot != value.startIndex && !tail.isEmpty && tail.count <= 2 && tail.allSatisfy(\.isNumber)        let whole = split ? String(value[..<dot!]) : value        dataRuns([(whole, DataType.mono(19), Stone.ink), (split ? "." + tail : "", DataType.mono(14), Stone.quiet)])            .fixedSize(horizontal: false, vertical: true)            .accessibilityLabel(value)    }}/// A place, a photo or a file: its mark in a small box, its name beside it, and Open where it opens.struct DataReference: View {    let mark: DataMark    let name: String    var line: String?    var open: String?    var tap: (() -> Void)?    var body: some View {        let content = HStack(spacing: 12) {            DataGlyph(mark: mark, size: 20)                .frame(width: 42, height: 42)                .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Stone.rule, lineWidth: 1))            VStack(alignment: .leading, spacing: 2) {                Text(verbatim: name).font(DataType.sans(16, .semibold)).foregroundStyle(Stone.ink).fixedSize(horizontal: false, vertical: true)                if let line { Text(verbatim: line).font(DataType.monoLine).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true) }            }            .frame(maxWidth: .infinity, alignment: .leading)            if let open, tap != nil { Text(verbatim: open).font(DataType.sans(16, .semibold)).foregroundStyle(Stone.ink) }        }        if let tap {            Button(action: tap) { content.contentShape(Rectangle()) }                .buttonStyle(.plain)                .accessibilityElement(children: .ignore)                .accessibilityLabel([name, open].compactMap { $0 }.joined(separator: ", "))                .accessibilityAddTraits(.isButton)        } else {            content.accessibilityElement(children: .combine)        }    }}/// Long text folded at three lines, with the core's "Show all 12 lines" opening it in place.struct DataLong: View {    let value: String    let folded: DataField.Folded?    @State private var open = false    var body: some View {        Text(verbatim: value).font(DataType.body).foregroundStyle(Stone.ink)            .lineSpacing(5)            .lineLimit(folded != nil && !open ? 3 : nil)            .fixedSize(horizontal: false, vertical: true)            .textSelection(.enabled)        if let folded, !open {            Button { open = true } label: {                HStack(spacing: 4) {                    Text(verbatim: folded.allLine).font(DataType.sans(15, .semibold))                    DataGlyph(mark: .down, size: 16)                }                .foregroundStyle(Stone.ink)                .frame(minHeight: 44).contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("data-show-all")        }    }}/// A LINK OPENED (data.html "A link opened"; `data.link`): the whole address first, the site in ink and the rest/// quiet, so it is seen before it is gone to; Open in browser leaves Cotton for Safari; Copy link copies it.struct DataLinkView: View {    let model: DataModel    let table: String    let id: String    let column: String    let close: () -> Void    @State private var read: DataRead<DataLinkSheet> = .reading    @Environment(\.openURL) private var openURL    var body: some View {        VStack(alignment: .leading, spacing: 12) {            switch read {            case .reading: DataWaiting().frame(minHeight: 120, alignment: .top)            case .refused(let words): DataLead(text: words)            case .read(let a):                Text(verbatim: a.title).font(DataType.sans(26, .bold, .title1)).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityAddTraits(.isHeader)                Text(verbatim: a.fromLine).font(DataType.sans(15)).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                address(a)                    .padding(14)                    .frame(maxWidth: .infinity, alignment: .leading)                    .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Stone.rule, lineWidth: 1))                    .accessibilityIdentifier("data-link-address")                Text(verbatim: a.note).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                Button {                    if let url = URL(string: a.address) { openURL(url) }                    close()                } label: { DataMarkedLabel(words: a.open, mark: .open) }                .buttonStyle(DataButtonStyle(go: true))                .accessibilityIdentifier("data-link-open")                Button {                    UIPasteboard.general.string = a.address                    model.tell(a.copied)                    close()                } label: { Text(verbatim: a.copy) }                .buttonStyle(DataButtonStyle())                .accessibilityIdentifier("data-link-copy")            }        }        .task { read = await DataRead.of { try await model.calls.link(table, id: id, column: column) } }    }    private func address(_ a: DataLinkSheet) -> Text {        let font = DataType.mono(14, .regular, .footnote)        guard !a.site.isEmpty, let at = a.address.range(of: a.site) else {            return Text(verbatim: a.address).font(font).foregroundStyle(Stone.ink)        }        return dataRuns([(String(a.address[..<at.lowerBound]), font, Stone.quiet),                         (a.site, DataType.mono(14, .semibold, .footnote), Stone.ink),                         (String(a.address[at.upperBound...]), font, Stone.quiet)])    }}/// A PICTURE OR FILE OPENED (data.html "A picture opened"; `data.media`, then `media.ensure` for its bytes): the picture,/// where it came from, and the note that nothing is kept in this app. A file opens in the phone's own viewer.struct DataMediaView: View {    let model: DataModel    let table: String    let id: String    let column: String    let close: () -> Void    @State private var read: DataRead<DataMedia> = .reading    @State private var picture: UIImage?    @State private var path: String?    @State private var away = false    @State private var viewing: URL?    var body: some View {        VStack(alignment: .leading, spacing: 12) {            switch read {            case .reading: DataWaiting().frame(minHeight: 120, alignment: .top)            case .refused(let words): DataLead(text: words)            case .read(let a):                Text(verbatim: a.name).font(DataType.sans(24, .bold, .title2)).foregroundStyle(Stone.ink)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityAddTraits(.isHeader)                if let picture {                    Image(uiImage: picture).resizable().scaledToFit()                        .frame(maxWidth: .infinity)                        .clipShape(RoundedRectangle(cornerRadius: 12))                        .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Stone.rule, lineWidth: 1))                        .accessibilityLabel(a.name)                }                if away { Text(verbatim: a.offline).font(DataType.sans(15)).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true) }                DataFlow(spacing: 10, lineSpacing: 2) {                    Text(verbatim: a.fromTitle).font(DataType.sans(15)).foregroundStyle(Stone.quiet)                    Text(verbatim: a.fromLine).font(DataType.sans(15)).foregroundStyle(Stone.ink).fixedSize(horizontal: false, vertical: true)                }                .accessibilityElement(children: .combine)                DataRule()                Text(verbatim: a.note).font(DataType.line).foregroundStyle(Stone.quiet).fixedSize(horizontal: false, vertical: true)                if a.kind != "photo", let path {                    Button { viewing = viewable(path, name: a.name) } label: { DataMarkedLabel(words: DataWords.line("media.open"), mark: .open) }                        .buttonStyle(DataButtonStyle(go: true))                        .accessibilityIdentifier("data-media-open")                }                Button(action: close) { Text(verbatim: a.close) }                    .buttonStyle(DataButtonStyle())                    .accessibilityIdentifier("data-media-close")            }        }        .task {            read = await DataRead.of { try await model.calls.media(table, id: id, column: column) }            guard let a = read.answer else { return }            path = try? await model.calls.ensure(a.key)            guard let path else { away = true; return }            if a.kind == "photo" {                picture = UIImage(contentsOfFile: path)            }        }        .quickLookPreview($viewing)        // Let go on close: the copy made for the viewer goes with the sheet.        .onDisappear { try? FileManager.default.removeItem(at: Self.folder) }    }    private static var folder: URL { FileManager.default.temporaryDirectory.appendingPathComponent("data-files", isDirectory: true) }    /// The fetched bytes under the file's own name, for the phone's viewer to know its type.    private func viewable(_ path: String, name: String) -> URL {        let dir = Self.folder        try? FileManager.default.removeItem(at: dir)        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)        let safe = name.replacingOccurrences(of: "/", with: "_")        let named = dir.appendingPathComponent(safe.isEmpty ? URL(fileURLWithPath: path).lastPathComponent : safe)        try? FileManager.default.copyItem(at: URL(fileURLWithPath: path), to: named)        return named    }}#endif