importCottonKitimportCottonValuesimportFoundationimport osimportSwiftUI/// One of a tool's views, as the core reads it (`shell.fan`).publicstructToolView: Identifiable, Hashable, Sendable, Decodable {publicvar id: Stringpublicvar label: String/// How many records its list holds; nil until the core has counted.publicvar count: Int?publicvar 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.publicvar face: String?/// The view's own order (`ToolView::over`), which the core reads it in;/// nil, the table's.publicvar 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").publicvar title: String?/// The words in the list's search field, as the core says them.publicvar search: String?/// The view's own slip and tile (`ToolView::over`), which the core/// resolves the slip's lines by; nil, the table's.publicvar slip: SlipLayout?publicvar tile: TileLayout?/// The view's own card (`ToolView::over`): Birthdays' birthday face over/// People's table, Web pages' over Documents'; nil, the table's.publicvar 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.publicvar 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.publicvar 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.publicvar 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`).publicvar 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.publicvar 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.publicvar 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.publicvar stack: [String] = []publicvar cover: String?/// The kit pictogram at the head of its tile, by reference/// (`photo:<sha256>`), 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.publicvar 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.publicvar 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.publicvar 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.publicvar 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.publicvar chat: String?publicvar read: ReadpublicstructCreate: Hashable, Sendable, Decodable {publicvar method: Stringpublicvar hint: String? }/// The `records.list` read that draws the view: a table, and the plan/// section or the columns it narrows to.publicstructRead: Hashable, Sendable, Decodable {publicvar table: String/// The definition's empty-view wording and references to other view reads.publicvar empty: Empty?publicstructEmpty: Hashable, Sendable, Decodable {publicvar line: Stringpublicvar counts: [String: String]?publicvar total: Int?publicvar view: String?func line(views: [ToolView]) -> String {let related = (counts ?? [:]).sorted { $0.key < $1.key }.compactMap { id, template -> String? inguardlet count = views.first(where: { $0.id == id })?.count, count > 0else { returnnil }returnShellLines.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?.totalguard total != 0else { returnnil }return empty?.line(views: views) }/// The day plan's section the view is (`today`, `late`, `upcoming`, `done`).publicvar section: String?/// The columns its records hold (a group's members, an email's kind).publicvar filter: [String: RecordValue]/// The view the core reads the table as (`<tool>/<id>`: its own order/// and slip, `list_records {view}`); nil for a group's members.publicvar name: String?/// The view's face (`ToolView.face`), carried to the list that draws it.publicvar face: String?/// Whether the view orders its records itself (`ToolView.sort`): the/// list keeps the order the core reads it in.publicvar ordersItself = false/// The view's heading, search words, slip and tile (`ToolView`),/// carried to the list that draws it.publicvar title: String?publicvar search: String?publicvar slip: SlipLayout?publicvar tile: TileLayout?publicvar card: DefinitionCardFace?enumCodingKeys: String, CodingKey {case table, section, emptycase filter = "where" }publicinit(table: String, section: String? = nil, filter: [String: RecordValue] = [:], name: String? = nil) {self.table = tableself.section = sectionself.filter = filterself.name = name }publicinit(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) ?? [:] } }enumCodingKeys: 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, chatcase isDefault = "default" }publicinit( 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 = idself.label = labelself.count = countself.isDefault = isDefaultself.face = faceself.sort = sortself.title = titleself.search = searchself.slip = slipself.tile = tileself.card = cardself.picture = pictureself.stack = stackself.cover = coverself.read = read }publicinit(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".iflet 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 (`<tool>/<id>`, `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 = cardreturn 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`).staticfunc 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.staticlet groupPrefix = "group:"/// The group a generated view lists, by its id; nil for a fixed view.publicvar 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.staticlet toolsShown = "shown"staticlet 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:<sha256>`). The/// shell draws it and reads no manifest.publicstructFanTileLook: Decodable, Equatable, Hashable, Sendable {publicvar stock: String?/// `courier` (typed words, the default) or `letterboard`.publicvar type: Stringpublicvar 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.publicvar tables: [String]?/// Its words' ink and baselines where the kit names them/// (`fan_tile.words`); nil, the type's own.publicvar 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.publicstructWords: Decodable, Equatable, Hashable, Sendable {publicvar ink: String?publicvar nameBaseline: Double?publicvar countBaselineOne: Double?publicvar countBaselineTwo: Double?publicinit(ink: String? = nil, nameBaseline: Double? = nil, countBaselineOne: Double? = nil, countBaselineTwo: Double? = nil) {self.ink = inkself.nameBaseline = nameBaselineself.countBaselineOne = countBaselineOneself.countBaselineTwo = countBaselineTwo }enumCodingKeys: String, CodingKey {case inkcase nameBaseline = "name_baseline"case countBaselineOne = "count_baseline_one"case countBaselineTwo = "count_baseline_two" } }publicinit(stock: String?, type: String, pictures: [String: String] = [:], tables: [String]? = nil, words: Words? = nil) {self.stock = stockself.type = typeself.pictures = picturesself.tables = tablesself.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.publicvar painted: Bool { stock != nil }/// Its words are the letterboard's cream capitals; else courier.publicvar letterboard: Bool { type == "letterboard" }/// The pictogram of the shell's tile `role`.publicfunc role(_ role: String) -> String? { pictures[role] }/// The tile of the tool owning `table` among `tiles`; none, nil.publicstaticfunc owning(_ table: String, in tiles: [FanTileLook]) -> FanTileLook? { tiles.first { $0.tables?.contains(table) == true } }/// The kit pictures it names, every one.publicvar 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.publicstructFanAnswer: Decodable, Equatable, Sendable {publicstructTile: Decodable, Equatable, Sendable, Identifiable {publicenumKind: 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.publicstructPicture: Decodable, Equatable, Sendable {publicvar object: String?publicvar photo: String? }/// The Home view a view's tile is (a group's list, a project's section).publicstructView: Decodable, Equatable, Sendable {publicvar id: Stringpublicvar name: String?publicvar opens: String?publicvar table: String? }publicvar key: Stringpublicvar name: Stringpublicvar kind: Kind/// The tool the tile is, or wears.publicvar tool: String?publicvar view: View?publicvar picture: Picture?publicvar stock: ToolCardTint?/// What every tile on its tiers is drawn as, where the tool names it/// (`fan_tile`): its stock, type and role pictures.publicvar tile: FanTileLook?/// Its page is a list its views ring.publicvar ringed: Bool/// It has no page the fan draws: its tile stands for it.publicvar poster: Bool/// The table its views list, where its page is the views' list (`ToolViewRoute`).publicvar viewsTable: String?/// Its views are counted, with their heads and the tool's lists.publicvar counted: Bool/// The view it stands on: the one chosen while it is still one, else the default.publicvar current: String?publicvar views: [ToolView]/// Asked for every tool: Home holds no tile of this one.publicvar hidden: Bool?publicvar id: String { key }enumCodingKeys: String, CodingKey {case key, name, kind, tool, view, picture, stock, tile, ringed, poster, counted, current, views, hiddencase viewsTable = "views_table" } }publicstructOpens: Decodable, Equatable, Sendable {/// `tools` or `views`.publicvar tier: Stringpublicvar tool: String?publicvar view: String? }publicstructRoot: Decodable, Equatable, Sendable {publicvar id: Stringpublicvar cards: [String]publicvar 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.publicstructStream: Decodable, Equatable, Sendable {publicvar tool: Stringpublicvar table: String }publicvar opens: Openspublicvar tiles: [Tile]publicvar root: Rootpublicvar stream: Stream?/// The fan opens on one tool's views (Cotton Books).publicvar 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@ObservablefinalclassToolViews {/// What a read of the fan is asked for: another of these reads again.structReading: Equatable {let database: String?let focus: String?let chosen: [String: String]let revision: Intlet 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.privatevar 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)guardlet current = current(of: tool), let at = views.firstIndex(where: { $0.id == current.id }), views.indices.contains(at + step), !views[at + step].aside else { returnnil }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?) {guardlet name = view?.name, let split = name.firstIndex(of: "/"), var answer else { return }let tool = String(name[..<split]), id = String(name[name.index(after: split)...])guardlet at = answer.tiles.firstIndex(where: { $0.key == tool }),let index = answer.tiles[at].views.firstIndex(where: { $0.id == id }), answer.tiles[at].views[index].count != total else { return } answer.tiles[at].views[index].count = totalself.answer = answer }/// The core's answer, held where it is still the read that lands.func take(_ answer: FanAnswer) {guardself.answer != answer else { return }self.answer = answer }/// Reads the fan of `database` again, standing on `tool` (`focus`): the/// views are that database's from the ask on (`show`), so the read lands/// whichever comes first,/// the ask or the window's own word that it shows `database`. An answer/// to a read asked since, or of another database, is dropped; a read/// that fails throws, for the caller to say.////// RULE (Cinemas leftovers, 7 Nov 2026: a fresh install stood ~10 s on a/// tools tier of one tile): the read was asked for the database it/// carried in its key but checked against the one `show` had last been/// told, so a read asked a frame before the window named the database it/// shows was dropped when it landed, or cleared just after it did, and/// nothing asked again until the data next moved.func reload(core: (any CottonCalling)?, database: String?, standing tool: String? = nil) asyncthrows {guardlet core else { return } show(database) focus(on: tool) asks += 1let asked = askslet answer: FanAnswerdo { answer = tryawait core.call(CottonMethod.shellFan,Ask(chosen: chosen, tool: focus, timezone: TimeZone.current.identifier), as: FanAnswer.self) } catch {Self.log.notice("fan read \(asked, privacy: .public) of \(database ?? "-", privacy: .public) failed: \(String(describing: error), privacy: .public)")throw error } #if os(iOS)// Cotton Chat's cards come from the core's own fan (`chat.list`), read once.awaitChatBooks.prime(core: core) #endiflet landed = asks == asked && self.database == databaseSelf.log.notice("fan read \(asked, privacy: .public) of \(database ?? "-", privacy: .public) \(landed ? "landed" : "dropped", privacy: .public): opens \(answer.opens.tier, privacy: .public) \(answer.opens.tool ?? "-", privacy: .public), \(answer.tiles.count) tiles, views \(answer.tiles.map { "\($0.key):\($0.views.count)" }.joined(separator: ""), privacy: .public)")guard landed else { return } #if os(iOS) take(ChatBooks.fan(answer)) #else take(answer) #endif }/// Reads the fan again as it stands: of the database it holds, on the/// tile it stands on (a page's own reread after its rows moved).func reload(core: (any CottonCalling)?) asyncthrows {tryawait reload(core: core, database: database, standing: focus) }/// Each read of the fan and what it answered (`com.cottondb.fan`, `read`).privatestaticlet log = Logger(subsystem: "com.cottondb.fan", category: "read")privatestructAsk: Encodable, Sendable {let chosen: [String: String]let tool: String?let timezone: String }}/// Views use the same cards and arc as every other fan tier: one card per/// view, in the order the core answered them.enumViewTier {staticfunc spoken(_ view: ToolView) -> String { view.count.map { "\(view.label), \($0)" } ?? view.line.map { "\(view.label), \($0)" } ?? view.label }staticfunc 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, ...)`).staticfunc choosesOnRest(tier: String, viewsTool: String?, chose: Bool) -> Bool {guard chose, let viewsTool else { returnfalse }return tier == id(of: viewsTool) }staticfunc 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.publicstructNotesListAsk: Codable, Hashable, Sendable {publicvar view: Stringpublicvar tag: String?/// A hand-made list's group id, with view `list` (Notes' side page).publicvar list: String?publicinit(view: String, tag: String? = nil, list: String? = nil) {self.view = viewself.tag = tagself.list = list }}