// A link names its database.//// A record lives in one database, and two databases may hold a record with// the same id, so a link that opens a record says which database it is in:// `database=<id>` as one more query item on the same URL. `Route` stays what// it was — every case, every path, every parser — and this wrapper is what the// URL layer produces and consumes. A link written with no database is// byte-for-byte the link it always was, and an old link still opens.//// Where a link lands is decided once, in `DatabaseLinkArrival.decide`: a// database this device holds is shown in the window the link arrived in before// the route is pushed; one it does not hold opens nothing; and a link with no// database opens in the only database that could hold it, or asks.importFoundation/// A route, and the database it opens in.publicstructDatabaseLink: Equatable, Sendable {/// The database the route opens in. Nil for a link written before links/// named one, or for a screen that is no single database's.publicvar database: String?publicvar route: Routepublicinit(database: String? = nil, route: Route) {self.database = databaseself.route = route }/// The query item's name.publicstaticlet queryKey = "database"/// The path this link is reached by: the route's own path, then/// `database=<id>` when there is a database. With none, exactly/// `route.path`.publicvar path: String {Self.appending(database, to: route.path) }/// `path` with `database=<id>` added after any query it already has./// Unchanged for no database.publicstaticfunc appending(_ database: String?, to path: String) -> String {guardlet database, !database.isEmpty else { return path }let item = "\(queryKey)=\(Route.esc(database))"return path + (path.contains("?") ? "&" : "?") + item }/// Read a path back. Nil when the route does not parse — the database/// alone opens nothing.publicstaticfunc parse(_ text: String) -> DatabaseLink? {guardlet route = Route.parse(text) else { returnnil }returnDatabaseLink(database: database(inQuery: text), route: route) }/// Where a `tinmen-cotton://` (or `cottondev://`) link lands — the route/// `Route.deepLink` reads, and the database the URL names.publicstaticfunc deepLink(_ url: URL) -> DatabaseLink? {guardlet route = Route.deepLink(url) else { returnnil }returnDatabaseLink(database: database(inQuery: "?" + (url.query ?? "")), route: route) }privatestaticfunc database(inQuery text: String) -> String? {let (_, query) = Route.splitQuery(text)guardlet database = query[queryKey], !database.isEmpty else { returnnil }return database }}extensionRoute {/// The project a `/projects/<slug>/…` route names, by slug.publicvar projectSlug: String? {switchself {case .projectsSlug(let slug), .projectsSlugSection(let slug, _), .projectsBrand(let slug), .projectsCode(let slug), .projectsFeedback(let slug), .projectsFeedbackReport(let slug, _), .projectsMemory(let slug), .projectsTodos(let slug):return slugdefault:returnnil } }}/// What a link does when it arrives in a window.publicenumDatabaseLinkArrival: Equatable, Sendable {/// Show `database` in this window, then open `route`.caseopen(database: String, route: Route)/// The link names a database this device does not hold: nothing opens.case notHeld(database: String)/// No database named, and more than one held database could hold the/// record. `among` is the held databases, the shown one first.case ask(route: Route, among: [String])/// No database named and no held list to choose from: the route opens in/// this window as it always has.case here(route: Route)/// Where `link` opens, given the databases this device holds and the one/// this window shows.////// A named database wins; then a `/projects/<slug>` route's own project/// database, when one held database is that project; then, with no/// database, the only one held — or, with several, `.ask`.publicstaticfunc decide(link: DatabaseLink, held: [HeldDatabase], shown: String?) -> DatabaseLinkArrival {iflet database = link.database {guard held.contains(where: { $0.databaseId == database }) else { return .notHeld(database: database) }return .open(database: database, route: link.route) }iflet project = projectDatabase(for: link.route, in: held) {return .open(database: project.databaseId, route: link.route) }switch held.count {case0:return .here(route: link.route)case1:return .open(database: held[0].databaseId, route: link.route)default:let order = DatabaseOrder.shown(held).map(\.databaseId)let first = order.filter { $0 == shown }return .ask(route: link.route, among: first + order.filter { $0 != shown }) } }/// The held project database a `/projects/<slug>/…` route names: the one/// whose id is the slug, or whose name makes that slug. Nil for any other/// route, for no match, and for two matches — a guess between two/// databases is not made here.publicstaticfunc projectDatabase(for route: Route, in held: [HeldDatabase]) -> HeldDatabase? {guardlet slug = route.projectSlug?.lowercased(), !slug.isEmpty else { returnnil }let matches = held.filter { !$0.isPersonal && ($0.databaseId == slug || slugOf($0.name) == slug) }return matches.count == 1 ? matches[0] : nil }/// A name in a project slug's alphabet: lowercase ASCII letters and/// digits, every other run one dash, no dash at either edge — the rule/// `cotton-core`'s `mint_project_slug` makes an address with.staticfunc slugOf(_ name: String) -> String {var out = ""var pendingDash = falsefor character in name.lowercased() {if character.isASCII && (character.isLetter || character.isNumber) {if pendingDash && !out.isEmpty { out.append("-") } pendingDash = false out.append(character) } else { pendingDash = true } }return out }}extensionDatabaseLinkArrival {/// The record `route` opens, as `read.record` (`get_record`) names it —/// its kind and id — or nil for a route that opens no record it reads./// What a link that names no database is looked up by.publicstaticfunc record(of route: Route) -> (kind: RecordKind, id: String)? {ifcase .calendarEvent(let id, _, _) = route { return id.isEmpty ? nil : (.event, id) }guardlet id = route.recordId, !id.isEmpty else { returnnil }return lookedUp.first { Route.record($0, id) == route }.map { ($0, id) } }/// The kinds `get_record` reads, each with a page of its own.staticlet lookedUp: [RecordKind] = [ .todo, .note, .person, .location, .meeting, .document, .memory, .transaction, .thought, ]/// Where an `.ask` lands once each of `among` has said whether it holds/// the link's record (`holding`): the only one that does opens; with/// none or several, the window keeps the database it shows.publicstaticfunc settle(route: Route, among: [String], holding: [String]) -> DatabaseLinkArrival {let holders = among.filter(holding.contains)return holders.count == 1 ? .open(database: holders[0], route: route) : .ask(route: route, among: among) }}