mvm_core_ui/MVMCoreUI/Accessibility/AccessibilityHandler.swift

224 lines
9.2 KiB
Swift

//
// AccessibilityHandler.swift
// MVMCoreUI
//
// Created by Bandaru, Krishna Kishore on 30/06/23.
// Copyright © 2023 Verizon Wireless. All rights reserved.
//
import Foundation
import Combine
public enum AccessibilityNotificationType {
case controllerChanged, layoutChanged, screenChanged, announcement
//TODO: - Foucs is shifting to respective element only if we add delay only on new viewcontroller appear. Need to investigate futher.
//https://developer.apple.com/forums/thread/132699,
//https://developer.apple.com/forums/thread/655359
//By default from iOS 13+ focus is getting shifted to first interactive element inside viewcontroller not to the navigationitem left barbutton item so posting layoutChanged notification with delay to push to leftbarbutton item on new screen push
var delay: Double {
switch self {
case .controllerChanged:
return 1.5
case .screenChanged, .layoutChanged:
return 0.0
default:
return 0.0
}
}
var accessibilityNotification: UIAccessibility.Notification {
switch self {
case .announcement:
return .announcement
case .screenChanged:
return .screenChanged
case .layoutChanged, .controllerChanged:
return .layoutChanged
}
}
}
public class AccessbilityOperation: MVMCoreOperation {
let argument: Any?
let notificationType: AccessibilityNotificationType
private var timerSource: DispatchSourceTimer?
public init(notificationType: AccessibilityNotificationType, argument: Any?) {
self.notificationType = notificationType
self.argument = argument
}
public override func main() {
Task { @MainActor in
guard UIAccessibility.isVoiceOverRunning, !checkAndHandleForCancellation() else {
stop()
return
}
timerSource = DispatchSource.makeTimerSource()
timerSource?.setEventHandler { [weak self] in
if !(self?.isCancelled ?? false), let notification = self?.notificationType.accessibilityNotification {
UIAccessibility.post(notification: notification, argument: self?.argument)
self?.markAsFinished()
} else {
self?.stop()
}
}
timerSource?.schedule(deadline: .now() + notificationType.delay)
timerSource?.activate()
}
}
public func stop() {
guard isCancelled else { return }
timerSource?.cancel()
markAsFinished()
}
}
open class AccessibilityHandler {
public static func shared() -> Self? {
guard let shared = CoreUIObject.sharedInstance()?.accessibilityHandler else { return nil }
return MVMCoreActionUtility.fatalClassCheck(object: shared)
}
public let webPageNavigated = PassthroughSubject<MVMCoreLoadObject?, Never>()
private var accessibilityOperationQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
private var anyCancellable: Set<AnyCancellable> = []
private weak var delegate: MVMCoreViewControllerProtocol?
private var accessibilityId: String?
private var operationType: UINavigationController.Operation?
private var previousAccessiblityElement: Any?
public init() {
registerWithNotificationCenter()
registerForPageChanges()
registerForFocusChanges()
// registerForTopNotificationsChanges()
registerForWebpageNavigation()
}
/// Registers with the notification center to know when json is updated.
private func registerWithNotificationCenter() {
NotificationCenter.default.publisher(for: NSNotification.Name(rawValue: NotificationResponseLoaded))
.sink { [weak self] notification in
self?.accessibilityId = (notification.userInfo?[String(describing: MVMCoreLoadObject.self)] as? MVMCoreLoadObject)?.pageJSON?.optionalStringForKey("accessibilityId")
}.store(in: &anyCancellable)
}
/// Registers to know when pages change.
private func registerForPageChanges() {
MVMCoreNavigationHandler.shared()?.addDelegate(self)
}
private func registerForFocusChanges() {
//Since foucs shifted to other elements cancelling existing focus shift notifications if any
NotificationCenter.default.publisher(for: UIAccessibility.elementFocusedNotification)
.sink { [weak self] notification in
self?.cancelAllOperations()
}.store(in: &anyCancellable)
}
private func registerForTopNotificationsChanges() {
NotificationHandler.shared()?.onNotificationShown
.sink { [weak self] (view, model) in
self?.post(notification: .layoutChanged, argument: view)
}.store(in: &anyCancellable)
NotificationHandler.shared()?.onNotificationDismissed
.sink { [weak self] (view, model) in
self?.post(notification: .announcement, argument: MVMCoreUIUtility.hardcodedString(withKey: "AccTopAlertClosed"))
self?.post(notification: .screenChanged, argument: self?.previousAccessiblityElement)
}.store(in: &anyCancellable)
print(anyCancellable)
}
private func registerForWebpageNavigation() {
webPageNavigated.sink { [weak self] _ in
self?.post(notification: .controllerChanged, argument: self?.getFirstFocusedElementOnScreen())
}.store(in: &anyCancellable)
}
private func add(operation: Operation) {
accessibilityOperationQueue.addOperation(operation)
}
private func cancelAllOperations() {
accessibilityOperationQueue.cancelAllOperations()
}
public func post(notification type: AccessibilityNotificationType, argument: Any?) {
guard UIAccessibility.isVoiceOverRunning else { return }
let accessbilityOperation = AccessbilityOperation(notificationType: type, argument: argument)
add(operation: accessbilityOperation)
previousAccessiblityElement = UIAccessibility.focusedElement(using: .notificationVoiceOver)
}
//Subclass can decide to trigger Accessibility notification on screen change.
open func canPostAccessbilityNotification(for viewController: UIViewController) -> Bool { true }
}
extension AccessibilityHandler: MVMCorePresentationDelegateProtocol {
public func navigationController(_ navigationController: UINavigationController, prepareDisplayFor viewController: UIViewController) {
delegate = viewController as? MVMCoreViewControllerProtocol
operationType = navigationController.viewControllers.contains(viewController) ? .pop : .push
}
public func navigationController(_ navigationController: UINavigationController, displayedViewController viewController: UIViewController) {
//TODO: - For push operation we are posting accessibility notification to the top left item or the identified accessibility element from pageJSON. Need to check the logic for pop operation
guard UIAccessibility.isVoiceOverRunning,
operationType == .push,
canPostAccessbilityNotification(for: viewController) else { return }
let accessbilityElement = getAccessbilityFocusedElement()
post(notification: .controllerChanged, argument: accessbilityElement ?? getFirstFocusedElementOnScreen())
}
}
extension AccessibilityHandler {
private func getAccessbilityFocusedElement() -> UIView? {
guard let accessibilityModels: [any AccessibilityElementProtocol] = (delegate?.delegateObject?() as? MVMCoreUIDelegateObject)?.moleculeDelegate?.getRootMolecules().allMoleculesOfType() else { return nil }
guard !accessibilityModels.isEmpty,
let accessibilityModel = (accessibilityModels.filter { $0.id == accessibilityId }).first as? MoleculeModelProtocol else {
return nil
}
return (delegate as? UIViewController)?.view?.getMoleculeViews { (subView: MoleculeViewProtocol) in
print("subview: \(subView)")
guard let moleculeModel = (subView as? MoleculeViewModelProtocol)?.getMoleculeModel() as? (any AccessibilityElementProtocol),
moleculeModel.id == (accessibilityModel as? (any AccessibilityElementProtocol))?.id else {
return false
}
return true
}.first
}
//To get first foucs element on the screen
private func getFirstFocusedElementOnScreen() -> Any? {
(delegate as? UIViewController)?.navigationItem.leftBarButtonItem ?? (delegate as? UIViewController)?.navigationItem.titleView ?? (delegate as? UIViewController)?.navigationController?.navigationBar
}
}
extension UIView {
private func getNestedSubviews<T>() -> [T] {
subviews.flatMap { subView -> [T] in
var result = subView.getNestedSubviews() as [T]
if let view = subView as? T { result.append(view) }
return result
}
}
func getMoleculeViews<T>(filter: ((T) -> Bool)) -> [T] {
return getNestedSubviews().compactMap {
filter($0) ? $0 : nil
}
}
}