term-kit-backend/Sources/TermKitBackend/View/TextField.swift

85 lines
2.3 KiB
Swift
Raw Normal View History

2024-07-10 14:41:11 +02:00
//
// Button.swift
// TermKitBackend
//
// Created by david-swift on 07.07.2024.
//
import TermKit
/// A simple text field view.
public struct TextField: TermKitWidget {
/// The text.
var text: Binding<String>
/// Whether the text field is secret.
var secret = false
/// The identifier for the closure.
let closureID = "closure"
/// Initialize the text field.
/// - Parameter text: The text.
public init(text: Binding<String>) {
self.text = text
}
/// 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 field = TermKit.TextField(text.wrappedValue)
2024-07-31 14:33:40 +02:00
let storage = ViewStorage(field, state: self)
2024-07-10 14:41:11 +02:00
field.secret = secret
field.textChanged = { _, _ in
(storage.fields[closureID] as? () -> Void)?()
}
storage.fields[closureID] = {
2024-07-31 14:33:40 +02:00
text.wrappedValue = field.text
2024-07-10 14:41:11 +02:00
}
return storage
}
/// 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-10 14:41:11 +02:00
guard let field = storage.pointer as? TermKit.TextField else {
return
}
storage.fields[closureID] = {
2024-07-31 14:33:40 +02:00
text.wrappedValue = field.text
2024-07-10 14:41:11 +02:00
}
if updateProperties {
2024-07-31 14:33:40 +02:00
if (storage.previousState as? Self)?.secret != secret {
field.secret = secret
}
2024-07-10 14:41:11 +02:00
if field.text != text.wrappedValue {
field.text = text.wrappedValue
}
2024-07-31 14:33:40 +02:00
storage.previousState = self
2024-07-10 14:41:11 +02:00
}
}
/// Set whether the text field is secret.
/// - Parameter secret: Whether the text field is secret.
/// - Returns: The view.
public func secret(_ secret: Bool) -> Self {
modify { $0.secret = secret }
}
}