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

71 lines
2.0 KiB
Swift
Raw Normal View History

2024-07-10 14:41:11 +02:00
//
// ListView.swift
// TermKitBackend
//
// Created by david-swift on 06.07.2024.
//
import TermKit
/// A list view contains multiple clickable rows.
public struct ListView<Element>: TermKitWidget where Element: CustomStringConvertible {
/// The rows.
var items: [Element]
/// Execute when a row gets clicked.
var activate: (Element) -> Void
/// Initialize the list view.
/// - Parameters:
/// - items: The rows.
/// - activate: Execute when a row gets clicked.
public init(_ items: [Element], activate: @escaping (Element) -> Void = { _ in }) {
self.items = items
self.activate = activate
}
/// 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 list = TermKit.ListView(items: items.map { $0.description })
setClosure(list: list)
return .init(list)
}
/// 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 list = storage.pointer as? TermKit.ListView else {
return
}
setClosure(list: list)
}
/// Set the closure executed when the row gets clicked.
/// - Parameter list: The list view object.
func setClosure(list: TermKit.ListView) {
list.activate = { index in
if let item = items[safe: index] {
activate(item)
}
return false
}
}
}