Cotton code
265 lines · 11.5 KB · SwiftRaw
// The typed-sigil grammar — pure.//// Neither sigil is a button anywhere in Cotton — the hash and the at are// TYPING grammar and nothing else. So the whole feature rests on reading the// token the caret is standing in, and on cutting that token back out once its// chip has landed. Both decisions live here, exhaustively unit-tested; the// dock only renders what this file says.//// `#` meant a TAG until chain 1 of the projects-first program. It means a// project now, and nothing in this file knows the difference — the two sigils// differ only in which vocabulary the dock hands the matcher, which is why the// cases below are named after the GLYPHS rather than after what each one means.//// WHICH INDEX SPACE `start` AND `end` LIVE IN — the one decision this port had// to make, because TypeScript and Swift disagree about what an index is.// The TypeScript counts UTF-16 code units, because that is what `String.length`// and `String.slice` count there. Swift's `String` cannot be indexed by an// integer at all, so a port has to choose a space, and the two candidates// diverge the moment somebody types an emoji or a Devanagari cluster.//// The choice here is CHARACTERS — `Array(text)`, one element per extended// grapheme cluster — for one reason: `String(chars[start..<end])` slices in// exactly that space, so the span this file reports and the cut// `removeSigilToken` performs can never disagree. That is the property the// TypeScript test asserts (`text.slice(token.start, token.end) === "#kitchen"`// over a string holding an emoji), and it is the property that keeps a chip// from swallowing half a grapheme and painting mojibake into somebody's// sentence. The price is that a CALLER must hand a caret in the same units:// a UTF-16 offset taken from a text view's selection has to be converted// before it arrives here, never passed through raw.import Foundation/// The two sigils, and the only two.////// `allCases` IS the TypeScript's `SIGILS`, in the same order — Swift gets the/// list from the type rather than needing a second declaration beside it.public enum Sigil: Character, Sendable, Equatable, CaseIterable {    case hash = "#"    case at = "@"}/// A `#…` or `@…` run in the draft.public struct SigilToken: Sendable, Equatable {    public let sigil: Sigil    /// The characters AFTER the sigil — `""` while only the sigil is typed.    public let query: String    /// Index of the sigil itself, in CHARACTERS (see the file header).    public let start: Int    /// Index one past the token's last character.    public let end: Int    public init(sigil: Sigil, query: String, start: Int, end: Int) {        self.sigil = sigil        self.query = query        self.start = start        self.end = end    }}/// A draft with a token cut out of it, and where the caret ended up.public struct SigilRemoval: Sendable, Equatable {    public let text: String    public let caret: Int    public init(text: String, caret: Int) {        self.text = text        self.caret = caret    }}/// What ends a token: whitespace, or EITHER sigil.////// Both sigils terminate a token, so `#meri@ravi` is a closed `#meri` followed/// by an `@` that opens nothing (it is not after whitespace). A name may hold/// spaces, but a typed token cannot — the space is what says the writer has/// finished naming; matching still reaches multi-word names by prefix.private func isBoundary(_ ch: Character) -> Bool {    ch.isWhitespace || Sigil(rawValue: ch) != nil}/// True when a sigil at `index` opens a token (start of text, or after space).private func opensToken(_ chars: [Character], _ index: Int) -> Bool {    if index == 0 { return true }    return chars[index - 1].isWhitespace}/// The tokenizer proper, over characters already split.////// `closedSigilToken` walks backwards asking this question up to a whole run of/// spaces' worth of times, and re-splitting the draft on every step would make/// one keystroke O(n²) in the length of what the person has written.private func sigilToken(in chars: [Character], caret: Int) -> SigilToken? {    let at = max(0, min(caret, chars.count))    // Walk back from the caret to the nearest sigil that opens a token, stopping    // at the first boundary character — a space between here and the sigil means    // the token is closed and the caret is somewhere else.    var start = -1    var sigil: Sigil?    var index = at - 1    while index >= 0 {        let ch = chars[index]        if let found = Sigil(rawValue: ch) {            if opensToken(chars, index) {                start = index                sigil = found            }            break        }        if isBoundary(ch) { break }        index -= 1    }    guard start >= 0, let sigil else { return nil }    var end = start + 1    while end < chars.count && !isBoundary(chars[end]) { end += 1 }    // The caret may not sit beyond the token it is supposed to be editing.    if at > end { return nil }    return SigilToken(sigil: sigil, query: String(chars[(start + 1)..<end]), start: start, end: end)}/// The `#…` or `@…` token the caret is standing in, or nil.////// The caret must be INSIDE the token (just after the sigil counts) — standing/// before the sigil, or past the space that closed it, is not editing it, and/// offering completions there would be the strip appearing at random.public func activeSigilToken(_ text: String, caret: Int) -> SigilToken? {    sigilToken(in: Array(text), caret: caret)}/// Cut a token out of the draft, healing the seam.////// The chip REPLACES the words: once `#gst` is a chip on the pending capture,/// leaving the literal `#gst` in the sentence would file the hash into the/// record's own text. One space survives where the token sat between two/// words; leading/trailing gaps collapse.public func removeSigilToken(_ text: String, token: SigilToken) -> SigilRemoval {    let chars = Array(text)    // A stale token — one read before the keystroke that shortened the draft —    // is a clamp in JavaScript and a TRAP in Swift, and the composer would take    // the whole app down with it. `slice` forgives; `chars[a..<b]` does not.    let start = max(0, min(token.start, chars.count))    let end = max(start, min(token.end, chars.count))    let before = chars[0..<start]    var after = chars[end...]    // A token only ever OPENS at the head of the text or after whitespace, so    // `before` never needs a space added back — the gap just needs collapsing,    // and a newline is never eaten (it is the writer's own paragraph break).    let eatsNewlines = before.isEmpty    while let next = after.first,        next.isWhitespace,        eatsNewlines || (next != "\n" && next != "\r")    {        after = after.dropFirst()    }    // The caret lands where the token was — the writer carries on mid-sentence.    return SigilRemoval(text: String(before) + String(after), caret: before.count)}/// Did this edit CLOSE a `#…` or `@…` token — i.e. did one whitespace character/// land exactly at its end?////// That is the space-or-enter completion (spec: the top match commits without/// a tap). Returns the closed token with its span WIDENED over the whitespace,/// so removing it takes the separator with it and leaves no double gap. Nil/// for every other edit — a paste, a deletion, a space typed anywhere else.public func closedSigilToken(prev: String, next: String) -> SigilToken? {    let before = Array(prev)    let after = Array(next)    guard after.count == before.count + 1 else { return nil }    var at = 0    while at < before.count && before[at] == after[at] { at += 1 }    // `at` is at most `before.count`, and `after` holds one more than that.    let inserted = after[at]    guard inserted.isWhitespace else { return nil }    // Everything after the insertion must be untouched — otherwise this was    // some other edit that merely happens to be one character longer.    guard Array(after[(at + 1)...]) == Array(before[at...]) else { return nil }    // Typing a space directly BEFORE an identical space produces the very same    // string either way, so the first differing index is not always where the    // finger landed. Walk back over that run and take the earliest position    // that actually closes a token.    var index = at    while index >= 0 {        if let token = sigilToken(in: before, caret: index), token.end == index,            !token.query.isEmpty        {            return SigilToken(                sigil: token.sigil, query: token.query, start: token.start, end: index + 1)        }        if index == 0 || before[index - 1] != inserted { break }        index -= 1    }    return nil}/// A completion as the strip needs it — id + name, nothing about how it is/// drawn. A project for `#`, a person for `@`; the matcher cannot tell them/// apart and does not need to.public struct SigilCandidate: Sendable, Equatable {    public let id: String    public let name: String    public init(id: String, name: String) {        self.id = id        self.name = name    }}/// How many completions the strip ever offers — one thumb's width of them.public let sigilSuggestionLimit = 5/// The TypeScript's `localeCompare`, which sorts a list a person reads.////// Locale-aware for the reason the phone's was — the names being ordered are/// the person's own — and **not case-insensitive**. `localeCompare` compares at/// tertiary strength: case is invisible while the letters differ, and decides/// only between two names that are otherwise the same word. Folding case here/// made those two ties, which then fell to the vocabulary's load order —/// deterministic, but a different top match from the one the phone offers, and/// the top match is what space commits.private func alphabetically(_ lhs: String, _ rhs: String) -> ComparisonResult {    lhs.compare(rhs, options: [], range: nil, locale: Locale.current)}/// The completions for a token, best first.////// Prefix matches beat contained matches (typing `ta` means `taxes` before/// `mehta`), ties break alphabetically so the top match — the one space/enter/// commits — never depends on the order the vocabulary happened to load in./// Already-attached candidates are gone from the list: a chip you can see is/// not a suggestion.public func matchCandidates(    _ candidates: [SigilCandidate],    query: String,    exclude: Set<String> = [],    limit: Int = sigilSuggestionLimit) -> [SigilCandidate] {    let q = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()    if q.isEmpty { return [] }    var scored: [(candidate: SigilCandidate, rank: Int, at: Int)] = []    for (at, candidate) in candidates.enumerated() {        if exclude.contains(candidate.id) { continue }        let name = candidate.name.lowercased()        if name.hasPrefix(q) {            scored.append((candidate, 0, at))        } else if name.contains(q) {            scored.append((candidate, 1, at))        }    }    scored.sort { lhs, rhs in        if lhs.rank != rhs.rank { return lhs.rank < rhs.rank }        let order = alphabetically(lhs.candidate.name, rhs.candidate.name)        if order != .orderedSame { return order == .orderedAscending }        // JavaScript's sort is stable and Swift's is not documented to be, so        // the vocabulary's own order is the last tiebreak: two projects sharing        // a name must not swap places between two renders of the same strip.        return lhs.at < rhs.at    }    // `prefix` traps on a negative length where `slice` would not.    return scored.prefix(max(0, limit)).map { $0.candidate }}