Revision control

Copy as Markdown

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Common
import UIKit
/// The view model used to configure a CardView
public struct CardViewModel {
public let view: UIView
public let a11yId: String
public let backgroundColor: ((Theme) -> UIColor)
// We need this init as by default the init generated by the compiler for the struct will be internal and
// can therefor not be used outside of the component library
public init(view: UIView, a11yId: String, backgroundColor: @escaping ((Theme) -> UIColor)) {
self.view = view
self.a11yId = a11yId
self.backgroundColor = backgroundColor
}
}
public class CardView: UIView, ThemeApplicable {
private struct UX {
static let verticalPadding: CGFloat = 8
static let horizontalPadding: CGFloat = 8
static let cornerRadius: CGFloat = 8
}
// MARK: - Properties
// UI
private lazy var rootView: UIView = .build { view in
view.layer.cornerRadius = UX.cornerRadius
}
private lazy var viewModel = CardViewModel(
view: rootView,
a11yId: "",
backgroundColor: { theme in
return theme.colors.layer1
})
// MARK: - Inits
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func applyTheme(theme: Theme) {
rootView.backgroundColor = viewModel.backgroundColor(theme)
}
public func configure(_ viewModel: CardViewModel) {
self.viewModel = viewModel
rootView.subviews.forEach { $0.removeFromSuperview() }
rootView.addSubview(viewModel.view)
rootView.accessibilityIdentifier = viewModel.a11yId
NSLayoutConstraint.activate([
viewModel.view.leadingAnchor.constraint(equalTo: rootView.leadingAnchor,
constant: UX.horizontalPadding),
viewModel.view.topAnchor.constraint(equalTo: rootView.topAnchor,
constant: UX.verticalPadding),
viewModel.view.trailingAnchor.constraint(equalTo: rootView.trailingAnchor,
constant: -UX.horizontalPadding),
viewModel.view.bottomAnchor.constraint(equalTo: rootView.bottomAnchor,
constant: -UX.verticalPadding),
])
}
private func setupLayout() {
addSubview(rootView)
NSLayoutConstraint.activate([
rootView.leadingAnchor.constraint(equalTo: leadingAnchor),
rootView.topAnchor.constraint(equalTo: topAnchor),
rootView.trailingAnchor.constraint(equalTo: trailingAnchor),
rootView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
}