forked from SwiftKickMobile/SwiftMessages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPresenter.swift
402 lines (358 loc) · 16.3 KB
/
Presenter.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
//
// MessagePresenter.swift
// SwiftMessages
//
// Created by Timothy Moose on 7/30/16.
// Copyright © 2016 SwiftKick Mobile LLC. All rights reserved.
//
import UIKit
protocol PresenterDelegate: AnimationDelegate {
func hide(presenter: Presenter)
}
class Presenter: NSObject {
enum PresentationContext {
case viewController(_: Weak<UIViewController>)
case view(_: Weak<UIView>)
func viewControllerValue() -> UIViewController? {
switch self {
case .viewController(let weak):
return weak.value
case .view:
return nil
}
}
func viewValue() -> UIView? {
switch self {
case .viewController(let weak):
return weak.value?.view
case .view(let weak):
return weak.value
}
}
}
let config: SwiftMessages.Config
let view: UIView
weak var delegate: PresenterDelegate?
lazy var maskingView: MaskingView = { return MaskingView() }()
var presentationContext = PresentationContext.viewController(Weak<UIViewController>(value: nil))
let animator: Animator
init(config: SwiftMessages.Config, view: UIView, delegate: PresenterDelegate) {
self.config = config
self.view = view
self.delegate = delegate
self.animator = Presenter.animator(forPresentationStyle: config.presentationStyle, delegate: delegate)
if let identifiable = view as? Identifiable {
id = identifiable.id
} else {
var mutableView = view
id = withUnsafePointer(to: &mutableView) { "\($0)" }
}
super.init()
}
private static func animator(forPresentationStyle style: SwiftMessages.PresentationStyle, delegate: AnimationDelegate) -> Animator {
switch style {
case .top:
return TopBottomAnimation(style: .top, delegate: delegate)
case .bottom:
return TopBottomAnimation(style: .bottom, delegate: delegate)
case .center:
return CenterAnimation(delegate: delegate)
case .custom(let animator):
animator.delegate = delegate
return animator
}
}
var id: String
var pauseDuration: TimeInterval? {
let duration: TimeInterval?
switch self.config.duration {
case .automatic:
duration = 2
case .seconds(let seconds):
duration = seconds
case .forever, .indefinite:
duration = nil
}
return duration
}
var showDate: Date?
private var interactivelyHidden = false;
var delayShow: TimeInterval? {
if case .indefinite(let opts) = config.duration { return opts.delay }
return nil
}
/// Returns the required delay for hiding based on time shown
var delayHide: TimeInterval? {
if interactivelyHidden { return 0 }
if case .indefinite(let opts) = config.duration, let showDate = showDate {
let timeIntervalShown = -showDate.timeIntervalSinceNow
return max(0, opts.minimum - timeIntervalShown)
}
return nil
}
/*
MARK: - Showing and hiding
*/
func show(completion: @escaping AnimationCompletion) throws {
try presentationContext = getPresentationContext()
install()
self.config.eventListeners.forEach { $0(.willShow) }
showAnimation() { completed in
completion(completed)
if completed {
if self.config.dimMode.modal {
self.showAccessibilityFocus()
} else {
self.showAccessibilityAnnouncement()
}
self.config.eventListeners.forEach { $0(.didShow) }
}
}
}
private func showAnimation(completion: @escaping AnimationCompletion) {
func dim(_ color: UIColor) {
self.maskingView.backgroundColor = UIColor.clear
UIView.animate(withDuration: 0.2, animations: {
self.maskingView.backgroundColor = color
})
}
func blur(style: UIBlurEffectStyle, alpha: CGFloat) {
let blurView = UIVisualEffectView(effect: nil)
blurView.alpha = alpha
maskingView.backgroundView = blurView
UIView.animate(withDuration: 0.3) {
blurView.effect = UIBlurEffect(style: style)
}
}
let context = animationContext()
animator.show(context: context) { (completed) in
completion(completed)
}
switch config.dimMode {
case .none:
break
case .gray:
dim(UIColor(white: 0, alpha: 0.3))
case .color(let color, _):
dim(color)
case .blur(let style, let alpha, _):
blur(style: style, alpha: alpha)
}
}
private func showAccessibilityAnnouncement() {
guard let accessibleMessage = view as? AccessibleMessage,
let message = accessibleMessage.accessibilityMessage else { return }
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, message)
}
private func showAccessibilityFocus() {
guard let accessibleMessage = view as? AccessibleMessage,
let focus = accessibleMessage.accessibilityElement ?? accessibleMessage.additonalAccessibilityElements?.first else { return }
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, focus)
}
var isHiding = false
func hide(completion: @escaping AnimationCompletion) {
isHiding = true
self.config.eventListeners.forEach { $0(.willHide) }
let context = animationContext()
animator.hide(context: context) { (completed) in
if let viewController = self.presentationContext.viewControllerValue() as? WindowViewController {
viewController.uninstall()
}
self.maskingView.removeFromSuperview()
completion(true)
self.config.eventListeners.forEach { $0(.didHide) }
}
func undim() {
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
self.maskingView.backgroundColor = UIColor.clear
}, completion: nil)
}
func unblur() {
guard let view = maskingView.backgroundView as? UIVisualEffectView else { return }
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
view.effect = nil
}, completion: nil)
}
switch config.dimMode {
case .none:
break
case .gray:
undim()
case .color:
undim()
case .blur:
unblur()
}
}
private func animationContext() -> AnimationContext {
return AnimationContext(messageView: view, containerView: maskingView, safeZoneConflicts: safeZoneConflicts(), interactiveHide: config.interactiveHide)
}
private func safeZoneConflicts() -> SafeZoneConflicts {
guard let window = maskingView.window else { return [] }
let inNormalWindowLevel: Bool = {
if let vc = presentationContext.viewControllerValue() as? WindowViewController {
return vc.windowLevel == UIWindowLevelNormal
}
return true
} ()
// TODO `underNavigationBar` and `underTabBar` should look up the presentation context's hierarchy
// TODO for cases where both should be true (probably not an issue for typical height messages, though).
let underNavigationBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UINavigationController { return vc.sm_isVisible(view: vc.navigationBar) }
return false
}()
let underTabBar: Bool = {
if let vc = presentationContext.viewControllerValue() as? UITabBarController { return vc.sm_isVisible(view: vc.tabBar) }
return false
}()
if #available(iOS 11, *) {
if !inNormalWindowLevel {
// TODO seeing `maskingView.safeAreaInsets.top` value of 20 on
// iPhone 8 with status bar window level, which doesn't seem right
// since the status bar is covered by the window. Applying a special rule
// to allow the animator to revove this amount from the layout margins if needed.
if maskingView.safeAreaInsets.top <= 20 {
return [.coveredStatusBar]
} else {
return [.sensorNotch, .homeIndicator]
}
}
var conflicts: SafeZoneConflicts = []
if !underNavigationBar {
conflicts.formUnion(.sensorNotch)
}
if !underTabBar {
conflicts.formUnion(.homeIndicator)
}
return conflicts
} else {
if UIApplication.shared.isStatusBarHidden { return [] }
if !inNormalWindowLevel || underNavigationBar { return [] }
let statusBarFrame = UIApplication.shared.statusBarFrame
let statusBarWindowFrame = window.convert(statusBarFrame, from: nil)
let statusBarViewFrame = maskingView.convert(statusBarWindowFrame, from: nil)
return statusBarViewFrame.intersects(maskingView.bounds) ? SafeZoneConflicts.statusBar : []
}
}
private func getPresentationContext() throws -> PresentationContext {
func newWindowViewController(_ windowLevel: UIWindowLevel) -> UIViewController {
let viewController = WindowViewController(windowLevel: windowLevel, config: config)
return viewController
}
switch config.presentationContext {
case .automatic:
if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
let viewController = rootViewController.sm_selectPresentationContextTopDown(config)
return .viewController(Weak(value: viewController))
} else {
throw SwiftMessagesError.noRootViewController
}
case .window(let level):
let viewController = newWindowViewController(level)
return .viewController(Weak(value: viewController))
case .viewController(let viewController):
let viewController = viewController.sm_selectPresentationContextBottomUp(config)
return .viewController(Weak(value: viewController))
case .view(let view):
return .view(Weak(value: view))
}
}
/*
MARK: - Installation
*/
func install() {
func topLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .top = config.presentationStyle, let nav = viewController as? UINavigationController, nav.sm_isVisible(view: nav.navigationBar) {
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: nav.navigationBar, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.00, constant: 0.0)
}
func bottomLayoutConstraint(view: UIView, containerView: UIView, viewController: UIViewController?) -> NSLayoutConstraint {
if case .bottom = config.presentationStyle, let tab = viewController as? UITabBarController, tab.sm_isVisible(view: tab.tabBar) {
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: tab.tabBar, attribute: .top, multiplier: 1.00, constant: 0.0)
}
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1.00, constant: 0.0)
}
func installMaskingView(containerView: UIView) {
maskingView.translatesAutoresizingMaskIntoConstraints = false
if let nav = presentationContext.viewControllerValue() as? UINavigationController {
containerView.insertSubview(maskingView, belowSubview: nav.navigationBar)
} else if let tab = presentationContext.viewControllerValue() as? UITabBarController {
containerView.insertSubview(maskingView, belowSubview: tab.tabBar)
} else {
containerView.addSubview(maskingView)
}
let leading = NSLayoutConstraint(item: maskingView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.00, constant: 0.0)
let trailing = NSLayoutConstraint(item: maskingView, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1.00, constant: 0.0)
let top = topLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue())
let bottom = bottomLayoutConstraint(view: maskingView, containerView: containerView, viewController: presentationContext.viewControllerValue())
containerView.addConstraints([top, leading, bottom, trailing])
// Update the container view's layout in order to know the masking view's frame
containerView.layoutIfNeeded()
}
func installInteractive() {
guard config.dimMode.modal else { return }
if config.dimMode.interactive {
maskingView.tappedHander = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.interactivelyHidden = true
strongSelf.delegate?.hide(presenter: strongSelf)
}
} else {
// There's no action to take, but the presence of
// a tap handler prevents interaction with underlying views.
maskingView.tappedHander = { }
}
}
func installAccessibility() {
var elements: [NSObject] = []
if let accessibleMessage = view as? AccessibleMessage {
if let message = accessibleMessage.accessibilityMessage {
let element = accessibleMessage.accessibilityElement ?? view
element.isAccessibilityElement = true
if element.accessibilityLabel == nil {
element.accessibilityLabel = message
}
elements.append(element)
}
if let additional = accessibleMessage.additonalAccessibilityElements {
elements += additional
}
}
if config.dimMode.interactive {
let dismissView = UIView(frame: maskingView.bounds)
dismissView.translatesAutoresizingMaskIntoConstraints = true
dismissView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
maskingView.addSubview(dismissView)
maskingView.sendSubview(toBack: dismissView)
dismissView.isUserInteractionEnabled = false
dismissView.isAccessibilityElement = true
dismissView.accessibilityLabel = config.dimModeAccessibilityLabel
dismissView.accessibilityTraits = UIAccessibilityTraitButton
elements.append(dismissView)
}
if config.dimMode.modal {
maskingView.accessibilityViewIsModal = true
}
maskingView.accessibleElements = elements
}
guard let containerView = presentationContext.viewValue() else { return }
if let windowViewController = presentationContext.viewControllerValue() as? WindowViewController {
windowViewController.install(becomeKey: becomeKeyWindow)
}
installMaskingView(containerView: containerView)
installInteractive()
installAccessibility()
}
private var becomeKeyWindow: Bool {
if config.becomeKeyWindow == .some(true) { return true }
switch config.dimMode {
case .gray, .color, .blur:
// Should become key window in modal presentation style
// for proper VoiceOver handling.
return true
case .none:
return false
}
}
}