SPB Git

Repository Public License

PhoneBrowserView.swift 21.4 KB 451 lines swift

1import LunarDesign2import NavigatorCore3import SwiftUI4import WebRuntime56/// Compact width (iPhone, narrow iPad windows): the page edge to edge, a floating glass dock within reach of7/// the thumb, a full-screen search cover and a tab switcher.8struct PhoneBrowserView: View {9    @Environment(\.lunarTheme) private var theme10    @Environment(BrowserStore.self) private var store11    let window: WindowModel12    @State private var isDockCompact = false13    @State private var scrollAnchor = 0.01415    /// Height the page keeps clear under the expanded dock. Constant: the page never reflows when the dock16    /// compacts or expands, so content does not jump.17    static let dockClearance: CGFloat = 13218    static let topBarClearance: CGFloat = 601920    @Environment(\.verticalSizeClass) private var verticalSizeClass21    private var atTop: Bool { store.settings.omniboxAtTop }22    private var bottomClearance: CGFloat { verticalSizeClass == .compact || atTop ? 76 : Self.dockClearance }23    /// A full-screen cover (search, tab switcher) is in front of the page and the dock.24    private var isCovered: Bool { window.omnibox.isEditing || window.isTabSwitcherVisible }2526    var body: some View {27        let engine = window.selectedTab?.engine28        ZStack {29            Rectangle().fill(pageBackground).ignoresSafeArea()30            WebAreaView(window: window, shape: .rounded(0), isFramed: false,31                        webOptions: WebEngineViewOptions(32                            obscuredInsets: EdgeInsets(top: atTop ? Self.topBarClearance : 0, leading: 0,33                                                       bottom: bottomClearance, trailing: 0)),34                        bottomChromeInset: bottomClearance)35                .ignoresSafeArea(.container, edges: .bottom)36                .accessibilityHidden(isCovered)37            VStack(spacing: 0) {38                if atTop, !window.hiddenChrome.contains(.toolbar) {39                    PhoneAddressPill(window: window)40                        .padding(LunarSpacing.unit)41                        .lunarGlass(.capsule, style: .chrome, elevation: .floating)42                        .padding(.horizontal, LunarSpacing.sm)43                        .padding(.top, LunarSpacing.unit)44                }45                Spacer(minLength: 0)46                if !window.hiddenChrome.contains(.toolbar) {47                    PhoneDock(window: window, isCompact: isDockCompact && !atTop, showsAddress: !atTop) {48                        isDockCompact = false49                    }50                    .padding(.horizontal, LunarSpacing.sm)51                    .padding(.bottom, LunarSpacing.unit)52                }53            }54            .accessibilityHidden(isCovered)55            if window.omnibox.isEditing {56                PhoneSearchCover(window: window, fieldAtBottom: !atTop)57                    .transition(.opacity)58                    .zIndex(2)59            }60            if window.isTabSwitcherVisible {61                PhoneTabSwitcher(window: window)62                    .transition(.opacity.combined(with: .scale(scale: 1.04)))63                    .zIndex(3)64            }65        }66        .lunarAnimation(.smooth, value: isDockCompact)67        .lunarAnimation(.snappy, value: window.omnibox.isEditing)68        .lunarAnimation(.smooth, value: window.isTabSwitcherVisible)69        .onChange(of: engine?.scroll.y) { _, offset in70            guard let offset, let engine else { return }71            // Hysteresis on the distance travelled since the last change of state, so that small movements and72            // the rubber band at the edges do not make the dock flicker.73            if engine.scroll.isAtTop || offset >= engine.scroll.maxY - 1 {74                if engine.scroll.isAtTop { isDockCompact = false }75                scrollAnchor = offset76            } else if isDockCompact {77                if offset > scrollAnchor { scrollAnchor = offset } else if scrollAnchor - offset > 28 { isDockCompact = false; scrollAnchor = offset }78            } else {79                if offset < scrollAnchor { scrollAnchor = offset } else if offset - scrollAnchor > 28, offset > 60 { isDockCompact = true; scrollAnchor = offset }80            }81        }82        .onChange(of: window.selectedTabID) { isDockCompact = false; scrollAnchor = 0 }83        .lunarAnimation(.smooth, value: window.hiddenChrome)84        .sheet(item: Binding(get: { window.panel.flatMap { store.registry.panel($0) != nil ? $0 : nil } },85                             set: { window.panel = $0 })) { id in86            if let panel = store.registry.panel(id) {87                PanelContainer(window: window, panel: panel)88                    .background(theme.windowGradient)89                    .presentationDetents([.large])90                    .presentationDragIndicator(.visible)91                    .environment(store)92                    .lunarTheme(theme)93            }94        }95        // A toolbar item of the dock menu whose content is a popover on wider layouts.96        .sheet(item: Binding(get: { window.toolbarSheetItemID.flatMap { store.registry.toolbarItem($0) } },97                             set: { window.toolbarSheetItemID = $0?.id })) { item in98            if case .popover(let content) = item.action {99                content(window)100                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)101                    .background(theme.windowGradient)102                    .presentationDetents([.medium, .large])103                    .presentationDragIndicator(.visible)104                    .environment(store)105                    .lunarTheme(theme)106            }107        }108    }109110    private var pageBackground: LunarRGBA {111        theme.isDark ? theme.windowBackground.mixed(with: theme.textPrimary, 0.045) : .white112    }113}114115/// Lock, host and reload: the resting state of the address field on a phone. Tapping it opens the search cover.116struct PhoneAddressPill: View {117    @Environment(\.lunarTheme) private var theme118    @Environment(BrowserStore.self) private var store119    let window: WindowModel120121    var body: some View {122        let tab = window.selectedTab123        let engine = tab?.engine124        HStack(spacing: LunarSpacing.unit) {125            WindowBadgesView(window: window, isCompact: true)126            SecurityIndicator(engine: engine)127            Button { window.omnibox.focus() } label: {128                Text(engine?.url.flatMap { InternalAddress.isInternal($0) ? nil : URLDisplay.host($0) } ?? L("Search or enter an address"))129                    .lunarFont(.body)130                    .foregroundStyle(engine?.url == nil ? theme.textTertiary : theme.textPrimary)131                    .lineLimit(1)132                    .frame(maxWidth: .infinity, alignment: .leading)133                    .frame(minHeight: LunarMetrics.touchTarget)134                    .contentShape(Rectangle())135            }136            .buttonStyle(.plain)137            .accessibilityLabel(L("Address"))138            .accessibilityValue(engine?.url.map(URLDisplay.host) ?? "")139            .accessibilityHint(L("Opens search"))140            .accessibilityIdentifier("phone.address")141            if let tab, !tab.pendingPopups.isEmpty { PopupIndicator(window: window, tab: tab) }142            ForEach(store.registry.toolbarItems(in: .addressField)) { item in143                ContributedToolbarButton(window: window, item: item, diameter: 36, isCompactWidth: true)144            }145            if let tab, !tab.isBlank {146                LunarIconButton(systemName: window.isLoading ? "xmark" : "arrow.clockwise",147                                label: window.isLoading ? L("Stop loading") : L("Reload"), diameter: 36) {148                    LunarHaptics.play(.lightImpact)149                    window.reloadOrStop()150                }151                .accessibilityIdentifier("phone.reload")152            }153        }154        .padding(.leading, LunarSpacing.xs)155        .padding(.trailing, LunarSpacing.unit)156        .lunarGlass(.capsule, style: .control, elevation: .flat)157        .overlay(alignment: .bottom) {158            if let engine, engine.isLoading {159                LunarProgressBar(value: max(0.05, engine.estimatedProgress), label: L("Page loading"), height: 2)160                    .padding(.horizontal, LunarSpacing.lg)161            }162        }163    }164}165166struct PhoneDock: View {167    @Environment(\.lunarTheme) private var theme168    @Environment(BrowserStore.self) private var store169    let window: WindowModel170    let isCompact: Bool171    var showsAddress = true172    let expand: () -> Void173    @Environment(\.verticalSizeClass) private var verticalSizeClass174    /// Landscape phone: one row, so that the dock takes as little of the short screen as possible.175    private var isLandscape: Bool { verticalSizeClass == .compact }176177    var body: some View {178        if isCompact {179            Button(action: expand) {180                HStack(spacing: LunarSpacing.unit + 2) {181                    let state = SecurityState(engine: window.selectedTab?.engine)182                    LunarIconView(.symbol(state.symbol), size: 13).foregroundStyle(theme.textSecondary)183                    Text(window.selectedTab?.engine.url.map(URLDisplay.host) ?? L("New Tab"))184                        .lunarFont(.subheadline).foregroundStyle(theme.textPrimary).lineLimit(1)185                }186                .padding(.horizontal, LunarSpacing.md)187                .frame(minHeight: 36)188                .frame(maxWidth: 260)189                .lunarGlass(.capsule, style: .chrome, elevation: .floating, interactive: true)190                .lunarHitTarget(.capsule)191            }192            .buttonStyle(LunarPressStyle())193            .accessibilityLabel(L("Show toolbar"))194            .accessibilityValue(window.selectedTab?.engine.url.map(URLDisplay.host) ?? "")195            .accessibilityIdentifier("phone.dock.compact")196            .transition(.scale(scale: 0.9, anchor: .bottom).combined(with: .opacity))197        } else {198            let layout = isLandscape ? AnyLayout(HStackLayout(spacing: LunarSpacing.xs)) : AnyLayout(VStackLayout(spacing: LunarSpacing.unit))199            layout {200                if showsAddress { PhoneAddressPill(window: window).layoutPriority(1) }201                HStack(spacing: isLandscape ? LunarSpacing.unit : 0) {202                    LunarIconButton(systemName: "chevron.left", label: L("Back"), diameter: 44) {203                        LunarHaptics.play(.selection); window.goBack()204                    }205                    .disabled(!window.canGoBack)206                    .accessibilityIdentifier("phone.back")207                    if !isLandscape { Spacer(minLength: 0) }208                    LunarIconButton(systemName: "chevron.right", label: L("Forward"), diameter: 44) {209                        LunarHaptics.play(.selection); window.goForward()210                    }211                    .disabled(!window.canGoForward)212                    .accessibilityIdentifier("phone.forward")213                    if !isLandscape { Spacer(minLength: 0) }214                    Button {215                        LunarHaptics.play(.selection)216                        Task {217                            if let tab = window.selectedTab { await store.refreshThumbnail(of: tab) }218                            window.isTabSwitcherVisible = true219                        }220                    } label: {221                        LunarIconView(.symbol("square.on.square"), size: 24)222                            .foregroundStyle(theme.textSecondary.mixed(with: theme.textPrimary, 0.5))223                            .frame(width: 44, height: 44)224                            .overlay(alignment: .topTrailing) {225                                Text(verbatim: "\(min(window.tabs.count, 99))").lunarFont(.overline).lunarTabularDigits()226                                    .foregroundStyle(theme.accent)227                                    .padding(.horizontal, 5).frame(minWidth: 18, minHeight: 18)228                                    .background { Capsule().fill(theme.elevatedSurface) }229                                    .overlay { Capsule().strokeBorder(theme.hairlineStrong, lineWidth: 1) }230                                    .offset(x: 4, y: -1)231                                    .accessibilityHidden(true)232                            }233                            .contentShape(Circle())234                    }235                    .buttonStyle(LunarPressStyle())236                    .accessibilityLabel(L("Tabs"))237                    .accessibilityValue(L("%d tabs", window.tabs.count))238                    .accessibilityIdentifier("phone.tabs")239                    if !isLandscape { Spacer(minLength: 0) }240                    LunarIconButton(systemName: "plus", label: L("New tab"), style: .glass, diameter: 44) {241                        LunarHaptics.play(.lightImpact)242                        window.newTab()243                        window.omnibox.focus()244                    }245                    .accessibilityIdentifier("phone.newTab")246                    if !isLandscape { Spacer(minLength: 0) }247                    ToolbarMenuButton(window: window, diameter: 44, isCompactWidth: true)248                        .accessibilityIdentifier("phone.menu")249                }250                .padding(.horizontal, LunarSpacing.xs)251            }252            .padding(LunarSpacing.xs)253            .lunarGlass(.lg, style: .chrome, elevation: .floating)254            .accessibilityElement(children: .contain)255            .accessibilityIdentifier("phone.dock")256            .transition(.scale(scale: 0.96, anchor: .bottom).combined(with: .opacity))257        }258    }259}260261/// Full-screen search: the field, the keyboard and local suggestions.262struct PhoneSearchCover: View {263    @Environment(\.lunarTheme) private var theme264    let window: WindowModel265    let fieldAtBottom: Bool266267    var body: some View {268        let omnibox = window.omnibox269        ZStack {270            Rectangle().fill(theme.windowGradient).ignoresSafeArea()271            VStack(spacing: LunarSpacing.xs) {272                if !fieldAtBottom { fieldRow(omnibox) }273                ScrollView {274                    VStack(spacing: 0) {275                        if fieldAtBottom { Spacer(minLength: 0) }276                        SuggestionList(omnibox: omnibox, rowHeight: 52)277                    }278                    .frame(maxWidth: .infinity)279                    .padding(.horizontal, LunarSpacing.xs)280                }281                .defaultScrollAnchor(fieldAtBottom ? .bottom : .top)282                .scrollDismissesKeyboard(.never)283                .scrollIndicators(.never)284                if fieldAtBottom { fieldRow(omnibox) }285            }286            .padding(.vertical, LunarSpacing.xs)287        }288        .accessibilityElement(children: .contain)289        .accessibilityIdentifier("phone.searchCover")290    }291292    private func fieldRow(_ omnibox: OmniboxModel) -> some View {293        HStack(spacing: LunarSpacing.xs) {294            HStack(spacing: LunarSpacing.xs) {295                LunarIconView(.symbol("magnifyingglass"), size: 16).foregroundStyle(theme.accent)296                OmniboxTextField(297                    text: Binding(get: { omnibox.text }, set: { omnibox.setText($0) }),298                    displayText: omnibox.text, prompt: L("Search or enter an address"), isEditing: true,299                    focusRequest: omnibox.focusRequest, textColor: theme.textPrimary.color,300                    promptColor: theme.textTertiary.color, tintColor: theme.accent.color, identifier: "omnibox.field",301                    onBeginEditing: {}, onEndEditing: {}, onSubmit: { omnibox.submit() },302                    onMove: { omnibox.moveHighlight(by: $0) }, onCancel: { omnibox.cancel() })303                    .frame(minHeight: LunarMetrics.touchTarget)304            }305            .padding(.horizontal, LunarSpacing.sm)306            .lunarGlass(.capsule, style: .control, elevation: .raised)307            .lunarFocusRing(.capsule, isFocused: true)308            Button(L("Cancel")) { omnibox.cancel() }309                .buttonStyle(.lunar(.secondary))310                .accessibilityIdentifier("phone.search.cancel")311        }312        .padding(.horizontal, LunarSpacing.sm)313        .onAppear { omnibox.requestFocusAgain() }314    }315}316317/// Grid of open tabs with their thumbnails. Swipe a card sideways to close it.318struct PhoneTabSwitcher: View {319    @Environment(\.lunarTheme) private var theme320    @Environment(BrowserStore.self) private var store321    let window: WindowModel322323    var body: some View {324        ZStack {325            BackdropView(density: 0.9)326            VStack(spacing: 0) {327                HStack {328                    Text(window.tabs.count == 1 ? L("1 Tab") : L("%d Tabs", window.tabs.count))329                        .lunarFont(.title2).lunarTabularDigits().foregroundStyle(theme.textPrimary)330                        .accessibilityAddTraits(.isHeader)331                        .accessibilityIdentifier("switcher.title")332                    Spacer()333                    Button(L("Done")) { window.isTabSwitcherVisible = false }334                        .buttonStyle(.lunar(.secondary))335                        .accessibilityIdentifier("switcher.done")336                }337                .padding(.horizontal, LunarSpacing.md)338                .padding(.vertical, LunarSpacing.xs)339                ScrollView {340                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 150, maximum: 240), spacing: LunarSpacing.sm)], spacing: LunarSpacing.sm) {341                        ForEach(window.tabs) { tab in342                            TabCard(window: window, tab: tab)343                        }344                    }345                    .padding(.horizontal, LunarSpacing.md)346                    .padding(.bottom, 96)347                }348                .scrollIndicators(.never)349            }350            VStack {351                Spacer()352                LunarIconButton(systemName: "plus", label: L("New tab"), style: .accent, diameter: 56) {353                    LunarHaptics.play(.lightImpact)354                    window.newTab()355                    window.isTabSwitcherVisible = false356                }357                .lunarShadow(.floating)358                .accessibilityIdentifier("switcher.newTab")359                .padding(.bottom, LunarSpacing.md)360            }361        }362        .accessibilityElement(children: .contain)363        .accessibilityIdentifier("switcher")364    }365}366367private struct TabCard: View {368    @Environment(\.lunarTheme) private var theme369    let window: WindowModel370    let tab: TabModel371    @State private var offset: CGFloat = 0372373    var body: some View {374        let selected = tab.id == window.selectedTabID375        VStack(spacing: 0) {376            HStack(spacing: LunarSpacing.unit + 2) {377                // The card below carries the title for assistive technologies.378                FaviconView(tab: tab, size: 16).accessibilityHidden(true)379                Text(tab.title).lunarFont(.caption).foregroundStyle(theme.textPrimary).lineLimit(1).accessibilityHidden(true)380                Spacer(minLength: 0)381                Button { close() } label: {382                    LunarIconView(.symbol("xmark"), size: 12).foregroundStyle(theme.textSecondary)383                        .frame(width: 26, height: 26)384                        .background { Circle().fill(theme.textPrimary.withAlpha(0.08)) }385                        .lunarHitTarget(.circle)386                }387                .buttonStyle(LunarPressStyle())388                .accessibilityLabel(L("Close %@", tab.title))389                .accessibilityIdentifier("switcher.close")390            }391            .padding(.leading, LunarSpacing.xs)392            .frame(height: LunarMetrics.touchTarget)393            Button { select() } label: {394                thumbnail395                    .frame(maxWidth: .infinity)396                    .frame(height: 190)397                    .clipped()398                    .contentShape(Rectangle())399            }400            .buttonStyle(.plain)401            .accessibilityLabel(tab.title)402            .accessibilityHint(L("Shows this tab"))403            .accessibilityAddTraits(selected ? .isSelected : [])404            .accessibilityIdentifier("switcher.card")405        }406        .background(theme.elevatedSurface)407        .clipShape(LunarShape.sm)408        .overlay { LunarShape.sm.strokeBorder(selected ? theme.accent : theme.hairlineStrong, lineWidth: selected ? 2 : 1) }409        .lunarShadow(.raised)410        .offset(x: offset)411        .opacity(1 - min(0.6, abs(offset) / 300))412        .gesture(DragGesture(minimumDistance: 18).onChanged { value in413            if abs(value.translation.width) > abs(value.translation.height) { offset = value.translation.width }414        }.onEnded { value in415            if abs(value.translation.width) > 110 { close() } else { withAnimation(LunarMotion.snappy.animation) { offset = 0 } }416        })417        .accessibilityAction(named: L("Close tab")) { close() }418    }419420    @ViewBuilder private var thumbnail: some View {421        if let image = tab.thumbnail ?? tab.engine.suspendedPage?.thumbnailPNG.flatMap(PlatformImage.init(data:)) {422            Color.clear.overlay(alignment: .top) {423                Image(platformImage: image).resizable().scaledToFill()424            }425        } else {426            ZStack {427                Rectangle().fill(theme.windowGradient)428                Group {429                    if tab.isBlank {430                        LunarMarkView(size: 54, showsGlow: false)431                    } else {432                        FaviconView(tab: tab, size: 40)433                    }434                }435                .accessibilityHidden(true)436            }437        }438    }439440    private func select() {441        LunarHaptics.play(.selection)442        window.select(tab.id)443        window.isTabSwitcherVisible = false444    }445446    private func close() {447        LunarHaptics.play(.mediumImpact)448        withAnimation(LunarMotion.snappy.animation) { window.close(tab.id) }449    }450}451
Files main
Menu

Theme