-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathAttachmentController.swift
1439 lines (1226 loc) · 60.6 KB
/
AttachmentController.swift
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import UIKit
import Display
import AsyncDisplayKit
import SwiftSignalKit
import Postbox
import TelegramCore
import TelegramPresentationData
import TelegramUIPreferences
import AccountContext
import TelegramStringFormatting
import UIKitRuntimeUtils
import MediaResources
import LegacyMessageInputPanel
import LegacyMessageInputPanelInputView
import AttachmentTextInputPanelNode
import ChatSendMessageActionUI
import MinimizedContainer
public enum AttachmentButtonType: Equatable {
case gallery
case file
case location
case quickReply
case contact
case poll
case app(AttachMenuBot)
case gift
case standalone
public var key: String {
switch self {
case .gallery:
return "gallery"
case .file:
return "file"
case .location:
return "location"
case .quickReply:
return "quickReply"
case .contact:
return "contact"
case .poll:
return "poll"
case let .app(bot):
return "app_\(bot.shortName)"
case .gift:
return "gift"
case .standalone:
return "standalone"
}
}
public static func ==(lhs: AttachmentButtonType, rhs: AttachmentButtonType) -> Bool {
switch lhs {
case .gallery:
if case .gallery = rhs {
return true
} else {
return false
}
case .file:
if case .file = rhs {
return true
} else {
return false
}
case .location:
if case .location = rhs {
return true
} else {
return false
}
case .quickReply:
if case .quickReply = rhs {
return true
} else {
return false
}
case .contact:
if case .contact = rhs {
return true
} else {
return false
}
case .poll:
if case .poll = rhs {
return true
} else {
return false
}
case let .app(lhsBot):
if case let .app(rhsBot) = rhs, lhsBot.peer.id == rhsBot.peer.id {
return true
} else {
return false
}
case .gift:
if case .gift = rhs {
return true
} else {
return false
}
case .standalone:
if case .standalone = rhs {
return true
} else {
return false
}
}
}
}
public protocol AttachmentContainable: ViewController, MinimizableController {
var requestAttachmentMenuExpansion: () -> Void { get set }
var updateNavigationStack: (@escaping ([AttachmentContainable]) -> ([AttachmentContainable], AttachmentMediaPickerContext?)) -> Void { get set }
var parentController: () -> ViewController? { get set }
var updateTabBarAlpha: (CGFloat, ContainedViewLayoutTransition) -> Void { get set }
var updateTabBarVisibility: (Bool, ContainedViewLayoutTransition) -> Void { get set }
var cancelPanGesture: () -> Void { get set }
var isContainerPanning: () -> Bool { get set }
var isContainerExpanded: () -> Bool { get set }
var isPanGestureEnabled: (() -> Bool)? { get }
var isInnerPanGestureEnabled: (() -> Bool)? { get }
var mediaPickerContext: AttachmentMediaPickerContext? { get }
var getCurrentSendMessageContextMediaPreview: (() -> ChatSendMessageContextScreenMediaPreview?)? { get }
func isContainerPanningUpdated(_ panning: Bool)
func resetForReuse()
func prepareForReuse()
func requestDismiss(completion: @escaping () -> Void)
func shouldDismissImmediately() -> Bool
func beforeMaximize(navigationController: NavigationController, completion: @escaping () -> Void)
}
public extension AttachmentContainable {
func isContainerPanningUpdated(_ panning: Bool) {
}
func resetForReuse() {
}
func prepareForReuse() {
}
func requestDismiss(completion: @escaping () -> Void) {
completion()
}
func shouldDismissImmediately() -> Bool {
return true
}
func beforeMaximize(navigationController: NavigationController, completion: @escaping () -> Void) {
completion()
}
var minimizedBounds: CGRect? {
return nil
}
var isFullscreen: Bool {
return false
}
var minimizedTopEdgeOffset: CGFloat? {
return nil
}
var minimizedIcon: UIImage? {
return nil
}
var minimizedProgress: Float? {
return nil
}
var isPanGestureEnabled: (() -> Bool)? {
return nil
}
var isInnerPanGestureEnabled: (() -> Bool)? {
return nil
}
var getCurrentSendMessageContextMediaPreview: (() -> ChatSendMessageContextScreenMediaPreview?)? {
return nil
}
}
public enum AttachmentMediaPickerSendMode {
case generic
case silently
case whenOnline
}
public enum AttachmentMediaPickerAttachmentMode {
case media
case files
}
public protocol AttachmentMediaPickerContext {
var selectionCount: Signal<Int, NoError> { get }
var caption: Signal<NSAttributedString?, NoError> { get }
var hasCaption: Bool { get }
var captionIsAboveMedia: Signal<Bool, NoError> { get }
func setCaptionIsAboveMedia(_ captionIsAboveMedia: Bool) -> Void
var canMakePaidContent: Bool { get }
var price: Int64? { get }
func setPrice(_ price: Int64) -> Void
var hasTimers: Bool { get }
var loadingProgress: Signal<CGFloat?, NoError> { get }
var mainButtonState: Signal<AttachmentMainButtonState?, NoError> { get }
var secondaryButtonState: Signal<AttachmentMainButtonState?, NoError> { get }
var bottomPanelBackgroundColor: Signal<UIColor?, NoError> { get }
func mainButtonAction()
func secondaryButtonAction()
func setCaption(_ caption: NSAttributedString)
func send(mode: AttachmentMediaPickerSendMode, attachmentMode: AttachmentMediaPickerAttachmentMode, parameters: ChatSendMessageActionSheetController.SendParameters?)
func schedule(parameters: ChatSendMessageActionSheetController.SendParameters?)
}
public extension AttachmentMediaPickerContext {
var selectionCount: Signal<Int, NoError> {
return .single(0)
}
var caption: Signal<NSAttributedString?, NoError> {
return .single(nil)
}
var captionIsAboveMedia: Signal<Bool, NoError> {
return .single(false)
}
var hasCaption: Bool {
return false
}
func setCaptionIsAboveMedia(_ captionIsAboveMedia: Bool) -> Void {
}
var canMakePaidContent: Bool {
return false
}
var price: Int64? {
return nil
}
func setPrice(_ price: Int64) -> Void {
}
var hasTimers: Bool {
return false
}
var loadingProgress: Signal<CGFloat?, NoError> {
return .single(nil)
}
var mainButtonState: Signal<AttachmentMainButtonState?, NoError> {
return .single(nil)
}
var secondaryButtonState: Signal<AttachmentMainButtonState?, NoError> {
return .single(nil)
}
var bottomPanelBackgroundColor: Signal<UIColor?, NoError> {
return .single(nil)
}
func setCaption(_ caption: NSAttributedString) {
}
func send(mode: AttachmentMediaPickerSendMode, attachmentMode: AttachmentMediaPickerAttachmentMode, parameters: ChatSendMessageActionSheetController.SendParameters?) {
}
func schedule(parameters: ChatSendMessageActionSheetController.SendParameters?) {
}
func mainButtonAction() {
}
func secondaryButtonAction() {
}
}
private func generateShadowImage() -> UIImage? {
return generateImage(CGSize(width: 140.0, height: 140.0), rotatedContext: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.saveGState()
context.setShadow(offset: CGSize(), blur: 60.0, color: UIColor(white: 0.0, alpha: 0.4).cgColor)
let path = UIBezierPath(roundedRect: CGRect(x: 60.0, y: 60.0, width: 20.0, height: 20.0), cornerRadius: 10.0).cgPath
context.addPath(path)
context.fillPath()
context.restoreGState()
context.setBlendMode(.clear)
context.addPath(path)
context.fillPath()
})?.stretchableImage(withLeftCapWidth: 70, topCapHeight: 70)
}
private func generateMaskImage() -> UIImage? {
return generateImage(CGSize(width: 390.0, height: 220.0), rotatedContext: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.setFillColor(UIColor.white.cgColor)
let path = UIBezierPath(roundedRect: CGRect(x: 0.0, y: 0.0, width: 390.0, height: 209.0), cornerRadius: 10.0).cgPath
context.addPath(path)
context.fillPath()
try? drawSvgPath(context, path: "M183.219,208.89 H206.781 C205.648,208.89 204.567,209.371 203.808,210.214 L197.23,217.523 C196.038,218.848 193.962,218.848 192.77,217.523 L186.192,210.214 C185.433,209.371 184.352,208.89 183.219,208.89 Z ")
})?.stretchableImage(withLeftCapWidth: 195, topCapHeight: 110)
}
public class AttachmentController: ViewController, MinimizableController {
private let context: AccountContext
private let updatedPresentationData: (initial: PresentationData, signal: Signal<PresentationData, NoError>)?
private let chatLocation: ChatLocation?
private let isScheduledMessages: Bool
private var buttons: [AttachmentButtonType]
private let initialButton: AttachmentButtonType
private let fromMenu: Bool
private var hasTextInput: Bool
private let isFullSize: Bool
private let makeEntityInputView: () -> AttachmentTextInputPanelInputView?
public var animateAppearance: Bool = false
public var willDismiss: () -> Void = {}
public var didDismiss: () -> Void = {}
public var mediaPickerContext: AttachmentMediaPickerContext? {
get {
return self.node.mediaPickerContext
}
set {
self.node.mediaPickerContext = newValue
}
}
private let _ready = Promise<Bool>()
override public var ready: Promise<Bool> {
return self._ready
}
public private(set) var minimizedTopEdgeOffset: CGFloat?
public private(set) var minimizedBounds: CGRect?
public var minimizedIcon: UIImage? {
return self.mainController.minimizedIcon
}
public var isFullscreen: Bool {
return self.mainController.isFullscreen
}
private final class Node: ASDisplayNode {
private weak var controller: AttachmentController?
fileprivate let dim: ASDisplayNode
private let shadowNode: ASImageNode
fileprivate let container: AttachmentContainer
private let makeEntityInputView: () -> AttachmentTextInputPanelInputView?
let panel: AttachmentPanel
fileprivate var currentType: AttachmentButtonType?
fileprivate var currentControllers: [AttachmentContainable] = []
private var validLayout: ContainerViewLayout?
private var modalProgress: CGFloat = 0.0
fileprivate var isDismissing = false
private let captionDisposable = MetaDisposable()
private let mediaSelectionCountDisposable = MetaDisposable()
private let loadingProgressDisposable = MetaDisposable()
private let mainButtonStateDisposable = MetaDisposable()
private let secondaryButtonStateDisposable = MetaDisposable()
private let bottomPanelBackgroundColorDisposable = MetaDisposable()
private var selectionCount: Int = 0
var mediaPickerContext: AttachmentMediaPickerContext? {
didSet {
if let mediaPickerContext = self.mediaPickerContext {
self.captionDisposable.set((mediaPickerContext.caption
|> deliverOnMainQueue).startStrict(next: { [weak self] caption in
if let strongSelf = self {
strongSelf.panel.updateCaption(caption ?? NSAttributedString())
}
}))
self.mediaSelectionCountDisposable.set((mediaPickerContext.selectionCount
|> deliverOnMainQueue).startStrict(next: { [weak self] count in
if let strongSelf = self {
strongSelf.updateSelectionCount(count)
}
}))
self.loadingProgressDisposable.set((mediaPickerContext.loadingProgress
|> deliverOnMainQueue).startStrict(next: { [weak self] progress in
if let strongSelf = self {
strongSelf.panel.updateLoadingProgress(progress)
if let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.4, curve: .spring))
}
}
}))
self.mainButtonStateDisposable.set((mediaPickerContext.mainButtonState
|> deliverOnMainQueue).startStrict(next: { [weak self] mainButtonState in
if let strongSelf = self {
let _ = (strongSelf.panel.animatingTransitionPromise.get()
|> filter { value in
return !value
}
|> take(1)).startStandalone(next: { [weak self] _ in
if let strongSelf = self {
strongSelf.panel.updateMainButtonState(mainButtonState)
if let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.4, curve: .spring))
}
}
})
}
}))
self.secondaryButtonStateDisposable.set((mediaPickerContext.secondaryButtonState
|> deliverOnMainQueue).startStrict(next: { [weak self] mainButtonState in
if let strongSelf = self {
let _ = (strongSelf.panel.animatingTransitionPromise.get()
|> filter { value in
return !value
}
|> take(1)).startStandalone(next: { [weak self] _ in
if let strongSelf = self {
strongSelf.panel.updateSecondaryButtonState(mainButtonState)
if let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.4, curve: .spring))
}
}
})
}
}))
self.bottomPanelBackgroundColorDisposable.set((mediaPickerContext.bottomPanelBackgroundColor
|> deliverOnMainQueue).startStrict(next: { [weak self] color in
if let strongSelf = self {
let _ = (strongSelf.panel.animatingTransitionPromise.get()
|> filter { value in
return !value
}
|> take(1)).startStandalone(next: { [weak self] _ in
if let strongSelf = self {
strongSelf.panel.updateCustomBottomPanelBackgroundColor(color)
}
})
}
}))
} else {
self.updateSelectionCount(0)
self.mediaSelectionCountDisposable.set(nil)
self.loadingProgressDisposable.set(nil)
self.mainButtonStateDisposable.set(nil)
self.secondaryButtonStateDisposable.set(nil)
self.bottomPanelBackgroundColorDisposable.set(nil)
}
}
}
private let wrapperNode: ASDisplayNode
private var isMinimizing = false
init(controller: AttachmentController, makeEntityInputView: @escaping () -> AttachmentTextInputPanelInputView?) {
self.controller = controller
self.makeEntityInputView = makeEntityInputView
self.dim = ASDisplayNode()
self.dim.alpha = 0.0
self.dim.backgroundColor = UIColor(white: 0.0, alpha: 0.25)
self.shadowNode = ASImageNode()
self.shadowNode.isUserInteractionEnabled = false
self.wrapperNode = ASDisplayNode()
self.wrapperNode.clipsToBounds = true
self.container = AttachmentContainer(isFullSize: controller.isFullSize)
self.container.canHaveKeyboardFocus = true
self.panel = AttachmentPanel(controller: controller, context: controller.context, chatLocation: controller.chatLocation, isScheduledMessages: controller.isScheduledMessages, updatedPresentationData: controller.updatedPresentationData, makeEntityInputView: makeEntityInputView)
self.panel.fromMenu = controller.fromMenu
self.panel.isStandalone = controller.isStandalone
super.init()
self.clipsToBounds = false
self.addSubnode(self.dim)
self.addSubnode(self.shadowNode)
self.addSubnode(self.wrapperNode)
self.container.controllerRemoved = { [weak self] controller in
if let strongSelf = self, let layout = strongSelf.validLayout, !strongSelf.isDismissing {
strongSelf.currentControllers = strongSelf.currentControllers.filter { $0 !== controller }
strongSelf.containerLayoutUpdated(layout, transition: .immediate)
}
}
self.container.updateModalProgress = { [weak self] progress, topInset, bounds, transition in
if let strongSelf = self, let layout = strongSelf.validLayout, !strongSelf.isDismissing {
var transition = transition
if strongSelf.container.supernode == nil {
transition = .animated(duration: 0.4, curve: .spring)
}
strongSelf.modalProgress = progress
strongSelf.controller?.minimizedTopEdgeOffset = topInset
strongSelf.controller?.minimizedBounds = bounds
if !strongSelf.isMinimizing {
strongSelf.controller?.updateModalStyleOverlayTransitionFactor(progress, transition: transition)
strongSelf.containerLayoutUpdated(layout, transition: transition)
}
}
}
self.container.isReadyUpdated = { [weak self] in
if let strongSelf = self, let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.4, curve: .spring))
}
}
self.container.interactivelyDismissed = { [weak self] velocity in
if let strongSelf = self, let layout = strongSelf.validLayout {
if let controller = strongSelf.controller, controller.shouldMinimizeOnSwipe?(strongSelf.currentType) == true {
var delta = layout.size.height
if let minimizedTopEdgeOffset = controller.minimizedTopEdgeOffset {
delta -= minimizedTopEdgeOffset
}
let damping: CGFloat = 180.0
let initialVelocity: CGFloat = delta > 0.0 ? velocity / delta : 0.0
strongSelf.minimize(damping: damping, initialVelocity: initialVelocity)
return false
} else {
strongSelf.controller?.dismiss(animated: true)
}
}
return true
}
self.container.isPanningUpdated = { [weak self] value in
if let strongSelf = self, let currentController = strongSelf.currentControllers.last, !value {
currentController.isContainerPanningUpdated(value)
}
}
self.container.isPanGestureEnabled = { [weak self] in
guard let self, let currentController = self.currentControllers.last else {
return true
}
if let isPanGestureEnabled = currentController.isPanGestureEnabled {
return isPanGestureEnabled()
} else {
return true
}
}
self.container.isInnerPanGestureEnabled = { [weak self] in
guard let self, let currentController = self.currentControllers.last else {
return true
}
if let isInnerPanGestureEnabled = currentController.isInnerPanGestureEnabled {
return isInnerPanGestureEnabled()
} else {
return true
}
}
self.container.shouldCancelPanGesture = { [weak self] in
if let strongSelf = self, let currentController = strongSelf.currentControllers.last {
if !currentController.shouldDismissImmediately() {
return true
} else {
return false
}
} else {
return false
}
}
self.container.requestDismiss = { [weak self] in
if let strongSelf = self, let currentController = strongSelf.currentControllers.last {
currentController.requestDismiss { [weak self] in
if let strongSelf = self {
strongSelf.controller?.dismiss(animated: true)
}
}
}
}
self.panel.selectionChanged = { [weak self] type in
if let strongSelf = self {
return strongSelf.switchToController(type)
} else {
return false
}
}
self.panel.longPressed = { [weak self] _ in
if let strongSelf = self, let currentController = strongSelf.currentControllers.last {
currentController.longTapWithTabBar?()
}
}
self.panel.beganTextEditing = { [weak self] in
if let strongSelf = self {
strongSelf.container.update(isExpanded: true, transition: .animated(duration: 0.4, curve: .spring))
}
}
self.panel.textUpdated = { [weak self] text in
if let strongSelf = self {
strongSelf.mediaPickerContext?.setCaption(text)
}
}
self.panel.sendMessagePressed = { [weak self] mode, parameters in
if let strongSelf = self {
switch mode {
case .generic:
strongSelf.mediaPickerContext?.send(mode: .generic, attachmentMode: .media, parameters: parameters)
case .silent:
strongSelf.mediaPickerContext?.send(mode: .silently, attachmentMode: .media, parameters: parameters)
case .schedule:
strongSelf.mediaPickerContext?.schedule(parameters: parameters)
case .whenOnline:
strongSelf.mediaPickerContext?.send(mode: .whenOnline, attachmentMode: .media, parameters: parameters)
}
}
}
self.panel.onMainButtonPressed = { [weak self] in
if let strongSelf = self {
strongSelf.mediaPickerContext?.mainButtonAction()
}
}
self.panel.onSecondaryButtonPressed = { [weak self] in
if let strongSelf = self {
strongSelf.mediaPickerContext?.secondaryButtonAction()
}
}
self.panel.requestLayout = { [weak self] in
if let strongSelf = self, let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.2, curve: .easeInOut))
}
}
self.panel.present = { [weak self] c in
if let strongSelf = self {
strongSelf.controller?.present(c, in: .window(.root))
}
}
self.panel.presentInGlobalOverlay = { [weak self] c in
if let strongSelf = self {
strongSelf.controller?.presentInGlobalOverlay(c, with: nil)
}
}
self.panel.getCurrentSendMessageContextMediaPreview = { [weak self] in
guard let self, let currentController = self.currentControllers.last else {
return nil
}
return currentController.getCurrentSendMessageContextMediaPreview?()
}
}
deinit {
self.captionDisposable.dispose()
self.mediaSelectionCountDisposable.dispose()
self.loadingProgressDisposable.dispose()
self.mainButtonStateDisposable.dispose()
self.secondaryButtonStateDisposable.dispose()
self.bottomPanelBackgroundColorDisposable.dispose()
}
private var inputContainerHeight: CGFloat?
private var inputContainerNode: ASDisplayNode?
override func didLoad() {
super.didLoad()
self.view.disablesInteractiveModalDismiss = true
self.dim.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dimTapGesture(_:))))
if let controller = self.controller {
let _ = self.switchToController(controller.initialButton)
if case let .app(bot) = controller.initialButton {
if let index = controller.buttons.firstIndex(where: {
if case let .app(otherBot) = $0, otherBot.peer.id == bot.peer.id {
return true
} else {
return false
}
}) {
self.panel.updateSelectedIndex(index)
}
} else if controller.initialButton != .standalone {
if let index = controller.buttons.firstIndex(where: {
if $0 == controller.initialButton {
return true
} else {
return false
}
}) {
self.panel.updateSelectedIndex(index)
}
}
}
if let (inputContainerHeight, inputContainerNode, _) = self.controller?.getInputContainerNode() {
self.inputContainerHeight = inputContainerHeight
self.inputContainerNode = inputContainerNode
self.addSubnode(inputContainerNode)
}
}
fileprivate func minimize(damping: CGFloat? = nil, initialVelocity: CGFloat? = nil) {
guard let controller = self.controller, let navigationController = controller.navigationController as? NavigationController else {
return
}
navigationController.minimizeViewController(controller, damping: damping, velocity: initialVelocity, beforeMaximize: { navigationController, completion in
controller.mainController.beforeMaximize(navigationController: navigationController, completion: completion)
}, setupContainer: { [weak self] current in
let minimizedContainer: MinimizedContainerImpl?
if let current = current as? MinimizedContainerImpl {
minimizedContainer = current
} else if let context = self?.controller?.context {
minimizedContainer = MinimizedContainerImpl(sharedContext: context.sharedContext)
} else {
minimizedContainer = nil
}
return minimizedContainer
}, animated: true)
self.dim.isHidden = true
self.isMinimizing = true
self.container.update(isExpanded: true, force: true, transition: .immediate)
self.isMinimizing = false
Queue.mainQueue().after(0.45, {
self.dim.isHidden = false
})
}
fileprivate func updateSelectionCount(_ count: Int, animated: Bool = true) {
self.selectionCount = count
if let layout = self.validLayout {
self.containerLayoutUpdated(layout, transition: animated ? .animated(duration: 0.4, curve: .spring) : .immediate)
}
}
@objc func dimTapGesture(_ recognizer: UITapGestureRecognizer) {
guard !self.isDismissing else {
return
}
if case .ended = recognizer.state {
if let lastController = self.currentControllers.last {
if let controller = self.controller, let layout = self.validLayout, !layout.metrics.isTablet, controller.shouldMinimizeOnSwipe?(self.currentType) == true {
self.minimize()
return
}
lastController.requestDismiss(completion: { [weak self] in
self?.controller?.dismiss(animated: true)
})
} else {
self.controller?.dismiss(animated: true)
}
}
}
func switchToController(_ type: AttachmentButtonType, animated: Bool = true) -> Bool {
guard self.currentType != type else {
if self.animating {
return false
}
if let controller = self.currentControllers.last {
controller.scrollToTopWithTabBar?()
controller.requestAttachmentMenuExpansion()
}
return true
}
let previousType = self.currentType
self.currentType = type
self.controller?.requestController(type, { [weak self] controller, mediaPickerContext in
if let strongSelf = self {
if let controller = controller {
strongSelf.controller?._ready.set(controller.ready.get())
controller._presentedInModal = true
controller.navigation_setPresenting(strongSelf.controller)
controller.requestAttachmentMenuExpansion = { [weak self] in
if let strongSelf = self, !strongSelf.container.isTracking {
strongSelf.container.update(isExpanded: true, transition: .animated(duration: 0.4, curve: .spring))
}
}
controller.updateNavigationStack = { [weak self] f in
if let strongSelf = self {
let (controllers, mediaPickerContext) = f(strongSelf.currentControllers)
strongSelf.currentControllers = controllers
strongSelf.mediaPickerContext = mediaPickerContext
if let layout = strongSelf.validLayout {
strongSelf.containerLayoutUpdated(layout, transition: .animated(duration: 0.4, curve: .spring))
}
}
}
controller.parentController = { [weak self] in
guard let self else {
return nil
}
return self.controller
}
controller.updateTabBarAlpha = { [weak self, weak controller] alpha, transition in
if let strongSelf = self, strongSelf.currentControllers.contains(where: { $0 === controller }) {
strongSelf.panel.updateBackgroundAlpha(alpha, transition: transition)
}
}
controller.updateTabBarVisibility = { [weak self, weak controller] isVisible, transition in
if let strongSelf = self, strongSelf.currentControllers.contains(where: { $0 === controller }) {
strongSelf.updateIsPanelVisible(isVisible, transition: transition)
}
}
controller.cancelPanGesture = { [weak self] in
if let strongSelf = self {
strongSelf.container.cancelPanGesture()
}
}
controller.isContainerPanning = { [weak self] in
if let strongSelf = self {
return strongSelf.container.isPanning
} else {
return false
}
}
controller.isContainerExpanded = { [weak self] in
if let strongSelf = self {
return strongSelf.container.isExpanded
} else {
return false
}
}
let previousController = strongSelf.currentControllers.last
strongSelf.currentControllers = [controller]
if previousType != nil && animated {
strongSelf.animateSwitchTransition(controller, previousController: previousController)
}
if let layout = strongSelf.validLayout {
strongSelf.switchingController = true
strongSelf.containerLayoutUpdated(layout, transition: animated ? .animated(duration: 0.3, curve: .spring) : .immediate)
strongSelf.switchingController = false
}
}
strongSelf.mediaPickerContext = mediaPickerContext
}
})
return true
}
private func animateSwitchTransition(_ controller: AttachmentContainable, previousController: AttachmentContainable?) {
guard let snapshotView = self.container.container.view.snapshotView(afterScreenUpdates: false) else {
return
}
snapshotView.frame = self.container.container.frame
self.container.clipNode.view.addSubview(snapshotView)
let _ = (controller.ready.get()
|> filter {
$0
}
|> take(1)
|> deliverOnMainQueue).startStandalone(next: { [weak self, weak snapshotView] _ in
guard let strongSelf = self, let layout = strongSelf.validLayout else {
return
}
if case .compact = layout.metrics.widthClass {
let offset = 25.0
let initialPosition = strongSelf.container.clipNode.layer.position
let targetPosition = initialPosition.offsetBy(dx: 0.0, dy: offset)
var startPosition = initialPosition
if let presentation = strongSelf.container.clipNode.layer.presentation() {
startPosition = presentation.position
}
strongSelf.container.clipNode.layer.animatePosition(from: startPosition, to: targetPosition, duration: 0.2, removeOnCompletion: false, completion: { [weak self] finished in
if let strongSelf = self, finished {
strongSelf.container.clipNode.layer.animateSpring(from: NSValue(cgPoint: targetPosition), to: NSValue(cgPoint: initialPosition), keyPath: "position", duration: 0.4, delay: 0.0, initialVelocity: 0.0, damping: 70.0, removeOnCompletion: false, completion: { [weak self] finished in
if finished {
self?.container.clipNode.layer.removeAllAnimations()
}
})
}
})
}
snapshotView?.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.23, removeOnCompletion: false, completion: { [weak snapshotView] _ in
snapshotView?.removeFromSuperview()
previousController?.resetForReuse()
})
})
}
private var animating = false
func animateIn() {
guard let layout = self.validLayout, let controller = self.controller else {
return
}
self.animating = true
if case .regular = layout.metrics.widthClass {
if controller.animateAppearance {
let targetPosition = self.position
let startPosition = targetPosition.offsetBy(dx: 0.0, dy: layout.size.height)
self.position = startPosition
let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .spring)
transition.animateView(allowUserInteraction: true, {
self.position = targetPosition
}, completion: { _ in
self.animating = false
})
} else {
self.animating = false
}
ContainedViewLayoutTransition.animated(duration: 0.3, curve: .linear).updateAlpha(node: self.dim, alpha: 0.1)
} else {
ContainedViewLayoutTransition.animated(duration: 0.3, curve: .linear).updateAlpha(node: self.dim, alpha: 1.0)
let targetPosition = self.container.position
let startPosition = targetPosition.offsetBy(dx: 0.0, dy: layout.size.height)
self.container.position = startPosition
let transition = ContainedViewLayoutTransition.animated(duration: 0.4, curve: .spring)
transition.animateView(allowUserInteraction: true, {
self.container.position = targetPosition
}, completion: { _ in
self.animating = false
})
}
}
func animateOut(completion: @escaping () -> Void = {}) {
guard let controller = self.controller else {
return
}
self.isDismissing = true
guard let layout = self.validLayout else {
return
}
self.animating = true
if case .regular = layout.metrics.widthClass {
self.layer.allowsGroupOpacity = true
self.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.3, removeOnCompletion: false, completion: { [weak self] _ in
let _ = self?.container.dismiss(transition: .immediate, completion: completion)
self?.animating = false
self?.layer.removeAllAnimations()
})
} else {
let positionTransition: ContainedViewLayoutTransition = .animated(duration: 0.25, curve: .easeInOut)
positionTransition.updatePosition(node: self.container, position: CGPoint(x: self.container.position.x, y: self.bounds.height + self.container.bounds.height / 2.0), completion: { [weak self] _ in
let _ = self?.container.dismiss(transition: .immediate, completion: completion)
self?.animating = false
})