import CottonKit import CottonValues import Foundation import os import SwiftUI /// One of a tool's views, as the core reads it (`shell.fan`). public struct ToolView: Identifiable, Hashable, Sendable, Decodable { public var id: String public var label: String /// How many records its list holds; nil until the core has counted. public var count: Int? public var isDefault: Bool /// How the list draws it: "list" as slips over a table whose own face is /// a grid (Birthdays over People's polaroids), "grid" as cards; nil, the /// table's own layout. public var face: String? /// The view's own order (`ToolView::over`), which the core reads it in; /// nil, the table's. public var sort: ListSort? /// The heading of the view's list: the tool's own name, as the core /// answers it (Web pages over Documents' table, never "Documents"). public var title: String? /// The words in the list's search field, as the core says them. public var search: String? /// The view's own slip and tile (`ToolView::over`), which the core /// resolves the slip's lines by; nil, the table's. public var slip: SlipLayout? public var tile: TileLayout? /// The view's own card (`ToolView::over`): Birthdays' birthday face over /// People's table, Web pages' over Documents'; nil, the table's. public var card: DefinitionCardFace? /// The day a view kept to its next day (`period: next_day`) keeps, as /// the core finds it from its rows (YYYY-MM-DD); nil for every other /// view, and for one with no later row. Its slip says the day's weekday /// ("Monday") in the person's own language, never the declared label. public var day: String? /// A Settings chip's own screen: its row's route, which the chip's page /// is (`SettingsRing`); nil for a tool's view, whose page is its list. public var address: String? /// A card that stands LEFT of the tool's first view and reads no table /// (the core's `aside`: Account, `shell.account`): its page is its own, /// and no deck rolls over into it. public var aside = false /// What such a card's tile says under its name, the way a view's says /// a count: "Signed out", "Synced 13:46" (the core's `line`). public var line: String? /// The line over the view's deck, as the core said it (`ToolView::head`: /// Finished's "12 of 24 this year"); nil for a view with none. public var head: String? /// The view's painted tile (`ToolView::picture`, one of the core's /// `VIEW_PICTURES`): its fan tile is that picture whole, the name and /// count typed beneath its object (`ViewTile`); nil, the plain card. public var picture: String? /// A list's tile (`ListTile`): the pictures of its first members, and /// the person's own picture for it, as media keys; empty and nil for a /// fixed view, and for a list with none. public var stack: [String] = [] public var cover: String? /// The kit pictogram at the head of its tile, by reference /// (`photo:`), where its tool's fan tile names one (`FanTileLook`); /// a list's is the tile's `list` role, drawn where it has no picture and /// no members' covers of its own. public var pictogram: String? /// A card that stands for one record of the kit's own (`fan_of`: Cotton /// Story's screenplays): the record it is, whose page it opens. public var story: String? /// A card that makes a record rather than listing any (Story's New /// screenplay): the method that makes it and the hint its name field shows. public var create: Create? /// A card of Cotton Notes' fan (Notes, Untagged, Archive, Bin, a tag): /// the list it opens: the `notes.list` request that draws it. public var notes: NotesListAsk? /// A card of Cotton Chat's fan (All, People, Groups, Unread, Archived, a /// source): the filter its list opens on, as `chat.list` names it. public var chat: String? public var read: Read public struct Create: Hashable, Sendable, Decodable { public var method: String public var hint: String? } /// The `records.list` read that draws the view: a table, and the plan /// section or the columns it narrows to. public struct Read: Hashable, Sendable, Decodable { public var table: String /// The definition's empty-view wording and references to other view reads. public var empty: Empty? public struct Empty: Hashable, Sendable, Decodable { public var line: String public var counts: [String: String]? public var total: Int? public var view: String? func line(views: [ToolView]) -> String { let related = (counts ?? [:]).sorted { $0.key < $1.key }.compactMap { id, template -> String? in guard let count = views.first(where: { $0.id == id })?.count, count > 0 else { return nil } return ShellLines.line("cards", template, ["count": String(count)]) } return ([ShellLines.line("cards", line, ["view": view ?? ""])] + related).joined(separator: " ") } } /// A fresh set keeps the table's simplest empty words. A narrowed /// set uses its own words until its declared whole-table count proves empty. func emptyLine(views: [ToolView]) -> String? { let id = name.flatMap { name in name.firstIndex(of: "/").map { String(name[name.index(after: $0)...]) } } let total = views.first(where: { $0.id == id })?.read.empty?.total ?? empty?.total guard total != 0 else { return nil } return empty?.line(views: views) } /// The day plan's section the view is (`today`, `late`, `upcoming`, `done`). public var section: String? /// The columns its records hold (a group's members, an email's kind). public var filter: [String: RecordValue] /// The view the core reads the table as (`/`: its own order /// and slip, `list_records {view}`); nil for a group's members. public var name: String? /// The view's face (`ToolView.face`), carried to the list that draws it. public var face: String? /// Whether the view orders its records itself (`ToolView.sort`): the /// list keeps the order the core reads it in. public var ordersItself = false /// The view's heading, search words, slip and tile (`ToolView`), /// carried to the list that draws it. public var title: String? public var search: String? public var slip: SlipLayout? public var tile: TileLayout? public var card: DefinitionCardFace? enum CodingKeys: String, CodingKey { case table, section, empty case filter = "where" } public init(table: String, section: String? = nil, filter: [String: RecordValue] = [:], name: String? = nil) { self.table = table self.section = section self.filter = filter self.name = name } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) table = try c.decode(String.self, forKey: .table) section = try c.decodeIfPresent(String.self, forKey: .section) empty = try c.decodeIfPresent(Empty.self, forKey: .empty) filter = try c.decodeIfPresent([String: RecordValue].self, forKey: .filter) ?? [:] } } enum CodingKeys: String, CodingKey { case id, label, count, read, face, sort, title, search, slip, tile, card, day, head, picture, stack, cover, address, pictogram, aside, line, story, create, notes, chat case isDefault = "default" } public init( id: String, label: String, count: Int? = nil, isDefault: Bool = false, face: String? = nil, sort: ListSort? = nil, title: String? = nil, search: String? = nil, slip: SlipLayout? = nil, tile: TileLayout? = nil, card: DefinitionCardFace? = nil, picture: String? = nil, stack: [String] = [], cover: String? = nil, read: Read ) { self.id = id self.label = label self.count = count self.isDefault = isDefault self.face = face self.sort = sort self.title = title self.search = search self.slip = slip self.tile = tile self.card = card self.picture = picture self.stack = stack self.cover = cover self.read = read } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) label = try c.decode(String.self, forKey: .label) count = try c.decodeIfPresent(Int.self, forKey: .count) isDefault = try c.decodeIfPresent(Bool.self, forKey: .isDefault) ?? false face = try c.decodeIfPresent(String.self, forKey: .face) sort = try c.decodeIfPresent(ListSort.self, forKey: .sort) title = try c.decodeIfPresent(String.self, forKey: .title) search = try c.decodeIfPresent(String.self, forKey: .search) slip = try c.decodeIfPresent(SlipLayout.self, forKey: .slip) tile = try c.decodeIfPresent(TileLayout.self, forKey: .tile) card = try c.decodeIfPresent(DefinitionCardFace.self, forKey: .card) day = try c.decodeIfPresent(String.self, forKey: .day) head = try c.decodeIfPresent(String.self, forKey: .head) picture = try c.decodeIfPresent(String.self, forKey: .picture) stack = try c.decodeIfPresent([String].self, forKey: .stack) ?? [] cover = try c.decodeIfPresent(String.self, forKey: .cover) pictogram = try c.decodeIfPresent(String.self, forKey: .pictogram) address = try c.decodeIfPresent(String.self, forKey: .address) aside = try c.decodeIfPresent(Bool.self, forKey: .aside) ?? false line = try c.decodeIfPresent(String.self, forKey: .line) story = try c.decodeIfPresent(String.self, forKey: .story) create = try c.decodeIfPresent(Create.self, forKey: .create) notes = try? c.decodeIfPresent(NotesListAsk.self, forKey: .notes) chat = try c.decodeIfPresent(String.self, forKey: .chat) read = try c.decode(Read.self, forKey: .read) // A Schedule's "Next class day" slip says the day itself: "Monday". if let weekday = day.flatMap({ CottonDate.weekday(of: $0) }) { label = weekday } } /// The read the view's list is drawn by: named so the core reads the /// table as the view says (`/`, `list_records {view}`), with the /// view's face, order, heading, search words, slip, tile and card. func drawnRead(of tool: String) -> Read { var read = read read.name = "\(tool)/\(id)" read.face = face read.ordersItself = sort != nil read.title = title read.search = search read.slip = slip read.tile = tile read.card = card return read } /// The view that reads `table` whole — no columns narrowing it, no plan /// section, no group (Books' All): where the first of many records /// brought at once stands (`Navigator.Bringing.many`). static func whole(of table: String, in views: [ToolView]) -> ToolView? { views.first { $0.read.table == table && $0.read.filter.isEmpty && $0.read.section == nil && $0.group == nil } } /// The prefix of a view the core generates from a group of the table. static let groupPrefix = "group:" /// The group a generated view lists, by its id; nil for a fixed view. public var group: String? { id.hasPrefix(Self.groupPrefix) ? String(id.dropFirst(Self.groupPrefix.count)) : nil } /// The Tools card's two views, by the ids the core answers them under /// (row B of the deck faces, 23 Oct 2026): the tools Home shows, and /// those its arrangement hides. static let toolsShown = "shown" static let toolsHidden = "hidden" } /// A tool's fan tile as the core answers it (`shell.fan`'s, `shell.opened`'s, /// `tools.acts`' and `shell.plus`' `tile`; the core's `fan_tile`): the kit /// picture every tile on the tool's tiers is drawn on, how its words are set, /// and the pictograms of the tiles the shell makes, by role (`list`, /// `new_list`, `more`) — each picture by reference (`photo:`). The /// shell draws it and reads no manifest. public struct FanTileLook: Decodable, Equatable, Hashable, Sendable { public var stock: String? /// `courier` (typed words, the default) or `letterboard`. public var type: String public var pictures: [String: String] /// The tables its tool owns: a whole's parts under it (a series' /// seasons, a season's episodes) are drawn on this tile too. public var tables: [String]? /// Its words' ink and baselines where the kit names them /// (`fan_tile.words`); nil, the type's own. public var words: Words? /// A tile's words as its painter set them: `#rrggbb` ink, and the /// name's and the count's baselines in pixels on the 696-high stock. public struct Words: Decodable, Equatable, Hashable, Sendable { public var ink: String? public var nameBaseline: Double? public var countBaselineOne: Double? public var countBaselineTwo: Double? public init(ink: String? = nil, nameBaseline: Double? = nil, countBaselineOne: Double? = nil, countBaselineTwo: Double? = nil) { self.ink = ink self.nameBaseline = nameBaseline self.countBaselineOne = countBaselineOne self.countBaselineTwo = countBaselineTwo } enum CodingKeys: String, CodingKey { case ink case nameBaseline = "name_baseline" case countBaselineOne = "count_baseline_one" case countBaselineTwo = "count_baseline_two" } } public init(stock: String?, type: String, pictures: [String: String] = [:], tables: [String]? = nil, words: Words? = nil) { self.stock = stock self.type = type self.pictures = pictures self.tables = tables self.words = words } /// Its tiles are painted (`PaintedTile`): drawn on its stock with their /// pictograms, whatever its type, which sets only their words /// (`paintedType`). A tile naming no stock is the shell's plain card. public var painted: Bool { stock != nil } /// Its words are the letterboard's cream capitals; else courier. public var letterboard: Bool { type == "letterboard" } /// The pictogram of the shell's tile `role`. public func role(_ role: String) -> String? { pictures[role] } /// The tile of the tool owning `table` among `tiles`; none, nil. public static func owning(_ table: String, in tiles: [FanTileLook]) -> FanTileLook? { tiles.first { $0.tables?.contains(table) == true } } /// The kit pictures it names, every one. public var photos: [String] { ([stock].compactMap { $0 } + pictures.values.sorted()) } } /// The fan as the core answers it (`shell.fan`): its tiles in the fan's /// order, each with its views in the ring's order, where the fan opens and /// its first tier. The shell draws it and decides nothing of it. public struct FanAnswer: Decodable, Equatable, Sendable { public struct Tile: Decodable, Equatable, Sendable, Identifiable { public enum Kind: String, Decodable, Sendable { case home, tools, settings, tool, view } /// What the tile's picture names: an object this app ships, and the /// photo record that stands for it, either. public struct Picture: Decodable, Equatable, Sendable { public var object: String? public var photo: String? } /// The Home view a view's tile is (a group's list, a project's section). public struct View: Decodable, Equatable, Sendable { public var id: String public var name: String? public var opens: String? public var table: String? } public var key: String public var name: String public var kind: Kind /// The tool the tile is, or wears. public var tool: String? public var view: View? public var picture: Picture? public var stock: ToolCardTint? /// What every tile on its tiers is drawn as, where the tool names it /// (`fan_tile`): its stock, type and role pictures. public var tile: FanTileLook? /// Its page is a list its views ring. public var ringed: Bool /// It has no page the fan draws: its tile stands for it. public var poster: Bool /// The table its views list, where its page is the views' list (`ToolViewRoute`). public var viewsTable: String? /// Its views are counted, with their heads and the tool's lists. public var counted: Bool /// The view it stands on: the one chosen while it is still one, else the default. public var current: String? public var views: [ToolView] /// Asked for every tool: Home holds no tile of this one. public var hidden: Bool? public var id: String { key } enum CodingKeys: String, CodingKey { case key, name, kind, tool, view, picture, stock, tile, ringed, poster, counted, current, views, hidden case viewsTable = "views_table" } } public struct Opens: Decodable, Equatable, Sendable { /// `tools` or `views`. public var tier: String public var tool: String? public var view: String? } public struct Root: Decodable, Equatable, Sendable { public var id: String public var cards: [String] public var raised: String? } /// The app's face is one stream of chats (`fan.stream`, Cotton Messages): /// the tool it is the face of and its conversation table. The shell /// draws no fan and pages the chats `shell.stream` names. public struct Stream: Decodable, Equatable, Sendable { public var tool: String public var table: String } public var opens: Opens public var tiles: [Tile] public var root: Root public var stream: Stream? /// The fan opens on one tool's views (Cotton Books). public var opensOnViews: Bool { opens.tier == "views" } } /// The fan of the database shown, as the core last answered it, and the /// view chosen of each tool: the ring writes the choice and the tool's page /// reads it. Kept for the window, so a page opened again stands on the view /// it was left on. @MainActor @Observable final class ToolViews { /// What a read of the fan is asked for: another of these reads again. struct Reading: Equatable { let database: String? let focus: String? let chosen: [String: String] let revision: Int let definitions: Int? } /// The core's answer for the database shown; nil until it lands. private(set) var answer: FanAnswer? /// The view chosen, by tool. private(set) var chosen: [String: String] = [:] /// The database these views are of. private(set) var database: String? /// The tile the fan stands on, whose views the core counts. private(set) var focus: String? /// The read last asked: only its answer lands, so a slower read asked /// before it — or of the database shown before — never stands over it. private var asks = 0 /// The fan's tile `key`. func tile(_ key: String) -> FanAnswer.Tile? { answer?.tiles.first { $0.key == key } } /// The tool's views, in the ring's order. func views(of tool: String) -> [ToolView] { tile(tool)?.views ?? [] } /// The view the tool's page draws: the one chosen here since the core /// last answered, else the one the core says it stands on. func current(of tool: String) -> ToolView? { let views = views(of: tool) return views.first { $0.id == chosen[tool] } ?? views.first { $0.id == tile(tool)?.current } } func choose(_ id: String, of tool: String) { guard chosen[tool] != id else { return } chosen[tool] = id } /// The fan stands on `tool`: its views are the ones counted. func focus(on tool: String?) { guard focus != tool else { return } focus = tool } /// The view `step` along from the current one in the ring's order; nil /// past either end (door row 5's rollover goes no further). func neighbour(of tool: String, step: Int) -> ToolView? { let views = views(of: tool) guard let current = current(of: tool), let at = views.firstIndex(where: { $0.id == current.id }), views.indices.contains(at + step), !views[at + step].aside else { return nil } return views[at + step] } /// The views are of `database`: another database's answer and choices go. func show(_ database: String?) { guard database != self.database else { return } self.database = database answer = nil chosen = [:] focus = nil } /// A landed list read supplies the count for that same view. Loaded /// pages never replace its total with their own length. func counted(_ total: Int, for view: ToolView.Read?) { guard let name = view?.name, let split = name.firstIndex(of: "/"), var answer else { return } let tool = String(name[.. String { view.count.map { "\(view.label), \($0)" } ?? view.line.map { "\(view.label), \($0)" } ?? view.label } static func id(of tool: String) -> String { "views-\(tool)" } /// RULE: a person's swipe that comes to rest on a card of the views tier /// shows that view, the page following the fan as the owner's first fan /// did (lost 2 Nov, `3b8327e9ce`; Android's views arc `onRaise`). Account /// too, as on Android. Only the views tier of the tool the fan stands on: /// a rest on acts, choices or faces chooses nothing, or acts would run by /// swiping; a tap's turn and a turn nobody asked for choose nothing /// (`chose` is `ArcChoice.chooses(.settled, ...)`). static func choosesOnRest(tier: String, viewsTool: String?, chose: Bool) -> Bool { guard chose, let viewsTool else { return false } return tier == id(of: viewsTool) } static func make(tool: String, views: [ToolView], current: String?, tile: FanTileLook? = nil) -> FanTier { FanTier(id: id(of: tool), cards: views.map { .init(id: $0.id, label: $0.label, style: .leaf, count: $0.count, painted: $0.picture.map(ViewTile.asset), list: $0.group == nil ? nil : ListTilePictures(cover: $0.cover, stack: $0.stack), pictogram: $0.pictogram, detail: $0.line) }, raised: current, tile: tile) } } /// A Cotton Notes list as the core names it (`notes.list`'s request, a fan /// card's `notes`): its view (`all`, `untagged`, `archive`, `bin`, `tag`) and /// the tag a tag's list is of. public struct NotesListAsk: Codable, Hashable, Sendable { public var view: String public var tag: String? /// A hand-made list's group id, with view `list` (Notes' side page). public var list: String? public init(view: String, tag: String? = nil, list: String? = nil) { self.view = view self.tag = tag self.list = list } }