SPB Git

Repository Public License

Sidebar.swift 17.4 KB 376 lines swift

1import CoreTransferable2import LunarDesign3import NavigatorCore4import OrbitEngine5import SwiftUI6import UniformTypeIdentifiers78extension UTType {9    /// A tab being dragged inside the app. Declared in the apps' Info.plist.10    static let orixTab = UTType(exportedAs: "ai.spboucher.orix.navigator.tab")11}1213struct TabDragItem: Codable, Transferable {14    var id: TabID1516    static var transferRepresentation: some TransferRepresentation {17        CodableRepresentation(contentType: .orixTab)18    }19}2021extension EnvironmentValues {22    /// Width kept free at the leading edge of the first chrome row for the window buttons (Mac).23    @Entry var windowControlsInset: CGFloat = 024}2526/// Context menu shared by every representation of a tab: the commands placed in `.tabContextMenu`, run on the27/// tab that was clicked, plus the list of windows the tab can move to.28struct TabContextMenu: View {29    @Environment(BrowserStore.self) private var store30    let window: WindowModel31    let tab: TabModel3233    var body: some View {34        CommandMenuItems(groups: store.registry.tabContextMenuCommands,35                         context: window.commandContext(tab: tab, source: .contextMenu))36        let others = store.windows.filter { store.canMoveTab(tab.id, to: $0) }37        if !others.isEmpty {38            Divider()39            Menu(L("Move to Window")) {40                ForEach(others) { other in41                    Button(other.selectedTab?.title ?? L("Window")) { store.moveTab(tab.id, to: other) }42                }43            }44        }45    }46}4748/// The floating sidebar: space header, pinned tabs, the vertical tab list, the sections features add and the49/// row of panel shortcuts. A building block for tab layouts (give it a width and a glass surface).50public struct SidebarView: View {51    @Environment(\.lunarTheme) private var theme52    @Environment(\.windowControlsInset) private var controlsInset53    @Environment(BrowserStore.self) private var store54    let window: WindowModel55    @State private var dropTarget: TabID?5657    public init(window: WindowModel) { self.window = window }5859    public var body: some View {60        VStack(alignment: .leading, spacing: LunarSpacing.sm) {61            HStack {62                Spacer()63                LunarIconButton(systemName: "sidebar.left", label: L("Hide sidebar"), isActive: true, diameter: 28) {64                    window.isSidebarCollapsed = true65                }66                .accessibilityIdentifier("sidebar.toggle")67            }68            .frame(height: 28)69            .padding(.leading, controlsInset)7071            spaceHeader7273            sections(.aboveTabs)7475            if !window.pinnedTabs.isEmpty { pinnedRow }7677            HStack {78                Text(L("Tabs")).textCase(.uppercase).lunarFont(.overline).foregroundStyle(theme.textSecondary)79                    .accessibilityAddTraits(.isHeader)80                Spacer()81                Text(verbatim: "\(window.unpinnedTabs.count)").lunarFont(.caption).lunarTabularDigits()82                    .foregroundStyle(theme.accent)83                    .accessibilityLabel(L("%d tabs", window.unpinnedTabs.count))84            }85            .padding(.horizontal, LunarSpacing.xs)86            .padding(.top, LunarSpacing.unit)8788            ScrollView {89                VStack(spacing: 2) {90                    ForEach(window.unpinnedTabs) { tab in91                        tabRow(tab)92                    }93                    Button { window.run(ShellCommandID.newTab, source: .sidebar) } label: {94                        LunarHoverRow {95                            HStack(spacing: LunarSpacing.sm) {96                                LunarIconView(.symbol("plus"), size: 18).foregroundStyle(theme.textSecondary)97                                Text(L("New tab")).lunarFont(.body).foregroundStyle(theme.textPrimary)98                                Spacer()99                                #if os(macOS)100                                LunarShortcut("⌘T")101                                #endif102                            }103                            .padding(.horizontal, LunarSpacing.sm)104                            .frame(minHeight: 40)105                        }106                    }107                    .buttonStyle(LunarPressStyle())108                    .accessibilityIdentifier("sidebar.newTab")109                    .padding(.top, LunarSpacing.unit)110                    .dropDestination(for: TabDragItem.self) { items, _ in111                        guard let item = items.first else { return false }112                        window.moveTab(item.id, before: nil)113                        return true114                    }115                }116            }117            .scrollIndicators(.never)118119            sections(.belowTabs)120121            LunarHairline()122            footer123        }124        .padding([.horizontal, .bottom], LunarSpacing.sm)125        // With window buttons in the header row (Mac), the row sits on their centre line.126        .padding(.top, controlsInset > 0 ? 0 : LunarSpacing.sm)127    }128129    @ViewBuilder private func sections(_ placement: SidebarSectionContribution.Placement) -> some View {130        ForEach(store.registry.sidebarSections.filter { $0.placement == placement && $0.isVisible(window) }) { section in131            section.content(window)132                .accessibilityElement(children: .contain)133                .accessibilityIdentifier("sidebar.section." + section.id)134        }135    }136137    /// The first five items by order; the others in a "More" menu.138    private var footer: some View {139        let context = window.commandContext(source: .sidebar)140        let items = store.registry.sidebarFooterItems.filter { $0.isVisible(context) }141        let shown = items.count > 5 ? Array(items.prefix(4)) : items142        let overflow = items.count > 5 ? Array(items.dropFirst(4)) : []143        return HStack(spacing: 0) {144            ForEach(Array(shown.enumerated()), id: \.element.id) { index, item in145                if index > 0 { Spacer(minLength: 0) }146                SidebarFooterButton(window: window, item: item, context: context)147            }148            if !overflow.isEmpty {149                Spacer(minLength: 0)150                Menu {151                    ForEach(overflow) { item in152                        Button {153                            window.perform(item.action, context: context)154                        } label: {155                            if case .symbol(let name) = item.state(context).icon ?? item.icon {156                                Label(item.label.string, systemImage: name)157                            } else {158                                Text(item.label.string)159                            }160                        }161                        .disabled(!item.state(context).isEnabled || !window.isEnabled(item.action, context: context))162                    }163                } label: {164                    LunarIconView(.symbol("ellipsis"), size: LunarMetrics.controlHeight * 0.5)165                        .foregroundStyle(theme.textSecondary.mixed(with: theme.textPrimary, 0.5))166                        .frame(width: LunarMetrics.controlHeight, height: LunarMetrics.controlHeight)167                        .contentShape(Circle())168                }169                .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()170                .accessibilityLabel(L("More"))171                .accessibilityIdentifier("sidebar.more")172                .help(L("More"))173            }174        }175        .padding(.horizontal, LunarSpacing.md)176    }177178    private var spaceHeader: some View {179        HStack(spacing: LunarSpacing.sm) {180            LunarPlanet(tint: LunarTint(rawValue: window.space.tint.rawValue) ?? .spectralViolet, size: 26, isActive: true,181                        hasRing: true)182                .frame(width: 36, height: 36)183            VStack(alignment: .leading, spacing: 1) {184                Text(window.space.name == "Home" ? L("Home") : window.space.name)185                    .lunarFont(.headline).foregroundStyle(theme.textPrimary).lineLimit(1)186                Text(window.tabs.count == 1 ? L("1 page") : L("%d pages", window.tabs.count))187                    .lunarFont(.caption).lunarTabularDigits().foregroundStyle(theme.textSecondary)188            }189            Spacer(minLength: 0)190            WindowBadgesView(window: window, isCompact: true)191        }192        .padding(LunarSpacing.xs)193        .background { LunarShape.sm.fill(theme.textPrimary.withAlpha(0.05)) }194        .lunarHairline(.sm)195        .accessibilityElement(children: .combine)196        .accessibilityLabel(([L("Space %@", window.space.name)] + store.registry.badges(for: window).map(\.label)).joined(separator: ", "))197    }198199    private var pinnedRow: some View {200        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: LunarSpacing.xs), count: 4), spacing: LunarSpacing.xs) {201            ForEach(window.pinnedTabs) { tab in202                Button { window.select(tab.id) } label: {203                    FaviconView(tab: tab, size: 24)204                        .frame(maxWidth: .infinity, minHeight: 44)205                        .background {206                            LunarShape.xs.fill(tab.id == window.selectedTabID ? theme.selection : theme.textPrimary.withAlpha(0.05))207                        }208                        .lunarHairline(.xs)209                        .contentShape(LunarShape.xs)210                }211                .buttonStyle(LunarPressStyle())212                .help(tab.title)213                .accessibilityLabel(tab.title)214                .accessibilityValue(L("Pinned"))215                .accessibilityAddTraits(tab.id == window.selectedTabID ? .isSelected : [])216                .contextMenu { TabContextMenu(window: window, tab: tab) }217                .draggable(TabDragItem(id: tab.id))218                .dropDestination(for: TabDragItem.self) { items, _ in219                    guard let item = items.first else { return false }220                    window.moveTab(item.id, before: tab.id)221                    return true222                }223            }224        }225    }226227    private func tabRow(_ tab: TabModel) -> some View {228        LunarTabChip(title: tab.title, favicon: tab.faviconImage(in: store, window: window), tint: FaviconView.tint(for: tab.title),229                     isSelected: tab.id == window.selectedTabID, isPinned: false, isLoading: tab.engine.isLoading,230                     audio: tab.audioState, layout: .vertical,231                     onSelect: { window.select(tab.id) }, onClose: { window.close(tab.id) },232                     onToggleMute: { window.toggleMute(tab.id) })233            .accessibilityIdentifier("tab." + tab.id.string)234            .contextMenu { TabContextMenu(window: window, tab: tab) }235            .overlay(alignment: .top) {236                if dropTarget == tab.id {237                    Capsule().fill(theme.accent).frame(height: 2).padding(.horizontal, LunarSpacing.xs).offset(y: -2)238                }239            }240            .draggable(TabDragItem(id: tab.id))241            .dropDestination(for: TabDragItem.self) { items, _ in242                guard let item = items.first else { return false }243                window.moveTab(item.id, before: tab.id)244                return true245            } isTargeted: { targeted in246                if targeted { dropTarget = tab.id } else if dropTarget == tab.id { dropTarget = nil }247            }248    }249}250251/// Horizontal tab strip (top of the window). A building block for tab layouts.252public struct TabStripView: View {253    @Environment(\.lunarTheme) private var theme254    @Environment(BrowserStore.self) private var store255    let window: WindowModel256    /// Compact layout: only the selected tab shows its title.257    var isCondensed = false258259    /// `isCondensed`: tabs are icons, only the selected one shows its title.260    public init(window: WindowModel, isCondensed: Bool = false) {261        self.window = window262        self.isCondensed = isCondensed263    }264265    public var body: some View {266        if isCondensed {267            ScrollViewReader { proxy in268                ScrollView(.horizontal) {269                    HStack(spacing: LunarSpacing.unit) {270                        ForEach(window.tabs) { tab in chip(tab, width: nil).id(tab.id) }271                    }272                    .padding(.vertical, 2)273                }274                .scrollIndicators(.never)275                .onChange(of: window.selectedTabID) { _, selected in276                    if let selected { withAnimation(LunarMotion.snappy.animation) { proxy.scrollTo(selected) } }277                }278            }279        } else {280            // OrbitEngine decides what fits: equal widths between a minimum and a maximum, the rest in a menu,281            // the selected tab always visible.282            GeometryReader { proxy in283                let metrics = TabStripMetrics(pinnedWidth: Double(LunarMetrics.tabChipHeight), minimumTabWidth: 96,284                                              maximumTabWidth: 220, spacing: Double(LunarSpacing.unit), overflowButtonWidth: 40)285                let layout = TabLayout.strip(order: window.tabs.map(\.id), pinned: Set(window.pinnedTabs.map(\.id)),286                                             selected: window.selectedTabID, width: Double(proxy.size.width), metrics: metrics)287                let visible = Set(layout.visible)288                HStack(spacing: LunarSpacing.unit) {289                    ForEach(window.tabs.filter { visible.contains($0.id) }) { tab in290                        chip(tab, width: tab.isPinned ? nil : CGFloat(layout.tabWidth))291                    }292                    if layout.hasOverflow {293                        Menu {294                            ForEach(window.tabs.filter { layout.overflow.contains($0.id) }) { tab in295                                Button(tab.title) { window.select(tab.id) }296                            }297                        } label: {298                            LunarIconView(.symbol("chevron.down"), size: 14).foregroundStyle(theme.textSecondary)299                                .frame(width: 32, height: 32)300                                .background { Circle().fill(theme.textPrimary.withAlpha(0.06)) }301                        }302                        .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()303                        .accessibilityLabel(L("%d more tabs", layout.overflow.count))304                        .accessibilityIdentifier("strip.overflow")305                    }306                    Spacer(minLength: 0)307                }308                .frame(height: proxy.size.height)309            }310        }311    }312313    @ViewBuilder private func chip(_ tab: TabModel, width: CGFloat?) -> some View {314        let selected = tab.id == window.selectedTabID315        Group {316            if tab.isPinned || (isCondensed && !selected) {317                Button { window.select(tab.id) } label: {318                    FaviconView(tab: tab, size: 18)319                        .frame(width: LunarMetrics.tabChipHeight, height: LunarMetrics.tabChipHeight)320                        .background { Capsule().fill(selected ? theme.selection : theme.textPrimary.withAlpha(0.05)) }321                        .contentShape(Capsule())322                }323                .buttonStyle(LunarPressStyle())324                .help(tab.title)325                .accessibilityLabel(tab.title)326                .accessibilityValue(tab.isPinned ? L("Pinned") : "")327                .accessibilityAddTraits(selected ? .isSelected : [])328            } else {329                LunarTabChip(title: tab.title, favicon: tab.faviconImage(in: store, window: window), tint: FaviconView.tint(for: tab.title),330                             isSelected: selected, isPinned: false, isLoading: tab.engine.isLoading,331                             audio: tab.audioState, layout: .horizontal,332                             onSelect: { window.select(tab.id) }, onClose: { window.close(tab.id) },333                             onToggleMute: { window.toggleMute(tab.id) })334                    .frame(width: width)335                    .frame(minWidth: width == nil ? 110 : nil, maxWidth: width == nil ? 220 : nil)336            }337        }338        .accessibilityIdentifier("tab." + tab.id.string)339        .contextMenu { TabContextMenu(window: window, tab: tab) }340        .draggable(TabDragItem(id: tab.id))341        .dropDestination(for: TabDragItem.self) { items, _ in342            guard let item = items.first else { return false }343            window.moveTab(item.id, before: tab.id)344            return true345        }346    }347}348349/// One icon of the sidebar's bottom row.350private struct SidebarFooterButton: View {351    @Environment(\.lunarTheme) private var theme352    @Environment(BrowserStore.self) private var store353    let window: WindowModel354    let item: SidebarFooterItem355    let context: CommandContext356    @State private var showsPopover = false357358    var body: some View {359        let state = item.state(context)360        LunarIconButton(state.icon ?? item.icon, label: item.label.string, isActive: state.isActive) {361            if case .popover = item.action { showsPopover = true } else { window.perform(item.action, context: context) }362        }363        .overlay(alignment: .topTrailing) {364            if let badge = state.badge, badge > 0 { CountBadge(count: badge).offset(x: 3, y: -2) }365        }366        .disabled(!state.isEnabled || !window.isEnabled(item.action, context: context))367        .accessibilityValue(state.accessibilityValue ?? "")368        .accessibilityIdentifier("sidebar." + item.id)369        .popover(isPresented: $showsPopover) {370            if case .popover(let content) = item.action {371                content(window).environment(store).lunarTheme(theme).presentationCompactAdaptation(.popover)372            }373        }374    }375}376
Files main
Menu

Theme