// The order a pick-one list offers records in — before anyone types, and once// they have. The link editor's picker (`LinkPicker`, any table) asks it, so a// name ranks the same wherever it is picked.//// Pure over plain values, so the rule is testable with no view and no records// (`PickerRankingTests`).//// ## Typing//// A name that STARTS with what was typed comes first, then a name in which a// WORD starts with it, then any other name that contains it. Case and accents// are ignored on both sides, so "ema" finds "Émile" and "EMMA" alike. Inside// each of the three the names read alphabetically, and two rows with the same// name keep the input's order.//// ## Before typing//// The ids already chosen first, then the rest in the input's own order.importFoundationpublicenumPickerRanking {/// How well `name` answers `query`: `0` it starts with it, `1` a word in/// it starts with it, `2` it contains it somewhere else, `nil` it does not/// contain it at all. A blank query matches nothing — the picker shows its/// suggestions instead.////// A WORD starts after anything that is not a letter or a digit, so the/// family name in "Test Zulu", the second half of "Test-Zulu" and the name/// after an apostrophe all count as word starts.publicstaticfunc matchRank(_ name: String, query: String) -> Int? {let needle = fold(query.trimmingCharacters(in: .whitespacesAndNewlines))guard !needle.isEmpty else { returnnil }let haystack = fold(name)var best: Int?var searchFrom = haystack.startIndexwhilelet hit = haystack.range(of: needle, range: searchFrom..<haystack.endIndex) {let rank: Intif hit.lowerBound == haystack.startIndex { rank = 0 } elseif !isWordCharacter(haystack[haystack.index(before: hit.lowerBound)]) { rank = 1 } else { rank = 2 } best = min(best ?? rank, rank)if rank == 0 { break } searchFrom = haystack.index(after: hit.lowerBound) }return best }/// Every item whose name matches `query`, best match first; alphabetical/// within a rank, and the input's order between two equal names.publicstaticfunc search<Item>( _ items: [Item], matching query: String, name: (Item) -> String ) -> [Item] { items.enumerated() .compactMap { offset, item -> (rank: Int, key: String, offset: Int, item: Item)? inguardlet rank = matchRank(name(item), query: query) else { returnnil }return (rank, fold(name(item)), offset, item) } .sorted { left, right inif left.rank != right.rank { return left.rank < right.rank }if left.key != right.key { return left.key < right.key }return left.offset < right.offset } .map(\.item) }/// What a picker offers before anyone types, at most `limit` of them.////// `chosen` is the ids already picked, in their own order; an id the list/// no longer carries is skipped. Then the rest in the order `items`/// arrived in — the app's order.publicstaticfunc suggestions<Item>( _ items: [Item], chosen: [String], limit: Int, id: (Item) -> String ) -> [Item] {guard limit > 0else { return [] }var byId: [String: Item] = [:]for item in items where byId[id(item)] == nil { byId[id(item)] = item }// The chosen first; an item already offered is not offered again// further down.let candidates: [Item] = chosen.compactMap { byId[$0] } + itemsvar taken: Set<String> = []var out: [Item] = []for item in candidates where out.count < limit {if taken.insert(id(item)).inserted { out.append(item) } }return out }/// Case- and accent-free, locale-free: the same fold on both sides of every/// comparison, so a phone set to another language ranks the same names the/// same way.staticfunc fold(_ text: String) -> String { text.folding(options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive], locale: nil) }privatestaticfunc isWordCharacter(_ character: Character) -> Bool { character.isLetter || character.isNumber }}