Merge 22c332123e0eec2e6e9282ed2ca97a27b39993fa into 04995f68e470a18d1fc99f86fa326c2a87bab4f2

This commit is contained in:
heyaim 2026-11-04 10:36:29 -06:00 committed by GitHub
commit 56b466005e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 578 additions and 26 deletions

View File

@ -113,22 +113,16 @@ final class ConversationUIModel: ObservableObject {
chatViewModel.updateAutocomplete(for: text, cursorPosition: cursorPosition)
}
var mentionReplacementRange: NSRange? { chatViewModel.autocompleteRange }
func completeNickname(_ nickname: String, in text: inout String) -> Int {
chatViewModel.completeNickname(nickname, in: &text)
}
/// Accept the currently highlighted mention suggestion, if any.
func completeSelectedSuggestion(in text: inout String) -> Bool {
guard showAutocomplete,
autocompleteSuggestions.indices.contains(selectedAutocompleteIndex)
else { return false }
_ = completeNickname(autocompleteSuggestions[selectedAutocompleteIndex], in: &text)
return true
}
/// Dismiss the mention suggestion panel without inserting (Escape).
/// Dismiss the mention suggestion panel without inserting.
func dismissAutocomplete() {
guard showAutocomplete else { return }
// The published UI mirror can lag behind a native selection change.
guard chatViewModel.showAutocomplete else { return }
chatViewModel.showAutocomplete = false
chatViewModel.autocompleteSuggestions = []
chatViewModel.autocompleteRange = nil

View File

@ -28,13 +28,16 @@ struct ContentComposerView: View {
@Binding var showMacImagePicker: Bool
#endif
@State private var mentionSelection = NSRange(location: 0, length: 0)
@State private var mentionInputText: String?
var body: some View {
VStack(alignment: .leading, spacing: 6) {
if conversationUIModel.showAutocomplete && !conversationUIModel.autocompleteSuggestions.isEmpty {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(conversationUIModel.autocompleteSuggestions.prefix(4).enumerated()), id: \.element) { index, suggestion in
Button(action: {
_ = conversationUIModel.completeNickname(suggestion, in: &messageText)
completeMention(suggestion)
}) {
HStack {
Text(suggestion)
@ -66,12 +69,7 @@ struct ContentComposerView: View {
}
HStack(alignment: .center, spacing: 4) {
TextField(
"",
text: $messageText,
prompt: Text(placeholderText)
.foregroundColor(palette.secondary.opacity(0.6))
)
composerField
.textFieldStyle(.plain)
.bitchatFont(size: 15)
.foregroundColor(palette.primary)
@ -88,7 +86,7 @@ struct ContentComposerView: View {
conversationUIModel.moveAutocompleteSelection(by: delta)
},
onAccept: {
conversationUIModel.completeSelectedSuggestion(in: &messageText)
completeHighlightedMention()
},
onDismiss: {
conversationUIModel.dismissAutocomplete()
@ -100,7 +98,7 @@ struct ContentComposerView: View {
.onSubmit {
if conversationUIModel.showAutocomplete,
!conversationUIModel.autocompleteSuggestions.isEmpty,
conversationUIModel.completeSelectedSuggestion(in: &messageText) {
completeHighlightedMention() {
return
}
onSendMessage()
@ -116,13 +114,20 @@ struct ContentComposerView: View {
.modifier(FocusEffectDisabledModifier())
.frame(maxWidth: .infinity, alignment: .leading)
.onChange(of: messageText) { newValue in
#if os(iOS)
if newValue != mentionInputText {
mentionSelection = NSRange(location: newValue.utf16.count, length: 0)
conversationUIModel.dismissAutocomplete()
}
#else
autocompleteDebounceTimer?.invalidate()
autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in
let cursorPosition = newValue.count
let cursorPosition = mentionCursor(in: newValue)
Task { @MainActor in
conversationUIModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)
}
}
#endif
}
HStack(alignment: .center, spacing: 4) {
@ -142,13 +147,79 @@ struct ContentComposerView: View {
.padding(.top, theme.usesGlassChrome ? 8 : 6)
.padding(.bottom, 8)
.themedChromePanel(edge: .bottom)
.onAppear {
#if os(iOS)
mentionSelection = NSRange(location: messageText.utf16.count, length: 0)
conversationUIModel.dismissAutocomplete()
#endif
}
.onChange(of: locationChannelsModel.selectedChannel) { _ in
#if os(iOS)
conversationUIModel.dismissAutocomplete()
#endif
}
.onChange(of: privateConversationModel.selectedPeerID) { _ in
#if os(iOS)
conversationUIModel.dismissAutocomplete()
#endif
}
.onDisappear {
autocompleteDebounceTimer?.invalidate()
#if os(iOS)
conversationUIModel.dismissAutocomplete()
#endif
}
}
}
private extension ContentComposerView {
@ViewBuilder
var composerField: some View {
#if os(iOS)
MentionTextField(text: $messageText, selection: $mentionSelection,
focused: Binding(get: { isTextFieldFocused.wrappedValue }, set: { isTextFieldFocused.wrappedValue = $0 }),
placeholder: placeholderText, placeholderColor: UIColor(palette.secondary.opacity(0.6)),
color: UIColor(palette.primary), monospaced: !theme.usesGlassChrome,
hasSuggestions: { conversationUIModel.showAutocomplete },
moveSuggestion: { conversationUIModel.moveAutocompleteSelection(by: $0) },
acceptSuggestion: { _ = completeHighlightedMention() },
dismissSuggestions: { conversationUIModel.dismissAutocomplete() },
onSelection: { text, cursor in
mentionInputText = text
if cursor < 0 { conversationUIModel.dismissAutocomplete() }
else { conversationUIModel.updateAutocomplete(for: text, cursorPosition: cursor) }
}, onReturn: {
if !completeHighlightedMention() { onSendMessage() }
})
#else
TextField("", text: $messageText, prompt: Text(placeholderText).foregroundColor(palette.secondary.opacity(0.6)))
#endif
}
func mentionCursor(in text: String) -> Int {
#if os(iOS)
let offset = min(mentionSelection.location, text.utf16.count)
let index = String.Index(utf16Offset: offset, in: text)
return text.distance(from: text.startIndex, to: index)
#else
return text.count
#endif
}
func completeMention(_ suggestion: String) {
let range = conversationUIModel.mentionReplacementRange
_ = conversationUIModel.completeNickname(suggestion, in: &messageText)
mentionInputText = messageText
if let range { mentionSelection = NSRange(location: range.location + suggestion.utf16.count, length: 0) }
}
func completeHighlightedMention() -> Bool {
guard conversationUIModel.showAutocomplete,
conversationUIModel.autocompleteSuggestions.indices.contains(conversationUIModel.selectedAutocompleteIndex) else { return false }
completeMention(conversationUIModel.autocompleteSuggestions[conversationUIModel.selectedAutocompleteIndex])
return true
}
/// The nearby-only scope toggle appears only where it means something:
/// the public mesh channel with the bridge on.
var showsNearbyOnlyToggle: Bool {
@ -504,3 +575,129 @@ private struct AutocompleteKeyboardNavigationModifier: ViewModifier {
}
#endif
}
#if os(iOS)
/// Selection is supplied by UIKit on the minimum supported iOS version.
private struct MentionTextField: UIViewRepresentable {
@Binding var text: String
@Binding var selection: NSRange
@Binding var focused: Bool
let placeholder: String
let placeholderColor: UIColor
let color: UIColor
let monospaced: Bool
let hasSuggestions: () -> Bool
let moveSuggestion: (Int) -> Void
let acceptSuggestion: () -> Void
let dismissSuggestions: () -> Void
let onSelection: (String, Int) -> Void
let onReturn: () -> Void
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeUIView(context: Context) -> UITextField {
let field = MentionNativeField()
field.delegate = context.coordinator
field.addTarget(context.coordinator, action: #selector(Coordinator.edit(_:)), for: .editingChanged)
field.adjustsFontForContentSizeCategory = true
field.autocorrectionType = .no
field.autocapitalizationType = .sentences
field.returnKeyType = .send
field.setContentHuggingPriority(.defaultLow, for: .horizontal)
field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return field
}
func sizeThatFits(_ proposal: ProposedViewSize, uiView: UITextField, context: Context) -> CGSize? {
CGSize(width: proposal.width ?? max(0, uiView.intrinsicContentSize.width),
height: uiView.intrinsicContentSize.height)
}
func updateUIView(_ field: UITextField, context: Context) {
context.coordinator.parent = self
context.coordinator.updating = true
defer { context.coordinator.updating = false }
if let native = field as? MentionNativeField {
native.hasSuggestions = hasSuggestions
native.moveSuggestion = moveSuggestion
native.acceptSuggestion = acceptSuggestion
native.dismissSuggestions = dismissSuggestions
}
field.textColor = color
let descriptor = UIFont.preferredFont(forTextStyle: .subheadline).fontDescriptor
field.font = UIFont(descriptor: monospaced ? (descriptor.withDesign(.monospaced) ?? descriptor) : descriptor, size: 0)
field.attributedPlaceholder = NSAttributedString(
string: placeholder, attributes: [.foregroundColor: placeholderColor]
)
if field.text != text {
if field.markedTextRange != nil { field.unmarkText() }
field.text = text
}
if field.markedTextRange == nil {
if let a = field.position(from: field.beginningOfDocument, offset: min(selection.location, text.utf16.count)),
let b = field.position(from: a, offset: min(selection.length, text.utf16.count - min(selection.location, text.utf16.count))) {
field.selectedTextRange = field.textRange(from: a, to: b)
}
}
}
final class Coordinator: NSObject, UITextFieldDelegate {
var parent: MentionTextField
var updating = false
init(_ parent: MentionTextField) { self.parent = parent }
@objc func edit(_ field: UITextField) { publish(field) }
func textFieldDidChangeSelection(_ field: UITextField) { publish(field) }
func publish(_ field: UITextField) {
guard !updating else { return }
if field.markedTextRange != nil {
parent.text = field.text ?? ""
parent.onSelection(parent.text, -1)
return
}
guard let range = field.selectedTextRange else { return }
parent.selection = NSRange(location: field.offset(from: field.beginningOfDocument, to: range.start), length: field.offset(from: range.start, to: range.end))
parent.text = field.text ?? ""
// Completion replaces the fragment before the caret, not selected text or a name suffix.
guard parent.selection.length == 0,
let caret = Range(parent.selection, in: parent.text)?.lowerBound else {
parent.onSelection(parent.text, -1)
return
}
if let next = parent.text[caret...].first,
next.isLetter || next.isNumber || next == "_" || next == "#" {
parent.onSelection(parent.text, -1)
return
}
parent.onSelection(parent.text, parent.text[..<caret].count)
}
func textFieldDidBeginEditing(_ field: UITextField) { if !updating { parent.focused = true } }
func textFieldDidEndEditing(_ field: UITextField) { if !updating { parent.focused = false } }
func textFieldShouldReturn(_ field: UITextField) -> Bool { parent.onReturn(); return false }
}
}
#endif
#if os(iOS)
private final class MentionNativeField: UITextField {
var hasSuggestions: () -> Bool = { false }
var moveSuggestion: (Int) -> Void = { _ in }
var acceptSuggestion: () -> Void = {}
var dismissSuggestions: () -> Void = {}
override var keyCommands: [UIKeyCommand]? {
guard hasSuggestions(), markedTextRange == nil else { return super.keyCommands }
let keys = [UIKeyCommand.inputUpArrow, UIKeyCommand.inputDownArrow, "\t", UIKeyCommand.inputEscape]
return keys.map {
let command = UIKeyCommand(input: $0, modifierFlags: [], action: #selector(mentionKey(_:)))
command.wantsPriorityOverSystemBehavior = true
return command
}
}
@objc private func mentionKey(_ command: UIKeyCommand) {
guard hasSuggestions(), markedTextRange == nil else { return }
switch command.input {
case UIKeyCommand.inputUpArrow: moveSuggestion(-1)
case UIKeyCommand.inputDownArrow: moveSuggestion(1)
case "\t": acceptSuggestion()
case UIKeyCommand.inputEscape: dismissSuggestions()
default: break
}
}
}
#endif

View File

@ -0,0 +1,357 @@
import BitFoundation
import Testing
@testable import bitchat
#if os(iOS)
import SwiftUI
import UIKit
@MainActor private struct MentionProbeComposer: View {
@State var text = "hey everyone, see you tomorrow"
@State var timer: Timer?
@State var picker = false
@State var source: UIImagePickerController.SourceType = .photoLibrary
@StateObject var voice = VoiceRecordingViewModel()
@FocusState var focus: Bool
var body: some View {
ContentComposerView(
messageText: $text, isTextFieldFocused: $focus, voiceRecordingVM: voice,
autocompleteDebounceTimer: $timer, onSendMessage: {}, showImagePicker: $picker,
imagePickerSourceType: $source)
}
}
extension ViewSmokeTests {
@Test @MainActor func completesMentionAtCaretWithoutLosingTrailingText() async throws {
let (vm, transport, _) = makeSmokeViewModel()
transport.peerNicknames[PeerID(str: "1122334455667788")] = "alice"
let models = makeSmokeFeatureModels(for: vm)
let host = UIHostingController(
rootView: MentionProbeComposer().environmentObject(models.conversationUIModel)
.environmentObject(models.privateConversationModel).environmentObject(
models.locationChannelsModel))
let scene = try #require(
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
window.frame = scene.coordinateSpace.bounds
window.rootViewController = host
window.windowLevel = .alert + 1
window.makeKeyAndVisible()
defer { window.isHidden = true }
try await Task.sleep(for: .milliseconds(500))
func fields(_ v: UIView) -> [UITextField] {
(v as? UITextField).map { [$0] } ?? v.subviews.flatMap(fields)
}
let field = try #require(fields(host.view).first)
field.becomeFirstResponder()
let start = try #require(field.position(from: field.beginningOfDocument, offset: 4))
let end = try #require(field.position(from: start, offset: 8))
field.selectedTextRange = field.textRange(from: start, to: end)
field.insertText("@al")
try await Task.sleep(for: .milliseconds(600))
#expect(field.text == "hey @al, see you tomorrow")
#expect(models.conversationUIModel.autocompleteSuggestions.contains("@alice"))
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @alice, see you tomorrow")
#expect(
field.offset(from: field.beginningOfDocument, to: field.selectedTextRange!.start) == 10)
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al")
try await Task.sleep(for: .milliseconds(600))
#expect(models.conversationUIModel.autocompleteSuggestions.contains("@alice"))
for prefix in ["😀 hey ", "👨‍👩‍👧‍👦 hey ", "e\u{301} hey "] {
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText(prefix + "@al, see you tomorrow")
let caret = field.position(
from: field.beginningOfDocument, offset: (prefix + "@al").utf16.count)!
field.selectedTextRange = field.textRange(from: caret, to: caret)
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions.contains("@alice"))
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == prefix + "@alice, see you tomorrow")
#expect(
field.offset(from: field.beginningOfDocument, to: field.selectedTextRange!.start)
== (prefix + "@alice").utf16.count)
}
field.selectedTextRange = field.textRange(
from: field.endOfDocument, to: field.endOfDocument)
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions.isEmpty)
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al")
try await Task.sleep(for: .milliseconds(300))
field.setMarkedText("中", selectedRange: NSRange(location: 1, length: 0))
try await Task.sleep(for: .milliseconds(300))
#expect(field.markedTextRange != nil)
#expect(models.conversationUIModel.autocompleteSuggestions.isEmpty)
field.unmarkText()
transport.peerNicknames[PeerID(str: "2233445566778899")] = "alex"
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al")
try await Task.sleep(for: .milliseconds(300))
let down = try #require(
field.keyCommands?.first { $0.input == UIKeyCommand.inputDownArrow })
_ = field.perform(down.action, with: down)
try await Task.sleep(for: .milliseconds(200))
#expect(models.conversationUIModel.selectedAutocompleteIndex == 1)
let up = try #require(field.keyCommands?.first { $0.input == UIKeyCommand.inputUpArrow })
_ = field.perform(up.action, with: up)
try await Task.sleep(for: .milliseconds(200))
#expect(models.conversationUIModel.selectedAutocompleteIndex == 0)
let tab = try #require(field.keyCommands?.first { $0.input == "\t" })
_ = field.perform(tab.action, with: tab)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @alex")
#expect(field.isFirstResponder)
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al")
try await Task.sleep(for: .milliseconds(300))
let escape = try #require(field.keyCommands?.first { $0.input == UIKeyCommand.inputEscape })
_ = field.perform(escape.action, with: escape)
try await Task.sleep(for: .milliseconds(200))
#expect(models.conversationUIModel.autocompleteSuggestions.isEmpty)
#expect(field.text == "hey @al")
field.resignFirstResponder()
try await Task.sleep(for: .milliseconds(200))
#expect(!field.isFirstResponder)
vm.geoNicknames = [String(repeating: "a", count: 60) + "dddd": "carol"]
vm.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pru"))
field.becomeFirstResponder()
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hello @ca, tomorrow")
let geoCaret = try #require(field.position(from: field.beginningOfDocument, offset: 9))
field.selectedTextRange = field.textRange(from: geoCaret, to: geoCaret)
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions == ["@carol#dddd"])
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hello @carol#dddd, tomorrow")
vm.activeChannel = .mesh
field.selectedTextRange = field.textRange(
from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hello @ca")
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions.isEmpty)
}
}
#endif
#if os(iOS)
extension ViewSmokeTests {
@Test @MainActor func switchingConversationsPreservesDraftsAndClearsSuggestions() async throws {
let previous = ComposerDraftStore.replaceAllForTesting()
defer { ComposerDraftStore.replaceAllForTesting(previous) }
let (vm, transport, _) = makeSmokeViewModel()
let peer = PeerID(str: "5152535455565758")
transport.updatePeerSnapshots([
makeSnapshot(peerID: peer, nickname: "alice", noiseByte: 0x66)
]
)
transport.peerNicknames[peer] = "alice"
let models = makeSmokeFeatureModels(for: vm)
try await Task.sleep(for: .milliseconds(200))
let privateKey = ComposerDraftStore.Key.privateChat(
stableID: vm.getFingerprint(for: peer) ?? peer.id)
ComposerDraftStore.save("private saved draft", for: privateKey)
let host = UIHostingController(
rootView: installSmokeEnvironment(ContentView(), featureModels: models))
let scene = try #require(
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
window.frame = scene.coordinateSpace.bounds
window.rootViewController = host
window.windowLevel = .alert + 1
window.makeKeyAndVisible()
defer { window.isHidden = true }
try await Task.sleep(for: .milliseconds(500))
func fields(_ v: UIView) -> [UITextField] {
(v as? UITextField).map { [$0] } ?? v.subviews.flatMap(fields)
}
let field = try #require(fields(host.view).first { $0.returnKeyType == .send })
field.becomeFirstResponder()
field.insertText("hey @al, see you tomorrow")
let caret = try #require(field.position(from: field.beginningOfDocument, offset: 7))
field.selectedTextRange = field.textRange(from: caret, to: caret)
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions.contains("@alice"))
models.privateConversationModel.startConversation(with: peer)
try await Task.sleep(for: .milliseconds(500))
#expect(fields(window).contains { $0.text == "private saved draft" })
#expect(
models.conversationUIModel.autocompleteSuggestions.isEmpty,
"Old mention must clear when loading another draft")
#expect(ComposerDraftStore.load(.mesh) == "hey @al, see you tomorrow")
models.privateConversationModel.endConversation()
try await Task.sleep(for: .milliseconds(500))
#expect(fields(window).contains { $0.text == "hey @al, see you tomorrow" })
#expect(ComposerDraftStore.load(privateKey) == "private saved draft")
let group = PeerID(groupID: Data(repeating: 0x31, count: 16))
let groupKey = ComposerDraftStore.Key.privateChat(stableID: group.id)
ComposerDraftStore.save("group @al, later", for: groupKey)
models.privateConversationModel.startConversation(with: group)
try await Task.sleep(for: .milliseconds(500))
let groupField = try #require(fields(window).first { $0.text == "group @al, later" })
groupField.becomeFirstResponder()
let groupCaret = try #require(
groupField.position(from: groupField.beginningOfDocument, offset: 9))
groupField.selectedTextRange = groupField.textRange(from: groupCaret, to: groupCaret)
try await Task.sleep(for: .milliseconds(300))
#expect(models.conversationUIModel.autocompleteSuggestions.contains("@alice"))
_ = groupField.delegate?.textFieldShouldReturn?(groupField)
try await Task.sleep(for: .milliseconds(300))
#expect(groupField.text == "group @alice, later")
models.privateConversationModel.endConversation()
try await Task.sleep(for: .milliseconds(400))
#expect(ComposerDraftStore.load(groupKey) == "group @alice, later")
#expect(fields(window).contains { $0.text == "hey @al, see you tomorrow" })
}
}
@MainActor
private func withBoundaryComposer(_ body: (UITextField, ConversationUIModel) async throws -> Void) async throws {
let (vm, transport, _) = makeSmokeViewModel()
transport.peerNicknames[PeerID(str: "1122334455667788")] = "alice"
let models = makeSmokeFeatureModels(for: vm)
let host = UIHostingController(rootView:
MentionProbeComposer().environmentObject(models.conversationUIModel)
.environmentObject(models.privateConversationModel)
.environmentObject(models.locationChannelsModel))
let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
let window = UIWindow(windowScene: scene)
window.frame = scene.coordinateSpace.bounds
window.rootViewController = host
window.windowLevel = .alert + 1
window.makeKeyAndVisible()
defer { window.isHidden = true; withExtendedLifetime(vm) {} }
try await Task.sleep(for: .milliseconds(500))
func fields(_ view: UIView) -> [UITextField] {
(view as? UITextField).map { [$0] } ?? view.subviews.flatMap(fields)
}
let field = try #require(fields(host.view).first { $0.returnKeyType == .send })
field.becomeFirstResponder()
try await body(field, models.conversationUIModel)
}
@MainActor
private func selectBoundaryRange(_ field: UITextField, location: Int, length: Int = 0) throws {
let start = try #require(field.position(from: field.beginningOfDocument, offset: location))
let end = try #require(field.position(from: start, offset: length))
field.selectedTextRange = field.textRange(from: start, to: end)
let actual = try #require(field.selectedTextRange)
#expect(field.offset(from: field.beginningOfDocument, to: actual.start) == location)
#expect(field.offset(from: actual.start, to: actual.end) == length)
}
extension ViewSmokeTests {
@Test @MainActor func mentionSelectionDismissesAndRecoversAtBoundary() async throws {
try await withBoundaryComposer { field, model in
field.selectedTextRange = field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al, later")
try selectBoundaryRange(field, location: 7)
try await Task.sleep(for: .milliseconds(300))
try #require(model.autocompleteSuggestions.contains("@alice"))
// The comma isolates selection dismissal from the word-continuation check.
try selectBoundaryRange(field, location: 7, length: 1)
#expect(model.mentionReplacementRange == nil)
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @al, later")
#expect(model.autocompleteSuggestions.isEmpty)
try selectBoundaryRange(field, location: 7)
try await Task.sleep(for: .milliseconds(300))
try #require(model.autocompleteSuggestions.contains("@alice"))
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @alice, later")
field.insertText("!")
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @alice!, later")
}
}
@Test @MainActor func mentionSuggestionsRespectFollowingNameCharacters() async throws {
try await withBoundaryComposer { field, model in
for suffix in ["ice", "_id", "2", "é", "e\u{301}", "中", "٢", "#abcd"] {
let text = "hey @al" + suffix + ", later"
field.selectedTextRange = field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText(text)
try selectBoundaryRange(field, location: 7)
try await Task.sleep(for: .milliseconds(300))
#expect(model.autocompleteSuggestions.isEmpty, "Name continuation: \(suffix)")
#expect(field.text == text)
}
for suffix in [", later", " later", ""] {
field.selectedTextRange = field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al" + suffix)
try selectBoundaryRange(field, location: 7)
try await Task.sleep(for: .milliseconds(300))
try #require(model.autocompleteSuggestions.contains("@alice"))
_ = field.delegate?.textFieldShouldReturn?(field)
try await Task.sleep(for: .milliseconds(300))
#expect(field.text == "hey @alice" + suffix)
}
}
}
}
extension ViewSmokeTests {
@Test @MainActor func mentionSuggestionsRejectCaretInsideCombinedCharacter() async throws {
try await withBoundaryComposer { field, model in
let text = "hey @al\u{301}, later"
field.selectedTextRange = field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText(text)
try selectBoundaryRange(field, location: 7)
try await Task.sleep(for: .milliseconds(300))
#expect(model.autocompleteSuggestions.isEmpty)
#expect(field.text == text)
}
}
}
extension ViewSmokeTests {
@Test @MainActor func immediateInvalidSelectionClearsPendingMention() async throws {
try await withBoundaryComposer { field, model in
try #require(!model.showAutocomplete)
field.selectedTextRange = field.textRange(from: field.beginningOfDocument, to: field.endOfDocument)
field.insertText("hey @al, later")
try selectBoundaryRange(field, location: 7)
try #require(model.mentionReplacementRange != nil)
// Do not yield between making a candidate and invalidating its selection.
try selectBoundaryRange(field, location: 7, length: 1)
#expect(model.mentionReplacementRange == nil)
try await Task.sleep(for: .milliseconds(300))
#expect(model.autocompleteSuggestions.isEmpty)
#expect(!model.showAutocomplete)
#expect(field.text == "hey @al, later")
}
}
}
#endif
extension ViewSmokeTests {
@Test @MainActor func dismissalClearsPendingAutocomplete() async throws {
let (viewModel, transport, _) = makeSmokeViewModel()
transport.peerNicknames[PeerID(str: "1122334455667788")] = "alice"
let model = makeSmokeFeatureModels(for: viewModel).conversationUIModel
model.updateAutocomplete(for: "@al", cursorPosition: 3)
try #require(viewModel.showAutocomplete)
try #require(!model.showAutocomplete)
model.dismissAutocomplete()
#expect(!viewModel.showAutocomplete)
#expect(viewModel.autocompleteSuggestions.isEmpty)
#expect(viewModel.autocompleteRange == nil)
#expect(viewModel.selectedAutocompleteIndex == 0)
try await Task.sleep(for: .milliseconds(300))
#expect(!model.showAutocomplete)
#expect(model.autocompleteSuggestions.isEmpty)
}
}

View File

@ -3,6 +3,8 @@ import Testing
@testable import bitchat
import BitFoundation
// These tests share process-wide drafts with the mounted conversation tests.
extension ViewSmokeTests {
@Suite(.serialized)
struct ComposerDraftStoreTests {
/// Isolate each test from leftover in-memory drafts.
@ -100,3 +102,5 @@ struct ComposerDraftStoreTests {
}
}
}
}

View File

@ -13,7 +13,7 @@ import BitFoundation
@testable import bitchat
@MainActor
private func makeSmokeViewModel() -> (viewModel: ChatViewModel, transport: MockTransport, identityManager: MockIdentityManager) {
func makeSmokeViewModel() -> (viewModel: ChatViewModel, transport: MockTransport, identityManager: MockIdentityManager) {
let keychain = MockKeychain()
let keychainHelper = MockKeychainHelper()
let idBridge = NostrIdentityBridge(keychain: keychainHelper)
@ -31,7 +31,7 @@ private func makeSmokeViewModel() -> (viewModel: ChatViewModel, transport: MockT
}
@MainActor
private struct SmokeFeatureModels {
struct SmokeFeatureModels {
let publicChatModel: PublicChatModel
let appChromeModel: AppChromeModel
let locationChannelsModel: LocationChannelsModel
@ -53,7 +53,7 @@ private func makeSmokeLocationManager() -> LocationChannelManager {
}
@MainActor
private func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatureModels {
func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatureModels {
let locationManager = makeSmokeLocationManager()
let conversations = viewModel.conversations
let publicChatModel = PublicChatModel(conversations: conversations)
@ -106,7 +106,7 @@ private func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatur
}
@MainActor
private func installSmokeEnvironment<V: View>(
func installSmokeEnvironment<V: View>(
_ view: V,
featureModels: SmokeFeatureModels
) -> some View {
@ -200,7 +200,7 @@ private func mount<V: View>(_ view: V) -> AnyObject {
#endif
}
private func makeSnapshot(
func makeSnapshot(
peerID: PeerID,
nickname: String,
connected: Bool = true,