-
Notifications
You must be signed in to change notification settings - Fork 895
/
Copy pathAddReactionManager.swift
1702 lines (1386 loc) · 66.2 KB
/
AddReactionManager.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
//
// AddReactionManager.swift
// Telegram
//
// Created by Mikhail Filimonov on 20.12.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import AppKit
import SwiftSignalKit
import TelegramCore
import Postbox
import ObjcUtils
import TelegramMedia
func parabollicReactionAnimation(_ layer: CALayer, fromPoint: NSPoint, toPoint: NSPoint, window: Window, completion: ((Bool)->Void)? = nil, duration: Double = 0.2) {
let view = View(frame: window.frame.size.bounds)
view.isEventLess = true
view.flip = false
view.backgroundColor = .clear
window.contentView?.addSubview(view)
layer.removeFromSuperlayer()
layer.frame = CGRect(origin: toPoint.offsetBy(dx: -layer.frame.width/2, dy: -layer.frame.height/2), size: layer.frame.size)
view.layer?.addSublayer(layer)
let transition = ContainedViewLayoutTransition.animated(duration: duration, curve: .linear)
let keyFrames = generateParabollicMotionKeyframes(from: fromPoint, to: toPoint, elevation: fromPoint.y < toPoint.y ? 50 : -50)
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.fromValue = 1
animation.toValue = 2.0
animation.duration = transition.duration / 2
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.isRemovedOnCompletion = true
animation.fillMode = .forwards
animation.speed = 1
animation.repeatCount = 1
animation.autoreverses = true
layer.add(animation, forKey: "transform.scale")
transition.animatePositionWithKeyframes(layer: layer, keyframes: keyFrames, removeOnCompletion: true, completion: { [weak view] completed in
CATransaction.begin()
completion?(completed)
CATransaction.commit()
DispatchQueue.main.async {
view?.removeFromSuperview()
}
})
}
private func generateParabollicMotionKeyframes(from sourcePoint: CGPoint, to targetPosition: CGPoint, elevation: CGFloat) -> [CGPoint] {
let midPoint = CGPoint(x: (sourcePoint.x + targetPosition.x) / 2.0, y: sourcePoint.y - elevation)
let x1 = sourcePoint.x
let y1 = sourcePoint.y
let x2 = midPoint.x
let y2 = midPoint.y
let x3 = targetPosition.x
let y3 = targetPosition.y
var keyframes: [CGPoint] = []
if abs(y1 - y3) < 5.0 && abs(x1 - x3) < 5.0 {
for i in 0 ..< 10 {
let k = CGFloat(i) / CGFloat(10 - 1)
let x = sourcePoint.x * (1.0 - k) + targetPosition.x * k
let y = sourcePoint.y * (1.0 - k) + targetPosition.y * k
keyframes.append(CGPoint(x: x, y: y))
}
} else {
let a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / ((x1 - x2) * (x1 - x3) * (x2 - x3))
let b = (x1 * x1 * (y2 - y3) + x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1)) / ((x1 - x2) * (x1 - x3) * (x2 - x3))
let c = (x2 * x2 * (x3 * y1 - x1 * y3) + x2 * (x1 * x1 * y3 - x3 * x3 * y1) + x1 * x3 * (x3 - x1) * y2) / ((x1 - x2) * (x1 - x3) * (x2 - x3))
for i in 0 ..< 10 {
let k = CGFloat(i) / CGFloat(10 - 1)
let x = sourcePoint.x * (1.0 - k) + targetPosition.x * k
let y = a * x * x + b * x + c
keyframes.append(CGPoint(x: x, y: y))
}
}
return keyframes
}
enum ContextReaction : Equatable {
case builtin(value: MessageReaction.Reaction, staticFile: TelegramMediaFile, selectFile: TelegramMediaFile, appearFile: TelegramMediaFile, isSelected: Bool)
case custom(value: MessageReaction.Reaction, fileId: Int64, TelegramMediaFile?, isSelected: Bool)
var file: TelegramMediaFile? {
switch self {
case let .builtin(_, staticFile, _, _, _):
return staticFile
case let .custom(_, _, file, _ ):
return file
}
}
var fileId: Int64 {
switch self {
case let .builtin(_, staticFile, _, _, _):
return staticFile.fileId.id
case let .custom(_, fileId, _, _):
return fileId
}
}
var isSelected: Bool {
switch self {
case let .builtin(_, _, _, _, isSelected):
return isSelected
case let .custom(_, _, _, isSelected):
return isSelected
}
}
func selectAnimation(_ context: AccountContext) -> Signal<TelegramMediaFile, NoError> {
switch self {
case let .builtin(_, _, selectAnimation, _, _):
return .single(selectAnimation)
case .custom:
return .complete()
}
}
var selectedAnimation: TelegramMediaFile? {
switch self {
case let .builtin(_, _, selectAnimation, _, _):
return selectAnimation
case let .custom(_, _, file, _ ):
return file
}
}
var appearAnimation: TelegramMediaFile? {
switch self {
case let .builtin(_, _, _, appearAnimation, _):
return appearAnimation
case .custom:
return nil
}
}
var value: MessageReaction.Reaction {
switch self {
case let .builtin(value, _, _, _, _):
return value
case let .custom(value, _, _, _):
return value
}
}
}
final class ContextAddReactionsListView : View, StickerFramesCollector {
private final class ReactionView : Control {
let player: LottiePlayerView
private var imageView: InlineStickerView?
private let disposable = MetaDisposable()
private let appearDisposable = MetaDisposable()
private let fetchDisposables = DisposableSet()
let reaction: ContextReaction
let context: AccountContext
private let stateDisposable = MetaDisposable()
private var selectAnimationData: Data?
private var currentKey: String?
private var selectionView : View?
private let presentation: TelegramPresentationTheme
required init(frame frameRect: NSRect, context: AccountContext, reaction: ContextReaction, add: @escaping(MessageReaction.Reaction, Bool, NSRect?)->Void, theme: TelegramPresentationTheme) {
let size: NSSize = reaction.isSelected ? NSMakeSize(25, 24) : NSMakeSize(frameRect.width, 30)
let rect = CGRect(origin: .zero, size: size)
let isLite = context.isLite(.emoji)
self.presentation = theme
self.player = LottiePlayerView(frame: rect)
self.reaction = reaction
self.context = context
super.init(frame: frameRect)
let imageView: InlineStickerView
if let file = reaction.selectedAnimation {
imageView = InlineStickerView(account: context.account, file: file, size: size, isPlayable: false)
} else {
imageView = InlineStickerView(account: context.account, inlinePacksContext: context.inlinePacksContext, emoji: .init(fileId: reaction.fileId, file: nil, emoji: clown), size: size, isPlayable: false)
}
self.imageView = imageView
addSubview(imageView)
addSubview(player)
self.player.isHidden = false
switch reaction {
case .builtin:
self.layer?.cornerRadius = 0
case .custom:
self.layer?.cornerRadius = 4
}
stateDisposable.set(player.state.start(next: { [weak self] state in
switch state {
case .playing:
delay(0.016, closure: {
self?.imageView?.removeFromSuperview()
})
case .stoped:
delay(0.016, closure: {
self?.imageView?.removeFromSuperview()
})
default:
break
}
}))
let signal = reaction.selectAnimation(context) |> mapToSignal {
context.account.postbox.mediaBox.resourceData($0.resource, attemptSynchronously: true)
}
|> filter {
$0.complete
}
|> deliverOnMainQueue
disposable.set(signal.start(next: { [weak self] resourceData in
if let data = try? Data(contentsOf: URL.init(fileURLWithPath: resourceData.path)) {
self?.selectAnimationData = data
if isLite {
let apply:()->Void = {
self?.apply(data, key: "select", policy: .framesCount(1))
}
apply()
}
}
}))
set(handler: { control in
if let window = control.window {
let wrect = control.convert(control.frame.size.bounds, to: nil)
let srect = window.convertToScreen(wrect)
add(reaction.value, true, context.window.convertFromScreen(srect))
}
}, for: .Click)
contextMenu = {
let menu = ContextMenu()
menu.addItem(ContextMenuItem(strings().chatContextReactionQuick, handler: {
context.reactions.updateQuick(reaction.value)
}, itemImage: MenuAnimation.menu_add_to_favorites.value))
return menu
}
if reaction.isSelected {
let view = View()
self.selectionView = view
view.frame = NSMakeRect(0, 0, 34, 34)
view.layer?.cornerRadius = view.frame.height / 2
view.backgroundColor = theme.colors.vibrant.mixedWith(NSColor(0x000000), alpha: 0.1)
self.addSubview(view, positioned: .below, relativeTo: self.subviews.first)
if case .custom = reaction.value {
self.player.layer?.cornerRadius = 4
self.imageView?.layer?.cornerRadius = 4
}
}
if let file = reaction.selectedAnimation {
fetchDisposables.add(fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, userLocation: .other, userContentType: .sticker, reference: .standalone(resource: file.resource)).start())
}
if let file = reaction.appearAnimation {
fetchDisposables.add(fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, userLocation: .other, userContentType: .sticker, reference: .standalone(resource: file.resource)).start())
}
}
var isLite: Bool {
return context.isLite(.emoji)
}
private func apply(_ data: Data, key: String, policy: LottiePlayPolicy) {
let animation = LottieAnimation(compressed: data, key: LottieAnimationEntryKey(key: .bundle("reaction_\(reaction.value)_\(key)"), size: player.frame.size), type: .lottie, cachePurpose: .none, playPolicy: policy, maximumFps: 60, runOnQueue: Queue(), metalSupport: false)
player.set(animation, reset: true, saveContext: true, animated: false)
self.currentKey = key
}
deinit {
disposable.dispose()
stateDisposable.dispose()
appearDisposable.dispose()
fetchDisposables.dispose()
}
override func layout() {
super.layout()
updateLayout(size: self.frame.size, transition: .immediate)
}
func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) {
transition.updateFrame(view: player, frame: self.focus(player.frame.size))
if let imageView = imageView {
transition.updateFrame(view: imageView, frame: self.focus(imageView.frame.size))
}
if let selectionView = self.selectionView {
selectionView.center()
}
}
private var previous: ControlState = .Normal
override func stateDidUpdate(_ state: ControlState) {
super.stateDidUpdate(state)
let isLite = context.isLite(.emoji)
switch state {
case .Hover:
if self.player.currentState != .playing, !isLite {
if self.player.animation?.playPolicy == .framesCount(1) {
self.player.set(self.player.animation?.withUpdatedPolicy(.once), reset: false)
} else {
if let data = selectAnimationData, self.currentKey != "select" {
self.apply(data, key: "select", policy: .framesCount(1))
} else {
self.player.playAgain()
}
}
}
default:
break
}
if previous == .Hover, state == .Highlight {
self.layer?.animateScaleCenter(from: 1, to: 0.8, duration: 0.2, removeOnCompletion: false)
} else if state == .Hover && previous == .Highlight {
self.layer?.animateScaleCenter(from: 0.8, to: 1, duration: 0.2, removeOnCompletion: true)
}
previous = state
}
private var timestamp: TimeInterval? = Date().timeIntervalSince1970
func playAppearAnimation() {
guard self.visibleRect != .zero && !self.isLite else {
return
}
if let appearAnimation = reaction.selectedAnimation {
let signal = context.account.postbox.mediaBox.resourceData(appearAnimation.resource, attemptSynchronously: true)
|> filter {
$0.complete
} |> take(1)
|> deliverOnMainQueue
// self.imageView?.removeFromSuperview()
appearDisposable.set(signal.start(next: { [weak self] resourceData in
if let data = try? Data(contentsOf: URL.init(fileURLWithPath: resourceData.path)) {
if let timestamp = self?.timestamp, Date().timeIntervalSince1970 - timestamp > 0.1 {
return
}
self?.apply(data, key: "appear", policy: .toEnd(from: 0))
}
}))
} else {
imageView?.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.35, bounce: true)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
class ShowMore : Control {
private let imageView = ImageView()
required init(frame frameRect: NSRect, theme: TelegramPresentationTheme) {
super.init(frame: frameRect)
self.backgroundColor = theme.colors.vibrant.mixedWith(NSColor(0x000000), alpha: 0.1)
self.scaleOnClick = true
self.layer?.cornerRadius = frameRect.height / 2
addSubview(self.imageView)
self.imageView.image = theme.icons.reactions_show_more
self.imageView.sizeToFit()
}
override func layout() {
super.layout()
imageView.center()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
private let scrollView = HorizontalScrollView()
private let documentView = View()
private let list: [ContextReaction]
private let topGradient = ShadowView()
private let bottomGradient = ShadowView()
private let backgroundView = View()
private let visualEffect = NSVisualEffectView(frame: .zero)
private let radiusLayer: CGFloat?
private var aboveTextView: TextView?
private let showMore: ShowMore
private let revealReactions:((ContextAddReactionsListView & StickerFramesCollector)->Void)?
private let maskLayer = SimpleShapeLayer()
private let backgroundColorView = View()
private let shadowLayer = SimpleShapeLayer()
private let presentation: TelegramPresentationTheme
private let hasBubble: Bool
private let aboveText: TextViewLayout?
required init(frame frameRect: NSRect, context: AccountContext, list: [ContextReaction], add:@escaping(MessageReaction.Reaction, Bool, NSRect?)->Void, radiusLayer: CGFloat? = 15, revealReactions:((ContextAddReactionsListView & StickerFramesCollector)->Void)? = nil, presentation: TelegramPresentationTheme = theme, hasBubble: Bool = true, aboveText: TextViewLayout? = nil) {
self.list = list
self.showMore = ShowMore(frame: NSMakeRect(0, 0, 34, 34), theme: presentation)
self.revealReactions = revealReactions
self.radiusLayer = radiusLayer
self.presentation = presentation
self.hasBubble = hasBubble
self.aboveText = aboveText
super.init(frame: frameRect)
let theme = presentation
backgroundView.layer?.mask = maskLayer
if !isLite(.blur) {
self.visualEffect.state = .active
self.visualEffect.wantsLayer = true
self.visualEffect.blendingMode = hasBubble ? .behindWindow : .withinWindow
}
showMore.isHidden = revealReactions == nil
showMore.set(handler: { [weak self] control in
if let view = self {
revealReactions?(view)
}
control.layer?.animateScaleCenter(from: 1, to: 0.1, duration: 0.35, removeOnCompletion: false)
control.layer?.animateAlpha(from: 1, to: 0, duration: 0.35, removeOnCompletion: false)
}, for: .Click)
shadowLayer.shadowColor = NSColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 0)
shadowLayer.shadowRadius = 2
shadowLayer.shadowOpacity = 0.2
shadowLayer.fillColor = NSColor.clear.cgColor
self.layer?.addSublayer(shadowLayer)
bottomGradient.shadowBackground = theme.colors.background.withAlphaComponent(1)
bottomGradient.direction = .horizontal(true)
topGradient.shadowBackground = theme.colors.background.withAlphaComponent(1)
topGradient.direction = .horizontal(false)
if !isLite(.blur) {
visualEffect.material = theme.colors.isDark ? .dark : .mediumLight
}
if #available(macOS 11.0, *), !isLite(.blur) {
backgroundColorView.backgroundColor = theme.colors.background.withAlphaComponent(0.7)
} else {
backgroundColorView.backgroundColor = theme.colors.background
}
if #available(macOS 11.0, *), !isLite(.blur) {
backgroundView.addSubview(visualEffect)
}
backgroundView.addSubview(backgroundColorView)
addSubview(backgroundView)
backgroundView.addSubview(scrollView)
addSubview(showMore)
backgroundView.addSubview(topGradient)
backgroundView.addSubview(bottomGradient)
if revealReactions == nil {
NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scrollView.clipView, queue: OperationQueue.main, using: { [weak self] notification in
self?.updateScroll()
})
} else {
var calc:CGFloat = 0
var clicked: Bool = false
scrollView.applyExternalScroll = { [weak self] event in
calc += abs(event.deltaY)
calc += abs(event.deltaX)
if calc > 30, !clicked {
self?.showMore.send(event: .Click)
AppMenu.closeAll()
clicked = true
return false
}
return true
}
}
scrollView.background = .clear
scrollView.documentView = documentView
let size = ContextAddReactionsListView.size
var x: CGFloat = 1
var y: CGFloat = 3
if let aboveText = aboveText {
y += aboveText.layoutSize.height + 2
}
for reaction in list {
let add:(ContextReaction)->Void = { reaction in
let itemSize = size.bounds
let reaction = ReactionView(frame: NSMakeRect(x, y, itemSize.width, itemSize.height), context: context, reaction: reaction, add: add, theme: presentation)
self.documentView.addSubview(reaction)
x += size.width + 4
}
if x < frame.width {
add(reaction)
} else {
DispatchQueue.main.async {
add(reaction)
}
}
}
if let aboveText = aboveText {
let aboveTextView = TextView()
aboveTextView.userInteractionEnabled = true
aboveTextView.isSelectable = false
addSubview(aboveTextView)
self.aboveTextView = aboveTextView
aboveTextView.update(aboveText)
}
updateLayout(size: frame.size, transition: .immediate)
for view in self.documentView.subviews {
let view = view as? ReactionView
view?.playAppearAnimation()
}
updateScroll()
}
func collect() -> [Int : LottiePlayerView] {
var frames:[Int : LottiePlayerView] = [:]
for (i, view) in self.documentView.subviews.enumerated() {
if let view = view as? ReactionView {
frames[i] = view.player
}
}
return frames
}
func invokeFirst() {
for view in self.documentView.subviews {
if let view = view as? ReactionView {
view.send(event: .Click)
return
}
}
}
static var size: CGSize {
return .init(width: 37, height: 34)
}
func rect(for reaction: ContextReaction) -> NSRect {
let view = documentView.subviews.compactMap {
$0 as? ReactionView
}.first(where: {
$0.reaction == reaction
})
if let view = view {
return view.frame
} else {
return .zero
}
}
private var previousOffset: NSPoint = .zero
private var previousRange: [Int] = []
private func updateScroll() {
self.topGradient.isHidden = self.scrollView.documentOffset.x == 0
self.bottomGradient.isHidden = self.scrollView.documentOffset.x == self.scrollView.documentSize.width - self.scrollView.frame.width
let range = visibleRange(self.scrollView.documentOffset)
if previousRange != range, !previousRange.isEmpty {
let new = range.filter({
!previousRange.contains($0)
})
for i in new {
let view = self.documentView.subviews[i] as? ReactionView
view?.playAppearAnimation()
}
}
self.previousRange = range
if self.radiusLayer != nil {
for view in documentView.subviews {
var fr = CATransform3DIdentity
if view.visibleRect.size != view.frame.size {
let value = max(0.5, view.visibleRect.width / view.frame.width)
fr = CATransform3DTranslate(fr, view.frame.width / 2, view.frame.height / 2, 0)
fr = CATransform3DScale(fr, value, value, 1)
fr = CATransform3DTranslate(fr, -(view.frame.width / 2), -(view.frame.height / 2), 0)
view.layer?.transform = fr
} else {
view.layer?.transform = fr
}
}
}
}
private func visibleRange(_ documentOffset: NSPoint) -> [Int] {
var range: [Int] = []
for (i, view) in documentView.subviews.enumerated() {
if view.visibleRect != .zero {
range.append(i)
}
}
return range
}
override func layout() {
super.layout()
updateLayout(size: frame.size, transition: .immediate)
}
static func width(for count: Int, maxCount: Int = .max, allowToAll: Bool = true) -> CGFloat {
var width = CGFloat(min(count, maxCount)) * self.size.width
width += CGFloat(min(count, maxCount)) * 4
if maxCount != .max, allowToAll {
width += self.size.width
}
return width
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func update(list: [AvailableReactions.Reaction]) {
}
func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) {
var rect = size.bounds.insetBy(dx: 10, dy: 10)
rect.origin.y -= 5
for subview in documentView.subviews {
let point: NSPoint
if let aboveText = aboveText {
point = NSMakePoint(subview.frame.minX, aboveText.layoutSize.height + 2 + 3)
} else {
point = NSMakePoint(subview.frame.minX, 3)
}
transition.updateFrame(view: subview, frame: CGRect(origin: point, size: subview.frame.size))
}
if let aboveTextView = aboveTextView {
aboveTextView.centerX(y: 8)
}
let documentRect = NSMakeSize(ContextAddReactionsListView.width(for: self.list.count), rect.height).bounds
var scrollRect = rect
if documentRect.width < scrollRect.width, self.list.count < 6 {
scrollRect.size.width = documentRect.width
scrollRect.origin.x = rect.minX + (rect.width - documentRect.width) / 2
}
transition.updateFrame(view: self.documentView, frame: documentRect)
transition.updateFrame(view: self.scrollView, frame: scrollRect)
transition.updateFrame(view: self.topGradient, frame: NSMakeRect(10, 0, 10, size.height))
transition.updateFrame(view: self.bottomGradient, frame: NSMakeRect(rect.width, 0, 10, size.height))
transition.updateFrame(view: visualEffect, frame: size.bounds)
transition.updateFrame(view: backgroundView, frame: size.bounds)
transition.updateFrame(view: backgroundColorView, frame: size.bounds)
if let aboveText = aboveText {
transition.updateFrame(view: showMore, frame: NSMakeRect(rect.maxX - showMore.frame.width - 3, rect.minY + 3 + aboveText.layoutSize.height + 2, showMore.frame.width, showMore.frame.height))
} else {
transition.updateFrame(view: showMore, frame: NSMakeRect(rect.maxX - showMore.frame.width - 3, rect.minY + 3, showMore.frame.width, showMore.frame.height))
}
// transition.updateFrame(layer: maskLayer, frame: rect.size.bounds)
transition.updateFrame(layer: shadowLayer, frame: size.bounds)
maskLayer.path = getMaskPath(rect: rect, hasBubble: self.hasBubble)
shadowLayer.path = getMaskPath(rect: rect, hasBubble: self.hasBubble)
shadowLayer.shadowPath = getMaskPath(rect: rect, hasBubble: self.hasBubble)
if transition.isAnimated {
maskLayer.animatePath()
}
}
private func getMaskPath(rect: CGRect, hasBubble: Bool = true) -> CGPath {
let mutablePath = CGMutablePath()
mutablePath.addRoundedRect(in: rect, cornerWidth: 20, cornerHeight: 20)
if hasBubble {
let bubbleRect = NSMakeRect(rect.width - 40, rect.maxY - 10, 20, 20)
mutablePath.addRoundedRect(in: bubbleRect, cornerWidth: bubbleRect.width / 2, cornerHeight: bubbleRect.width / 2)
}
return mutablePath
}
}
//
//private final class LockView : View {
// private let visualEffect = NSVisualEffectView()
// override init() {
// let frameRect = NSMakeSize(20, 20).bounds
// super.init(frame: frameRect, theme: TelegramPresentationTheme)
// addSubview(visualEffect)
// visualEffect.wantsLayer = true
// visualEffect.blendingMode = .withinWindow
// visualEffect.state = .active
// visualEffect.material = theme.dark ? .dark : .light
//
// let maskLayer = CALayer()
// maskLayer.frame = frameRect
// maskLayer.contents = theme.icons.premium_reaction_lock
//
// self.layer?.mask = maskLayer
//
// self.background = theme.colors.grayText.withAlphaComponent(0.5)
//
// }
//
// required init?(coder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
//
// required init(frame frameRect: NSRect) {
// fatalError("init(frame:) has not been implemented")
// }
//}
/*
final class AddReactionManager : NSObject, Notifable {
private final class ItemView : View {
private let reaction: AvailableReactions.Reaction
init(frame frameRect: NSRect, reaction: AvailableReactions.Reaction) {
self.reaction = reaction
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
private final class ListView : View {
private final class ReactionView : Control {
private let player = LottiePlayerView(frame: NSMakeRect(0, 0, 20, 20))
private let imageView = TransformImageView(frame: NSMakeRect(0, 0, 20, 20))
private let disposable = MetaDisposable()
let reaction: AvailableReactions.Reaction
private let stateDisposable = MetaDisposable()
private let premium: LockView?
required init(frame frameRect: NSRect, context: AccountContext, reaction: AvailableReactions.Reaction, add: @escaping(MessageReaction.Reaction)->Void) {
self.reaction = reaction
if reaction.isPremium, !context.isPremium {
self.premium = LockView()
} else {
self.premium = nil
}
super.init(frame: frameRect)
addSubview(imageView)
addSubview(player)
let signal = context.account.postbox.mediaBox.resourceData(reaction.selectAnimation.resource, attemptSynchronously: true)
|> filter {
$0.complete
}
|> deliverOnMainQueue
_ = fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, reference: .standalone(resource: reaction.selectAnimation.resource)).start()
_ = fetchedMediaResource(mediaBox: context.account.postbox.mediaBox, reference: .standalone(resource: reaction.appearAnimation.resource)).start()
stateDisposable.set(player.state.start(next: { [weak self] state in
switch state {
case .playing:
delay(0.016, closure: {
self?.imageView.removeFromSuperview()
})
case .stoped:
delay(0.016, closure: {
self?.imageView.removeFromSuperview()
})
default:
break
}
}))
let size = imageView.frame.size
let arguments = TransformImageArguments(corners: .init(), imageSize: size, boundingSize: size, intrinsicInsets: NSEdgeInsetsZero, emptyColor: nil)
self.imageView.setSignal(signal: cachedMedia(media: reaction.staticIcon, arguments: arguments, scale: System.backingScale, positionFlags: nil), clearInstantly: true)
if !self.imageView.isFullyLoaded {
imageView.setSignal(chatMessageSticker(postbox: context.account.postbox, file: .standalone(media: reaction.staticIcon), small: false, scale: System.backingScale), cacheImage: { result in
cacheMedia(result, media: reaction.staticIcon, arguments: arguments, scale: System.backingScale)
})
}
imageView.set(arguments: arguments)
disposable.set(signal.start(next: { [weak self] resourceData in
if let data = try? Data(contentsOf: URL.init(fileURLWithPath: resourceData.path)) {
self?.apply(data)
}
}))
set(handler: { _ in
add(reaction.value)
}, for: .Click)
if !reaction.isPremium || context.isPremium {
contextMenu = {
let menu = ContextMenu()
menu.addItem(ContextMenuItem(strings().chatContextReactionQuick, handler: {
context.reactions.updateQuick(reaction.value)
}, itemImage: MenuAnimation.menu_add_to_favorites.value))
return menu
}
}
if let premium = premium {
addSubview(premium)
}
self.imageView.isHidden = premium != nil
self.player.isHidden = premium != nil
}
private func apply(_ data: Data) {
let animation = LottieAnimation(compressed: data, key: LottieAnimationEntryKey(key: .bundle("reaction_\(reaction.value)"), size: player.frame.size), type: .lottie, cachePurpose: .none, playPolicy: .framesCount(1), maximumFps: 30, runOnQueue: .mainQueue())
player.set(animation, reset: false, saveContext: true, animated: false)
}
deinit {
disposable.dispose()
stateDisposable.dispose()
}
override func layout() {
super.layout()
updateLayout(size: self.frame.size, transition: .immediate)
}
func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) {
transition.updateFrame(view: player, frame: self.focus(player.frame.size))
transition.updateFrame(view: imageView, frame: self.focus(imageView.frame.size))
if let premium = premium {
transition.updateFrame(view: premium, frame: self.focus(premium.frame.size))
}
}
private var previous: ControlState = .Normal
override func stateDidUpdate(_ state: ControlState) {
super.stateDidUpdate(state)
switch state {
case .Hover:
if self.player.animation?.playPolicy == .framesCount(1) {
self.player.set(self.player.animation?.withUpdatedPolicy(.once), reset: false)
} else {
self.player.playAgain()
}
default:
break
}
if previous == .Hover, state == .Highlight {
self.layer?.animateScaleCenter(from: 1, to: 0.8, duration: 0.2, removeOnCompletion: false)
} else if state == .Hover && previous == .Highlight {
self.layer?.animateScaleCenter(from: 0.8, to: 1, duration: 0.2, removeOnCompletion: true)
}
previous = state
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
}
private let scrollView = ScrollView()
private let documentView = View()
private let list: [AvailableReactions.Reaction]
private let isReversed: Bool
private let topGradient = ShadowView()
private let bottomGradient = ShadowView()
required init(frame frameRect: NSRect, context: AccountContext, isReversed: Bool, list: [AvailableReactions.Reaction], add:@escaping(MessageReaction.Reaction)->Void) {
self.list = list
self.isReversed = isReversed
super.init(frame: frameRect)
addSubview(scrollView)
addSubview(topGradient)
addSubview(bottomGradient)
scrollView.background = .clear
scrollView.documentView = documentView
let size = NSMakeSize(30, 30)
var y: CGFloat = 0
for reaction in (isReversed ? list.reversed() : list) {
let reaction = ReactionView(frame: NSMakeRect(0, y, size.width, size.height), context: context, reaction: reaction, add: add)
documentView.addSubview(reaction)
y += size.height
}
updateLayout(size: frame.size, transition: .immediate)
if isReversed {
scrollView.clipView.scroll(to: NSMakePoint(0, documentView.frame.height - scrollView.frame.height))
}
bottomGradient.shadowBackground = theme.colors.background.withAlphaComponent(1)
bottomGradient.direction = .vertical(true)
topGradient.shadowBackground = theme.colors.background.withAlphaComponent(1)
topGradient.direction = .vertical(false)
layer?.cornerRadius = frame.width / 2
}
func rect(for reaction: AvailableReactions.Reaction) -> NSRect {
let view = documentView.subviews.compactMap {
$0 as? ReactionView
}.first(where: {
$0.reaction == reaction
})
if let view = view {
return view.frame
} else {