Files
element-x-ios/ElementX/Sources/Screens/RoomScreen/View/RoomScreen.swift
T
Mauro 426fdc70a1 Add a developer option and selection mode for timeline messages (#6102)
* Add a developer option and selection mode for timeline messages

First step of the multi-select messages feature (element-meta#3255, iOS
counterpart of element-x-android#6918). Everything is gated behind the new
`messageMultiSelectEnabled` developer option and nothing changes while it
is off.

- Adds a "Select" action to the timeline item menu for remote messages in
  the room, focused and thread timelines. Choosing it enters selection
  mode with that message selected.
- While selecting, every bubbled row shows a checkbox on its leading edge
  and tapping or long pressing a row toggles it. State events, redacted
  messages, live locations, unsupported events and local echoes cannot be
  selected and stay inert. Selected rows get the accent background.
- The navigation bar swaps to a Cancel button and an "N selected" title,
  the back button is hidden and the composer is removed until the
  selection ends (Cancel or deselecting the last item). This is the hook
  where the bulk action bar will land in the next PR.
- The selection is capped at 30 messages, showing a toast when the cap
  is hit, and is cleared if the developer option is switched off.
- The selection state lives in `TimelineViewModel` so room and thread
  timelines share the behaviour without extra plumbing.

Includes unit tests for the menu action gating and the selection state
transitions, plus RoomScreen and bubble styler previews for the new state.

* Harden the timeline selection mode after review

- Reconcile the selection with timeline updates: selected messages that
  become unselectable (e.g. redacted) are dropped, and the selection is
  cleared when the timeline is swapped for a focused or live one, so the
  count can never refer to items that aren't on screen.
- Keep the composer mounted but collapsed while selecting, instead of
  removing it from the hierarchy. This preserves the draft and composer
  mode and avoids the disappear side effects. The footer with the identity
  warnings stays visible.
- Give the long press modifier an `isEnabled` flag so the recogniser is
  disabled while selecting, rather than only skipping the action while
  still animating and buzzing.
- Gate the Mac context menu on the selection like the other gestures.
- VoiceOver: a selectable bubble becomes a button carrying the selected
  trait whose default action toggles it, non-selectable rows lose their
  message actions while selecting, and reactions, thread summaries and the
  checkbox are hidden from the accessibility tree in selection mode.

* Stop voice message recordings when entering selection mode

The composer is collapsed rather than removed while selecting, so an
in-progress recording would otherwise keep the microphone open out of
sight. Entering the selection now stops the recording, which moves the
composer to the preview state so the message is still there to play or
send once the selection ends. Playback of voice messages is unaffected.

* Use the translated strings for the message selection mode

The selection strings have been imported to Localazy, so the untranslated
placeholders are dropped in favour of `action_select`,
`screen_room_maximum_messages_selected` and the `screen_room_selection_count`
plural. Only these keys are taken from the download to keep the change
focused.

* Apply review suggestions to the message selection mode

Addresses the first review round on the selection mode:

- Undecryptable messages are no longer selectable, as none of the bulk
  actions can be taken on them from the single item menu either.
- Renames for clarity: the menu action is `selectMessages` (leaving room
  for a future `selectText`), the view action is `startSelection`, the
  state exposes `contains(_:)`, `limit` and `isAtLimit`, and the composer
  collapsing modifier is `collapsedInPlace(_:)`.
- `canSelectMessages` uses a switch expression, the selection state doc
  comment refers to a feature flag rather than Labs, the recording helper
  doc describes only what it does, and `toggleSelection()` moves below
  the subviews.

* Keep the accessibility labels of timeline items while selecting

The selection mode used to replace each item's accessibility body with a
plain combined element, dropping the sender name representation and the
gallery label. The per item labelling now always applies, and the selection
only changes the interaction on top of it: the message actions are offered
as before, or the item becomes a button carrying the selected trait whose
default action toggles it. Polls and galleries collapse into a single
element only while selecting, as their children are inert then.

* Keep the timeline types within the lint limits after rebasing

The redaction reason work on develop grew the menu action handler and the
timeline view model right up to SwiftLint's size limits, so the selection
additions tipped them over. The `selectMessages` case now shares the
`downloadMedia` break and the selection flag subscription lives in the
selection extension.

* Fix the snapshot regressions from the selection mode

- Drop `geometryGroup()` from the bubble row: it stopped the avatar
  placeholder initial from rendering, which showed up as a mismatch in
  every timeline item snapshot.
- Collapse the composer with opacity instead of clipping, as the clip also
  removed the composer background from the home indicator area while the
  composer was fully visible.
- Keep the timeline item menu preview on the default flag-off state so the
  existing menu snapshots stay valid.
- Record the new "Selecting" room screen and "Selection" bubble snapshots
  on the same iPhone SE simulator CI uses.
2026-09-09 13:36:57 +02:00

422 lines
18 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-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 Compound
import SwiftUI
import WysiwygComposer
struct RoomScreen: View {
@ObservedObject private var context: RoomScreenViewModelType.Context
@ObservedObject private var timelineContext: TimelineViewModelType.Context
let composerToolbar: ComposerToolbar
@Environment(\.accessibilityVoiceOverEnabled) private var isVoiceOverEnabled
enum MarkAsReadSource {
case up
case down
}
/// Which scroll button (if any) currently has the "Mark as read" pill displayed alongside it.
/// Set when the user long-presses one of the scroll buttons; the pill anchors to that button.
@State private var markAsReadSource: MarkAsReadSource?
init(context: RoomScreenViewModelType.Context,
timelineContext: TimelineViewModelType.Context,
composerToolbar: ComposerToolbar) {
self.context = context
self.timelineContext = timelineContext
self.composerToolbar = composerToolbar
}
var body: some View {
TimelineView(timelineContext: timelineContext)
.overlay {
// Sits below the bottom-trailing overlay in z-order, so taps on the pill or
// buttons still go to them; taps anywhere else dismiss the pill.
if markAsReadSource != nil {
Color.clear
.contentShape(Rectangle())
.onTapGesture { dismissMarkAsReadPill() }
}
}
.overlay(alignment: .bottomTrailing) {
VStack(alignment: .trailing, spacing: 16) {
HStack(spacing: 8) {
if markAsReadSource == .up {
markAsReadPill
.transition(.move(edge: .trailing).combined(with: .opacity))
}
jumpToReadMarkerButton
}
HStack(spacing: 8) {
if markAsReadSource == .down {
markAsReadPill
.transition(.move(edge: .trailing).combined(with: .opacity))
}
TimelineScrollButton(isHidden: !timelineContext.viewState.shouldShowScrollToBottomButton,
showsBadge: scrollToBottomShowsBadge,
onLongPress: scrollToBottomShowsBadge ? { revealMarkAsReadPill(source: .down) } : nil) {
dismissMarkAsReadPill()
timelineContext.send(viewAction: .scrollToBottom)
}
.accessibilityIdentifier(A11yIdentifiers.roomScreen.scrollToBottom)
}
}
.padding()
.animation(.elementDefault, value: markAsReadSource)
}
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.topBanners([
TopBannerLayer(verticalBanners: [
TopBannerItem(pinnedItemsBanner, isVisible: context.viewState.shouldShowPinnedEventsBanner && !isVoiceOverEnabled),
TopBannerItem(liveLocationBanner, isVisible: context.viewState.isSharingLiveLocation && !isVoiceOverEnabled)
]),
// This can overlay on top of the stacked banners
TopBannerLayer(knockRequestsBanner, isVisible: context.viewState.shouldSeeKnockRequests)
], footer: dateBadge)
.safeAreaInset(edge: .top) {
// When VoiceOver is enabled the scroll gestures don't trigger, so the banner never
// hides itself and the .overlay layout above would permanently obscure the top of
// the timeline. So whenever VoiceOver is enabled we use a safe area inset to
// vertically stack it above the timeline instead.
if context.viewState.shouldShowPinnedEventsBanner || context.viewState.isSharingLiveLocation, isVoiceOverEnabled {
VStack(spacing: 0) {
if context.viewState.shouldShowPinnedEventsBanner {
pinnedItemsBanner
}
if context.viewState.isSharingLiveLocation {
liveLocationBanner
}
}
}
}
.safeAreaInset(edge: .bottom, spacing: 0) {
VStack(spacing: 0) {
RoomScreenFooterView(details: context.viewState.footerDetails,
mediaProvider: context.mediaProvider) { action in
context.send(viewAction: .footerViewAction(action))
}
composer
.padding(.top, 8)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.environmentObject(timelineContext)
.environment(\.timelineContext, timelineContext)
// Make sure the reply header honours the hideTimelineMedia setting too.
.environment(\.shouldAutomaticallyLoadImages, !timelineContext.viewState.hideTimelineMedia)
.collapsedInPlace(isSelectionActive)
}
}
.navigationBarBackButtonHidden(isSelectionActive)
.toolbarRole(RoomHeaderView.toolbarRole)
.navigationTitle(L10n.screenRoomTitle) // Hidden but used for back button text.
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.toolbarBackground(.visible, for: .navigationBar) // Fix the toolbar's background.
.overlay { loadingIndicator }
.alert(item: $context.alertInfo)
.timelineMediaPreview(viewModel: $context.mediaPreviewViewModel)
.onChange(of: pillSourceButtonIsVisible) { _, isVisible in
if !isVisible {
dismissMarkAsReadPill()
}
}
.track(screen: .Room)
.sentryTrace("\(Self.self)")
}
private var liveLocationBanner: some View {
LiveLocationSharingBannerView {
context.send(viewAction: .tappedOpenLiveLocation)
} onStop: {
context.send(viewAction: .tappedStopLiveLocation)
}
}
private var pinnedItemsBanner: some View {
PinnedItemsBannerView(state: context.viewState.pinnedEventsBannerState,
onMainButtonTap: { context.send(viewAction: .tappedPinnedEventsBanner) },
onViewAllButtonTap: { context.send(viewAction: .viewAllPins) })
}
private var knockRequestsBanner: some View {
KnockRequestsBannerView(requests: context.viewState.displayedKnockRequests,
onDismiss: dismissKnockRequestsBanner,
onAccept: context.viewState.canAcceptKnocks ? acceptKnockRequest : nil,
onViewAll: onViewAllKnockRequests,
mediaProvider: context.mediaProvider)
.padding(.top, 16)
}
@ViewBuilder
private var dateBadge: some View {
if !isVoiceOverEnabled {
FloatingDateBadge(dateText: timelineContext.floatingDate?.formattedDateSeparator()) {
timelineContext.send(viewAction: .scrollToFirstItemForCurrentDate)
}
}
}
private func dismissKnockRequestsBanner() {
context.send(viewAction: .dismissKnockRequests)
}
private func acceptKnockRequest(eventID: String) {
context.send(viewAction: .acceptKnock(eventID: eventID))
}
private func onViewAllKnockRequests() {
context.send(viewAction: .viewKnockRequests)
}
@ViewBuilder
private var jumpToReadMarkerButton: some View {
if timelineContext.viewState.shouldShowJumpToReadMarker {
TimelineScrollButton(direction: .up,
showsBadge: true) {
revealMarkAsReadPill(source: .up)
} callback: {
dismissMarkAsReadPill()
timelineContext.send(viewAction: .scrollToReadMarker)
}
}
}
private var markAsReadPill: some View {
Button {
timelineContext.send(viewAction: .markAllAsRead)
dismissMarkAsReadPill()
} label: {
markAsReadPillLabel
}
}
@ViewBuilder
private var markAsReadPillLabel: some View {
// Font scales with Dynamic Type via the Compound token; padding is a fixed point value
// so the pill grows with the text instead of growing twice over.
let label = Label {
Text(L10n.screenRoomlistMarkAsRead)
} icon: {
CompoundIcon(\.markAsRead, size: .medium, relativeTo: .compound.bodyLG)
}
.font(.compound.bodyLG)
.foregroundStyle(.compound.textPrimary)
.padding(.horizontal, 20)
.padding(.vertical, 20)
if #available(iOS 26, *) {
label.glassEffect(.regular.interactive(), in: Capsule())
} else {
label.background(.regularMaterial, in: Capsule())
}
}
private func revealMarkAsReadPill(source: MarkAsReadSource) {
markAsReadSource = source
}
private func dismissMarkAsReadPill() {
markAsReadSource = nil
}
/// Whether the scroll button that the pill is anchored to is still being rendered.
/// Used to dismiss an orphaned pill when the source button gets hidden — without
/// this, the pill can render alongside an invisible button. Returns `true` when no
/// pill is shown so the `onChange` doesn't fire spuriously when the source clears.
private var pillSourceButtonIsVisible: Bool {
switch markAsReadSource {
case .up: timelineContext.viewState.shouldShowJumpToReadMarker
case .down: timelineContext.viewState.shouldShowScrollToBottomButton
case .none: true
}
}
/// Hide the new-messages dot when the jump-to-read-marker feature is disabled.
private var scrollToBottomShowsBadge: Bool {
timelineContext.viewState.jumpToReadMarkerEnabled
&& timelineContext.viewState.bindings.hasNewMessagesAtBottom
}
@ViewBuilder
private var composer: some View {
if context.viewState.hasSuccessor {
tombstonedDialogue
} else if context.viewState.canSendMessage, !ProcessInfo.isRunningAccessibilityTests {
// We are not sure why but when wrapped in the room screen the composer toolbar breaks the accessibility tests
composerToolbar
} else {
ComposerDisabledView()
}
}
private var tombstonedDialogue: some View {
VStack(spacing: 16) {
Text(L10n.screenRoomTimelineTombstonedRoomMessage)
.font(.compound.bodyMD)
.foregroundStyle(.compound.textPrimary)
Button {
context.send(viewAction: .displaySuccessorRoom)
} label: {
Text(L10n.screenRoomTimelineTombstonedRoomAction)
.frame(maxWidth: .infinity)
}
.buttonStyle(.compound(.primary, size: .medium))
}
.padding(.top, 16)
.padding(.horizontal, 16)
.padding(.bottom, 12)
.highlight(gradient: .compound.info, borderColor: .compound.borderInfoSubtle)
}
@ViewBuilder
private var loadingIndicator: some View {
if timelineContext.viewState.showLoading {
ProgressView()
.progressViewStyle(.circular)
.tint(.compound.textPrimary)
.padding(16)
.background(.ultraThickMaterial)
.cornerRadius(8)
}
}
private var isSelectionActive: Bool {
timelineContext.viewState.selection.isActive
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
if isSelectionActive {
TimelineSelectionToolbar(count: timelineContext.viewState.selection.count) {
timelineContext.send(viewAction: .clearSelection)
}
} else {
roomToolbar
}
}
@ToolbarContentBuilder
private var roomToolbar: some ToolbarContent {
// .principal + .primaryAction works better than .navigation leading + trailing
// as the latter disables interaction in the action button for rooms with long names
ToolbarItem(placement: .principal) {
RoomHeaderView(roomName: context.viewState.roomTitle,
roomAvatar: context.viewState.roomAvatar,
dmRecipientDetails: context.viewState.dmRecipientDetails,
roomHistorySharingState: context.viewState.roomHistorySharingState,
mediaProvider: context.mediaProvider) {
context.send(viewAction: .displayRoomDetails)
}
}
if !ProcessInfo.processInfo.isiOSAppOnMac {
if context.viewState.shouldShowCallButton {
RoomCallControlsToolbar(viewState: context.viewState) { isVoiceCall in
context.send(viewAction: .displayCall(isVoiceCall: isVoiceCall))
}
}
}
if context.viewState.roomThreadListEnabled {
if #available(iOS 26, *) {
ToolbarSpacer(.fixed, placement: .primaryAction)
}
ToolbarItem(placement: .primaryAction) {
Button {
context.send(viewAction: .displayThreadList)
} label: {
CompoundIcon(\.threads)
}
}
}
}
}
// MARK: - Previews
struct RoomScreen_Previews: PreviewProvider, TestablePreview {
static let viewModels = makeViewModels()
static let readOnlyViewModels = makeViewModels(canSendMessage: false)
static let tombstonedViewModels = makeViewModels(hasSuccessor: true)
static let selectingViewModels = makeViewModels(isSelecting: true)
static let composerViewModel = ComposerToolbarViewModel.mock()
static var previews: some View {
ElementNavigationStack {
RoomScreen(context: viewModels.room.context,
timelineContext: viewModels.timeline.context,
composerToolbar: ComposerToolbar(context: composerViewModel.context))
}
.previewDisplayName("Normal")
ElementNavigationStack {
RoomScreen(context: readOnlyViewModels.room.context,
timelineContext: readOnlyViewModels.timeline.context,
composerToolbar: ComposerToolbar(context: composerViewModel.context))
}
.previewDisplayName("Read-only")
.snapshotPreferences(expect: readOnlyViewModels.room.context.$viewState.map { !$0.canSendMessage })
ElementNavigationStack {
RoomScreen(context: tombstonedViewModels.room.context,
timelineContext: tombstonedViewModels.timeline.context,
composerToolbar: ComposerToolbar(context: composerViewModel.context))
}
.previewDisplayName("Tombstoned")
.snapshotPreferences(expect: tombstonedViewModels.room.context.$viewState.map(\.hasSuccessor))
ElementNavigationStack {
RoomScreen(context: selectingViewModels.room.context,
timelineContext: selectingViewModels.timeline.context,
composerToolbar: ComposerToolbar(context: composerViewModel.context))
}
.previewDisplayName("Selecting")
.snapshotPreferences(expect: selectingViewModels.timeline.context.$viewState.map(\.selection.isActive))
}
static func makeViewModels(canSendMessage: Bool = true, hasSuccessor: Bool = false, isSelecting: Bool = false) -> ViewModels {
let roomProxyMock = JoinedRoomProxyMock(.init(id: "stable_id",
name: "Preview room",
hasOngoingCall: true,
successor: hasSuccessor ? .init(roomId: UUID().uuidString, reason: nil) : nil,
powerLevelsConfiguration: .init(canUserSendMessage: canSendMessage)))
let roomViewModel = RoomScreenViewModel.mock(roomProxyMock: roomProxyMock)
let appSettings = AppSettings.volatile()
appSettings.messageMultiSelectEnabled = isSelecting
let timelineController = TimelineControllerMock(.init())
let timelineViewModel = TimelineViewModel(roomProxy: roomProxyMock,
timelineController: timelineController,
userSession: UserSessionMock(.init()),
mediaPlayerProvider: MediaPlayerProviderMock(),
userIndicatorController: UserIndicatorControllerMock(),
appMediator: AppMediatorMock(.init()),
appSettings: appSettings,
analyticsService: AnalyticsServiceMock(.init()),
emojiProvider: EmojiProvider(appSettings: appSettings),
linkMetadataProvider: LinkMetadataProvider(),
timelineControllerFactory: TimelineControllerFactoryMock(.init()))
if isSelecting {
let eventIDs = timelineController.timelineItems.compactMap { ($0 as? EventBasedTimelineItemProtocol)?.id.eventID }
timelineViewModel.state.selection.selectedEventIDs = Set(eventIDs.prefix(2))
}
return .init(room: roomViewModel, timeline: timelineViewModel)
}
struct ViewModels {
let room: RoomScreenViewModelProtocol
let timeline: TimelineViewModelProtocol
}
}