SPB Git

Repository Public License

ContributedControls.swift 8.9 KB 225 lines swift

1import LunarDesign2import NavigatorCore3import SwiftUI45// MARK: - Commands as menu items67/// Menu items for runs of commands (dividers between runs). Used by the menu bar, the window menu and the tab8/// context menu, so that an item looks and behaves the same everywhere.9struct CommandMenuItems: View {10    let groups: [[NavigatorCommand]]11    let context: CommandContext?12    var showsIcons = false13    var showsShortcuts = false1415    var body: some View {16        let visible = groups.map { $0.filter(shows) }.filter { !$0.isEmpty }17        ForEach(Array(visible.enumerated()), id: \.offset) { index, group in18            if index > 0 { Divider() }19            ForEach(group) { command in item(command) }20        }21    }2223    private func shows(_ command: NavigatorCommand) -> Bool {24        guard command.hidesWhenUnavailable, let context else { return true }25        return command.isAvailable(context)26    }2728    @ViewBuilder private func item(_ command: NavigatorCommand) -> some View {29        let title = context.map(command.displayTitle(in:)) ?? command.title.string30        let enabled = context.map(command.isAvailable) ?? false31        Group {32            if let isChecked = command.isChecked, let context {33                Toggle(isOn: Binding(get: { isChecked(context) }, set: { _ in run(command) })) { label(title, command) }34            } else {35                Button { run(command) } label: { label(title, command) }36            }37        }38        .keyboardShortcut(showsShortcuts ? command.shortcut?.keyboardShortcut : nil)39        .disabled(!enabled)40    }4142    @ViewBuilder private func label(_ title: String, _ command: NavigatorCommand) -> some View {43        if showsIcons, case .symbol(let name)? = command.icon {44            Label(title, systemImage: name)45        } else {46            Text(title)47        }48    }4950    private func run(_ command: NavigatorCommand) {51        guard let context, command.isAvailable(context) else { return }52        Task { await command.perform(context) }53    }54}5556// MARK: - Contributed controls5758extension WindowModel {59    /// Runs the action of a contributed control. Popovers are presented by the control itself.60    func perform(_ action: ContributionAction, context: CommandContext) {61        switch action {62        case .command(let id): store.registry.perform(id, in: context)63        case .panel(let id): togglePanel(id)64        case .overlay(let id): toggle(overlay: id)65        case .perform(let body): body(context)66        case .popover: break67        }68    }6970    func isEnabled(_ action: ContributionAction, context: CommandContext) -> Bool {71        if case .command(let id) = action { return store.registry.command(id)?.isAvailable(context) ?? false }72        return true73    }74}7576/// A count on the corner of a toolbar or sidebar icon.77struct CountBadge: View {78    @Environment(\.lunarTheme) private var theme79    let count: Int8081    var body: some View {82        Text(verbatim: count > 99 ? "99+" : "\(count)")83            .lunarFont(.overline).lunarTabularDigits()84            .foregroundStyle(theme.accent)85            .padding(.horizontal, 4).frame(minWidth: 16, minHeight: 16)86            .background { Capsule().fill(theme.elevatedSurface) }87            .overlay { Capsule().strokeBorder(theme.hairlineStrong, lineWidth: 1) }88            .accessibilityHidden(true)89    }90}9192/// A toolbar item contributed through the registry, drawn as an icon button.93struct ContributedToolbarButton: View {94    @Environment(\.lunarTheme) private var theme95    @Environment(BrowserStore.self) private var store96    let window: WindowModel97    let item: ToolbarItemContribution98    var diameter: CGFloat = LunarMetrics.controlHeight99    var isCompactWidth = false100    @State private var showsPopover = false101102    var body: some View {103        let context = window.commandContext(source: .toolbar, isCompactWidth: isCompactWidth)104        if item.isVisible(context) {105            let state = item.state(context)106            LunarIconButton(state.icon ?? item.icon, label: item.label.string, isActive: state.isActive, diameter: diameter) {107                if case .popover = item.action { showsPopover = true } else { window.perform(item.action, context: context) }108            }109            .overlay(alignment: .topTrailing) {110                if let badge = state.badge, badge > 0 { CountBadge(count: badge).offset(x: 3, y: -2) }111            }112            .disabled(!state.isEnabled || !window.isEnabled(item.action, context: context))113            .accessibilityValue(state.accessibilityValue ?? (state.badge.map { $0 > 0 ? "\($0)" : "" } ?? ""))114            .accessibilityIdentifier("toolbar." + item.id)115            .popover(isPresented: $showsPopover) {116                if case .popover(let content) = item.action {117                    content(window)118                        .environment(store)119                        .lunarTheme(theme)120                        .presentationCompactAdaptation(.popover)121                }122            }123        }124    }125}126127/// The marks features put on a window (private, focus…).128struct WindowBadgesView: View {129    @Environment(\.lunarTheme) private var theme130    @Environment(BrowserStore.self) private var store131    let window: WindowModel132    /// Icon only, for tight places (the phone address pill, the toolbar's leading edge).133    var isCompact = false134135    var body: some View {136        let badges = store.registry.badges(for: window)137        if !badges.isEmpty {138            HStack(spacing: LunarSpacing.unit) {139                ForEach(Array(badges.enumerated()), id: \.offset) { _, badge in140                    if isCompact {141                        LunarIconView(badge.icon, size: 15)142                            .foregroundStyle(tone(badge.status))143                            .frame(width: 26, height: 26)144                            .background { Circle().fill(tone(badge.status).withAlpha(0.14)) }145                            .accessibilityElement()146                            .accessibilityLabel(badge.label)147                            .help(badge.label)148                    } else {149                        LunarBadge(badge.label, status: badge.status, icon: badge.icon)150                    }151                }152            }153            .accessibilityElement(children: .contain)154            .accessibilityIdentifier("window.badges")155        }156    }157158    private func tone(_ status: LunarStatus) -> LunarRGBA {159        switch status {160        case .neutral: theme.textSecondary161        case .accent: theme.accent162        case .success: theme.success163        case .warning: theme.warning164        case .danger: theme.danger165        }166    }167}168169// MARK: - Window overlays170171/// Draws the overlay a window presents, above everything of the scene. Escape dismisses it.172struct WindowOverlayHost: View {173    @Environment(\.lunarTheme) private var theme174    @Environment(BrowserStore.self) private var store175    let window: WindowModel176    @FocusState private var hasFocus: Bool177178    var body: some View {179        ZStack {180            if let id = window.presentedOverlayID, let overlay = store.registry.overlay(id) {181                content(overlay)182                    .id(id)183                    .transition(.opacity)184                    .accessibilityElement(children: .contain)185                    .accessibilityAddTraits(.isModal)186                    .accessibilityIdentifier("overlay." + id)187                    // The host takes focus so that Escape reaches it even when the overlay has no field.188                    .focusable()189                    .focusEffectDisabled()190                    .focused($hasFocus)191                    .onKeyPress(.escape) {192                        window.dismissOverlay()193                        return .handled194                    }195                    #if os(macOS)196                    .onExitCommand { window.dismissOverlay() }197                    #endif198                    .onAppear { hasFocus = true }199            }200        }201        .lunarAnimation(.snappy, value: window.presentedOverlayID)202    }203204    @ViewBuilder private func content(_ overlay: WindowOverlayContribution) -> some View {205        switch overlay.style {206        case .fullCover:207            overlay.content(window)208                .frame(maxWidth: .infinity, maxHeight: .infinity)209                .background { BackdropView() }210        case .scrim(let alignment, let maxWidth, let maxHeight):211            ZStack(alignment: alignment) {212                Rectangle().fill(LunarRGBA.black.withAlpha(theme.isDark ? 0.5 : 0.28))213                    .ignoresSafeArea()214                    .contentShape(Rectangle())215                    .onTapGesture { if overlay.dismissesOnOutsideTap { window.dismissOverlay() } }216                    .accessibilityHidden(true)217                overlay.content(window)218                    .frame(maxWidth: maxWidth, maxHeight: maxHeight)219                    .padding(.horizontal, LunarSpacing.lg)220                    .padding(.vertical, alignment == .top ? 72 : LunarSpacing.lg)221            }222        }223    }224}225
Files main
Menu

Theme