Cotton code
173 lines · 7.7 KB · SwiftRaw
// 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.import Foundation/// A route, and the database it opens in.public struct DatabaseLink: 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.    public var database: String?    public var route: Route    public init(database: String? = nil, route: Route) {        self.database = database        self.route = route    }    /// The query item's name.    public static let 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`.    public var path: String {        Self.appending(database, to: route.path)    }    /// `path` with `database=<id>` added after any query it already has.    /// Unchanged for no database.    public static func appending(_ database: String?, to path: String) -> String {        guard let 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.    public static func parse(_ text: String) -> DatabaseLink? {        guard let route = Route.parse(text) else { return nil }        return DatabaseLink(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.    public static func deepLink(_ url: URL) -> DatabaseLink? {        guard let route = Route.deepLink(url) else { return nil }        return DatabaseLink(database: database(inQuery: "?" + (url.query ?? "")), route: route)    }    private static func database(inQuery text: String) -> String? {        let (_, query) = Route.splitQuery(text)        guard let database = query[queryKey], !database.isEmpty else { return nil }        return database    }}extension Route {    /// The project a `/projects/<slug>/…` route names, by slug.    public var projectSlug: String? {        switch self {        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 slug        default:            return nil        }    }}/// What a link does when it arrives in a window.public enum DatabaseLinkArrival: Equatable, Sendable {    /// Show `database` in this window, then open `route`.    case open(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`.    public static func decide(link: DatabaseLink, held: [HeldDatabase], shown: String?) -> DatabaseLinkArrival {        if let database = link.database {            guard held.contains(where: { $0.databaseId == database }) else { return .notHeld(database: database) }            return .open(database: database, route: link.route)        }        if let project = projectDatabase(for: link.route, in: held) {            return .open(database: project.databaseId, route: link.route)        }        switch held.count {        case 0:            return .here(route: link.route)        case 1:            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.    public static func projectDatabase(for route: Route, in held: [HeldDatabase]) -> HeldDatabase? {        guard let slug = route.projectSlug?.lowercased(), !slug.isEmpty else { return nil }        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.    static func slugOf(_ name: String) -> String {        var out = ""        var pendingDash = false        for 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    }}extension DatabaseLinkArrival {    /// 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.    public static func record(of route: Route) -> (kind: RecordKind, id: String)? {        if case .calendarEvent(let id, _, _) = route { return id.isEmpty ? nil : (.event, id) }        guard let id = route.recordId, !id.isEmpty else { return nil }        return lookedUp.first { Route.record($0, id) == route }.map { ($0, id) }    }    /// The kinds `get_record` reads, each with a page of its own.    static let 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.    public static func 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)    }}