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)
}
}
@@ -0,0 +1,65 @@
//
// 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
struct LoginScreenCoordinatorParameters {
}
final class LoginScreenCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: LoginScreenCoordinatorParameters
private let loginScreenHostingController: UIViewController
private var loginScreenViewModel: LoginScreenViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: ((LoginScreenViewModelResult) -> Void)?
// MARK: - Setup
init(parameters: LoginScreenCoordinatorParameters) {
self.parameters = parameters
loginScreenViewModel = LoginScreenViewModel()
let view = LoginScreen(context: loginScreenViewModel.context)
loginScreenHostingController = UIHostingController(rootView: view)
loginScreenHostingController.isModalInPresentation = true
loginScreenViewModel.completion = { [weak self] result in
MXLog.debug("[LoginScreenCoordinator] LoginScreenViewModel did complete.")
guard let self = self else { return }
self.completion?(result)
}
}
// MARK: - Public
func start() {
}
func toPresentable() -> UIViewController {
return self.loginScreenHostingController
}
}
@@ -0,0 +1,44 @@
//
// 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
enum LoginScreenViewModelResult {
case login((username: String, password: String))
}
enum LoginScreenViewAction {
case login
}
struct LoginScreenViewState: BindableState {
var bindings: LoginScreenViewStateBindings
}
struct LoginScreenViewStateBindings {
var username: String
var password: String
}
struct LoginScreenErrorAlertInfo: Identifiable {
enum AlertType {
case genericFailure
}
let id: AlertType
let title: String
let subtitle: String
}
@@ -0,0 +1,49 @@
//
// 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
@available(iOS 14, *)
typealias LoginScreenViewModelType = StateStoreViewModel<LoginScreenViewState,
Never,
LoginScreenViewAction>
@available(iOS 14, *)
class LoginScreenViewModel: LoginScreenViewModelType, LoginScreenViewModelProtocol {
// MARK: - Properties
// MARK: Private
// MARK: Public
var completion: ((LoginScreenViewModelResult) -> Void)?
// MARK: - Setup
init() {
super.init(initialViewState: LoginScreenViewState(bindings: LoginScreenViewStateBindings(username: "",
password: "")))
}
// MARK: - Public
override func process(viewAction: LoginScreenViewAction) {
switch viewAction {
case .login:
completion?(.login((username: context.username, password: context.password)))
}
}
}
@@ -0,0 +1,24 @@
//
// 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
protocol LoginScreenViewModelProtocol {
var completion: ((LoginScreenViewModelResult) -> Void)? { get set }
@available(iOS 14, *)
var context: LoginScreenViewModelType.Context { get }
}
@@ -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,30 @@
//
// 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 LoginScreenViewModelTests: XCTestCase {
override func setUpWithError() throws {
}
func testInitialState() {
}
}
@@ -0,0 +1,57 @@
//
// 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
struct LoginScreen: View {
@ObservedObject var context: LoginScreenViewModel.Context
var body: some View {
NavigationView {
VStack {
TextField("Username", text: $context.username)
.textFieldStyle(.roundedBorder)
.disableAutocorrection(true)
.autocapitalization(.none)
SecureField("Password", text: $context.password)
.textFieldStyle(.roundedBorder)
Button("Login") {
context.send(viewAction: .login)
}
.buttonStyle(.borderedProminent)
.padding(.horizontal, 50)
}
.padding(.horizontal, 8.0)
.navigationTitle("Login")
.navigationBarTitleDisplayMode(.inline)
.onSubmit {
context.send(viewAction: .login)
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
// MARK: - Previews
struct LoginScreen_Previews: PreviewProvider {
static var previews: some View {
let viewModel = LoginScreenViewModel()
LoginScreen(context: viewModel.context)
}
}
@@ -0,0 +1,67 @@
//
// 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
struct RoomScreenCoordinatorParameters {
let roomProxy: RoomProxyProtocol
}
final class RoomScreenCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: RoomScreenCoordinatorParameters
private let roomScreenHostingController: UIViewController
private var roomScreenViewModel: RoomScreenViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: ((RoomScreenViewModelResult) -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: RoomScreenCoordinatorParameters) {
self.parameters = parameters
let timelineProvider = RoomTimelineProvider(roomProxy: parameters.roomProxy)
let timelineController = RoomTimelineController(timelineProvider: timelineProvider)
let viewModel = RoomScreenViewModel(roomProxy: parameters.roomProxy, timelineController: timelineController)
let view = RoomScreen(context: viewModel.context)
roomScreenViewModel = viewModel
roomScreenHostingController = UIHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[RoomScreenCoordinator] did start.")
roomScreenViewModel.completion = { [weak self] result in
MXLog.debug("[RoomScreenCoordinator] RoomScreenViewModel did complete with result: \(result).")
guard let self = self else { return }
self.completion?(result)
}
}
func toPresentable() -> UIViewController {
return self.roomScreenHostingController
}
}
@@ -0,0 +1,50 @@
//
// 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
enum RoomScreenViewModelResult {
}
enum RoomScreenViewAction {
case loadPreviousPage
}
private var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
return dateFormatter
}()
struct RoomScreenMessage: Identifiable, Equatable {
let id: String
let sender: String
let text: String
let originServerTs: Date
var timestamp: String {
dateFormatter.string(from: originServerTs)
}
}
struct RoomScreenViewState: BindableState {
var roomTitle: String?
var isLoading: Bool = false
var messages: [RoomScreenMessage] = []
}
@@ -0,0 +1,74 @@
//
// 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
@available(iOS 14, *)
typealias RoomScreenViewModelType = StateStoreViewModel<RoomScreenViewState,
Never,
RoomScreenViewAction>
@available(iOS 14, *)
class RoomScreenViewModel: RoomScreenViewModelType, RoomScreenViewModelProtocol {
private struct Constants {
static let backPaginationPageSize: UInt = 20
}
private let roomProxy: RoomProxyProtocol
private let timelineController: RoomTimelineControllerProtocol
var completion: ((RoomScreenViewModelResult) -> Void)?
// MARK: - Setup
init(roomProxy: RoomProxyProtocol, timelineController: RoomTimelineControllerProtocol) {
self.roomProxy = roomProxy
self.timelineController = timelineController
super.init(initialViewState: RoomScreenViewState())
state.messages = buildRoomScreenMessages(timelineController.timelineItems)
timelineController.callbacks.sink { [weak self] callback in
guard let self = self else { return }
switch callback {
case .updatedTimelineItems:
self.state.messages = self.buildRoomScreenMessages(timelineController.timelineItems)
}
}.store(in: &cancellables)
timelineController.paginateBackwards(Constants.backPaginationPageSize)
}
// MARK: - Public
override func process(viewAction: RoomScreenViewAction) {
switch viewAction {
case .loadPreviousPage:
timelineController.paginateBackwards(Constants.backPaginationPageSize)
}
}
// MARK: - Private
private func buildRoomScreenMessages(_ timelineItems: [RoomTimelineItemProtocol]) -> [RoomScreenMessage] {
timelineItems.map { RoomScreenMessage(id: $0.id,
sender: $0.senderDisplayName,
text: $0.text,
originServerTs: $0.originServerTs) }
}
}
@@ -0,0 +1,24 @@
//
// 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
protocol RoomScreenViewModelProtocol {
var completion: ((RoomScreenViewModelResult) -> Void)? { get set }
@available(iOS 14, *)
var context: RoomScreenViewModelType.Context { get }
}
@@ -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,21 @@
//
// 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
class RoomScreenViewModelTests: XCTestCase {
}
@@ -0,0 +1,85 @@
//
// 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
struct RoomScreen: View {
let timelineBottomDividerIdentifier = "TimelineBottomDividerIdentifier"
@ObservedObject var context: RoomScreenViewModel.Context
@State var backPaginationMessageIdentifier: String?
var body: some View {
ScrollViewReader { reader in
List {
if backPaginationMessageIdentifier != nil {
HStack {
Spacer()
ProgressView()
Spacer()
}
} else {
Rectangle()
.onAppear {
let _ = MXLog.debug("Request load previous page")
backPaginationMessageIdentifier = context.viewState.messages.first?.id
context.send(viewAction: .loadPreviousPage)
}
.frame(height: 0.0)
}
ForEach(context.viewState.messages) { message in
VStack(alignment: .leading) {
HStack {
Text(message.sender)
Spacer()
Text(message.timestamp)
}
.font(.footnote)
Text(message.text)
}
.listRowSeparator(.hidden)
}
Divider()
.id(timelineBottomDividerIdentifier)
.listRowSeparator(.hidden)
}
.listStyle(.plain)
.onAppear {
reader.scrollTo(timelineBottomDividerIdentifier, anchor: .bottom)
}
.onChange(of: context.viewState.messages) { _ in
if backPaginationMessageIdentifier != nil {
self.backPaginationMessageIdentifier = nil
return
}
reader.scrollTo(timelineBottomDividerIdentifier, anchor: .bottom)
}
}
}
}
// MARK: - Previews
struct RoomScreen_Previews: PreviewProvider {
static var previews: some View {
let viewModel = RoomScreenViewModel(roomProxy: MockRoomProxy(displayName: "Test"),
timelineController: MockRoomTimelineController())
RoomScreen(context: viewModel.context)
}
}
@@ -0,0 +1,12 @@
//
// SplashViewController.swift
// ElementX
//
// Created by Stefan Ceriu on 14.02.2022.
//
import UIKit
class SplashViewController: UIViewController {
}
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="19529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19519"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="SplashViewController" customModule="ElementX" customModuleProvider="target">
<connections>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="app-logo" translatesAutoresizingMaskIntoConstraints="NO" id="ue7-fB-5XS">
<rect key="frame" x="87" y="328" width="240" height="240"/>
<color key="tintColor" red="0.050980392156862744" green="0.74117647058823533" blue="0.54509803921568623" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</imageView>
</subviews>
<viewLayoutGuide key="safeArea" id="fnl-2z-Ty3"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="fnl-2z-Ty3" firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="ue7-fB-5XS" secondAttribute="bottom" constant="16" id="Cip-Sc-gaF"/>
<constraint firstItem="ue7-fB-5XS" firstAttribute="top" relation="greaterThanOrEqual" secondItem="fnl-2z-Ty3" secondAttribute="top" constant="16" id="Clt-cS-YAr"/>
<constraint firstItem="ue7-fB-5XS" firstAttribute="centerY" secondItem="i5M-Pr-FkT" secondAttribute="centerY" id="N3w-Jf-MRA"/>
<constraint firstItem="fnl-2z-Ty3" firstAttribute="trailing" relation="greaterThanOrEqual" secondItem="ue7-fB-5XS" secondAttribute="trailing" constant="16" id="WfN-3K-kpr"/>
<constraint firstItem="ue7-fB-5XS" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="ujr-SL-AyX"/>
<constraint firstItem="ue7-fB-5XS" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="fnl-2z-Ty3" secondAttribute="leading" constant="16" id="yNl-Wu-AES"/>
</constraints>
<point key="canvasLocation" x="137.68115942028987" y="153.34821428571428"/>
</view>
</objects>
<resources>
<image name="app-logo" width="240" height="240"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -0,0 +1,64 @@
//
// 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
struct TemplateSimpleScreenCoordinatorParameters {
let promptType: TemplateSimpleScreenPromptType
}
final class TemplateSimpleScreenCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: TemplateSimpleScreenCoordinatorParameters
private let templateSimpleScreenHostingController: UIViewController
private var templateSimpleScreenViewModel: TemplateSimpleScreenViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: ((TemplateSimpleScreenViewModelResult) -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: TemplateSimpleScreenCoordinatorParameters) {
self.parameters = parameters
let viewModel = TemplateSimpleScreenViewModel(promptType: parameters.promptType)
let view = TemplateSimpleScreen(viewModel: viewModel.context)
templateSimpleScreenViewModel = viewModel
templateSimpleScreenHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[TemplateSimpleScreenCoordinator] did start.")
templateSimpleScreenViewModel.completion = { [weak self] result in
MXLog.debug("[TemplateSimpleScreenCoordinator] TemplateSimpleScreenViewModel did complete with result: \(result).")
guard let self = self else { return }
self.completion?(result)
}
}
func toPresentable() -> UIViewController {
return self.templateSimpleScreenHostingController
}
}
@@ -0,0 +1,57 @@
//
// 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 SwiftUI
/// Using an enum for the screen allows you define the different state cases with
/// the relevant associated data for each case.
@available(iOS 14.0, *)
enum MockTemplateSimpleScreenScreenState: MockScreenState, CaseIterable {
// A case for each state you want to represent
// with specific, minimal associated data that will allow you
// mock that screen.
case promptType(TemplateSimpleScreenPromptType)
/// The associated screen
var screenType: Any.Type {
TemplateSimpleScreen.self
}
/// A list of screen state definitions
static var allCases: [MockTemplateSimpleScreenScreenState] {
// Each of the presence statuses
TemplateSimpleScreenPromptType.allCases.map(MockTemplateSimpleScreenScreenState.promptType)
}
/// Generate the view struct for the screen state.
var screenView: ([Any], AnyView) {
let promptType: TemplateSimpleScreenPromptType
switch self {
case .promptType(let type):
promptType = type
}
let viewModel = TemplateSimpleScreenViewModel(promptType: promptType)
// can simulate service and viewModel actions here if needs be.
return (
[promptType, viewModel],
AnyView(TemplateSimpleScreen(viewModel: viewModel.context)
.addDependency(MockAvatarService.example))
)
}
}
@@ -0,0 +1,67 @@
//
// 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
// MARK: - Coordinator
enum TemplateSimpleScreenPromptType {
case regular
case upgrade
}
extension TemplateSimpleScreenPromptType: Identifiable, CaseIterable {
var id: Self { self }
var title: String {
switch self {
case .regular:
return VectorL10n.roomCreationMakePublicPromptTitle
case .upgrade:
return VectorL10n.roomDetailsHistorySectionPromptTitle
}
}
var image: ImageAsset {
switch self {
case .regular:
return Asset.Images.appSymbol
case .upgrade:
return Asset.Images.keyVerificationSuccessShield
}
}
}
// MARK: View model
enum TemplateSimpleScreenViewModelResult {
case accept
case cancel
}
// MARK: View
struct TemplateSimpleScreenViewState: BindableState {
var promptType: TemplateSimpleScreenPromptType
var count: Int
}
enum TemplateSimpleScreenViewAction {
case incrementCount
case decrementCount
case accept
case cancel
}
@@ -0,0 +1,54 @@
//
// 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
@available(iOS 14, *)
typealias TemplateSimpleScreenViewModelType = StateStoreViewModel<TemplateSimpleScreenViewState,
Never,
TemplateSimpleScreenViewAction>
@available(iOS 14, *)
class TemplateSimpleScreenViewModel: TemplateSimpleScreenViewModelType, TemplateSimpleScreenViewModelProtocol {
// MARK: - Properties
// MARK: Private
// MARK: Public
var completion: ((TemplateSimpleScreenViewModelResult) -> Void)?
// MARK: - Setup
init(promptType: TemplateSimpleScreenPromptType, initialCount: Int = 0) {
super.init(initialViewState: TemplateSimpleScreenViewState(promptType: promptType, count: 0))
}
// MARK: - Public
override func process(viewAction: TemplateSimpleScreenViewAction) {
switch viewAction {
case .accept:
completion?(.accept)
case .cancel:
completion?(.cancel)
case .incrementCount:
state.count += 1
case .decrementCount:
state.count -= 1
}
}
}
@@ -0,0 +1,24 @@
//
// 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
protocol TemplateSimpleScreenViewModelProtocol {
var completion: ((TemplateSimpleScreenViewModelResult) -> Void)? { get set }
@available(iOS 14, *)
var context: TemplateSimpleScreenViewModelType.Context { get }
}
@@ -0,0 +1,45 @@
//
// 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
import RiotSwiftUI
@available(iOS 14.0, *)
class TemplateSimpleScreenUITests: MockScreenTest {
override class var screenType: MockScreenState.Type {
return MockTemplateSimpleScreenScreenState.self
}
override class func createTest() -> MockScreenTest {
return TemplateSimpleScreenUITests(selector: #selector(verifyTemplateSimpleScreenScreen))
}
func verifyTemplateSimpleScreenScreen() throws {
guard let screenState = screenState as? MockTemplateSimpleScreenScreenState else { fatalError("no screen") }
switch screenState {
case .promptType(let promptType):
verifyTemplateSimpleScreenPromptType(promptType: promptType)
}
}
func verifyTemplateSimpleScreenPromptType(promptType: TemplateSimpleScreenPromptType) {
let title = app.staticTexts["title"]
XCTAssert(title.exists)
XCTAssertEqual(title.label, promptType.title)
}
}
@@ -0,0 +1,49 @@
//
// 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 RiotSwiftUI
@available(iOS 14.0, *)
class TemplateSimpleScreenViewModelTests: XCTestCase {
private enum Constants {
static let counterInitialValue = 0
}
var viewModel: TemplateSimpleScreenViewModelProtocol!
var context: TemplateSimpleScreenViewModelType.Context!
override func setUpWithError() throws {
viewModel = TemplateSimpleScreenViewModel(promptType: .regular, initialCount: Constants.counterInitialValue)
context = viewModel.context
}
func testInitialState() {
XCTAssertEqual(context.viewState.count, Constants.counterInitialValue)
}
func testCounter() throws {
context.send(viewAction: .incrementCount)
XCTAssertEqual(context.viewState.count, 1)
context.send(viewAction: .incrementCount)
XCTAssertEqual(context.viewState.count, 2)
context.send(viewAction: .decrementCount)
XCTAssertEqual(context.viewState.count, 1)
}
}
@@ -0,0 +1,113 @@
//
// 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
@available(iOS 14.0, *)
struct TemplateSimpleScreen: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
private var horizontalPadding: CGFloat {
horizontalSizeClass == .regular ? 50 : 16
}
// MARK: Public
@ObservedObject var viewModel: TemplateSimpleScreenViewModel.Context
// MARK: Views
var body: some View {
GeometryReader { geometry in
VStack {
ScrollView(showsIndicators: false) {
mainContent
.padding(.top, 50)
.padding(.horizontal, horizontalPadding)
}
buttons
.padding(.horizontal, horizontalPadding)
.padding(.bottom, geometry.safeAreaInsets.bottom > 0 ? 0 : 16)
}
}
.background(theme.colors.background.ignoresSafeArea())
.accentColor(theme.colors.accent)
}
/// The main content of the view to be shown in a scroll view.
var mainContent: some View {
VStack(spacing: 36) {
Text(viewModel.viewState.promptType.title)
.font(theme.fonts.title1B)
.foregroundColor(theme.colors.primaryContent)
.accessibilityIdentifier("title")
Image(viewModel.viewState.promptType.image.name)
.resizable()
.scaledToFit()
.frame(width: 100)
.foregroundColor(theme.colors.accent)
HStack {
Text("Counter: \(viewModel.viewState.count)")
.foregroundColor(theme.colors.primaryContent)
Button("-") {
viewModel.send(viewAction: .decrementCount)
}
Button("+") {
viewModel.send(viewAction: .incrementCount)
}
}
.font(theme.fonts.title3)
}
}
/// The action buttons shown at the bottom of the view.
var buttons: some View {
VStack {
Button { viewModel.send(viewAction: .accept) } label: {
Text("Accept")
.font(theme.fonts.bodySB)
}
.buttonStyle(PrimaryActionButtonStyle())
Button { viewModel.send(viewAction: .cancel) } label: {
Text("Cancel")
.font(theme.fonts.body)
.padding(.vertical, 12)
}
}
}
}
// MARK: - Previews
@available(iOS 14.0, *)
struct TemplateSimpleScreen_Previews: PreviewProvider {
static let stateRenderer = MockTemplateSimpleScreenScreenState.stateRenderer
static var previews: some View {
stateRenderer.screenGroup()
}
}