Handle live location sharing viewer screen.

This commit is contained in:
SBiOSoftWhare
2022-04-05 18:36:41 +02:00
parent c149eab998
commit 6ecdba34da
9 changed files with 603 additions and 0 deletions
@@ -0,0 +1,87 @@
//
// 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 LiveLocationSharingViewerCoordinatorParameters {
let session: MXSession
}
final class LiveLocationSharingViewerCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: LiveLocationSharingViewerCoordinatorParameters
private let liveLocationSharingViewerHostingController: UIViewController
private var liveLocationSharingViewerViewModel: LiveLocationSharingViewerViewModelProtocol
private let shareLocationActivityControllerBuilder = ShareLocationActivityControllerBuilder()
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: (() -> Void)?
// MARK: - Setup
@available(iOS 14.0, *)
init(parameters: LiveLocationSharingViewerCoordinatorParameters) {
self.parameters = parameters
let service = LiveLocationSharingViewerService(session: parameters.session)
let viewModel = LiveLocationSharingViewerViewModel(mapStyleURL: BuildSettings.tileServerMapStyleURL, service: service)
let view = LiveLocationSharingViewer(viewModel: viewModel.context)
.addDependency(AvatarService.instantiate(mediaManager: parameters.session.mediaManager))
liveLocationSharingViewerViewModel = viewModel
liveLocationSharingViewerHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[LiveLocationSharingViewerCoordinator] did start.")
liveLocationSharingViewerViewModel.completion = { [weak self] result in
guard let self = self else { return }
MXLog.debug("[LiveLocationSharingViewerCoordinator] LiveLocationSharingViewerViewModel did complete with result: \(result).")
switch result {
case .done:
self.completion?()
case .share(let coordinate):
self.presentLocationActivityController(with: coordinate)
case .stopLocationSharing:
self.stopLocationSharing()
}
}
}
func toPresentable() -> UIViewController {
return self.liveLocationSharingViewerHostingController
}
func presentLocationActivityController(with coordinate: CLLocationCoordinate2D) {
let shareActivityController = shareLocationActivityControllerBuilder.build(with: coordinate)
self.liveLocationSharingViewerHostingController.present(shareActivityController, animated: true)
}
func stopLocationSharing() {
// TODO: Handle stop location sharing
}
}
@@ -0,0 +1,68 @@
//
// 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 Combine
import CoreLocation
// MARK: - Coordinator
// MARK: View model
enum LiveLocationSharingViewerViewModelResult {
case done
case share(_ coordinate: CLLocationCoordinate2D)
case stopLocationSharing
}
// MARK: View
@available(iOS 14, *)
struct LiveLocationSharingViewerViewState: BindableState {
/// Map style URL
let mapStyleURL: URL
/// Map annotations to display on map
var annotations: [UserLocationAnnotation]
/// Map annotation to focus on
var highlightedAnnotation: UserLocationAnnotation?
/// Live location list items
var listItemsViewData: [LiveLocationListItemViewData]
var showLoadingIndicator: Bool = false
var shareButtonEnabled: Bool {
!showLoadingIndicator
}
let errorSubject = PassthroughSubject<LocationSharingViewError, Never>()
var bindings = LocationSharingViewStateBindings()
}
struct LiveLocationSharingViewerViewStateBindings {
var alertInfo: AlertInfo<LocationSharingAlertType>?
}
enum LiveLocationSharingViewerViewAction {
case done
case stopSharing
case tapListItem(_ userId: String)
case share(_ annotation: UserLocationAnnotation)
}
@@ -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 Mapbox
@available(iOS 14, *)
typealias LiveLocationSharingViewerViewModelType = StateStoreViewModel<LiveLocationSharingViewerViewState,
Never,
LiveLocationSharingViewerViewAction>
@available(iOS 14, *)
class LiveLocationSharingViewerViewModel: LiveLocationSharingViewerViewModelType, LiveLocationSharingViewerViewModelProtocol {
// MARK: - Properties
// MARK: Private
private let liveLocationSharingViewerService: LiveLocationSharingViewerServiceProtocol
private var mapViewErrorAlertInfoBuilder: MapViewErrorAlertInfoBuilder
// MARK: Public
var completion: ((LiveLocationSharingViewerViewModelResult) -> Void)?
// MARK: - Setup
init(mapStyleURL: URL, service: LiveLocationSharingViewerServiceProtocol) {
let viewState = LiveLocationSharingViewerViewState(mapStyleURL: mapStyleURL, annotations: [], highlightedAnnotation: nil, listItemsViewData: [])
liveLocationSharingViewerService = service
mapViewErrorAlertInfoBuilder = MapViewErrorAlertInfoBuilder()
super.init(initialViewState: viewState)
state.errorSubject.sink { [weak self] error in
guard let self = self else { return }
self.processError(error)
}.store(in: &cancellables)
self.update(with: service.usersLiveLocation)
}
// MARK: - Public
override func process(viewAction: LiveLocationSharingViewerViewAction) {
switch viewAction {
case .done:
completion?(.done)
case .stopSharing:
completion?(.stopLocationSharing)
case .tapListItem(let userId):
self.highlighAnnotation(with: userId)
case .share(let userLocationAnnotation):
completion?(.share(userLocationAnnotation.coordinate))
}
}
// MARK: - Private
private func processError(_ error: LocationSharingViewError) {
guard state.bindings.alertInfo == nil else {
return
}
let alertInfo = mapViewErrorAlertInfoBuilder.build(with: error) { [weak self] in
switch error {
case .invalidLocationAuthorization:
if let applicationSettingsURL = URL(string:UIApplication.openSettingsURLString) {
UIApplication.shared.open(applicationSettingsURL)
} else {
self?.completion?(.done)
}
default:
self?.completion?(.done)
}
}
state.bindings.alertInfo = alertInfo
}
private func userLocationAnnotations(from usersLiveLocation: [UserLiveLocation]) -> [UserLocationAnnotation] {
return usersLiveLocation.map { userLiveLocation in
return UserLocationAnnotation(avatarData: userLiveLocation.avatarData, coordinate: userLiveLocation.coordinate)
}
}
private func currentUserLocationAnnotation(from annotations: [UserLocationAnnotation]) -> UserLocationAnnotation? {
annotations.first { annotation in
return liveLocationSharingViewerService.isCurrentUserId(annotation.userId)
}
}
private func getHighlightedAnnotation(from annotations: [UserLocationAnnotation]) -> UserLocationAnnotation? {
if let userAnnotation = self.currentUserLocationAnnotation(from: annotations) {
return userAnnotation
} else {
return annotations.first
}
}
private func listItemsViewData(from usersLiveLocation: [UserLiveLocation]) -> [LiveLocationListItemViewData] {
var listItemsViewData: [LiveLocationListItemViewData] = []
let sortedUsersLiveLocation = usersLiveLocation.sorted { userLiveLocation1, userLiveLocation2 in
return userLiveLocation1.displayName > userLiveLocation2.displayName
}
listItemsViewData = sortedUsersLiveLocation.map({ userLiveLocation in
return self.listItemViewData(from: userLiveLocation)
})
let currentUserIndex = listItemsViewData.firstIndex { viewData in
return viewData.isCurrentUser
}
// Move current user as first item
if let currentUserIndex = currentUserIndex {
let currentUserViewData = listItemsViewData[currentUserIndex]
listItemsViewData.remove(at: currentUserIndex)
listItemsViewData.insert(currentUserViewData, at: 0)
}
return listItemsViewData
}
private func listItemViewData(from userLiveLocation: UserLiveLocation) -> LiveLocationListItemViewData {
let isCurrentUser = self.liveLocationSharingViewerService.isCurrentUserId(userLiveLocation.userId)
let expirationDate = userLiveLocation.timestamp + userLiveLocation.timeout
return LiveLocationListItemViewData(userId: userLiveLocation.userId, isCurrentUser: isCurrentUser, avatarData: userLiveLocation.avatarData, displayName: userLiveLocation.displayName, expirationDate: expirationDate, lastUpdate: userLiveLocation.lastUpdate)
}
private func update(with usersLiveLocation: [UserLiveLocation]) {
let annotations: [UserLocationAnnotation] = self.userLocationAnnotations(from: usersLiveLocation)
let highlightedAnnotation = self.getHighlightedAnnotation(from: annotations)
let listViewItems = self.listItemsViewData(from: usersLiveLocation)
self.state.annotations = annotations
self.state.highlightedAnnotation = highlightedAnnotation
self.state.listItemsViewData = listViewItems
}
private func highlighAnnotation(with userId: String) {
let foundUserAnnotation = self.state.annotations.first { annotation in
annotation.userId == userId
}
guard let foundUserAnnotation = foundUserAnnotation else {
return
}
self.state.highlightedAnnotation = foundUserAnnotation
}
}
@@ -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 LiveLocationSharingViewerViewModelProtocol {
var completion: ((LiveLocationSharingViewerViewModelResult) -> Void)? { get set }
@available(iOS 14, *)
var context: LiveLocationSharingViewerViewModelType.Context { get }
}
@@ -0,0 +1,63 @@
//
// 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 MockLiveLocationSharingViewerScreenState: MockScreenState, CaseIterable {
// A case for each state you want to represent
// with specific, minimal associated data that will allow you
// mock that screen.
case currentUser
case multipleUsers
/// The associated screen
var screenType: Any.Type {
LiveLocationSharingViewer.self
}
/// A list of screen state definitions
static var allCases: [MockLiveLocationSharingViewerScreenState] {
return [.currentUser, .multipleUsers]
}
/// Generate the view struct for the screen state.
var screenView: ([Any], AnyView) {
let service: LiveLocationSharingViewerServiceProtocol
switch self {
case .currentUser:
service = MockLiveLocationSharingViewerService()
case .multipleUsers:
service = MockLiveLocationSharingViewerService(generateRandomUsers: true)
}
let mapStyleURL = URL(string: "https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx")!
let viewModel = LiveLocationSharingViewerViewModel(mapStyleURL: mapStyleURL, service: service)
// can simulate service and viewModel actions here if needs be.
return (
[service, viewModel],
AnyView(LiveLocationSharingViewer(viewModel: viewModel.context))
)
}
}
@@ -0,0 +1,26 @@
//
// 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 LiveLocationSharingViewerUITests: MockScreenTest {
override class var screenType: MockScreenState.Type {
return MockLiveLocationSharingViewerScreenState.self
}
}
@@ -0,0 +1,35 @@
//
// 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 Combine
@testable import RiotSwiftUI
@available(iOS 14.0, *)
class LiveLocationSharingViewerViewModelTests: XCTestCase {
var service: MockLiveLocationSharingViewerService!
var viewModel: LiveLocationSharingViewerViewModelProtocol!
var context: LiveLocationSharingViewerViewModelType.Context!
var cancellables = Set<AnyCancellable>()
override func setUpWithError() throws {
service = MockLiveLocationSharingViewerService()
viewModel = LiveLocationSharingViewerViewModel(mapStyleURL: BuildSettings.tileServerMapStyleURL, service: service)
context = viewModel.context
}
}
@@ -0,0 +1,118 @@
//
// 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 DSBottomSheet
@available(iOS 14.0, *)
struct LiveLocationSharingViewer: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
var isBottomSheetVisible = true
@State private var isBottomSheetExpanded = false
// MARK: Public
@ObservedObject var viewModel: LiveLocationSharingViewerViewModel.Context
var body: some View {
ZStack(alignment: .bottom) {
LocationSharingMapView(tileServerMapURL: viewModel.viewState.mapStyleURL,
annotations: viewModel.viewState.annotations,
highlightedAnnotation: viewModel.viewState.highlightedAnnotation,
userAvatarData: nil,
showsUserLocation: false,
userLocation: Binding.constant(nil),
mapCenterCoordinate: Binding.constant(nil),
onCalloutTap: { annotation in
if let userLocationAnnotation = annotation as? UserLocationAnnotation {
viewModel.send(viewAction: .share(userLocationAnnotation))
}
},
errorSubject: viewModel.viewState.errorSubject)
MapCreditsView()
}
.bottomSheet(sheet, if: isBottomSheetVisible)
.alert(item: $viewModel.alertInfo) { info in
info.alert
}
.accentColor(theme.colors.accent)
.activityIndicator(show: viewModel.viewState.showLoadingIndicator)
}
var userLocationList: some View {
ScrollView {
VStack(alignment: .leading, spacing: 14) {
ForEach(viewModel.viewState.listItemsViewData) { viewData in
LiveLocationListItem(viewData: viewData, onStopSharingAction: {
viewModel.send(viewAction: .stopSharing)
}, onBackgroundTap: { userId in
// Push bottom sheet down on item tap
isBottomSheetExpanded = false
viewModel.send(viewAction: .tapListItem(userId))
})
}
}
.padding()
}
}
}
// MARK: - Bottom sheet
@available(iOS 14.0, *)
extension LiveLocationSharingViewer {
var sheetStyle: BottomSheetStyle {
var bottomSheetStyle = BottomSheetStyle.standard
bottomSheetStyle.snapRatio = 0.16
let backgroundColor = theme.colors.background
let handleStyle = BottomSheetHandleStyle(backgroundColor: backgroundColor, dividerColor: backgroundColor)
bottomSheetStyle.handleStyle = handleStyle
return bottomSheetStyle
}
var sheet: some BottomSheetView {
BottomSheet(
isExpanded: $isBottomSheetExpanded,
minHeight: .points(150),
maxHeight: .available,
style: sheetStyle) {
userLocationList
}
}
}
// MARK: - Previews
@available(iOS 14.0, *)
struct LiveLocationSharingViewer_Previews: PreviewProvider {
static let stateRenderer = MockLiveLocationSharingViewerScreenState.stateRenderer
static var previews: some View {
Group {
stateRenderer.screenGroup().theme(.light).preferredColorScheme(.light)
stateRenderer.screenGroup().theme(.dark).preferredColorScheme(.dark)
}
}
}