Cotton code
44 lines · 1.9 KB · SwiftRaw
import Foundationextension Route {    /// The record this screen is about, when it is about one.    ///    /// A shake report carries it beside the route so an agent can open the    /// row without parsing a path. The rule is the payload's own labels: `id`    /// when a case has one (forty-odd do, and `history(kind:id:)` puts it    /// second, which is why the label is asked for rather than the position),    /// else the one label that names a record without saying `id` — `thread`.    /// A date, a month, a slug, a kind or a token is not a record, and a case    /// with none of these answers nil rather than the first string it holds.    public var recordId: String? {        let payload = Mirror(reflecting: self).children.first?.value        guard let payload else { return nil }        let fields = Mirror(reflecting: payload)        // A single-value payload has no labels: `Mirror` hands the value        // itself, and its case label is the only name it ever had.        if fields.children.isEmpty {            return Route.singleLabel(of: self).flatMap { label in                Route.recordLabels.contains(label) ? payload as? String : nil            }        }        for label in Route.recordLabels {            if let text = fields.children.first(where: { $0.label == label })?.value as? String {                return text            }        }        return nil    }    /// In order of preference.    private static let recordLabels = ["id", "thread"]    /// The label of a one-value payload, read off the case's own description:    /// `messagesThread(thread: "t")` → `thread`.    private static func singleLabel(of route: Route) -> String? {        let text = String(describing: route)        guard let open = text.firstIndex(of: "("), let colon = text[open...].firstIndex(of: ":") else {            return nil        }        return String(text[text.index(after: open)..<colon])    }}