// // VDSLabel.swift // VDS // // Created by Matt Bruce on 7/28/22. // import Foundation import UIKit import VDSColorTokens import Combine @objc(VDSLabel) open class Label: UILabel, ViewProtocol, UserInfoable { //-------------------------------------------------- // MARK: - Combine Properties //-------------------------------------------------- /// Set of Subscribers for any Publishers for this Control. open var subscribers = Set() //-------------------------------------------------- // MARK: - Properties //-------------------------------------------------- private var initialSetupPerformed = false /// Key of whether or not updateView() is called in setNeedsUpdate() open var shouldUpdateView: Bool = true open var useAttributedText: Bool = false open var useScaledFont: Bool = false { didSet { setNeedsUpdate() }} /// Current Surface and this is used to pass down to child objects that implement Surfacable open var surface: Surface = .light { didSet { setNeedsUpdate() }} open var attributes: [any LabelAttributeModel]? { didSet { setNeedsUpdate() }} open var textStyle: TextStyle = .defaultStyle { didSet { setNeedsUpdate() }} open var edgeInsets: UIEdgeInsets { textStyle.edgeInsets } open var textPosition: TextPosition = .left { didSet { setNeedsUpdate() }} open var userInfo = [String: Primitive]() open override var numberOfLines: Int { didSet { setNeedsUpdate() }} open override var lineBreakMode: NSLineBreakMode { didSet { setNeedsUpdate() }} override open var text: String? { didSet { attributes = nil setNeedsUpdate() } } /// Whether the View is enabled or not. open override var isEnabled: Bool { didSet { setNeedsUpdate() } } //-------------------------------------------------- // MARK: - Configuration Properties //-------------------------------------------------- open var textColorConfiguration: AnyColorable = ViewColorConfiguration().with { $0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forDisabled: true) $0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOndark, forDisabled: false) }.eraseToAnyColorable(){ didSet { setNeedsUpdate() }} //-------------------------------------------------- // MARK: - Initializers //-------------------------------------------------- required public init() { super.init(frame: .zero) initialSetup() } public override init(frame: CGRect) { super.init(frame: .zero) initialSetup() } public required init?(coder: NSCoder) { super.init(coder: coder) initialSetup() } //-------------------------------------------------- // MARK: - Public Functions //-------------------------------------------------- open func initialSetup() { if !initialSetupPerformed { //register for ContentSizeChanges NotificationCenter .Publisher(center: .default, name: UIContentSizeCategory.didChangeNotification) .sink { [weak self] notification in self?.setNeedsUpdate() }.store(in: &subscribers) backgroundColor = .clear numberOfLines = 0 lineBreakMode = .byWordWrapping translatesAutoresizingMaskIntoConstraints = false accessibilityCustomActions = [] accessibilityTraits = .staticText setup() setNeedsUpdate() } } open func setup() {} /// Resets to default settings. open func reset() { shouldUpdateView = false surface = .light isEnabled = true attributes = nil textStyle = .defaultStyle textPosition = .left text = nil attributedText = nil numberOfLines = 0 backgroundColor = .clear shouldUpdateView = true setNeedsUpdate() } //-------------------------------------------------- // MARK: - Overrides //-------------------------------------------------- open override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: edgeInsets)) } //-------------------------------------------------- // MARK: - Overrides //-------------------------------------------------- /// Function used to make changes to the View based off a change events or from local properties. open func updateView() { if !useAttributedText { if let text = text { accessibilityCustomActions = [] //create the primary string let mutableText = NSMutableAttributedString.mutableText(for: text, textStyle: textStyle, useScaledFont: useScaledFont, textColor: textColorConfiguration.getColor(self), alignment: textPosition.textAlignment, lineBreakMode: lineBreakMode) applyAttributes(mutableText) //set the attributed text attributedText = mutableText //force a drawText setNeedsDisplay() } } } open func updateAccessibility() { accessibilityLabel = text } // MARK: - Private Attributes private func applyAttributes(_ mutableAttributedString: NSMutableAttributedString) { actions = [] if let attributes = attributes { //loop through the models attributes for attribute in attributes { //add attribute on the string attribute.setAttribute(on: mutableAttributedString) //see if the attribute is Actionable if let actionable = attribute as? any ActionLabelAttributeModel{ //create a accessibleAction let customAccessibilityAction = customAccessibilityAction(text: mutableAttributedString.string, range: actionable.range, accessibleText: actionable.accessibleText) //create a wrapper for the attributes range, block and actions.append(LabelAction(range: actionable.range, action: actionable.action, accessibilityID: customAccessibilityAction?.hashValue ?? -1)) } } } } //-------------------------------------------------- // MARK: - Actionable //-------------------------------------------------- private var tapGesture: UITapGestureRecognizer? { willSet { if let tapGesture = tapGesture, newValue == nil { removeGestureRecognizer(tapGesture) } else if let gesture = newValue, tapGesture == nil { addGestureRecognizer(gesture) } } } private struct LabelAction { var range: NSRange var action: PassthroughSubject var accessibilityId: Int = 0 func performAction() { action.send() } init(range: NSRange, action: PassthroughSubject, accessibilityID: Int = 0) { self.range = range self.action = action self.accessibilityId = accessibilityID } } private var actions: [LabelAction] = [] { didSet { isUserInteractionEnabled = !actions.isEmpty accessibilityTraits = !actions.isEmpty ? .link : .staticText if actions.isEmpty { tapGesture = nil } else { //add tap gesture if tapGesture == nil { let singleTap = UITapGestureRecognizer(target: self, action: #selector(textLinkTapped)) singleTap.numberOfTapsRequired = 1 tapGesture = singleTap } if actions.count > 1 { actions.sort { first, second in return first.range.location < second.range.location } } } } } @objc private func textLinkTapped(_ gesture: UITapGestureRecognizer) { for actionable in actions { // This determines if we tapped on the desired range of text. if gesture.didTapActionInLabel(self, inRange: actionable.range) { actionable.performAction() return } } } //-------------------------------------------------- // MARK: - Accessibility For Actions //-------------------------------------------------- private func customAccessibilityAction(text: String?, range: NSRange, accessibleText: String? = nil) -> UIAccessibilityCustomAction? { guard let text = text else { return nil } //TODO: accessibilityHint for Label // if accessibilityHint == nil { // accessibilityHint = MVMCoreUIUtility.hardcodedString(withKey: "swipe_to_select_with_action_hint") // } let actionText = accessibleText ?? NSString(string:text).substring(with: range) let accessibleAction = UIAccessibilityCustomAction(name: actionText, target: self, selector: #selector(accessibilityCustomAction(_:))) accessibilityCustomActions?.append(accessibleAction) return accessibleAction } @objc public func accessibilityCustomAction(_ action: UIAccessibilityCustomAction) { for actionable in actions { if action.hash == actionable.accessibilityId { actionable.performAction() return } } } open override func accessibilityActivate() -> Bool { guard let accessibleActions = accessibilityCustomActions else { return false } for actionable in actions { for action in accessibleActions { if action.hash == actionable.accessibilityId { actionable.performAction() return true } } } return false } }