-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathMainViewController+UnifiedToggleInput.swift
More file actions
701 lines (594 loc) · 28.9 KB
/
MainViewController+UnifiedToggleInput.swift
File metadata and controls
701 lines (594 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//
// MainViewController+UnifiedToggleInput.swift
// DuckDuckGo
//
// Copyright © 2026 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AIChat
import Bookmarks
import Combine
import DesignResourcesKit
import Subscription
import Suggestions
import UIKit
// MARK: - Unified Toggle Input Setup
extension MainViewController {
enum UnifiedInputChromeBackgroundState: String {
case standardChrome
case aiTabSearchChromeHidden
case aiTabChatChromeHidden
}
func setUpUnifiedToggleInputIfNeeded() {
guard unifiedToggleInputFeature.isAvailable else { return }
let coordinator = UnifiedToggleInputCoordinator(
isToggleEnabled: aiChatSettings.isAIChatSearchInputUserSettingsEnabled,
duckAiNativeStorageHandler: duckAiNativeStorageHandler,
toggleModeStorage: toggleModeStorage
)
coordinator.delegate = self
coordinator.updateVoiceSearchAvailability(voiceSearchHelper.isVoiceSearchEnabled)
coordinator.updateAIVoiceChatAvailability(voiceShortcutFeature.isAvailable)
coordinator.onAnimatedDismissToOmnibar = { [weak self] in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
self.dismissUnifiedToggleInputToOmnibar(coordinator: coordinator)
}
self.unifiedToggleInputCoordinator = coordinator
installUnifiedToggleInputViewController(coordinator.viewController)
if let omniBarVC = viewCoordinator.omniBar as? DefaultOmniBarViewController {
omniBarVC.unifiedToggleInputOmnibarActivating = self
}
setUpAIChatTabChatHeader()
installUnifiedInputContentViewController()
installFloatingSubmitViewController()
subscribeToIntentPublisher(coordinator)
subscribeToModeChanges(coordinator)
subscribeToSystemEvents()
subscribeToToggleSettings()
}
func updateUnifiedToggleInputKeyboardVisibility(_ keyboardVisible: Bool) {
unifiedToggleInputCoordinator?.updateOmnibarInputVisibility(keyboardVisible)
}
func refreshUnifiedToggleInput(for tab: TabViewController) {
guard unifiedToggleInputFeature.isAvailable,
let coordinator = unifiedToggleInputCoordinator else {
return
}
let action = refreshAction(for: tab, coordinator: coordinator)
switch action {
case .unbindInactiveNonAITab:
refreshInactiveNonAITab(tab: tab, coordinator: coordinator)
tab.updateWebViewBottomAnchor(for: currentBarsVisibility)
return
case .refreshAITab(let behavior):
let completedRefresh = refreshAITab(tab: tab, coordinator: coordinator, behavior: behavior)
if !completedRefresh {
return
}
case .refreshNonAITab:
refreshNonAITab(tab: tab, coordinator: coordinator)
}
tab.updateWebViewBottomAnchor(for: currentBarsVisibility)
}
func applyUnifiedInputChromeBackground(_ state: UnifiedInputChromeBackgroundState, updateWebView: Bool = true) {
let statusBackgroundPresentation: MainViewCoordinator.StatusBackgroundPresentation
let containerBackgroundColor: UIColor?
let webViewBackgroundColor: UIColor?
switch state {
case .standardChrome:
statusBackgroundPresentation = .standard
containerBackgroundColor = nil
webViewBackgroundColor = nil
case .aiTabSearchChromeHidden:
statusBackgroundPresentation = .aiTabSearchChromeHidden
containerBackgroundColor = .clear
webViewBackgroundColor = .clear
case .aiTabChatChromeHidden:
statusBackgroundPresentation = .aiTabChatChromeHidden
containerBackgroundColor = .clear
webViewBackgroundColor = .clear
}
viewCoordinator.setStatusBackgroundPresentation(statusBackgroundPresentation)
if case .standardChrome = state {
refreshStatusBarBackgroundAfterAIChrome()
}
viewCoordinator.navigationBarContainer.backgroundColor = containerBackgroundColor
viewCoordinator.unifiedInputContentContainer?.backgroundColor = containerBackgroundColor ?? .clear
viewCoordinator.unifiedToggleInputContainer.backgroundColor = .clear
unifiedToggleInputCoordinator?.viewController.view.backgroundColor = .clear
guard updateWebView else { return }
if let webView = currentTab?.webView {
webView.backgroundColor = webViewBackgroundColor
webView.scrollView.backgroundColor = webViewBackgroundColor
webView.underPageBackgroundColor = webViewBackgroundColor
}
}
func recomputeOmnibarEditingHeightIfNeeded() {
guard let coordinator = unifiedToggleInputCoordinator,
coordinator.isOmnibarSession else {
return
}
let height = coordinator.omnibarEditingHeight()
guard viewCoordinator.constraints.navigationBarContainerHeight.constant != height else { return }
viewCoordinator.constraints.navigationBarContainerHeight.constant = height
viewCoordinator.navigationBarContainer.superview?.layoutIfNeeded()
coordinator.pushContentInsets()
}
}
private extension MainViewController {
enum UnifiedToggleInputRefreshAction {
case unbindInactiveNonAITab
case refreshAITab(AITabRefreshBehavior)
case refreshNonAITab
}
enum AITabRefreshBehavior {
case preserveCurrentPresentation(allowsEarlyReturn: Bool)
case showCollapsed(expandAfterRefresh: Bool)
}
func installUnifiedToggleInputViewController(_ inputVC: UnifiedToggleInputViewController) {
addChild(inputVC)
inputVC.view.translatesAutoresizingMaskIntoConstraints = false
viewCoordinator.unifiedToggleInputContainer.addSubview(inputVC.view)
NSLayoutConstraint.activate([
inputVC.view.topAnchor.constraint(equalTo: viewCoordinator.unifiedToggleInputContainer.topAnchor),
inputVC.view.leadingAnchor.constraint(equalTo: viewCoordinator.unifiedToggleInputContainer.leadingAnchor),
inputVC.view.trailingAnchor.constraint(equalTo: viewCoordinator.unifiedToggleInputContainer.trailingAnchor),
inputVC.view.bottomAnchor.constraint(equalTo: viewCoordinator.unifiedToggleInputContainer.bottomAnchor),
])
inputVC.didMove(toParent: self)
}
func subscribeToIntentPublisher(_ coordinator: UnifiedToggleInputCoordinator) {
coordinator.intentPublisher
.sink { [weak self] intent in
self?.handleUnifiedToggleInputIntent(intent)
}
.store(in: &unifiedToggleInputCancellables)
}
func subscribeToModeChanges(_ coordinator: UnifiedToggleInputCoordinator) {
coordinator.modeChangePublisher
.sink { [weak self] mode in
self?.handleModeChange(mode)
}
.store(in: &unifiedToggleInputCancellables)
coordinator.attachmentsChangePublisher
.sink { [weak self] in
guard let self, let coordinator = unifiedToggleInputCoordinator else { return }
if coordinator.isAITabExpanded || coordinator.isOmnibarSession {
adjustUI(withKeyboardFrame: latestKeyboardFrame, in: 0.2, animationCurve: .curveEaseInOut)
}
}
.store(in: &unifiedToggleInputCancellables)
}
func handleModeChange(_ mode: TextEntryMode) {
guard let coordinator = unifiedToggleInputCoordinator else { return }
if coordinator.isOmnibarSession {
handleOmnibarModeChange(mode, coordinator: coordinator)
} else if coordinator.isAITabExpanded {
handleAITabModeChange(mode, coordinator: coordinator)
} else if coordinator.isAITabState && mode == .aiChat {
coordinator.showExpanded(inputMode: .aiChat)
}
}
func handleOmnibarModeChange(_ mode: TextEntryMode, coordinator: UnifiedToggleInputCoordinator) {
updateUnifiedInputContentVisibility(for: coordinator)
syncBottomOmnibarAnchorIfNeeded(for: coordinator)
adjustUI(withKeyboardFrame: latestKeyboardFrame, in: 0.2, animationCurve: .curveEaseInOut)
unifiedToggleInputCoordinator?.syncContentInputMode(mode)
updateFloatingSubmitVisibility()
}
func handleAITabModeChange(_ mode: TextEntryMode, coordinator: UnifiedToggleInputCoordinator) {
UIView.performWithoutAnimation {
updateUnifiedInputContentVisibility(for: coordinator)
let chromeBackgroundState = aiTabChromeBackgroundState(for: coordinator.computeRenderState())
applyUnifiedInputChromeBackground(chromeBackgroundState)
viewCoordinator.navigationBarContainer.superview?.layoutIfNeeded()
}
adjustUI(withKeyboardFrame: latestKeyboardFrame, in: 0.2, animationCurve: .curveEaseInOut)
if keyboardShowing,
!coordinator.viewController.isInputFirstResponder,
currentTab?.aiChatContextualSheetCoordinator.isSheetPresented != true {
DispatchQueue.main.async { [weak coordinator] in
guard let coordinator, coordinator.isAITabExpanded else { return }
coordinator.activateInput()
}
}
}
func subscribeToSystemEvents() {
NotificationCenter.default.publisher(for: .speechRecognizerDidChangeAvailability)
.sink { [weak self] _ in
guard let self else { return }
self.unifiedToggleInputCoordinator?.updateVoiceSearchAvailability(self.voiceSearchHelper.isVoiceSearchEnabled)
}
.store(in: &unifiedToggleInputCancellables)
NotificationCenter.default.publisher(for: .entitlementsDidChange)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self else { return }
self.unifiedToggleInputCoordinator?.fetchModels()
if self.currentTab?.isAITab == true {
self.refreshAIChatTabChatHeaderSubscriptionState()
}
}
.store(in: &unifiedToggleInputCancellables)
}
func subscribeToToggleSettings() {
NotificationCenter.default.publisher(for: .aiChatSettingsChanged)
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
let enabled = self.aiChatSettings.isAIChatSearchInputUserSettingsEnabled
coordinator.updateToggleEnabled(enabled)
coordinator.contentViewController.isSwipeEnabled = enabled
}
.store(in: &unifiedToggleInputCancellables)
}
func refreshAction(for tab: TabViewController, coordinator: UnifiedToggleInputCoordinator) -> UnifiedToggleInputRefreshAction {
if !tab.isAITab {
if !coordinator.isActive && viewCoordinator.aiChatTabChatHeaderContainer.isHidden {
return .unbindInactiveNonAITab
}
return .refreshNonAITab
}
if coordinator.isAITabState {
return .refreshAITab(.preserveCurrentPresentation(allowsEarlyReturn: viewCoordinator.isNavigationChromeHidden))
}
let hasExistingChat = tab.url?.duckAIChatID != nil
let tabURL = tab.url ?? tab.link?.url
let isVoiceMode = tabURL?.isDuckAIVoiceMode == true || tab.isVoiceModeRequested
let isSidebarOpen = tabURL?.isDuckAISidebarOpen == true
tab.isVoiceModeRequested = false
let shouldExpandAfterRefresh = !hasExistingChat && !coordinator.hasSubmittedPrompt && !isVoiceMode && !isSidebarOpen
return .refreshAITab(.showCollapsed(expandAfterRefresh: shouldExpandAfterRefresh))
}
func refreshInactiveNonAITab(tab: TabViewController, coordinator: UnifiedToggleInputCoordinator) {
coordinator.unbind()
viewCoordinator.hideAITabChrome()
applyUnifiedInputChromeBackground(.standardChrome)
viewCoordinator.moveAddressBarToPosition(appSettings.currentAddressBarPosition)
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
}
func refreshAITab(
tab: TabViewController,
coordinator: UnifiedToggleInputCoordinator,
behavior: AITabRefreshBehavior
) -> Bool {
let hasExistingChat = tab.url?.duckAIChatID != nil
bindAITabIfPossible(tab: tab, coordinator: coordinator, hasExistingChat: hasExistingChat)
if case .preserveCurrentPresentation(let allowsEarlyReturn) = behavior, allowsEarlyReturn {
syncPreservedAITabPresentation(coordinator: coordinator)
return false
}
ensureStandardChromeVisibleForAITabRefresh()
tab.webView.scrollView.contentInset = .zero
coordinator.deactivateToOmnibar()
viewCoordinator.showAITabChrome()
applyUnifiedInputChromeBackground(.aiTabChatChromeHidden)
applyAITabRefreshBehavior(behavior, coordinator: coordinator)
updateUnifiedInputContentVisibility(for: coordinator)
refreshAIChatTabChatHeaderSubscriptionState()
tab.borderView.isTopVisible = false
tab.borderView.isBottomVisible = false
return true
}
func bindAITabIfPossible(tab: TabViewController, coordinator: UnifiedToggleInputCoordinator, hasExistingChat: Bool) {
if let userScript = tab.userScripts?.aiChatUserScript {
coordinator.bindToTab(userScript, hasExistingChat: hasExistingChat)
}
}
func ensureStandardChromeVisibleForAITabRefresh() {
guard swipeTabsCoordinator?.tabsModel != nil else { return }
showBars()
}
}
extension MainViewController {
func aiTabChromeBackgroundState(for renderState: UTIRenderState) -> UnifiedInputChromeBackgroundState {
renderState.isContentVisible ? .aiTabSearchChromeHidden : .aiTabChatChromeHidden
}
}
private extension MainViewController {
func syncPreservedAITabPresentation(coordinator: UnifiedToggleInputCoordinator) {
let renderState = coordinator.computeRenderState()
let chromeBackgroundState = aiTabChromeBackgroundState(for: renderState)
applyUnifiedInputChromeBackground(chromeBackgroundState)
updateUnifiedInputContentVisibility(for: coordinator)
refreshAIChatTabChatHeaderSubscriptionState()
}
func applyAITabRefreshBehavior(_ behavior: AITabRefreshBehavior, coordinator: UnifiedToggleInputCoordinator) {
switch behavior {
case .preserveCurrentPresentation:
break
case .showCollapsed(let expandAfterRefresh):
coordinator.showCollapsed()
guard expandAfterRefresh else { return }
DispatchQueue.main.async { [weak coordinator] in
guard let coordinator, coordinator.isAITabState else { return }
coordinator.showExpanded(inputMode: .aiChat)
}
}
}
func refreshNonAITab(tab: TabViewController, coordinator: UnifiedToggleInputCoordinator) {
coordinator.deactivateToOmnibar()
coordinator.hide()
coordinator.unbind()
viewCoordinator.hideAITabChrome()
viewCoordinator.moveAddressBarToPosition(appSettings.currentAddressBarPosition)
refreshViewsBasedOnAddressBarPosition(appSettings.currentAddressBarPosition)
applyUnifiedInputChromeBackground(.standardChrome)
tab.borderView.updateForAddressBarPosition(appSettings.currentAddressBarPosition)
tab.borderView.isBottomVisible = true
}
func setUpAIChatTabChatHeader() {
let headerView = AIChatTabChatHeaderView()
headerView.delegate = self
headerView.translatesAutoresizingMaskIntoConstraints = false
viewCoordinator.aiChatTabChatHeaderContainer.addSubview(headerView)
NSLayoutConstraint.activate([
headerView.topAnchor.constraint(equalTo: viewCoordinator.aiChatTabChatHeaderContainer.topAnchor),
headerView.leadingAnchor.constraint(equalTo: viewCoordinator.aiChatTabChatHeaderContainer.leadingAnchor),
headerView.trailingAnchor.constraint(equalTo: viewCoordinator.aiChatTabChatHeaderContainer.trailingAnchor),
headerView.bottomAnchor.constraint(equalTo: viewCoordinator.aiChatTabChatHeaderContainer.bottomAnchor),
])
self.aiChatTabChatHeaderView = headerView
}
func refreshAIChatTabChatHeaderSubscriptionState() {
Task { @MainActor [weak self] in
let isActive = (try? await AppDependencyProvider.shared.subscriptionManager.isFeatureEnabled(.paidAIChat)) ?? false
self?.aiChatTabChatHeaderView?.configure(isSubscriptionActive: isActive)
}
}
}
extension MainViewController {
func updateUnifiedInputContentVisibility(for coordinator: UnifiedToggleInputCoordinator) {
let isOnAITab = currentTab?.isAITab == true
let renderState = coordinator.computeRenderState()
if coordinator.isAITabState {
coordinator.contentViewController.forceBottomBarLayout = true
} else {
coordinator.contentViewController.forceBottomBarLayout = false
}
applyTopChromeState(renderState: renderState, isOnAITab: isOnAITab, coordinator: coordinator)
}
func applyTopChromeState(renderState: UTIRenderState, isOnAITab: Bool, coordinator: UnifiedToggleInputCoordinator) {
if isOnAITab, viewCoordinator.isNavigationChromeHidden {
let chromeBackgroundState = aiTabChromeBackgroundState(for: renderState)
applyUnifiedInputChromeBackground(chromeBackgroundState, updateWebView: false)
}
if coordinator.isAITabState {
coordinator.applyDismissButtonVisibility()
}
viewCoordinator.updateUnifiedToggleInputColors(
inputView: coordinator.viewController.view
)
if renderState.isContentVisible {
coordinator.contentViewController.setActive(true)
coordinator.syncContentInputMode(renderState.contentInputMode, animated: false)
coordinator.pushContentInsets()
viewCoordinator.showUnifiedInputContent()
coordinator.contentViewController.refreshVisibleContentIfNeeded()
} else {
coordinator.contentViewController.setActive(false)
viewCoordinator.hideUnifiedInputContent()
}
if isOnAITab {
if renderState.isContentVisible {
viewCoordinator.hideAIChatTabChatHeader()
} else {
viewCoordinator.showAIChatTabChatHeader()
}
if viewIfLoaded?.window != nil {
view.layoutIfNeeded()
}
}
}
func installUnifiedInputContentViewController() {
guard let coordinator = unifiedToggleInputCoordinator,
let container = viewCoordinator.unifiedInputContentContainer else {
return
}
let contentVC = coordinator.contentViewController
contentVC.suggestionTrayDependencies = suggestionTrayDependencies
contentVC.delegate = self
contentVC.onDismissRequested = { [weak self] in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
if coordinator.isOmnibarSession {
self.dismissUnifiedToggleInputToOmnibar(coordinator: coordinator)
} else if coordinator.isAITabExpanded {
coordinator.showCollapsed()
}
}
contentVC.onSwipeDownRequested = { [weak self] in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
coordinator.dismissOmnibarKeyboard()
}
contentVC.isSwipeEnabled = coordinator.isToggleEnabled
addChild(contentVC)
contentVC.view.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(contentVC.view)
NSLayoutConstraint.activate([
contentVC.view.topAnchor.constraint(equalTo: container.topAnchor),
contentVC.view.leadingAnchor.constraint(equalTo: container.leadingAnchor),
contentVC.view.trailingAnchor.constraint(equalTo: container.trailingAnchor),
contentVC.view.bottomAnchor.constraint(equalTo: container.bottomAnchor),
])
contentVC.didMove(toParent: self)
}
func installFloatingSubmitViewController() {
guard let coordinator = unifiedToggleInputCoordinator else { return }
let floatingVC = coordinator.floatingSubmitViewController
floatingVC.delegate = self
addChild(floatingVC)
floatingVC.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(floatingVC.view)
NSLayoutConstraint.activate([
floatingVC.view.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor, constant: -8),
floatingVC.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
floatingVC.didMove(toParent: self)
floatingVC.subscribe(to: coordinator.textChangePublisher)
floatingVC.view.isHidden = true
}
func updateFloatingSubmitVisibility() {
guard let coordinator = unifiedToggleInputCoordinator else { return }
let renderState = coordinator.computeRenderState()
coordinator.floatingSubmitViewController.view.isHidden = !renderState.isFloatingSubmitVisible
}
}
private extension MainViewController {
func dismissUnifiedToggleInputToOmnibar(coordinator: UnifiedToggleInputCoordinator) {
applyUnifiedInputChromeBackground(.standardChrome)
let isTopPosition = coordinator.cardPosition == .top
if isTopPosition && coordinator.isToggleEnabled {
coordinator.viewController.animateToggleHide(additionalAnimations: { [weak self] in
guard let self else { return }
self.viewCoordinator.animateUnifiedToggleInputOmnibarDismissLayout()
self.viewCoordinator.unifiedInputContentContainer.alpha = 0
}, completion: { [weak self] in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
self.viewCoordinator.unifiedInputContentContainer.isHidden = true
self.viewCoordinator.unifiedInputContentContainer.alpha = 1
coordinator.deactivateToOmnibar(resetView: false, animateDismiss: false)
})
} else if isTopPosition {
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseInOut, animations: { [weak self] in
guard let self else { return }
self.viewCoordinator.animateUnifiedToggleInputOmnibarDismissLayout()
self.viewCoordinator.unifiedInputContentContainer.alpha = 0
}, completion: { [weak self] _ in
guard let self, let coordinator = self.unifiedToggleInputCoordinator else { return }
self.viewCoordinator.unifiedInputContentContainer.isHidden = true
self.viewCoordinator.unifiedInputContentContainer.alpha = 1
coordinator.deactivateToOmnibar(resetView: false, animateDismiss: false)
})
} else {
coordinator.deactivateToOmnibar()
}
}
func handleUnifiedToggleInputSearchSubmission(_ query: String) {
let isAITabSubmission = currentTab?.isAITab == true
if isAITabSubmission {
viewCoordinator.hideAITabChrome()
applyUnifiedInputChromeBackground(.standardChrome, updateWebView: false)
// Preempt any synchronous UI refresh triggered by loadQuery so the presentation stays mapped to standard chrome.
}
loadQuery(query)
if isAITabSubmission {
applyUnifiedInputChromeBackground(.standardChrome)
}
}
}
// MARK: - UnifiedToggleInputOmnibarActivating
extension MainViewController: UnifiedToggleInputOmnibarActivating {
func activateFromOmnibarIfNeeded(currentText: String?) -> UnifiedToggleInputActivationDecision {
guard let coordinator = unifiedToggleInputCoordinator,
currentTab?.isAITab != true else {
return .allowDefault
}
let position: UnifiedToggleInputCardPosition = appSettings.currentAddressBarPosition == .bottom ? .bottom : .top
let inputMode = tabManager.currentTabsModel.currentTab?.preferredTextEntryMode ?? .search
coordinator.activateFromOmnibar(prefilledText: currentText, inputMode: inputMode, cardPosition: position)
return .intercept
}
}
// MARK: - UnifiedToggleInputDelegate
extension MainViewController: UnifiedToggleInputDelegate {
func unifiedToggleInputDidCommitMode(_ mode: TextEntryMode) {
tabManager.currentTabsModel.currentTab?.preferredTextEntryMode = mode
}
func unifiedToggleInputDidSubmitPrompt(_ prompt: String, modelId: String?, tools: [AIChatRAGTool]?, images: [AIChatNativePrompt.NativePromptImage]?) {
openAIChat(prompt, autoSend: true, tools: tools, modelId: modelId, images: images)
}
func unifiedToggleInputDidSubmitQuery(_ query: String) {
handleUnifiedToggleInputSearchSubmission(query)
}
func unifiedToggleInputDidRequestVoiceSearch() {
let mode = unifiedToggleInputCoordinator?.inputMode ?? .search
if mode == .aiChat && voiceShortcutFeature.isAvailable {
onDuckAIVoiceModeRequested()
} else {
handleVoiceSearchOpenRequest(preferredTarget: mode == .aiChat ? .AIChat : .SERP)
}
}
func unifiedToggleInputDidChangeHeight() {
if unifiedToggleInputCoordinator?.isOmnibarSession == true {
recomputeOmnibarEditingHeightIfNeeded()
} else {
unifiedToggleInputCoordinator?.pushContentInsets()
}
}
}
// MARK: - UnifiedInputContentContainerViewControllerDelegate
extension MainViewController: UnifiedInputContentContainerViewControllerDelegate {
func unifiedInputEditingStateDidSubmitQuery(_ query: String) {
unifiedToggleInputCoordinator?.clearText()
unifiedToggleInputCoordinator?.handleExternalSubmission(.query)
handleUnifiedToggleInputSearchSubmission(query)
}
func unifiedInputEditingStateDidSubmitPrompt(_ query: String, tools: [AIChatRAGTool]?) {
unifiedToggleInputCoordinator?.clearText()
unifiedToggleInputCoordinator?.handleExternalSubmission(.prompt)
openAIChat(query, autoSend: true, tools: tools)
}
func unifiedInputEditingStateDidSelectFavorite(_ favorite: BookmarkEntity) {
handleFavoriteSelected(favorite)
}
func unifiedInputEditingStateDidEditFavorite(_ favorite: BookmarkEntity) {
segueToEditBookmark(favorite)
}
func unifiedInputEditingStateDidSelectSuggestion(_ suggestion: Suggestion) {
handleSuggestionSelected(suggestion)
}
func unifiedInputEditingStateDidSelectChatHistory(url: URL) {
onChatHistorySelected(url: url)
}
func unifiedInputEditingStateDidRequestSwitchTab(_ tab: Tab) {
onSwitchToTab(tab)
}
func unifiedInputEditingStateDidRequestFireMode() {
unifiedToggleInputCoordinator?.contentViewController.dismissAnimated()
navigateToFireMode()
}
func unifiedInputEditingStateDidChangeMode(_ mode: TextEntryMode) {
unifiedToggleInputCoordinator?.syncInputModeFromExternalSource(mode)
}
}
// MARK: - AIChatTabChatHeaderViewDelegate
extension MainViewController: AIChatTabChatHeaderViewDelegate {
func aiChatTabChatHeaderDidTapSettings() {
unifiedToggleInputCoordinator?.showCollapsed()
currentTab?.submitToggleSidebarAction()
}
func aiChatTabChatHeaderDidTapNewChat() {
unifiedToggleInputCoordinator?.startNewChat()
unifiedToggleInputCoordinator?.showExpanded(inputMode: .aiChat)
currentTab?.submitStartChatAction()
}
func aiChatTabChatHeaderDidTapUpgrade() {
NotificationCenter.default.post(
name: .settingsDeepLinkNotification,
object: SettingsViewModel.SettingsDeepLinkSection.subscriptionFlow()
)
}
}
// MARK: - UnifiedToggleInputFloatingSubmitDelegate
extension MainViewController: UnifiedToggleInputFloatingSubmitDelegate {
func floatingSubmitDidTapSubmit() {
guard let coordinator = unifiedToggleInputCoordinator else { return }
let text = coordinator.currentText
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
coordinator.switchBarHandler.submitText(text)
}
func floatingSubmitDidTapVoice() {
onDuckAIVoiceModeRequested()
}
}