Create poll UX (#1571)

* Add poll attachment button

* Add poll creation feature flag

* Setup navigation to CreatePollScreen

* Add create/cancel actions

* Add create poll screen ui skeleton

* Add bindings in CreatePollScreen

* Add logics in CreatePollScreen

* Cleanup code

* Fix option deletion crash

* Fix conflicts

* Add create poll logic

* Add localisations

* Fix test build errors

* Fix crash

* Add UTs

* Add accessibility IDs

* Add ui tests

* Add 240 char limit

* Fix addOption hide behavior

* Add maxNumberOfOptions

* Cleanup code

* Move delete workaround in the view model

* Use compound delete icon
This commit is contained in:
Alfonso Grillo
2023-08-30 11:23:30 +02:00
committed by GitHub
parent e08d7b491e
commit a2623dd254
41 changed files with 846 additions and 3 deletions
@@ -24,6 +24,7 @@ enum ComposerToolbarViewModelAction {
case displayMediaPicker
case displayDocumentPicker
case displayLocationPicker
case displayPollForm
case handlePasteOrDrop(provider: NSItemProvider)
@@ -40,6 +41,7 @@ enum ComposerToolbarViewAction {
case displayMediaPicker
case displayDocumentPicker
case displayLocationPicker
case displayPollForm
case handlePasteOrDrop(provider: NSItemProvider)
}
@@ -78,6 +78,8 @@ final class ComposerToolbarViewModel: ComposerToolbarViewModelType, ComposerTool
actionsSubject.send(.displayDocumentPicker)
case .displayLocationPicker:
actionsSubject.send(.displayLocationPicker)
case .displayPollForm:
actionsSubject.send(.displayPollForm)
case .handlePasteOrDrop(let provider):
actionsSubject.send(.handlePasteOrDrop(provider: provider))
}
@@ -65,6 +65,15 @@ struct RoomAttachmentPicker: View {
PickerLabel(title: L10n.screenRoomAttachmentSourceLocation, icon: Image(asset: Asset.Images.locationPin))
}
.accessibilityLabel(A11yIdentifiers.roomScreen.attachmentPickerLocation)
if ServiceLocator.shared.settings.pollsCreationEnabled {
Button {
context.showAttachmentPopover = false
context.send(viewAction: .displayPollForm)
} label: {
PickerLabel(title: L10n.screenRoomAttachmentSourcePoll, icon: Image(asset: Asset.Images.timelinePollAttachment))
}
}
}
.padding(.top, isPresented ? 20 : 0)
.background {
@@ -0,0 +1,61 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import SwiftUI
struct CreatePollScreenCoordinatorParameters { }
enum CreatePollScreenCoordinatorAction {
case cancel
case create(question: String, options: [String], pollKind: Poll.Kind)
}
final class CreatePollScreenCoordinator: CoordinatorProtocol {
private let parameters: CreatePollScreenCoordinatorParameters
private var viewModel: CreatePollScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<CreatePollScreenCoordinatorAction, Never> = .init()
private var cancellables: Set<AnyCancellable> = .init()
var actions: AnyPublisher<CreatePollScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: CreatePollScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = CreatePollScreenViewModel()
}
func start() {
viewModel.actions.sink { [weak self] action in
MXLog.info("Coordinator: received view model action: \(action)")
guard let self else { return }
switch action {
case let .create(question, options, pollKind):
self.actionsSubject.send(.create(question: question, options: options, pollKind: pollKind))
case .cancel:
self.actionsSubject.send(.cancel)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(CreatePollScreen(context: viewModel.context))
}
}
@@ -0,0 +1,49 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum CreatePollScreenViewModelAction {
case create(question: String, options: [String], pollKind: Poll.Kind)
case cancel
}
struct CreatePollScreenViewState: BindableState {
let maxNumberOfOptions = 20
var bindings: CreatePollScreenViewStateBindings = .init()
}
struct CreatePollScreenViewStateBindings {
var question = ""
var options: [Option] = [.init(), .init()]
var isUndisclosed = false
struct Option: Identifiable, Equatable {
let id = UUID()
var text = ""
}
var isCreateButtonDisabled: Bool {
question.isEmpty || options.count < 2 || options.contains { $0.text.isEmpty }
}
}
enum CreatePollScreenViewAction {
case cancel
case create
case deleteOption(index: Int)
case addOption
}
@@ -0,0 +1,59 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import SwiftUI
typealias CreatePollScreenViewModelType = StateStoreViewModel<CreatePollScreenViewState, CreatePollScreenViewAction>
class CreatePollScreenViewModel: CreatePollScreenViewModelType, CreatePollScreenViewModelProtocol {
private var actionsSubject: PassthroughSubject<CreatePollScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<CreatePollScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init() {
super.init(initialViewState: .init())
}
// MARK: - Public
override func process(viewAction: CreatePollScreenViewAction) {
switch viewAction {
case .create:
actionsSubject.send(.create(question: state.bindings.question,
options: state.bindings.options.map(\.text),
pollKind: state.bindings.isUndisclosed ? .undisclosed : .disclosed))
case .cancel:
actionsSubject.send(.cancel)
case .deleteOption(let index):
// fixes a crash that caused an index out of range when an option with the keyboard focus was deleted
Task {
try await Task.sleep(for: .milliseconds(100))
guard state.bindings.options.indices.contains(index) else {
return
}
state.bindings.options.remove(at: index)
}
case .addOption:
guard state.bindings.options.count < state.maxNumberOfOptions else {
return
}
state.bindings.options.append(.init())
}
}
}
@@ -0,0 +1,23 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
@MainActor
protocol CreatePollScreenViewModelProtocol {
var actions: AnyPublisher<CreatePollScreenViewModelAction, Never> { get }
var context: CreatePollScreenViewModelType.Context { get }
}
@@ -0,0 +1,168 @@
//
// Copyright 2022 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Compound
import SwiftUI
struct CreatePollScreen: View {
@ObservedObject var context: CreatePollScreenViewModel.Context
@FocusState var focus: Focus?
enum Focus: Hashable {
case question
case option(index: Int)
}
var body: some View {
Form {
questionSection
optionsSection
showResultsSection
}
.compoundForm()
.scrollDismissesKeyboard(.immediately)
.environment(\.editMode, .constant(.active))
.navigationTitle(L10n.screenCreatePollTitle)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
.animation(.elementDefault, value: context.options)
}
// MARK: - Private
private var questionSection: some View {
Section(L10n.screenCreatePollQuestionDesc) {
TextField(text: $context.question) {
Text(L10n.screenCreatePollQuestionHint)
.compoundFormTextFieldPlaceholder()
}
.introspect(.textField, on: .iOS(.v16)) { textField in
textField.clearButtonMode = .whileEditing
}
.textFieldStyle(.compoundForm)
.focused($focus, equals: .question)
.accessibilityIdentifier(A11yIdentifiers.createPollScreen.question)
}
.compoundFormSection()
}
private var optionsSection: some View {
Section {
ForEach(context.options) { option in
if let index = context.options.firstIndex(of: option) {
CreatePollOptionView(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.createPollScreen.optionID(index))
}
}
.onMove { offsets, toOffset in
context.options.move(fromOffsets: offsets, toOffset: toOffset)
}
if context.options.count < context.viewState.maxNumberOfOptions {
Button(L10n.screenCreatePollAddOptionBtn) {
context.send(viewAction: .addOption)
}
.accessibilityIdentifier(A11yIdentifiers.createPollScreen.addOption)
}
}
.compoundFormSection()
}
private var showResultsSection: some View {
Section {
Toggle(L10n.screenCreatePollAnonymousDesc, isOn: $context.isUndisclosed)
.accessibilityIdentifier(A11yIdentifiers.createPollScreen.pollKind)
}
.compoundFormSection()
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .navigationBarLeading) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionCreate) {
context.send(viewAction: .create)
}
.disabled(context.viewState.bindings.isCreateButtonDisabled)
.accessibilityIdentifier(A11yIdentifiers.createPollScreen.create)
}
}
}
private struct CreatePollOptionView: View {
@Environment(\.editMode) var editMode
@Binding var text: String
let placeholder: String
let canDeleteItem: Bool
let deleteAction: () -> Void
var body: some View {
HStack {
if editMode?.wrappedValue == .active {
Button(action: deleteAction) {
CompoundIcon(\.delete)
.font(.system(size: 24))
.foregroundColor(.compound.iconCriticalPrimary)
}
.disabled(!canDeleteItem)
.buttonStyle(PlainButtonStyle())
}
TextField(text: $text) {
Text(placeholder)
.compoundFormTextFieldPlaceholder()
}
.introspect(.textField, on: .iOS(.v16)) { textField in
textField.clearButtonMode = .whileEditing
}
.textFieldStyle(.compoundForm)
}
}
}
// MARK: - Previews
struct CreatePollScreen_Previews: PreviewProvider {
static let viewModel = CreatePollScreenViewModel()
static var previews: some View {
NavigationStack {
CreatePollScreen(context: viewModel.context)
}
}
}
private extension Binding where Value == String {
func limited(to limit: Int) -> Self {
.init {
wrappedValue
} set: { newValue in
wrappedValue = String(newValue.prefix(limit))
}
}
}
@@ -31,6 +31,7 @@ enum RoomScreenCoordinatorAction {
case presentMediaUploadPreviewScreen(URL)
case presentRoomDetails
case presentLocationPicker
case presentPollForm
case presentLocationViewer(body: String, geoURI: GeoURI, description: String?)
case presentEmojiPicker(itemID: TimelineItemIdentifier, selectedEmojis: Set<String>)
case presentRoomMemberDetails(member: RoomMemberProxyProtocol)
@@ -86,6 +87,8 @@ final class RoomScreenCoordinator: CoordinatorProtocol {
actionsSubject.send(.presentMediaUploadPicker(.documents))
case .displayLocationPicker:
actionsSubject.send(.presentLocationPicker)
case .displayPollForm:
actionsSubject.send(.presentPollForm)
case .displayMediaUploadPreviewScreen(let url):
actionsSubject.send(.presentMediaUploadPreviewScreen(url))
case .displayRoomMemberDetails(let member):
@@ -28,6 +28,7 @@ enum RoomScreenViewModelAction {
case displayMediaPicker
case displayDocumentPicker
case displayLocationPicker
case displayPollForm
case displayMediaUploadPreviewScreen(url: URL)
case displayRoomMemberDetails(member: RoomMemberProxyProtocol)
case displayMessageForwarding(itemID: TimelineItemIdentifier)
@@ -158,6 +158,8 @@ class RoomScreenViewModel: RoomScreenViewModelType, RoomScreenViewModelProtocol
actionsSubject.send(.displayDocumentPicker)
case .displayLocationPicker:
actionsSubject.send(.displayLocationPicker)
case .displayPollForm:
actionsSubject.send(.displayPollForm)
case .handlePasteOrDrop(let provider):
handlePasteOrDrop(provider)
case .composerModeChanged(mode: let mode):
@@ -52,6 +52,7 @@ protocol DeveloperOptionsProtocol: AnyObject {
var swiftUITimelineEnabled: Bool { get set }
var pollsInTimelineEnabled: Bool { get set }
var richTextEditorEnabled: Bool { get set }
var pollsCreationEnabled: Bool { get set }
}
extension AppSettings: DeveloperOptionsProtocol { }
@@ -70,6 +70,10 @@ struct DeveloperOptionsScreen: View {
Toggle(isOn: $context.pollsInTimelineEnabled) {
Text("View polls in timeline")
}
Toggle(isOn: $context.pollsCreationEnabled) {
Text("View polls creation flow")
}
}
Section("Rich Text Editor") {