// 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.. 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).. 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.. 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 = [], 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 } }