Revision control

Copy as Markdown

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
import Common
import Shared
import ComponentLibrary
// TODO: - FXIOS-16295 improve VoiceOver by adding notification announcement before and after recording.
public final class QuickAnswersViewController: UIViewController, Themeable {
private enum UX {
static let titleFadeDuration: TimeInterval = 0.1
static let presentationNavigationBarOffset: CGFloat = -20.0
static let backdropFadeDuration: TimeInterval = 0.2
static let followUpButtonSize: CGFloat = 62.0
static let followUpFadeOutDuration: TimeInterval = 0.3
static let followUpFadeInDuration: TimeInterval = 0.2
static let resultBlobsFadeDelay: TimeInterval = 0.2
}
// MARK: - Properties
private lazy var backgroundEffectView = AIBackgroundEffectView(parentController: self)
private lazy var closeButton: UIButton = .build { [weak self] in
$0.setImage(
UIImage(named: StandardImageIdentifiers.Large.cross)?.withRenderingMode(.alwaysTemplate),
for: .normal
)
$0.addAction(
UIAction(handler: { _ in
self?.dismiss(with: nil)
}),
for: .touchUpInside
)
}
private let titleLabel: UILabel = .build {
$0.font = FXFontStyles.Bold.body.scaledFont()
$0.adjustsFontForContentSizeCategory = true
$0.alpha = 0.0
}
private lazy var followUpButton: QuickAnswersEntryPointButton = .build(nil) { [weak self] in
QuickAnswersEntryPointButton {
self?.startFollowUp()
}
}
private var followUpButtonTitle: String {
return viewModel.supportsFollowUpQuestions
? stringsConfiguration.contentView.followUpButton
: stringsConfiguration.contentView.newQuestionButton
}
/// Replaced by a new instance for each question asked after an answer, so no state from the previous one leaks.
private lazy var contentView = makeContentView(isFollowUpQuestion: false)
private let transitionDelegate: OptInTransitionAnimator
public let themeManager: any ThemeManager
public var currentWindowUUID: WindowUUID?
public var themeListenerCancellable: Any?
private let windowUUID: WindowUUID
private let notificationCenter: NotificationProtocol
private weak var navigationHandler: QuickAnswersNavigationHandler?
private let viewModel: QuickAnswersViewModel
private let learnMoreURL: URL?
private let stringsConfiguration: QuickAnswersViewConfiguration
private lazy var errorHandler = ErrorHandler(
presenter: self,
strings: stringsConfiguration.errors,
onDismiss: { [weak self] in
self?.dismiss(with: nil)
}
)
private lazy var privacyTipPresenter = QuickAnswersPrivacyTipPresenter(
presenter: self,
strings: stringsConfiguration.privacyBanner
)
public convenience init(
navigationHandler: QuickAnswersNavigationHandler?,
transitionType: QuickAnswersTransitionType,
prefs: Prefs,
windowUUID: WindowUUID,
themeManager: any ThemeManager,
telemetry: QuickAnswersTelemetry,
configFetcher: QuickAnswersConfigFetcher,
learnMoreURL: URL?,
stringsConfiguration: QuickAnswersViewConfiguration,
notificationCenter: NotificationProtocol = NotificationCenter.default,
) {
self.init(
navigationHandler: navigationHandler,
viewModel: QuickAnswersViewModel(prefs: prefs, telemetry: telemetry, configFetcher: configFetcher),
transitionType: transitionType,
windowUUID: windowUUID,
themeManager: themeManager,
learnMoreURL: learnMoreURL,
stringsConfiguration: stringsConfiguration,
notificationCenter: notificationCenter
)
}
init(
navigationHandler: QuickAnswersNavigationHandler?,
viewModel: QuickAnswersViewModel,
transitionType: QuickAnswersTransitionType,
windowUUID: WindowUUID,
themeManager: any ThemeManager,
learnMoreURL: URL?,
stringsConfiguration: QuickAnswersViewConfiguration,
notificationCenter: NotificationProtocol
) {
self.navigationHandler = navigationHandler
self.currentWindowUUID = windowUUID
self.windowUUID = windowUUID
self.themeManager = themeManager
self.notificationCenter = notificationCenter
self.stringsConfiguration = stringsConfiguration
let sourceRevealAnimator: SourceRevealTransitionAnimator = switch transitionType {
case let .sourceReveal(sourceRect):
SourceRevealTransitionAnimator(sourceRect: sourceRect, isOptInVisible: viewModel.isOptInRequired)
}
self.transitionDelegate = OptInTransitionAnimator(
isOptInSheetPending: { [weak viewModel] in
viewModel?.isOptInSheetRequired ?? false
},
fallback: sourceRevealAnimator
)
self.viewModel = viewModel
self.learnMoreURL = learnMoreURL
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .custom
transitioningDelegate = transitionDelegate
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
applyTheme()
listenForThemeChanges(withNotificationCenter: notificationCenter)
registerCallbacks()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.startFlow()
}
private func setupSubviews() {
closeButton.accessibilityLabel = stringsConfiguration.closeAccessibilityLabel
closeButton.showsLargeContentViewer = true
closeButton.largeContentTitle = stringsConfiguration.closeAccessibilityLabel
view.addSubview(backgroundEffectView)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeButton)
navigationItem.titleView = titleLabel
backgroundEffectView.pinToSuperview()
installContentView(contentView)
if viewModel.feature.isFollowUpEnabled {
setupFollowUpToolbar()
}
}
private func makeContentView(isFollowUpQuestion: Bool) -> QuickAnswersContentView {
let contentView: QuickAnswersContentView = .build()
contentView.configureStrings(stringsConfiguration.contentView, isFollowUpQuestion: isFollowUpQuestion)
contentView.onTranscriptVisibilityChange = { [weak self] isTranscriptVisible, transcript in
UIView.animate(withDuration: UX.titleFadeDuration) {
self?.titleLabel.alpha = isTranscriptVisible ? 0.0 : 1.0
self?.titleLabel.text = isTranscriptVisible ? nil : transcript
}
}
if #available(iOS 17.0, *) {
contentView.configurePrivacyLink { [weak self] in
self?.presentPrivacyTip()
}
}
contentView.applyTheme(theme: themeManager.getCurrentTheme(for: windowUUID))
return contentView
}
private func installContentView(_ contentView: QuickAnswersContentView) {
view.insertSubview(contentView, aboveSubview: backgroundEffectView)
setContentScrollView(contentView.scrollView, for: .top)
contentView.pinToSuperview()
}
private func setupFollowUpToolbar() {
followUpButton.accessibilityLabel = followUpButtonTitle
NSLayoutConstraint.activate([
followUpButton.widthAnchor.constraint(greaterThanOrEqualToConstant: UX.followUpButtonSize),
followUpButton.heightAnchor.constraint(equalToConstant: UX.followUpButtonSize),
])
let followUpItem = UIBarButtonItem(customView: followUpButton)
if #available(iOS 26, *) {
followUpItem.hidesSharedBackground = true
}
toolbarItems = [.flexibleSpace(), followUpItem, .flexibleSpace()]
}
private func registerCallbacks() {
viewModel.onStateChange = { [weak self] state in
switch state {
case .showOptIn:
self?.showOptIn()
case .recordingStarted:
self?.triggerHaptic()
self?.contentView.startAudioWaveformAnimation()
case .speechResult(let result, let error):
if let error {
self?.errorHandler.handleSpeechError(error)
} else {
self?.contentView.configureTranscript(result.text)
}
case .loadingSearchResult:
UIAccessibility.post(notification: .screenChanged, argument: self?.contentView)
self?.triggerHaptic()
self?.contentView.configureSearching()
case .showSearchResult(let result, let error):
if let error {
self?.errorHandler.handleSearchError(error)
} else {
self?.triggerHaptic()
self?.backgroundEffectView.showResult(blobsRevealDelay: UX.resultBlobsFadeDelay)
self?.showFollowUpButton()
self?.contentView.configureResult(
result.resultText,
modelName: self?.viewModel.modelDisplayName ?? "",
sources: result.sources
) { [weak self] url in
self?.viewModel.recordCitationTapped()
self?.dismiss(with: url)
}
}
}
}
contentView.configureOptIn(
strings: stringsConfiguration.optIn,
learnMoreURL: learnMoreURL,
theme: themeManager.getCurrentTheme(for: windowUUID),
onContinue: { [weak self] in
self?.contentView.hideOptIn()
self?.viewModel.completeOptIn()
},
onLearnMore: { [weak self] url in
self?.dismiss(with: url)
}
)
}
@available(iOS 17.0, *)
private func presentPrivacyTip() {
privacyTipPresenter.present(
from: contentView.privacyTipSourceView,
iconColor: themeManager.getCurrentTheme(for: currentWindowUUID).colors.textSecondary
)
}
// MARK: - Opt-in
private func showOptIn() {
guard viewModel.feature.isOptInRedesignEnabled else {
contentView.showOptIn()
return
}
let controller = OptInViewController(
windowUUID: windowUUID,
themeManager: themeManager,
strings: stringsConfiguration.optInRedesign,
closeAccessibilityLabel: stringsConfiguration.closeAccessibilityLabel,
onContinue: { [weak self] in
self?.presentedViewController?.dismiss(animated: true)
self?.viewModel.completeOptIn()
},
onLearnMore: { [weak self] in
self?.dismiss(with: self?.learnMoreURL)
},
onDismiss: { [weak self] in
self?.dismiss(with: nil)
}
)
present(controller, animated: true) { [weak self] in
self?.revealBackdrop()
}
}
/// Fades in this screen, which the presentation transition keeps hidden while the opt-in sheet slides up.
private func revealBackdrop() {
guard let backdropView = transitionDelegate.hiddenContainerView,
let superview = backdropView.superview else { return }
// Cross-dissolved rather than faded in, since the form sheet materials flash while an ancestor's alpha animates.
UIView.transition(with: superview, duration: UX.backdropFadeDuration, options: .transitionCrossDissolve) {
backdropView.isHidden = false
}
}
// MARK: - Presentation transition
func prepareForPresentationTransition(sourceRect: CGRect, isOptInVisible: Bool) {
contentView.prepareForPresentationTransition(
sourceRect: sourceRect,
containerWidth: view.frame.width,
topInset: navigationController?.navigationBar.frame.maxY ?? 0.0,
isOptInVisible: isOptInVisible
)
backgroundEffectView.alpha = 0.0
backgroundEffectView.prepareForPresentationTransition()
navigationController?.navigationBar.transform = CGAffineTransform(
translationX: 0.0,
y: UX.presentationNavigationBarOffset
)
navigationController?.navigationBar.alpha = 0.0
}
func applyPresentationTransition(isOptInVisible: Bool) {
contentView.applyPresentationTransition(isOptInVisible: isOptInVisible)
backgroundEffectView.alpha = 1.0
backgroundEffectView.applyPresentationTransition()
navigationController?.navigationBar.alpha = 1.0
navigationController?.navigationBar.transform = .identity
}
private func showFollowUpButton() {
guard viewModel.feature.isFollowUpEnabled else { return }
navigationController?.setToolbarHidden(false, animated: false)
followUpButton.revealTitle(followUpButtonTitle)
}
private func startFollowUp() {
navigationController?.setToolbarHidden(true, animated: true)
backgroundEffectView.hideResult(duration: UX.followUpFadeOutDuration)
UIView.animate(withDuration: UX.followUpFadeOutDuration, delay: 0.0, options: .curveEaseIn) { [self] in
titleLabel.alpha = 0.0
}
contentView.animateOut(duration: UX.followUpFadeOutDuration) { [weak self] in
self?.replaceContentViewForFollowUp()
}
}
private func replaceContentViewForFollowUp() {
contentView.removeFromSuperview()
titleLabel.text = nil
contentView = makeContentView(isFollowUpQuestion: viewModel.supportsFollowUpQuestions)
contentView.alpha = 0.0
installContentView(contentView)
UIView.animate(withDuration: UX.followUpFadeInDuration) { [self] in
contentView.alpha = 1.0
}
UIAccessibility.post(notification: .screenChanged, argument: contentView)
viewModel.startFollowUp()
}
private func dismiss(with url: URL?) {
triggerHaptic()
viewModel.dismiss()
navigationHandler?.dismissQuickAnswers(with: url.flatMap(QuickAnswersNavigationType.url))
}
private func triggerHaptic() {
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.prepare()
generator.impactOccurred()
}
// MARK: - Themeable
public func applyTheme() {
let theme = themeManager.getCurrentTheme(for: windowUUID)
view.backgroundColor = theme.colors.layer1
closeButton.tintColor = theme.colors.iconPrimary
titleLabel.textColor = theme.colors.textPrimary
followUpButton.configure(theme: theme, shouldStartGlowing: false)
contentView.applyTheme(theme: theme)
backgroundEffectView.applyTheme(theme: theme)
}
}