vds_ios/VDS/Components/Label/Label.swift
Matt Bruce 94ad6cd9f8 updated label/badge to AnyColorable
Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2022-10-10 10:44:04 -05:00

319 lines
11 KiB
Swift

//
// VDSLabel.swift
// VDS
//
// Created by Matt Bruce on 7/28/22.
//
import Foundation
import UIKit
import VDSColorTokens
import Combine
public class Label:LabelBase<DefaultLabelModel>{}
open class LabelBase<ModelType: LabelModel>: UILabel, ModelHandlerable, ViewProtocol, Resettable {
//--------------------------------------------------
// MARK: - Combine Properties
//--------------------------------------------------
@Published public var model: ModelType = ModelType()
public var modelPublisher: Published<ModelType>.Publisher { $model }
public var subscribers = Set<AnyCancellable>()
//--------------------------------------------------
// MARK: - Properties
//--------------------------------------------------
@Proxy(\.model.surface)
open var surface: Surface
@Proxy(\.model.disabled)
open var disabled: Bool {
didSet {
self.isEnabled = !disabled
}
}
open override var isEnabled: Bool {
get { !model.disabled }
set {
//create local vars for clear coding
let disabled = !newValue
if model.disabled != disabled {
model.disabled = disabled
}
isUserInteractionEnabled = isEnabled
}
}
@Proxy(\.model.attributes)
open var attributes: [any LabelAttributeModel]?
@Proxy(\.model.typograpicalStyle)
open var typograpicalStyle: TypographicalStyle
@Proxy(\.model.textPosition)
open var textPosition: TextPosition
//can't use @Proxy here
override open var text: String? {
didSet {
if model.text != oldValue {
model.text = text
}
}
}
//--------------------------------------------------
// MARK: - Configuration Properties
//--------------------------------------------------
public var textColorConfiguration: AnyColorable<ModelType> = .init(colorable: DisabledSurfaceColorConfiguration().with {
$0.disabled.lightColor = VDSColor.elementsSecondaryOnlight
$0.disabled.darkColor = VDSColor.elementsSecondaryOndark
$0.enabled.lightColor = VDSColor.elementsPrimaryOnlight
$0.enabled.darkColor = VDSColor.elementsPrimaryOndark
})
//--------------------------------------------------
// MARK: - Initializers
//--------------------------------------------------
required public init() {
super.init(frame: .zero)
initialSetup()
}
public required init(with model: ModelType) {
super.init(frame: .zero)
initialSetup()
set(with: model)
}
public override init(frame: CGRect) {
super.init(frame: .zero)
initialSetup()
set(with: model)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
initialSetup()
}
//--------------------------------------------------
// MARK: - Public Functions
//--------------------------------------------------
open func initialSetup() {
backgroundColor = .clear
numberOfLines = 0
lineBreakMode = .byWordWrapping
translatesAutoresizingMaskIntoConstraints = false
accessibilityCustomActions = []
accessibilityTraits = .staticText
setupUpdateView()
setup()
}
open func setup() {}
open func reset() {
text = nil
attributedText = nil
textColor = .black
font = TypographicalStyle.BodyLarge.font
textAlignment = .left
accessibilityCustomActions = []
accessibilityTraits = .staticText
numberOfLines = 0
}
//--------------------------------------------------
// MARK: - Overrides
//--------------------------------------------------
open func updateView(viewModel: ModelType) {
textAlignment = viewModel.textPosition.textAlignment
textColor = textColorConfiguration.getColor(viewModel)
if let vdsFont = viewModel.font {
font = vdsFont
} else {
font = TypographicalStyle.defaultStyle.font
}
if let text = viewModel.text, let font = font, let textColor = textColor {
//clear the arrays holding actions
accessibilityCustomActions = []
actions = []
//create the primary string
let startingAttributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor]
let mutableText = NSMutableAttributedString(string: text, attributes: startingAttributes)
//set the local lineHeight/lineSpacing attributes
setStyleAttributes(viewModel: viewModel, attributedString: mutableText)
if let attributes = viewModel.attributes {
//loop through the models attributes
for attribute in attributes {
//add attribute on the string
attribute.setAttribute(on: mutableText)
//see if the attribute is Actionable
if let actionable = attribute as? any ActionLabelAttributeModel{
//create a accessibleAction
let customAccessibilityAction = customAccessibilityAction(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))
}
}
}
//only enabled if enabled and has actions
isUserInteractionEnabled = !viewModel.disabled && !actions.isEmpty
//set the attributed text
attributedText = mutableText
} else {
text = viewModel.text
}
}
// MARK: - Private Attributes
private func setStyleAttributes(viewModel: ModelType, attributedString: NSMutableAttributedString) {
//get the range
let entireRange = NSRange(location: 0, length: attributedString.length)
//set letterSpacing
if viewModel.typograpicalStyle.letterSpacing > 0.0 {
attributedString.addAttribute(.kern, value: viewModel.typograpicalStyle.letterSpacing, range: entireRange)
}
//set lineHeight
if viewModel.typograpicalStyle.lineHeight > 0.0 {
let lineHeight = viewModel.typograpicalStyle.lineHeight
let adjustment = lineHeight > font.lineHeight ? 2.0 : 1.0
let baselineOffset = (lineHeight - font.lineHeight) / 2.0 / adjustment
let paragraph = NSMutableParagraphStyle().with {
$0.maximumLineHeight = lineHeight
$0.minimumLineHeight = lineHeight
$0.alignment = viewModel.textPosition.textAlignment
$0.lineBreakMode = lineBreakMode
}
attributedString.addAttribute(.baselineOffset, value: baselineOffset, range: entireRange)
attributedString.addAttribute( .paragraphStyle, value: paragraph, range: entireRange)
} else if viewModel.textPosition != .left {
let paragraph = NSMutableParagraphStyle().with {
$0.alignment = viewModel.textPosition.textAlignment
$0.lineBreakMode = lineBreakMode
}
attributedString.addAttribute( .paragraphStyle, value: paragraph, range: entireRange)
}
}
//--------------------------------------------------
// 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<Void, Never>
var accessibilityId: Int = 0
func performAction() {
action.send()
}
init(range: NSRange, action: PassthroughSubject<Void, Never>, accessibilityID: Int = 0) {
self.range = range
self.action = action
self.accessibilityId = accessibilityID
}
}
private var actions: [LabelAction] = [] {
didSet {
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.didTapAttributedTextInLabel(self, inRange: actionable.range) {
actionable.performAction()
return
}
}
}
//--------------------------------------------------
// MARK: - Accessibility For Actions
//--------------------------------------------------
private func customAccessibilityAction(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
}
}