From 8d4f6f301b190e61ff00941af29f1f73b62683b0 Mon Sep 17 00:00:00 2001 From: Stefan Ceriu Date: Thu, 10 Mar 2022 16:45:34 +0200 Subject: [PATCH] Better timeline handling, based on improved rust APIs. --- ElementX.xcodeproj/project.pbxproj | 57 +++++-- .../HomeScreen/HomeScreenViewModel.swift | 3 +- .../Screens/RoomScreen/RoomScreenModels.swift | 2 - .../RoomScreen/RoomScreenViewModel.swift | 2 - .../Screens/RoomScreen/View/RoomScreen.swift | 154 +++++++++++++++--- ElementX/Sources/Services/MockRoomProxy.swift | 3 +- ElementX/Sources/Services/RoomProxy.swift | 51 ++++-- .../Sources/Services/RoomProxyProtocol.swift | 4 +- .../Timeline/RoomTimelineProvider.swift | 23 +-- .../RoomTimelineItemProtocol.swift | 0 .../TextRoomTimelineItem.swift | 0 11 files changed, 219 insertions(+), 80 deletions(-) rename ElementX/Sources/Services/Timeline/{ => TimelineItems}/RoomTimelineItemProtocol.swift (100%) rename ElementX/Sources/Services/Timeline/{ => TimelineItems}/TextRoomTimelineItem.swift (100%) diff --git a/ElementX.xcodeproj/project.pbxproj b/ElementX.xcodeproj/project.pbxproj index e65ebed6d..5de0497aa 100644 --- a/ElementX.xcodeproj/project.pbxproj +++ b/ElementX.xcodeproj/project.pbxproj @@ -8,16 +8,19 @@ /* Begin PBXBuildFile section */ 182BC48127C4EBBB00A30C33 /* Kingfisher in Frameworks */ = {isa = PBXBuildFile; productRef = 182BC48027C4EBBB00A30C33 /* Kingfisher */; }; + 184B31DF27D898960075A669 /* Introspect in Frameworks */ = {isa = PBXBuildFile; productRef = 184B31DE27D898960075A669 /* Introspect */; }; 1850253F27B6918D002E6B18 /* ElementXTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1850253E27B6918D002E6B18 /* ElementXTests.swift */; }; 1850254927B6918D002E6B18 /* ElementXUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1850254827B6918D002E6B18 /* ElementXUITests.swift */; }; 1850254B27B6918D002E6B18 /* ElementXUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1850254A27B6918D002E6B18 /* ElementXUITestsLaunchTests.swift */; }; - 1850255927B69388002E6B18 /* MatrixRustSDK in Frameworks */ = {isa = PBXBuildFile; productRef = 1850255827B69388002E6B18 /* MatrixRustSDK */; }; 1850256C27B6A135002E6B18 /* AppCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1850256227B6A135002E6B18 /* AppCoordinator.swift */; }; 1850256F27B6A135002E6B18 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1850256527B6A135002E6B18 /* AppDelegate.swift */; }; 1850257027B6A135002E6B18 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 1850256827B6A135002E6B18 /* Assets.xcassets */; }; 1850257127B6A135002E6B18 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 1850256927B6A135002E6B18 /* LaunchScreen.storyboard */; }; + 1859CF5527D7A6FF00E86E4E /* MatrixRustSDK in Frameworks */ = {isa = PBXBuildFile; productRef = 1859CF5427D7A6FF00E86E4E /* MatrixRustSDK */; }; 1863A3FC27BA5A9100B52E4D /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = 1863A3FB27BA5A9100B52E4D /* KeychainAccess */; }; 1863A40627BA6DFC00B52E4D /* SwiftyBeaver in Frameworks */ = {isa = PBXBuildFile; productRef = 1863A40527BA6DFC00B52E4D /* SwiftyBeaver */; }; + 18A318DC27DA42C9000867CD /* RoomTimelineItemProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18A318DA27DA42C9000867CD /* RoomTimelineItemProtocol.swift */; }; + 18A318DD27DA42C9000867CD /* TextRoomTimelineItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18A318DB27DA42C9000867CD /* TextRoomTimelineItem.swift */; }; 18F2BAD727D25B4000DD1988 /* RoomProxyProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BA7327D25B4000DD1988 /* RoomProxyProtocol.swift */; }; 18F2BAD827D25B4000DD1988 /* RoomProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BA7427D25B4000DD1988 /* RoomProxy.swift */; }; 18F2BAD927D25B4000DD1988 /* MockRoomProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BA7527D25B4000DD1988 /* MockRoomProxy.swift */; }; @@ -76,8 +79,6 @@ 18F2BB2027D25D3400DD1988 /* RoomScreenUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BAC127D25B4000DD1988 /* RoomScreenUITests.swift */; }; 18F2BB2127D25D3C00DD1988 /* HomeScreenUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BAA727D25B4000DD1988 /* HomeScreenUITests.swift */; }; 18F2BB2227D25D4600DD1988 /* LoginScreenUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BACF27D25B4000DD1988 /* LoginScreenUITests.swift */; }; - 18F2BB2427D262A900DD1988 /* RoomTimelineItemProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BB2327D262A900DD1988 /* RoomTimelineItemProtocol.swift */; }; - 18F2BB2627D262FA00DD1988 /* TextRoomTimelineItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BB2527D262FA00DD1988 /* TextRoomTimelineItem.swift */; }; 18F2BB2827D2647A00DD1988 /* MockRoomTimelineController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BB2727D2647A00DD1988 /* MockRoomTimelineController.swift */; }; 18F2BB2A27D2648900DD1988 /* RoomTimelineControllerProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F2BB2927D2648900DD1988 /* RoomTimelineControllerProtocol.swift */; }; /* End PBXBuildFile section */ @@ -111,6 +112,9 @@ 1850256727B6A135002E6B18 /* ElementX.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = ElementX.entitlements; sourceTree = ""; }; 1850256827B6A135002E6B18 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 1850256A27B6A135002E6B18 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 18A318D827D9E7AD000867CD /* matrix-rust-components-swift */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = "matrix-rust-components-swift"; path = "../matrix-rust-components-swift"; sourceTree = ""; }; + 18A318DA27DA42C9000867CD /* RoomTimelineItemProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RoomTimelineItemProtocol.swift; sourceTree = ""; }; + 18A318DB27DA42C9000867CD /* TextRoomTimelineItem.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TextRoomTimelineItem.swift; sourceTree = ""; }; 18F2BA7327D25B4000DD1988 /* RoomProxyProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RoomProxyProtocol.swift; sourceTree = ""; }; 18F2BA7427D25B4000DD1988 /* RoomProxy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RoomProxy.swift; sourceTree = ""; }; 18F2BA7527D25B4000DD1988 /* MockRoomProxy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockRoomProxy.swift; sourceTree = ""; }; @@ -169,8 +173,6 @@ 18F2BAD427D25B4000DD1988 /* LoginScreenCoordinator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginScreenCoordinator.swift; sourceTree = ""; }; 18F2BAD627D25B4000DD1988 /* LoginScreen.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginScreen.swift; sourceTree = ""; }; 18F2BB1927D25BE800DD1988 /* RoomTimelineController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomTimelineController.swift; sourceTree = ""; }; - 18F2BB2327D262A900DD1988 /* RoomTimelineItemProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomTimelineItemProtocol.swift; sourceTree = ""; }; - 18F2BB2527D262FA00DD1988 /* TextRoomTimelineItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextRoomTimelineItem.swift; sourceTree = ""; }; 18F2BB2727D2647A00DD1988 /* MockRoomTimelineController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockRoomTimelineController.swift; sourceTree = ""; }; 18F2BB2927D2648900DD1988 /* RoomTimelineControllerProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoomTimelineControllerProtocol.swift; sourceTree = ""; }; 18FE279627C7B85300016375 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -183,7 +185,8 @@ files = ( 182BC48127C4EBBB00A30C33 /* Kingfisher in Frameworks */, 1863A3FC27BA5A9100B52E4D /* KeychainAccess in Frameworks */, - 1850255927B69388002E6B18 /* MatrixRustSDK in Frameworks */, + 184B31DF27D898960075A669 /* Introspect in Frameworks */, + 1859CF5527D7A6FF00E86E4E /* MatrixRustSDK in Frameworks */, 1863A40627BA6DFC00B52E4D /* SwiftyBeaver in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -208,6 +211,7 @@ 1850251B27B6918C002E6B18 = { isa = PBXGroup; children = ( + 18A318D827D9E7AD000867CD /* matrix-rust-components-swift */, 1850252627B6918C002E6B18 /* ElementX */, 1850253D27B6918D002E6B18 /* ElementXTests */, 1850254727B6918D002E6B18 /* ElementXUITests */, @@ -274,6 +278,15 @@ path = "Supporting Files"; sourceTree = ""; }; + 18A318D927DA42C9000867CD /* TimelineItems */ = { + isa = PBXGroup; + children = ( + 18A318DA27DA42C9000867CD /* RoomTimelineItemProtocol.swift */, + 18A318DB27DA42C9000867CD /* TextRoomTimelineItem.swift */, + ); + path = TimelineItems; + sourceTree = ""; + }; 18F2BA7227D25B4000DD1988 /* Services */ = { isa = PBXGroup; children = ( @@ -293,8 +306,7 @@ 18F2BB1927D25BE800DD1988 /* RoomTimelineController.swift */, 18F2BB2727D2647A00DD1988 /* MockRoomTimelineController.swift */, 18F2BA7727D25B4000DD1988 /* RoomTimelineProvider.swift */, - 18F2BB2327D262A900DD1988 /* RoomTimelineItemProtocol.swift */, - 18F2BB2527D262FA00DD1988 /* TextRoomTimelineItem.swift */, + 18A318D927DA42C9000867CD /* TimelineItems */, ); path = Timeline; sourceTree = ""; @@ -575,10 +587,11 @@ ); name = ElementX; packageProductDependencies = ( - 1850255827B69388002E6B18 /* MatrixRustSDK */, 1863A3FB27BA5A9100B52E4D /* KeychainAccess */, 1863A40527BA6DFC00B52E4D /* SwiftyBeaver */, 182BC48027C4EBBB00A30C33 /* Kingfisher */, + 1859CF5427D7A6FF00E86E4E /* MatrixRustSDK */, + 184B31DE27D898960075A669 /* Introspect */, ); productName = ElementX; productReference = 1850252427B6918C002E6B18 /* ElementX.app */; @@ -654,10 +667,11 @@ ); mainGroup = 1850251B27B6918C002E6B18; packageReferences = ( - 1850255727B69388002E6B18 /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */, 1863A3FA27BA5A9100B52E4D /* XCRemoteSwiftPackageReference "KeychainAccess" */, 1863A40427BA6DFC00B52E4D /* XCRemoteSwiftPackageReference "SwiftyBeaver" */, 182BC47F27C4EBBB00A30C33 /* XCRemoteSwiftPackageReference "Kingfisher" */, + 1859CF5327D7A6FF00E86E4E /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */, + 184B31DD27D898960075A669 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */, ); productRefGroup = 1850252527B6918C002E6B18 /* Products */; projectDirPath = ""; @@ -728,6 +742,7 @@ 18F2BAFF27D25B4000DD1988 /* HomeScreenModels.swift in Sources */, 18F2BB1527D25B4000DD1988 /* LoginScreenViewModelProtocol.swift in Sources */, 18F2BAEB27D25B4000DD1988 /* LabelledActivityIndicatorView.swift in Sources */, + 18A318DC27DA42C9000867CD /* RoomTimelineItemProtocol.swift in Sources */, 18F2BAE427D25B4000DD1988 /* Presentable.swift in Sources */, 18F2BAF927D25B4000DD1988 /* SplashViewController.swift in Sources */, 18F2BAE327D25B4000DD1988 /* RootRouter.swift in Sources */, @@ -736,7 +751,6 @@ 18F2BAD927D25B4000DD1988 /* MockRoomProxy.swift in Sources */, 18F2BAE727D25B4000DD1988 /* RoundedToastView.swift in Sources */, 18F2BAF227D25B4000DD1988 /* WeakDictionaryKeyReference.swift in Sources */, - 18F2BB2427D262A900DD1988 /* RoomTimelineItemProtocol.swift in Sources */, 18F2BAE027D25B4000DD1988 /* NavigationRouter.swift in Sources */, 18F2BAF627D25B4000DD1988 /* Coordinator.swift in Sources */, 18F2BAEA27D25B4000DD1988 /* ActivityCenter.swift in Sources */, @@ -761,7 +775,6 @@ 18F2BADF27D25B4000DD1988 /* NavigationRouterStore.swift in Sources */, 18F2BAFE27D25B4000DD1988 /* HomeScreenViewModelProtocol.swift in Sources */, 18F2BAE827D25B4000DD1988 /* RectangleToastView.swift in Sources */, - 18F2BB2627D262FA00DD1988 /* TextRoomTimelineItem.swift in Sources */, 18F2BB1627D25B4000DD1988 /* LoginScreenModels.swift in Sources */, 18F2BADA27D25B4000DD1988 /* RoomTimelineProvider.swift in Sources */, 18F2BB0027D25B4000DD1988 /* HomeScreen.swift in Sources */, @@ -769,6 +782,7 @@ 18F2BB0127D25B4000DD1988 /* HomeScreenViewModel.swift in Sources */, 18F2BAF027D25B4000DD1988 /* ActivityDismissal.swift in Sources */, 18F2BADD27D25B4000DD1988 /* KeychainController.swift in Sources */, + 18A318DD27DA42C9000867CD /* TextRoomTimelineItem.swift in Sources */, 18F2BAFB27D25B4000DD1988 /* HomeScreenCoordinator.swift in Sources */, 18F2BB0C27D25B4000DD1988 /* RoomScreenCoordinator.swift in Sources */, 18F2BB0E27D25B4000DD1988 /* RoomScreenViewModelProtocol.swift in Sources */, @@ -1136,7 +1150,15 @@ minimumVersion = 7.0.0; }; }; - 1850255727B69388002E6B18 /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */ = { + 184B31DD27D898960075A669 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/siteline/SwiftUI-Introspect.git"; + requirement = { + branch = master; + kind = branch; + }; + }; + 1859CF5327D7A6FF00E86E4E /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/matrix-org/matrix-rust-components-swift.git"; requirement = { @@ -1168,9 +1190,14 @@ package = 182BC47F27C4EBBB00A30C33 /* XCRemoteSwiftPackageReference "Kingfisher" */; productName = Kingfisher; }; - 1850255827B69388002E6B18 /* MatrixRustSDK */ = { + 184B31DE27D898960075A669 /* Introspect */ = { isa = XCSwiftPackageProductDependency; - package = 1850255727B69388002E6B18 /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */; + package = 184B31DD27D898960075A669 /* XCRemoteSwiftPackageReference "SwiftUI-Introspect" */; + productName = Introspect; + }; + 1859CF5427D7A6FF00E86E4E /* MatrixRustSDK */ = { + isa = XCSwiftPackageProductDependency; + package = 1859CF5327D7A6FF00E86E4E /* XCRemoteSwiftPackageReference "matrix-rust-components-swift" */; productName = MatrixRustSDK; }; 1863A3FB27BA5A9100B52E4D /* KeychainAccess */ = { diff --git a/ElementX/Sources/Screens/HomeScreen/HomeScreenViewModel.swift b/ElementX/Sources/Screens/HomeScreen/HomeScreenViewModel.swift index bd3a953de..77a5da5e6 100644 --- a/ElementX/Sources/Screens/HomeScreen/HomeScreenViewModel.swift +++ b/ElementX/Sources/Screens/HomeScreen/HomeScreenViewModel.swift @@ -66,8 +66,7 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol self.roomList = roomList roomList.forEach({ roomProxy in - roomProxy.paginateBackwards(start: 0, finish: 1) - roomProxy.startLiveEventListener() + roomProxy.paginateBackwards(count: 1, callback: nil) roomProxy.callbacks.sink { [weak self] callback in switch callback { case .updatedLastMessage: diff --git a/ElementX/Sources/Screens/RoomScreen/RoomScreenModels.swift b/ElementX/Sources/Screens/RoomScreen/RoomScreenModels.swift index b3b1abb7d..7529453d9 100644 --- a/ElementX/Sources/Screens/RoomScreen/RoomScreenModels.swift +++ b/ElementX/Sources/Screens/RoomScreen/RoomScreenModels.swift @@ -32,7 +32,6 @@ private var dateFormatter: DateFormatter = { }() struct RoomScreenMessage: Identifiable, Equatable { - let id: String let sender: String let text: String @@ -45,6 +44,5 @@ struct RoomScreenMessage: Identifiable, Equatable { struct RoomScreenViewState: BindableState { var roomTitle: String? - var isLoading: Bool = false var messages: [RoomScreenMessage] = [] } diff --git a/ElementX/Sources/Screens/RoomScreen/RoomScreenViewModel.swift b/ElementX/Sources/Screens/RoomScreen/RoomScreenViewModel.swift index 94b802d3e..1e70eb20e 100644 --- a/ElementX/Sources/Screens/RoomScreen/RoomScreenViewModel.swift +++ b/ElementX/Sources/Screens/RoomScreen/RoomScreenViewModel.swift @@ -50,8 +50,6 @@ class RoomScreenViewModel: RoomScreenViewModelType, RoomScreenViewModelProtocol self.state.messages = self.buildRoomScreenMessages(timelineController.timelineItems) } }.store(in: &cancellables) - - timelineController.paginateBackwards(Constants.backPaginationPageSize) } // MARK: - Public diff --git a/ElementX/Sources/Screens/RoomScreen/View/RoomScreen.swift b/ElementX/Sources/Screens/RoomScreen/View/RoomScreen.swift index d11c2a30b..8608a5c11 100644 --- a/ElementX/Sources/Screens/RoomScreen/View/RoomScreen.swift +++ b/ElementX/Sources/Screens/RoomScreen/View/RoomScreen.swift @@ -15,33 +15,47 @@ // import SwiftUI +import Introspect +import Combine struct RoomScreen: View { - let timelineBottomDividerIdentifier = "TimelineBottomDividerIdentifier" + @State private var scrollViewObserver: ScrollViewObserver = ScrollViewObserver() + @State private var messages: [RoomScreenMessage] = [] + + @State private var didRequestBackPagination = false + @State private var hasPendingMessages = false + @State private var wasBottomVisible = false + + @State private var previousTopMostMessageIdentifier: String? + + private let timelineBottomAnchor = "TimelineBottomAnchor" @ObservedObject var context: RoomScreenViewModel.Context - @State var backPaginationMessageIdentifier: String? var body: some View { - ScrollViewReader { reader in + ScrollViewReader { scrollViewProxy in List { - if backPaginationMessageIdentifier != nil { + if didRequestBackPagination == false { + Color + .clear + .onAppear { + guard didRequestBackPagination == false else { + return + } + + didRequestBackPagination = true + context.send(viewAction: .loadPreviousPage) + } + } else { HStack { Spacer() ProgressView() Spacer() } - } else { - Rectangle() - .onAppear { - let _ = MXLog.debug("Request load previous page") - backPaginationMessageIdentifier = context.viewState.messages.first?.id - context.send(viewAction: .loadPreviousPage) - } - .frame(height: 0.0) } - ForEach(context.viewState.messages) { message in + + ForEach(messages) { message in VStack(alignment: .leading) { HStack { Text(message.sender) @@ -55,23 +69,117 @@ struct RoomScreen: View { .id(message.id) } - Divider() - .id(timelineBottomDividerIdentifier) + Color.clear .listRowSeparator(.hidden) + .id(timelineBottomAnchor) } .listStyle(.plain) - .onAppear { - reader.scrollTo(timelineBottomDividerIdentifier, anchor: .bottom) - } - .onChange(of: context.viewState.messages) { _ in - if backPaginationMessageIdentifier != nil { - reader.scrollTo(backPaginationMessageIdentifier, anchor: .bottom) - self.backPaginationMessageIdentifier = nil + .environment(\.defaultMinListRowHeight, 0.0) + .navigationBarTitleDisplayMode(.inline) + // Fetch the underlying UIScrollView and start observing it + .introspectTableView { scrollView in + if scrollView == scrollViewObserver.scrollView { return } - reader.scrollTo(timelineBottomDividerIdentifier, anchor: .bottom) + scrollViewObserver = ScrollViewObserver(scrollView: scrollView) } + // Scroll to the bottom when the timeline first appears + .onAppear { + scrollViewProxy.scrollTo(timelineBottomAnchor, anchor: .bottom) + } + // When the view state changes check whether the user is interacting with the scroll view. + // Updating in that case causes undesired scrolling. Delay until the scroll view stops scrolling. + // Also store previous top most message identifier to have something to scroll to after the update. + .onChange(of: context.viewState.messages) { newValue in + previousTopMostMessageIdentifier = messages.first?.id + wasBottomVisible = scrollViewObserver.isBottomVisible + + if scrollViewObserver.isTracking == true { + hasPendingMessages = true + return + } + + messages = newValue + } + // Check if we have pending messages to apply and apply them when the scroll finishes scrolling + .onReceive(scrollViewObserver.didEndScrolling, perform: { + if hasPendingMessages { + messages = context.viewState.messages + hasPendingMessages = false + } + }) + // Process timeline updates + .onChange(of: messages, perform: { _ in + if didRequestBackPagination && wasBottomVisible { + scrollViewProxy.scrollTo(timelineBottomAnchor, anchor: .bottom) + } else if didRequestBackPagination == false { + if wasBottomVisible { + scrollViewProxy.scrollTo(timelineBottomAnchor, anchor: .bottom) + } + } else { + // Manual scrolling breaks inertia. Don't do it if the scroll view is decelerating + if scrollViewObserver.isDecelerating == false { + scrollViewProxy.scrollTo(previousTopMostMessageIdentifier, anchor: .top) + } + } + + didRequestBackPagination = false + }) + } + } +} + +/// Simple wrapper around an UIScrollView that publishes when it finishes scrolling +class ScrollViewObserver: NSObject, UIScrollViewDelegate { + private(set) var scrollView: UIScrollView? + + let didEndScrolling = PassthroughSubject() + + override init() { + + } + + init(scrollView: UIScrollView) { + self.scrollView = scrollView + super.init() + + scrollView.delegate = self + } + + var isTracking: Bool { + self.scrollView?.isTracking == true + } + + var isDecelerating: Bool { + self.scrollView?.isDecelerating == true + } + + var isTopVisible: Bool { + guard let scrollView = scrollView else { + return false + } + + return (scrollView.contentOffset.y + scrollView.adjustedContentInset.top) <= 0.0 + } + + var isBottomVisible: Bool { + guard let scrollView = scrollView else { + return false + } + + return (scrollView.contentOffset.y) >= (scrollView.contentSize.height - scrollView.frame.size.height) + } + + // MARK: - UIScrollViewDelegate + + func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { + didEndScrolling.send(()) + } + + func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerating: Bool) { + if decelerating == false { + didEndScrolling.send(()) } } } diff --git a/ElementX/Sources/Services/MockRoomProxy.swift b/ElementX/Sources/Services/MockRoomProxy.swift index 1fcfea454..d53eea733 100644 --- a/ElementX/Sources/Services/MockRoomProxy.swift +++ b/ElementX/Sources/Services/MockRoomProxy.swift @@ -8,6 +8,7 @@ import Foundation import UIKit import Combine +import MatrixRustSDK struct MockRoomProxy: RoomProxyProtocol { let id = UUID().uuidString @@ -38,7 +39,7 @@ struct MockRoomProxy: RoomProxyProtocol { } - func paginateBackwards(start: UInt, finish: UInt) { + func paginateBackwards(count: UInt, callback: ((Result<[Message], Error>) -> Void)?) { } } diff --git a/ElementX/Sources/Services/RoomProxy.swift b/ElementX/Sources/Services/RoomProxy.swift index bba30c9ec..fe7148479 100644 --- a/ElementX/Sources/Services/RoomProxy.swift +++ b/ElementX/Sources/Services/RoomProxy.swift @@ -14,6 +14,7 @@ import MatrixRustSDK enum RoomProxyError: Error { case failedRetrievingDisplayName case failedRetrievingAvatar + case backwardStreamNotAvailable } private class WeakRoomProxyWrapper: RoomDelegate { @@ -23,27 +24,32 @@ private class WeakRoomProxyWrapper: RoomDelegate { self.roomProxy = roomProxy } + // MARK: - RoomDelegate + func didReceiveMessage(message: Message) { DispatchQueue.main.async { self.roomProxy?.appendMessage(message) } } - - func didPaginateBackwards(messages: [Message]) { - DispatchQueue.main.async { - self.roomProxy?.preprendMessages(messages) - } - } } class RoomProxy: RoomProxyProtocol, Equatable { private let room: Room + private let processingQueue: DispatchQueue + + private var backwardStream: BackwardsStreamProtocol? let callbacks = PassthroughSubject() init(room: Room) { self.room = room - self.room.setDelegate(delegate: WeakRoomProxyWrapper(roomProxy: self)) + processingQueue = DispatchQueue(label: "RoomProxyProcessingQueue") + + processingQueue.async { + self.backwardStream = room.startLiveEventListener() + } + + room.setDelegate(delegate: WeakRoomProxyWrapper(roomProxy: self)) } var id: String { @@ -119,13 +125,26 @@ class RoomProxy: RoomProxyProtocol, Equatable { } } } - - func startLiveEventListener() { - room.startLiveEventListener() - } - - func paginateBackwards(start: UInt, finish: UInt) { - room.paginateBackwards(from: UInt8(start), to: UInt8(finish)) + + func paginateBackwards(count: UInt, callback: ((Result<[Message], Error>) -> Void)?) { + processingQueue.async { + guard let backwardStream = self.backwardStream else { + DispatchQueue.main.async { + callback?(.failure(RoomProxyError.backwardStreamNotAvailable)) + } + return + } + + let messages = backwardStream.paginateBackwards(count: UInt64(count)) + + DispatchQueue.main.async { + callback?(.success(messages)) + + if self.lastMessage == nil { + self.lastMessage = messages.last?.content() + } + } + } } // MARK: - Equatable @@ -137,11 +156,7 @@ class RoomProxy: RoomProxyProtocol, Equatable { // MARK: - Private fileprivate func preprendMessages(_ messages: [Message]) { - if lastMessage == nil { - lastMessage = messages.last?.content() - } - callbacks.send(.prependedMessages(messages)) } fileprivate func appendMessage(_ message: Message) { diff --git a/ElementX/Sources/Services/RoomProxyProtocol.swift b/ElementX/Sources/Services/RoomProxyProtocol.swift index 2555f25b6..6dd360095 100644 --- a/ElementX/Sources/Services/RoomProxyProtocol.swift +++ b/ElementX/Sources/Services/RoomProxyProtocol.swift @@ -10,7 +10,6 @@ import Combine import MatrixRustSDK enum RoomProxyCallback { - case prependedMessages([Message]) case addedMessage(Message) case updatedLastMessage } @@ -32,8 +31,7 @@ protocol RoomProxyProtocol { func loadDisplayName(_ completion: @escaping (Result) -> Void) func loadAvatar(_ completion: @escaping (Result) -> Void) - func startLiveEventListener() - func paginateBackwards(start: UInt, finish: UInt) + func paginateBackwards(count: UInt, callback: ((Result<[Message], Error>) -> Void)?) var callbacks: PassthroughSubject { get } } diff --git a/ElementX/Sources/Services/Timeline/RoomTimelineProvider.swift b/ElementX/Sources/Services/Timeline/RoomTimelineProvider.swift index 5862afa96..c06de91ba 100644 --- a/ElementX/Sources/Services/Timeline/RoomTimelineProvider.swift +++ b/ElementX/Sources/Services/Timeline/RoomTimelineProvider.swift @@ -19,7 +19,6 @@ class RoomTimelineProvider { private var cancellables = Set() private var paginationCounter: UInt = 0 - private var isWaitingPaginationResponse = false let callbacks = PassthroughSubject() private(set) var messages = [Message]() @@ -27,17 +26,12 @@ class RoomTimelineProvider { init(roomProxy: RoomProxyProtocol) { self.roomProxy = roomProxy - self.roomProxy.startLiveEventListener() - self.roomProxy.callbacks.sink { [weak self] callback in guard let self = self else { return } switch callback { case .addedMessage(let message): self.messages.append(message) - case .prependedMessages(let messages): - self.messages.insert(contentsOf: messages.reversed(), at: 0) - self.isWaitingPaginationResponse = false case .updatedLastMessage: break } @@ -48,14 +42,15 @@ class RoomTimelineProvider { } func paginateBackwards(_ count: UInt) { - if isWaitingPaginationResponse { - return + self.roomProxy.paginateBackwards(count: count) { result in + switch result { + case .success(let messages): + self.messages.insert(contentsOf: messages.reversed(), at: 0) + self.callbacks.send(.updatedMessages) + case .failure(let error): + MXLog.debug("Failed paginating backwards with error: \(error)") + self.callbacks.send(.updatedMessages) + } } - - self.roomProxy.paginateBackwards(start: paginationCounter, finish: count) - isWaitingPaginationResponse = true - - // This is not in any way correct but it will do for now. - self.paginationCounter += count } } diff --git a/ElementX/Sources/Services/Timeline/RoomTimelineItemProtocol.swift b/ElementX/Sources/Services/Timeline/TimelineItems/RoomTimelineItemProtocol.swift similarity index 100% rename from ElementX/Sources/Services/Timeline/RoomTimelineItemProtocol.swift rename to ElementX/Sources/Services/Timeline/TimelineItems/RoomTimelineItemProtocol.swift diff --git a/ElementX/Sources/Services/Timeline/TextRoomTimelineItem.swift b/ElementX/Sources/Services/Timeline/TimelineItems/TextRoomTimelineItem.swift similarity index 100% rename from ElementX/Sources/Services/Timeline/TextRoomTimelineItem.swift rename to ElementX/Sources/Services/Timeline/TimelineItems/TextRoomTimelineItem.swift