Cotton code
124 lines · 5.4 KB · SwiftRaw
import CottonKitimport CottonValuesimport SwiftUI/// Home's Recent shelf (board part `recent`): the person's last opens, newest/// first, one per tool page or record (`read.recentVisits`), drawn as the same/// tiles Home draws and the record's own slip. It is a shelf beside the tiles,/// never an order for them: a tile tapped here opens as it does on the grid/// (on a fan Home, the fan turns to it), and nothing here moves a tile.struct RecentShelf: View {    let heading: String    let limit: Int    /// Home's tiles, to find a visited tool's own tile by.    let tiles: [GridTile]    /// Visits are the person's own: drawn on the personal database's Home only.    let shown: Bool    let onTile: (GridTile) -> Void    let onRecord: (TableRecord, TableDefinition) -> Void    @Environment(\.cottonCore) private var core    @Environment(\.records) private var store    @Environment(\.tableDefinitions) private var definitions    @Environment(\.cottonSync) private var sync    @Environment(\.theme) private var theme    @State private var entries: [RecentEntry] = []    var body: some View {        Group {            if shown, !entries.isEmpty {                VStack(alignment: .leading, spacing: BoardPageKnobs.boardSectionRowGap) {                    ProjectSectionHeading(title: heading, count: nil)                    ScrollView(.horizontal, showsIndicators: false) {                        HStack(alignment: .top, spacing: RecordListSurfaceKnobs.paperGap) {                            ForEach(entries) { entry in item(entry) }                        }                    }                    .scrollClipDisabled()                }                .accessibilityElement(children: .contain)                .accessibilityIdentifier("board-recent")            }        }        .task(id: Reading(shown: shown, local: sync?.localWrites ?? 0, foreign: sync?.foreignRevision ?? 0, limit: limit)) {            guard shown, let core, let visits = try? await core.recentVisits(limit: limit), !Task.isCancelled else { return }            var landed: [RecentEntry] = []            for visit in visits {                if let entry = await RecentEntry.resolve(visit, tiles: tiles, definitions: definitions.all, store: store) {                    landed.append(entry)                }            }            if !Task.isCancelled { entries = landed }        }    }    private struct Reading: Hashable {        var shown: Bool        var local: Int        var foreign: Int        var limit: Int    }    @ViewBuilder private func item(_ entry: RecentEntry) -> some View {        switch entry.kind {        case .tile(let tile):            Button { onTile(tile) } label: {                ToolCard(key: tile.stockKey, name: tile.name, picture: tile.picture, stock: tile.stock,                         now: Calendar.current.startOfDay(for: Date()), width: RecentShelfKnobs.tileWidth)            }            .buttonStyle(MotionButtonStyle())            .accessibilityIdentifier("recent-tool-\(tile.key)")        case .record(let record, let definition):            SectionFace(definition: definition, records: [record], headed: false, onSlip: { onRecord($0, definition) })                .frame(width: theme.scale[.shelfTileMinW], alignment: .topLeading)                .accessibilityIdentifier("recent-record-\(record.id)")        }    }}/// One thing on the shelf, resolved to what draws it.struct RecentEntry: Identifiable {    enum Kind {        case tile(GridTile)        case record(TableRecord, TableDefinition)    }    let id: String    let kind: Kind    /// A visited tool is its own tile, found by its view or its key; a visited    /// record is read from the tool's tables. Nil when it is gone — a tile    /// taken off Home, a record deleted — so the shelf never draws a blank.    static func resolve(_ visit: RecentVisit, tiles: [GridTile], definitions: [TableDefinition], store: (any Records)?) async -> RecentEntry? {        switch visit.target {        case .tool:            guard let tile = tile(for: visit, in: tiles) else { return nil }            return RecentEntry(id: "tool:\(visit.view)", kind: .tile(tile))        case .record:            guard let id = visit.record, let store else { return nil }            for definition in tables(for: visit.tool, in: definitions) {                if let record = try? await store.get(table: definition.id, id: id) {                    return RecentEntry(id: "record:\(definition.id)/\(id)", kind: .record(record, definition))                }            }            return nil        }    }    static func tile(for visit: RecentVisit, in tiles: [GridTile]) -> GridTile? {        tiles.first { "tool/\($0.key)" == visit.view } ?? tiles.first { $0.key == visit.tool }    }    /// The tables a visit's tool names: a usage row holds the tool's key    /// (`homeUsage`), or a table's own id where the table is no tool's.    static func tables(for tool: String, in definitions: [TableDefinition]) -> [TableDefinition] {        if let own = definitions.first(where: { $0.id == tool }) { return [own] }        guard let home = definitions.first(where: { $0.tool?.key == tool }) else { return [] }        let named = home.tool?.tables ?? []        let tables = named.compactMap { name in definitions.first { $0.id == name } }        return tables.isEmpty ? [home] : tables    }}enum RecentShelfKnobs {    static let tileWidth: CGFloat = 96}