Added room timeline screen with live events listening and back pagination. Rearranged project files.

This commit is contained in:
Stefan Ceriu
2022-03-08 14:24:33 +02:00
parent f403c59b95
commit c22d9689d4
77 changed files with 1269 additions and 491 deletions
@@ -0,0 +1,103 @@
//
// Copyright 2021 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 SwiftUI
import Combine
import Kingfisher
struct HomeScreenCoordinatorParameters {
let userSession: UserSession
}
enum HomeScreenCoordinatorResult {
case logout
case selectRoom(roomIdentifier: String)
}
final class HomeScreenCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: HomeScreenCoordinatorParameters
private let hostingController: UIViewController
private var viewModel: HomeScreenViewModelProtocol
private var cancellables = Set<AnyCancellable>()
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: ((HomeScreenCoordinatorResult) -> Void)?
// MARK: - Setup
init(parameters: HomeScreenCoordinatorParameters, imageCache: Kingfisher.ImageCache) {
self.parameters = parameters
let userDisplayName = self.parameters.userSession.userDisplayName ?? self.parameters.userSession.userIdentifier
viewModel = HomeScreenViewModel(userDisplayName: userDisplayName, imageCache: imageCache)
let view = HomeScreen(context: viewModel.context)
hostingController = UIHostingController(rootView: view)
viewModel.completion = { [weak self] result in
guard let self = self else { return }
switch result {
case .logout:
self.completion?(.logout)
case .loadUserAvatar:
self.parameters.userSession.loadUserAvatar({ result in
switch result {
case .success(let avatar):
self.viewModel.updateWithUserAvatar(avatar)
default:
break
}
})
case .selectRoom(let roomIdentifier):
self.completion?(.selectRoom(roomIdentifier: roomIdentifier))
}
}
parameters.userSession.callbacks.sink { [weak self] result in
switch result {
case .updatedRoomsList:
self?.updateRoomsList()
}
}.store(in: &cancellables)
}
// MARK: - Public
func start() {
}
func toPresentable() -> UIViewController {
return self.hostingController
}
// MARK: - Private
func updateRoomsList() {
parameters.userSession.getRoomList { [weak self] rooms in
self?.viewModel.updateWithRoomList(rooms)
}
}
}
@@ -0,0 +1,77 @@
//
// Copyright 2021 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
import UIKit
enum HomeScreenViewModelResult {
case logout
case loadUserAvatar
case selectRoom(roomIdentifier: String)
}
enum HomeScreenViewAction {
case logout
case loadUserAvatar
case loadRoomData(roomIdentifier: String)
case selectRoom(roomIdentifier: String)
}
struct HomeScreenViewState: BindableState {
let userDisplayName: String
var userAvatar: UIImage?
var rooms: [HomeScreenRoom] = []
var isLoadingRooms: Bool = false
var firstDirectRooms: [HomeScreenRoom] {
Array(rooms.filter { $0.isDirect }.prefix(5))
}
var otherDirectRooms: [HomeScreenRoom] {
Array(rooms.filter { $0.isDirect }.dropFirst(5))
}
var firstNondirectRooms: [HomeScreenRoom] {
Array(rooms.filter { !$0.isDirect }.prefix(5))
}
var otherNondirectRooms: [HomeScreenRoom] {
Array(rooms.filter { !$0.isDirect }.dropFirst(5))
}
}
struct HomeScreenRoom: Identifiable {
let id: String
var displayName: String?
let topic: String?
let lastMessage: String?
var avatar: UIImage?
let isDirect: Bool
let isEncrypted: Bool
}
extension MutableCollection where Element == HomeScreenRoom {
mutating func updateEach(_ update: (inout Element) -> Void) {
for index in indices {
update(&self[index])
}
}
}
@@ -0,0 +1,181 @@
//
// Copyright 2021 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 SwiftUI
import Combine
import Kingfisher
@available(iOS 14, *)
typealias HomeScreenViewModelType = StateStoreViewModel<HomeScreenViewState,
Never,
HomeScreenViewAction>
@available(iOS 14, *)
class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol {
private var roomUpdateListeners = Set<AnyCancellable>()
private var roomList: [RoomProxyProtocol]? {
didSet {
self.state.isLoadingRooms = (roomList == nil)
}
}
private let imageCache: ImageCache
var completion: ((HomeScreenViewModelResult) -> Void)?
// MARK: - Setup
init(userDisplayName: String, imageCache: Kingfisher.ImageCache) {
self.imageCache = imageCache
super.init(initialViewState: HomeScreenViewState(userDisplayName: userDisplayName, isLoadingRooms: true))
}
// MARK: - Public
override func process(viewAction: HomeScreenViewAction) {
switch viewAction {
case .logout:
self.completion?(.logout)
case .loadRoomData(let roomIdentifier):
self.loadAvatarForRoomWithIdentifier(roomIdentifier)
self.loadRoomDisplayNameForRoomWithIdentifier(roomIdentifier)
case .loadUserAvatar:
self.completion?(.loadUserAvatar)
case .selectRoom(let roomIdentifier):
self.completion?(.selectRoom(roomIdentifier: roomIdentifier))
}
}
func updateWithRoomList(_ roomList: [RoomProxyProtocol]) {
roomUpdateListeners.removeAll()
self.roomList = roomList
roomList.forEach({ roomProxy in
roomProxy.paginateBackwards(start: 0, finish: 1)
roomProxy.startLiveEventListener()
roomProxy.callbacks.sink { [weak self] callback in
switch callback {
case .updatedLastMessage:
self?.updateRoomForProxy(roomProxy)
default:
break
}
}
.store(in: &roomUpdateListeners)
})
state.rooms = roomList.map { roomProxy in
roomFromProxy(roomProxy)
}
}
func updateWithUserAvatar(_ avatar: UIImage?) {
self.state.userAvatar = avatar
}
// MARK: - Private
private func loadAvatarForRoomWithIdentifier(_ roomIdentifier: String) {
guard let room = roomList?.filter({ $0.id == roomIdentifier }).first,
let cacheKey = room.avatarURL?.path else {
return
}
if imageCache.isCached(forKey: cacheKey) {
imageCache.retrieveImage(forKey: cacheKey) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let value):
self.updateAvatar(value.image, forRoomWithIdentifier: roomIdentifier)
case .failure(let error):
MXLog.error("Failed retrieving avatar from cache with error: \(error)")
}
}
return
}
room.loadAvatar { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let avatar):
guard let avatar = avatar else {
return
}
self.imageCache.store(avatar, forKey: cacheKey)
self.updateAvatar(avatar, forRoomWithIdentifier: roomIdentifier)
default:
break
}
}
}
private func loadRoomDisplayNameForRoomWithIdentifier(_ roomIdentifier: String) {
guard let room = roomList?.filter({ $0.id == roomIdentifier }).first else {
return
}
room.loadDisplayName { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let displayName):
self.updateDisplayName(displayName, forRoomWithIdentifier: roomIdentifier)
default:
break
}
}
}
private func updateDisplayName(_ displayName: String, forRoomWithIdentifier roomIdentifier: String) {
guard let index = self.state.rooms.firstIndex(where: { $0.id == roomIdentifier }) else {
return
}
self.state.rooms[index].displayName = displayName
}
private func updateAvatar(_ avatar: UIImage?, forRoomWithIdentifier roomIdentifier: String) {
guard let index = self.state.rooms.firstIndex(where: { $0.id == roomIdentifier }) else {
return
}
self.state.rooms[index].avatar = avatar
}
private func updateRoomForProxy(_ roomProxy: RoomProxyProtocol) {
state.rooms.updateEach { room in
if room.id != roomProxy.id {
return
}
room = roomFromProxy(roomProxy)
}
}
private func roomFromProxy(_ roomProxy: RoomProxyProtocol) -> HomeScreenRoom {
HomeScreenRoom(id: roomProxy.id,
displayName: roomProxy.name,
topic: roomProxy.topic,
lastMessage: roomProxy.lastMessage,
isDirect: roomProxy.isDirect,
isEncrypted: roomProxy.isEncrypted)
}
}
@@ -0,0 +1,28 @@
//
// Copyright 2021 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
import UIKit
protocol HomeScreenViewModelProtocol {
var completion: ((HomeScreenViewModelResult) -> Void)? { get set }
var context: HomeScreenViewModelType.Context { get }
func updateWithRoomList(_ roomList: [RoomProxyProtocol])
func updateWithUserAvatar(_ avatar: UIImage?)
}
@@ -0,0 +1,17 @@
//
// Copyright 2021 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 XCTest
@@ -0,0 +1,29 @@
//
// Copyright 2021 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 XCTest
@testable import ElementX
class HomeScreenViewModelTests: XCTestCase {
override func setUpWithError() throws {
}
func testInitialState() {
}
}
@@ -0,0 +1,170 @@
//
// Copyright 2021 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 SwiftUI
import Kingfisher
struct HomeScreen: View {
@ObservedObject var context: HomeScreenViewModel.Context
// MARK: Views
var body: some View {
NavigationView {
VStack(spacing: 16.0) {
if context.viewState.isLoadingRooms {
VStack {
Text("Loading rooms")
ProgressView()
}
} else {
List {
Section("People") {
ForEach(context.viewState.firstDirectRooms) { room in
RoomCell(room: room, context: context)
}
let other = context.viewState.otherDirectRooms
if other.count > 0 {
DisclosureGroup("See more") {
ForEach(other) { room in
RoomCell(room: room, context: context)
}
}
}
}
Section("Rooms") {
ForEach(context.viewState.firstNondirectRooms) { room in
RoomCell(room: room, context: context)
}
let other = context.viewState.otherNondirectRooms
if other.count > 0 {
DisclosureGroup("See more") {
ForEach(other) { room in
RoomCell(room: room, context: context)
}
}
}
}
}
.listStyle(.plain)
}
Spacer()
}
.ignoresSafeArea(.all, edges: .bottom)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
HStack {
if let avatar = context.viewState.userAvatar {
Image(uiImage: avatar)
.resizable()
.scaledToFill()
.frame(width: 40, height: 40, alignment: .center)
.mask(Circle())
} else {
let _ = context.send(viewAction: .loadUserAvatar)
}
Text("Hello, \(context.viewState.userDisplayName)!")
.font(.subheadline)
.fontWeight(.bold)
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Logout") {
context.send(viewAction: .logout)
}
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct RoomCell: View {
let room: HomeScreenRoom
let context: HomeScreenViewModel.Context
var body: some View {
Button {
context.send(viewAction: .selectRoom(roomIdentifier: room.id))
} label: {
HStack(spacing: 16.0) {
if let avatar = room.avatar {
Image(uiImage: avatar)
.resizable()
.scaledToFill()
.frame(width: 40, height: 40)
.mask(Circle())
} else {
let _ = context.send(viewAction: .loadRoomData(roomIdentifier: room.id))
Image(systemName: "person.3")
.frame(width: 40, height: 40)
}
VStack(alignment: .leading, spacing: 4.0) {
Text(roomName(room))
.font(.headline)
.fontWeight(.regular)
if let roomTopic = room.topic, roomTopic.count > 0 {
Text(roomTopic)
.font(.footnote)
.fontWeight(.bold)
.lineLimit(1)
}
if let lastMessage = room.lastMessage {
Text(lastMessage)
.font(.footnote)
.fontWeight(.medium)
.lineLimit(1)
}
}
}
.frame(minHeight: 60.0)
}
}
private func roomName(_ room: HomeScreenRoom) -> String {
room.displayName ?? room.id + (room.isEncrypted ? "🛡": "")
}
}
// MARK: - Previews
struct HomeScreen_Previews: PreviewProvider {
static var previews: some View {
let viewModel = HomeScreenViewModel(userDisplayName: "Johnny Appleseed", imageCache: ImageCache.default)
let rooms = [MockRoomProxy(displayName: "Alfa"),
MockRoomProxy(displayName: "Beta"),
MockRoomProxy(displayName: "Omega")]
viewModel.updateWithRoomList(rooms)
viewModel.updateWithUserAvatar(UIImage(systemName: "person.fill.questionmark"))
return HomeScreen(context: viewModel.context)
}
}