SPB Git

Repository Public License

EXTENDING.md 31.0 KB 539 lines markdown

1# Extending the shell23How a feature target (`FeatureOrbit`, `FeatureCommand`, `FeaturePrivacy`, `FeatureReading`, `FeatureAgent`,4`FeatureStudio`) plugs into the browser shell (`NavigatorUI`) without editing it.56The shell knows nothing about features. At launch both apps call78```swift9NavigatorFeatures.registerAll(in: AppEnvironment.shared.registry)   // before AppEnvironment.start()10```1112which calls `public enum <X>Feature { @MainActor public static func register(in registry: FeatureRegistry) }` of13each feature (`Sources/Feature<X>/<X>Feature.swift`). Everything a feature adds goes through that one function.14The shell's own commands, panels, layouts and settings sections are registered through the same calls15(`Sources/NavigatorUI/Extension/ShellCommands.swift`, `ShellContributions.swift`): read them as examples.1617## 1. Rules1819- **Register once, in `register(in:)`, synchronously.** No registration later, no registration from a view.20- **Identifiers** are stable strings, unique per kind, prefixed by the feature: `orbit.open`, `shield.panel`.21  Commands are dotted lower-case (`^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$`). An overlay and a panel must not share22  an identifier. A duplicate keeps the first registration and adds a line to `registry.issues` — the tests fail.23- **Threading.** The registry, every contribution closure, `BrowserStore`, `WindowModel`, `TabModel`, `WebEngine`24  and `FeatureServices` are `@MainActor`. Predicates (`isAvailable`, `isVisible`, `state`, `isChecked`,25  `isActive(in:)`, badge closures) run during view updates: they read state, they never mutate it, never block and26  never start work. Hooks run synchronously on the main actor in registration order: return at once and start a27  `Task` for anything real. Disk and network never on the main actor: put them in your engine's actor.28- **Read observable state** in predicates (the window, its tabs, engines, your `@Observable` per-window state) so29  that views update; state kept elsewhere will not refresh the chrome.30- **Never import another feature.** Share through `store.services` (§9) or run a command by identifier31  (`window.run("agent.summarize")`).32- **Private windows.** Check `window.isEphemeral` / `event.isEphemeral` / `context.isEphemeralWindow` before33  writing anything about a page or a tab: nothing from an ephemeral window may reach disk (§8).34- **Strings**: every user-facing string in your own String Catalog, English and French (Canada) (§10).35- No placeholder contribution: a command that does nothing, a panel with fake content or an inert toolbar item36  must not be registered.3738## 2. Commands3940One action = one `NavigatorCommand`. The menu bar (Mac), hardware-keyboard commands (iPad), the "…" window41menu (capsule and phone dock), tab and page context menus, the Help panel, the command palette and `-ORIXRun`42all run commands from the registry.4344```swift45public struct NavigatorCommand: Identifiable {46    public let id: String47    public var title: LocalizedText                 // palette, Help, menus48    public var category: CommandCategory            // .tabs .navigation .page .view .bookmarks .history .windows .tools .privacy .app, or your own49    public var icon: LunarIcon?                     // .symbol("…") or .glyph(.orbit)50    public var shortcut: CommandShortcut?51    public var keywords: [String]                   // localised search terms for the palette52    public var placements: [CommandPlacement]53    public var hidesWhenUnavailable: Bool           // menus drop the item instead of disabling it54    public var dynamicTitle: (@MainActor (CommandContext) -> LocalizedText?)?   // "Unpin Tab"; nil keeps `title`55    public var isAvailable: @MainActor (CommandContext) -> Bool                 // default: always56    public var isChecked: (@MainActor (CommandContext) -> Bool)?                // non-nil: shown with a check mark57    public var perform: @MainActor (CommandContext) async -> Void58    public init(id:title:category:icon:shortcut:keywords:placements:hidesWhenUnavailable:dynamicTitle:isAvailable:isChecked:perform:)59    @MainActor public func displayTitle(in context: CommandContext) -> String60}6162public struct CommandCategory: Identifiable, Hashable, Sendable { public init(id: String, title: LocalizedText, order: Int) }6364public enum MenuBarMenu: String, Sendable, CaseIterable { case app, file, edit, view, history, bookmarks, tools, window, help }6566public enum CommandPlacement: Hashable, Sendable {67    case menuBar(MenuBarMenu, group: Int, order: Int)   // `.tools` is the menu for what fits nowhere else68    case windowMenu(group: Int, order: Int)             // "…" menu: capsule (Mac, iPad) and phone dock69    case tabContextMenu(group: Int, order: Int)         // context.tab is the tab that was clicked70    case pageContextMenu(order: Int)                    // Mac: any element; iOS: links. After WebKit's items71}7273public struct CommandShortcut: Hashable, Sendable, CustomStringConvertible {74    public enum Key: Hashable, Sendable { case character(Character), tab, `return`, escape, delete, space, upArrow, downArrow, leftArrow, rightArrow }75    public struct Modifiers: OptionSet, Hashable, Sendable { static let command, shift, option, control }76    public init(_ key: Key, modifiers: Modifiers = .command)77    public init(_ character: Character, modifiers: Modifiers = .command)78    public var keyCaps: [String]                        // ["⇧", "⌘", "T"]79    public var keyboardShortcut: KeyboardShortcut       // SwiftUI80}8182@MainActor public struct CommandContext {83    public let environment: AppEnvironment84    public let store: BrowserStore85    public let window: WindowModel?          // nil when no browser window has focus86    public let tab: TabModel?                // the selected tab, or the tab the command was invoked on87    public var source: CommandSource         // .menuBar .windowMenu .contextMenu .toolbar .sidebar .palette .help .launchArgument .feature88    public var isCompactWidth: Bool89    public var registry: FeatureRegistry; public var services: FeatureServices; public var settings: AppSettings90    public var engine: WebEngine?; public var url: URL?91    public var hasPage: Bool                 // not the new-tab page92    public var isWebPage: Bool               // http(s)93    public var isEphemeralWindow: Bool94    public init(environment:store:window:tab:source:isCompactWidth:)95    public func targeting(_ tab: TabModel?, source: CommandSource? = nil) -> CommandContext96}97```9899Groups separate runs of menu items with a divider; `order` sorts inside a group. The shell uses multiples of 10100for both (see the table in §12) so that a feature can slot in between: `.menuBar(.view, group: 45, order: 10)`.101102Running commands:103104```swift105registry.commands                                   // [NavigatorCommand], registration order106registry.command("orbit.open")                      // NavigatorCommand?107await registry.run("orbit.open", in: context)       // Bool: false if unknown or unavailable108registry.perform("orbit.open", in: context)         // fire and forget109window.commandContext(tab:source:isCompactWidth:)   // a context for a window110window.run("orbit.open")                            // from a button111registry.commandsByCategory()                       // for a palette: [(category, commands)]112registry.commands(in: .view)                        // [[NavigatorCommand]] runs of a menu113```114115Default shortcuts must not collide (`registry.shortcutCollisions`, tested) and must not take a system or116text-editing shortcut (⌘Q ⌘H ⌘M ⌘C ⌘V ⌘X ⌘Z ⌘A ⇧⌘Z ⇥ space). Taken by the shell: §12.117118## 3. Side panels119120Right-hand panel on Mac and iPad (348 pt unless `preferredWidth`), a sheet on iPhone. The shell draws the121header (icon, title, close); your view fills the rest and gets `BrowserStore` and the Lunar theme from the122environment.123124```swift125public struct SidePanelID: RawRepresentable, Hashable, Sendable, Identifiable, ExpressibleByStringLiteral126    // shell: .history .bookmarks .downloads .settings .help127public struct SidePanelContribution: Identifiable {128    public init<Content: View>(id: SidePanelID, title: LocalizedText, icon: LunarIcon, preferredWidth: CGFloat? = nil,129                               @ViewBuilder content: @escaping @MainActor (WindowModel) -> Content)130}131window.panel = "shield.panel"; window.togglePanel("shield.panel"); window.panel = nil132```133134Register a command that opens it (and place it in a menu) — a panel nothing opens is unreachable.135136## 4. Toolbar items, sidebar, window badges137138```swift139public enum ContributionAction {140    case command(String)                          // disabled while the command is unavailable141    case panel(SidePanelID)                       // toggles142    case overlay(String)                          // toggles143    case perform(@MainActor (CommandContext) -> Void)144    case popover(@MainActor (WindowModel) -> AnyView)   // popover; a sheet from the phone menu145}146public struct ContributionState: Equatable, Sendable {147    public init(isActive: Bool = false, badge: Int? = nil, isEnabled: Bool = true, icon: LunarIcon? = nil, accessibilityValue: String? = nil)148}149public struct ToolbarItemPlacement: OptionSet {150    static let addressField   // inside the address field, before Reload (Mac, iPad) and in the phone address pill: page indicators151    static let capsule        // a capsule button after Share (Mac, iPad); on iPhone an entry of the dock "…" menu152}153public struct ToolbarItemContribution: Identifiable {154    public init(id: String, label: LocalizedText, icon: LunarIcon, placement: ToolbarItemPlacement, order: Int = 100,155                isVisible: @escaping @MainActor (CommandContext) -> Bool = { _ in true },      // e.g. { $0.isWebPage }156                state: @escaping @MainActor (CommandContext) -> ContributionState = { _ in .normal },157                action: ContributionAction)158}159public struct SidebarSectionContribution: Identifiable {   // a block of the vertical sidebar (268 pt wide)160    public enum Placement { case aboveTabs, belowTabs }161    public init<Content: View>(id: String, placement: Placement, order: Int = 100,162                               isVisible: @escaping @MainActor (WindowModel) -> Bool = { _ in true },163                               @ViewBuilder content: @escaping @MainActor (WindowModel) -> Content)164}165public struct SidebarFooterItem: Identifiable {   // icon row at the bottom; first five by order, the rest in "More"166    public init(id: String, label: LocalizedText, icon: LunarIcon, order: Int = 100, isVisible:state:action:)167}   // shell: history 10, bookmarks 20, downloads 30, settings 1000168public struct WindowBadge: Equatable, Sendable { public init(label: String, icon: LunarIcon, status: LunarStatus = .neutral) }169public struct WindowBadgeContribution: Identifiable {170    public init(id: String, order: Int = 100, badge: @escaping @MainActor (WindowModel) -> WindowBadge?)171}172```173174A window badge marks the chrome of a kind of window (private, focus): it is drawn in the sidebar's space header,175at the leading edge of the toolbar when the sidebar is not shown, and in the phone address pill.176"Phone menu entries" are commands placed in `.windowMenu` plus `capsule` toolbar items: there is no separate177kind. The capsule has room for about three extra buttons at the minimum window width; prefer `addressField`178for page indicators and the window menu for the rest.179180## 5. Window overlays181182Full-window modal surfaces (the Orbit view, the command palette).183184```swift185public enum WindowOverlayStyle { case scrim(alignment: Alignment = .center, maxWidth: CGFloat? = 640, maxHeight: CGFloat? = nil), fullCover }186public struct WindowOverlayContribution: Identifiable {187    public init<Content: View>(id: String, style: WindowOverlayStyle, dismissesOnOutsideTap: Bool = true,188                               @ViewBuilder content: @escaping @MainActor (WindowModel) -> Content)189}190window.present(overlay: "command.palette"); window.toggle(overlay:); window.dismissOverlay(); window.presentedOverlayID191window.focusPage()      // what dismissOverlay() does after hiding192```193194One overlay per window; presenting replaces the one shown. Escape always dismisses, then keyboard focus goes195back to the page. `.scrim` content brings its own surface (`.lunarGlass(...)`); `.fullCover` gets the window196backdrop. A text field in your overlay takes focus itself (`@FocusState`, `.onAppear`).197198## 6. Web area, tab content, chrome visibility, tab layouts199200```swift201@MainActor public protocol WebAreaContentProvider: AnyObject {202    var id: String { get }203    var priority: Int { get }                          // higher wins. Reader 100, Split 200, full takeover 300204    func isActive(in window: WindowModel) -> Bool      // observable state only205    func makeContent(_ context: WebAreaContext) -> AnyView206}207@MainActor public final class WebAreaProvider: WebAreaContentProvider {    // closure form208    public init<Content: View>(id: String, priority: Int, isActive: @escaping @MainActor (WindowModel) -> Bool,209                               @ViewBuilder content: @escaping @MainActor (WebAreaContext) -> Content)210}211@MainActor public struct WebAreaContext { window; webOptions: WebEngineViewOptions; bottomChromeInset: CGFloat; isCompactWidth: Bool }212registry.register(webArea: provider); registry.activeWebAreaProvider(for: window)213214public struct TabContentView: View {     // one tab: web view, new-tab page, error / certificate / blocked pages215    public init(window: WindowModel, tab: TabModel, options: WebEngineViewOptions = .init(), bottomInset: CGFloat = 0)216}217```218219The shell asks providers from the highest priority down and uses the first that is active; with none it shows220`TabContentView` for the selected tab. The shell keeps drawing banners, the find bar, page prompts and toasts on221top, and the rounded frame around. Split composes several `TabContentView`s (activate their engines with222`store.pool.activate(tab.engine)`; pass `context.webOptions`); Reader returns its article view.223224Chrome visibility (Focus):225226```swift227public struct ChromeElements: OptionSet { static let sidebar, tabStrip, toolbar, panel, all }228window.setChromeHidden([.sidebar, .tabStrip], requester: "orbit.focus")   // [] releases229window.hiddenChrome                                                       // union of all requests230```231232Whoever hides the toolbar must offer a way back (a command with a shortcut): the shell does not override it.233234Tab layouts (Mac, iPad; the phone has its own):235236```swift237public struct TabLayoutContribution: Identifiable {238    public init<Content: View>(mode: TabLayoutMode, title: LocalizedText, icon: LunarIcon,239                               @ViewBuilder body: @escaping @MainActor (TabLayoutContext) -> Content)240}241@MainActor public struct TabLayoutContext { window; windowControlsInset: CGFloat; hiddenChrome: ChromeElements }242registry.supportedLayouts      // shell: [.vertical, .horizontal, .compact]; + .grid / .orbit once registered243```244245`body` draws everything of the window except the side panel, from the public blocks `SidebarView(window:)`,246`TabStripView(window:isCondensed:)`, `NewTabButton(window:)`, `BrowserToolbarRow(window:leadingReserve:)` and247`WebAreaView(window:)`; keep `windowControlsInset` free at the leading edge of the first row and honour248`hiddenChrome`. The commands `view.layout.grid` / `view.layout.orbit` and the Settings choice exist already and249become available when the renderer is registered.250251## 7. Settings sections252253```swift254public struct SettingsSectionContribution: Identifiable {255    public init<Content: View>(id: String, title: LocalizedText, icon: LunarIcon, order: Int,256                               isVisible: @escaping @MainActor (WindowModel) -> Bool = { _ in true },257                               @ViewBuilder content: @escaping @MainActor (WindowModel) -> Content)258}259```260261`content` is stacked vertically inside the section's card. Shell sections: appearance 10, search 20, tabs 30,262newtab 40, onehanded 50 (iPhone), downloads 60, privacy 70, about 10 000 (always last); features use 100…9 999.263Persist values with `store.database.settings` and your own `SettingKey`s. Open at a section with264`window.panel = .settings; window.settingsSectionRequest = "shield.settings"` or `-ORIXSettingsSection <id>`.265266## 8. Engine hooks, profiles, private windows267268```swift269public struct EngineHooks: Identifiable {270    public init(id: String,271        profileContextCreated: (@MainActor (ProfileEvent) -> Void)? = nil,    // once per ProfileContext: attach rule lists here272        windowOpened: (@MainActor (WindowEvent) -> Void)? = nil,273        windowClosed: (@MainActor (WindowEvent) -> Void)? = nil,274        configureSettings: (@MainActor (inout WebEngineSettings, _ profile: Profile, _ isEphemeral: Bool) -> Void)? = nil,275        engineCreated: (@MainActor (TabEvent) -> Void)? = nil,                // install user scripts / stylesheets276        engineWillClose: (@MainActor (TabEvent) -> Void)? = nil,277        navigationCommitted: (@MainActor (NavigationEvent) -> Void)? = nil,   // also same-document navigations (same commitCount, new url)278        navigationFinished: (@MainActor (NavigationEvent) -> Void)? = nil,    // loaded, no error page; title is final279        tabSelected: (@MainActor (TabEvent, _ previous: TabID?) -> Void)? = nil,280        tabClosed: (@MainActor (TabEvent) -> Void)? = nil)281}282ProfileEvent:    store, profile, context: ProfileContext, isGhost283WindowEvent:     store, window, windowID, profile, space, isEphemeral, isGhost284TabEvent:        store, window, tab, engine, tabID, windowID, spaceID, profile, profileContext, isGhost, isEphemeral285NavigationEvent: tab: TabEvent, url, title, commitCount, engine, profile, isGhost, isEphemeral286registry.whenStoreReady { store in … }     // database open, services created, before windows are restored287```288289Order at launch: `register(in:)` → store opens → `whenStoreReady` callbacks → restored windows290(`windowOpened`, `profileContextCreated`, `engineCreated` per tab) → first window on screen. Create your291long-lived services in `whenStoreReady`, so that hooks can use them.292293Windows, profiles, spaces:294295```swift296window.profile: Profile; window.space: OrbitSpace; window.persistence: WindowPersistence; window.isEphemeral297window.dataProfileID            // whose bookmarks/history the window reads (the default profile for a private window)298store.profile; store.space      // the default profile and its first space299store.openWindow(in: space, profile: profile, persistence: .normal | .ephemeral, url: nil) -> WindowModel300store.windows(of: profileID); store.canMoveTab(_:to:); store.profileContext(for: profile)301```302303`.normal` needs a stored profile and space (`store.services.orbit.createProfile(name:tint:)`,304`.createSpace(profile:name:…)`); such windows are restored at the next launch with their profile.305`.ephemeral` is the private window: the store never sends it or its tabs to `SessionOrchestrator`, it has no306recently-closed tabs, WebRuntime records no history for its (ghost) profile, permission answers stay in memory,307its site icons stay in memory, its tabs are not suggested to other windows and cannot be moved to a normal308window. It always runs on a ghost profile: pass one (`GhostSession(database:)` of PrivacyEngine gives a profile309and a space) or pass a standard profile and the store derives a ghost one. When the last window of a ghost310profile closes, the store ends the WebKit session, the in-memory permissions and the icons.311`anEphemeralWindowWritesNothing` (NavigatorUITests) proves zero rows and zero files; keep it true: **a feature312must not write anything when `isEphemeral` is true**. Mark the chrome with a `WindowBadgeContribution`:313314```swift315registry.register(WindowBadgeContribution(id: "ghost.badge") { window in316    window.isEphemeral ? WindowBadge(label: L("Private"), icon: .glyph(.ghost), status: .accent) : nil317})318```319320On the Mac and iPad a new window gets its own scene; on iPhone the single scene switches to it and falls back321to another window when it closes.322323Per-window and per-tab feature state (one instance per type, created on first use, released with the owner):324325```swift326window.featureState(SplitState.self) { SplitState() }     // make it @Observable327window.existingFeatureState(SplitState.self)              // nil if never created — use this in predicates328tab.featureState(ReaderState.self) { ReaderState() }; tab.existingFeatureState(ReaderState.self); tab.window329```330331## 9. Services332333```swift334@MainActor public final class FeatureServices {       // store.services, context.services335    public let database: NavigatorDatabase336    public let settings: AppSettings337    public let orbit: OrbitService338    public let permissions: PermissionService?        // nil only in tests without one339    public let downloads: DownloadManager?340    public let profiles: WebProfileRegistry341    public let secrets: any SecretStore               // Keychain, service "ai.spboucher.orix.navigator"; in memory in tests342    public let favicons: FaviconStore343    public let dataDirectory: URL?344    public func register<Service>(_ service: Service, for key: ServiceKey<Service>)345    public func service<Service>(_ key: ServiceKey<Service>) -> Service?       // also services[key]346}347public struct ServiceKey<Service>: Hashable, Sendable { public init(_ name: String) }   // in NavigatorCore348```349350To offer a service to other features without being imported by them, put the contract in a **new NavigatorCore351file named after your feature** (allowed by AGENT_RULES), keep the implementation in the feature, publish it in352`whenStoreReady`:353354```swift355// Sources/NavigatorCore/FeatureAgent+Services.swift356public protocol PageSummarizing: Sendable { func summarize(tab: TabID) async throws -> String }357extension ServiceKey where Service == any PageSummarizing { public static let pageSummarizer = ServiceKey("agent.pageSummarizer") }358// FeatureAgent359registry.whenStoreReady { store in store.services.register(Summarizer(store) as any PageSummarizing, for: .pageSummarizer) }360// FeatureReading — degrade when absent, never crash361if let summarizer = store.services.service(.pageSummarizer) { … } else { /* hide the button */ }362```363364## 10. Localisation365366Each feature has its own catalog, `Sources/Feature<X>/Resources/Localizable.xcstrings` (source language `en`,367plus `fr-CA`), in its own bundle. The key is the English text. `<X>Feature.swift` already declares:368369```swift370let strings = FeatureStrings(module: "FeatureOrbit", bundle: .module)371func L(_ key: String, _ arguments: any CVarArg...) -> String   // a string now: L("%d tabs", count)372func T(_ key: String) -> LocalizedText                          // a title for the registry: T("Open Orbit")373```374375Always call `L("literal")` / `T("literal")` with a string literal: `NavigatorFeaturesTests` scans your sources376for those calls and fails on a key missing in English or French (Canada), on differing `%@`/`%d` placeholders377and on catalog entries no code uses. Registry titles must be `T(...)`, never `.verbatim`.378379## 11. Launch arguments (screenshots without input)380381```382-ORIXShow <id>              a built-in target, else an overlay id, else a panel id, else a command id383-ORIXRun <command-id>       repeatable, run in order after -ORIXShow, on the first window384-ORIXSettingsSection <id>   opens Settings scrolled to a section385-ORIXTabLayout vertical|horizontal|compact|grid|orbit386```387388`scripts/shot.sh mac orbit -- -ORIXShow orbit.view`. Every feature screen must be reachable this way: give389each a command (state that needs several steps: `-ORIXRun a -ORIXRun b`).390391## 12. What the shell registers392393Menu groups (`group`): file 10 new · 20 open · 30 close · 40 tab state · 50 share/export; edit 10 find · 20394copy; view 10 reload · 20 zoom · 30 page mode · 40 sidebar/panels · 50 layouts; history 10 back/forward · 20395history · 30 clear; bookmarks 10; window 10 next/previous · 20 move · 30 select; help 10 · 20; app 10.396Window menu: 10 new · 20 panels/bookmark · 30 page · 40 layouts · 90 settings/help.397Tab context menu: 10 tab state · 20 move · 30 copy · 40 close.398399| Command id | Title | Shortcut |400|---|---|---|401| `tab.new` | New Tab | ⌘T |402| `tab.close` | Close Tab | ⌘W |403| `tab.closeOthers` | Close Other Tabs | |404| `tab.reopenClosed` | Reopen Closed Tab | ⇧⌘T |405| `tab.reload` | Reload (tab context menu) | |406| `tab.duplicate` | Duplicate Tab | |407| `tab.pin` | Pin Tab / Unpin Tab | |408| `tab.mute` | Mute Tab / Unmute Tab | |409| `tab.moveLeft`, `tab.moveRight` | Move Tab Left / Right | |410| `tab.moveToNewWindow` | Move Tab to New Window | |411| `tab.next`, `tab.previous` | Show Next / Previous Tab | ⌃⇥, ⌃⇧⇥ |412| `tabs.showSwitcher` | Show All Tabs (compact width) | |413| `tab.select.1` … `tab.select.8`, `tab.select.last` | Show Tab N / Show Last Tab | ⌘1 … ⌘8, ⌘9 |414| `window.new` | New Window | ⌘N |415| `window.close` (Mac) | Close Window | ⇧⌘W |416| `omnibox.focus` | Open Location… | ⌘L |417| `nav.back`, `nav.forward` | Back, Forward | ⌘[, ⌘] |418| `page.reload`, `page.reloadFromOrigin`, `page.stop` | Reload Page, Reload from Origin, Stop | ⌘R, ⇧⌘R, ⌘. |419| `find.show`, `find.next`, `find.previous` | Find in Page…, Find Next, Find Previous | ⌘F, ⌘G, ⇧⌘G |420| `bookmark.add` | Bookmark This Page… | ⌘D |421| `page.copyURL` | Copy Page Address | ⇧⌘C |422| `page.share`, `page.savePDF`, `page.print` | Share…, Save as PDF…, Print… | –, –, ⌘P |423| `page.toggleContentMode` | Request Mobile Site / Request Desktop Site | |424| `view.zoomIn`, `view.zoomOut`, `view.zoomReset` | Zoom In, Zoom Out, Actual Size | ⌘+, ⌘-, ⌘0 |425| `view.toggleSidebar` | Hide Sidebar / Show Sidebar | ⌘S |426| `view.layout.vertical` `.horizontal` `.compact` `.grid` `.orbit` | Vertical / Horizontal / Compact Tabs, Grid of Tabs, Orbit Tabs | |427| `panel.history`, `panel.bookmarks`, `panel.downloads`, `panel.settings` | Show History, Show Bookmarks, Show Downloads, Settings… | ⌘Y, ⌥⌘B, ⇧⌘J, ⌘, |428| `panel.close` | Close Side Panel | |429| `privacy.clearData` | Clear Browsing Data… | |430| `help.show`, `help.welcome` | ORIX Navigator Help, Show Welcome Screens | ⇧⌘/ |43143257 commands on the Mac (56 on iOS, which has no `window.close`); constants in `ShellCommandID`.433434## 13. A complete minimal feature435436```swift437import LunarDesign438import NavigatorCore439import NavigatorUI440import SwiftUI441import WebRuntime442443@MainActor @Observable final class PulseWindowState { var count = 0 }444445@MainActor final class PulseService {            // long-lived, created once per store446    private(set) var pagesSeen: [TabID: Int] = [:]447    func note(_ event: NavigationEvent) {448        guard !event.isEphemeral else { return }    // nothing about a private page is kept449        pagesSeen[event.tab.tabID, default: 0] += 1450    }451    func forget(_ tab: TabID) { pagesSeen[tab] = nil }452}453extension ServiceKey where Service == PulseService { static let pulse = ServiceKey("pulse.service") }454455public enum PulseFeature {456    @MainActor public static func register(in registry: FeatureRegistry) {457        let category = CommandCategory(id: "pulse", title: T("Pulse"), order: 200)458459        // Service, then the hooks that feed it.460        registry.whenStoreReady { store in store.services.register(PulseService(), for: .pulse) }461        registry.register(EngineHooks(462            id: "pulse",463            navigationFinished: { event in event.tab.store.services.service(.pulse)?.note(event) },464            tabClosed: { event in event.store.services.service(.pulse)?.forget(event.tabID) }))465466        // Command: opens the panel. Menu bar (View), window menu, shortcut, palette, Help, -ORIXRun.467        registry.register(NavigatorCommand(468            id: "pulse.show", title: T("Show Pulse"), category: category, icon: .glyph(.blink),469            shortcut: CommandShortcut("u", modifiers: [.command, .option]), keywords: [L("activity")],470            placements: [.menuBar(.view, group: 45, order: 10), .windowMenu(group: 25, order: 10)],471            isAvailable: { $0.window != nil },472            isChecked: { $0.window?.panel == "pulse.panel" },473            perform: { $0.window?.togglePanel("pulse.panel") }))474        registry.register(NavigatorCommand(475            id: "pulse.overview", title: T("Pulse Overview"), category: category, icon: .glyph(.blink),476            isAvailable: { $0.window != nil }, perform: { $0.window?.present(overlay: "pulse.overview") }))477478        // Panel.479        registry.register(SidePanelContribution(id: "pulse.panel", title: T("Pulse"), icon: .glyph(.blink)) { window in480            PulsePanel(window: window)481        })482483        // Toolbar item: only on web pages, shows a count, opens the panel.484        registry.register(ToolbarItemContribution(485            id: "pulse.indicator", label: T("Pulse"), icon: .glyph(.blink), placement: .addressField,486            isVisible: { $0.isWebPage },487            state: { context in488                let seen = context.tab.flatMap { context.services.service(.pulse)?.pagesSeen[$0.id] } ?? 0489                return ContributionState(isActive: context.window?.panel == "pulse.panel", badge: seen,490                                         accessibilityValue: L("%d pages", seen))491            },492            action: .command("pulse.show")))493494        // Overlay.495        registry.register(WindowOverlayContribution(id: "pulse.overview", style: .scrim(alignment: .top, maxWidth: 560)) { window in496            PulseOverview(window: window)497        })498499        // Settings section.500        registry.register(SettingsSectionContribution(id: "pulse.settings", title: T("Pulse"), icon: .glyph(.blink), order: 300) { _ in501            PulseSettings()502        })503    }504}505506struct PulsePanel: View {507    @Environment(\.lunarTheme) private var theme508    @Environment(BrowserStore.self) private var store509    let window: WindowModel510511    var body: some View {512        let state = window.featureState(PulseWindowState.self) { PulseWindowState() }513        VStack(alignment: .leading, spacing: LunarSpacing.sm) {514            Text(L("%d pages", store.services.service(.pulse)?.pagesSeen.values.reduce(0, +) ?? 0))515                .lunarFont(.headline).foregroundStyle(theme.textPrimary)516            Button(L("Count")) { state.count += 1 }.buttonStyle(.lunar(.secondary))517            Button(L("Pulse Overview")) { window.run("pulse.overview") }.buttonStyle(.lunar(.primary))518        }519        .padding(LunarSpacing.md)520    }521}522```523524`PulseOverview` and `PulseSettings` are ordinary views. Screenshots:525`scripts/shot.sh mac pulse -- -ORIXOpenURL https://example.com -ORIXShow pulse.panel`, `-ORIXShow pulse.overview`,526`-ORIXSettingsSection pulse.settings`.527528## 14. Checklist before you report529530- [ ] Everything registered from `<X>Feature.register(in:)`; no edit outside your directories (new shared531      contracts: one new file `Sources/NavigatorCore/Feature<X>+….swift`).532- [ ] Identifiers prefixed and unique; `registry.issues` empty.533- [ ] Each screen has a command; each command has a `T("…")` title in en and fr-CA; shortcuts do not collide.534- [ ] Predicates are pure and read observable state; hooks return at once; no disk or network on the main actor.535- [ ] Nothing is written, indexed, logged or cached for an ephemeral window; secrets only in `services.secrets`.536- [ ] Compact width works: commands in `.windowMenu`, panels as sheets, `capsule` items in the dock menu.537- [ ] `swift test --filter "Feature<X>Tests|NavigatorFeaturesTests|NavigatorUITests"` green, zero warnings in538      your target; `scripts/build.sh mac` and `ios` build; screenshots taken with `scripts/shot.sh` and looked at.539
Files main
Menu

Theme