Skip to content

Commit

Permalink
Introduce subscription observation token (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
alphatroya authored Mar 30, 2021
1 parent 7320615 commit c0fb1f8
Show file tree
Hide file tree
Showing 17 changed files with 735 additions and 128 deletions.
2 changes: 1 addition & 1 deletion .swiftformat
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
--swiftversion 5.2
--header "\nCopyright © {created.year} Alexey Korolev <alphatroya@gmail.com>\n//"
--header "\nMIT License\n\nCopyright (c) {created.year} Alexey Korolev\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
--maxwidth 140
--wraparguments before-first
--wrapcollections before-first
126 changes: 30 additions & 96 deletions Sources/KeyboardManager/KeyboardManager.swift
Original file line number Diff line number Diff line change
@@ -1,86 +1,32 @@
//
// Copyright © 2020 Alexey Korolev <alphatroya@gmail.com>
// MIT License
//
// Copyright (c) 2021 Alexey Korolev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import UIKit

/// Keyboard's notification observing closure
public typealias KeyboardManagerEventClosure = (KeyboardManagerEvent) -> Void

/// Keyboard transition metadata object
public enum KeyboardManagerEvent {
/// UIKeyboardWillShow notification case event
case willShow(KeyboardManagerEvent.Data)

/// UIKeyboardDidShow notification case event
case didShow(KeyboardManagerEvent.Data)

/// UIKeyboardWillHide notification case event
case willHide(KeyboardManagerEvent.Data)

/// UIKeyboardDidHide notification case event
case didHide(KeyboardManagerEvent.Data)

/// UIKeyboardWillChangeFrame notification case event
case willFrameChange(KeyboardManagerEvent.Data)

/// UIKeyboardDidChangeFrame notification case event
case didFrameChange(KeyboardManagerEvent.Data)

/// `UIKeyboardFrameBeginUserInfoKey` and `UIKeyboardFrameEndUserInfoKey` values
public struct Frame {
/// Begin transition keyboard frame
public var begin: CGRect

/// Final transition keyboard frame
public var end: CGRect
}

/// Notification `userInfo` metadata info
public struct Data {
/// Keyboard frames
public var frame: Frame

/// Animation curve value
public var animationCurve: Int

/// Transition animation duration value
public var animationDuration: Double

/// `UIKeyboardIsLocalUserInfoKey` `userInfo` value
public var isLocal: Bool

static func null() -> Data {
let frame = Frame(begin: CGRect.zero, end: CGRect.zero)
return Data(frame: frame, animationCurve: 0, animationDuration: 0.0, isLocal: false)
}
}

var data: KeyboardManagerEvent.Data {
switch self {
case let .willShow(data),
let .didShow(data),
let .willHide(data),
let .didHide(data),
let .willFrameChange(data),
let .didFrameChange(data):
return data
}
}
}

/// Manager class who monitors keyboard's notification
public final class KeyboardManager {
/// Notify a client for a new parsed keyboard events
public var eventClosure: KeyboardManagerEventClosure?

final class KeyboardManager {
let notificationCenter: NotificationCenter

/**
Keyboard manager instance constructor
- parameter notificationCenter: observed notification center
*/
public init(notificationCenter: NotificationCenter = .default) {
init(notificationCenter: NotificationCenter = .default) {
self.notificationCenter = notificationCenter

notificationCenter.addObserver(
Expand Down Expand Up @@ -125,7 +71,11 @@ public final class KeyboardManager {
notificationCenter.removeObserver(self)
}

private var innerEventClosures: [KeyboardManagerEventClosure] = []
private var observers: [KeyboardManagerEventClosure] = []

func addEventClosure(_ eventClosure: @escaping KeyboardManagerEventClosure) {
observers.append(eventClosure)
}

@objc
private func keyboardWillShow(_ notification: Notification) {
Expand Down Expand Up @@ -158,8 +108,7 @@ public final class KeyboardManager {
}

private func invokeClosures(_ event: KeyboardManagerEvent) {
eventClosure?(event)
innerEventClosures.forEach { $0(event) }
observers.forEach { $0(event) }
}

private func extractData(from notification: Notification) -> KeyboardManagerEvent.Data {
Expand All @@ -179,18 +128,7 @@ public final class KeyboardManager {
isLocal: isLocal.boolValue
)
}
}

public extension KeyboardManager {
/**
Automatically adjusts view's bottom constraint offset after receiving keyboard's notifications

- parameter superview: parent view for adjusted constraints
- parameter bottomConstraint: current bottom constraint instance
- parameter bottomOffset: minimal preserved constraint offset value
- parameter safeAreaInsets: safe area generator for compensate offset for view controllers with tabbar
- parameter animated: should changes be animated
*/
func bindToKeyboardNotifications(
superview: UIView,
bottomConstraint: NSLayoutConstraint,
Expand Down Expand Up @@ -218,19 +156,15 @@ public extension KeyboardManager {
superview.layoutIfNeeded()
}
}
innerEventClosures += [closure]
observers += [closure]
}

/**
Automatically adjusts scrollView's contentInset property with animation after receiving keyboard's notifications
- parameter scrollView: current scroll view instance
*/
func bindToKeyboardNotifications(scrollView: UIScrollView) {
let initialScrollViewInsets = scrollView.contentInset
let closure = { [unowned self] event in
self.handle(by: scrollView, event: event, initialInset: initialScrollViewInsets)
}
innerEventClosures += [closure]
observers += [closure]
}

private func handle(by scrollView: UIScrollView, event: KeyboardManagerEvent, initialInset: UIEdgeInsets) {
Expand Down
86 changes: 86 additions & 0 deletions Sources/KeyboardManager/KeyboardManagerEvent.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//
// MIT License
//
// Copyright (c) 2021 Alexey Korolev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import UIKit

/// Keyboard transition metadata object
public enum KeyboardManagerEvent {
/// UIKeyboardWillShow notification case event
case willShow(KeyboardManagerEvent.Data)

/// UIKeyboardDidShow notification case event
case didShow(KeyboardManagerEvent.Data)

/// UIKeyboardWillHide notification case event
case willHide(KeyboardManagerEvent.Data)

/// UIKeyboardDidHide notification case event
case didHide(KeyboardManagerEvent.Data)

/// UIKeyboardWillChangeFrame notification case event
case willFrameChange(KeyboardManagerEvent.Data)

/// UIKeyboardDidChangeFrame notification case event
case didFrameChange(KeyboardManagerEvent.Data)

/// `UIKeyboardFrameBeginUserInfoKey` and `UIKeyboardFrameEndUserInfoKey` values
public struct Frame {
/// Begin transition keyboard frame
public var begin: CGRect

/// Final transition keyboard frame
public var end: CGRect
}

/// Notification `userInfo` metadata info
public struct Data {
/// Keyboard frames
public var frame: Frame

/// Animation curve value
public var animationCurve: Int

/// Transition animation duration value
public var animationDuration: Double

/// `UIKeyboardIsLocalUserInfoKey` `userInfo` value
public var isLocal: Bool

static func null() -> Data {
let frame = Frame(begin: CGRect.zero, end: CGRect.zero)
return Data(frame: frame, animationCurve: 0, animationDuration: 0.0, isLocal: false)
}
}

var data: KeyboardManagerEvent.Data {
switch self {
case let .willShow(data),
let .didShow(data),
let .willHide(data),
let .didHide(data),
let .willFrameChange(data),
let .didFrameChange(data):
return data
}
}
}
27 changes: 27 additions & 0 deletions Sources/KeyboardManager/KeyboardManagerEventClosure.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// MIT License
//
// Copyright (c) 2021 Alexey Korolev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import Foundation

/// Keyboard's notification observing closure
public typealias KeyboardManagerEventClosure = (KeyboardManagerEvent) -> Void
101 changes: 101 additions & 0 deletions Sources/KeyboardManager/KeyboardObserver.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//
// MIT License
//
// Copyright (c) 2021 Alexey Korolev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

import UIKit

/// Token instance that internally store subscription, cancels subscription on deallocation
public final class KeyboardObserverToken {
init(keyboardManager: KeyboardManager) {
self.keyboardManager = keyboardManager
}

private var keyboardManager: KeyboardManager
}

/// Keyboard observer is a namespace for subscription static methods
public enum KeyboardObserver {
/**
Add observer closure for observing keyboard events
- Parameters:
- notificationCenter: notification center to observe notifications
- observer: closure for observing events
- Returns: observer token that store subscription
*/
public static func addObserver(
_ notificationCenter: NotificationCenter = .default,
_ observer: @escaping KeyboardManagerEventClosure
) -> KeyboardObserverToken {
let keyboardManager = KeyboardManager(notificationCenter: notificationCenter)
keyboardManager.addEventClosure(observer)
return KeyboardObserverToken(keyboardManager: keyboardManager)
}

/**
Automatically adjusts view's bottom constraint offset after receiving keyboard's notifications

- Parameters:
- _ notificationCenter: notification center to observe notifications
- superview: parent view for adjusted constraints
- bottomConstraint: current bottom constraint instance
- bottomOffset: minimal preserved constraint offset value
- safeAreaInsets: safe area generator for compensate offset for view controllers with tabbar
- animated: should changes be animated
- Returns: observer token that store subscription
*/
public static func addObserver(
_ notificationCenter: NotificationCenter = .default,
superview: UIView,
bottomConstraint: NSLayoutConstraint,
bottomOffset: CGFloat = 0.0,
safeAreaInsets: @escaping () -> UIEdgeInsets = { UIEdgeInsets.zero },
animated: Bool = false
) -> KeyboardObserverToken {
let keyboardManager = KeyboardManager(notificationCenter: notificationCenter)
keyboardManager.bindToKeyboardNotifications(
superview: superview,
bottomConstraint: bottomConstraint,
bottomOffset: bottomOffset,
safeAreaInsets: safeAreaInsets,
animated: animated
)
return KeyboardObserverToken(keyboardManager: keyboardManager)
}

/**
Automatically adjusts scrollView's contentInset property with animation after receiving keyboard's notifications
- Parameters:
- _ notificationCenter: notification center to observe notifications
- scrollView: scroll view instance
- Returns: observer token that store subscription
*/
public static func addObserver(
_ notificationCenter: NotificationCenter = .default,
scrollView: UIScrollView
) -> KeyboardObserverToken {
let keyboardManager = KeyboardManager(notificationCenter: notificationCenter)
keyboardManager.bindToKeyboardNotifications(
scrollView: scrollView
)
return KeyboardObserverToken(keyboardManager: keyboardManager)
}
}
Loading

0 comments on commit c0fb1f8

Please sign in to comment.