Cotton code
50 lines · 2.6 KB · SwiftRaw
// A record's related rows, opened under the view its tool partitions them by// (`Route.tableList`'s `view`). A group card's own route is the core's// (`shell.deck`'s `group`).import CottonKitimport CottonValuesimport Foundationenum GroupOpening {    /// A counted file-index row opens the same partitioned deck, when declared.    static func related(_ related: RelatedRecords, record: TableRecord, title: String?,                        tables: [TableDefinition], tools: [ToolDefinition]) -> Route? {        guard let column = related.column else { return nil }        let view = partitioned(over: related.table, by: column, tables: tables, tools: tools)        return .tableList(table: related.table,            filter: FilteredListOpening.encoded(related.whereValues(parent: record)),            title: FilteredListOpening.title(view?.view.label ?? related.label, of: title),            query: nil, view: view?.name)    }    /// Every tool's declared views with the tool they are named under: each    /// home table's tool (keyed by its key, else the table's id), then each    /// installed tool's.    private static func views(tables: [TableDefinition], tools: [ToolDefinition]) -> [(tool: String, view: DefinitionToolView)] {        let homes = tables.flatMap { home in (home.tool?.views ?? []).map { (home.tool?.key ?? home.id, $0) } }        return homes + tools.flatMap { tool in tool.views.map { (tool.id, $0) } }    }    /// The view a tool partitions `table` by `column`, named `<tool>/<id>`.    static func partitioned(        over table: String, by column: String, tables: [TableDefinition], tools: [ToolDefinition]    ) -> (name: String, view: DefinitionToolView)? {        views(tables: tables, tools: tools)            .first { $0.view.partition == column && $0.view.read["table"] == .string(table) }            .map { ("\($0.tool)/\($0.view.id)", $0.view) }    }    /// The read a list draws for the view `name` names (`<tool>/<id>`), as    /// a ring's view is drawn (`ToolView.drawnRead`); nil when no tool has it.    static func read(named name: String, tables: [TableDefinition], tools: [ToolDefinition]) -> ToolView.Read? {        guard let (tool, view) = views(tables: tables, tools: tools).first(where: { "\($0.tool)/\($0.view.id)" == name }),              let data = try? JSONEncoder().encode(view.read),              let read = try? JSONDecoder().decode(ToolView.Read.self, from: data)        else { return nil }        return ToolView(            id: view.id, label: view.label, face: view.face, sort: view.sort,            slip: view.slip, tile: view.tile, card: view.card, read: read        ).drawnRead(of: tool)    }}