vds_ios/VDS/Components/Checkbox/Checkbox.swift
Matt Bruce 61d65e9b60 added toggle cotainer to meet specs
refactored all configurable default properties to one area

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2022-08-05 14:37:49 -05:00

427 lines
15 KiB
Swift

//
// Checkbox.swift
// VDS
//
// Created by Matt Bruce on 7/22/22.
//
import Foundation
import UIKit
import VDSColorTokens
import VDSFormControlsTokens
import Combine
/**
A custom implementation of Apple's UISwitch.
By default this class begins in the off state.
Container: The background of the checkbox control.
Knob: The circular indicator that slides on the container.
*/
public class Checkbox: CheckboxBase<DefaultCheckboxModel>{}
open class CheckboxBase<ModelType: CheckboxModel>: Control<ModelType>, Changable {
//--------------------------------------------------
// MARK: - Private Properties
//--------------------------------------------------
private var mainStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .top
stackView.axis = .vertical
return stackView
}()
private var checkboxStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .top
stackView.axis = .horizontal
return stackView
}()
private var checkboxLabelStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
return stackView
}()
private var primaryLabel: Label = {
let label = Label()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var secondaryLabel: Label = {
let label = Label()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var errorLabel: Label = {
let label = Label()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
private var checkboxView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
//--------------------------------------------------
// MARK: - Configuration Properties
//--------------------------------------------------
public let checkboxSize = CGSize(width: 20, height: 20)
private var checkboxBackgroundColorConfiguration: CheckboxErrorColorConfiguration = {
let config = CheckboxErrorColorConfiguration()
config.forTrue.enabled.lightColor = VDSColor.elementsPrimaryOnlight
config.forTrue.enabled.darkColor = VDSColor.elementsPrimaryOndark
config.forTrue.disabled.lightColor = VDSColor.interactiveDisabledOnlight
config.forTrue.disabled.darkColor = VDSColor.interactiveDisabledOndark
//error doesn't care enabled/disable
config.error.forTrue.lightColor = VDSColor.elementsPrimaryOnlight
config.error.forTrue.darkColor = VDSColor.elementsPrimaryOndark
config.error.forFalse.lightColor = VDSColor.feedbackErrorBackgroundOnlight
config.error.forFalse.darkColor = VDSColor.feedbackErrorBackgroundOndark
return config
}()
private var checkboxBorderColorConfiguration: CheckboxErrorColorConfiguration = {
let config = CheckboxErrorColorConfiguration()
config.forTrue.enabled.lightColor = VDSColor.elementsPrimaryOnlight
config.forTrue.enabled.darkColor = VDSColor.elementsPrimaryOndark
config.forFalse.enabled.lightColor = VDSFormControlsColor.borderOnlight
config.forFalse.enabled.darkColor = VDSFormControlsColor.borderOndark
config.forTrue.disabled.lightColor = VDSColor.interactiveDisabledOnlight
config.forTrue.disabled.darkColor = VDSColor.interactiveDisabledOndark
config.forFalse.disabled.lightColor = VDSColor.interactiveDisabledOnlight
config.forFalse.disabled.darkColor = VDSColor.interactiveDisabledOndark
//error doesn't care enabled/disable
config.error.forTrue.lightColor = VDSColor.elementsPrimaryOnlight
config.error.forTrue.darkColor = VDSColor.elementsPrimaryOndark
config.error.forFalse.lightColor = VDSColor.feedbackErrorOnlight
config.error.forFalse.darkColor = VDSColor.feedbackErrorOndark
return config
}()
private var checkboxCheckColorConfiguration: BinarySurfaceColorConfiguration<ModelType> = {
let config = BinarySurfaceColorConfiguration<ModelType>()
config.forTrue.lightColor = VDSColor.elementsPrimaryOndark
config.forTrue.darkColor = VDSColor.elementsPrimaryOnlight
return config
}()
//--------------------------------------------------
// MARK: - Public Properties
//--------------------------------------------------
public var onChange: Blocks.ActionBlock?
@Proxy(\.model.id)
open var id: String?
@Proxy(\.model.on)
open var isOn: Bool
@Proxy(\.model.labelText)
open var labelText: String?
@Proxy(\.model.childText)
open var childText: String?
@Proxy(\.model.showError)
open var showError: Bool
@Proxy(\.model.errorText)
open var errorText: String?
@Proxy(\.model.inputId)
open var inputId: String?
@Proxy(\.model.value)
open var value: AnyHashable?
@Proxy(\.model.dataAnalyticsTrack)
open var dataAnalyticsTrack: String?
@Proxy(\.model.dataClickStream)
open var dataClickStream: String?
@Proxy(\.model.dataTrack)
open var dataTrack: String?
@Proxy(\.model.accessibilityHintEnabled)
open var accessibilityHintEnabled: String?
@Proxy(\.model.accessibilityHintDisabled)
open var accessibilityHintDisabled: String?
@Proxy(\.model.accessibilityValueEnabled)
open var accessibilityValueEnabled: String?
@Proxy(\.model.accessibilityValueDisabled)
open var accessibilityValueDisabled: String?
@Proxy(\.model.accessibilityLabelEnabled)
open var accessibilityLabelEnabled: String?
@Proxy(\.model.accessibilityLabelDisabled)
open var accessibilityLabelDisabled: String?
//--------------------------------------------------
// MARK: - Computed Properties
//--------------------------------------------------
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
}
}
}
//--------------------------------------------------
// MARK: - Initializers
//--------------------------------------------------
public convenience init() {
self.init(with: ModelType())
}
required public init(with model: ModelType) {
super.init(with: model)
}
required public init?(coder: NSCoder) {
super.init(with: ModelType())
}
//--------------------------------------------------
// MARK: - Constraints
//--------------------------------------------------
private var knobLeadingConstraint: NSLayoutConstraint?
private var knobTrailingConstraint: NSLayoutConstraint?
private var knobHeightConstraint: NSLayoutConstraint?
private var knobWidthConstraint: NSLayoutConstraint?
private var checkboxHeightConstraint: NSLayoutConstraint?
private var checkboxWidthConstraint: NSLayoutConstraint?
//functions
//--------------------------------------------------
// MARK: - Lifecycle
//--------------------------------------------------
open override func setup() {
super.setup()
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(Checkbox.toggleAndAction)))
isAccessibilityElement = true
accessibilityTraits = .button
addSubview(mainStackView)
mainStackView.addArrangedSubview(checkboxStackView)
mainStackView.addArrangedSubview(errorLabel)
checkboxStackView.addArrangedSubview(checkboxView)
checkboxStackView.addArrangedSubview(checkboxLabelStackView)
checkboxLabelStackView.addArrangedSubview(primaryLabel)
checkboxLabelStackView.addArrangedSubview(secondaryLabel)
checkboxHeightConstraint = checkboxView.heightAnchor.constraint(equalToConstant: checkboxSize.height)
checkboxHeightConstraint?.isActive = true
checkboxWidthConstraint = checkboxView.widthAnchor.constraint(equalToConstant: checkboxSize.width)
checkboxWidthConstraint?.isActive = true
updateCheckbox(model)
mainStackView.topAnchor.constraint(equalTo: topAnchor).isActive = true
mainStackView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
mainStackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
mainStackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
func updateLabels(_ viewModel: ModelType) {
//deal with labels
if model.shouldShowLabels {
//add the stackview to hold the 2 labels
//top label
if let labelModel = viewModel.labelModel {
primaryLabel.set(with: labelModel)
primaryLabel.isHidden = false
} else {
primaryLabel.isHidden = true
}
//bottom label
if let childModel = viewModel.childModel {
secondaryLabel.set(with: childModel)
secondaryLabel.isHidden = false
} else {
secondaryLabel.isHidden = true
}
checkboxStackView.spacing = 12
checkboxLabelStackView.spacing = 4
checkboxLabelStackView.isHidden = false
} else {
checkboxStackView.spacing = 0
checkboxLabelStackView.spacing = 0
checkboxLabelStackView.isHidden = true
}
//either add/remove the error from the main stack
if let errorModel = model.errorModel, model.shouldShowError {
errorLabel.set(with: errorModel)
mainStackView.spacing = 8
errorLabel.isHidden = false
} else {
mainStackView.spacing = 0
errorLabel.isHidden = true
}
}
public override func reset() {
super.reset()
updateCheckbox(model)
setAccessibilityLabel()
onChange = nil
}
//--------------------------------------------------
// MARK: - Checkbox View
//--------------------------------------------------
/// Manages the appearance of the checkbox.
private var shapeLayer: CAShapeLayer?
private func updateCheckbox(_ viewModel: ModelType) {
//get the colors
let backgroundColor = checkboxBackgroundColorConfiguration.getColor(viewModel)
let borderColor = checkboxBorderColorConfiguration.getColor(viewModel)
let checkColor = checkboxCheckColorConfiguration.getColor(viewModel)
if let shapeLayer = shapeLayer, let sublayers = layer.sublayers, sublayers.contains(shapeLayer) {
shapeLayer.removeFromSuperlayer()
self.shapeLayer = nil
}
checkboxView.backgroundColor = backgroundColor
checkboxView.layer.borderColor = borderColor.cgColor
checkboxView.layer.cornerRadius = 2.0
checkboxView.layer.borderWidth = 1.0
if shapeLayer == nil {
let bounds = checkboxView.bounds
let length = max(bounds.size.height, bounds.size.width)
guard length > 0.0, shapeLayer == nil else { return }
//draw the checkmark layer
let xInsetLeft = length * 0.25
let yInsetTop = length * 0.3
let innerWidth = length - (xInsetLeft + length * 0.25) // + Right X Inset
let innerHeight = length - (yInsetTop + length * 0.35) // + Bottom Y Inset
let startPoint = CGPoint(x: xInsetLeft, y: yInsetTop + (innerHeight / 2))
let pivotOffSet = CGPoint(x: xInsetLeft + (innerWidth * 0.33), y: yInsetTop + innerHeight)
let endOffset = CGPoint(x: xInsetLeft + innerWidth, y: yInsetTop)
let bezierPath = UIBezierPath()
bezierPath.move(to: startPoint)
bezierPath.addLine(to: pivotOffSet)
bezierPath.addLine(to: endOffset)
let shapeLayer = CAShapeLayer()
self.shapeLayer = shapeLayer
shapeLayer.frame = bounds
layer.addSublayer(shapeLayer)
shapeLayer.strokeColor = checkColor.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.path = bezierPath.cgPath
shapeLayer.lineJoin = .miter
shapeLayer.lineWidth = 2
CATransaction.withDisabledAnimations {
shapeLayer.strokeEnd = model.on ? 1 : 0
}
}
}
//--------------------------------------------------
// MARK: - Actions
//--------------------------------------------------
open override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
super.sendAction(action, to: target, for: event)
toggleAndAction()
}
open override func sendActions(for controlEvents: UIControl.Event) {
super.sendActions(for: controlEvents)
toggleAndAction()
}
/// This will checkbox the state of the Checkbox and execute the actionBlock if provided.
@objc public func toggleAndAction() {
isOn.toggle()
onChange?()
}
override open func accessibilityActivate() -> Bool {
// Hold state in case User wanted isAnimated to remain off.
guard isUserInteractionEnabled else { return false }
sendActions(for: .touchUpInside)
return true
}
//--------------------------------------------------
// MARK: - UIResponder
//--------------------------------------------------
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
sendActions(for: .touchUpInside)
}
//--------------------------------------------------
// MARK: - State
//--------------------------------------------------
/// Follow the SwiftUI View paradigm
/// - Parameter viewModel: state
open override func onStateChange(viewModel: ModelType) {
let enabled = !viewModel.disabled
updateLabels(viewModel)
updateCheckbox(viewModel)
setAccessibilityHint(enabled)
setAccessibilityValue(viewModel.on)
setAccessibilityLabel(viewModel.on)
isUserInteractionEnabled = !viewModel.disabled
setNeedsLayout()
layoutIfNeeded()
}
//--------------------------------------------------
// MARK: - Color Class Configurations
//--------------------------------------------------
private class CheckboxErrorColorConfiguration: BinaryDisabledSurfaceColorConfiguration<ModelType> {
public let error = BinarySurfaceColorConfiguration<ModelType>()
override func getColor(_ viewModel: ModelType) -> UIColor {
//only show error is enabled and showError == true
let showErrorColor = !viewModel.disabled && viewModel.showError
if showErrorColor {
return error.getColor(viewModel)
} else {
return super.getColor(viewModel)
}
}
}
}