-
-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathComposeContentViewModel.swift
More file actions
828 lines (726 loc) · 30.7 KB
/
ComposeContentViewModel.swift
File metadata and controls
828 lines (726 loc) · 30.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//
// ComposeContentViewModel.swift
//
//
// Created by MainasuK on 22/9/30.
//
import os.log
import UIKit
import Combine
import CoreDataStack
import Meta
import MetaTextKit
import MastodonMeta
import MastodonCore
import MastodonSDK
import MastodonLocalization
public protocol ComposeContentViewModelDelegate: AnyObject {
func composeContentViewModel(_ viewModel: ComposeContentViewModel, handleAutoComplete info: ComposeContentViewModel.AutoCompleteInfo) -> Bool
}
public final class ComposeContentViewModel: NSObject, ObservableObject {
public enum ComposeContext {
case composeStatus
case editStatus(status: Status, statusSource: Mastodon.Entity.StatusSource)
}
let logger = Logger(subsystem: "ComposeContentViewModel", category: "ViewModel")
var disposeBag = Set<AnyCancellable>()
// tableViewCell
let composeReplyToTableViewCell = ComposeReplyToTableViewCell()
let composeContentTableViewCell = ComposeContentTableViewCell()
// input
let context: AppContext
let composeContext: ComposeContext
let destination: Destination
weak var delegate: ComposeContentViewModelDelegate?
@Published var viewLayoutFrame = ViewLayoutFrame()
// author (me)
@Published var authContext: AuthContext
// auto-complete info
@Published var autoCompleteRetryLayoutTimes = 0
@Published var autoCompleteInfo: AutoCompleteInfo? = nil
// emoji
var customEmojiPickerDiffableDataSource: UICollectionViewDiffableDataSource<CustomEmojiPickerSection, CustomEmojiPickerItem>?
// output
// limit
@Published public var maxTextInputLimit = 500
// content
public weak var contentMetaText: MetaText? {
didSet {
guard let textView = contentMetaText?.textView else { return }
customEmojiPickerInputViewModel.configure(textInput: textView)
}
}
// allow dismissing the compose view without confirmation if content == intialContent
@Published public var initialContent = ""
@Published public var content = ""
@Published public var contentWeightedLength = 0
@Published public var isContentEmpty = true
@Published public var isContentValid = true
@Published public var isContentEditing = false
// content warning
weak var contentWarningMetaText: MetaText? {
didSet {
guard let textView = contentWarningMetaText?.textView else { return }
customEmojiPickerInputViewModel.configure(textInput: textView)
}
}
@Published public var isContentWarningActive = false
@Published public var contentWarning = ""
@Published public var contentWarningWeightedLength = 0 // set 0 when not composing
@Published public var isContentWarningEditing = false
// author
@Published var avatarURL: URL?
@Published var name: MetaContent = PlaintextMetaContent(string: "")
@Published var username: String = ""
// attachment
@Published public var attachmentViewModels: [AttachmentViewModel] = []
@Published public var maxMediaAttachmentLimit = 4
@Published public internal(set) var maxImageMediaSizeLimitInByte = 10 * 1024 * 1024 // 10 MiB
// poll
@Published public var isPollActive = false
@Published public var pollOptions: [PollComposeItem.Option] = {
// initial with 2 options
var options: [PollComposeItem.Option] = []
options.append(PollComposeItem.Option())
options.append(PollComposeItem.Option())
return options
}()
@Published public var pollExpireConfigurationOption: PollComposeItem.ExpireConfiguration.Option = .oneDay
@Published public var pollMultipleConfigurationOption: PollComposeItem.MultipleConfiguration.Option = false
@Published public var maxPollOptionLimit = 4
// emoji
@Published var isEmojiActive = false
let customEmojiViewModel: EmojiService.CustomEmojiViewModel?
let customEmojiPickerInputViewModel = CustomEmojiPickerInputViewModel()
@Published var isLoadingCustomEmoji = false
// visibility
@Published public var visibility: Mastodon.Entity.Status.Visibility
@Published public var isVisibilityButtonEnabled = false
// language
@Published public var language: String
@Published public private(set) var recentLanguages: [String]
// UI & UX
@Published var replyToCellFrame: CGRect = .zero
@Published var contentCellFrame: CGRect = .zero
@Published var contentTextViewFrame: CGRect = .zero
@Published var scrollViewState: ScrollViewState = .fold
@Published var characterCount: Int = 0
@Published public private(set) var isPublishBarButtonItemEnabled = true
@Published var isAttachmentButtonEnabled = false
@Published var isPollButtonEnabled = false
@Published public private(set) var shouldDismiss = true
// size limit
public var sizeLimit: AttachmentViewModel.SizeLimit {
AttachmentViewModel.SizeLimit(
image: maxImageMediaSizeLimitInByte,
video: nil
)
}
public init(
context: AppContext,
authContext: AuthContext,
composeContext: ComposeContext,
destination: Destination,
initialContent: String
) {
self.context = context
self.authContext = authContext
self.destination = destination
self.composeContext = composeContext
self.visibility = {
// default private when user locked
var visibility: Mastodon.Entity.Status.Visibility = {
guard let author = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: context.managedObjectContext)?.user else {
return .public
}
return author.locked ? .private : .public
}()
// set visibility for reply post
if case .reply(let record) = destination {
context.managedObjectContext.performAndWait {
guard let status = record.object(in: context.managedObjectContext) else {
assertionFailure()
return
}
let repliedStatusVisibility = status.visibility
switch repliedStatusVisibility {
case .public, .unlisted:
// keep default
break
case .private:
visibility = .private
case .direct:
visibility = .direct
case ._other:
assertionFailure()
break
}
}
}
return visibility
}()
self.customEmojiViewModel = context.emojiService.dequeueCustomEmojiViewModel(
for: authContext.mastodonAuthenticationBox.domain
)
if case let ComposeContext.editStatus(status, _) = composeContext {
if status.isContentSensitive {
isContentWarningActive = true
contentWarning = status.spoilerText ?? ""
}
if let poll = status.poll {
isPollActive = !poll.expired
pollMultipleConfigurationOption = poll.multiple
if let pollExpiresAt = poll.expiresAt {
pollExpireConfigurationOption = .init(closestDateToExpiry: pollExpiresAt)
}
pollOptions = poll.options.sortedByIndex().map {
let option = PollComposeItem.Option()
option.text = $0.title
return option
}
}
}
let recentLanguages = context.settingService.currentSetting.value?.recentLanguages ?? []
self.recentLanguages = recentLanguages
self.language = recentLanguages.first ?? Locale.current.languageCode ?? "en"
super.init()
// end init
// setup initial value
let initialContentWithSpace = initialContent.isEmpty ? "" : initialContent + " "
switch destination {
case .reply(let record):
context.managedObjectContext.performAndWait {
guard let status = record.object(in: context.managedObjectContext) else {
assertionFailure()
return
}
let author = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: context.managedObjectContext)?.user
var mentionAccts: [String] = []
if author?.id != status.author.id {
mentionAccts.append("@" + status.author.acct)
}
let mentions = status.mentions
.filter { author?.id != $0.id }
for mention in mentions {
let acct = "@" + mention.acct
guard !mentionAccts.contains(acct) else { continue }
mentionAccts.append(acct)
}
for acct in mentionAccts {
UITextChecker.learnWord(acct)
}
if let spoilerText = status.spoilerText, !spoilerText.isEmpty {
self.isContentWarningActive = true
self.contentWarning = spoilerText
}
let initialComposeContent = mentionAccts.joined(separator: " ")
let preInsertedContent = initialComposeContent.isEmpty ? "" : initialComposeContent + " "
self.initialContent = preInsertedContent + initialContentWithSpace
self.content = preInsertedContent + initialContentWithSpace
}
case .topLevel:
self.initialContent = initialContentWithSpace
self.content = initialContentWithSpace
}
// set limit
let _configuration: Mastodon.Entity.Instance.Configuration? = {
var configuration: Mastodon.Entity.Instance.Configuration? = nil
context.managedObjectContext.performAndWait {
guard let authentication = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: context.managedObjectContext)
else { return }
configuration = authentication.instance?.configuration
}
return configuration
}()
if let configuration = _configuration {
// set character limit
if let maxCharacters = configuration.statuses?.maxCharacters {
maxTextInputLimit = maxCharacters
}
// set media limit
if let maxMediaAttachments = configuration.statuses?.maxMediaAttachments {
maxMediaAttachmentLimit = maxMediaAttachments
}
// set poll option limit
if let maxOptions = configuration.polls?.maxOptions {
maxPollOptionLimit = maxOptions
}
// set photo attachment limit
if let imageSizeLimit = configuration.mediaAttachments?.imageSizeLimit {
maxImageMediaSizeLimitInByte = imageSizeLimit
}
// TODO: more limit
}
switch composeContext {
case .composeStatus:
self.isVisibilityButtonEnabled = true
case let .editStatus(status, _):
if let visibility = Mastodon.Entity.Status.Visibility(rawValue: status.visibility.rawValue) {
self.visibility = visibility
}
self.isVisibilityButtonEnabled = false
self.attachmentViewModels = status.attachments.compactMap {
guard let assetURL = $0.assetURL, let url = URL(string: assetURL) else { return nil }
let mediaAttachmentSettings = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: context.managedObjectContext)?.instance?.configurationV2?.mediaAttachments
let attachmentViewModel = AttachmentViewModel(
api: context.apiService,
authContext: authContext,
input: .mastodonAssetUrl(url, $0.id),
sizeLimit: sizeLimit,
delegate: self,
mediaAttachmentSettings: mediaAttachmentSettings
)
attachmentViewModel.caption = $0.altDescription ?? ""
return attachmentViewModel
}
}
bind()
}
}
extension ComposeContentViewModel {
private func bind() {
// bind author
$authContext
.sink { [weak self] authContext in
guard let self = self else { return }
guard let user = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: self.context.managedObjectContext)?.user else { return }
self.avatarURL = user.avatarImageURL()
self.name = user.nameMetaContent ?? PlaintextMetaContent(string: user.displayNameWithFallback)
self.username = user.acctWithDomain
}
.store(in: &disposeBag)
// bind text
$content
.map { $0.count }
.assign(to: &$contentWeightedLength)
Publishers.CombineLatest(
$contentWarning,
$isContentWarningActive
)
.map { $1 ? $0.count : 0 }
.assign(to: &$contentWarningWeightedLength)
Publishers.CombineLatest3(
$contentWeightedLength,
$contentWarningWeightedLength,
$maxTextInputLimit
)
.map { $0 + $1 <= $2 }
.assign(to: &$isContentValid)
// bind attachment
$attachmentViewModels
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
guard let self = self else { return }
Task {
try await self.uploadMediaInQueue()
}
}
.store(in: &disposeBag)
// bind emoji inputView
$isEmojiActive.assign(to: &customEmojiPickerInputViewModel.$isCustomEmojiComposing)
// bind toolbar
Publishers.CombineLatest3(
$isPollActive,
$attachmentViewModels,
$maxMediaAttachmentLimit
)
.receive(on: DispatchQueue.main)
.sink { [weak self] isPollActive, attachmentViewModels, maxMediaAttachmentLimit in
guard let self = self else { return }
let shouldMediaDisable = isPollActive || attachmentViewModels.count >= maxMediaAttachmentLimit
let shouldPollDisable = attachmentViewModels.count > 0
self.isAttachmentButtonEnabled = !shouldMediaDisable
self.isPollButtonEnabled = !shouldPollDisable
}
.store(in: &disposeBag)
// bind status content character count
Publishers.CombineLatest3(
$contentWeightedLength,
$contentWarningWeightedLength,
$isContentWarningActive
)
.map { contentWeightedLength, contentWarningWeightedLength, isContentWarningActive -> Int in
var count = contentWeightedLength
if isContentWarningActive {
count += contentWarningWeightedLength
}
return count
}
.assign(to: &$characterCount)
// bind compose bar button item UI state
let isComposeContentEmpty = $content
.map { $0.isEmpty }
let isComposeContentValid = Publishers.CombineLatest(
$characterCount,
$maxTextInputLimit
)
.map { characterCount, maxTextInputLimit in
characterCount <= maxTextInputLimit
}
let isMediaEmpty = $attachmentViewModels
.map { $0.isEmpty }
let isMediaUploadAllSuccess = $attachmentViewModels
.map { attachmentViewModels in
return Publishers.MergeMany(attachmentViewModels.map { $0.$uploadState })
.delay(for: 0.3, scheduler: DispatchQueue.main) // convert to outputs with delay. Due to @Published emit before changes
.map { _ in attachmentViewModels.map { $0.uploadState } }
}
.switchToLatest()
.map { outputs in
guard outputs.allSatisfy({ $0 == .finish }) else { return false }
return true
}
.prepend(true)
let isPollOptionsAllValid = $pollOptions
.map { options in
return Publishers.MergeMany(options.map { $0.$text })
.delay(for: 0.3, scheduler: DispatchQueue.main) // convert to outputs with delay. Due to @Published emit before changes
.map { _ in options.map { $0.text } }
}
.switchToLatest()
.map { outputs in
return outputs.allSatisfy { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
}
.prepend(true)
let isPublishBarButtonItemEnabledPrecondition1 = Publishers.CombineLatest4(
isComposeContentEmpty,
isComposeContentValid,
isMediaEmpty,
isMediaUploadAllSuccess
)
.map { isComposeContentEmpty, isComposeContentValid, isMediaEmpty, isMediaUploadAllSuccess -> Bool in
if isMediaEmpty {
return isComposeContentValid && !isComposeContentEmpty
} else {
return isComposeContentValid && isMediaUploadAllSuccess
}
}
.eraseToAnyPublisher()
let isPublishBarButtonItemEnabledPrecondition2 = Publishers.CombineLatest(
$isPollActive,
isPollOptionsAllValid
)
.map { isPollActive, isPollOptionsAllValid -> Bool in
if isPollActive {
return isPollOptionsAllValid
} else {
return true
}
}
.eraseToAnyPublisher()
Publishers.CombineLatest(
isPublishBarButtonItemEnabledPrecondition1,
isPublishBarButtonItemEnabledPrecondition2
)
.map { $0 && $1 }
.assign(to: &$isPublishBarButtonItemEnabled)
// bind modal dismiss state
Publishers.CombineLatest4(
$contentWarning,
$content,
$isPollActive,
$attachmentViewModels
)
.receive(on: DispatchQueue.main)
.map { contentWarning, content, hasPoll, attachments in
let trimmedContent = content.trimmingCharacters(in: .whitespacesAndNewlines)
let initialContent = self.initialContent.trimmingCharacters(in: .whitespacesAndNewlines)
let canDiscardContent = trimmedContent.isEmpty || trimmedContent == initialContent
let canDiscardPoll = !hasPoll
let canDiscardAttachments = attachments.isEmpty
return canDiscardContent && canDiscardPoll && canDiscardAttachments
}
.assign(to: &$shouldDismiss)
// languages
context.settingService.currentSetting
.flatMap { settings in
if let settings {
return settings.publisher(for: \.recentLanguages, options: .initial).eraseToAnyPublisher()
} else if let code = Locale.current.languageCode {
return Just([code]).eraseToAnyPublisher()
}
return Just([]).eraseToAnyPublisher()
}
.assign(to: &$recentLanguages)
}
}
extension ComposeContentViewModel {
public enum Destination {
case topLevel
case reply(parent: ManagedObjectRecord<Status>)
}
public enum ScrollViewState {
case fold // snap to input
case expand // snap to reply
}
}
extension ComposeContentViewModel {
public struct AutoCompleteInfo {
// model
let inputText: Substring
// range
let symbolRange: Range<String.Index>
let symbolString: Substring
let toCursorRange: Range<String.Index>
let toCursorString: Substring
let toHighlightEndRange: Range<String.Index>
let toHighlightEndString: Substring
// geometry
var textBoundingRect: CGRect = .zero
var symbolBoundingRect: CGRect = .zero
}
}
extension ComposeContentViewModel {
func createNewPollOptionIfCould() {
logger.log(level: .debug, "\((#file as NSString).lastPathComponent, privacy: .public)[\(#line, privacy: .public)], \(#function, privacy: .public)")
guard pollOptions.count < maxPollOptionLimit else { return }
let option = PollComposeItem.Option()
option.shouldBecomeFirstResponder = true
pollOptions.append(option)
}
}
extension ComposeContentViewModel {
public enum ComposeError: LocalizedError {
case pollHasEmptyOption
public var errorDescription: String? {
switch self {
case .pollHasEmptyOption:
return L10n.Scene.Compose.Poll.thePollIsInvalid
}
}
public var failureReason: String? {
switch self {
case .pollHasEmptyOption:
return L10n.Scene.Compose.Poll.thePollHasEmptyOption
}
}
}
public func statusPublisher() throws -> StatusPublisher {
let authContext = self.authContext
// author
let managedObjectContext = self.context.managedObjectContext
var _author: ManagedObjectRecord<MastodonUser>?
managedObjectContext.performAndWait {
_author = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: managedObjectContext)?.user.asRecord
}
guard let author = _author else {
throw AppError.badAuthentication
}
// poll
_ = try {
guard isPollActive else { return }
let isAllNonEmpty = pollOptions
.map { $0.text }
.allSatisfy { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
guard isAllNonEmpty else {
throw ComposeError.pollHasEmptyOption
}
}()
// save language to recent languages
if let settings = context.settingService.currentSetting.value {
settings.managedObjectContext?.performAndWait {
settings.recentLanguages = [language] + settings.recentLanguages.filter { $0 != language }
}
}
return MastodonStatusPublisher(
author: author,
replyTo: {
if case .reply(let status) = destination {
return status
}
return nil
}(),
isContentWarningComposing: isContentWarningActive,
contentWarning: contentWarning,
content: content,
isMediaSensitive: isContentWarningActive,
attachmentViewModels: attachmentViewModels,
isPollComposing: isPollActive,
pollOptions: pollOptions,
pollExpireConfigurationOption: pollExpireConfigurationOption,
pollMultipleConfigurationOption: pollMultipleConfigurationOption,
visibility: visibility,
language: language
)
}
// MastodonEditStatusPublisher
public func statusEditPublisher() throws -> StatusPublisher? {
let authContext = self.authContext
guard case let .editStatus(status, _) = composeContext else { return nil }
// author
let managedObjectContext = self.context.managedObjectContext
var _author: ManagedObjectRecord<MastodonUser>?
managedObjectContext.performAndWait {
_author = authContext.mastodonAuthenticationBox.authenticationRecord.object(in: managedObjectContext)?.user.asRecord
}
guard let author = _author else {
throw AppError.badAuthentication
}
// poll
_ = try {
guard isPollActive else { return }
let isAllNonEmpty = pollOptions
.map { $0.text }
.allSatisfy { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
guard isAllNonEmpty else {
throw ComposeError.pollHasEmptyOption
}
}()
// save language to recent languages
if let settings = context.settingService.currentSetting.value {
settings.managedObjectContext?.performAndWait {
settings.recentLanguages = [language] + settings.recentLanguages.filter { $0 != language }
}
}
return MastodonEditStatusPublisher(statusID: status.id,
author: author,
isContentWarningComposing: isContentWarningActive,
contentWarning: contentWarning,
content: content,
isMediaSensitive: isContentWarningActive,
attachmentViewModels: attachmentViewModels,
isPollComposing: isPollActive,
pollOptions: pollOptions,
pollExpireConfigurationOption: pollExpireConfigurationOption,
pollMultipleConfigurationOption: pollMultipleConfigurationOption,
visibility: visibility,
language: language)
}
}
extension ComposeContentViewModel {
public enum AttachmentPrecondition: Error, LocalizedError {
case videoAttachWithPhoto
case moreThanOneVideo
public var errorDescription: String? {
return L10n.Common.Alerts.PublishPostFailure.title
}
public var failureReason: String? {
switch self {
case .videoAttachWithPhoto:
return L10n.Common.Alerts.PublishPostFailure.AttachmentsMessage.videoAttachWithPhoto
case .moreThanOneVideo:
return L10n.Common.Alerts.PublishPostFailure.AttachmentsMessage.moreThanOneVideo
}
}
}
// check exclusive limit:
// - up to 1 video
// - up to N photos
public func checkAttachmentPrecondition() throws {
let attachmentViewModels = self.attachmentViewModels
guard !attachmentViewModels.isEmpty else { return }
var photoAttachmentViewModels: [AttachmentViewModel] = []
var videoAttachmentViewModels: [AttachmentViewModel] = []
attachmentViewModels.forEach { attachmentViewModel in
guard let output = attachmentViewModel.output else {
assertionFailure()
return
}
switch output {
case .image:
photoAttachmentViewModels.append(attachmentViewModel)
case .video:
videoAttachmentViewModels.append(attachmentViewModel)
}
}
if !videoAttachmentViewModels.isEmpty {
guard videoAttachmentViewModels.count == 1 else {
throw AttachmentPrecondition.moreThanOneVideo
}
guard photoAttachmentViewModels.isEmpty else {
throw AttachmentPrecondition.videoAttachWithPhoto
}
}
}
}
// MARK: - DeleteBackwardResponseTextFieldRelayDelegate
extension ComposeContentViewModel: DeleteBackwardResponseTextFieldRelayDelegate {
func deleteBackwardResponseTextFieldDidReturn(_ textField: DeleteBackwardResponseTextField) {
let index = textField.tag
if index + 1 == pollOptions.count {
createNewPollOptionIfCould()
} else if index < pollOptions.count {
pollOptions[index + 1].textField?.becomeFirstResponder()
}
}
func deleteBackwardResponseTextField(_ textField: DeleteBackwardResponseTextField, textBeforeDelete: String?) {
guard (textBeforeDelete ?? "").isEmpty else {
// do nothing when not empty
return
}
let index = textField.tag
guard index > 0 else {
// do nothing at first row
return
}
func optionBeforeRemoved() -> PollComposeItem.Option? {
guard index > 0 else { return nil }
let indexBeforeRemoved = pollOptions.index(before: index)
let itemBeforeRemoved = pollOptions[indexBeforeRemoved]
return itemBeforeRemoved
}
func optionAfterRemoved() -> PollComposeItem.Option? {
guard index < pollOptions.count - 1 else { return nil }
let indexAfterRemoved = pollOptions.index(after: index)
let itemAfterRemoved = pollOptions[indexAfterRemoved]
return itemAfterRemoved
}
// move first responder
let _option = optionBeforeRemoved() ?? optionAfterRemoved()
_option?.textField?.becomeFirstResponder()
guard pollOptions.count > 2 else {
// remove item when more then 2 options
return
}
pollOptions.remove(at: index)
}
}
// MARK: - AttachmentViewModelDelegate
extension ComposeContentViewModel: AttachmentViewModelDelegate {
public func attachmentViewModel(
_ viewModel: AttachmentViewModel,
uploadStateValueDidChange state: AttachmentViewModel.UploadState
) {
Task {
try await uploadMediaInQueue()
}
}
@MainActor
func uploadMediaInQueue() async throws {
for (i, attachmentViewModel) in attachmentViewModels.enumerated() {
switch attachmentViewModel.uploadState {
case .none:
return
case .compressing:
return
case .ready:
let count = self.attachmentViewModels.count
logger.log(level: .debug, "\((#file as NSString).lastPathComponent, privacy: .public)[\(#line, privacy: .public)], \(#function, privacy: .public): upload \(i)/\(count) attachment")
try await attachmentViewModel.upload()
return
case .uploading:
return
case .fail:
return
case .finish:
continue
}
}
}
public func attachmentViewModel(
_ viewModel: AttachmentViewModel,
actionButtonDidPressed action: AttachmentViewModel.Action
) {
switch action {
case .retry:
Task {
try await viewModel.upload(isRetry: true)
}
case .remove:
attachmentViewModels.removeAll(where: { $0 === viewModel })
Task {
try await uploadMediaInQueue()
}
}
}
}