vds_ios_sample/VDSSample/ViewControllers/InputFieldViewController.swift
2024-05-22 08:51:37 -05:00

753 lines
28 KiB
Swift

//
// TextEntryFieldViewController.swift
// VDSSample
//
// Created by Matt Bruce on 10/3/22.
//
import Foundation
import UIKit
import VDS
import VDSTokens
import Combine
class InputFieldViewController: BaseViewController<InputField> {
lazy var helperTextPlacementPickerSelectorView = {
PickerSelectorView(title: "",
picker: self.picker,
items: InputField.HelperTextPlacement.allCases)
}()
lazy var inputTypePickerSelectorView = {
PickerSelectorView(title: "",
picker: self.picker,
items: InputField.FieldType.allCases)
}()
var disabledSwitch = Toggle()
var requiredSwitch = Toggle()
var labelTextField = TextField()
var errorTextField = TextField()
var successTextField = TextField()
var helperTextField = TextField()
var widthTextField = NumericField()
var showErrorSwitch = Toggle()
var showSuccessSwitch = Toggle()
var tooltipTitleTextField = TextField()
var tooltipContentTextField = TextField()
//FieldType sections
//password
var hidePasswordButtonTextField = TextField()
var showPasswordButtonTextField = TextField()
lazy var passwordSection = FormSection().with {
$0.title = "Password Settings"
$0.addFormRow(label: "Hide Button", view: hidePasswordButtonTextField)
$0.addFormRow(label: "Show Button", view: showPasswordButtonTextField)
$0.isHidden = true
}
//date
lazy var dateFormatPickerSelectorView = {
PickerSelectorView(title: "",
picker: self.picker,
items: InputField.DateFormat.allCases)
}()
lazy var dateSection = FormSection().with {
$0.title = "Date Settings"
$0.addFormRow(label: "Date Format", view: dateFormatPickerSelectorView)
$0.isHidden = true
}
//inlineAction
var inlineActionTextField = TextField()
lazy var inlineActionSection = FormSection().with {
$0.title = "inlineAction Settings"
$0.addFormRow(label: "Action Text", view: inlineActionTextField)
$0.isHidden = true
}
//securityCode
lazy var cardTypePickerSelectorView = {
PickerSelectorView(title: "",
picker: self.picker,
items: InputField.CreditCardType.allCases)
}()
lazy var securityCodeSection = FormSection().with {
$0.title = "Security Code Settings"
$0.addFormRow(label: "Card Type", view: cardTypePickerSelectorView)
$0.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
addContentTopView(view: component)
setupPicker()
setupModel()
}
override func setupForm(){
super.setupForm()
let fieldType = FormSection().with {
$0.title = "Field Type Settings"
$0.addFormRow(label: "Field Type", view: inputTypePickerSelectorView)
}
let general = FormSection().with {
$0.title = "\n\nGeneral Settings"
}
general.addFormRow(label: "Disabled", view: disabledSwitch)
general.addFormRow(label: "Required", view: requiredSwitch)
general.addFormRow(label: "Surface", view: surfacePickerSelectorView)
general.addFormRow(label: "Label Text", view: labelTextField)
general.addFormRow(label: "Helper Text Placement", view: helperTextPlacementPickerSelectorView)
general.addFormRow(label: "Helper Text", view: helperTextField)
general.addFormRow(label: "Error", view: showErrorSwitch)
general.addFormRow(label: "Error Text", view: errorTextField)
general.addFormRow(label: "Success", view: showSuccessSwitch)
general.addFormRow(label: "Success Text", view: successTextField)
general.addFormRow(label: "Width", view: widthTextField)
general.addFormRow(label: "ToolTip Title", view: tooltipTitleTextField)
general.addFormRow(label: "ToolTip Content", view: tooltipContentTextField)
append(section: fieldType)
append(section: passwordSection)
append(section: dateSection)
append(section: inlineActionSection)
append(section: securityCodeSection)
append(section: general)
requiredSwitch.onChange = { [weak self] sender in
self?.component.isRequired = sender.isOn
}
showErrorSwitch.onChange = { [weak self] sender in
guard let self else { return }
self.component.showError = sender.isOn
if self.component.showError != sender.isOn {
self.showErrorSwitch.isOn = self.component.showError
}
}
showSuccessSwitch.onChange = { [weak self] sender in
guard let self else { return }
self.component.showSuccess = sender.isOn
if self.component.showSuccess != sender.isOn {
self.showSuccessSwitch.isOn = self.component.showSuccess
}
}
disabledSwitch.onChange = { [weak self] sender in
self?.component.isEnabled = !sender.isOn
}
labelTextField
.textPublisher
.sink { [weak self] text in
self?.component.labelText = text
}.store(in: &subscribers)
helperTextField
.textPublisher
.sink { [weak self] text in
self?.component.helperText = text
}.store(in: &subscribers)
errorTextField
.textPublisher
.sink { [weak self] text in
self?.component.errorText = text
}.store(in: &subscribers)
widthTextField
.numberPublisher
.sink { [weak self] number in
self?.component.width = number?.cgFloatValue
}.store(in: &subscribers)
tooltipTitleTextField
.textPublisher
.sink { [weak self] text in
self?.updateTooltip()
}.store(in: &subscribers)
tooltipContentTextField
.textPublisher
.sink { [weak self] text in
self?.updateTooltip()
}.store(in: &subscribers)
//field types
//password
hidePasswordButtonTextField
.textPublisher
.sink { [weak self] text in
self?.component.hidePasswordButtonText = text
}.store(in: &subscribers)
showPasswordButtonTextField
.textPublisher
.sink { [weak self] text in
self?.component.showPasswordButtonText = text
}.store(in: &subscribers)
//inlineAction
inlineActionTextField
.textPublisher
.sink { [weak self] text in
if !text.isEmpty {
self?.component.actionTextLinkModel = .init(text: text, onClick: { inputField in
var value = inputField.value ?? ""
value = !value.isEmpty ? value : "nil"
self?.present(UIAlertController(title: "inlineAction", message: "Clicked and you get the value: \(value)", preferredStyle: .alert).with{ $0.addAction(.init(title: "OK", style: .default)) }, animated: true)
})
} else {
self?.component.actionTextLinkModel = nil
}
}.store(in: &subscribers)
}
func setupModel() {
component.fieldType = .text
component.labelText = "Street Address"
component.helperText = "For example: 123 Verizon St"
component.errorText = "Enter a valid address."
component.successText = "Good job entering a valid address!"
component.onChange = { component in
if let text = component.value {
print("text entry: \(text)")
} else {
print("text entry: null")
}
}
//setup UI
surfacePickerSelectorView.text = component.surface.rawValue
helperTextPlacementPickerSelectorView.text = component.helperTextPlacement.rawValue
dateFormatPickerSelectorView.text = component.dateFormat.rawValue
inputTypePickerSelectorView.text = component.fieldType.rawValue
disabledSwitch.isOn = !component.isEnabled
requiredSwitch.isOn = component.isRequired
labelTextField.text = component.labelText
helperTextField.text = component.helperText
showErrorSwitch.isOn = component.showError
errorTextField.text = component.errorText
showSuccessSwitch.isOn = component.showSuccess
successTextField.text = component.successText
tooltipTitleTextField.text = component.tooltipModel?.title
tooltipContentTextField.text = component.tooltipModel?.content
if let width = component.width {
widthTextField.text = String(describing: width)
}
}
//Picker
func setupPicker(){
surfacePickerSelectorView.onPickerDidSelect = { [weak self] item in
self?.component.surface = item
self?.contentTopView.backgroundColor = item.color
}
helperTextPlacementPickerSelectorView.onPickerDidSelect = { [weak self] item in
self?.component.helperTextPlacement = item
}
inputTypePickerSelectorView.onPickerDidSelect = { [weak self] item in
let _ = self?.component.resignFirstResponder()
self?.component.text = ""
self?.component.fieldType = item
self?.updateFormSections()
}
dateFormatPickerSelectorView.onPickerDidSelect = { [weak self] item in
self?.component.dateFormat = item
self?.updateFormSections()
}
cardTypePickerSelectorView.onPickerDidSelect = { [weak self] item in
self?.component.cardType = item
}
}
func updateTooltip() {
let title = tooltipTitleTextField.text ?? ""
let content = tooltipContentTextField.text ?? ""
component.tooltipModel = !title.isEmpty || !content.isEmpty ? .init(title: title,
content: content) : nil
}
func updateFormSections() {
[passwordSection, dateSection, inlineActionSection, securityCodeSection].forEach { $0.isHidden = true }
//reset other fields
component.actionTextLinkModel = nil
component.tooltipModel = nil
component.cardType = .generic
tooltipTitleTextField.text = nil
tooltipContentTextField.text = nil
dateFormatPickerSelectorView.text = component.dateFormat.rawValue
cardTypePickerSelectorView.text = component.cardType.rawValue
switch component.fieldType {
case .inlineAction:
inlineActionTextField.text = nil
inlineActionSection.isHidden = false
case .password:
passwordSection.isHidden = false
case .date:
dateSection.isHidden = false
case .securityCode:
securityCodeSection.isHidden = false
default:
break
}
}
}
extension InputFieldViewController: ComponentSampleable {
static func makeSample() -> ComponentSample {
let component = Self.makeComponent()
component.fieldType = .text
component.labelText = "Street Address"
component.helperText = "For example: 123 Verizon St"
component.errorText = "Enter a valid address."
component.successText = "Good job entering a valid address!"
component.tooltipModel = .init(title: "Check the formatting of your address", content: "House/Building number then street name")
return ComponentSample(component: component, trailingPinningType: .lessThanOrEqual)
}
}
import VDSTokens
import Combine
/// Base Class used to build out a Input controls.
open class TEntryFieldBase: Control, Changeable, FormFieldInternalValidatable {
//--------------------------------------------------
// MARK: - Initializers
//--------------------------------------------------
required public init() {
super.init(frame: .zero)
}
public override init(frame: CGRect) {
super.init(frame: .zero)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
//--------------------------------------------------
// MARK: - Enums
//--------------------------------------------------
/// Enum used to describe the position of the helper text.
public enum HelperTextPlacement: String, CaseIterable {
case bottom, right
}
//--------------------------------------------------
// MARK: - Private Properties
//--------------------------------------------------
internal var primaryStackView: UIStackView = {
return UIStackView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.axis = .vertical
$0.distribution = .fill
$0.alignment = .leading
}
}()
/// This is the veritcal stack view that has 2 rows, the containerView and the return view
/// of the getBottomContainer() method, by default returns the bottomContainerStackView.
internal let secondaryStackView = UIStackView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.axis = .vertical
$0.distribution = .fill
}
/// This is the view that will be wrapped with the border for userInteraction.
/// The only subview of this view is the fieldStackView
internal var containerView: UIView = {
return UIView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
}
}()
/// This is a horizontal Stack View that is placed inside the containterView (bordered view)
/// The first arrangedView will be the view from getFieldContainer()
/// The second view is the statusIcon.
internal var fieldStackView: UIStackView = {
return UIStackView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.axis = .horizontal
$0.distribution = .fill
$0.alignment = .top
}
}()
/// This is a vertical stack used for the errorLabel and helperLabel.
internal var bottomContainerStackView: UIStackView = {
return UIStackView().with {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.axis = .vertical
$0.distribution = .fill
$0.spacing = VDSLayout.space2X
}
}()
open var rules = [AnyRule<String>]()
//--------------------------------------------------
// MARK: - Configuration Properties
//--------------------------------------------------
// Sizes are from InVision design specs.
internal var maxWidth: CGFloat { frame.size.width }
internal var minWidth: CGFloat { containerSize.width }
internal var containerSize: CGSize { CGSize(width: minWidth, height: 44) }
internal let primaryColorConfiguration = ViewColorConfiguration().with {
$0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forDisabled: true)
$0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOndark, forDisabled: false)
}
internal let secondaryColorConfiguration = ViewColorConfiguration().with {
$0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forDisabled: true)
$0.setSurfaceColors(VDSColor.elementsSecondaryOnlight, VDSColor.elementsSecondaryOndark, forDisabled: false)
}
internal var backgroundColorConfiguration = ControlColorConfiguration().with {
$0.setSurfaceColors(VDSFormControlsColor.backgroundOnlight, VDSFormControlsColor.backgroundOndark, forState: .normal)
$0.setSurfaceColors(VDSFormControlsColor.backgroundOnlight, VDSFormControlsColor.backgroundOndark, forState: .disabled)
$0.setSurfaceColors(VDSColor.feedbackErrorBackgroundOnlight, VDSColor.feedbackErrorBackgroundOndark, forState: .error)
$0.setSurfaceColors(VDSColor.feedbackErrorBackgroundOnlight, VDSColor.feedbackErrorBackgroundOndark, forState: [.error, .focused])
}
internal var borderColorConfiguration = ControlColorConfiguration().with {
$0.setSurfaceColors(VDSFormControlsColor.borderOnlight, VDSFormControlsColor.borderOndark, forState: .normal)
$0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOnlight, forState: .focused)
$0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOnlight, forState: [.focused, .error])
$0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forState: .disabled)
$0.setSurfaceColors(VDSColor.feedbackErrorOnlight, VDSColor.feedbackErrorOndark, forState: .error)
$0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forState: [.disabled,.error])
}
internal let iconColorConfiguration = ControlColorConfiguration().with {
$0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOndark, forState: .normal)
$0.setSurfaceColors(VDSColor.interactiveDisabledOnlight, VDSColor.interactiveDisabledOndark, forState: .disabled)
$0.setSurfaceColors(VDSColor.elementsPrimaryOnlight, VDSColor.elementsPrimaryOndark, forState: .error)
}
internal var readOnlyBorderColorConfiguration = ControlColorConfiguration().with {
$0.setSurfaceColors(VDSFormControlsColor.borderReadonlyOnlight, VDSFormControlsColor.borderReadonlyOndark, forState: .normal)
}
//--------------------------------------------------
// MARK: - Public Properties
//--------------------------------------------------
open var onChangeSubscriber: AnyCancellable?
open var titleLabel = Label().with {
$0.setContentCompressionResistancePriority(.required, for: .vertical)
$0.textStyle = .bodySmall
}
open var errorLabel = Label().with {
$0.setContentCompressionResistancePriority(.required, for: .vertical)
$0.textStyle = .bodySmall
$0.accessibilityValue = "error"
}
open var helperLabel = Label().with {
$0.setContentCompressionResistancePriority(.required, for: .vertical)
$0.textStyle = .bodySmall
}
open var statusIcon: Icon = Icon().with {
$0.size = .medium
}
open var labelText: String? { didSet { setNeedsUpdate() } }
open var helperText: String? { didSet { setNeedsUpdate() } }
/// Whether not to show the error.
open var showError: Bool = false { didSet { setNeedsUpdate() } }
/// FormFieldValidator
open var validator: (any FormFieldValidatorable)?
/// Override UIControl state to add the .error state if showError is true.
open override var state: UIControl.State {
get {
var state = super.state
if showError || hasInternalError {
state.insert(.error)
}
return state
}
}
open var errorText: String? { didSet { setNeedsUpdate() } }
open var tooltipModel: Tooltip.TooltipModel? { didSet { setNeedsUpdate() } }
open var transparentBackground: Bool = false { didSet { setNeedsUpdate() } }
open var width: CGFloat? { didSet { setNeedsUpdate() } }
open var inputId: String? { didSet { setNeedsUpdate() } }
/// The text of this textField.
open var value: String? {
get { fatalError("must be read from subclass")}
}
open var defaultValue: AnyHashable? { didSet { setNeedsUpdate() } }
open var isRequired: Bool = false { didSet { setNeedsUpdate() } }
open var isReadOnly: Bool = false { didSet { setNeedsUpdate() } }
//--------------------------------------------------
// MARK: - Constraints
//--------------------------------------------------
internal var heightConstraint: NSLayoutConstraint?
internal var widthConstraint: NSLayoutConstraint?
//--------------------------------------------------
// MARK: - Overrides
//--------------------------------------------------
/// Called once when a view is initialized and is used to Setup additional UI or other constants and configurations.
open override func setup() {
super.setup()
isAccessibilityElement = false
addSubview(primaryStackView)
//create the wrapping view
heightConstraint = containerView.heightGreaterThanEqualTo(constant: containerSize.height)
widthConstraint = containerView.width(constant: frame.size.width)
secondaryStackView.addArrangedSubview(containerView)
secondaryStackView.setCustomSpacing(8, after: containerView)
//add ContainerStackView
//this is the horizontal stack that contains
//the left, InputContainer, Icons, Buttons
containerView.addSubview(fieldStackView)
fieldStackView.pinToSuperView(.uniform(VDSLayout.space3X))
let fieldContainerView = getFieldContainer()
fieldContainerView.translatesAutoresizingMaskIntoConstraints = false
//add the view to add input fields
fieldStackView.addArrangedSubview(fieldContainerView)
fieldStackView.addArrangedSubview(statusIcon)
fieldStackView.setCustomSpacing(VDSLayout.space3X, after: fieldContainerView)
//get the container this is what show helper text, error text
//can include other for character count, max length
let bottomContainer = getBottomContainer()
//this is the vertical stack that contains error text, helper text
bottomContainerStackView.addArrangedSubview(errorLabel)
bottomContainerStackView.addArrangedSubview(helperLabel)
primaryStackView.addArrangedSubview(titleLabel)
primaryStackView.addArrangedSubview(secondaryStackView)
secondaryStackView.addArrangedSubview(bottomContainer)
primaryStackView.setCustomSpacing(4, after: titleLabel)
primaryStackView
.pinTop()
.pinLeading()
.pinTrailing(0, .defaultHigh)
.pinBottom(0, .defaultHigh)
titleLabel.textColorConfiguration = primaryColorConfiguration.eraseToAnyColorable()
errorLabel.textColorConfiguration = primaryColorConfiguration.eraseToAnyColorable()
helperLabel.textColorConfiguration = secondaryColorConfiguration.eraseToAnyColorable()
}
/// Resets to default settings.
open override func reset() {
super.reset()
titleLabel.reset()
errorLabel.reset()
helperLabel.reset()
titleLabel.textStyle = .bodySmall
errorLabel.textStyle = .bodySmall
helperLabel.textStyle = .bodySmall
labelText = nil
helperText = nil
showError = false
errorText = nil
tooltipModel = nil
transparentBackground = false
width = nil
inputId = nil
defaultValue = nil
isRequired = false
isReadOnly = false
onChange = nil
}
/// Used to make changes to the View based off a change events or from local properties.
open override func updateView() {
super.updateView()
updateContainerView()
updateTitleLabel()
updateErrorLabel()
updateHelperLabel()
updateContainerWidth()
}
open func validate(){
updateRules()
validator = FormFieldValidator<TEntryFieldBase>(field: self, rules: rules)
validator?.validate()
setNeedsUpdate()
}
//--------------------------------------------------
// MARK: - Private Methods
//--------------------------------------------------
internal func updateContainerView() {
containerView.backgroundColor = backgroundColorConfiguration.getColor(self)
containerView.layer.borderColor = isReadOnly ? readOnlyBorderColorConfiguration.getColor(self).cgColor : borderColorConfiguration.getColor(self).cgColor
containerView.layer.borderWidth = VDSFormControls.borderWidth
containerView.layer.cornerRadius = VDSFormControls.borderRadius
}
//--------------------------------------------------
// MARK: - Public Methods
//--------------------------------------------------
open func updateContainerWidth() {
if let width, width > minWidth && width < maxWidth {
widthConstraint?.constant = width
} else {
widthConstraint?.constant = maxWidth >= minWidth ? maxWidth : minWidth
}
widthConstraint?.activate()
}
/// Container for the area in which the user interacts.
open func getFieldContainer() -> UIView {
fatalError("Subclass must return the view that contains the field/view the user will interact with.")
}
/// Container for the area in which helper or error text presents.
open func getBottomContainer() -> UIView {
return bottomContainerStackView
}
internal func updateRules() {
rules.removeAll()
if self.isRequired {
let rule = RequiredRule()
if let errorText, !errorText.isEmpty {
rule.errorMessage = errorText
} else if let labelText{
rule.errorMessage = "You must enter a \(labelText)"
} else {
rule.errorMessage = "You must enter a value"
}
rules.append(.init(rule))
}
}
open func updateTitleLabel() {
//update the local vars for the label since we no
//long have a model
var attributes: [any LabelAttributeModel] = []
var updatedLabelText = labelText
//dealing with the "Optional" addition to the text
if let oldText = updatedLabelText, !isRequired, !oldText.hasSuffix("Optional") {
if isEnabled {
let optionColorAttr = ColorLabelAttribute(location: oldText.count + 2,
length: 8,
color: VDSColor.elementsSecondaryOnlight)
attributes.append(optionColorAttr)
}
updatedLabelText = "\(oldText) Optional"
}
if let tooltipModel {
attributes.append(TooltipLabelAttribute(surface: surface, model: tooltipModel, presenter: self))
}
//set the titleLabel
titleLabel.text = updatedLabelText
titleLabel.attributes = attributes
titleLabel.surface = surface
titleLabel.isEnabled = isEnabled
}
open func updateErrorLabel(){
if showError, let errorText {
errorLabel.text = errorText
errorLabel.surface = surface
errorLabel.isEnabled = isEnabled
errorLabel.isHidden = false
statusIcon.name = .error
statusIcon.surface = surface
statusIcon.isHidden = !isEnabled || state.contains(.focused)
} else if hasInternalError, let internalErrorText {
errorLabel.text = internalErrorText
errorLabel.surface = surface
errorLabel.isEnabled = isEnabled
errorLabel.isHidden = false
statusIcon.name = .error
statusIcon.surface = surface
statusIcon.isHidden = !isEnabled || state.contains(.focused)
} else {
statusIcon.isHidden = true
errorLabel.isHidden = true
}
statusIcon.color = iconColorConfiguration.getColor(self)
}
open func updateHelperLabel(){
//set the helper label position
if let helperText {
helperLabel.text = helperText
helperLabel.surface = surface
helperLabel.isEnabled = isEnabled
helperLabel.isHidden = false
} else {
helperLabel.isHidden = true
}
}
}
class RequiredRule: Rule {
var maxLength: Int?
var errorMessage: String = "This field is required."
func isValid(value: String?) -> Bool {
guard let value, !value.isEmpty, value.count > 0 else { return false }
return true
}
}