Cotton code
359 lines · 16.3 KB · SwiftRaw
// `/search` — the whole database's search, and nothing else.//// The panel was a menu you opened; this is a page you type into. **At rest there// is nothing above the docked field but the recent searches** — the pinned row,// the leased zone, the tools grid and the tag chips have all gone: Find is// search, and the launcher it had grown into is Home's "Your data" card now, so// a person who has not learned to open search can still reach Documents.//// Rules it keeps:////   * **a PLACE is a swap, a RECORD is a push** — a matched place goes somewhere//     you meant to be (back lands on the page); a search hit is something you//     looked INTO, and back belongs on the search that found it;//   * a search is REMEMBERED only when it opened something;//   * **no skeleton, anywhere.** The tools rail is static so it answers the//     instant it is typed, and the record sections are an ANSWER — a screen that//     drew grey bars for a query nobody has finished typing would be inventing//     suspense. `SearchModel` has no `isFirstRead` for that reason, and the//     absence is deliberate rather than missing.//// ## The four rules that keep the sentences honest////  1. `searchDebounceMs` (250) — long enough that typing a word is one query//     rather than five, short enough that the list still feels like it is//     following you.//  2. `searchMinLength` (2) — below this, a search over everything is a scan//     whose result nobody reads.//  3. The previous answer is HELD while the next one is computed, so the list//     never flickers empty between keystrokes (react-query's `keepPreviousData`,//     which here is simply "only assign on success").//  4. **The failure is forced away while the query does not bite.** "Nothing in//     your database matches that." is a verdict on the person's records and only//     a query that actually ran has earned it; a search nobody asked for cannot//     fail.//// ## The clock//// The debounce is measured through `ToastScheduler` — the app's one// scheduled-work seam. It is named for its first caller and is not toast-shaped:// `schedule(after:_:)` returning a cancellable ticket is exactly what a debounce// needs, and a second protocol would be a second timer with a second double to// keep honest. Nothing here touches `Task.sleep` or `Date()`.import CottonKitimport Foundation/// How long the field rests before the database is asked.public let searchDebounceMs = 250/// Below this, a search over everything is a scan whose result nobody reads./// The tools' own fields draw the same line.public let searchMinLength = 2@MainActor@Observablepublic final class SearchModel {    /// What is in the field right now. The places rail filters on THIS, because    /// the directory is static and can answer between keystrokes.    public private(set) var query = ""    /// The debounced query the hits answer — what highlighting marks.    public private(set) var settled = ""    /// The core's answer, section by section in its order; empty until the    /// query bites.    private(set) var sections: [FindSection] = []    /// The search's own failure, when it had one. `false` while the query does    /// not bite — see rule 4 in the header.    public private(set) var searchFailed = false    /// Sections opened with "See all", by id — reset with each new query,    /// because an expansion is an answer to THIS answer, not a setting.    public private(set) var expanded: [String] = []    /// Past searches that opened something, newest first.    public private(set) var recents: [String] = []    /// The kinds (in a database, when several are read) an expanded section has    /// read to their last hit — a page that came back short.    private var readToEnd: Set<String> = []    /// The expanded section's page in flight, so a second scroll to its tail    /// does not ask for the same page twice.    private var paging: String?    private let core: any CottonCalling    private let store: any SearchRecentsStore    private let scheduler: any ToastScheduler    private var ticket: (any ToastTicket)?    /// Which flight's answer is still wanted. A slower earlier search must never    /// overwrite a later one's rows.    private var generation = 0    /// The search in flight, if there is one.    ///    /// Internal rather than private so a test can AWAIT the flight instead of    /// sleeping: a `Task.sleep` in a test is a wall clock in disguise, and the    /// one thing this screen's tests need is to know when the answer landed.    private(set) var searchTask: Task<Void, Never>?    /// The databases this device holds, which the screen hands over from its    /// environment: with more than one, the search reads them all.    @ObservationIgnored var databases: DatabasesModel?    public init(        core: any CottonCalling,        recents store: any SearchRecentsStore = UserDefaultsSearchRecents(),        scheduler: any ToastScheduler = SystemToastScheduler()    ) {        self.core = core        self.store = store        self.scheduler = scheduler    }    /// True once the trimmed, debounced query is long enough to search.    public var bites: Bool { settled.count >= searchMinLength }    /// The shown database's package tools and the places, for the places    /// rail (`HomeData.findTools`). The app ships no tool (owner's ruling,    /// 21 Oct 2026), so until `tools.list` and the catalogue are read the    /// rail holds the places alone.    ///    /// **No row carries a count, and that is exact rather than a shortcut.**    /// Find draws no figure — the rail is a chip with a name and a glyph. The    /// rail matches on a tool's NAME, which no count can change.    public private(set) var tools: [FindTool] = HomeData.findTools([], definitions: TableDefinitions([]))    /// The list, as data.    var items: [SearchItem] {        searchItems(            tools: tools,            recents: recents,            sections: sections,            expanded: expanded,            pages: places,            query: query        )    }    // ── Reading ──────────────────────────────────────────────────────────    /// The recents, off this device. Called on appear; there is nothing else to    /// load, because Find asks the database nothing until it is typed into.    public func load() {        recents = store.load()        Task { await readPlaces() }        Task { await readTools() }    }    /// The database's package tools, with the catalogue their routes are    /// read against (`BoardLayout.route(for:in:)`); a read that fails leaves    /// the places alone.    private func readTools() async {        guard let catalogue = try? await DefinitionCatalogues.shared.catalogue(core),              let packages = try? await ToolPackageCatalog.read(core) else { return }        let definitions = TableDefinitions(DefinitionCatalogue.tables(catalogue).tables)        tools = HomeData.findTools(packages.tools.map(\.definition), definitions: definitions)    }    /// The device and database pages' places, off the shown database's own    /// definitions (`PageFind`): none until they are read, none where no tool    /// draws those tables.    private(set) var places: [PageFind.Place] = []    private func readPlaces() async {        guard let catalogue = try? await DefinitionCatalogues.shared.catalogue(core) else { return }        let tables = DefinitionCatalogue.tables(catalogue).tables.filter { ["device", "database"].contains($0.id) }        places = PageFind.places(TableDefinitions(tables))    }    /// A keystroke, a pasted line, or a recent tapped — one door, so the    /// expansion reset and the debounce cannot be forgotten at one of them.    public func type(_ next: String) {        query = next        expanded = []        readToEnd = []        paging = nil        let value = next.trimmingCharacters(in: .whitespacesAndNewlines)        ticket?.cancel()        ticket = scheduler.schedule(after: Double(searchDebounceMs) / 1000) { [weak self] in            self?.settle(value)        }    }    /// "See all" — the section opens in place and reads its next page; its    /// tail asks for the one after (`more`) until every hit is in hand.    public func expand(_ section: String, page: Int) {        guard !expanded.contains(section) else { return }        expanded.append(section)        more(section, page: page)    }    /// The expanded section's next page: a built-in section's kinds in the    /// order the core names them (`kinds`), an imported section's table, each    /// in one database at a time until a page comes back short (architect, 15    /// Oct 2026: each section answers its first page and its exact total;    /// expanding pages through every hit).    public func more(_ id: String, page: Int) {        guard expanded.contains(id), paging == nil, bites,              let section = sections.first(where: { $0.id == id }) else { return }        let held = section.hits        let databases = held.map(\.database).reduce(into: [FeedRowDatabase?]()) { seen, database in            if !seen.contains(where: { $0?.databaseId == database?.databaseId }) { seen.append(database) }        }        let lanes: [String?] = section.defined ? [nil] : section.kinds.map(Optional.some)        for kind in lanes {            for database in databases.isEmpty ? [nil] : databases {                let key = "\(id)|\(kind ?? "")|\(database?.databaseId ?? "")"                guard !readToEnd.contains(key) else { continue }                let offset = held.filter { (kind == nil || $0.kind == kind) && $0.database?.databaseId == database?.databaseId }.count                paging = id                let flight = generation                let request = SearchRequest(                    query: settled, database: database?.databaseId, kind: kind, offset: offset, limit: page,                    channel: "search", table: section.defined ? id : nil                )                searchTask = Task { [weak self] in                    await self?.page(request, key: key, section: id, database: database, size: page, flight: flight)                }                return            }        }    }    // ── Opening ──────────────────────────────────────────────────────────    /// A place: the route to REPLACE with, so the stack does not grow. Back from    /// where you land pops to the page, never to a keyboard you already used.    public func openPlace(_ chip: SearchPlaceChip) -> Route? {        Route.parse(chip.tool.path)    }    /// A hit: the route to PUSH (the core's `opens`), and the search that    /// found it is remembered on the way.    ///    /// The recents keep the DEBOUNCED words the hits answered, so a half-typed    /// prefix never lands in the list. `nil` for a hit that opens nothing, and    /// NOTHING is remembered for one of those: the search did not open anything.    func open(_ hit: FindHit) -> Route? {        guard let route = hit.opens else { return nil }        if !settled.isEmpty {            recents = rememberRecent(recents, settled)            store.save(recents)        }        return route    }    public func clearRecents() {        recents = []        store.save(recents)    }    // ── The search itself ────────────────────────────────────────────────    private func settle(_ value: String) {        ticket = nil        guard value != settled else { return }        settled = value        generation += 1        readToEnd = []        paging = nil        guard bites else {            // A query that does not bite has no answer and cannot have failed.            sections = []            searchFailed = false            return        }        let flight = generation        searchTask = Task { [weak self] in await self?.search(value, flight: flight) }    }    private func search(_ value: String, flight: Int) async {        do {            // Each section's first page and its exact total; an expanded            // section reads the rest a page at a time.            let request = SearchRequest(                query: value,                database: FeedRowDatabase.scope(holding: databases?.held.count ?? 0),                limit: searchSectionCollapsed,                channel: "search"            )            let read = try await core.callJSON(CottonMethod.readFind, request)            guard flight == generation else { return }            sections = FindSection.all(read)            searchFailed = false        } catch {            guard flight == generation else { return }            // The rows already in hand stay. A refusal is a fact about THIS            // round trip, and blanking a list somebody is reading to say so            // costs them the answer they already had.            searchFailed = true        }    }    /// One page of one kind (or one imported table) in one database, placed    /// after the section's hits it continues.    private func page(_ request: SearchRequest, key: String, section id: String, database: FeedRowDatabase?, size: Int, flight: Int) async {        defer { if flight == generation { paging = nil } }        do {            let read = try await core.callJSON(CottonMethod.readFind, request)            guard flight == generation, let at = sections.firstIndex(where: { $0.id == id }) else { return }            // A page read from one database names it on every hit.            let next = (FindSection.all(read).first { $0.id == id }?.hits ?? []).map { hit in                var hit = hit                hit.database = hit.database ?? database                return hit            }            if next.count < size { readToEnd.insert(key) }            let held = sections[at].hits            let after = held.lastIndex {                (request.kind == nil || $0.kind == request.kind) && $0.database?.databaseId == database?.databaseId            }.map { $0 + 1 } ?? held.endIndex            sections[at].hits.insert(contentsOf: next, at: after)        } catch {            guard flight == generation else { return }            searchFailed = true        }    }}// MARK: - What this screen asks for/// `read.find`'s request — `{query}`, and `database: "all"` when this device/// holds more than one database.////// `phone/reads.rs::find` reads `args["query"]` as a string and treats anything/// else as empty. The DEBOUNCE and the two-character floor are this file's: the/// crate happily searches for "a", and a field somebody is typing into must not/// ask it to. `database` is left out when nil, so with one database held the/// request is `{query}` exactly as before.struct SearchRequest: Encodable, Sendable {    var query: String    var database: String?    /// The reader's zone, so a hit's day (`when`) is the device's day — the    /// same day its page says — never the workspace's or UTC's.    var timezone: String    /// What the search is narrowed to: `"mail"` is the box inside Mail, which    /// answers mail alone (mailsearch). Left out — everything — when nil.    var scope: String?    /// One kind alone, as an expanded section pages through it.    var kind: String?    /// The hits of each kind skipped before this page.    var offset: Int?    /// The hits per kind; left out, every hit (mail's own list pages the ids).    var limit: Int?    /// A newer search on the channel stops this one in the core, so fast    /// typing never queues stale SQL (architect, 15 Oct 2026).    var channel: String?    /// One imported table alone, as its expanded section pages through it.    var table: String?    init(        query: String, database: String? = nil, timezone: String = TimeZone.current.identifier,        scope: String? = nil, kind: String? = nil, offset: Int? = nil, limit: Int? = nil,        channel: String? = nil, table: String? = nil    ) {        self.query = query        self.database = database        self.timezone = timezone        self.scope = scope        self.kind = kind        self.offset = offset        self.limit = limit        self.channel = channel        self.table = table    }}