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

68 lines
1.8 KiB
Swift
Raw Normal View History

2024-07-10 14:41:11 +02:00
//
// ProgressBar.swift
// TermKitBackend
//
// Created by david-swift on 07.07.2024.
//
import TermKit
/// A simple progress bar view.
public struct ProgressBar: TermKitWidget {
/// The current value.
var value: Double
/// The maximum value.
var max: Double
2024-07-31 14:33:40 +02:00
/// The fraction displayed in the progress bar.
var fraction: Float {
.init(value / max)
}
2024-07-10 14:41:11 +02:00
/// Initialize a progress bar.
/// - Parameters:
/// - value: The current value.
/// - max: The maximum value.
public init(value: Double, max: Double = 1) {
self.value = value
self.max = max
}
/// 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-07-10 14:41:11 +02:00
modifiers: [(any AnyView) -> any AnyView],
2024-07-18 16:07:37 +02:00
type: Data.Type
) -> ViewStorage where Data: ViewRenderData {
2024-07-10 14:41:11 +02:00
let bar = TermKit.ProgressBar()
2024-07-31 14:33:40 +02:00
bar.fraction = fraction
return .init(bar, 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,
modifiers: [(any AnyView) -> any AnyView],
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.ProgressBar,
updateProperties,
(storage.previousState as? Self)?.fraction != fraction else {
2024-07-10 14:41:11 +02:00
return
}
2024-07-31 14:33:40 +02:00
pointer.fraction = fraction
storage.previousState = self
2024-07-10 14:41:11 +02:00
}
}