Files
element-x-ios/ElementX/Sources/Screens/FilePreviewScreen/TimelineMediaPreviewViewModel.swift
T
Mauro ad1d7a3010 Add multi selection to the Forward action (#6190)
* Start message selection from the Forward action

Behind the multi-select developer option, choosing Forward on a message
now starts a selection with that message checked, instead of the
dedicated Select menu action which is removed. Only forwardable
messages can be selected: remote, decrypted, non-redacted events that
aren't state, unsupported, poll or live location items.

The chrome follows the Figma exploration: the room header stays, an X
in the trailing toolbar position ends the selection, rows show only the
checkbox (no highlight, 10pt gap to the bubble), and the composer is
replaced by a single primary "Forward N messages" button. The limits
are now 10 messages into 5 rooms.

Tapping the button forwards the selection in timeline order, never in
the order the messages were tapped. MessageForwardingItem carries
several contents and the forwarding screen sends them one after the
other per room, reporting a single error toast on partial failures.
The selection is kept while the forwarding screen is open so cancelling
it returns to the selection; it is cleared by the flow coordinator once
the messages are sent, or by the X in the timeline.

New plural action_forward_messages lives in Untranslated for now;
action_select and screen_room_selection_count are no longer used.

* Tidy the selection code after review

Reuse ToolbarButton's cancel role for the selection's toolbar item so it
matches the other screens on every OS version, and disable the room
header while selecting so the room details can't cover the selection.

Move the forwardable/selected item helpers next to the existing
nonisolated array extension, drop the unused MessageForwardingItem
initialisers and the single-item makeForwardingItem overload, and
simplify the forwarding loop now that a room either sends or isn't
reachable.

The action bar preview builds its own view model instead of putting
the shared mock into selection mode for every later preview, and a
test locks that Forward keeps forwarding directly in the pinned
timeline.

* Select messages to forward from the pinned timeline too

Forward is offered in the pinned events timeline, so with the flag on
it starts a selection there as well, with the same cancel item in the
toolbar and the same forward button at the bottom. Forwarding from
that sheet already dismisses the whole sheet, so the selection is
discarded with it. Only the media timelines keep forwarding a single
item directly.

* Confirm with a toast when messages are forwarded to several rooms

When a single room is picked the flow opens it, which is confirmation
enough. When several rooms are picked the user stays in the origin room,
so a "Messages forwarded" toast tells them it worked, as in the designs.
The new screen_room_message_forwarded / screen_room_messages_forwarded
strings live in Untranslated for now.

* Apply review suggestions to multi-message forwarding

Strings
- The forward button and the multi-room toast now use the Localazy
  plurals action_forward_messages and screen_room_messages_forwarded;
  the toast shows the count. The Untranslated copies and the unused
  action_select are gone.

Selection
- Drop the dead startSelection view action and the redundant
  canSelectMessages guard; tests start a selection through Forward
  like the app does.
- Remove two comments on the selection state that restated the code.

Forwarding
- After a send, clear the selection in the room and any open thread
  instead of working out which one started it; only one can be
  selecting at a time.
- Explain that stickers are excluded because the SDK can only forward
  m.room.message content.

* Rename the timeline selection to message selection

"Selection" alone was too generic in a timeline that also has text and
room selections. The selection state, toolbar, action bar and
accessibility types, the timeline state's property, the view actions
and the public clear method now say "message selection". Private
helpers keep their short names.

* Rename MessageForwardingItem to MessageForwardingPayload

The type now carries several messages, so "item" no longer described
it. The factory method and the variables and action labels holding it
follow the new name.
2026-09-25 11:51:14 +00:00

311 lines
15 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2024-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Combine
import Foundation
typealias TimelineMediaPreviewViewModelType = StateStoreViewModel<TimelineMediaPreviewViewState, TimelineMediaPreviewViewAction>
class TimelineMediaPreviewViewModel: TimelineMediaPreviewViewModelType {
static let displayMessageForwardingDelay: TimeInterval = 1.0
let instanceID = UUID()
private let timelineViewModel: TimelineViewModelProtocol
private let mediaProvider: MediaProviderProtocol
private let photoLibraryManager: PhotoLibraryManagerProtocol
private let userIndicatorController: UserIndicatorControllerProtocol
private let appMediator: AppMediatorProtocol
private var contentScannerService: ContentScannerServiceProtocol? {
timelineViewModel.context.contentScannerService
}
private let actionsSubject: PassthroughSubject<TimelineMediaPreviewViewModelAction, Never> = .init()
var actions: AnyPublisher<TimelineMediaPreviewViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
/// Initialises a preview spanning the whole timeline's media, staying in sync with it as it paginates.
init(initialItem: EventBasedMessageTimelineItemProtocol,
timelineViewModel: TimelineViewModelProtocol,
mediaProvider: MediaProviderProtocol,
photoLibraryManager: PhotoLibraryManagerProtocol,
userIndicatorController: UserIndicatorControllerProtocol,
appMediator: AppMediatorProtocol) {
self.timelineViewModel = timelineViewModel
self.mediaProvider = mediaProvider
self.photoLibraryManager = photoLibraryManager
self.userIndicatorController = userIndicatorController
self.appMediator = appMediator
let timelineState = timelineViewModel.context.viewState.timelineState
super.init(initialViewState: TimelineMediaPreviewViewState(dataSource: .init(itemViewStates: timelineState.itemViewStates,
initialItem: initialItem,
paginationState: timelineState.paginationState,
allowedGalleryItemTypes: timelineViewModel.context.viewState.allowedGalleryItemTypes)),
mediaProvider: mediaProvider)
rebuildCurrentItemActions()
let canRedactSelfPublisher = timelineViewModel.context.$viewState.map(\.canCurrentUserRedactSelf)
let canRedactOthersPublisher = timelineViewModel.context.$viewState.map(\.canCurrentUserRedactOthers)
canRedactSelfPublisher.merge(with: canRedactOthersPublisher)
.sink { [weak self] _ in
self?.rebuildCurrentItemActions()
}
.store(in: &cancellables)
timelineViewModel.context.$viewState.map(\.timelineState.itemViewStates)
.removeDuplicates()
.sink { [weak self] itemViewStates in
self?.state.dataSource.updatePreviewItems(itemViewStates: itemViewStates)
}
.store(in: &cancellables)
timelineViewModel.context.$viewState.map(\.timelineState.paginationState)
.removeDuplicates()
.sink { [weak self] paginationState in
guard let self else { return }
state.dataSource.paginationState = paginationState
paginateIfNeeded()
}
.store(in: &cancellables)
}
/// Initialises the preview scoped to a single gallery's attachments. The data source is
/// built from the gallery's items directly and isn't kept in sync with the underlying
/// timeline — gallery contents don't change without the event being replaced or redacted.
init(galleryItem: GalleryRoomTimelineItem,
initialIndex: Int,
timelineViewModel: TimelineViewModelProtocol,
mediaProvider: MediaProviderProtocol,
photoLibraryManager: PhotoLibraryManagerProtocol,
userIndicatorController: UserIndicatorControllerProtocol,
appMediator: AppMediatorProtocol) {
self.timelineViewModel = timelineViewModel
self.mediaProvider = mediaProvider
self.photoLibraryManager = photoLibraryManager
self.userIndicatorController = userIndicatorController
self.appMediator = appMediator
super.init(initialViewState: TimelineMediaPreviewViewState(dataSource: .init(galleryItem: galleryItem,
initialIndex: initialIndex)),
mediaProvider: mediaProvider)
rebuildCurrentItemActions()
timelineViewModel.context.$viewState.map(\.canCurrentUserRedactSelf)
.merge(with: timelineViewModel.context.$viewState.map(\.canCurrentUserRedactOthers))
.sink { [weak self] _ in self?.rebuildCurrentItemActions() }
.store(in: &cancellables)
}
override func process(viewAction: TimelineMediaPreviewViewAction) {
switch viewAction {
case .updateCurrentItem(let item):
Task { await updateCurrentItem(item) }
case .showItemDetails(let mediaItem):
state.previewControllerDriver.send(.showItemDetails(mediaItem))
case .menuAction(let action, let item):
switch action {
case .viewInRoomTimeline:
state.previewControllerDriver.send(.dismissDetailsSheet)
actionsSubject.send(.viewInRoomTimeline(item.timelineItem.id))
case .downloadMedia:
Task { await saveCurrentItem() }
case .redact:
state.bindings.redactConfirmationItem = item
case .forward(let itemID):
Task { await forwardItem(itemID: itemID) }
default:
MXLog.error("Received unexpected action: \(action)")
}
case .redactConfirmation(let item, let reason):
redactItem(item, reason: reason)
case .timelineEndReached:
showTimelineEndIndicator()
}
}
private func forwardItem(itemID: TimelineItemIdentifier) async {
guard let forwardingPayload = await timelineViewModel.makeForwardingPayload(for: [itemID]) else { return }
state.previewControllerDriver.send(.dismissDetailsSheet)
actionsSubject.send(.displayMessageForwarding(forwardingPayload))
}
private func updateCurrentItem(_ previewItem: TimelineMediaPreviewItem) async {
if case let .media(item) = previewItem {
item.downloadError = nil // Clear any existing error so that the download is retried.
}
setCurrentItem(previewItem)
if case let .media(mediaItem) = previewItem {
guard mediaItem.fileHandle == nil, let source = mediaItem.mediaSource else { return }
guard await checkSourceIsSafeIfNeeded(for: mediaItem, source: source) else { return }
switch await mediaProvider.loadFileFromSource(source, filename: mediaItem.filename) {
case .success(let handle):
mediaItem.fileHandle = handle
state.previewControllerDriver.send(.itemLoaded(mediaItem.id))
case .failure(let error):
MXLog.error("Failed loading media: \(error)")
context.objectWillChange.send() // Manually trigger the SwiftUI view update.
mediaItem.downloadError = error
}
} else {
paginateIfNeeded()
}
}
/// Scans the media when a content scanner is configured, returning whether it's safe to be downloaded
/// and previewed, reflecting the scan's progress and outcome in the current item. Both the media and
/// its thumbnail are scanned as either being downloaded through the scanner can flag the media.
private func checkSourceIsSafeIfNeeded(for mediaItem: TimelineMediaPreviewItem.Media, source: MediaSourceProxy) async -> Bool {
guard let contentScannerService else { return true }
let sources = [source, mediaItem.thumbnailMediaSource].compactMap { $0 }
// Only reflect the scanning state when there's no cached verdict, so that
// scanned items don't flash the scanning indicator when they're revisited.
if contentScannerService.scanResultFromSources(sources) == nil {
setCurrentItem(.contentScan(.init(media: mediaItem, state: .scanning)))
}
switch await contentScannerService.loadScanResultFromSources(sources) {
case .success(true):
finishScan(with: .media(mediaItem), for: mediaItem)
return true
case .success(false):
finishScan(with: .contentScan(.init(media: mediaItem, state: .failure(.notSafe))), for: mediaItem)
return false
case .failure:
finishScan(with: .contentScan(.init(media: mediaItem, state: .failure(.notFound))), for: mediaItem)
return false
}
}
/// Reflects the outcome of a scan in the current item, unless the user has already swiped on to another item.
private func finishScan(with previewItem: TimelineMediaPreviewItem, for mediaItem: TimelineMediaPreviewItem.Media) {
guard state.currentItem.mediaItem === mediaItem else { return }
setCurrentItem(previewItem)
}
private func setCurrentItem(_ previewItem: TimelineMediaPreviewItem) {
context.objectWillChange.send() // The data source is a reference type so the view needs a manual update.
state.dataSource.updateCurrentItem(previewItem)
rebuildCurrentItemActions()
}
private func paginateIfNeeded() {
switch state.currentItem {
case .loading(.paginatingBackwards):
if state.dataSource.paginationState.backward == .idle {
timelineViewModel.context.send(viewAction: .paginateBackwards)
}
case .loading(.paginatingForwards):
if state.dataSource.paginationState.forward == .idle {
timelineViewModel.context.send(viewAction: .paginateForwards)
}
default:
break
}
}
private func rebuildCurrentItemActions() {
let timelineContext = timelineViewModel.context
state.currentItemActions = state.currentItem.mediaItem.flatMap { mediaItem in
TimelineItemMenuActionProvider(timelineItem: mediaItem.timelineItem,
canCurrentUserSendMessage: timelineContext.viewState.canCurrentUserSendMessage,
canCurrentUserRedactSelf: timelineContext.viewState.canCurrentUserRedactSelf,
canCurrentUserRedactOthers: timelineContext.viewState.canCurrentUserRedactOthers,
canCurrentUserPin: timelineContext.viewState.canCurrentUserPin,
pinnedEventIDs: timelineContext.viewState.pinnedEventIDs,
isViewSourceEnabled: timelineContext.viewState.isViewSourceEnabled,
areThreadsEnabled: timelineContext.viewState.areThreadsEnabled,
timelineKind: timelineContext.viewState.timelineKind,
emojiProvider: timelineContext.viewState.emojiProvider)
.makeActions()
}
}
private func saveCurrentItem() async {
guard case let .media(mediaItem) = state.currentItem, let fileURL = mediaItem.fileHandle?.url else {
MXLog.error("Unable to save an item without a URL, the button shouldn't be visible.")
return
}
// Dismiss the details sheet (nicer flow for images/video but _required_ in order to select a file directory).
state.previewControllerDriver.send(.dismissDetailsSheet)
do {
switch mediaItem.kind {
case .file:
state.previewControllerDriver.send(.exportFile(.init(url: fileURL)))
return // Don't show the indicator.
case .image:
try await photoLibraryManager.addResource(.photo, at: fileURL).get()
case .video:
try await photoLibraryManager.addResource(.video, at: fileURL).get()
}
showSavedIndicator()
} catch PhotoLibraryManagerError.notAuthorized {
MXLog.error("Not authorised to save item to photo library")
state.previewControllerDriver.send(.authorizationRequired(appMediator: appMediator))
} catch {
MXLog.error("Failed saving item: \(error)")
showErrorIndicator()
}
}
private func redactItem(_ item: TimelineMediaPreviewItem.Media, reason: String) {
timelineViewModel.context.send(viewAction: .redactConfirmed(itemID: item.timelineItem.id, reason: reason))
state.bindings.redactConfirmationItem = nil
state.previewControllerDriver.send(.dismissDetailsSheet)
actionsSubject.send(.dismiss)
showRedactedIndicator()
}
// MARK: - Indicators
private func showRedactedIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: statusIndicatorID,
type: .toast,
title: L10n.commonFileDeleted,
icon: \.check))
}
private func showSavedIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: statusIndicatorID,
type: .toast,
title: L10n.commonFileSaved,
icon: \.check))
}
private func showErrorIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: statusIndicatorID,
type: .toast,
title: L10n.errorUnknown,
icon: \.close))
}
private func showTimelineEndIndicator() {
userIndicatorController.submitIndicator(UserIndicator(id: statusIndicatorID,
type: .toast,
title: L10n.screenMediaDetailsNoMoreMediaToShow))
}
private var statusIndicatorID: String {
"\(Self.self)-Status"
}
}