term-kit-backend/Sources/TermKitBackend/Menu/Menu.swift

60 lines
1.8 KiB
Swift
Raw Normal View History

2024-07-10 14:41:11 +02:00
//
// Menu.swift
// TermKitBackend
//
// Created by david-swift on 07.07.2024.
//
import TermKit
2024-07-19 23:41:19 +02:00
/// A menu is an item of a `MenuBar`.
2024-07-18 16:07:37 +02:00
public struct Menu: MenuContext.Widget {
2024-07-10 14:41:11 +02:00
/// The menu's label, displayed in the menu bar.
var label: String
/// The content of the menu.
2024-07-18 16:07:37 +02:00
var content: Body
2024-07-10 14:41:11 +02:00
/// Initialize a menu.
/// - Parameters:
/// - label: The menu's label, displayed in the menu bar.
/// - content: The content of the menu.
2024-07-18 16:07:37 +02:00
public init(_ label: String, @ViewBuilder content: () -> Body) {
2024-07-10 14:41:11 +02:00
self.label = label
self.content = content()
}
/// The view storage.
/// - Parameters:
2024-07-18 16:07:37 +02:00
/// - modifiers: Modify the views before updating.
/// - type: The type of the views.
/// - Returns: The view storage.
public func container<Data>(
modifiers: [(any AnyView) -> any AnyView],
type: Data.Type
) -> ViewStorage where Data: ViewRenderData {
let children = content.storages(modifiers: modifiers, type: type)
2024-07-10 14:41:11 +02:00
let menu = MenuBarItem(title: label, children: children.compactMap { $0.pointer as? MenuItem })
return .init(menu, content: [.mainContent: children])
}
2024-07-18 16:07:37 +02:00
/// Update the view storage.
2024-07-10 14:41:11 +02:00
/// - Parameters:
/// - storage: The storage to update.
2024-07-18 16:07:37 +02:00
/// - modifiers: Modify the views before updating.
2024-07-10 14:41:11 +02:00
/// - updateProperties: Whether to update the properties.
2024-07-18 16:07:37 +02:00
/// - type: The type of the views.
public func update<Data>(
_ storage: ViewStorage,
modifiers: [(AnyView) -> AnyView],
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 storages = storage.content[.mainContent] else {
return
}
2024-07-18 16:07:37 +02:00
content.update(storages, modifiers: modifiers, updateProperties: updateProperties, type: type)
2024-07-10 14:41:11 +02:00
}
}