Move location sharing screens in the appropriate folder.

This commit is contained in:
SBiOSoftWhare
2022-08-03 10:39:28 +02:00
parent 6a1e500835
commit a7281880a4
48 changed files with 0 additions and 0 deletions
@@ -1,97 +0,0 @@
//
// 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
let roomId: String
let navigationRouter: NavigationRouterType?
}
final class LiveLocationSharingViewerCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: LiveLocationSharingViewerCoordinatorParameters
private let navigationRouter: NavigationRouterType
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
init(parameters: LiveLocationSharingViewerCoordinatorParameters) {
self.parameters = parameters
let service = LiveLocationSharingViewerService(session: parameters.session, roomId: parameters.roomId)
let viewModel = LiveLocationSharingViewerViewModel(
mapStyleURL: parameters.session.vc_homeserverConfiguration().tileServer.mapStyleURL,
service: service)
let view = LiveLocationSharingViewer(viewModel: viewModel.context)
.addDependency(AvatarService.instantiate(mediaManager: parameters.session.mediaManager))
liveLocationSharingViewerViewModel = viewModel
liveLocationSharingViewerHostingController = VectorHostingController(rootView: view)
navigationRouter = parameters.navigationRouter ?? NavigationRouter()
}
// 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)
}
}
let viewController: UIViewController = self.liveLocationSharingViewerHostingController
if navigationRouter.modules.count > 1 {
navigationRouter.push(viewController, animated: true, popCompletion: nil)
} else {
navigationRouter.setRootModule(viewController)
}
}
func toPresentable() -> UIViewController {
return navigationRouter.toPresentable()
.vc_setModalFullScreen(true) // Set fullscreen as DSBottomSheet is not working with modal pan gesture recognizer
}
func presentLocationActivityController(with coordinate: CLLocationCoordinate2D) {
let shareActivityController = shareLocationActivityControllerBuilder.build(with: coordinate)
self.liveLocationSharingViewerHostingController.present(shareActivityController, animated: true)
}
}
@@ -1,79 +0,0 @@
//
// 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)
}
// MARK: View
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: LocationAnnotation?
/// Live location list items
var listItemsViewData: [LiveLocationListItemViewData]
var showLoadingIndicator: Bool = false
var shareButtonEnabled: Bool {
!showLoadingIndicator
}
/// True to indicate that everybody stopped to share live location sharing in the room
var isAllLocationSharingEnded: Bool {
return listItemsViewData.isEmpty
}
var isBottomSheetVisible: Bool {
return isAllLocationSharingEnded == false
}
var showMapLoadingError: Bool = false
let errorSubject = PassthroughSubject<LocationSharingViewError, Never>()
var bindings = LocationSharingViewStateBindings()
}
struct LiveLocationSharingViewerViewStateBindings {
var alertInfo: AlertInfo<LocationSharingAlertType>?
var showMapCreditsSheet = false
}
enum LiveLocationSharingViewerViewAction {
case done
case stopSharing
case tapListItem(_ userId: String)
case share(_ annotation: UserLocationAnnotation)
case mapCreditsDidTap
}
@@ -1,243 +0,0 @@
//
// 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
typealias LiveLocationSharingViewerViewModelType = StateStoreViewModel<LiveLocationSharingViewerViewState,
Never,
LiveLocationSharingViewerViewAction>
class LiveLocationSharingViewerViewModel: LiveLocationSharingViewerViewModelType, LiveLocationSharingViewerViewModelProtocol {
// MARK: - Properties
// MARK: Private
private var liveLocationSharingViewerService: LiveLocationSharingViewerServiceProtocol
private var mapViewErrorAlertInfoBuilder: MapViewErrorAlertInfoBuilder
private var screenUpdateTimer: Timer?
// Last annotation that could be highlighted
// Used to set map position when location sharing is ended
private var lastHighlightableAnnotation: LocationAnnotation?
// 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.setupLocationSharingService()
self.setupScreenUpdateTimer()
}
// MARK: - Public
override func process(viewAction: LiveLocationSharingViewerViewAction) {
switch viewAction {
case .done:
completion?(.done)
case .stopSharing:
stopUserLocationSharing()
case .tapListItem(let userId):
self.highlighAnnotation(with: userId)
case .share(let userLocationAnnotation):
completion?(.share(userLocationAnnotation.coordinate))
case .mapCreditsDidTap:
state.bindings.showMapCreditsSheet.toggle()
}
}
// MARK: - Private
private func setupLocationSharingService() {
self.updateUsersLiveLocation(highlightFirstLocation: true)
liveLocationSharingViewerService.didUpdateUsersLiveLocation = { [weak self] liveLocations in
self?.update(with: liveLocations, highlightFirstLocation: false)
}
self.liveLocationSharingViewerService.startListeningLiveLocationUpdates()
}
private func updateUsersLiveLocation(highlightFirstLocation: Bool) {
self.update(with: liveLocationSharingViewerService.usersLiveLocation, highlightFirstLocation: highlightFirstLocation)
}
private func setupScreenUpdateTimer() {
self.screenUpdateTimer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] timer in
self?.updateUsersLiveLocation(highlightFirstLocation: false)
}
}
private func processError(_ error: LocationSharingViewError) {
guard state.bindings.alertInfo == nil else {
return
}
if case .failedLoadingMap = error {
state.showMapLoadingError = true
}
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], highlightFirstLocation: Bool) {
let annotations: [UserLocationAnnotation] = self.userLocationAnnotations(from: usersLiveLocation)
var highlightedAnnotation: LocationAnnotation?
if highlightFirstLocation {
highlightedAnnotation = self.getHighlightedAnnotation(from: annotations)
}
if let highlightableAnnotation = self.getHighlightedAnnotation(from: annotations) {
self.lastHighlightableAnnotation = highlightableAnnotation
}
if let lastHighlightableAnnotation = self.lastHighlightableAnnotation, usersLiveLocation.isEmpty {
highlightedAnnotation = InvisibleLocationAnnotation(coordinate: lastHighlightableAnnotation.coordinate)
}
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
}
private func stopUserLocationSharing() {
self.state.showLoadingIndicator = true
self.liveLocationSharingViewerService.stopUserLiveLocationSharing { result in
self.state.showLoadingIndicator = false
switch result {
case .success:
break
case.failure:
self.state.bindings.alertInfo = AlertInfo(id: .stopLocationSharingError,
title: VectorL10n.error,
message: VectorL10n.locationSharingLiveStopSharingError,
primaryButton: (VectorL10n.ok, nil))
}
}
}
}
@@ -1,23 +0,0 @@
//
// 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 }
var context: LiveLocationSharingViewerViewModelType.Context { get }
}
@@ -1,62 +0,0 @@
//
// 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.
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))
)
}
}
@@ -1,37 +0,0 @@
//
// 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
protocol LiveLocationSharingViewerServiceProtocol {
/// All shared users live location
var usersLiveLocation: [UserLiveLocation] { get }
/// Called when users live location are updated (new location, location stopped, ).
var didUpdateUsersLiveLocation: (([UserLiveLocation]) -> Void)? { get set }
func isCurrentUserId(_ userId: String) -> Bool
func startListeningLiveLocationUpdates()
func stopListeningLiveLocationUpdates()
/// Stop current user location sharing
func stopUserLiveLocationSharing(completion: @escaping (Result<Void, Error>) -> Void)
}
@@ -1,114 +0,0 @@
//
// 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 CoreLocation
import MatrixSDK
class LiveLocationSharingViewerService: LiveLocationSharingViewerServiceProtocol {
// MARK: - Properties
private(set) var usersLiveLocation: [UserLiveLocation] = []
private let roomId: String
private var beaconInfoSummaryListener: Any?
// MARK: Private
private let session: MXSession
// MARK: Public
var didUpdateUsersLiveLocation: (([UserLiveLocation]) -> Void)?
// MARK: - Setup
init(session: MXSession, roomId: String) {
self.session = session
self.roomId = roomId
self.updateUsersLiveLocation(notifyUpdate: false)
}
// MARK: - Public
func isCurrentUserId(_ userId: String) -> Bool {
return self.session.myUserId == userId
}
func startListeningLiveLocationUpdates() {
self.beaconInfoSummaryListener = self.session.aggregations.beaconAggregations.listenToBeaconInfoSummaryUpdateInRoom(withId: self.roomId) { [weak self] _ in
self?.updateUsersLiveLocation(notifyUpdate: true)
}
}
func stopListeningLiveLocationUpdates() {
if let listener = beaconInfoSummaryListener {
self.session.aggregations.removeListener(listener)
self.beaconInfoSummaryListener = nil
}
}
func stopUserLiveLocationSharing(completion: @escaping (Result<Void, Error>) -> Void) {
self.session.locationService.stopUserLocationSharing(inRoomWithId: roomId) { response in
switch response {
case .success:
completion(.success(Void()))
case .failure(let error):
completion(.failure(error))
}
}
}
// MARK: - Private
private func updateUsersLiveLocation(notifyUpdate: Bool) {
let beaconInfoSummaries = self.session.locationService.getDisplayableBeaconInfoSummaries(inRoomWithId: roomId)
self.usersLiveLocation = Self.usersLiveLocation(fromBeaconInfoSummaries: beaconInfoSummaries, session: session)
if notifyUpdate {
self.didUpdateUsersLiveLocation?(self.usersLiveLocation)
}
}
class private func usersLiveLocation(fromBeaconInfoSummaries beaconInfoSummaries: [MXBeaconInfoSummaryProtocol], session: MXSession) -> [UserLiveLocation] {
return beaconInfoSummaries.compactMap { beaconInfoSummary in
let beaconInfo = beaconInfoSummary.beaconInfo
guard let lastBeacon = beaconInfoSummary.lastBeacon else {
return nil
}
let avatarData = session.avatarInput(for: beaconInfoSummary.userId)
let timestamp = TimeInterval(beaconInfo.timestamp/1000)
let timeout = TimeInterval(beaconInfo.timeout/1000)
let lastUpdate = TimeInterval(lastBeacon.timestamp/1000)
let coordinate = CLLocationCoordinate2D(latitude: lastBeacon.location.latitude, longitude: lastBeacon.location.longitude)
return UserLiveLocation(avatarData: avatarData,
timestamp: timestamp,
timeout: timeout,
lastUpdate: lastUpdate,
coordinate: coordinate)
}
}
}
@@ -1,114 +0,0 @@
//
// 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
class MockLiveLocationSharingViewerService: LiveLocationSharingViewerServiceProtocol {
// MARK: Properties
private(set) var usersLiveLocation: [UserLiveLocation] = []
var didUpdateUsersLiveLocation: (([UserLiveLocation]) -> Void)?
// MARK: Setup
init(generateRandomUsers: Bool = false) {
let firstUserLiveLocation = self.createFirstUserLiveLocation()
let secondUserLiveLocation = self.createSecondUserLiveLocation()
var usersLiveLocation: [UserLiveLocation] = [firstUserLiveLocation, secondUserLiveLocation]
if generateRandomUsers {
for _ in 1...20 {
let randomUser = self.createRandomUserLiveLocation()
usersLiveLocation.append(randomUser)
}
}
self.usersLiveLocation = usersLiveLocation
}
// MARK: Public
func isCurrentUserId(_ userId: String) -> Bool {
return "@alice:matrix.org" == userId
}
func startListeningLiveLocationUpdates() {
}
func stopListeningLiveLocationUpdates() {
}
func stopUserLiveLocationSharing(completion: @escaping (Result<Void, Error>) -> Void) {
}
// MARK: Private
private func createFirstUserLiveLocation() -> UserLiveLocation {
let userAvatarData = AvatarInput(mxContentUri: nil, matrixItemId: "@alice:matrix.org", displayName: "Alice")
let userCoordinate = CLLocationCoordinate2D(latitude: 51.4932641, longitude: -0.257096)
let currentTimeInterval = Date().timeIntervalSince1970
let timestamp = currentTimeInterval - 300
let timeout: TimeInterval = 800
let lastUpdate = currentTimeInterval - 100
return UserLiveLocation(avatarData: userAvatarData, timestamp: timestamp, timeout: timeout, lastUpdate: lastUpdate, coordinate: userCoordinate)
}
private func createSecondUserLiveLocation() -> UserLiveLocation {
let userAvatarData = AvatarInput(mxContentUri: nil, matrixItemId: "@bob:matrix.org", displayName: "Bob")
let coordinate = CLLocationCoordinate2D(latitude: 51.4952641, longitude: -0.259096)
let currentTimeInterval = Date().timeIntervalSince1970
let timestamp = currentTimeInterval - 600
let timeout: TimeInterval = 1200
let lastUpdate = currentTimeInterval - 300
return UserLiveLocation(avatarData: userAvatarData, timestamp: timestamp, timeout: timeout, lastUpdate: lastUpdate, coordinate: coordinate)
}
private func createRandomUserLiveLocation() -> UserLiveLocation {
let uuidString = UUID().uuidString.suffix(8)
let random = Double.random(in: 0.005...0.010)
let userAvatarData = AvatarInput(mxContentUri: nil, matrixItemId: "@user_\(uuidString):matrix.org", displayName: "User \(uuidString)")
let coordinate = CLLocationCoordinate2D(latitude: 51.4952641 + random, longitude: -0.259096 + random)
let currentTimeInterval = Date().timeIntervalSince1970
let timestamp = currentTimeInterval - 600
let timeout: TimeInterval = 1200
let lastUpdate = currentTimeInterval - 300
return UserLiveLocation(avatarData: userAvatarData, timestamp: timestamp, timeout: timeout, lastUpdate: lastUpdate, coordinate: coordinate)
}
}
@@ -1,43 +0,0 @@
//
// 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
import CoreLocation
/// Represents user live location
struct UserLiveLocation {
var userId: String {
return avatarData.matrixItemId
}
var displayName: String {
return avatarData.displayName ?? self.userId
}
let avatarData: AvatarInputProtocol
/// Location sharing start date
let timestamp: TimeInterval
/// Sharing duration from the start sharing date
let timeout: TimeInterval
/// Last coordinatore update date
let lastUpdate: TimeInterval
let coordinate: CLLocationCoordinate2D
}
@@ -1,22 +0,0 @@
//
// 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
class LiveLocationSharingViewerUITests: MockScreenTestCase {
// Tests to be implemented.
}
@@ -1,34 +0,0 @@
//
// 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
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.defaultTileServerMapStyleURL, service: service)
context = viewModel.context
}
}
@@ -1,189 +0,0 @@
//
// 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 SwiftUI
struct LiveLocationListItem: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: Public
let viewData: LiveLocationListItemViewData
var timeoutText: String {
let timeLeftString: String
if let elapsedTimeString = self.elapsedTimeString(from: viewData.expirationDate, isPastDate: false) {
timeLeftString = VectorL10n.locationSharingLiveListItemTimeLeft(elapsedTimeString)
} else {
timeLeftString = VectorL10n.locationSharingLiveListItemSharingExpired
}
return timeLeftString
}
var lastUpdateText: String {
let timeLeftString: String
if let elapsedTimeString = self.elapsedTimeString(from: viewData.lastUpdate, isPastDate: true) {
timeLeftString = VectorL10n.locationSharingLiveListItemLastUpdate(elapsedTimeString)
} else {
timeLeftString = VectorL10n.locationSharingLiveListItemLastUpdateInvalid
}
return timeLeftString
}
var displayName: String {
return viewData.isCurrentUser ? VectorL10n.locationSharingLiveListItemCurrentUserDisplayName : viewData.displayName
}
var onStopSharingAction: (() -> (Void))? = nil
var onBackgroundTap: ((String) -> (Void))? = nil
// MARK: - Body
var body: some View {
HStack {
HStack(spacing: 18) {
AvatarImage(avatarData: viewData.avatarData, size: .medium)
.border()
VStack(alignment: .leading, spacing: 2) { Text(displayName)
.font(theme.fonts.bodySB)
.foregroundColor(theme.colors.primaryContent)
Text(timeoutText)
.font(theme.fonts.caption1)
.foregroundColor(theme.colors.primaryContent)
Text(lastUpdateText)
.font(theme.fonts.caption1)
.foregroundColor(theme.colors.secondaryContent)
}
}
if viewData.isCurrentUser {
Spacer()
Button(VectorL10n.locationSharingLiveListItemStopSharingAction) {
onStopSharingAction?()
}
.font(theme.fonts.body)
.foregroundColor(theme.colors.alert)
}
}
.onTapGesture {
onBackgroundTap?(self.viewData.userId)
}
}
// MARK: - Private
private func elapsedTimeString(from timestamp: TimeInterval, isPastDate: Bool) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.hour, .minute, .second]
let date = Date(timeIntervalSince1970: timestamp)
let elaspedTimeinterval = date.timeIntervalSinceNow
var timeLeftString: String?
// Negative value indicate that the timestamp is in the past
// Positive value indicate that the timestamp is in the future
// Return nil if the sign is not the one as expected
if (isPastDate && elaspedTimeinterval <= 0) || (!isPastDate && elaspedTimeinterval >= 0) {
timeLeftString = formatter.string(from: abs(elaspedTimeinterval))
}
return timeLeftString
}
}
struct LiveLocationListPreview: View {
let liveLocationSharingViewerService: LiveLocationSharingViewerServiceProtocol = MockLiveLocationSharingViewerService()
var viewDataList: [LiveLocationListItemViewData] {
return self.listItemsViewData(from: liveLocationSharingViewerService.usersLiveLocation)
}
var body: some View {
VStack(alignment: .leading, spacing: 14) {
ForEach(viewDataList) { viewData in
LiveLocationListItem(viewData: viewData, onStopSharingAction: {
}, onBackgroundTap: { userId in
})
}
Spacer()
}
.padding()
}
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)
}
}
struct LiveLocationListItem_Previews: PreviewProvider {
static var previews: some View {
Group {
LiveLocationListPreview().theme(.light).preferredColorScheme(.light)
LiveLocationListPreview().theme(.dark).preferredColorScheme(.dark)
}
}
}
@@ -1,39 +0,0 @@
//
// 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
/// View data for LiveLocationListItem
struct LiveLocationListItemViewData: Identifiable {
var id: String {
return userId
}
let userId: String
let isCurrentUser: Bool
let avatarData: AvatarInputProtocol
let displayName: String
/// The location sharing expiration date
let expirationDate: TimeInterval
/// Last coordinatore update
let lastUpdate: TimeInterval
}
@@ -1,181 +0,0 @@
//
// 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
struct LiveLocationSharingViewer: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
@Environment(\.openURL) var openURL
@State private var isBottomSheetExpanded = false
var bottomSheetCollapsedHeight: CGFloat = 150.0
// MARK: Public
@ObservedObject var viewModel: LiveLocationSharingViewerViewModel.Context
var body: some View {
ZStack(alignment: .bottom) {
if !viewModel.viewState.showMapLoadingError {
LocationSharingMapView(tileServerMapURL: viewModel.viewState.mapStyleURL,
annotations: viewModel.viewState.annotations,
highlightedAnnotation: viewModel.viewState.highlightedAnnotation,
userAvatarData: nil,
showsUserLocation: false,
userAnnotationCanShowCallout: true,
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)
// Show map credits above collapsed bottom sheet height if bottom sheet is visible
if viewModel.viewState.isBottomSheetVisible {
VStack(alignment: .center) {
Spacer()
MapCreditsView(action: {
viewModel.send(viewAction: .mapCreditsDidTap)
})
.offset(y: -(bottomSheetCollapsedHeight)) // Put the copyright action above the collapsed bottom sheet
.padding(.bottom, 10)
}
.ignoresSafeArea()
}
} else {
MapLoadingErrorView()
.padding(.bottom, viewModel.viewState.isBottomSheetVisible ? bottomSheetCollapsedHeight : 0)
}
if viewModel.viewState.isAllLocationSharingEnded {
VStack(alignment: .center) {
Spacer()
// Show map credits only if map is visible
if !viewModel.viewState.showMapLoadingError {
MapCreditsView(action: {
viewModel.send(viewAction: .mapCreditsDidTap)
})
.padding(.bottom, 5)
}
HStack(spacing: 10) {
Image(uiImage: Asset.Images.locationLiveCellIcon.image)
.renderingMode(.template)
.foregroundColor(theme.colors.quaternaryContent)
.frame(width: 40, height: 40)
Text(VectorL10n.liveLocationSharingEnded)
.font(theme.fonts.body)
.foregroundColor(theme.colors.tertiaryContent)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 10)
.padding(.horizontal, 15)
.background(theme.colors.background.ignoresSafeArea())
}
}
}
.navigationTitle(VectorL10n.locationSharingLiveViewerTitle)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button(VectorL10n.close) {
viewModel.send(viewAction: .done)
}
}
}
.accentColor(theme.colors.accent)
.background(theme.colors.system.ignoresSafeArea())
.bottomSheet(sheet, if: viewModel.viewState.isBottomSheetVisible)
.actionSheet(isPresented: $viewModel.showMapCreditsSheet) {
return MapCreditsActionSheet(openURL: { url in
openURL(url)
}).sheet
}
.alert(item: $viewModel.alertInfo) { info in
info.alert
}
.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()
}
.background(theme.colors.background.ignoresSafeArea())
}
}
// MARK: - Bottom sheet
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(bottomSheetCollapsedHeight),
maxHeight: .available,
style: sheetStyle) {
userLocationList
}
}
}
// MARK: - Previews
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)
}
}
}
@@ -1,237 +0,0 @@
//
// 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
import SwiftUI
import MatrixSDK
struct LocationSharingCoordinatorParameters {
let session: MXSession
let roomDataSource: MXKRoomDataSource
let mediaManager: MXMediaManager
let avatarData: AvatarInputProtocol
}
// Map between type from MatrixSDK and type from SwiftUI target, as we don't want
// to add the SDK as a dependency to it. We need to translate from one to the other on this level.
extension MXEventAssetType {
func locationSharingCoordinateType() -> LocationSharingCoordinateType? {
let coordinateType: LocationSharingCoordinateType?
switch self {
case .user:
coordinateType = .user
case .pin:
coordinateType = .pin
default:
coordinateType = nil
}
return coordinateType
}
}
extension LocationSharingCoordinateType {
func eventAssetType() -> MXEventAssetType {
let eventAssetType: MXEventAssetType
switch self {
case .user:
eventAssetType = .user
case .pin:
eventAssetType = .pin
}
return eventAssetType
}
}
final class LocationSharingCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: LocationSharingCoordinatorParameters
private let locationSharingHostingController: UIViewController
private var locationSharingViewModel: LocationSharingViewModelProtocol
// MARK: Public
var childCoordinators: [Coordinator] = []
var completion: (() -> Void)?
// MARK: - Setup
init(parameters: LocationSharingCoordinatorParameters) {
self.parameters = parameters
let locationSharingService = LocationSharingService(session: parameters.roomDataSource.mxSession)
let viewModel = LocationSharingViewModel(
mapStyleURL: parameters.session.vc_homeserverConfiguration().tileServer.mapStyleURL,
avatarData: parameters.avatarData,
isLiveLocationSharingEnabled: true,
service: locationSharingService)
let view = LocationSharingView(context: viewModel.context)
.addDependency(AvatarService.instantiate(mediaManager: parameters.mediaManager))
locationSharingViewModel = viewModel
locationSharingHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
locationSharingViewModel.completion = { [weak self] result in
guard let self = self else { return }
switch result {
case .cancel:
self.completion?()
case .share(let latitude, let longitude, let coordinateType):
self.shareStaticLocation(latitude: latitude, longitude: longitude, coordinateType: coordinateType)
case .shareLiveLocation(let timeout):
self.startLiveLocationSharing(with: timeout)
case .checkLiveLocationCanBeStarted(let completion):
self.checkLiveLocationCanBeStarted(completion: completion)
}
}
}
static func shareLocationActivityController(_ location: CLLocationCoordinate2D) -> UIActivityViewController {
return UIActivityViewController(activityItems: [ShareToMapsAppActivity.urlForMapsAppType(.apple, location: location)],
applicationActivities: [ShareToMapsAppActivity(type: .apple, location: location),
ShareToMapsAppActivity(type: .google, location: location),
ShareToMapsAppActivity(type: .osm, location: location)])
}
// MARK: - Private
private func presentShareLocationActivity(with location: CLLocationCoordinate2D) {
self.locationSharingHostingController.present(Self.shareLocationActivityController(location), animated: true)
}
private func shareStaticLocation(latitude: Double, longitude: Double, coordinateType: LocationSharingCoordinateType) {
self.locationSharingViewModel.startLoading()
self.parameters.roomDataSource.sendLocation(withLatitude: latitude, longitude: longitude, description: nil, coordinateType: coordinateType.eventAssetType()) { [weak self] _ in
guard let self = self else { return }
self.locationSharingViewModel.stopLoading()
self.completion?()
} failure: { [weak self] error in
guard let self = self else { return }
MXLog.error("[LocationSharingCoordinator] Failed sharing location with error: \(String(describing: error))")
self.locationSharingViewModel.stopLoading(error: .locationSharingError)
}
}
private func startLiveLocationSharing(with timeout: TimeInterval) {
guard let locationService = self.parameters.roomDataSource.mxSession.locationService, let roomId = self.parameters.roomDataSource.roomId else {
self.locationSharingViewModel.stopLoading(error: .locationSharingError)
return
}
locationService.startUserLocationSharing(withRoomId: roomId, description: nil, timeout: timeout) { [weak self] response in
guard let self = self else { return }
switch response {
case .success:
DispatchQueue.main.async {
self.locationSharingViewModel.stopLoading()
self.completion?()
}
case .failure(let error):
MXLog.error("[LocationSharingCoordinator] Failed to start live location sharing with error: \(String(describing: error))")
DispatchQueue.main.async {
self.locationSharingViewModel.stopLoading(error: .locationSharingError)
}
}
}
}
private func checkLiveLocationCanBeStarted(completion: @escaping ((Result<Void, Error>) -> Void)) {
guard self.canShareLiveLocation() else {
completion(.failure(LiveLocationStartError.powerLevelNotHighEnough))
return
}
self.showLabFlagPromotionIfNeeded { labFlagEnabled in
if labFlagEnabled {
completion(.success(Void()))
} else {
completion(.failure(LiveLocationStartError.labFlagNotEnabled))
}
}
}
// Check if user can send beacon info state event
private func canShareLiveLocation() -> Bool {
guard let myUserId = self.parameters.roomDataSource.mxSession.myUserId else {
return false
}
let userPowerLevelRawValue = self.parameters.roomDataSource.roomState.powerLevels.powerLevelOfUser(withUserID: myUserId)
guard let userPowerLevel = RoomPowerLevel(rawValue: userPowerLevelRawValue) else {
return false
}
return userPowerLevel.rawValue >= RoomPowerLevel.moderator.rawValue
}
private func showLabFlagPromotionIfNeeded(completion: @escaping ((Bool) -> Void)) {
guard RiotSettings.shared.enableLiveLocationSharing == false else {
// Live location sharing lab flag is already enabled, do not present lab flag promotion screen
completion(true)
return
}
self.showLabFlagPromotion(completion: completion)
}
private func showLabFlagPromotion(completion: @escaping ((Bool) -> Void)) {
// TODO: Use a NavigationRouter instead of using NavigationView inside LocationSharingView
// In order to use `NavigationRouter.present`
let coordinator = LiveLocationLabPromotionCoordinator()
coordinator.start()
coordinator.completion = { [weak self, weak coordinator] enableLiveLocation in
guard let self = self, let coordinator = coordinator else { return }
completion(enableLiveLocation)
coordinator.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
self.locationSharingHostingController.present(coordinator.toPresentable(), animated: true)
self.add(childCoordinator: coordinator)
}
// MARK: - Presentable
func toPresentable() -> UIViewController {
return locationSharingHostingController
}
}
@@ -1,29 +0,0 @@
//
// 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
import CoreLocation
/// Build a UIActivityViewController to share a location
class ShareLocationActivityControllerBuilder {
func build(with location: CLLocationCoordinate2D) -> UIActivityViewController {
return UIActivityViewController(activityItems: [ShareToMapsAppActivity.urlForMapsAppType(.apple, location: location)],
applicationActivities: [ShareToMapsAppActivity(type: .apple, location: location),
ShareToMapsAppActivity(type: .google, location: location),
ShareToMapsAppActivity(type: .osm, location: location)])
}
}
@@ -1,83 +0,0 @@
//
// 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
extension UIActivity.ActivityType {
static let shareToMapsApp = UIActivity.ActivityType("Element.ShareToMapsApp")
}
class ShareToMapsAppActivity: UIActivity {
enum MapsAppType {
case apple
case google
case osm
}
private let type: MapsAppType
private let location: CLLocationCoordinate2D
private override init() {
fatalError()
}
init(type: MapsAppType, location: CLLocationCoordinate2D) {
self.type = type
self.location = location
}
static func urlForMapsAppType(_ type: MapsAppType, location: CLLocationCoordinate2D) -> URL {
switch type {
case .apple:
return URL(string: "https://maps.apple.com?ll=\(location.latitude),\(location.longitude)&q=Pin")!
case .google:
return URL(string: "https://www.google.com/maps/search/?api=1&query=\(location.latitude),\(location.longitude)")!
case .osm:
return URL(string: "https://www.openstreetmap.org/?mlat=\(location.latitude)&mlon=\(location.longitude)")!
}
}
override var activityTitle: String? {
switch type {
case .apple:
return VectorL10n.locationSharingOpenAppleMaps
case .google:
return VectorL10n.locationSharingOpenGoogleMaps
case .osm:
return VectorL10n.locationSharingOpenOpenStreetMaps
}
}
var activityCategory: UIActivity.Category {
return .action
}
override var activityType: UIActivity.ActivityType {
return .shareToMapsApp
}
override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return true
}
override func prepare(withActivityItems activityItems: [Any]) {
let url = Self.urlForMapsAppType(type, location: location)
UIApplication.shared.open(url, options: [:]) { [weak self] result in
self?.activityDidFinish(result)
}
}
}
@@ -1,65 +0,0 @@
//
// 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 Mapbox
/// Base class to handle a map annotation
class LocationAnnotation: NSObject, MGLAnnotation {
// MARK: - Properties
// Title property is needed to enable annotation selection and callout view showing
var title: String?
let coordinate: CLLocationCoordinate2D
// MARK: - Setup
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
}
/// POI map annotation
class PinLocationAnnotation: LocationAnnotation {}
/// User map annotation
class UserLocationAnnotation: LocationAnnotation {
// MARK: - Properties
var userId: String {
return avatarData.matrixItemId
}
let avatarData: AvatarInputProtocol
// MARK: - Setup
init(avatarData: AvatarInputProtocol,
coordinate: CLLocationCoordinate2D) {
self.avatarData = avatarData
super.init(coordinate: coordinate)
super.title = self.avatarData.displayName ?? self.userId
}
}
/// Invisible annotation
class InvisibleLocationAnnotation: LocationAnnotation {}
@@ -1,116 +0,0 @@
//
// 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
import Combine
import CoreLocation
// This is the equivalent of MXEventAssetType in the MatrixSDK
enum LocationSharingCoordinateType {
case user
case pin
}
enum LiveLocationSharingTimeout: TimeInterval {
// Timer are in milliseconde because timestamp are in millisecond in Matrix SDK
case short = 900000 // 15 minutes
case medium = 3600000 // 1 hour
case long = 28800000 // 8 hours
}
enum LocationSharingViewAction {
case cancel
case share
case sharePinLocation
case goToUserLocation
case startLiveSharing
case shareLiveLocation(timeout: LiveLocationSharingTimeout)
case userDidPan
case mapCreditsDidTap
}
enum LocationSharingViewModelResult {
case cancel
case share(latitude: Double, longitude: Double, coordinateType: LocationSharingCoordinateType)
case shareLiveLocation(timeout: TimeInterval)
case checkLiveLocationCanBeStarted(_ completion: ((Result<Void, Error>) -> Void))
}
enum LiveLocationStartError: Error {
case powerLevelNotHighEnough
case labFlagNotEnabled
}
enum LocationSharingViewError {
case failedLoadingMap
case failedLocatingUser
case invalidLocationAuthorization
case failedSharingLocation
}
struct LocationSharingViewState: BindableState {
/// Map style URL
let mapStyleURL: URL
/// Current user avatarData
let userAvatarData: AvatarInputProtocol
/// Map annotations to display on map
var annotations: [LocationAnnotation]
/// Map annotation to focus on
var highlightedAnnotation: LocationAnnotation?
/// Indicates whether the user has moved around the map to drop a pin somewhere other than their current location
var isPinDropSharing: Bool = false
var showLoadingIndicator: Bool = false
/// True to indicate to show and follow current user location
var showsUserLocation: Bool = false
/// Used to hide live location sharing features
var isLiveLocationSharingEnabled: Bool = false
var shareButtonEnabled: Bool {
!showLoadingIndicator
}
var showMapLoadingError: Bool = false
let errorSubject = PassthroughSubject<LocationSharingViewError, Never>()
var bindings = LocationSharingViewStateBindings()
}
struct LocationSharingViewStateBindings {
var alertInfo: AlertInfo<LocationSharingAlertType>?
var userLocation: CLLocationCoordinate2D?
var pinLocation: CLLocationCoordinate2D?
var showingTimerSelector = false
var showMapCreditsSheet = false
}
enum LocationSharingAlertType {
case mapLoadingError
case userLocatingError
case authorizationError
case locationSharingError
case stopLocationSharingError
case locationSharingPowerLevelError
}
@@ -1,40 +0,0 @@
//
// 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
import CoreLocation
enum MockLocationSharingScreenState: MockScreenState, CaseIterable {
case shareUserLocation
var screenType: Any.Type {
LocationSharingView.self
}
var screenView: ([Any], AnyView) {
let locationSharingService = MockLocationSharingService()
let mapStyleURL = URL(string: "https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx")!
let viewModel = LocationSharingViewModel(mapStyleURL: mapStyleURL,
avatarData: AvatarInput(mxContentUri: "", matrixItemId: "alice:matrix.org", displayName: "Alice"),
isLiveLocationSharingEnabled: true, service: locationSharingService)
return ([viewModel],
AnyView(LocationSharingView(context: viewModel.context)
.addDependency(MockAvatarService.example)))
}
}
@@ -1,205 +0,0 @@
//
// 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 CoreLocation
typealias LocationSharingViewModelType = StateStoreViewModel<LocationSharingViewState,
Never,
LocationSharingViewAction>
class LocationSharingViewModel: LocationSharingViewModelType, LocationSharingViewModelProtocol {
// MARK: - Properties
// MARK: Private
private let locationSharingService: LocationSharingServiceProtocol
// MARK: Public
var completion: ((LocationSharingViewModelResult) -> Void)?
// MARK: - Setup
init(mapStyleURL: URL, avatarData: AvatarInputProtocol, isLiveLocationSharingEnabled: Bool = false, service: LocationSharingServiceProtocol) {
self.locationSharingService = service
let viewState = LocationSharingViewState(mapStyleURL: mapStyleURL,
userAvatarData: avatarData,
annotations: [],
highlightedAnnotation: nil,
showsUserLocation: true,
isLiveLocationSharingEnabled: isLiveLocationSharingEnabled)
super.init(initialViewState: viewState)
state.errorSubject.sink { [weak self] error in
guard let self = self else { return }
self.processError(error)
}.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: LocationSharingViewAction) {
switch viewAction {
case .cancel:
completion?(.cancel)
case .share:
// Share current user location
guard let location = state.bindings.userLocation else {
processError(.failedLocatingUser)
return
}
completion?(.share(latitude: location.latitude, longitude: location.longitude, coordinateType: .user))
case .sharePinLocation:
guard let pinLocation = state.bindings.pinLocation else {
processError(.failedLocatingUser)
return
}
completion?(.share(latitude: pinLocation.latitude, longitude: pinLocation.longitude, coordinateType: .pin))
case .goToUserLocation:
state.showsUserLocation = true
state.isPinDropSharing = false
case .startLiveSharing:
self.startLiveLocationSharing()
case .shareLiveLocation(let timeout):
state.bindings.showingTimerSelector = false
completion?(.shareLiveLocation(timeout: timeout.rawValue))
case .userDidPan:
state.showsUserLocation = false
state.isPinDropSharing = true
case .mapCreditsDidTap:
state.bindings.showMapCreditsSheet.toggle()
}
}
// MARK: - LocationSharingViewModelProtocol
public func startLoading() {
state.showLoadingIndicator = true
}
func stopLoading(error: LocationSharingAlertType?) {
state.showLoadingIndicator = false
if let error = error {
let alertInfo: AlertInfo<LocationSharingAlertType>
switch error {
case .locationSharingPowerLevelError:
alertInfo = AlertInfo(id: error,
title: VectorL10n.locationSharingInvalidPowerLevelTitle,
message: VectorL10n.locationSharingInvalidPowerLevelMessage,
primaryButton: (VectorL10n.ok, nil))
default:
alertInfo = AlertInfo(id: error,
title: VectorL10n.locationSharingPostFailureTitle,
message: VectorL10n.locationSharingPostFailureSubtitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, nil))
}
state.bindings.alertInfo = alertInfo
}
}
// MARK: - Private
private func processError(_ error: LocationSharingViewError) {
guard state.bindings.alertInfo == nil else {
return
}
let primaryButtonCompletion = { [weak self] () -> Void in
self?.completion?(.cancel)
}
switch error {
case .failedLoadingMap:
state.bindings.alertInfo = AlertInfo(id: .mapLoadingError,
title: VectorL10n.locationSharingLoadingMapErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, primaryButtonCompletion))
state.showMapLoadingError = true
case .failedLocatingUser:
state.bindings.alertInfo = AlertInfo(id: .userLocatingError,
title: VectorL10n.locationSharingLocatingUserErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, primaryButtonCompletion))
case .invalidLocationAuthorization:
state.bindings.alertInfo = AlertInfo(id: .authorizationError,
title: VectorL10n.locationSharingInvalidAuthorizationErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.locationSharingInvalidAuthorizationNotNow, primaryButtonCompletion),
secondaryButton: (VectorL10n.locationSharingInvalidAuthorizationSettings, {
UIApplication.shared.vc_openSettings()
}))
default:
break
}
}
private func checkLocationAuthorizationAndPresentTimerSelector() {
self.locationSharingService.requestAuthorization { [weak self] authorizationStatus in
guard let self = self else {
return
}
switch authorizationStatus {
case .unknown, .denied:
// Show error alert
self.state.bindings.alertInfo = AlertInfo(id: .userLocatingError,
title: VectorL10n.locationSharingLocatingUserErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, { UIApplication.shared.vc_openSettings()
}))
case .authorizedInForeground:
// When user only authorized location in foreground, advize to use background location
self.state.bindings.alertInfo = AlertInfo(id: .userLocatingError,
title: VectorL10n.locationSharingAllowBackgroundLocationTitle,
message: VectorL10n.locationSharingAllowBackgroundLocationMessage,
primaryButton: (VectorL10n.locationSharingAllowBackgroundLocationCancelAction, {}),
secondaryButton: (VectorL10n.locationSharingAllowBackgroundLocationValidateAction, { UIApplication.shared.vc_openSettings() }))
case .authorizedAlways:
self.state.bindings.showingTimerSelector = true
}
}
}
private func startLiveLocationSharing() {
guard let completion = completion else {
return
}
completion(.checkLiveLocationCanBeStarted({ result in
switch result {
case .success:
self.checkLocationAuthorizationAndPresentTimerSelector()
case .failure(let error):
if case LiveLocationStartError.powerLevelNotHighEnough = error {
self.stopLoading(error: .locationSharingPowerLevelError)
}
}
}))
}
}
@@ -1,30 +0,0 @@
//
// 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 LocationSharingViewModelProtocol {
var completion: ((LocationSharingViewModelResult) -> Void)? { get set }
func startLoading()
func stopLoading(error: LocationSharingAlertType?)
}
extension LocationSharingViewModelProtocol {
func stopLoading() {
stopLoading(error: nil)
}
}
@@ -1,37 +0,0 @@
//
// 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 SwiftUI
struct MapCreditsActionSheet {
// Open URL action
let openURL: (URL) -> Void
// Map credits action sheet
var sheet: ActionSheet {
ActionSheet(title: Text(VectorL10n.locationSharingMapCreditsTitle),
buttons: [
.default(Text("© MapTiler")) {
openURL(URL(string: "https://www.maptiler.com/copyright/")!)
},
.default(Text("© OpenStreetMap")) {
openURL(URL(string: "https://www.openstreetmap.org/copyright")!)
},
.cancel()
])
}
}
@@ -1,46 +0,0 @@
//
// 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
struct MapViewErrorAlertInfoBuilder {
func build(with error: LocationSharingViewError, primaryButtonCompletion: (() -> Void)?) -> AlertInfo<LocationSharingAlertType>? {
let alertInfo: AlertInfo<LocationSharingAlertType>?
switch error {
case .failedLoadingMap:
alertInfo = AlertInfo(id: .mapLoadingError,
title: VectorL10n.locationSharingLoadingMapErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, primaryButtonCompletion))
case .failedLocatingUser:
alertInfo = AlertInfo(id: .userLocatingError,
title: VectorL10n.locationSharingLocatingUserErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.ok, primaryButtonCompletion))
case .invalidLocationAuthorization:
alertInfo = AlertInfo(id: .authorizationError,
title: VectorL10n.locationSharingInvalidAuthorizationErrorTitle(AppInfo.current.displayName),
primaryButton: (VectorL10n.locationSharingInvalidAuthorizationNotNow, primaryButtonCompletion),
secondaryButton: (VectorL10n.locationSharingInvalidAuthorizationSettings, primaryButtonCompletion))
default:
alertInfo = nil
}
return alertInfo
}
}
@@ -1,33 +0,0 @@
//
// 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
/// Location authorization status
enum LocationAuthorizationStatus {
/// Location status unknown
case unknown
/// Location access is denied
case denied
/// Location only authorized in foreground
case authorizedInForeground
/// Location only authorized in foreground and background
case authorizedAlways
}
@@ -1,28 +0,0 @@
//
// 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
/// Location authorization request handler
typealias LocationAuthorizationHandler = (_ authorizationStatus: LocationAuthorizationStatus) -> Void
protocol LocationSharingServiceProtocol {
/// Request location authorization
func requestAuthorization(_ handler: @escaping LocationAuthorizationHandler)
}
@@ -1,53 +0,0 @@
//
// 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 CoreLocation
import MatrixSDK
class LocationSharingService: LocationSharingServiceProtocol {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private var userLocationService: UserLocationServiceProtocol? {
return self.session.userLocationService
}
// MARK: Public
// MARK: - Setup
init(session: MXSession) {
self.session = session
}
// MARK: - Public
func requestAuthorization(_ handler: @escaping LocationAuthorizationHandler) {
guard let userLocationService = self.userLocationService else {
MXLog.error("[LocationSharingService] No userLocationService found for the current session")
handler(LocationAuthorizationStatus.unknown)
return
}
userLocationService.requestAuthorization(handler)
}
}
@@ -1,25 +0,0 @@
//
// 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
class MockLocationSharingService: LocationSharingServiceProtocol {
func requestAuthorization(_ handler: @escaping LocationAuthorizationHandler) {
handler(.authorizedAlways)
}
}
@@ -1,33 +0,0 @@
//
// 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
class LocationSharingUITests: MockScreenTestCase {
func testInitialUserLocation() {
goToScreenWithIdentifier(MockLocationSharingScreenState.shareUserLocation.title)
XCTAssertTrue(app.buttons["Cancel"].exists)
XCTAssertTrue(app.otherElements["Map"].exists)
}
// Need a delay when showing the map otherwise the simulator breaks
private func goToScreenWithIdentifier(_ identifier: String) {
app.goToScreenWithIdentifier(identifier)
sleep(2)
}
}
@@ -1,104 +0,0 @@
//
// 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
import CoreLocation
@testable import RiotSwiftUI
class LocationSharingViewModelTests: XCTestCase {
var cancellables = Set<AnyCancellable>()
func testInitialState() {
let viewModel = buildViewModel()
XCTAssertTrue(viewModel.context.viewState.shareButtonEnabled)
XCTAssertFalse(viewModel.context.viewState.showLoadingIndicator)
XCTAssertNotNil(viewModel.context.viewState.mapStyleURL)
XCTAssertNotNil(viewModel.context.viewState.userAvatarData)
XCTAssertNil(viewModel.context.viewState.bindings.userLocation)
XCTAssertNil(viewModel.context.viewState.bindings.alertInfo)
}
func testCancellation() {
let viewModel = buildViewModel()
let expectation = self.expectation(description: "Cancellation completion should be invoked")
viewModel.completion = { result in
switch result {
case .share:
XCTFail()
case .cancel:
expectation.fulfill()
case .shareLiveLocation:
XCTFail()
case .checkLiveLocationCanBeStarted:
XCTFail()
}
}
viewModel.context.send(viewAction: .cancel)
waitForExpectations(timeout: 3)
}
func testShareNoUserLocation() {
let viewModel = buildViewModel()
XCTAssertNil(viewModel.context.viewState.bindings.userLocation)
viewModel.context.send(viewAction: .share)
XCTAssertNotNil(viewModel.context.viewState.bindings.alertInfo)
XCTAssertEqual(viewModel.context.viewState.bindings.alertInfo?.id, .userLocatingError)
}
func testLoading() {
let viewModel = buildViewModel()
viewModel.startLoading()
XCTAssertFalse(viewModel.context.viewState.shareButtonEnabled)
XCTAssertTrue(viewModel.context.viewState.showLoadingIndicator)
viewModel.stopLoading()
XCTAssertTrue(viewModel.context.viewState.shareButtonEnabled)
XCTAssertFalse(viewModel.context.viewState.showLoadingIndicator)
}
func testInvalidLocationAuthorization() {
let viewModel = buildViewModel()
viewModel.context.viewState.errorSubject.send(.invalidLocationAuthorization)
XCTAssertNotNil(viewModel.context.alertInfo)
XCTAssertEqual(viewModel.context.viewState.bindings.alertInfo?.id, .authorizationError)
}
private func buildViewModel() -> LocationSharingViewModel {
let service = MockLocationSharingService()
return LocationSharingViewModel(mapStyleURL: URL(string: "http://empty.com")!,
avatarData: AvatarInput(mxContentUri: "", matrixItemId: "", displayName: ""), service: service)
}
}
@@ -1,210 +0,0 @@
//
// 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
struct LocationSharingMapView: UIViewRepresentable {
// MARK: - Constants
private struct Constants {
static let mapZoomLevel = 15.0
}
// MARK: - Properties
/// Map style URL (https://docs.mapbox.com/api/maps/styles/)
let tileServerMapURL: URL
/// Map annotations
let annotations: [LocationAnnotation]
/// Map annotation to focus on
let highlightedAnnotation: LocationAnnotation?
/// Current user avatar data, used to replace current location annotation view with the user avatar
let userAvatarData: AvatarInputProtocol?
/// True to indicate to show and follow current user location
var showsUserLocation: Bool = false
/// True to indicate that a touch on user annotation can show a callout
var userAnnotationCanShowCallout: Bool = false
/// Last user location if `showsUserLocation` has been enabled
@Binding var userLocation: CLLocationCoordinate2D?
/// Coordinate of the center of the map
@Binding var mapCenterCoordinate: CLLocationCoordinate2D?
/// Called when an annotation callout view is tapped
var onCalloutTap: ((MGLAnnotation) -> Void)?
/// Publish view errors if any
let errorSubject: PassthroughSubject<LocationSharingViewError, Never>
/// Called when the user pan on the map
var userDidPan: (() -> Void)?
// MARK: - UIViewRepresentable
func makeUIView(context: Context) -> MGLMapView {
let mapView = self.makeMapView()
mapView.delegate = context.coordinator
let panGesture = UIPanGestureRecognizer(target: context.coordinator, action: #selector(context.coordinator.didPan))
panGesture.delegate = context.coordinator
mapView.addGestureRecognizer(panGesture)
return mapView
}
func updateUIView(_ mapView: MGLMapView, context: Context) {
mapView.vc_removeAllAnnotations()
mapView.addAnnotations(self.annotations)
if let highlightedAnnotation = self.highlightedAnnotation {
mapView.setCenter(highlightedAnnotation.coordinate, zoomLevel: Constants.mapZoomLevel, animated: false)
}
if self.showsUserLocation {
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
} else {
mapView.showsUserLocation = false
mapView.userTrackingMode = .none
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// MARK: - Private
private func makeMapView() -> MGLMapView {
let mapView = MGLMapView(frame: .zero, styleURL: tileServerMapURL)
mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
return mapView
}
}
// MARK: - Coordinator
extension LocationSharingMapView {
class Coordinator: NSObject, MGLMapViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
var locationSharingMapView: LocationSharingMapView
// MARK: - Setup
init(_ locationSharingMapView: LocationSharingMapView) {
self.locationSharingMapView = locationSharingMapView
}
// MARK: - MGLMapViewDelegate
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
if let userLocationAnnotation = annotation as? UserLocationAnnotation {
return LocationAnnotationView(userLocationAnnotation: userLocationAnnotation)
} else if let pinLocationAnnotation = annotation as? PinLocationAnnotation {
return LocationAnnotationView(pinLocationAnnotation: pinLocationAnnotation)
} else if annotation is MGLUserLocation, let currentUserAvatarData = locationSharingMapView.userAvatarData {
// Replace default current location annotation view with a UserLocationAnnotatonView when the map is center on user location
return LocationAnnotationView(avatarData: currentUserAvatarData)
}
return nil
}
func mapViewDidFailLoadingMap(_ mapView: MGLMapView, withError error: Error) {
locationSharingMapView.errorSubject.send(.failedLoadingMap)
}
func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) {
locationSharingMapView.userLocation = userLocation?.coordinate
}
func mapView(_ mapView: MGLMapView, didChangeLocationManagerAuthorization manager: MGLLocationManager) {
guard mapView.showsUserLocation else {
return
}
switch manager.authorizationStatus {
case .restricted:
fallthrough
case .denied:
locationSharingMapView.errorSubject.send(.invalidLocationAuthorization)
default:
break
}
}
func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) {
locationSharingMapView.mapCenterCoordinate = mapView.centerCoordinate
}
// MARK: Callout
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return annotation is UserLocationAnnotation && locationSharingMapView.userAnnotationCanShowCallout
}
func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {
if let userLocationAnnotation = annotation as? UserLocationAnnotation {
return UserAnnotationCalloutView(userLocationAnnotation: userLocationAnnotation)
}
return nil
}
func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) {
locationSharingMapView.onCalloutTap?(annotation)
// Hide the callout
mapView.deselectAnnotation(annotation, animated: true)
}
// MARK: UIGestureRecognizer
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return gestureRecognizer is UIPanGestureRecognizer
}
@objc
func didPan() {
locationSharingMapView.userDidPan?()
}
}
}
// MARK: - MGLMapView convenient methods
extension MGLMapView {
func vc_removeAllAnnotations() {
guard let annotations = self.annotations else {
return
}
self.removeAnnotations(annotations)
}
}
@@ -1,63 +0,0 @@
//
// 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 LocationSharingMarkerView<Content: View>: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: Public
let backgroundColor: Color
@ViewBuilder var markerImage: Content
var body: some View {
ZStack {
Rectangle()
.rotation(Angle(degrees: 45))
.fill(backgroundColor)
.frame(width: 7, height: 7)
.offset(x: 0, y: 21)
markerImage
.frame(width: 40, height: 40)
}
}
}
// MARK: - Previews
struct LocationSharingUserMarkerView_Previews: PreviewProvider {
static var previews: some View {
let avatarData = AvatarInput(mxContentUri: "",
matrixItemId: "test",
displayName: "Alice")
VStack(alignment: .center, spacing: 15) {
LocationSharingMarkerView(backgroundColor: .green) {
AvatarImage(avatarData: avatarData, size: .medium)
.border()
}
LocationSharingMarkerView(backgroundColor: .green) {
AvatarImage(avatarData: avatarData, size: .medium)
.border()
}
}
}
}
@@ -1,67 +0,0 @@
//
// 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 SwiftUI
struct LocationSharingOptionButton<Content: View>: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
let text: String
let action: () -> (Void)
@ViewBuilder var buttonIcon: Content
var body: some View {
Button(action: action) {
HStack(spacing: 18) {
buttonIcon
.frame(width: 40, height: 40)
Text(text)
.font(theme.fonts.body)
.foregroundColor(theme.colors.primaryContent)
}
}
}
}
struct LocationSharingOptionButton_Previews: PreviewProvider {
static var previews: some View {
VStack(alignment: .leading) {
LocationSharingOptionButton(text: VectorL10n.locationSharingStaticShareTitle) {
} buttonIcon: {
AvatarImage(avatarData: AvatarInput(mxContentUri: nil, matrixItemId: "Alice", displayName: "Alice"), size: .medium)
.border()
}
LocationSharingOptionButton(text: VectorL10n.locationSharingLiveShareTitle) {
} buttonIcon: {
Image(uiImage: Asset.Images.locationLiveIcon.image)
.resizable()
}
LocationSharingOptionButton(text: VectorL10n.locationSharingPinDropShareTitle) {
} buttonIcon: {
Image(uiImage: Asset.Images.locationPinIcon.image)
.resizable()
}
}
}
}
@@ -1,196 +0,0 @@
//
// 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 CoreLocation
struct LocationSharingView: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
@Environment(\.openURL) var openURL
// MARK: Public
@ObservedObject var context: LocationSharingViewModel.Context
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
if !context.viewState.showMapLoadingError {
mapView
}
VStack(spacing: 0) {
if context.viewState.showMapLoadingError {
MapLoadingErrorView()
} else {
// Show map credits only if map is visible
MapCreditsView(action: {
context.send(viewAction: .mapCreditsDidTap)
})
.padding(.bottom, 10.0)
.actionSheet(isPresented: $context.showMapCreditsSheet) {
return MapCreditsActionSheet(openURL: { url in
openURL(url)
}).sheet
}
}
buttonsView
.background(theme.colors.background)
.clipShape(RoundedCornerShape(radius: 8, corners: [.topLeft, .topRight]))
}
}
.background(theme.colors.background.ignoresSafeArea())
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(VectorL10n.cancel, action: {
context.send(viewAction: .cancel)
})
}
ToolbarItem(placement: .principal) {
Text(VectorL10n.locationSharingTitle)
.font(.headline)
.foregroundColor(theme.colors.primaryContent)
}
}
.navigationBarTitleDisplayMode(.inline)
.introspectNavigationController { navigationController in
ThemeService.shared().theme.applyStyle(onNavigationBar: navigationController.navigationBar)
}
.alert(item: $context.alertInfo) { info in
info.alert
}
}
.accentColor(theme.colors.accent)
.activityIndicator(show: context.viewState.showLoadingIndicator)
.navigationViewStyle(StackNavigationViewStyle())
}
var mapView: some View {
ZStack(alignment: .topTrailing) {
ZStack(alignment: .center) {
LocationSharingMapView(tileServerMapURL: context.viewState.mapStyleURL,
annotations: context.viewState.annotations,
highlightedAnnotation: context.viewState.highlightedAnnotation,
userAvatarData: context.viewState.userAvatarData,
showsUserLocation: context.viewState.showsUserLocation,
userLocation: $context.userLocation,
mapCenterCoordinate: $context.pinLocation,
errorSubject: context.viewState.errorSubject,
userDidPan: {
context.send(viewAction: .userDidPan)
})
if context.viewState.isPinDropSharing {
LocationSharingMarkerView(backgroundColor: theme.colors.accent) {
Image(uiImage: Asset.Images.locationPinIcon.image)
.resizable()
.shapedBorder(color: theme.colors.accent, borderWidth: 3, shape: Circle())
}
}
}
Button {
context.send(viewAction: .goToUserLocation)
} label: {
Image(uiImage: Asset.Images.locationCenterMapIcon.image)
.foregroundColor(theme.colors.accent)
}
.padding(6.0)
.background(theme.colors.background)
.clipShape(RoundedCornerShape(radius: 4, corners: [.allCorners]))
.shadow(radius: 2.0)
.offset(x: -11.0, y: 52)
}
}
var buttonsView: some View {
VStack(alignment: .leading, spacing: 15) {
if !context.viewState.isPinDropSharing {
LocationSharingOptionButton(text: VectorL10n.locationSharingStaticShareTitle) {
context.send(viewAction: .share)
} buttonIcon: {
AvatarImage(avatarData: context.viewState.userAvatarData, size: .medium)
.border()
}
.disabled(!context.viewState.shareButtonEnabled)
// Hide for now until live location sharing is finished
if context.viewState.isLiveLocationSharingEnabled {
LocationSharingOptionButton(text: VectorL10n.locationSharingLiveShareTitle) {
context.send(viewAction: .startLiveSharing)
} buttonIcon: {
Image(uiImage: Asset.Images.locationLiveIcon.image)
.resizable()
}
.disabled(!context.viewState.shareButtonEnabled)
}
} else {
LocationSharingOptionButton(text: VectorL10n.locationSharingPinDropShareTitle) {
context.send(viewAction: .sharePinLocation)
} buttonIcon: {
Image(uiImage: Asset.Images.locationPinIcon.image)
.resizable()
}
.disabled(!context.viewState.shareButtonEnabled)
}
}
.actionSheet(isPresented: $context.showingTimerSelector) {
ActionSheet(title: Text(VectorL10n.locationSharingLiveTimerSelectorTitle),
buttons: [
.default(Text(VectorL10n.locationSharingLiveTimerSelectorShort)) {
context.send(viewAction: .shareLiveLocation(timeout: .short))
},
.default(Text(VectorL10n.locationSharingLiveTimerSelectorMedium)) {
context.send(viewAction: .shareLiveLocation(timeout: .medium))
},
.default(Text(VectorL10n.locationSharingLiveTimerSelectorLong)) {
context.send(viewAction: .shareLiveLocation(timeout: .long))
},
.cancel()
])
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
@ViewBuilder
private var activityIndicator: some View {
if context.viewState.showLoadingIndicator {
ActivityIndicator()
}
}
}
// MARK: - Previews
struct LocationSharingView_Previews: PreviewProvider {
static let stateRenderer = MockLocationSharingScreenState.stateRenderer
static var previews: some View {
Group {
stateRenderer.screenGroup().theme(.light).preferredColorScheme(.light)
stateRenderer.screenGroup().theme(.dark).preferredColorScheme(.dark)
}
}
}
@@ -1,50 +0,0 @@
//
// 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 MapCreditsView: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: Public
var action: (() -> Void)?
var body: some View {
HStack {
Spacer()
Button {
action?()
} label: {
Text(VectorL10n.locationSharingMapCreditsTitle)
.font(theme.fonts.footnote)
.foregroundColor(theme.colors.accent)
}
.padding(.horizontal)
}
}
}
struct MapCreditsView_Previews: PreviewProvider {
static var previews: some View {
MapCreditsView()
}
}
@@ -1,52 +0,0 @@
//
// 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 SwiftUI
struct MapLoadingErrorView: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: Public
var action: (() -> Void)?
var body: some View {
VStack {
VStack {
Image(uiImage: Asset.Images.locationMapError.image)
.frame(width: 40, height: 40)
Text(VectorL10n.locationSharingMapLoadingError)
.multilineTextAlignment(.center)
.font(theme.fonts.caption1)
.foregroundColor(theme.colors.primaryContent)
}
.padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(theme.colors.system.ignoresSafeArea())
}
}
struct MapLoadingErrorView_Previews: PreviewProvider {
static var previews: some View {
MapLoadingErrorView()
}
}
@@ -1,85 +0,0 @@
//
// 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
import Reusable
class UserAnnotationCalloutContentView: UIView, Themable, NibLoadable {
// MARK: - Constants
private static let sizingView = UserAnnotationCalloutContentView.instantiate()
private enum Constants {
static let height: CGFloat = 44.0
static let cornerRadius: CGFloat = 8.0
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet var backgroundView: UIView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var shareButton: UIButton!
// MARK: - Setup
static func instantiate() -> UserAnnotationCalloutContentView {
return UserAnnotationCalloutContentView.loadFromNib()
}
// MARK: - Public
func update(theme: Theme) {
self.backgroundView.backgroundColor = theme.colors.background
self.titleLabel.textColor = theme.colors.secondaryContent
self.titleLabel.font = theme.fonts.callout
self.shareButton.tintColor = theme.colors.secondaryContent
}
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
self.titleLabel.text = VectorL10n.locationSharingLiveMapCalloutTitle
self.backgroundView.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundView.layer.cornerRadius = Constants.cornerRadius
}
static func contentViewSize() -> CGSize {
let sizingView = self.sizingView
sizingView.frame = CGRect(x: 0, y: 0, width: 1, height: Constants.height)
sizingView.setNeedsLayout()
sizingView.layoutIfNeeded()
let fittingSize = CGSize(width: UIView.layoutFittingCompressedSize.width, height: Constants.height)
let size = sizingView.systemLayoutSizeFitting(fittingSize,
withHorizontalFittingPriority: .fittingSizeLevel,
verticalFittingPriority: .required)
return size
}
}
@@ -1,65 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="20037" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="20020"/>
<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"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB" customClass="UserAnnotationCalloutContentView" customModule="Riot" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="222" height="62"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="WEX-LH-zYE">
<rect key="frame" x="0.0" y="0.0" width="222" height="62"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
</view>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8qV-yr-fDH">
<rect key="frame" x="10" y="0.0" width="173" height="62"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="252" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Htx-uD-cf2">
<rect key="frame" x="188" y="0.0" width="24" height="62"/>
<inset key="imageEdgeInsets" minX="0.0" minY="0.0" maxX="2.2250738585072014e-308" maxY="0.0"/>
<state key="normal" image="share_action_button"/>
</button>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstAttribute="trailing" secondItem="WEX-LH-zYE" secondAttribute="trailing" id="3Rb-Vi-QNG"/>
<constraint firstItem="Htx-uD-cf2" firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="WEX-LH-zYE" secondAttribute="bottom" id="8oX-y9-FA8"/>
<constraint firstItem="8qV-yr-fDH" firstAttribute="top" secondItem="WEX-LH-zYE" secondAttribute="top" id="Cqh-a4-3xH"/>
<constraint firstItem="WEX-LH-zYE" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" id="Glo-Kv-b9P"/>
<constraint firstAttribute="bottom" secondItem="WEX-LH-zYE" secondAttribute="bottom" id="TVK-pw-MQi"/>
<constraint firstItem="Htx-uD-cf2" firstAttribute="centerY" secondItem="8qV-yr-fDH" secondAttribute="centerY" id="VLm-I1-Xa5"/>
<constraint firstItem="Htx-uD-cf2" firstAttribute="leading" secondItem="8qV-yr-fDH" secondAttribute="trailing" constant="5" id="aNO-Wu-hrO"/>
<constraint firstItem="Htx-uD-cf2" firstAttribute="trailing" secondItem="WEX-LH-zYE" secondAttribute="trailing" constant="-10" id="eB7-OT-FSZ"/>
<constraint firstItem="Htx-uD-cf2" firstAttribute="top" relation="greaterThanOrEqual" secondItem="WEX-LH-zYE" secondAttribute="top" id="gsk-Ld-Ahq"/>
<constraint firstItem="WEX-LH-zYE" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="kVf-HO-jBq"/>
<constraint firstItem="8qV-yr-fDH" firstAttribute="leading" secondItem="WEX-LH-zYE" secondAttribute="leading" constant="10" id="nDk-Sm-zM4"/>
<constraint firstItem="8qV-yr-fDH" firstAttribute="bottom" secondItem="WEX-LH-zYE" secondAttribute="bottom" id="ypH-Wk-ly7"/>
</constraints>
<nil key="simulatedTopBarMetrics"/>
<nil key="simulatedBottomBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<connections>
<outlet property="backgroundView" destination="WEX-LH-zYE" id="G7V-Kl-xz0"/>
<outlet property="shareButton" destination="Htx-uD-cf2" id="crB-EP-vHO"/>
<outlet property="titleLabel" destination="8qV-yr-fDH" id="9o1-jU-nR6"/>
</connections>
<point key="canvasLocation" x="-7.2463768115942031" y="-193.52678571428569"/>
</view>
</objects>
<resources>
<image name="share_action_button" width="24" height="24"/>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
@@ -1,156 +0,0 @@
//
// 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 Mapbox
class UserAnnotationCalloutView: UIView, MGLCalloutView, Themable {
// MARK: - Constants
private enum Constants {
static let animationDuration: TimeInterval = 0.2
static let bottomMargin: CGFloat = 3.0
}
// MARK: - Properties
// MARK: Overrides
var representedObject: MGLAnnotation
lazy var leftAccessoryView: UIView = UIView()
lazy var rightAccessoryView: UIView = UIView()
var delegate: MGLCalloutViewDelegate?
// Allow the callout to remain open during panning.
let dismissesAutomatically: Bool = false
let isAnchoredToAnnotation: Bool = true
// https://github.com/mapbox/mapbox-gl-native/issues/9228
override var center: CGPoint {
set {
var newCenter = newValue
newCenter.y -= bounds.midY + Constants.bottomMargin
super.center = newCenter
}
get {
return super.center
}
}
// MARK: Private
lazy var contentView: UserAnnotationCalloutContentView = {
return UserAnnotationCalloutContentView.instantiate()
}()
// MARK: - Setup
required init(userLocationAnnotation: UserLocationAnnotation) {
self.representedObject = userLocationAnnotation
super.init(frame: .zero)
self.vc_addSubViewMatchingParent(self.contentView)
self.update(theme: ThemeService.shared().theme)
let size = UserAnnotationCalloutContentView.contentViewSize()
self.frame = CGRect(origin: .zero, size: size)
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Public
func update(theme: Theme) {
self.contentView.update(theme: theme)
}
// MARK: - Overrides
func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {
// Set callout above the marker view
self.center = view.center.applying(CGAffineTransform(translationX: 0, y: view.bounds.height/2 + self.bounds.height))
delegate?.calloutViewWillAppear?(self)
view.addSubview(self)
if isCalloutTappable() {
// Handle taps and eventually try to send them to the delegate (usually the map view).
self.contentView.shareButton.addTarget(self, action: #selector(UserAnnotationCalloutView.calloutTapped), for: .touchUpInside)
} else {
// Disable tapping and highlighting.
self.contentView.shareButton.isUserInteractionEnabled = false
}
if animated {
alpha = 0
UIView.animate(withDuration: Constants.animationDuration) { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.alpha = 1
strongSelf.delegate?.calloutViewDidAppear?(strongSelf)
}
} else {
delegate?.calloutViewDidAppear?(self)
}
}
func dismissCallout(animated: Bool) {
if (superview != nil) {
if animated {
UIView.animate(withDuration: Constants.animationDuration, animations: { [weak self] in
self?.alpha = 0
}, completion: { [weak self] _ in
self?.removeFromSuperview()
})
} else {
removeFromSuperview()
}
}
}
// MARK: - Callout interaction handlers
func isCalloutTappable() -> Bool {
if let delegate = delegate {
if delegate.responds(to: #selector(MGLCalloutViewDelegate.calloutViewShouldHighlight)) {
return delegate.calloutViewShouldHighlight!(self)
}
}
return false
}
@objc func calloutTapped() {
if isCalloutTappable() && delegate!.responds(to: #selector(MGLCalloutViewDelegate.calloutViewTapped)) {
delegate!.calloutViewTapped!(self)
}
}
}
@@ -1,100 +0,0 @@
//
// 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
import Mapbox
class LocationAnnotationView: MGLUserLocationAnnotationView {
// MARK: - Constants
private enum Constants {
static let defaultFrame = CGRect(x: 0, y: 0, width: 46, height: 46)
}
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: - Setup
override init(annotation: MGLAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier:
reuseIdentifier)
self.frame = Constants.defaultFrame
}
convenience init(avatarData: AvatarInputProtocol) {
self.init(annotation: nil, reuseIdentifier: nil)
self.addUserMarkerView(with: avatarData)
}
convenience init(userLocationAnnotation: UserLocationAnnotation) {
// TODO: Use a reuseIdentifier
self.init(annotation: userLocationAnnotation, reuseIdentifier: nil)
self.addUserMarkerView(with: userLocationAnnotation.avatarData)
}
convenience init(pinLocationAnnotation: PinLocationAnnotation) {
// TODO: Use a reuseIdentifier
self.init(annotation: pinLocationAnnotation, reuseIdentifier: nil)
self.addPinMarkerView()
}
required init?(coder: NSCoder) {
fatalError()
}
// MARK: - Private
private func addUserMarkerView(with avatarData: AvatarInputProtocol) {
guard let avatarMarkerView = UIHostingController(rootView: LocationSharingMarkerView(backgroundColor: theme.userColor(for: avatarData.matrixItemId)) {
AvatarImage(avatarData: avatarData, size: .medium)
.border()
}).view else {
return
}
addMarkerView(avatarMarkerView)
}
private func addPinMarkerView() {
guard let pinMarkerView = UIHostingController(rootView: LocationSharingMarkerView(backgroundColor: theme.colors.accent) {
Image(uiImage: Asset.Images.locationPinIcon.image)
.resizable()
.shapedBorder(color: theme.colors.accent, borderWidth: 3, shape: Circle())
}).view else {
return
}
addMarkerView(pinMarkerView)
}
private func addMarkerView(_ markerView: UIView) {
markerView.backgroundColor = .clear
addSubview(markerView)
markerView.frame = self.bounds
}
}
@@ -1,89 +0,0 @@
//
// 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
import SwiftUI
import MatrixSDK
struct StaticLocationViewingCoordinatorParameters {
let session: MXSession
let mediaManager: MXMediaManager
let avatarData: AvatarInputProtocol
let location: CLLocationCoordinate2D
let coordinateType: LocationSharingCoordinateType
}
final class StaticLocationViewingCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: StaticLocationViewingCoordinatorParameters
private let staticLocationViewingHostingController: UIViewController
private var staticLocationViewingViewModel: StaticLocationViewingViewModelProtocol
private let shareLocationActivityControllerBuilder = ShareLocationActivityControllerBuilder()
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var completion: (() -> Void)?
// MARK: - Setup
init(parameters: StaticLocationViewingCoordinatorParameters) {
self.parameters = parameters
let viewModel = StaticLocationViewingViewModel(
mapStyleURL: parameters.session.vc_homeserverConfiguration().tileServer.mapStyleURL,
avatarData: parameters.avatarData,
location: parameters.location,
coordinateType: parameters.coordinateType)
let view = StaticLocationView(viewModel: viewModel.context)
.addDependency(AvatarService.instantiate(mediaManager: parameters.mediaManager))
staticLocationViewingViewModel = viewModel
staticLocationViewingHostingController = VectorHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[StaticLocationSharingViewerCoordinator] did start.")
staticLocationViewingViewModel.completion = { [weak self] result in
guard let self = self else { return }
MXLog.debug("[StaticLocationSharingViewerCoordinator] StaticLocationSharingViewerViewModel did complete with result: \(result).")
switch result {
case .close:
self.completion?()
case .share(let coordinate):
self.presentLocationActivityController(with: coordinate)
}
}
}
func toPresentable() -> UIViewController {
return self.staticLocationViewingHostingController
}
func presentLocationActivityController(with coordinate: CLLocationCoordinate2D) {
let shareActivityController = shareLocationActivityControllerBuilder.build(with: coordinate)
self.staticLocationViewingHostingController.present(shareActivityController, animated: true)
}
}
@@ -1,56 +0,0 @@
//
// 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
import CoreLocation
/// Using an enum for the screen allows you define the different state cases with
/// the relevant associated data for each case.
enum MockStaticLocationViewingScreenState: MockScreenState, CaseIterable {
// A case for each state you want to represent
// with specific, minimal associated data that will allow you
// mock that screen.
case showUserLocation
case showPinLocation
/// The associated screen
var screenType: Any.Type {
StaticLocationView.self
}
/// A list of screen state definitions
static var allCases: [MockStaticLocationViewingScreenState] {
return [.showUserLocation, .showPinLocation]
}
/// Generate the view struct for the screen state.
var screenView: ([Any], AnyView) {
let location = CLLocationCoordinate2D(latitude: 51.4932641, longitude: -0.257096)
let coordinateType: LocationSharingCoordinateType = self == .showUserLocation ? .user : .pin
let mapStyleURL = URL(string: "https://api.maptiler.com/maps/streets/style.json?key=fU3vlMsMn4Jb6dnEIFsx")!
let viewModel = StaticLocationViewingViewModel(mapStyleURL: mapStyleURL,
avatarData: AvatarInput(mxContentUri: "", matrixItemId: "alice:matrix.org", displayName: "Alice"),
location: location,
coordinateType: coordinateType)
return ([viewModel],
AnyView(StaticLocationView(viewModel: viewModel.context)
.addDependency(MockAvatarService.example))
)
}
}
@@ -1,59 +0,0 @@
//
// 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: View model
enum StaticLocationViewingViewAction {
case close
case share
}
enum StaticLocationViewingViewModelResult {
case close
case share(_ coordinate: CLLocationCoordinate2D)
}
// MARK: View
struct StaticLocationViewingViewState: BindableState {
/// Map style URL
let mapStyleURL: URL
/// Current user avatarData
let userAvatarData: AvatarInputProtocol
/// Shared annotation to display existing location
let sharedAnnotation: LocationAnnotation
var showLoadingIndicator: Bool = false
var shareButtonEnabled: Bool {
!showLoadingIndicator
}
let errorSubject = PassthroughSubject<LocationSharingViewError, Never>()
var bindings = StaticLocationViewingViewBindings()
}
struct StaticLocationViewingViewBindings {
var alertInfo: AlertInfo<LocationSharingAlertType>?
}
@@ -1,94 +0,0 @@
//
// 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 CoreLocation
typealias StaticLocationViewingViewModelType = StateStoreViewModel<StaticLocationViewingViewState,
Never,
StaticLocationViewingViewAction>
class StaticLocationViewingViewModel: StaticLocationViewingViewModelType, StaticLocationViewingViewModelProtocol {
// MARK: - Properties
// MARK: Private
private var mapViewErrorAlertInfoBuilder: MapViewErrorAlertInfoBuilder
// MARK: Public
var completion: ((StaticLocationViewingViewModelResult) -> Void)?
// MARK: - Setup
init(mapStyleURL: URL, avatarData: AvatarInputProtocol, location: CLLocationCoordinate2D, coordinateType: LocationSharingCoordinateType) {
let sharedAnnotation: LocationAnnotation
switch coordinateType {
case .user:
sharedAnnotation = UserLocationAnnotation(avatarData: avatarData, coordinate: location)
case .pin:
sharedAnnotation = PinLocationAnnotation(coordinate: location)
}
let viewState = StaticLocationViewingViewState(mapStyleURL: mapStyleURL,
userAvatarData: avatarData,
sharedAnnotation: sharedAnnotation)
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)
}
// MARK: - Public
override func process(viewAction: StaticLocationViewingViewAction) {
switch viewAction {
case .close:
completion?(.close)
case .share:
completion?(.share(state.sharedAnnotation.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?(.close)
}
default:
self?.completion?(.close)
}
}
state.bindings.alertInfo = alertInfo
}
}
@@ -1,23 +0,0 @@
//
// 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 StaticLocationViewingViewModelProtocol {
var completion: ((StaticLocationViewingViewModelResult) -> Void)? { get set }
var context: StaticLocationViewingViewModelType.Context { get }
}
@@ -1,22 +0,0 @@
//
// 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
class StaticLocationViewingUITests: MockScreenTestCase {
// This test has issues running consistently on CI. Removed for now until the issue has been fixed.
}
@@ -1,89 +0,0 @@
//
// 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
import CoreLocation
@testable import RiotSwiftUI
class StaticLocationViewingViewModelTests: XCTestCase {
var cancellables = Set<AnyCancellable>()
func testInitialState() {
let viewModel = buildViewModel()
XCTAssertTrue(viewModel.context.viewState.shareButtonEnabled)
XCTAssertFalse(viewModel.context.viewState.showLoadingIndicator)
XCTAssertNotNil(viewModel.context.viewState.mapStyleURL)
XCTAssertNotNil(viewModel.context.viewState.userAvatarData)
XCTAssertNil(viewModel.context.viewState.bindings.alertInfo)
}
func testCancellation() {
let viewModel = buildViewModel()
let expectation = self.expectation(description: "Cancellation completion should be invoked")
viewModel.completion = { result in
switch result {
case .share:
XCTFail()
case .close:
expectation.fulfill()
}
}
viewModel.context.send(viewAction: .close)
waitForExpectations(timeout: 3)
}
func testShareExistingLocation() {
let viewModel = buildViewModel()
let expectation = self.expectation(description: "Share completion should be invoked")
viewModel.completion = { result in
switch result {
case .share(let coordinate):
XCTAssertEqual(coordinate.latitude, viewModel.context.viewState.sharedAnnotation.coordinate.latitude)
XCTAssertEqual(coordinate.longitude, viewModel.context.viewState.sharedAnnotation.coordinate.longitude)
expectation.fulfill()
case .close:
XCTFail()
}
}
XCTAssertNotNil(viewModel.context.viewState.sharedAnnotation)
viewModel.context.send(viewAction: .share)
XCTAssertNil(viewModel.context.viewState.bindings.alertInfo)
waitForExpectations(timeout: 3)
}
private func buildViewModel() -> StaticLocationViewingViewModel {
StaticLocationViewingViewModel(mapStyleURL: URL(string: "http://empty.com")!,
avatarData: AvatarInput(mxContentUri: "", matrixItemId: "", displayName: ""),
location: CLLocationCoordinate2D(latitude: 51.4932641, longitude: -0.257096),
coordinateType: .user)
}
}
@@ -1,96 +0,0 @@
//
// 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 StaticLocationView: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme
// MARK: Public
@ObservedObject var viewModel: StaticLocationViewingViewModel.Context
// MARK: Views
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
LocationSharingMapView(tileServerMapURL: viewModel.viewState.mapStyleURL,
annotations: [viewModel.viewState.sharedAnnotation],
highlightedAnnotation: viewModel.viewState.sharedAnnotation,
userAvatarData: viewModel.viewState.userAvatarData,
showsUserLocation: false,
userLocation: Binding.constant(nil),
mapCenterCoordinate: Binding.constant(nil),
errorSubject: viewModel.viewState.errorSubject)
MapCreditsView()
}
.ignoresSafeArea(.all, edges: [.bottom])
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(VectorL10n.cancel, action: {
viewModel.send(viewAction: .close)
})
}
ToolbarItem(placement: .principal) {
Text(VectorL10n.locationSharingTitle)
.font(.headline)
.foregroundColor(theme.colors.primaryContent)
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
viewModel.send(viewAction: .share)
} label: {
Image(uiImage: Asset.Images.locationShareIcon.image)
}
.disabled(!viewModel.viewState.shareButtonEnabled)
.accessibilityIdentifier("shareButton")
}
}
.navigationBarTitleDisplayMode(.inline)
.introspectNavigationController { navigationController in
ThemeService.shared().theme.applyStyle(onNavigationBar: navigationController.navigationBar)
}
.alert(item: $viewModel.alertInfo) { info in
info.alert
}
}
.accentColor(theme.colors.accent)
.activityIndicator(show: viewModel.viewState.showLoadingIndicator)
.navigationViewStyle(StackNavigationViewStyle())
}
@ViewBuilder
private var activityIndicator: some View {
if viewModel.viewState.showLoadingIndicator {
ActivityIndicator()
}
}
}
// MARK: - Previews
struct StaticLocationSharingViewer_Previews: PreviewProvider {
static let stateRenderer = MockStaticLocationViewingScreenState.stateRenderer
static var previews: some View {
stateRenderer.screenGroup()
}
}