diff --git a/ios/Packages/Sybil/Sources/Sybil/SybilQuickQuestionView.swift b/ios/Packages/Sybil/Sources/Sybil/SybilQuickQuestionView.swift index 1952c6d..1b989b0 100644 --- a/ios/Packages/Sybil/Sources/Sybil/SybilQuickQuestionView.swift +++ b/ios/Packages/Sybil/Sources/Sybil/SybilQuickQuestionView.swift @@ -1,6 +1,7 @@ import MarkdownUI import Observation import SwiftUI +import UIKit struct SybilQuickQuestionView: View { @Bindable var viewModel: SybilViewModel @@ -8,7 +9,6 @@ struct SybilQuickQuestionView: View { @Environment(\.dismiss) private var dismiss @FocusState private var promptFocused: Bool - @State private var promptSelection: TextSelection? private var hasAnswerContent: Bool { !viewModel.quickQuestionMessages.isEmpty || viewModel.quickQuestionError != nil @@ -37,8 +37,6 @@ struct SybilQuickQuestionView: View { return } promptFocused = true - let prompt = viewModel.quickQuestionPrompt - promptSelection = TextSelection(range: prompt.startIndex.. Void + + func makeUIView(context: Context) -> QuickQuestionNativeTextField { + SybilFontRegistry.registerIfNeeded() + let textField = QuickQuestionNativeTextField() + textField.delegate = context.coordinator + textField.addTarget(context.coordinator, action: #selector(Coordinator.textDidChange(_:)), for: .editingChanged) + textField.placeholder = placeholder + let baseFont = UIFont(name: "Inter", size: 17) ?? UIFont.systemFont(ofSize: 17) + textField.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: baseFont) + textField.adjustsFontForContentSizeCategory = true + textField.textColor = UIColor(SybilTheme.text) + textField.backgroundColor = .clear + textField.borderStyle = .none + textField.autocapitalizationType = .sentences + textField.autocorrectionType = .yes + textField.returnKeyType = .send + textField.keyboardAppearance = .dark + textField.accessibilityIdentifier = "quick-question-prompt" + textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + textField.setContentHuggingPriority(.defaultLow, for: .horizontal) + return textField + } + + func updateUIView(_ textField: QuickQuestionNativeTextField, context: Context) { + context.coordinator.parent = self + if textField.text != text { + textField.text = text + } + textField.wantsFirstResponder = focused + } + + func makeCoordinator() -> Coordinator { + Coordinator(parent: self) + } + + @MainActor + final class Coordinator: NSObject, UITextFieldDelegate { + var parent: QuickQuestionTextField + private var lastSelectedFocusRequest: Int? + + init(parent: QuickQuestionTextField) { + self.parent = parent + } + + @objc func textDidChange(_ textField: UITextField) { + parent.text = textField.text ?? "" + } + + func textFieldDidBeginEditing(_ textField: UITextField) { + parent.focused = true + guard lastSelectedFocusRequest != parent.focusRequest else { + return + } + lastSelectedFocusRequest = parent.focusRequest + guard let text = textField.text, !text.isEmpty, + let range = textField.textRange( + from: textField.beginningOfDocument, + to: textField.endOfDocument + ) + else { + return + } + textField.selectedTextRange = range + } + + func textFieldDidEndEditing(_ textField: UITextField) { + parent.focused = false + } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + parent.submit() + return false + } + } +} + private struct QuickQuestionPickerPill: View { var title: String diff --git a/ios/Tests/SybilUITests/QuickQuestionSelectionUITests.swift b/ios/Tests/SybilUITests/QuickQuestionSelectionUITests.swift new file mode 100644 index 0000000..d6d0953 --- /dev/null +++ b/ios/Tests/SybilUITests/QuickQuestionSelectionUITests.swift @@ -0,0 +1,77 @@ +import XCTest + +/// Uses the repository's 127.0.0.1 contract fixture and the real iOS home-screen shortcut. +@MainActor +final class QuickQuestionSelectionUITests: XCTestCase { + private let app = XCUIApplication() + private let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") + + override func setUp() async throws { + continueAfterFailure = false + try await control(["action": "reset", "count": 0]) + app.launchArguments = [ + "-sybil.ios.apiBaseURL", "http://127.0.0.1:8799/api", + "-sybil.ios.adminToken", "fixture-token" + ] + } + + override func tearDown() async throws { + app.terminate() + } + + func testPrefilledDraftIsSelectedOnReopenAndTypingReplacesIt() async throws { + app.launch() + openQuickQuestionFromHomeScreen() + + let prompt = app.textFields["quick-question-prompt"] + XCTAssertTrue(prompt.waitForExistence(timeout: 10)) + XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10)) + prompt.typeText("retained draft") + XCTAssertEqual(prompt.value as? String, "retained draft") + + dismissQuickQuestion(prompt) + openQuickQuestionFromHomeScreen() + + XCTAssertTrue(prompt.waitForExistence(timeout: 10)) + XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 10)) + XCTAssertEqual(prompt.value as? String, "retained draft") + + // The field is already focused with its initial draft selected. Do not tap + // it here: typing immediately is the behavior under test. + prompt.typeText("replacement") + XCTAssertEqual(prompt.value as? String, "replacement") + } + + private func openQuickQuestionFromHomeScreen() { + XCUIDevice.shared.press(.home) + let sybilIcon = springboard.icons.matching(identifier: "Sybil").firstMatch + XCTAssertTrue(sybilIcon.waitForExistence(timeout: 10)) + sybilIcon.press(forDuration: 1.2) + + let quickQuestion = springboard.buttons["Quick question"] + XCTAssertTrue(quickQuestion.waitForExistence(timeout: 5)) + quickQuestion.tap() + } + + private func dismissQuickQuestion(_ prompt: XCUIElement) { + if app.keyboards.firstMatch.exists, app.scrollViews.firstMatch.exists { + app.scrollViews.firstMatch.swipeDown() + } + + let grabber = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.08)) + let lowerSheet = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.92)) + grabber.press(forDuration: 0.1, thenDragTo: lowerSheet) + + let dismissed = expectation(for: NSPredicate(format: "exists == false"), evaluatedWith: prompt) + wait(for: [dismissed], timeout: 5) + } + + private func control(_ body: [String: Any]) async throws { + var request = URLRequest(url: URL(string: "http://127.0.0.1:8799/control")!) + request.httpMethod = "POST" + request.httpBody = try JSONSerialization.data(withJSONObject: body) + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + let (_, response) = try await URLSession.shared.data(for: request) + XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 200) + } +}