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.
This commit is contained in:
Mauro
2026-09-09 13:36:57 +02:00
committed by GitHub
parent 0454916b65
commit 426fdc70a1
31 changed files with 811 additions and 79 deletions
@@ -231,6 +231,7 @@ class TimelineMediaPreviewViewModel: TimelineMediaPreviewViewModelType {
pinnedEventIDs: timelineContext.viewState.pinnedEventIDs,
isViewSourceEnabled: timelineContext.viewState.isViewSourceEnabled,
areThreadsEnabled: timelineContext.viewState.areThreadsEnabled,
isMultiSelectEnabled: timelineContext.viewState.canSelectMessages,
timelineKind: timelineContext.viewState.timelineKind,
emojiProvider: timelineContext.viewState.emojiProvider)
.makeActions()
@@ -110,8 +110,10 @@ struct RoomScreen: View {
.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)
@@ -285,8 +287,23 @@ struct RoomScreen: View {
}
}
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) {
@@ -329,6 +346,7 @@ 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 {
@@ -354,9 +372,17 @@ struct RoomScreen_Previews: PreviewProvider, TestablePreview {
}
.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) -> ViewModels {
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,
@@ -365,8 +391,11 @@ struct RoomScreen_Previews: PreviewProvider, TestablePreview {
let roomViewModel = RoomScreenViewModel.mock(roomProxyMock: roomProxyMock)
let appSettings = AppSettings.volatile()
appSettings.messageMultiSelectEnabled = isSelecting
let timelineController = TimelineControllerMock(.init())
let timelineViewModel = TimelineViewModel(roomProxy: roomProxyMock,
timelineController: TimelineControllerMock(.init()),
timelineController: timelineController,
userSession: UserSessionMock(.init()),
mediaPlayerProvider: MediaPlayerProviderMock(),
userIndicatorController: UserIndicatorControllerMock(),
@@ -377,6 +406,11 @@ struct RoomScreen_Previews: PreviewProvider, TestablePreview {
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)
}
@@ -69,6 +69,7 @@ protocol DeveloperOptionsProtocol: AnyObject {
var linkPreviewsEnabled: Bool { get set }
var jumpToReadMarkerEnabled: Bool { get set }
var messageMultiSelectEnabled: Bool { get set }
var linkNewDeviceEnabled: Bool { get set }
@@ -101,6 +101,11 @@ struct DeveloperOptionsScreen: View {
Text("Jump to unread")
Text("Adds a button to jump to the read marker, plus a presence dot on the scroll-to-bottom button when new messages arrive while scrolled away.")
}
Toggle(isOn: $context.messageMultiSelectEnabled) {
Text("Multi-select messages")
Text("Adds a Select action to the message menu to pick several messages at once.")
}
}
Section {
@@ -30,6 +30,7 @@ struct ThreadTimelineScreen: View {
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.toolbarBackground(.visible, for: .navigationBar) // Fix the toolbar's background.
.navigationBarBackButtonHidden(isSelectionActive)
.timelineMediaPreview(viewModel: $context.mediaPreviewViewModel)
.overlay(alignment: .top) {
FloatingDateBadge(dateText: timelineContext.floatingDate?.formattedDateSeparator()) {
@@ -50,9 +51,14 @@ struct ThreadTimelineScreen: View {
.environment(\.timelineContext, timelineContext)
// Make sure the reply header honours the hideTimelineMedia setting too.
.environment(\.shouldAutomaticallyLoadImages, !timelineContext.viewState.hideTimelineMedia)
.collapsedInPlace(isSelectionActive)
}
}
private var isSelectionActive: Bool {
timelineContext.viewState.selection.isActive
}
@ViewBuilder
private var composer: some View {
if context.viewState.canSendMessage {
@@ -64,16 +70,22 @@ struct ThreadTimelineScreen: View {
@ToolbarContentBuilder
private var toolbar: 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: L10n.commonThread,
roomSubtitle: context.viewState.roomTitle,
roomAvatar: context.viewState.roomAvatar,
dmRecipientDetails: context.viewState.dmRecipientDetails,
roomHistorySharingState: context.viewState.roomHistorySharingState,
mediaProvider: context.mediaProvider) {
// There is no action but the iOS 26 designs have it looking like a button.
if isSelectionActive {
TimelineSelectionToolbar(count: timelineContext.viewState.selection.count) {
timelineContext.send(viewAction: .clearSelection)
}
} else {
// .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: L10n.commonThread,
roomSubtitle: context.viewState.roomTitle,
roomAvatar: context.viewState.roomAvatar,
dmRecipientDetails: context.viewState.dmRecipientDetails,
roomHistorySharingState: context.viewState.roomHistorySharingState,
mediaProvider: context.mediaProvider) {
// There is no action but the iOS 26 designs have it looking like a button.
}
}
}
}
@@ -224,8 +224,8 @@ class TimelineInteractionHandler {
analyticsService.trackInteraction(name: .PinnedMessageListViewTimeline)
guard let eventID = itemID.eventID else { return }
actionsSubject.send(.viewInRoomTimeline(eventID: eventID))
case .downloadMedia:
break // Handled inline in the media preview screen.
case .downloadMedia, .selectMessages:
break // Handled by the media preview screen and the TimelineViewModel respectively.
case .translate:
guard let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol else { return }
actionsSubject.send(.showTranslation(text: messageTimelineItem.body))
@@ -372,6 +372,12 @@ class TimelineInteractionHandler {
await voiceMessageRecorder.stopRecording()
}
/// Stops the recording when one is in progress, moving the composer to the preview state.
func stopRecordingVoiceMessageIfNeeded() async {
guard voiceMessageRecorder.isRecording else { return }
await voiceMessageRecorder.stopRecording()
}
func cancelRecordingVoiceMessage() async {
await voiceMessageRecorder.cancelRecording()
voiceMessageRecorderObserver = nil
@@ -69,6 +69,12 @@ enum TimelineViewAction {
/// The user has confirmed the removal of an item, optionally giving a reason.
case redactConfirmed(itemID: TimelineItemIdentifier, reason: String?)
/// Start a multi-selection with the specified item.
case startSelection(itemID: TimelineItemIdentifier)
/// Add or remove an item from the active multi-selection.
case toggleSelection(itemID: TimelineItemIdentifier)
case clearSelection
case tappedOnSenderDetails(sender: TimelineItemSender)
case displayReactionSummary(itemID: TimelineItemIdentifier, key: String)
case displayEmojiPicker(itemID: TimelineItemIdentifier)
@@ -131,6 +137,8 @@ struct TimelineViewState: BindableState {
var linkPreviewsEnabled: Bool
var jumpToReadMarkerEnabled: Bool
var selection: TimelineSelectionState
let hasPredecessor: Bool
/// The `pinnedEventIDs` are used only to determine if an item is already pinned or not.
@@ -197,6 +205,33 @@ struct TimelineViewStateBindings {
var textToBeTranslated: String?
}
/// The state of the multi-selection of messages, active as soon as an item is selected.
struct TimelineSelectionState: Equatable {
static let limit = 30
/// Mirrors the `messageMultiSelectEnabled` feature flag.
var isEnabled = false
/// The event IDs of the selected items. Only remote messages can be selected.
var selectedEventIDs: Set<String> = []
var isActive: Bool {
!selectedEventIDs.isEmpty
}
var count: Int {
selectedEventIDs.count
}
var isAtLimit: Bool {
count >= Self.limit
}
func contains(_ eventID: String?) -> Bool {
guard let eventID else { return false }
return selectedEventIDs.contains(eventID)
}
}
struct TimelineItemActionMenuInfo: Equatable, Identifiable {
static func == (lhs: TimelineItemActionMenuInfo, rhs: TimelineItemActionMenuInfo) -> Bool {
lhs.id == rhs.id
@@ -319,6 +354,15 @@ enum ScrollDirection: Equatable {
}
extension TimelineViewState {
/// Multi-selection is only offered in the room and thread timelines.
var canSelectMessages: Bool {
guard selection.isEnabled else { return false }
return switch timelineKind {
case .live, .detached, .thread: true
case .pinned, .media: false
}
}
/// The user is at the bottom of a live timeline (no jump-to-bottom button needed).
var isAtBottomAndLive: Bool {
bindings.isScrolledToBottom && timelineState.isLive
@@ -20,6 +20,7 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
static let detachedTimelineSize: UInt16 = 100
static let focusTimelineToastIndicatorID = "RoomScreenFocusTimelineToastIndicator"
static let toastErrorID = "RoomScreenToastError"
static let selectionLimitIndicatorID = "RoomScreenSelectionLimitIndicator"
}
private let roomProxy: JoinedRoomProxyProtocol
@@ -102,6 +103,7 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
areThreadsEnabled: appSettings.threadsEnabled,
linkPreviewsEnabled: appSettings.linkPreviewsEnabled,
jumpToReadMarkerEnabled: appSettings.jumpToReadMarkerEnabled,
selection: .init(isEnabled: appSettings.messageMultiSelectEnabled),
hasPredecessor: roomProxy.predecessorRoom != nil,
pinnedEventIDs: roomProxy.infoPublisher.value.pinnedEventIDs,
emojiProvider: emojiProvider,
@@ -196,12 +198,20 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
}
case .displayTimelineItemMenu(let itemID):
timelineInteractionHandler.displayTimelineItemActionMenu(for: itemID)
case .handleTimelineItemMenuAction(let itemID, .selectMessages):
startSelection(itemID: itemID)
case .handleTimelineItemMenuAction(let itemID, let action):
timelineInteractionHandler.handleTimelineItemMenuAction(action, itemID: itemID)
case .redactConfirmed(let itemID, let reason):
state.bindings.redactConfirmationInfo = nil
// A blank reason is no reason at all, so don't send one.
timelineInteractionHandler.redact(itemID, reason: reason?.isBlank == false ? reason : nil)
case .startSelection(let itemID):
startSelection(itemID: itemID)
case .toggleSelection(let itemID):
toggleSelection(itemID: itemID)
case .clearSelection:
state.selection.selectedEventIDs.removeAll()
case .tappedOnSenderDetails(let sender):
handleTappedOnSenderDetails(sender: sender)
case .displayEmojiPicker(let itemID):
@@ -465,6 +475,7 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
switch callback {
case .updatedTimelineItems(let updatedItems, let isSwitchingTimelines):
buildTimelineViews(timelineItems: updatedItems, isSwitchingTimelines: isSwitchingTimelines)
reconcileSelection(with: updatedItems, isSwitchingTimelines: isSwitchingTimelines)
if !updatedItems.isEmpty {
analyticsService.signpost.finishTransaction(.openRoom)
@@ -584,6 +595,8 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
.weakAssign(to: \.state.jumpToReadMarkerEnabled, on: self)
.store(in: &cancellables)
setupSelectionSubscriptions()
userSession.clientProxy.timelineMediaVisibilityPublisher
.removeDuplicates()
.flatMap { [weak self] timelineMediaVisibility -> AnyPublisher<Bool, Never> in
@@ -1172,6 +1185,81 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
}
}
// MARK: - Selection
extension TimelineViewModel {
private func setupSelectionSubscriptions() {
appSettings.messageMultiSelectEnabledPublisher
.sink { [weak self] isEnabled in
self?.state.selection.isEnabled = isEnabled
if !isEnabled {
self?.state.selection.selectedEventIDs.removeAll()
}
}
.store(in: &cancellables)
}
private func startSelection(itemID: TimelineItemIdentifier) {
guard state.canSelectMessages, let eventID = selectableEventID(for: itemID) else { return }
// The composer is collapsed while selecting, so don't leave the microphone open behind it.
Task { await timelineInteractionHandler.stopRecordingVoiceMessageIfNeeded() }
actionsSubject.send(.composer(action: .removeFocus))
guard !state.selection.isAtLimit || state.selection.selectedEventIDs.contains(eventID) else {
showSelectionLimitToast()
return
}
state.selection.selectedEventIDs.insert(eventID)
}
private func toggleSelection(itemID: TimelineItemIdentifier) {
guard state.selection.isActive, let eventID = selectableEventID(for: itemID) else { return }
if state.selection.selectedEventIDs.contains(eventID) {
state.selection.selectedEventIDs.remove(eventID)
} else if state.selection.isAtLimit {
showSelectionLimitToast()
} else {
state.selection.selectedEventIDs.insert(eventID)
}
}
/// Drops selected items that are no longer selectable (e.g. redacted), or the whole selection
/// when the timeline is swapped, so the selection always refers to items that are on screen.
private func reconcileSelection(with timelineItems: [RoomTimelineItemProtocol], isSwitchingTimelines: Bool) {
guard state.selection.isActive else { return }
if isSwitchingTimelines {
state.selection.selectedEventIDs.removeAll()
return
}
let selectableEventIDs = timelineItems.compactMap { item -> String? in
guard let item = item as? EventBasedTimelineItemProtocol, item.isBulkSelectable else { return nil }
return item.id.eventID
}
state.selection.selectedEventIDs.formIntersection(selectableEventIDs)
}
/// The event ID of the item, when it is part of this timeline and can be bulk selected.
private func selectableEventID(for itemID: TimelineItemIdentifier) -> String? {
guard let item = timelineController.timelineItems.firstUsingStableID(itemID) as? EventBasedTimelineItemProtocol,
item.isBulkSelectable else {
return nil
}
return item.id.eventID
}
private func showSelectionLimitToast() {
userIndicatorController.submitIndicator(UserIndicator(id: Constants.selectionLimitIndicatorID,
type: .toast,
title: L10n.screenRoomMaximumMessagesSelected,
icon: \.info))
}
}
// MARK: - Mocks
extension TimelineViewModel {
@@ -339,6 +339,7 @@ struct TimelineItemMenu_Previews: PreviewProvider, TestablePreview {
pinnedEventIDs: [],
isViewSourceEnabled: true,
areThreadsEnabled: true,
isMultiSelectEnabled: false,
timelineKind: .live,
emojiProvider: EmojiProvider(appSettings: .volatile()))
guard let actions = provider.makeActions() else { return nil }
@@ -68,6 +68,7 @@ enum TimelineItemMenuAction: Identifiable, Hashable {
case reply(isThread: Bool)
case replyInThread
case forward(itemID: TimelineItemIdentifier)
case selectMessages
case viewSource
case report
case react
@@ -169,6 +170,8 @@ enum TimelineItemMenuAction: Identifiable, Hashable {
Label(L10n.actionReplyInThread, icon: \.threads)
case .forward:
Label(L10n.actionForward, icon: \.forward)
case .selectMessages:
Label(L10n.actionSelect, icon: \.check)
case .redact(let isMedia):
Label(isMedia ? L10n.actionDeleteFile : L10n.actionRemoveMessage, icon: \.delete)
case .viewSource:
@@ -17,6 +17,7 @@ struct TimelineItemMenuActionProvider {
let pinnedEventIDs: Set<String>
let isViewSourceEnabled: Bool
let areThreadsEnabled: Bool
let isMultiSelectEnabled: Bool
let timelineKind: TimelineKind
let emojiProvider: EmojiProviderProtocol
@@ -65,6 +66,10 @@ struct TimelineItemMenuActionProvider {
actions.append(.forward(itemID: item.id))
}
if isMultiSelectEnabled, item.isBulkSelectable {
actions.append(.selectMessages)
}
if item.isEditable, canCurrentUserSendMessage {
if item.supportsMediaCaption {
if item.hasMediaCaption {
@@ -9,6 +9,7 @@
import SwiftUI
struct LongPressWithFeedback: ViewModifier {
let isEnabled: Bool
let action: () -> Void
@State private var triggerTask: Task<Void, Never>?
@@ -17,7 +18,7 @@ struct LongPressWithFeedback: ViewModifier {
func body(content: Content) -> some View {
mainContent(content: content)
.gesture(LongPressGestureRepresentable { gesture in
.gesture(LongPressGestureRepresentable(isEnabled: isEnabled) { gesture in
switch gesture.state {
case .began:
handleLongPress(isPressing: true)
@@ -69,8 +70,10 @@ struct LongPressWithFeedback: ViewModifier {
}
extension View {
func longPressWithFeedback(action: @escaping () -> Void) -> some View {
modifier(LongPressWithFeedback(action: action))
/// Adds a long press gesture with scale and haptic feedback. Pass `isEnabled: false` to
/// disable the recogniser entirely, so that neither the feedback nor the action fire.
func longPressWithFeedback(isEnabled: Bool = true, action: @escaping () -> Void) -> some View {
modifier(LongPressWithFeedback(isEnabled: isEnabled, action: action))
}
}
@@ -127,6 +130,7 @@ struct LongPressWithFeedback_Previews: PreviewProvider, TestablePreview {
/// Fixes the issue on iOS 18 where LongPress conflicts with the scroll view
/// https://github.com/feedback-assistant/reports/issues/542#issuecomment-2581322968
private struct LongPressGestureRepresentable: UIGestureRecognizerRepresentable {
var isEnabled: Bool
var handle: (UILongPressGestureRecognizer) -> Void
func makeCoordinator(converter: CoordinateSpaceConverter) -> Coordinator {
@@ -137,10 +141,14 @@ private struct LongPressGestureRepresentable: UIGestureRecognizerRepresentable {
let gesture = UILongPressGestureRecognizer()
gesture.minimumPressDuration = 0.25
gesture.delegate = context.coordinator
gesture.isEnabled = true
gesture.isEnabled = isEnabled
return gesture
}
func updateUIGestureRecognizer(_ recognizer: UILongPressGestureRecognizer, context: Context) {
recognizer.isEnabled = isEnabled
}
func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) {
handle(recognizer)
}
@@ -8,60 +8,91 @@
import SwiftUI
/// How a timeline item takes part in an active multi-selection, for accessibility purposes.
enum TimelineItemAccessibilitySelection {
/// No selection is active, the item offers its regular message actions.
case none
/// A selection is active, the item acts as a toggle when it can be selected.
case selecting(isSelected: Bool)
}
private struct TimelineItemAccessibilityModifier: ViewModifier {
let timelineItem: RoomTimelineItemProtocol
let selection: TimelineItemAccessibilitySelection
let action: () -> Void
private var isSelecting: Bool {
if case .selecting = selection {
return true
}
return false
}
func body(content: Content) -> some View {
switch timelineItem {
case is PollRoomTimelineItem:
content
.accessibilityActions {
Button(L10n.commonMessageActions) {
action()
}
}
// The answers stay traversable on their own, unless the whole poll acts as a selection toggle.
if isSelecting {
interactions(for: content.accessibilityElement(children: .combine))
} else {
interactions(for: content)
}
// A gallery is a container so that each of its attachments can be focussed on its own.
// Everything that isn't an attachment is announced when entering it, as the caption and
// the send info are hidden where they're shown to avoid being read twice.
case let timelineItem as GalleryRoomTimelineItem:
content
.accessibilityElement(children: .contain)
interactions(for: content
.accessibilityElement(children: isSelecting ? .combine : .contain)
.accessibilityLabel { _ in
Text(timelineItem.sender.displayName ?? timelineItem.sender.id)
if let caption = timelineItem.content.caption, !caption.isBlank {
Text(caption)
}
Text(timelineItem.localizedSendInfo)
}
.accessibilityActions {
Button(L10n.commonMessageActions) {
action()
}
}
})
case let timelineItem as EventBasedTimelineItemProtocol:
content
interactions(for: content
.accessibilityRepresentation {
VStack(spacing: 8) {
Text(timelineItem.sender.displayName ?? timelineItem.sender.id)
content
}
}
.accessibilityElement(children: .combine)
.accessibilityActions {
Button(L10n.commonMessageActions) {
action()
}
}
.accessibilityElement(children: .combine))
default:
content
.accessibilityElement(children: .combine)
}
}
/// Offers the message actions, or turns the item into a selection toggle while selecting.
@ViewBuilder
private func interactions(for view: some View) -> some View {
switch selection {
case .none:
view
.accessibilityActions {
Button(L10n.commonMessageActions) {
action()
}
}
case .selecting(let isSelected):
if let item = timelineItem as? EventBasedTimelineItemProtocol, item.isBulkSelectable {
view
.accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)
.accessibilityAction(.default, action)
} else {
// Items that can't be selected are inert while selecting.
view
}
}
}
}
extension View {
func timelineItemAccessibility(_ timelineItem: RoomTimelineItemProtocol, action: @escaping () -> Void) -> some View {
modifier(TimelineItemAccessibilityModifier(timelineItem: timelineItem, action: action))
func timelineItemAccessibility(_ timelineItem: RoomTimelineItemProtocol,
selection: TimelineItemAccessibilitySelection = .none,
action: @escaping () -> Void) -> some View {
modifier(TimelineItemAccessibilityModifier(timelineItem: timelineItem, selection: selection, action: action))
}
}
@@ -42,6 +42,14 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
return context.viewState.pinnedEventIDs.contains(eventID)
}
private var isSelectionActive: Bool {
context.viewState.selection.isActive
}
private var isSelected: Bool {
context.viewState.selection.contains(timelineItem.id.eventID)
}
/// The base padding applied to bubbles on either side.
///
/// **Note:** This is on top of the insets applied to the cells by the table view.
@@ -53,6 +61,45 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
}
var body: some View {
HStack(spacing: 0) {
if isSelectionActive {
selectionIndicator
}
bubble
}
.padding(EdgeInsets(top: 1, leading: 8, bottom: 1, trailing: 8))
.background(isSelected ? Color.compound.bgAccentSelected : .clear)
.highlightedTimelineItem(isFocussed)
.overlay { selectionOverlay }
.animation(.elementDefault.disabledDuringTests(), value: isSelectionActive)
.onPreferenceChange(ContentScanningFailurePreferenceKey.self) { contentScanningFailure = $0 }
}
private var selectionIndicator: some View {
// The ZStack keeps the transition on the indicator's appearance rather than its checked state.
ZStack {
ListRowAccessory.multiSelection(isSelected)
.opacity(timelineItem.isBulkSelectable ? 1 : 0) // Keeps the bubbles aligned.
}
.padding(.leading, 8)
.transition(.move(edge: .leading).combined(with: .opacity))
.accessibilityHidden(true) // The bubble itself carries the selected state.
}
/// Captures every touch while selecting so the content's own gestures can't fire.
@ViewBuilder
private var selectionOverlay: some View {
if isSelectionActive {
Color.clear
.contentShape(Rectangle())
.onTapGesture { toggleSelection() }
.onLongPressGesture { toggleSelection() }
.accessibilityHidden(true)
}
}
private var bubble: some View {
ZStack(alignment: .trailingFirstTextBaseline) {
VStack(alignment: alignment, spacing: -8) {
if !timelineItem.isOutgoing, !isDM {
@@ -84,9 +131,6 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
.padding(.leading, bubbleAvatarPadding)
}
}
.padding(EdgeInsets(top: 1, leading: 8, bottom: 1, trailing: 8))
.highlightedTimelineItem(isFocussed)
.onPreferenceChange(ContentScanningFailurePreferenceKey.self) { contentScanningFailure = $0 }
}
@ViewBuilder
@@ -128,8 +172,12 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
// Figma overlaps reactions by 3
VStack(alignment: alignment, spacing: -3) {
messageBubbleWithActions
.timelineItemAccessibility(timelineItem) {
context.send(viewAction: .displayTimelineItemMenu(itemID: timelineItem.id))
.timelineItemAccessibility(timelineItem, selection: isSelectionActive ? .selecting(isSelected: isSelected) : .none) {
if isSelectionActive {
toggleSelection()
} else {
context.send(viewAction: .displayTimelineItemMenu(itemID: timelineItem.id))
}
}
// Do not display reactions in the pinned events timeline
@@ -141,6 +189,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
isLayoutRTL: timelineItem.isOutgoing)
// Workaround to stop the message long press stealing the touch from the reaction buttons
.onTapGesture { }
.accessibilityHidden(isSelectionActive)
}
if context.viewState.areThreadsEnabled,
@@ -150,6 +199,7 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
context.send(viewAction: .displayThread(itemID: timelineItem.id))
}
.padding(5)
.accessibilityHidden(isSelectionActive)
}
}
}
@@ -162,7 +212,8 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
// is no longer an issue on iOS 18. Note: it's fine for this to be empty, we handle
// specific taps within the timeline views themselves.
}
.longPressWithFeedback {
// The UIKit recogniser would still receive touches through the selection overlay.
.longPressWithFeedback(isEnabled: !isSelectionActive) {
context.send(viewAction: .displayTimelineItemMenu(itemID: timelineItem.id))
}
.swipeRightAction {
@@ -170,30 +221,38 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
.foregroundColor(.compound.iconPrimary)
.accessibilityHidden(true)
} shouldStartAction: {
timelineItem.canBeRepliedTo
!isSelectionActive && timelineItem.canBeRepliedTo
} action: {
context.send(viewAction: .handleTimelineItemMenuAction(itemID: timelineItem.id,
action: .reply(isThread: timelineItem.properties.isThreaded)))
}
.contextMenu {
let provider = TimelineItemMenuActionProvider(timelineItem: timelineItem,
canCurrentUserSendMessage: context.viewState.canCurrentUserSendMessage,
canCurrentUserRedactSelf: context.viewState.canCurrentUserRedactSelf,
canCurrentUserRedactOthers: context.viewState.canCurrentUserRedactOthers,
canCurrentUserPin: context.viewState.canCurrentUserPin,
pinnedEventIDs: context.viewState.pinnedEventIDs,
isViewSourceEnabled: context.viewState.isViewSourceEnabled,
areThreadsEnabled: context.viewState.areThreadsEnabled,
timelineKind: context.viewState.timelineKind,
emojiProvider: context.viewState.emojiProvider)
TimelineItemMacContextMenu(item: timelineItem, actionProvider: provider) { action in
context.send(viewAction: .handleTimelineItemMenuAction(itemID: timelineItem.id, action: action))
if !isSelectionActive {
macContextMenu
}
}
.pinnedIndicator(isPinned: isPinned, isOutgoing: timelineItem.isOutgoing)
.padding(.top, messageBubbleTopPadding)
}
@ViewBuilder
private var macContextMenu: some View {
let provider = TimelineItemMenuActionProvider(timelineItem: timelineItem,
canCurrentUserSendMessage: context.viewState.canCurrentUserSendMessage,
canCurrentUserRedactSelf: context.viewState.canCurrentUserRedactSelf,
canCurrentUserRedactOthers: context.viewState.canCurrentUserRedactOthers,
canCurrentUserPin: context.viewState.canCurrentUserPin,
pinnedEventIDs: context.viewState.pinnedEventIDs,
isViewSourceEnabled: context.viewState.isViewSourceEnabled,
areThreadsEnabled: context.viewState.areThreadsEnabled,
isMultiSelectEnabled: context.viewState.canSelectMessages,
timelineKind: context.viewState.timelineKind,
emojiProvider: context.viewState.emojiProvider)
TimelineItemMacContextMenu(item: timelineItem, actionProvider: provider) { action in
context.send(viewAction: .handleTimelineItemMenuAction(itemID: timelineItem.id, action: action))
}
}
var messageBubble: some View {
contentWithReply
.timelineItemSendInfo(timelineItem: timelineItem,
@@ -238,6 +297,11 @@ struct TimelineItemBubbledStylerView<Content: View>: View {
}
}
private func toggleSelection() {
guard timelineItem.isBulkSelectable else { return }
context.send(viewAction: .toggleSelection(itemID: timelineItem.id))
}
private var messageBubbleTopPadding: CGFloat {
guard timelineItem.isOutgoing || isDM else { return 0 }
return timelineGroupStyle == .single || timelineGroupStyle == .first ? 8 : 0
@@ -398,6 +462,26 @@ struct TimelineItemBubbledStylerView_Previews: PreviewProvider, TestablePreview
static let unsafeViewModel = TimelineViewModel.mock(contentScannerService: ContentScannerServiceMock(.init(scanResult: false)))
static let selectingViewModel: TimelineViewModel = {
let appSettings = AppSettings.volatile()
appSettings.messageMultiSelectEnabled = true
let viewModel = TimelineViewModel(roomProxy: JoinedRoomProxyMock(.init()),
focussedEventID: nil,
timelineController: TimelineControllerMock(.init()),
userSession: UserSessionMock(.init()),
mediaPlayerProvider: MediaPlayerProviderMock(),
userIndicatorController: UserIndicatorControllerMock(),
appMediator: AppMediatorMock(.init()),
appSettings: appSettings,
analyticsService: AnalyticsServiceMock(.init()),
emojiProvider: EmojiProvider(appSettings: appSettings),
linkMetadataProvider: LinkMetadataProvider(),
timelineControllerFactory: TimelineControllerFactoryMock(.init()))
viewModel.state.selection.selectedEventIDs = ["selected"]
return viewModel
}()
static var previews: some View {
mockTimeline
.previewDisplayName("Mock Timeline")
@@ -427,6 +511,39 @@ struct TimelineItemBubbledStylerView_Previews: PreviewProvider, TestablePreview
.previewDisplayName("Pinned messages")
.previewLayout(.fixed(width: 390, height: 1150))
.padding(.bottom, 20)
selection
.previewDisplayName("Selection")
}
static var selection: some View {
VStack(spacing: 0) {
RoomTimelineItemView(viewState: .init(item: TextRoomTimelineItem(id: .event(uniqueID: .init("1"), eventOrTransactionID: .eventID("selected")),
timestamp: .mock,
isOutgoing: false,
isEditable: false,
canBeRepliedTo: true,
sender: .init(id: "@alice:matrix.org", displayName: "Alice"),
content: .init(body: "A selected message.")),
groupStyle: .single))
RoomTimelineItemView(viewState: .init(item: TextRoomTimelineItem(id: .event(uniqueID: .init("2"), eventOrTransactionID: .eventID("unselected")),
timestamp: .mock,
isOutgoing: true,
isEditable: false,
canBeRepliedTo: true,
sender: .init(id: "@bob:matrix.org"),
content: .init(body: "A message that isn't selected.")),
groupStyle: .single))
RoomTimelineItemView(viewState: .init(item: RedactedRoomTimelineItem(id: .event(uniqueID: .init("3"), eventOrTransactionID: .eventID("redacted")),
body: "Message removed",
timestamp: .mock,
isOutgoing: false,
isEditable: false,
canBeRepliedTo: false,
sender: .init(id: "@alice:matrix.org", displayName: "Alice")),
groupStyle: .single))
}
.environmentObject(selectingViewModel.context)
.environment(\.timelineContext, selectingViewModel.context)
}
static var mockTimeline: some View {
@@ -0,0 +1,27 @@
//
// Copyright 2026 Element Creations Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Compound
import SwiftUI
/// The navigation bar content shown while messages are being selected in a timeline.
struct TimelineSelectionToolbar: ToolbarContent {
let count: Int
let onCancel: () -> Void
var body: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel, role: .cancel, action: onCancel)
}
ToolbarItem(placement: .principal) {
Text(L10n.screenRoomSelectionCount(count))
.font(.compound.bodyLGSemibold)
.foregroundStyle(.compound.textPrimary)
}
}
}
@@ -41,6 +41,7 @@ struct TimelineView: View {
pinnedEventIDs: timelineContext.viewState.pinnedEventIDs,
isViewSourceEnabled: timelineContext.viewState.isViewSourceEnabled,
areThreadsEnabled: timelineContext.viewState.areThreadsEnabled,
isMultiSelectEnabled: timelineContext.viewState.canSelectMessages,
timelineKind: timelineContext.viewState.timelineKind,
emojiProvider: timelineContext.viewState.emojiProvider)
.makeActions()