SPB Git

Repository Public License

FeatureRegistry.swift 12.2 KB 256 lines swift

1import Foundation2import LunarDesign3import NavigatorCore4import Observation5import SwiftUI67/// Everything features contribute to the shell. One registry per process, owned by `AppEnvironment`, filled once8/// at launch by `NavigatorFeatures.registerAll(in:)` before the first window appears; the shell's own commands,9/// panels, layouts and settings sections are registered through the same calls (`includesShell`).10///11/// Identifiers are unique per kind. Registering a second contribution with an identifier already taken keeps12/// the first and records a line in `issues` (checked by the tests): nothing is replaced silently.13@MainActor14@Observable15public final class FeatureRegistry {16    public private(set) var commands: [NavigatorCommand] = []17    public private(set) var panels: [SidePanelContribution] = []18    public private(set) var toolbarItems: [ToolbarItemContribution] = []19    public private(set) var sidebarSections: [SidebarSectionContribution] = []20    public private(set) var sidebarFooterItems: [SidebarFooterItem] = []21    public private(set) var windowBadges: [WindowBadgeContribution] = []22    public private(set) var overlays: [WindowOverlayContribution] = []23    public private(set) var tabLayouts: [TabLayoutContribution] = []24    public private(set) var settingsSections: [SettingsSectionContribution] = []25    public private(set) var engineHooks: [EngineHooks] = []26    /// Highest priority first.27    @ObservationIgnored public private(set) var webAreaProviders: [any WebAreaContentProvider] = []28    /// Registration mistakes (duplicate identifiers). Empty in a correct build.29    public private(set) var issues: [String] = []3031    @ObservationIgnored private var commandIndex: [String: Int] = [:]32    @ObservationIgnored private var storeReadyCallbacks: [@MainActor (BrowserStore) -> Void] = []33    @ObservationIgnored private var readyStores: [ObjectIdentifier] = []3435    /// `includesShell: false` gives an empty registry (tests of the registry itself).36    public init(includesShell: Bool = true) {37        if includesShell { ShellContributions.register(in: self) }38    }3940    // MARK: Commands4142    public func register(_ command: NavigatorCommand) {43        guard commandIndex[command.id] == nil else { issues.append("Duplicate command id: \(command.id)"); return }44        commandIndex[command.id] = commands.count45        commands.append(command)46    }4748    public func register(commands: [NavigatorCommand]) { commands.forEach(register) }4950    public func command(_ id: String) -> NavigatorCommand? { commandIndex[id].map { commands[$0] } }5152    /// Runs the command if it exists and is available in `context`. Returns whether it ran.53    @discardableResult54    public func run(_ id: String, in context: CommandContext) async -> Bool {55        guard let command = command(id), command.isAvailable(context) else { return false }56        await command.perform(context)57        return true58    }5960    /// Fire-and-forget form for button actions.61    public func perform(_ id: String, in context: CommandContext) {62        guard let command = command(id), command.isAvailable(context) else { return }63        Task { await command.perform(context) }64    }6566    /// Commands sorted for the palette and Help: by category order, then by title.67    public func commandsByCategory() -> [(category: CommandCategory, commands: [NavigatorCommand])] {68        var groups: [String: (category: CommandCategory, commands: [NavigatorCommand])] = [:]69        for command in commands { groups[command.category.id, default: (command.category, [])].commands.append(command) }70        return groups.values71            .sorted { ($0.category.order, $0.category.id) < ($1.category.order, $1.category.id) }72            .map { ($0.category, $0.commands) }73    }7475    /// The commands placed somewhere, as runs separated by dividers.76    func placedCommands(_ matches: (CommandPlacement) -> Bool) -> [[NavigatorCommand]] {77        var keyed: [(group: Int, order: Int, index: Int, command: NavigatorCommand)] = []78        for (index, command) in commands.enumerated() {79            guard let placement = command.placement(where: matches) else { continue }80            let key = placement.sortKey81            keyed.append((key.0, key.1, index, command))82        }83        keyed.sort { ($0.group, $0.order, $0.index) < ($1.group, $1.order, $1.index) }84        var runs: [[NavigatorCommand]] = []85        var currentGroup: Int?86        for entry in keyed {87            if entry.group != currentGroup { runs.append([]); currentGroup = entry.group }88            runs[runs.count - 1].append(entry.command)89        }90        return runs91    }9293    /// Commands of a menu-bar menu, in display order, grouped between dividers.94    public func commands(in menu: MenuBarMenu) -> [[NavigatorCommand]] {95        placedCommands { if case .menuBar(menu, _, _) = $0 { true } else { false } }96    }9798    public var windowMenuCommands: [[NavigatorCommand]] {99        placedCommands { if case .windowMenu = $0 { true } else { false } }100    }101102    public var tabContextMenuCommands: [[NavigatorCommand]] {103        placedCommands { if case .tabContextMenu = $0 { true } else { false } }104    }105106    public var pageContextMenuCommands: [NavigatorCommand] {107        placedCommands { if case .pageContextMenu = $0 { true } else { false } }.flatMap { $0 }108    }109110    // MARK: Panels, toolbar, sidebar, badges111112    public func register(_ panel: SidePanelContribution) {113        guard self.panel(panel.id) == nil else { issues.append("Duplicate panel id: \(panel.id)"); return }114        panels.append(panel)115    }116117    public func panel(_ id: SidePanelID) -> SidePanelContribution? { panels.first { $0.id == id } }118119    public func register(_ item: ToolbarItemContribution) {120        guard !toolbarItems.contains(where: { $0.id == item.id }) else { issues.append("Duplicate toolbar item id: \(item.id)"); return }121        toolbarItems.append(item)122        toolbarItems.sort { ($0.order, $0.id) < ($1.order, $1.id) }123    }124125    public func toolbarItems(in placement: ToolbarItemPlacement) -> [ToolbarItemContribution] {126        toolbarItems.filter { !$0.placement.isDisjoint(with: placement) }127    }128129    public func toolbarItem(_ id: String) -> ToolbarItemContribution? { toolbarItems.first { $0.id == id } }130131    public func register(_ section: SidebarSectionContribution) {132        guard !sidebarSections.contains(where: { $0.id == section.id }) else { issues.append("Duplicate sidebar section id: \(section.id)"); return }133        sidebarSections.append(section)134        sidebarSections.sort { ($0.order, $0.id) < ($1.order, $1.id) }135    }136137    public func register(_ item: SidebarFooterItem) {138        guard !sidebarFooterItems.contains(where: { $0.id == item.id }) else { issues.append("Duplicate sidebar footer id: \(item.id)"); return }139        sidebarFooterItems.append(item)140        sidebarFooterItems.sort { ($0.order, $0.id) < ($1.order, $1.id) }141    }142143    public func register(_ badge: WindowBadgeContribution) {144        guard !windowBadges.contains(where: { $0.id == badge.id }) else { issues.append("Duplicate window badge id: \(badge.id)"); return }145        windowBadges.append(badge)146        windowBadges.sort { ($0.order, $0.id) < ($1.order, $1.id) }147    }148149    /// The badges the window carries right now.150    public func badges(for window: WindowModel) -> [WindowBadge] { windowBadges.compactMap { $0.badge(window) } }151152    // MARK: Overlays, web area, layouts, settings153154    public func register(_ overlay: WindowOverlayContribution) {155        guard self.overlay(overlay.id) == nil else { issues.append("Duplicate overlay id: \(overlay.id)"); return }156        overlays.append(overlay)157    }158159    public func overlay(_ id: String) -> WindowOverlayContribution? { overlays.first { $0.id == id } }160161    public func register(webArea provider: any WebAreaContentProvider) {162        guard !webAreaProviders.contains(where: { $0.id == provider.id }) else { issues.append("Duplicate web area provider id: \(provider.id)"); return }163        webAreaProviders.append(provider)164        webAreaProviders.sort { ($0.priority, $1.id) > ($1.priority, $0.id) }165    }166167    /// The provider that renders the web area of `window` now, or `nil` for the shell's single-tab view.168    public func activeWebAreaProvider(for window: WindowModel) -> (any WebAreaContentProvider)? {169        webAreaProviders.first { $0.isActive(in: window) }170    }171172    public func register(_ layout: TabLayoutContribution) {173        guard tabLayout(layout.mode) == nil else { issues.append("Duplicate tab layout: \(layout.mode.rawValue)"); return }174        tabLayouts.append(layout)175    }176177    public func tabLayout(_ mode: TabLayoutMode) -> TabLayoutContribution? { tabLayouts.first { $0.mode == mode } }178179    /// The layouts a window can use, in the canonical order (vertical, horizontal, compact, grid, orbit).180    public var supportedLayouts: [TabLayoutMode] {181        TabLayoutMode.allCases.filter { mode in tabLayouts.contains { $0.mode == mode } }182    }183184    public func register(_ section: SettingsSectionContribution) {185        guard !settingsSections.contains(where: { $0.id == section.id }) else { issues.append("Duplicate settings section id: \(section.id)"); return }186        settingsSections.append(section)187        settingsSections.sort { ($0.order, $0.id) < ($1.order, $1.id) }188    }189190    // MARK: Hooks and store readiness191192    public func register(_ hooks: EngineHooks) {193        guard !engineHooks.contains(where: { $0.id == hooks.id }) else { issues.append("Duplicate engine hooks id: \(hooks.id)"); return }194        engineHooks.append(hooks)195    }196197    /// Runs `body` once the browser store exists (database open, services created, windows restored but not198    /// restored yet, so before any engine hook fires): the place to create a feature's long-lived services and199    /// publish them in `store.services`. Call it from `register(in:)`.200    public func whenStoreReady(_ body: @escaping @MainActor (BrowserStore) -> Void) {201        storeReadyCallbacks.append(body)202    }203204    func storeBecameReady(_ store: BrowserStore) {205        guard !readyStores.contains(ObjectIdentifier(store)) else { return }206        readyStores.append(ObjectIdentifier(store))207        for callback in storeReadyCallbacks { callback(store) }208    }209210    // MARK: Presenting by identifier211212    /// What an identifier names, in the order `-ORIXShow` resolves it.213    public enum Presentable: Equatable { case overlay, panel, command }214215    public func presentable(_ id: String) -> Presentable? {216        if overlay(id) != nil { return .overlay }217        if panel(SidePanelID(id)) != nil { return .panel }218        if command(id) != nil { return .command }219        return nil220    }221222    /// Shows the overlay or the panel named `id`, or runs the command named `id`. Returns `false` for an223    /// unknown identifier. This is what `-ORIXShow <id>` calls.224    @discardableResult225    public func present(_ id: String, in window: WindowModel) async -> Bool {226        switch presentable(id) {227        case .overlay: window.present(overlay: id); return true228        case .panel: window.panel = SidePanelID(id); return true229        case .command: return await run(id, in: window.commandContext(source: .launchArgument))230        case nil: return false231        }232    }233234    // MARK: Audit235236    /// Every registered identifier, by kind (tests check uniqueness and naming).237    public var identifiersByKind: [String: [String]] {238        [239            "command": commands.map(\.id), "panel": panels.map(\.id.rawValue), "toolbarItem": toolbarItems.map(\.id),240            "sidebarSection": sidebarSections.map(\.id), "sidebarFooterItem": sidebarFooterItems.map(\.id),241            "windowBadge": windowBadges.map(\.id), "overlay": overlays.map(\.id),242            "webAreaProvider": webAreaProviders.map(\.id), "tabLayout": tabLayouts.map(\.id),243            "settingsSection": settingsSections.map(\.id), "engineHooks": engineHooks.map(\.id),244        ]245    }246247    /// Pairs of commands that claim the same default shortcut.248    public var shortcutCollisions: [(shortcut: CommandShortcut, commandIDs: [String])] {249        var owners: [CommandShortcut: [String]] = [:]250        for command in commands { if let shortcut = command.shortcut { owners[shortcut, default: []].append(command.id) } }251        return owners.filter { $0.value.count > 1 }252            .map { (shortcut: $0.key, commandIDs: $0.value.sorted()) }253            .sorted { $0.commandIDs.first ?? "" < $1.commandIDs.first ?? "" }254    }255}256
Files main
Menu

Theme