Files
element-x-ios/ElementX/Sources/Screens/CreatePollScreen/View/PollFormScreen.swift
T
Mauro a520d94760 Swift 6 Migration (#5733)
* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
2026-06-18 17:55:31 +02:00

244 lines
9.5 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 Compound
import SwiftUI
struct PollFormScreen: View {
@Bindable var context: PollFormScreenViewModel.Context
@FocusState var focus: Focus?
enum Focus: Hashable {
case question
case option(index: Int)
}
var body: some View {
Form {
questionSection
optionsSection
showResultsSection
deletePollSection
}
.trackAnalyticsIfNeeded(context: context)
.compoundList()
.scrollDismissesKeyboard(.immediately)
.environment(\.editMode, .constant(.active))
.navigationTitle(context.viewState.navigationTitle)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.animation(.elementDefault, value: context.options)
.interactiveDismissDisabled(context.viewState.formContentHasChanged)
.alert(item: $context.alertInfo)
}
// MARK: - Private
private var questionSection: some View {
Section {
ListRow(label: .plain(title: L10n.screenCreatePollQuestionHint),
kind: .textField(text: $context.question, axis: .vertical))
.focused($focus, equals: .question)
.accessibilityIdentifier(A11yIdentifiers.pollFormScreen.question)
} header: {
Text(L10n.screenCreatePollQuestionDesc)
.compoundListSectionHeader()
}
}
private var optionsSection: some View {
Section {
ForEach(context.options) { option in
if let index = context.options.firstIndex(of: option) {
PollFormOptionRow(text: $context.options[index].text.limited(to: 240),
placeholder: L10n.screenCreatePollAnswerHint(index + 1),
canDeleteItem: context.options.count > 2) {
if case .option(let focusedIndex) = focus, focusedIndex == index {
focus = nil
}
context.send(viewAction: .deleteOption(index: index))
}
.focused($focus, equals: .option(index: index))
.accessibilityIdentifier(A11yIdentifiers.pollFormScreen.optionID(index))
.onChange(of: context.options[index].text) { _, newOptionText in
guard let lastCharacter = newOptionText.last, lastCharacter.isNewline else {
return
}
context.options[index].text.removeLast()
submitOption(at: index)
}
.onSubmit { // onSubmit is still called when using the return key on a hardware keyboard
submitOption(at: index)
}
.submitLabel(index == context.options.endIndex - 1 ? .done : .next)
}
}
.onMove { offsets, toOffset in
context.options.move(fromOffsets: offsets, toOffset: toOffset)
}
if context.options.count < context.viewState.maxNumberOfOptions {
ListRow(label: .plain(title: L10n.screenCreatePollAddOptionBtn),
kind: .button {
context.send(viewAction: .addOption)
focus = context.options.indices.last.map { .option(index: $0) }
})
.accessibilityIdentifier(A11yIdentifiers.pollFormScreen.addOption)
}
} header: {
Text(L10n.screenCreatePollOptionsSectionTitle)
.compoundListSectionHeader()
}
// Disables animations when the text view resizes for multiline
.animation(.noAnimation, value: UUID())
}
private func submitOption(at index: Array<PollFormScreenViewStateBindings.Option>.Index) {
let nextOptionIndex = index == context.options.endIndex - 1 ? nil : index + 1
focus = nextOptionIndex.map { .option(index: $0) }
}
private var showResultsSection: some View {
Section {
ListRow(label: .plain(title: L10n.screenCreatePollAnonymousDesc),
kind: .toggle($context.isUndisclosed))
.accessibilityIdentifier(A11yIdentifiers.pollFormScreen.pollKind)
} header: {
Text(L10n.screenCreatePollSettingsSectionTitle)
.compoundListSectionHeader()
}
}
@ViewBuilder
private var deletePollSection: some View {
switch context.viewState.mode {
case .edit:
Section {
ListRow(label: .plain(title: L10n.actionDeletePoll, role: .destructive),
kind: .button { context.send(viewAction: .delete) })
}
case .new:
EmptyView()
}
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .navigationBarLeading) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
ToolbarItem(placement: .confirmationAction) {
Button(context.viewState.submitButtonTitle) {
context.send(viewAction: .submit)
}
.disabled(context.viewState.isSubmitButtonDisabled)
.accessibilityIdentifier(A11yIdentifiers.pollFormScreen.submit)
}
}
}
private extension View {
@ViewBuilder
func trackAnalyticsIfNeeded(context: PollFormScreenViewModel.Context) -> some View {
switch context.viewState.mode {
case .edit:
self
case .new:
track(screen: .CreatePollView)
}
}
}
private struct PollFormOptionRow: View {
@Environment(\.editMode) var editMode
@Binding var text: String
let placeholder: String
let canDeleteItem: Bool
let deleteAction: () -> Void
var body: some View {
ListRow(kind: .custom {
HStack(spacing: 16) {
if editMode?.wrappedValue == .active {
Button(role: .destructive, action: deleteAction) {
CompoundIcon(\.delete)
}
.disabled(!canDeleteItem)
.buttonStyle(.compound(.textLink))
.accessibilityLabel(L10n.screenCreatePollRemoveAccessibilityLabel(L10n.screenCreatePollOptionAccessibilityLabel(placeholder, text)))
}
TextField(text: $text, axis: .vertical) {
Text(placeholder)
.compoundTextFieldPlaceholder()
}
// For some reason the placeholder is always read by voice over even if I disable or override the label, so if the text is empty we use an empy accessibility label
.accessibilityLabel(text.isEmpty ? "" : L10n.screenCreatePollOptionAccessibilityLabel(placeholder, text))
// Allows the move action voice over to give priority to this field over the remove button
.accessibilitySortPriority(1)
.tint(.compound.iconAccentTertiary)
.alignmentGuide(.listRowSeparatorLeading) { _ in 0 }
}
.padding(.horizontal, ListRowPadding.horizontal)
.padding(.vertical, ListRowPadding.vertical)
})
}
}
// MARK: - Previews
struct PollFormScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = makeViewModel(mode: .new(topic: nil))
static let editViewModel = makeViewModel(mode: .edit(eventID: "1234", poll: poll))
static let poll = Poll(question: "Cats or Dogs?",
kind: .disclosed,
maxSelections: 1,
options: [
.init(id: "0", text: "Cats", votes: 0, allVotes: 0, isSelected: false, isWinning: false),
.init(id: "0", text: "Dogs", votes: 0, allVotes: 0, isSelected: false, isWinning: false),
.init(id: "0", text: "Fish", votes: 0, allVotes: 0, isSelected: false, isWinning: false)
],
votes: [:],
endDate: nil,
createdByAccountOwner: true)
static var previews: some View {
ElementNavigationStack {
PollFormScreen(context: viewModel.context)
}
.previewDisplayName("New")
ElementNavigationStack {
PollFormScreen(context: editViewModel.context)
}
.previewDisplayName("Edit")
}
static func makeViewModel(mode: PollFormMode) -> PollFormScreenViewModel {
PollFormScreenViewModel(mode: mode,
timelineController: TimelineControllerMock(.init()),
analytics: AnalyticsServiceMock(.init()),
userIndicatorController: UserIndicatorControllerMock())
}
}
private extension Binding where Value == String {
func limited(to limit: Int) -> Self {
.init {
wrappedValue
} set: { newValue in
wrappedValue = String(newValue.prefix(limit))
}
}
}