Search tab (#5754)

* Add a developer flag for the search tab
Introduces a globalSearchEnabled user preference (off by default) with a toggle in Developer Options, used to gate the new search experience.

* Support search role tabs in the tab coordinator
Migrates the NavigationTabCoordinator to SwiftUI's value-based Tab API and adds an isSearch option so a tab can adopt the iOS 26 .search role, which detaches it into the trailing search button in the tab bar.

* Moves room search to a new screen
Adds a new screen that filters the alternate room summary provider as you type, shows an empty state, and lists matching rooms with their matrix identifier. Supports hardware keyboard selection (arrow keys to move through results, return to open) by reaching into the system search field.

* Present search in a dedicated tab
Adds the search tab to the chats flow on iOS 26 when the flag is enabled, rendered as the detached .search role button. The Cmd+K shortcut now selects this tab, and the home screen's inline search is hidden while the tab is available.

* Remove the old global search screen
The dedicated search tab replaces the Cmd+K floating window, so the GlobalSearchScreen, its window plumbing in the WindowManager, and its presentation in the chats flow are all removed.
This commit is contained in:
Stefan Ceriu
2026-06-19 13:50:17 +03:00
committed by GitHub
parent 9a6f7595e5
commit 7f1b6086ae
58 changed files with 731 additions and 780 deletions
@@ -1,58 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2023-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import Compound
import SwiftUI
struct GlobalSearchScreenCoordinatorParameters {
let roomSummaryProvider: RoomSummaryProviderProtocol
let mediaProvider: MediaProviderProtocol
}
enum GlobalSearchControllerAction {
case dismiss
case select(roomID: String)
}
class GlobalSearchScreenCoordinator: CoordinatorProtocol {
private let viewModel: GlobalSearchScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<GlobalSearchControllerAction, Never> = .init()
var actions: AnyPublisher<GlobalSearchControllerAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: GlobalSearchScreenCoordinatorParameters) {
viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: parameters.roomSummaryProvider,
mediaProvider: parameters.mediaProvider)
viewModel.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .dismiss:
actionsSubject.send(.dismiss)
case .select(let roomID):
actionsSubject.send(.select(roomID: roomID))
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(GlobalSearchScreen(context: viewModel.context))
}
func stop() {
viewModel.stop()
}
}
@@ -1,37 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Foundation
enum GlobalSearchScreenViewModelAction {
case dismiss
case select(roomID: String)
}
struct GlobalSearchScreenViewState: BindableState {
var rooms = [GlobalSearchRoom]()
var bindings: GlobalSearchScreenViewStateBindings
}
struct GlobalSearchScreenViewStateBindings {
var searchQuery: String
}
enum GlobalSearchScreenViewAction {
case dismiss
case select(roomID: String)
case reachedTop
case reachedBottom
}
struct GlobalSearchRoom: Identifiable, Equatable {
let id: String
let title: String
let description: String
let avatar: RoomAvatar
}
@@ -1,101 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import SwiftUI
typealias GlobalSearchScreenViewModelType = StateStoreViewModel<GlobalSearchScreenViewState, GlobalSearchScreenViewAction>
class GlobalSearchScreenViewModel: GlobalSearchScreenViewModelType, GlobalSearchScreenViewModelProtocol {
private let roomSummaryProvider: RoomSummaryProviderProtocol
private var actionsSubject: PassthroughSubject<GlobalSearchScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<GlobalSearchScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(roomSummaryProvider: RoomSummaryProviderProtocol,
mediaProvider: MediaProviderProtocol) {
self.roomSummaryProvider = roomSummaryProvider
super.init(initialViewState: GlobalSearchScreenViewState(bindings: .init(searchQuery: "")),
mediaProvider: mediaProvider)
roomSummaryProvider.roomListPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] summaries in
self?.updateRooms(with: summaries)
}
.store(in: &cancellables)
context.$viewState
.map(\.bindings.searchQuery)
.removeDuplicates()
.sink { [weak self] searchQuery in
if searchQuery.isEmpty {
self?.roomSummaryProvider.setFilter(.all(filters: []))
} else {
self?.roomSummaryProvider.setFilter(.search(query: searchQuery))
}
}
.store(in: &cancellables)
updateRooms(with: roomSummaryProvider.roomListPublisher.value)
}
func stop() {
// This is a shared provider so we should reset the filtering when we are done with the view
roomSummaryProvider.setFilter(.all(filters: []))
}
// MARK: - Public
override func process(viewAction: GlobalSearchScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .dismiss:
actionsSubject.send(.dismiss)
case .select(let roomID):
actionsSubject.send(.select(roomID: roomID))
case .reachedTop:
updateVisibleRange(edge: .top)
case .reachedBottom:
updateVisibleRange(edge: .bottom)
}
}
// MARK: - Private
private func updateRooms(with summaries: [RoomSummary]) {
state.rooms = summaries.compactMap { summary in
GlobalSearchRoom(id: summary.id,
title: summary.name,
description: summary.roomListDescription,
avatar: summary.avatar)
}
}
/// The actual range values don't matter as long as they contain the lower
/// or upper bounds. updateVisibleRange is a hybrid API that powers both
/// sliding sync visible range update and list paginations
/// For lists other than the home screen one we don't care about visible ranges,
/// we just need the respective bounds to be there to trigger a next page load or
/// a reset to just one page
private func updateVisibleRange(edge: UIRectEdge) {
switch edge {
case .top:
roomSummaryProvider.updateVisibleRange(0..<0)
case .bottom:
let roomCount = roomSummaryProvider.roomListPublisher.value.count
roomSummaryProvider.updateVisibleRange(roomCount..<roomCount)
default:
break
}
}
}
@@ -1,16 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
protocol GlobalSearchScreenViewModelProtocol {
var actions: AnyPublisher<GlobalSearchScreenViewModelAction, Never> { get }
var context: GlobalSearchScreenViewModelType.Context { get }
func stop()
}
@@ -1,215 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
struct GlobalSearchScreen: View {
@ObservedObject var context: GlobalSearchScreenViewModel.Context
@State private var selectedRoom: GlobalSearchRoom?
@FocusState private var searchFieldFocus
var body: some View {
List {
header
Section {
ForEach(context.viewState.rooms) { room in
GlobalSearchScreenListRow(room: room, context: context)
.listRowBackground(backgroundColor(for: room))
.listRowInsets(.init())
.contentShape(.rect)
.onTapGesture {
context.send(viewAction: .select(roomID: room.id))
}
.onAppear {
if room == context.viewState.rooms.first {
context.send(viewAction: .reachedTop)
} else if room == context.viewState.rooms.last {
context.send(viewAction: .reachedBottom)
}
}
}
}
}
.listStyle(.plain)
.frame(maxWidth: 700, maxHeight: 800)
.background(.compound.bgCanvasDefault)
.clipShape(RoundedRectangle(cornerRadius: 10))
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.black.opacity(0.5).ignoresSafeArea())
.background { keyboardShortcuts }
.onAppear {
selectedRoom = context.viewState.rooms.first
searchFieldFocus = true
}
.onChange(of: context.viewState.rooms) {
selectedRoom = context.viewState.rooms.first
}
.onTapGesture {
context.send(viewAction: .dismiss)
}
}
private var header: some View {
GlobalSearchTextFieldRepresentable(placeholder: L10n.actionSearch, text: $context.searchQuery) { keyCode in
switch keyCode {
case .keyboardUpArrow:
moveToNextEntry(backwards: true)
return true
case .keyboardDownArrow:
moveToNextEntry()
return true
case .keyboardReturnOrEnter, .keyboardReturn:
if let selectedRoom {
context.send(viewAction: .select(roomID: selectedRoom.id))
}
return true
case .keyboardEscape:
context.send(viewAction: .dismiss)
return true
default:
return false
}
} endEditingHandler: {
if let selectedRoom {
context.send(viewAction: .select(roomID: selectedRoom.id))
} else { // Bring the focus back to the text field
searchFieldFocus = true
}
}
.focused($searchFieldFocus)
.autocorrectionDisabled(true)
.autocapitalization(.none)
.textInputAutocapitalization(.never)
}
private var keyboardShortcuts: some View {
Button("") {
context.send(viewAction: .dismiss)
}
// Need this to enable escape on the textField and forward the presses
.keyboardShortcut(.escape, modifiers: [])
}
private func backgroundColor(for room: GlobalSearchRoom) -> Color {
if selectedRoom == room {
.compound.bgSubtlePrimary
} else {
.compound.bgCanvasDefault
}
}
private func moveToNextEntry(backwards: Bool = false) {
guard let selectedRoom else {
selectedRoom = context.viewState.rooms.first
return
}
guard let currentIndex = context.viewState.rooms.firstIndex(of: selectedRoom) else {
return
}
let nextIndex = (backwards ? currentIndex - 1 : currentIndex + 1)
guard context.viewState.rooms.indices.contains(nextIndex) else {
return
}
self.selectedRoom = context.viewState.rooms[nextIndex]
}
}
private struct GlobalSearchTextFieldRepresentable: UIViewRepresentable {
let placeholder: String
@Binding var text: String
let keyPressHandler: (UIKeyboardHIDUsage) -> Bool
let endEditingHandler: () -> Void
func makeUIView(context: Context) -> UITextField {
let textField = GlobalSearchTextField(keyPressHandler: keyPressHandler)
textField.delegate = context.coordinator
textField.autocorrectionType = .no
textField.placeholder = placeholder
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $text, endEditingHandler: endEditingHandler)
}
class Coordinator: NSObject, UITextFieldDelegate {
var text: Binding<String>
let endEditingHandler: () -> Void
init(text: Binding<String>, endEditingHandler: @escaping () -> Void) {
self.text = text
self.endEditingHandler = endEditingHandler
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// pressesBegan sometimes doesn't receive return events. Handle it here instead
if string.rangeOfCharacter(from: .newlines) != nil {
endEditingHandler()
return false
}
let currentText = textField.text ?? ""
DispatchQueue.main.async {
self.text.wrappedValue = (currentText as NSString).replacingCharacters(in: range, with: string)
}
return true
}
}
}
private class GlobalSearchTextField: UITextField {
let keyPressHandler: (UIKeyboardHIDUsage) -> Bool
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError()
}
init(keyPressHandler: @escaping (UIKeyboardHIDUsage) -> Bool) {
self.keyPressHandler = keyPressHandler
super.init(frame: .zero)
}
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
guard let key = presses.first?.key else {
super.pressesBegan(presses, with: event)
return
}
if keyPressHandler(key.keyCode) {
return
}
super.pressesBegan(presses, with: event)
}
}
// MARK: - Previews
struct GlobalSearchScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded(.mockRooms))),
mediaProvider: MediaProviderMock(.init()))
static var previews: some View {
ElementNavigationStack {
GlobalSearchScreen(context: viewModel.context)
}
}
}
@@ -1,54 +0,0 @@
//
// Copyright 2025 Element Creations Ltd.
// Copyright 2024-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
struct GlobalSearchScreenListRow: View {
@Environment(\.dynamicTypeSize) var dynamicTypeSize
let room: GlobalSearchRoom
let context: GlobalSearchScreenViewModel.Context
var body: some View {
ZStack { // The list row swallows listRowBackgrounds for some reason
ListRow(label: .avatar(title: room.title,
description: room.description,
icon: avatar),
kind: .label)
}
}
@ViewBuilder
var avatar: some View {
if dynamicTypeSize < .accessibility3 {
RoomAvatarImage(avatar: room.avatar,
avatarSize: .room(on: .messageForwarding),
mediaProvider: context.mediaProvider)
.dynamicTypeSize(dynamicTypeSize < .accessibility1 ? dynamicTypeSize : .accessibility1)
.accessibilityHidden(true)
}
}
}
struct GlobalSearchScreenListRow_Previews: PreviewProvider, TestablePreview {
static let viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded(.mockRooms))),
mediaProvider: MediaProviderMock(.init()))
static var previews: some View {
List {
GlobalSearchScreenListRow(room: .init(id: "123",
title: "Tech central",
description: "The best place in the whole wide world",
avatar: .room(id: "123",
name: "Tech central",
avatarURL: .mockMXCAvatar)),
context: viewModel.context)
}
}
}
@@ -115,6 +115,9 @@ struct HomeScreenViewState: BindableState {
var shouldShowSpaceFilters = false
var selectedSpaceFilter: SpaceServiceFilter?
/// Inline room list search is disabled when the dedicated global search tab is shown instead (see `UserSessionFlowCoordinator`).
var isRoomListSearchEnabled = true
var visibleRooms: [HomeScreenRoom] {
if roomListMode == .skeletons {
return placeholderRooms
@@ -49,6 +49,10 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
bindings: .init(filtersState: .init(appSettings: appSettings))),
mediaProvider: userSession.mediaProvider)
if appSettings.globalSearchEnabled, #available(iOS 26.0, *) {
state.isRoomListSearchEnabled = false
}
userSession.clientProxy.userAvatarURLPublisher
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userAvatarURL, on: self)
@@ -59,10 +59,9 @@ struct HomeScreenContent: View {
topSection
}
}
.isSearching($context.isSearchFieldFocused)
.searchable(text: $context.searchQuery, placement: .navigationBarDrawer(displayMode: .always))
.compoundSearchField()
.disableAutocorrection(true)
.roomListSearchable(isEnabled: context.viewState.isRoomListSearchEnabled,
isSearchFieldFocused: $context.isSearchFieldFocused,
searchQuery: $context.searchQuery)
}
}
.introspect(.scrollView, on: .supportedVersions) { scrollView in
@@ -161,3 +160,17 @@ struct HomeScreenContent: View {
context.send(viewAction: .updateVisibleItemRange(firstIndex..<lastIndex))
}
}
private extension View {
@ViewBuilder
func roomListSearchable(isEnabled: Bool, isSearchFieldFocused: Binding<Bool>, searchQuery: Binding<String>) -> some View {
if isEnabled {
isSearching(isSearchFieldFocused)
.searchable(text: searchQuery, placement: .navigationBarDrawer(displayMode: .always))
.compoundSearchField()
.disableAutocorrection(true)
} else {
self
}
}
}
@@ -0,0 +1,49 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import SwiftUI
struct SearchScreenCoordinatorParameters {
let roomSummaryProvider: RoomSummaryProviderProtocol
let mediaProvider: MediaProviderProtocol
}
enum SearchScreenCoordinatorAction {
case presentRoom(roomID: String)
}
final class SearchScreenCoordinator: CoordinatorProtocol {
private let viewModel: SearchScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<SearchScreenCoordinatorAction, Never> = .init()
var actionsPublisher: AnyPublisher<SearchScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SearchScreenCoordinatorParameters) {
viewModel = SearchScreenViewModel(roomSummaryProvider: parameters.roomSummaryProvider,
mediaProvider: parameters.mediaProvider)
}
func start() {
viewModel.actionsPublisher.sink { [weak self] action in
guard let self else { return }
switch action {
case .presentRoom(let roomID):
actionsSubject.send(.presentRoom(roomID: roomID))
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(SearchScreen(context: viewModel.context))
}
}
@@ -0,0 +1,39 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Foundation
enum SearchScreenViewModelAction {
case presentRoom(roomID: String)
}
struct SearchScreenViewState: BindableState {
var rooms = [SearchScreenRoom]()
var bindings: SearchScreenViewStateBindings
var isSearching: Bool {
!bindings.searchQuery.isEmpty
}
}
struct SearchScreenViewStateBindings {
var searchQuery = ""
}
enum SearchScreenViewAction {
case appeared
case selectRoom(roomID: String)
case reachedTop
case reachedBottom
}
struct SearchScreenRoom: Identifiable, Equatable {
let id: String
let title: String
let description: String
let avatar: RoomAvatar
}
@@ -0,0 +1,115 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import AsyncAlgorithms
import Combine
import SwiftUI
typealias SearchScreenViewModelType = StateStoreViewModelV2<SearchScreenViewState, SearchScreenViewAction>
class SearchScreenViewModel: SearchScreenViewModelType, SearchScreenViewModelProtocol {
private let roomSummaryProvider: RoomSummaryProviderProtocol
private var searchQueryObservationTask: Task<Void, Never>?
private let actionsSubject: PassthroughSubject<SearchScreenViewModelAction, Never> = .init()
var actionsPublisher: AnyPublisher<SearchScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(roomSummaryProvider: RoomSummaryProviderProtocol,
mediaProvider: MediaProviderProtocol,
initialSearchQuery: String = "") {
self.roomSummaryProvider = roomSummaryProvider
super.init(initialViewState: SearchScreenViewState(bindings: .init(searchQuery: initialSearchQuery)),
mediaProvider: mediaProvider)
roomSummaryProvider.roomListPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] summaries in
self?.updateRooms(with: summaries)
}
.store(in: &cancellables)
searchQueryObservationTask = Task { [weak self] in
guard let stream = self?.context.observe(\.viewState.bindings.searchQuery).removeDuplicates() else { return }
for await searchQuery in stream {
self?.updateFilter(for: searchQuery)
}
}
updateRooms(with: roomSummaryProvider.roomListPublisher.value)
}
isolated deinit {
searchQueryObservationTask?.cancel()
}
// MARK: - Public
override func process(viewAction: SearchScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .appeared:
// The provider is shared, so other consumers may have changed its filter while we were off-screen.
// Re-apply ours on every appearance to keep the displayed results in sync with the query.
updateFilter(for: state.bindings.searchQuery)
case .selectRoom(let roomID):
actionsSubject.send(.presentRoom(roomID: roomID))
case .reachedTop:
updateVisibleRange(edge: .top)
case .reachedBottom:
updateVisibleRange(edge: .bottom)
}
}
// MARK: - Private
private func updateFilter(for searchQuery: String) {
if searchQuery.isEmpty {
roomSummaryProvider.setFilter(.excludeAll)
} else {
roomSummaryProvider.setFilter(.search(query: searchQuery))
}
}
private func updateRooms(with summaries: [RoomSummary]) {
state.rooms = summaries.map { summary in
// Show the matrix identifier as the subtitle: the other member's user ID for DMs,
// otherwise the room's canonical alias.
let identifier = if summary.isDirect {
summary.heroes.first?.userID ?? summary.canonicalAlias
} else {
summary.canonicalAlias
}
return SearchScreenRoom(id: summary.id,
title: summary.name,
description: identifier ?? "",
avatar: summary.avatar)
}
}
/// The actual range values don't matter as long as they contain the lower
/// or upper bounds. updateVisibleRange is a hybrid API that powers both
/// sliding sync visible range update and list paginations.
/// For lists other than the home screen one we don't care about visible ranges,
/// we just need the respective bounds to be there to trigger a next page load or
/// a reset to just one page.
private func updateVisibleRange(edge: UIRectEdge) {
switch edge {
case .top:
roomSummaryProvider.updateVisibleRange(0..<0)
case .bottom:
let roomCount = roomSummaryProvider.roomListPublisher.value.count
roomSummaryProvider.updateVisibleRange(roomCount..<roomCount)
default:
break
}
}
}
@@ -0,0 +1,14 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
@MainActor
protocol SearchScreenViewModelProtocol {
var actionsPublisher: AnyPublisher<SearchScreenViewModelAction, Never> { get }
var context: SearchScreenViewModelType.Context { get }
}
@@ -0,0 +1,263 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import GameController
import SwiftUI
import SwiftUIIntrospect
struct SearchScreen: View {
@Bindable var context: SearchScreenViewModel.Context
@FocusState private var isSearchFieldFocused: Bool
/// The room highlighted for hardware keyboard selection (arrow keys + return).
@State private var selectedRoomID: String?
/// The selection is only meaningful with a hardware keyboard, so don't highlight anything otherwise.
@State private var isHardwareKeyboardConnected = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Rendered as content rather than a navigation title so it stays visible while the search field is focused.
Text(L10n.actionSearch)
.font(.compound.headingXLBold)
.foregroundStyle(.compound.textPrimary)
.accessibilityAddTraits(.isHeader)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.vertical, 8)
if context.viewState.rooms.isEmpty {
emptyState
} else {
roomList
}
}
.frame(maxHeight: .infinity, alignment: .top)
.background(Color.compound.bgCanvasDefault)
.searchable(text: $context.searchQuery, placement: .toolbarPrincipal)
.searchFocused($isSearchFieldFocused)
.autocorrectionDisabled(true)
.onSubmit(of: .search) {
if let selectedRoomID {
context.send(viewAction: .selectRoom(roomID: selectedRoomID))
}
}
.searchResultsKeyboardNavigation(moveUp: { moveSelection(backwards: true) },
moveDown: { moveSelection(backwards: false) })
// The TabView calls onAppear each time the search tab is selected, so the field re-focuses
// and the selection resets on every switch.
.onAppear {
context.send(viewAction: .appeared)
isSearchFieldFocused = true
selectedRoomID = context.viewState.rooms.first?.id
updateHardwareKeyboardConnected()
}
.onReceive(NotificationCenter.default.publisher(for: .GCKeyboardDidConnect)) { _ in
updateHardwareKeyboardConnected()
}
.onReceive(NotificationCenter.default.publisher(for: .GCKeyboardDidDisconnect)) { _ in
updateHardwareKeyboardConnected()
}
// Reset to the first result when the results change (e.g. a new query), keyed on the top result
// so pagination and background updates that leave it untouched don't clobber the selection.
.onChange(of: context.viewState.rooms.first?.id) {
selectedRoomID = context.viewState.rooms.first?.id
}
}
@ViewBuilder
private var emptyState: some View {
if context.viewState.isSearching {
TitleAndIcon(title: L10n.commonNoResults,
subtitle: UntranslatedL10n.screenSearchNoResultsMessage(context.searchQuery),
icon: \.search,
iconStyle: .defaultSolid)
.frame(maxWidth: .infinity)
.padding(40)
} else {
TitleAndIcon(title: UntranslatedL10n.screenSearchEmptyStateTitle,
subtitle: UntranslatedL10n.screenSearchEmptyStateMessage,
icon: \.search,
iconStyle: .defaultSolid)
.frame(maxWidth: .infinity)
.padding(40)
}
}
private var roomList: some View {
List {
ForEach(context.viewState.rooms) { room in
SearchScreenRoomCell(room: room,
context: context,
isLast: room == context.viewState.rooms.last,
isSelected: isHardwareKeyboardConnected && selectedRoomID == room.id)
.onAppear {
if room == context.viewState.rooms.first {
context.send(viewAction: .reachedTop)
} else if room == context.viewState.rooms.last {
context.send(viewAction: .reachedBottom)
}
}
}
}
.compoundList(.plain)
}
private func moveSelection(backwards: Bool) {
let rooms = context.viewState.rooms
guard let selectedRoomID,
let currentIndex = rooms.firstIndex(where: { $0.id == selectedRoomID })
else {
selectedRoomID = rooms.first?.id
return
}
let nextIndex = backwards ? currentIndex - 1 : currentIndex + 1
guard rooms.indices.contains(nextIndex) else { return }
self.selectedRoomID = rooms[nextIndex].id
}
private func updateHardwareKeyboardConnected() {
isHardwareKeyboardConnected = GCKeyboard.coalesced != nil
}
}
private struct SearchScreenRoomCell: View {
let room: SearchScreenRoom
let context: SearchScreenViewModel.Context
let isLast: Bool
let isSelected: Bool
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
var body: some View {
Button {
context.send(viewAction: .selectRoom(roomID: room.id))
} label: {
HStack(spacing: 12) {
avatar
VStack(alignment: .leading, spacing: 0) {
Text(room.title)
.font(.compound.bodyLG)
.foregroundStyle(.compound.textPrimary)
.lineLimit(1)
if !room.description.isEmpty {
Text(room.description)
.font(.compound.bodyMD)
.foregroundStyle(.compound.textSecondary)
.lineLimit(1)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
}
.buttonStyle(SearchScreenRoomCellButtonStyle(isSelected: isSelected))
.listRowInsets(.init())
.listRowSeparator(.hidden)
.rowDivider()
}
@ViewBuilder
private var avatar: some View {
if dynamicTypeSize < .accessibility3 {
RoomAvatarImage(avatar: room.avatar,
avatarSize: .room(on: .globalSearch),
mediaProvider: context.mediaProvider)
.dynamicTypeSize(dynamicTypeSize < .accessibility1 ? dynamicTypeSize : .accessibility1)
.accessibilityHidden(true)
}
}
}
private struct SearchScreenRoomCellButtonStyle: ButtonStyle {
let isSelected: Bool
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(isSelected || configuration.isPressed ? Color.compound.bgSubtleSecondary : Color.compound.bgCanvasDefault)
.contentShape(Rectangle())
.animation(isSelected ? .none : .easeOut(duration: 0.1).disabledDuringTests(), value: isSelected)
}
}
private extension View {
/// Forwards hardware up/down arrow presses from the system search field to the given closures.
///
/// The `.search` role tab owns its text field, so there's no SwiftUI hook for its key presses. We reach the
/// field through the navigation stack (as ``SearchFieldStyle`` does) and swap its class for one that overrides
/// `pressesBegan` — the same key interception the old global search performed on its own field.
func searchResultsKeyboardNavigation(moveUp: @escaping () -> Void, moveDown: @escaping () -> Void) -> some View {
introspect(.navigationStack, on: .supportedVersions, scope: .ancestor) { navigationController in
guard let textField = navigationController.navigationBar.topItem?.searchController?.searchBar.searchTextField else {
return
}
if !(textField is KeyNavigatingSearchTextField) {
object_setClass(textField, KeyNavigatingSearchTextField.self)
}
KeyNavigatingSearchTextField.keyHandler = { keyCode in
switch keyCode {
case .keyboardUpArrow:
moveUp()
case .keyboardDownArrow:
moveDown()
default:
return false
}
return true
}
}
}
}
/// A `UISearchTextField` whose class is installed at runtime via `object_setClass`, so it must not declare any
/// stored properties. The handler is static, which is fine as there's only ever a single search field.
private final class KeyNavigatingSearchTextField: UISearchTextField {
static var keyHandler: ((UIKeyboardHIDUsage) -> Bool)?
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
if let keyCode = presses.first?.key?.keyCode, Self.keyHandler?(keyCode) == true {
return
}
super.pressesBegan(presses, with: event)
}
}
// MARK: - Previews
struct SearchScreen_Previews: PreviewProvider, TestablePreview {
static let emptyViewModel = SearchScreenViewModel(roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded([]))),
mediaProvider: MediaProviderMock(.init()))
static let loadedViewModel = SearchScreenViewModel(roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded(.mockRooms))),
mediaProvider: MediaProviderMock(.init()),
initialSearchQuery: "Foundation")
static let noResultsViewModel = SearchScreenViewModel(roomSummaryProvider: RoomSummaryProviderMock(.init(state: .loaded([]))),
mediaProvider: MediaProviderMock(.init()),
initialSearchQuery: "John Doe")
static var previews: some View {
ElementNavigationStack {
SearchScreen(context: emptyViewModel.context)
}
.previewDisplayName("Empty")
ElementNavigationStack {
SearchScreen(context: noResultsViewModel.context)
}
.previewDisplayName("No results")
ElementNavigationStack {
SearchScreen(context: loadedViewModel.context)
}
.previewDisplayName("Loaded")
}
}
@@ -74,6 +74,8 @@ protocol DeveloperOptionsProtocol: AnyObject {
var linkNewDeviceEnabled: Bool { get set }
var roomThreadListEnabled: Bool { get set }
var globalSearchEnabled: Bool { get set }
}
extension AppSettings: DeveloperOptionsProtocol { }
@@ -49,6 +49,11 @@ struct DeveloperOptionsScreen: View {
Text("Link new device with QR code")
}
Toggle(isOn: $context.globalSearchEnabled) {
Text("Global search")
Text("Moves search to a separate tab")
}
context.viewState.appHooks
.developerOptionsScreenHook
.generalSectionRows()