-
-
Notifications
You must be signed in to change notification settings - Fork 538
Expand file tree
/
Copy pathCore.swift
More file actions
1498 lines (1294 loc) · 61.4 KB
/
Core.swift
File metadata and controls
1498 lines (1294 loc) · 61.4 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
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
// Copyright 2018-Present Shin Yamamoto. All rights reserved. MIT license.
#if canImport(Combine)
import Combine
#endif
import UIKit
import os.log
///
/// The presentation model of FloatingPanel
///
class Core: NSObject, UIGestureRecognizerDelegate {
private weak var ownerVC: FloatingPanelController?
let surfaceView: SurfaceView
var backdropView: BackdropView {
didSet {
backdropView.dismissalTapGestureRecognizer
.addTarget(self, action: #selector(handleBackdrop(tapGesture:)))
}
}
let layoutAdapter: LayoutAdapter
let behaviorAdapter: BehaviorAdapter
weak var scrollView: UIScrollView? {
didSet {
oldValue?.panGestureRecognizer.removeTarget(self, action: nil)
scrollView?.panGestureRecognizer.addTarget(self, action: #selector(handle(panGesture:)))
if let cur = scrollView {
if oldValue == nil {
initialScrollOffset = cur.contentOffset
scrollBounce = cur.bounces
scrollIndictorVisible = cur.showsVerticalScrollIndicator
}
scrollLocked = false
} else {
if let pre = oldValue {
pre.isDirectionalLockEnabled = false
pre.bounces = scrollBounce
pre.showsVerticalScrollIndicator = scrollIndictorVisible
}
}
}
}
private(set) var state: FloatingPanelState = .hidden {
didSet {
os_log(msg, log: devLog, type: .debug, "state changed: \(oldValue) -> \(state)")
if let fpc = ownerVC {
fpc.delegate?.floatingPanelDidChangeState?(fpc)
}
}
}
@available(iOS 13.0, *)
private(set) var statePublisher: CurrentValueSubject<FloatingPanelState, Never>? {
get { _statePublisher as? CurrentValueSubject<FloatingPanelState, Never> }
set { _statePublisher = newValue }
}
private var _statePublisher: Any?
var panGestureRecognizer: FloatingPanelPanGestureRecognizer
let panGestureDelegateRouter: FloatingPanelPanGestureRecognizer.DelegateRouter
var isRemovalInteractionEnabled: Bool = false
fileprivate var isSuspended: Bool = false // Prevent a memory leak in the modal transition
fileprivate var transitionAnimator: UIViewPropertyAnimator?
fileprivate var moveAnimator: NumericSpringAnimator?
private var initialSurfaceLocation: CGPoint = .zero
private var initialTranslation: CGPoint = .zero
private var initialLocation: CGPoint {
return panGestureRecognizer.initialLocation
}
var interactionInProgress: Bool = false
var isAttracting: Bool = false
// Removal interaction
var removalVector: CGVector = .zero
// Scroll handling
private var initialScrollOffset: CGPoint?
private var scrollBounce = false
private var scrollIndictorVisible = false
private var scrollBounceThreshold: CGFloat = -30.0
private var scrollLocked = false
// MARK: - Interface
init(_ vc: FloatingPanelController, layout: FloatingPanelLayout, behavior: FloatingPanelBehavior) {
ownerVC = vc
surfaceView = SurfaceView()
surfaceView.position = layout.position
surfaceView.backgroundColor = .white
backdropView = BackdropView()
backdropView.backgroundColor = .black
backdropView.alpha = 0.0
layoutAdapter = LayoutAdapter(vc: vc, layout: layout)
behaviorAdapter = BehaviorAdapter(vc: vc, behavior: behavior)
panGestureRecognizer = FloatingPanelPanGestureRecognizer()
panGestureDelegateRouter = FloatingPanelPanGestureRecognizer.DelegateRouter(panGestureRecognizer: panGestureRecognizer)
super.init()
if #available(iOS 13.0, *) {
statePublisher = .init(.hidden)
}
panGestureRecognizer.set(floatingPanel: self)
surfaceView.addGestureRecognizer(panGestureRecognizer)
panGestureRecognizer.addTarget(self, action: #selector(handle(panGesture:)))
// Assign the delegate router to `FloatingPanelPanGestureRecognizer.delegate` only after setting
// `FloatingPanelPanGestureRecognizer.floatingPanel` property.
// This is because `delegateOrigin` is used at the time of assignment to its `delegate` property
// through the delegate router.
panGestureRecognizer.delegate = panGestureDelegateRouter
// Set the tap-to-dismiss action of the backdrop view.
// It's disabled by default. See also BackdropView.dismissalTapGestureRecognizer.
backdropView.dismissalTapGestureRecognizer.addTarget(self, action: #selector(handleBackdrop(tapGesture:)))
}
deinit {
// Release `NumericSpringAnimator.displayLink` from the run loop.
self.moveAnimator?.stopAnimation(false)
}
func move(
to: FloatingPanelState,
animated: Bool,
moveAnimator: UIViewPropertyAnimator? = nil,
completion: (() -> Void)? = nil
) {
move(
from: state,
to: to,
animated: animated,
moveAnimator: moveAnimator,
completion: completion
)
}
private func move(
from: FloatingPanelState,
to: FloatingPanelState,
animated: Bool,
moveAnimator: UIViewPropertyAnimator?,
completion: (() -> Void)? = nil
) {
assert(layoutAdapter.validStates.contains(to), "Can't move to '\(to)' state because it's not valid in the layout")
guard let vc = ownerVC else {
completion?()
return
}
if !isScrollable(state: state) {
lockScrollView()
}
tearDownActiveInteraction()
interruptAnimationIfNeeded()
if animated {
let updateScrollView: () -> Void = { [weak self] in
guard let self = self else { return }
if self.isScrollable(state: self.state), 0 == self.layoutAdapter.offset(from: self.state) {
self.unlockScrollView()
} else {
self.lockScrollView()
}
}
let animator: UIViewPropertyAnimator
switch (from, to) {
case (.hidden, let to):
animator = vc.animatorForPresenting(to: to)
case (_, .hidden):
let animationVector = CGVector(dx: abs(removalVector.dx), dy: abs(removalVector.dy))
animator = vc.animatorForDismissing(with: animationVector)
default:
guard let moveAnimator = moveAnimator else {
startAttraction(to: to, with: .zero) { [weak self] in
self?.endAttraction(false)
updateScrollView()
completion?()
}
return
}
animator = moveAnimator
}
let shouldDoubleLayout = from == .hidden
&& surfaceView.hasStackView()
&& layoutAdapter.isIntrinsicAnchor(state: to)
animator.addAnimations { [weak self] in
guard let self = self else { return }
self.state = to
self.updateLayout(to: to)
if shouldDoubleLayout {
os_log(msg, log: sysLog, type: .info, "Lay out the surface again to modify an intrinsic size error according to UIStackView")
self.updateLayout(to: to)
}
}
animator.addCompletion { [weak self] _ in
guard let self = self else { return }
self.transitionAnimator = nil
updateScrollView()
self.ownerVC?.notifyDidMove()
completion?()
}
self.transitionAnimator = animator
if isSuspended {
return
}
animator.startAnimation()
} else {
self.state = to
self.updateLayout(to: to)
if isScrollable(state: state) {
self.unlockScrollView()
} else {
self.lockScrollView()
}
ownerVC?.notifyDidMove()
completion?()
}
}
// MARK: - Layout update
func activateLayout(
forceLayout: Bool = false,
contentInsetAdjustmentBehavior: FloatingPanelController.ContentInsetAdjustmentBehavior
) {
layoutAdapter.prepareLayout()
// preserve the current content offset if contentInsetAdjustmentBehavior is `.always`
var contentOffset: CGPoint?
if contentInsetAdjustmentBehavior == .always {
contentOffset = scrollView?.contentOffset
}
if layoutAdapter.validStates.contains(state) == false {
state = layoutAdapter.initialState
}
layoutAdapter.updateStaticConstraint()
layoutAdapter.activateLayout(for: state, forceLayout: forceLayout)
// Update the backdrop alpha only when called in `Controller.show(animated:completion:)`
// Because that prevents a backdrop flicking just before presenting a panel(#466).
if forceLayout {
backdropView.alpha = getBackdropAlpha(for: state)
}
if let contentOffset = contentOffset {
scrollView?.contentOffset = contentOffset
}
adjustScrollContentInsetIfNeeded()
}
private func updateLayout(to target: FloatingPanelState) {
layoutAdapter.activateLayout(for: target, forceLayout: true)
backdropView.alpha = getBackdropAlpha(for: target)
adjustScrollContentInsetIfNeeded()
if #available(iOS 13.0, *) {
statePublisher?.send(target)
}
}
private func getBackdropAlpha(for target: FloatingPanelState) -> CGFloat {
return target == .hidden ? 0.0 : layoutAdapter.backdropAlpha(for: target)
}
func getBackdropAlpha(at cur: CGFloat, with translation: CGFloat) -> CGFloat {
/* os_log(msg, log: devLog, type: .debug, "currentY: \(currentY) translation: \(translation)") */
let forwardY = (translation >= 0)
let segment = layoutAdapter.segment(at: cur, forward: forwardY)
let lowerState = segment.lower ?? layoutAdapter.mostExpandedState
let upperState = segment.upper ?? layoutAdapter.leastExpandedState
let preState = forwardY ? lowerState : upperState
let nextState = forwardY ? upperState : lowerState
let next = value(of: layoutAdapter.surfaceLocation(for: nextState))
let pre = value(of: layoutAdapter.surfaceLocation(for: preState))
let nextAlpha = layoutAdapter.backdropAlpha(for: nextState)
let preAlpha = layoutAdapter.backdropAlpha(for: preState)
if pre == next {
return preAlpha
}
return preAlpha + max(min(1.0, 1.0 - (next - cur) / (next - pre) ), 0.0) * (nextAlpha - preAlpha)
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGestureRecognizer else { return false }
/* os_log(msg, log: devLog, type: .debug, "shouldRecognizeSimultaneouslyWith", otherGestureRecognizer) */
switch otherGestureRecognizer {
case is FloatingPanelPanGestureRecognizer:
// All visible panels' pan gesture should be recognized simultaneously.
return true
case is UIPanGestureRecognizer,
is UISwipeGestureRecognizer,
is UIRotationGestureRecognizer,
is UIScreenEdgePanGestureRecognizer,
is UIPinchGestureRecognizer:
if surfaceView.grabberAreaContains(gestureRecognizer.location(in: surfaceView)) {
return true
}
// all gestures of the tracking scroll view should be recognized in parallel
// and handle them in self.handle(panGesture:)
return scrollView?.gestureRecognizers?.contains(otherGestureRecognizer) ?? false
default:
// Should recognize tap/long press gestures in parallel when the surface view is at an anchor position.
let adapterY = layoutAdapter.position(for: state)
return abs(value(of: layoutAdapter.surfaceLocation) - adapterY) < (1.0 / surfaceView.fp_displayScale)
}
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if otherGestureRecognizer is FloatingPanelPanGestureRecognizer {
// If this panel is the farthest descendant of visible panels,
// its ancestors' pan gesture must wait for its pan gesture to fail
if let view = otherGestureRecognizer.view, surfaceView.isDescendant(of: view) {
return true
}
}
if otherGestureRecognizer.name == "_UISheetInteractionBackgroundDismissRecognizer" {
// The dismiss gesture of a sheet modal should not begin until the pan gesture fails.
return true
}
if surfaceView.grabberAreaContains(gestureRecognizer.location(in: surfaceView)) {
return true
}
return false
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard gestureRecognizer == panGestureRecognizer else { return false }
// Should begin the pan gesture without waiting for the tracking scroll view's gestures.
// `scrollView.gestureRecognizers` can contains the following gestures
// * UIScrollViewDelayedTouchesBeganGestureRecognizer
// * UIScrollViewPanGestureRecognizer (scrollView.panGestureRecognizer)
// * _UIDragAutoScrollGestureRecognizer
// * _UISwipeActionPanGestureRecognizer
// * UISwipeDismissalGestureRecognizer
if let scrollView = scrollView {
// On short contents scroll, `_UISwipeActionPanGestureRecognizer` blocks
// the panel's pan gesture if not returns false
if let scrollGestureRecognizers = scrollView.gestureRecognizers,
scrollGestureRecognizers.contains(otherGestureRecognizer) {
switch otherGestureRecognizer {
case scrollView.panGestureRecognizer:
if surfaceView.grabberAreaContains(gestureRecognizer.location(in: surfaceView)) {
return false
}
guard isScrollable(state: state) else { return false }
// The condition where offset > 0 must not be included here. Because it will stop recognizing
// the panel pan gesture if a user starts scrolling content from an offset greater than 0.
return allowScrollPanGesture(of: scrollView) { offset in offset <= scrollBounceThreshold }
default:
return false
}
}
}
switch otherGestureRecognizer {
case is FloatingPanelPanGestureRecognizer:
// If this panel is the farthest descendant of visible panels,
// its pan gesture does not require its ancestors' pan gesture to fail
if let view = otherGestureRecognizer.view, surfaceView.isDescendant(of: view) {
return false
}
return true
case is UIPanGestureRecognizer,
is UISwipeGestureRecognizer,
is UIRotationGestureRecognizer,
is UIScreenEdgePanGestureRecognizer,
is UIPinchGestureRecognizer:
if otherGestureRecognizer.name == "_UISheetInteractionBackgroundDismissRecognizer" {
// Should begin the pan gesture without waiting the dismiss gesture of a sheet modal.
return false
}
if surfaceView.grabberAreaContains(gestureRecognizer.location(in: surfaceView)) {
return false
}
// Do not begin the pan gesture until these gestures fail
return true
default:
// Should begin the pan gesture without waiting tap/long press gestures fail
return false
}
}
// MARK: - Gesture handling
@objc func handleBackdrop(tapGesture: UITapGestureRecognizer) {
removalVector = .zero
ownerVC?.remove()
}
@objc func handle(panGesture: UIPanGestureRecognizer) {
switch panGesture {
case scrollView?.panGestureRecognizer:
guard let scrollView = scrollView else { return }
let velocity = value(of: panGesture.velocity(in: panGesture.view))
let location = panGesture.location(in: surfaceView)
let insideMostExpandedAnchor = 0 < layoutAdapter.offsetFromMostExpandedAnchor
os_log(msg, log: devLog, type: .debug, """
scroll gesture(\(state):\(panGesture.state)) -- \
inside expanded anchor = \(insideMostExpandedAnchor), \
interactionInProgress = \(interactionInProgress), \
scroll offset = \(value(of: scrollView.contentOffset)), \
location = \(value(of: location)), velocity = \(velocity)
"""
)
let baseOffset = contentOffsetForPinning(of: scrollView)
let offsetDiff = value(of: scrollView.contentOffset - baseOffset)
if insideMostExpandedAnchor {
// Prevent scrolling if needed
if isScrollable(state: state), let initialScrollOffset = initialScrollOffset {
if interactionInProgress {
os_log(msg, log: devLog, type: .debug, "settle offset -- \(value(of: initialScrollOffset))")
// Return content offset to initial offset to prevent scrolling
stopScrolling(at: initialScrollOffset)
} else {
if surfaceView.grabberAreaContains(initialLocation) {
// Preserve the current content offset in moving from full.
stopScrolling(at: initialScrollOffset)
}
/// When the scroll offset is at the pinned offset and a panel is moved, the content
/// must be fixed at the pinned position without scrolling. According to the scroll
/// pan gesture behavior, the content might have already scrolled a bit by the time
/// this handler is called. Thus `initialScrollOffset` property is used here.
if value(of: initialScrollOffset - baseOffset) == 0.0 {
stopScrolling(at: initialScrollOffset)
}
}
} else if let initialScrollOffset = initialScrollOffset {
// Return content offset to initial offset to prevent scrolling
stopScrolling(at: initialScrollOffset)
}
// Hide a scroll indicator at the non-top in dragging.
if interactionInProgress {
lockScrollView()
} else {
// Put back the scroll indicator and bounce of tracking scroll view
// for scrollable states, not most expanded state.
if isScrollable(state: state), self.transitionAnimator == nil {
switch layoutAdapter.position {
case .top, .left:
if offsetDiff < 0 && velocity > 0 {
unlockScrollView()
}
case .bottom, .right:
if offsetDiff > 0 && velocity < 0 {
unlockScrollView()
}
}
}
}
} else {
// Here handles seamless scrolling at the most expanded position
if interactionInProgress {
// Show a scroll indicator at the top in dragging.
switch layoutAdapter.position {
case .top, .left:
if offsetDiff <= 0 && velocity >= 0 {
unlockScrollView()
return
}
case .bottom, .right:
if offsetDiff >= 0 && velocity <= 0 {
unlockScrollView()
return
}
}
if isScrollable(state: state) {
// Adjust a small gap of the scroll offset just after swiping down starts in the grabber area.
if surfaceView.grabberAreaContains(location), surfaceView.grabberAreaContains(initialLocation),
let initialScrollOffset = initialScrollOffset {
stopScrolling(at: initialScrollOffset)
}
}
} else {
if isScrollable(state: state) {
let allowScroll = allowScrollPanGesture(of: scrollView) { offset in
offset <= scrollBounceThreshold || 0 < offset
}
switch layoutAdapter.position {
case .top, .left:
if velocity < 0, !allowScroll {
lockScrollView(strict: true)
}
if velocity > 0, allowScroll {
unlockScrollView()
}
case .bottom, .right:
// Hide a scroll indicator just before starting an interaction by swiping a panel down.
if velocity > 0, !allowScroll {
lockScrollView(strict: true)
}
// Show a scroll indicator when an animation is interrupted at the top and content is scrolled up
if velocity < 0, allowScroll {
unlockScrollView()
}
}
// Adjust a small gap of the scroll offset just before swiping down starts in the grabber area,
if surfaceView.grabberAreaContains(location), surfaceView.grabberAreaContains(initialLocation),
let initialScrollOffset = initialScrollOffset {
stopScrolling(at: initialScrollOffset)
}
}
}
}
case panGestureRecognizer:
let translation = panGesture.translation(in: panGestureRecognizer.view!.superview)
// The touch velocity in the surface view
let velocity = panGesture.velocity(in: panGesture.view)
// The touch location in the surface view
let location = panGesture.location(in: panGesture.view)
os_log(msg, log: devLog, type: .debug, """
panel gesture(\(state):\(panGesture.state)) -- \
translation = \(value(of: translation)), \
location = \(value(of: location)), \
velocity = \(value(of: velocity))
""")
if interactionInProgress == false, isAttracting == false,
let vc = ownerVC, vc.delegate?.floatingPanelShouldBeginDragging?(vc) == false {
return
}
interruptAnimationIfNeeded()
if panGesture.state == .began {
panningBegan(at: location)
return
}
if shouldScrollViewHandleTouch(scrollView, point: location, velocity: value(of: velocity)) {
return
}
switch panGesture.state {
case .changed:
if interactionInProgress == false {
startInteraction(with: translation, at: location)
}
panningChange(with: translation)
case .ended, .cancelled, .failed:
if interactionInProgress == false {
startInteraction(with: translation, at: location)
// Workaround: Prevent stopping the surface view b/w anchors if the pan gesture
// doesn't pass through .changed state after an interruptible animator is interrupted.
let diff = translation - .leastNonzeroMagnitude
layoutAdapter.updateInteractiveEdgeConstraint(diff: value(of: diff),
scrollingContent: true,
allowsRubberBanding: behaviorAdapter.allowsRubberBanding(for:))
}
panningEnd(with: translation, velocity: velocity)
default:
break
}
default:
return
}
}
private func interruptAnimationIfNeeded() {
if let animator = self.moveAnimator, animator.isRunning {
os_log(msg, log: devLog, type: .debug, "the attraction animator interrupted!!!")
animator.stopAnimation(true)
endAttraction(false)
}
if let animator = self.transitionAnimator {
guard 0 <= layoutAdapter.offsetFromMostExpandedAnchor else { return }
os_log(msg, log: devLog, type: .debug, "a panel animation(interruptible: \(animator.isInterruptible)) interrupted!!!")
if animator.isInterruptible {
animator.stopAnimation(false)
// A user can stop a panel at the nearest Y of a target position so this fine-tunes
// the a small gap between the presentation layer frame and model layer frame
// to unlock scroll view properly at finishAnimation(at:)
if 0 == layoutAdapter.offsetFromMostExpandedAnchor {
layoutAdapter.surfaceLocation = layoutAdapter.surfaceLocation(for: layoutAdapter.mostExpandedState)
}
animator.finishAnimation(at: .current)
} else {
animator.stopAnimation(true)
}
}
}
private func shouldScrollViewHandleTouch(_ scrollView: UIScrollView?, point: CGPoint, velocity: CGFloat) -> Bool {
// When no scrollView, nothing to handle.
guard let scrollView = scrollView, scrollView.frame.contains(initialLocation) else { return false }
// Prevents moving a panel on swipe actions using _UISwipeActionPanGestureRecognizer.
// [Warning] Do not apply this to WKWebView. Since iOS 17.4, WKWebView has an additional pan
// gesture recognizer besides UIScrollViewPanGestureRecognizer. Applying this to WKWebView
// will block panel movements because another pan gesture isn't `scrollView.panGestureRecognizer`.
if let scrollGestureRecognizers = scrollView.gestureRecognizers,
scrollView is UITableView || scrollView is UICollectionView {
for gesture in scrollGestureRecognizers {
guard gesture.state == .began || gesture.state == .changed else {
continue
}
if gesture != scrollView.panGestureRecognizer {
return true
}
}
}
guard
isScrollable(state: state), // When not top most(i.e. .full), don't scroll.
interactionInProgress == false, // When interaction already in progress, don't scroll.
abs(layoutAdapter.offset(from: state)) < 1, // Indistinguishably close to an anchor point.
!surfaceView.grabberAreaContains(initialLocation) // When the initial point is within grabber area, don't scroll
else {
return false
}
let offset = value(of: scrollView.contentOffset - contentOffsetForPinning(of: scrollView))
// The zero offset must be excluded because the offset is usually zero
// after a panel moves from half/tip to full.
switch layoutAdapter.position {
case .top, .left:
if offset < 0.0 {
return true
}
if velocity >= 0, offset > 0.0 {
return true
}
case .bottom, .right:
if offset > 0.0 {
return true
}
if velocity <= 0, offset < 0.0 {
return true
}
}
if scrollView.isDecelerating {
return true
}
if let tableView = (scrollView as? UITableView), tableView.isEditing {
return true
}
return false
}
private func panningBegan(at location: CGPoint) {
// A user interaction does not always start from Began state of the pan gesture
// because it can be recognized in scrolling a content in a content view controller.
// So here just preserve the current state if needed.
os_log(msg, log: devLog, type: .debug, "panningBegan -- location = \(value(of: location))")
guard let scrollView = scrollView else { return }
initialScrollOffset = scrollView.contentOffset
}
private func panningChange(with translation: CGPoint) {
let pre = value(of: layoutAdapter.surfaceLocation)
let diff = value(of: translation - initialTranslation)
let next = pre + diff
os_log(msg, log: devLog, type: .debug, """
panningChange -- translation = \(value(of: translation)), diff = \(diff), pre = \(pre), next = \(next)
""")
layoutAdapter.updateInteractiveEdgeConstraint(
diff: diff,
scrollingContent: shouldScrollingContentInMoving(from: pre, to: next),
allowsRubberBanding: behaviorAdapter.allowsRubberBanding(for:)
)
let cur = value(of: layoutAdapter.surfaceLocation)
backdropView.alpha = getBackdropAlpha(at: cur, with: value(of: translation))
guard (pre != cur) else { return }
if let vc = ownerVC {
vc.delegate?.floatingPanelDidMove?(vc)
}
}
/// Determines if the content should scroll while the surface is moving from `cur` to `target`.
///
/// - Note: `cur` argument starts from an anchor location of surface view in a state. For example,
/// it starts from zero if the state is full whose FloatingPanelLayoutAnchor.absoluteInset is zero
/// and there is no additional safe area insets like a navigation bar. Therefore, `cur` argument
/// can be minus if the absoluteInset is minus with such a condition.
private func shouldScrollingContentInMoving(from cur: CGFloat, to target: CGFloat) -> Bool {
// Don't allow scrolling if the initial panning location is in the grabber area.
if surfaceView.grabberAreaContains(initialLocation) {
return false
}
if let sv = scrollView, sv.panGestureRecognizer.state == .changed {
let (contentSize, bounds, alwaysBounceHorizontal, alwaysBounceVertical)
= (sv.contentSize, sv.bounds, sv.alwaysBounceHorizontal, sv.alwaysBounceVertical)
switch layoutAdapter.position {
case .top:
if cur < target, contentSize.height > bounds.height || alwaysBounceVertical {
return true
}
case .left:
if cur < target, contentSize.width > bounds.width || alwaysBounceHorizontal {
return true
}
case .bottom:
if cur > target, contentSize.height > bounds.height || alwaysBounceVertical {
return true
}
case .right:
if cur > target, contentSize.width > bounds.width || alwaysBounceHorizontal {
return true
}
}
}
return false
}
private func panningEnd(with translation: CGPoint, velocity: CGPoint) {
os_log(msg, log: devLog, type: .debug, "panningEnd -- translation = \(value(of: translation)), velocity = \(value(of: velocity))")
if state == .hidden {
os_log(msg, log: devLog, type: .debug, "Already hidden")
return
}
let currentPos = value(of: layoutAdapter.surfaceLocation)
let mainVelocity = value(of: velocity)
var target = self.targetState(from: currentPos, with: mainVelocity)
endInteraction(for: target)
if isRemovalInteractionEnabled {
let distToHidden = CGFloat(abs(currentPos - layoutAdapter.position(for: .hidden)))
switch layoutAdapter.position {
case .top, .bottom:
removalVector = (distToHidden != 0) ? CGVector(dx: 0.0, dy: velocity.y/distToHidden) : .zero
case .left, .right:
removalVector = (distToHidden != 0) ? CGVector(dx: velocity.x/distToHidden, dy: 0.0) : .zero
}
if shouldRemove(with: removalVector) {
ownerVC?.remove()
return
}
}
if let vc = ownerVC {
vc.delegate?.floatingPanelWillEndDragging?(vc, withVelocity: velocity, targetState: &target)
}
guard shouldAttract(to: target) else {
self.endWithoutAttraction(target)
return
}
if let vc = ownerVC {
vc.delegate?.floatingPanelDidEndDragging?(vc, willAttract: true)
}
startAttraction(to: target, with: velocity) { [weak self] in
self?.endAttraction(true)
}
}
// MARK: - Behavior
private func shouldRemove(with velocityVector: CGVector) -> Bool {
guard let vc = ownerVC else { return false }
if let result = vc.delegate?.floatingPanel?(vc, shouldRemoveAt: vc.surfaceLocation, with: velocityVector) {
return result
}
let threshold = behaviorAdapter.removalInteractionVelocityThreshold
switch layoutAdapter.position {
case .top:
return (velocityVector.dy <= -threshold)
case .left:
return (velocityVector.dx <= -threshold)
case .bottom:
return (velocityVector.dy >= threshold)
case .right:
return (velocityVector.dx >= threshold)
}
}
private func startInteraction(with translation: CGPoint, at location: CGPoint) {
/* Don't lock a scroll view to show a scroll indicator after hitting the top */
os_log(msg, log: devLog, type: .debug, "startInteraction -- translation = \(value(of: translation)), location = \(value(of: location))")
guard interactionInProgress == false else { return }
var offset: CGPoint = .zero
initialSurfaceLocation = layoutAdapter.surfaceLocation
if isScrollable(state: state), let scrollView = scrollView {
ifLabel: if surfaceView.grabberAreaContains(initialLocation) {
initialScrollOffset = scrollView.contentOffset
} else if scrollView.frame.contains(initialLocation) {
let pinningOffset = contentOffsetForPinning(of: scrollView)
// This code block handles the scenario where there's a navigation bar or toolbar
// above the tracking scroll view with corresponding content insets set, and users
// move the panel by interacting with these bars. One case of the scenario can be
// tested with 'Show Navigation Controller' in Samples.app
do {
// Adjust the location by subtracting scrollView's origin to reference the frame
// rectangle of the scroll view itself.
let _location = scrollView.convert(location, from: surfaceView) - scrollView.bounds.origin
os_log(msg, log: devLog, type: .debug, "startInteraction -- location in scroll view = \(_location))")
// Keep the scroll content offset if the current touch position is inside its
// content inset area.
switch layoutAdapter.position {
case .top, .left:
let base = value(of: scrollView.bounds.size)
if value(of: pinningOffset) + (base - value(of: _location)) < 0 {
initialScrollOffset = scrollView.contentOffset
break ifLabel
}
case .bottom, .right:
if value(of: pinningOffset) + value(of: _location) < 0 {
initialScrollOffset = scrollView.contentOffset
break ifLabel
}
}
}
// `initialScrollOffset` must be reset to the pinning offset because the value of `scrollView.contentOffset`,
// for instance, is a value in [-30, 0) on a bottom positioned panel with `allowScrollPanGesture(of:condition:)`.
// If it's not reset, the following logic to shift the surface frame will not work and then the scroll
// content offset will become an unexpected value.
initialScrollOffset = pinningOffset
// Shift the surface frame to negate the scroll content offset at startInteraction(at:offset:)
let offsetDiff = scrollView.contentOffset - pinningOffset
switch layoutAdapter.position {
case .top, .left:
if value(of: offsetDiff) > 0 {
offset = -offsetDiff
}
case .bottom, .right:
if value(of: offsetDiff) < 0 {
offset = -offsetDiff
}
}
} else {
initialScrollOffset = scrollView.contentOffset
}
os_log(msg, log: devLog, type: .debug, "initial scroll offset -- \(optional: initialScrollOffset)")
}
initialTranslation = translation
if let vc = ownerVC {
vc.delegate?.floatingPanelWillBeginDragging?(vc)
}
layoutAdapter.startInteraction(at: state, offset: offset)
interactionInProgress = true
lockScrollView()
}
private func endInteraction(for state: FloatingPanelState) {
os_log(msg, log: devLog, type: .debug, "endInteraction to \(state)")
if let scrollView = scrollView {
os_log(msg, log: devLog, type: .debug, "endInteraction -- scroll offset = \(scrollView.contentOffset)")
}
interactionInProgress = false
// Prevent to keep a scroll view indicator visible at the half/tip position
if !isScrollable(state: state) {
lockScrollView()
}
layoutAdapter.endInteraction(at: state)
}
private func tearDownActiveInteraction() {
guard panGestureRecognizer.isEnabled else { return }
// Cancel the pan gesture so that panningEnd(with:velocity:) is called
panGestureRecognizer.isEnabled = false
panGestureRecognizer.isEnabled = true
}
private func shouldAttract(to state: FloatingPanelState) -> Bool {
if layoutAdapter.position(for: state) == value(of: layoutAdapter.surfaceLocation) {
return false
}
return true
}
private func startAttraction(to state: FloatingPanelState, with velocity: CGPoint, completion: @escaping (() -> Void)) {
os_log(msg, log: devLog, type: .debug, "startAnimation to \(state) -- velocity = \(value(of: velocity))")
guard let vc = ownerVC else { return }
isAttracting = true
vc.delegate?.floatingPanelWillBeginAttracting?(vc, to: state)
move(to: state, with: value(of: velocity), completion: completion)
}
private func move(to state: FloatingPanelState, with velocity: CGFloat, completion: @escaping (() -> Void)) {
let (animationConstraint, target) = layoutAdapter.setUpAttraction(to: state)
let initialData = NumericSpringAnimator.Data(value: animationConstraint.constant, velocity: velocity)
moveAnimator = NumericSpringAnimator(
initialData: initialData,
target: target,
displayScale: surfaceView.fp_displayScale,
decelerationRate: behaviorAdapter.springDecelerationRate,
responseTime: behaviorAdapter.springResponseTime,
update: { [weak self] data in
guard let self = self,
let ownerVC = self.ownerVC // Ensure the owner vc is existing for `layoutAdapter.surfaceLocation`
else { return }
animationConstraint.constant = data.value
let current = self.value(of: self.layoutAdapter.surfaceLocation)
let translation = data.value - initialData.value
self.backdropView.alpha = self.getBackdropAlpha(at: current, with: translation)
// Pin the offset of the tracking scroll view while moving by this animator
if let scrollView = self.scrollView, let initialScrollOffset = self.initialScrollOffset {
self.stopScrolling(at: initialScrollOffset)
os_log(msg, log: devLog, type: .debug, "move -- pinning scroll offset = \(scrollView.contentOffset)")
}
ownerVC.notifyDidMove()
},
completion: { [weak self] in
guard let self = self,
let ownerVC = self.ownerVC
else { return }
self.updateLayout(to: state)
// Notify when it has reached the target anchor point. At this point, the surface location is equal to
// the target anchor location.
ownerVC.notifyDidMove()
completion()
})
moveAnimator?.startAnimation()
self.state = state
}
private func endAttraction(_ tryUnlockScroll: Bool) {
self.isAttracting = false
self.moveAnimator = nil
// We need to reset `initialScrollOffset` because the scroll offset can become unexpected
// under the following circumstances:
// 1. The scroll offset changes while the panel does not move.
// 2. The panel is then moved using `move(to:animate:completion:)`.
self.initialScrollOffset = nil
if let vc = ownerVC {
vc.delegate?.floatingPanelDidEndAttracting?(vc)
}
if let scrollView = scrollView {