2024-07-10 14:41:11 +02:00
|
|
|
//
|
|
|
|
// Checkbox.swift
|
|
|
|
// TermKitBackend
|
|
|
|
//
|
|
|
|
// Created by david-swift on 07.07.2024.
|
|
|
|
//
|
|
|
|
|
|
|
|
import TermKit
|
|
|
|
|
|
|
|
/// A simple checkbox widget.
|
|
|
|
public struct Checkbox: TermKitWidget {
|
|
|
|
|
|
|
|
/// The label of the checkbox.
|
|
|
|
var label: String
|
|
|
|
/// Whether the checkbox is on.
|
|
|
|
var isOn: Binding<Bool>
|
|
|
|
|
|
|
|
/// Initialize the checkbox.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - label: The label.
|
|
|
|
/// - isOn: Whether the checkbox is on.
|
|
|
|
public init(_ label: String, isOn: Binding<Bool>) {
|
|
|
|
self.label = label
|
|
|
|
self.isOn = isOn
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The view storage.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - modifiers: Modify views before being updated.
|
|
|
|
/// - type: The type of the app storage.
|
2024-07-18 16:07:37 +02:00
|
|
|
/// - Returns: The view storage.
|
|
|
|
public func container<Data>(
|
2024-08-25 16:42:55 +02:00
|
|
|
data: WidgetData,
|
2024-07-18 16:07:37 +02:00
|
|
|
type: Data.Type
|
|
|
|
) -> ViewStorage where Data: ViewRenderData {
|
2024-07-10 14:41:11 +02:00
|
|
|
let button = TermKit.Checkbox(label, checked: isOn.wrappedValue)
|
|
|
|
button.toggled = { _ in
|
|
|
|
isOn.wrappedValue = button.checked
|
|
|
|
}
|
2024-07-31 14:33:40 +02:00
|
|
|
return .init(button, state: self)
|
2024-07-10 14:41:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Update the stored content.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - storage: The storage to update.
|
|
|
|
/// - modifiers: Modify views before being updated
|
|
|
|
/// - updateProperties: Whether to update the view's properties.
|
|
|
|
/// - type: The type of the app storage.
|
2024-07-18 16:07:37 +02:00
|
|
|
public func update<Data>(
|
2024-07-10 14:41:11 +02:00
|
|
|
_ storage: ViewStorage,
|
2024-08-25 16:42:55 +02:00
|
|
|
data: WidgetData,
|
2024-07-10 14:41:11 +02:00
|
|
|
updateProperties: Bool,
|
2024-07-18 16:07:37 +02:00
|
|
|
type: Data.Type
|
|
|
|
) where Data: ViewRenderData {
|
2024-07-31 14:33:40 +02:00
|
|
|
guard let pointer = storage.pointer as? TermKit.Checkbox else {
|
2024-07-10 14:41:11 +02:00
|
|
|
return
|
|
|
|
}
|
2024-07-31 14:33:40 +02:00
|
|
|
if updateProperties {
|
|
|
|
if (storage.previousState as? Self)?.label != label {
|
|
|
|
pointer.text = label
|
|
|
|
}
|
|
|
|
if (storage.previousState as? Self)?.isOn.wrappedValue != isOn.wrappedValue {
|
|
|
|
pointer.checked = isOn.wrappedValue
|
|
|
|
}
|
|
|
|
storage.previousState = self
|
|
|
|
}
|
|
|
|
pointer.toggled = { _ in
|
|
|
|
isOn.wrappedValue = pointer.checked
|
2024-07-10 14:41:11 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|