// // MenuCollection.swift // MacBackend // // Created by david-swift on 02.08.2024. // import AppKit import Foundation /// A collection of menus. public struct MenuCollection: MenuWidget, Wrapper { /// The content of the collection. var content: Body /// Initialize a menu. /// - Parameter content: The content of the collection. public init(@ViewBuilder content: @escaping () -> Body) { self.content = content() } /// The view storage. /// - Parameters: /// - data: The widget data. /// - type: The type of the views. /// - Returns: The view storage. public func container( data: WidgetData, type: Data.Type ) -> ViewStorage where Data: ViewRenderData { let storages = content.storages(data: data, type: type) return .init(nil, content: [.mainContent: storages]) } /// Update the stored content. /// - Parameters: /// - storage: The storage to update. /// - data: The widget data. /// - updateProperties: Whether to update the properties. /// - type: The type of the views. public func update( _ storage: ViewStorage, data: WidgetData, updateProperties: Bool, type: Data.Type ) where Data: ViewRenderData { guard let storages = storage.content[.mainContent] else { return } content.update(storages, data: data, updateProperties: updateProperties, type: type) } /// Render the collection as a menu. /// - Parameters: /// - data: The widget data. /// - menu: The menu. /// - Returns: The view storage with the GMenu as the pointer. public func getMenu(data: WidgetData, menu: NSMenu? = nil) -> ViewStorage { let item = NSMenuItem() let menu = menu ?? .init() let storage = container(data: data.noModifiers, type: MenuContext.self) initializeMenu(menu: menu, storage: storage) storage.pointer = item item.menu = menu return storage } /// Initialize a menu. /// - Parameters: /// - menu: The pointer to the GMenu. /// - storage: The storage for the menu's content. /// - app: The app object. /// - window: The window object. func initializeMenu(menu: NSMenu, storage: ViewStorage) { if let item = storage.pointer as? NSMenuItem { menu.addItem(item) } else { for element in storage.content[.mainContent] ?? [] { initializeMenu(menu: menu, storage: element) } } } }