Files
element-x-ios/ElementX/Sources/Services/Timeline/TimelineItems/EventBasedTimelineItemProtocol.swift
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

133 lines
4.6 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 Foundation
import UIKit
nonisolated protocol EventBasedTimelineItemProtocol: RoomTimelineItemProtocol, CustomStringConvertible {
var timestamp: Date { get }
var isOutgoing: Bool { get }
var isEditable: Bool { get }
var canBeRepliedTo: Bool { get }
var sender: TimelineItemSender { get }
var body: String { get }
var properties: RoomTimelineItemProperties { get }
}
nonisolated extension EventBasedTimelineItemProtocol {
var description: String {
"\(String(describing: Self.self)): id: \(id), timestamp: \(timestamp), isOutgoing: \(isOutgoing), properties: \(properties)"
}
var isForwardable: Bool {
isRemoteMessage && !(self is PollRoomTimelineItem) && !(self is LiveLocationRoomTimelineItem)
}
/// Whether the item can be part of a multi-selection of messages.
var isBulkSelectable: Bool {
isRemoteMessage
&& !isRedacted
&& !hasFailedDecryption
&& !(self is StateRoomTimelineItem)
&& !(self is UnsupportedRoomTimelineItem)
&& !(self is LiveLocationRoomTimelineItem)
}
var isRemoteMessage: Bool {
id.eventID != nil
}
var isRedacted: Bool {
self is RedactedRoomTimelineItem
}
var pollIfAvailable: Poll? {
(self as? PollRoomTimelineItem)?.poll
}
var hasStatusIcon: Bool {
hasFailedToSend || properties.encryptionAuthenticity != nil || properties.encryptionForwarder != nil
}
var hasFailedToSend: Bool {
properties.deliveryStatus?.isSendingFailed == true
}
var hasFailedDecryption: Bool {
self is EncryptedRoomTimelineItem
}
var timelineMenuDescription: String {
switch self {
case is VoiceMessageRoomTimelineItem:
return L10n.commonVoiceMessage
default:
return body.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
/// The inline area to reserve at the trailing edge of the message text so the
/// bubble's natural size accommodates the timestamp (which is overlaid on the
/// bubble's bottom-trailing corner). Text wraps around this area: if it fits on
/// the last line, the timestamp tucks inline; otherwise it sits on a new line.
/// Sized using the same dynamic-type-aware font as the rendered timestamp.
var trailingReservedSize: CGSize {
let textStyle: UIFont.TextStyle = .caption1 // matches compound.bodyXS
let font = UIFont.preferredFont(forTextStyle: textStyle)
let textSize = (localizedSendInfo as NSString).size(withAttributes: [.font: font])
var width = textSize.width
var height = textSize.height
if hasStatusIcon {
// CompoundIcon at .xSmall is 16pt at the base size; scale with the same UIFontMetrics
// as the icon's `relativeTo: .compound.bodyXS` modifier, plus the 4pt HStack spacing.
let iconSize = UIFontMetrics(forTextStyle: textStyle).scaledValue(for: 16)
width += iconSize + 4
height = max(height, iconSize)
}
// Small visual gap between the text content and the overlaid timestamp.
width += 4
return CGSize(width: ceil(width), height: ceil(height))
}
/// contains the timestamp and an optional edited localised prefix
/// example: (edited) 12:17 PM
var localizedSendInfo: String {
var start = ""
if properties.isEdited {
start = "\(L10n.commonEditedSuffix) "
}
return start + timestamp.formattedTime()
}
var isCopyable: Bool {
guard let messageBasedItem = self as? EventBasedMessageTimelineItemProtocol else {
return false
}
switch messageBasedItem.contentType {
case .audio, .file, .image, .video, .location, .voice, .gallery:
return false
case .text, .emote, .notice:
return true
}
}
var supportsMediaCaption: Bool {
guard let messageBasedItem = self as? EventBasedMessageTimelineItemProtocol else { return false }
return messageBasedItem.supportsMediaCaption
}
var hasMediaCaption: Bool {
guard let messageBasedItem = self as? EventBasedMessageTimelineItemProtocol else { return false }
return messageBasedItem.hasMediaCaption
}
}