Cotton code
70 lines · 2.8 KB · SwiftRaw
// One table's list under one project the route names — a project's own Todos// (`/projects/[slug]/todos`, `/todos/done?project=<id>`). Projects are a filter// (rebuild note 7b95efa4): the list is the table's own list with that project// as the current one, never a second screen.//// A route carries the project's id or its slug, and this resolves either, the// id first, as the crate always has. A project that resolves to nothing// narrows to NOTHING — it says so — and never to the whole table.import CottonValuesimport SwiftUIpublic struct ProjectListRoute: View {    enum Found: Equatable {        case project(String)        case none        case failed    }    private let table: String    private let project: String    private let onOpen: ((TableRecord) -> Void)?    @Environment(\.records) private var store    @State private var found: Found?    /// - Parameter project: the project's id or its slug.    public init(table: String, project: String, onOpen: ((TableRecord) -> Void)? = nil) {        self.table = table        self.project = project        self.onOpen = onOpen    }    public var body: some View {        switch found {        case .project(let id)?:            TableListRoute(table: table, onOpen: onOpen)                .environment(\.currentProject, id)        case .none?:            PaperScreen {                QuietState(title: ShellLines.line("record", "project.not_found"), message: ShellLines.line("record", "project.not_found_message"))            }        case .failed?:            PaperScreen {                QuietState(                    title: ShellLines.line("record", "project.unreadable"), message: ShellLines.line("empty", "unchanged"),                    actionLabel: ShellLines.line("record", "try_again"), action: { found = nil })            }        case nil:            PaperScreen { EmptyView() }  // no loader: the rows are local and land next frame                .task(id: project) { found = await Self.resolve(project, in: store) }        }    }    /// The project's id for `reference`: a project with that id, else one    /// with that slug.    static func resolve(_ reference: String, in store: (any Records)?) async -> Found {        guard let store, !reference.isEmpty else { return .failed }        do {            guard let projects = try await store.tableDefinitions().first(where: { $0.role == .project }) else { return .none }            if let byID = try await store.get(table: projects.id, id: reference) { return .project(byID.id) }            if let slug = projects.scopeBy, let bySlug = try await store.first(table: projects.id, column: slug, equals: .text(reference)) {                return .project(bySlug.id)            }            return .none        } catch {            return .failed        }    }}