Add support for quick room search through the Cmd+K shortcut (#2363)

This commit is contained in:
Stefan Ceriu
2024-01-29 14:55:11 +02:00
committed by GitHub
parent c442afa5f6
commit 197b088662
28 changed files with 796 additions and 61 deletions
@@ -0,0 +1,65 @@
//
// Copyright 2023 New Vector Ltd
//
// 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 Combine
import Compound
import SwiftUI
struct GlobalSearchScreenCoordinatorParameters {
let roomSummaryProvider: RoomSummaryProviderProtocol
let mediaProvider: MediaProviderProtocol
}
enum GlobalSearchControllerAction {
case dismiss
case select(roomID: String)
}
@MainActor
class GlobalSearchScreenCoordinator: CoordinatorProtocol {
private let parameters: GlobalSearchScreenCoordinatorParameters
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) {
self.parameters = parameters
viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: parameters.roomSummaryProvider,
imageProvider: 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))
}
}
@@ -0,0 +1,45 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 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 name: String
let alias: String?
let avatarURL: URL?
}
@@ -0,0 +1,106 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 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,
imageProvider: ImageProviderProtocol) {
self.roomSummaryProvider = roomSummaryProvider
super.init(initialViewState: GlobalSearchScreenViewState(bindings: .init(searchQuery: "")),
imageProvider: imageProvider)
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
self?.roomSummaryProvider.setFilter(.normalizedMatchRoomName(searchQuery))
}
.store(in: &cancellables)
updateRooms(with: roomSummaryProvider.roomListPublisher.value)
}
// MARK: - Public
override func process(viewAction: GlobalSearchScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .dismiss:
actionsSubject.send(.dismiss)
roomSummaryProvider.setFilter(.all) // This is a shared provider
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
switch summary {
case .empty:
return nil
case .invalidated(let details), .filled(let details):
return GlobalSearchRoom(id: details.id,
name: details.name,
alias: details.canonicalAlias,
avatarURL: details.avatarURL)
}
}
}
/// 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,23 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Combine
@MainActor
protocol GlobalSearchScreenViewModelProtocol {
var actions: AnyPublisher<GlobalSearchScreenViewModelAction, Never> { get }
var context: GlobalSearchScreenViewModelType.Context { get }
}
@@ -0,0 +1,221 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 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())
.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) { _ in
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 {
Group {
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 { return }
if keyPressHandler(key.keyCode) {
return
}
super.pressesBegan(presses, with: event)
}
}
// MARK: - Previews
struct GlobalSearchScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)),
imageProvider: MockMediaProvider())
static var previews: some View {
NavigationStack {
GlobalSearchScreen(context: viewModel.context)
}
}
}
@@ -0,0 +1,62 @@
//
// Copyright 2024 New Vector Ltd
//
// 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 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.name,
description: room.alias ?? room.id,
icon: avatar),
kind: .label)
}
}
@ViewBuilder @MainActor
var avatar: some View {
if dynamicTypeSize < .accessibility3 {
LoadableAvatarImage(url: room.avatarURL,
name: room.name,
contentID: room.id,
avatarSize: .room(on: .messageForwarding),
imageProvider: context.imageProvider)
.dynamicTypeSize(dynamicTypeSize < .accessibility1 ? dynamicTypeSize : .accessibility1)
.accessibilityHidden(true)
}
}
}
struct GlobalSearchScreenListRow_Previews: PreviewProvider, TestablePreview {
static let viewModel = GlobalSearchScreenViewModel(roomSummaryProvider: MockRoomSummaryProvider(state: .loaded(.mockRooms)),
imageProvider: MockMediaProvider())
static var previews: some View {
List {
GlobalSearchScreenListRow(room: .init(id: "123",
name: "Tech central",
alias: "The best place in the whole wide world",
avatarURL: .picturesDirectory),
context: viewModel.context)
}
}
}