SPB Git

Repository Public License

SettingsPanel.swift 19.9 KB 460 lines swift

1import LunarDesign2import NavigatorCore3import SwiftUI45/// A miniature of a theme, drawn from its own roles.6struct ThemeSwatch: View {7    @Environment(\.lunarTheme) private var current8    let family: LunarThemeFamily9    let variant: LunarThemeVariant10    let isSelected: Bool11    let action: () -> Void1213    var body: some View {14        let theme = family.theme(variant)15        Button(action: action) {16            VStack(alignment: .leading, spacing: LunarSpacing.unit + 2) {17                ZStack(alignment: .topLeading) {18                    RoundedRectangle(cornerRadius: 10, style: .continuous).fill(theme.windowGradient)19                    HStack(spacing: 4) {20                        RoundedRectangle(cornerRadius: 4, style: .continuous).fill(theme.chromeSurface)21                            .frame(width: 18)22                            .overlay(alignment: .top) { Circle().fill(theme.accentSecondary).frame(width: 6, height: 6).padding(.top, 5) }23                        VStack(spacing: 4) {24                            Capsule().fill(theme.elevatedSurface).frame(height: 8)25                                .overlay(alignment: .leading) { Circle().fill(theme.accent).frame(width: 5, height: 5).padding(.leading, 3) }26                            RoundedRectangle(cornerRadius: 4, style: .continuous)27                                .fill(theme.isDark ? theme.windowBackground.mixed(with: theme.textPrimary, 0.08) : .white)28                        }29                    }30                    .padding(5)31                }32                .frame(height: 54)33                .overlay(alignment: .bottomTrailing) {34                    if isSelected {35                        LunarIconView(.symbol("checkmark.circle.fill"), size: 16).foregroundStyle(theme.accent)36                            .background { Circle().fill(theme.windowBackground).padding(2) }37                            .padding(4)38                    }39                }40                .overlay {41                    RoundedRectangle(cornerRadius: 10, style: .continuous)42                        .strokeBorder(isSelected ? current.accent : current.hairline, lineWidth: isSelected ? 2 : 1)43                }44                Text(family.name).lunarFont(.caption).foregroundStyle(isSelected ? current.textPrimary : current.textSecondary)45                    .lineLimit(1).minimumScaleFactor(0.8)46            }47            .contentShape(Rectangle())48        }49        .buttonStyle(LunarPressStyle())50        .accessibilityLabel(L("Theme %@", family.name))51        .accessibilityHint(family.summary)52        .accessibilityAddTraits(isSelected ? .isSelected : [])53        .accessibilityIdentifier("theme." + family.id)54    }55}5657struct ThemeGrid: View {58    @Environment(\.lunarTheme) private var theme59    @Bindable var settings: AppSettings60    var minimumWidth: CGFloat = 926162    var body: some View {63        LazyVGrid(columns: [GridItem(.adaptive(minimum: minimumWidth), spacing: LunarSpacing.sm)], spacing: LunarSpacing.sm) {64            ForEach(LunarThemes.all) { family in65                ThemeSwatch(family: family, variant: theme.variant, isSelected: settings.themeID == family.id) {66                    settings.themeID = family.id67                }68            }69        }70    }71}7273struct AppearancePicker: View {74    @Environment(\.horizontalSizeClass) private var sizeClass75    @Bindable var settings: AppSettings7677    var body: some View {78        // Icons are dropped where three labelled segments would not fit (phone width, narrow panels).79        let icons = Self.showsIcons(sizeClass)80        LunarSegmentedControl(L("Appearance"), selection: $settings.appearance, segments: [81            LunarSegment(L("System"), value: .system, icon: icons ? .symbol("circle.lefthalf.filled") : nil),82            LunarSegment(L("Light"), value: .light, icon: icons ? .symbol("sun.max") : nil),83            LunarSegment(L("Dark"), value: .dark, icon: icons ? .symbol("moon") : nil),84        ])85        .accessibilityIdentifier("settings.appearance")86    }87}8889extension AppearancePicker {90    static func showsIcons(_ sizeClass: UserInterfaceSizeClass?) -> Bool {91        #if os(iOS)92        sizeClass == .regular93        #else94        true95        #endif96    }97}9899struct SearchEngineList: View {100    @Environment(\.lunarTheme) private var theme101    @Bindable var settings: AppSettings102    var engines: [SearchEngine]103104    var body: some View {105        VStack(spacing: 2) {106            ForEach(engines) { engine in107                let selected = settings.searchEngineID == engine.id108                HStack(spacing: 0) {109                    Button { settings.searchEngineID = engine.id } label: {110                        LunarHoverRow(isSelected: selected) {111                            HStack(spacing: LunarSpacing.sm) {112                                LunarIconView(.symbol(selected ? "largecircle.fill.circle" : "circle"), size: 18)113                                    .foregroundStyle(selected ? theme.accent : theme.textTertiary)114                                VStack(alignment: .leading, spacing: 1) {115                                    Text(engine.name).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary)116                                    if !engine.isBuiltIn {117                                        Text(engine.template).lunarFont(.caption).foregroundStyle(theme.textSecondary)118                                            .lineLimit(1).truncationMode(.middle)119                                    }120                                }121                                Spacer(minLength: 0)122                            }123                            .padding(.horizontal, LunarSpacing.sm)124                            .frame(minHeight: LunarMetrics.hitTarget > 40 ? LunarMetrics.hitTarget : 40)125                        }126                    }127                    .buttonStyle(LunarPressStyle())128                    .accessibilityElement(children: .combine)129                    .accessibilityAddTraits(selected ? .isSelected : [])130                    .accessibilityIdentifier("engine." + engine.id)131                    if !engine.isBuiltIn {132                        LunarIconButton(systemName: "trash", label: L("Remove %@", engine.name), diameter: 28) {133                            settings.removeCustomSearchEngine(id: engine.id)134                        }135                    }136                }137            }138        }139    }140}141142/// Identifiers of the shell's settings sections (`-ORIXSettingsSection`, `window.settingsSectionRequest`).143public enum ShellSettingsSectionID {144    public static let appearance = "appearance"145    public static let search = "search"146    public static let tabs = "tabs"147    public static let newTab = "newtab"148    public static let oneHanded = "onehanded"149    public static let downloads = "downloads"150    public static let privacy = "privacy"151    public static let about = "about"152}153154/// The Settings panel: the registered sections, in order — the shell's, then the features', then About.155struct SettingsPanel: View {156    @Environment(\.lunarTheme) private var theme157    @Environment(BrowserStore.self) private var store158    let window: WindowModel159160    var body: some View {161        ScrollViewReader { proxy in162            ScrollView {163                VStack(alignment: .leading, spacing: LunarSpacing.md) {164                    ForEach(store.registry.settingsSections.filter { $0.isVisible(window) }) { section in165                        VStack(alignment: .leading, spacing: LunarSpacing.xs) {166                            HStack(spacing: LunarSpacing.unit + 2) {167                                LunarIconView(section.icon, size: 13).foregroundStyle(theme.textTertiary).accessibilityHidden(true)168                                Text(section.title.string).textCase(.uppercase).lunarFont(.overline).foregroundStyle(theme.textSecondary)169                                    .accessibilityAddTraits(.isHeader)170                            }171                            .padding(.horizontal, LunarSpacing.xs)172                            LunarCard(padding: LunarSpacing.sm, shape: .sm, elevation: .flat) {173                                VStack(alignment: .leading, spacing: LunarSpacing.sm) { section.content(window) }174                                    .frame(maxWidth: .infinity, alignment: .leading)175                            }176                        }177                        .id(section.id)178                        .accessibilityElement(children: .contain)179                        .accessibilityIdentifier("settings.section." + section.id)180                    }181                }182                .padding(LunarSpacing.sm)183            }184            .scrollIndicators(.never)185            .task(id: window.settingsSectionRequest) {186                guard let target = window.settingsSectionRequest else { return }187                // The sections must be laid out before one of them can be scrolled to.188                try? await Task.sleep(for: .milliseconds(120))189                withAnimation(LunarMotion.smooth.animation) { proxy.scrollTo(target, anchor: .top) }190                window.settingsSectionRequest = nil191            }192        }193    }194}195196/// A switch row of a settings section.197struct SettingsToggle: View {198    @Environment(\.lunarTheme) private var theme199    let title: String200    @Binding var isOn: Bool201    let id: String202203    init(_ title: String, isOn: Binding<Bool>, id: String) { self.title = title; self._isOn = isOn; self.id = id }204205    var body: some View {206        Toggle(title, isOn: $isOn).toggleStyle(.lunar).lunarFont(.body).foregroundStyle(theme.textPrimary)207            .accessibilityIdentifier(id)208    }209}210211/// Explanatory text under a setting.212struct SettingsFootnote: View {213    @Environment(\.lunarTheme) private var theme214    let text: String215216    init(_ text: String) { self.text = text }217218    var body: some View {219        Text(text).lunarFont(.footnote).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)220    }221}222223struct AppearanceSettingsSection: View {224    @Environment(BrowserStore.self) private var store225226    var body: some View {227        AppearancePicker(settings: store.settings)228        ThemeGrid(settings: store.settings)229    }230}231232struct SearchSettingsSection: View {233    @Environment(\.lunarTheme) private var theme234    @Environment(BrowserStore.self) private var store235    @State private var customName = ""236    @State private var customTemplate = ""237    @State private var customError: String?238239    var body: some View {240        let settings = store.settings241        SearchEngineList(settings: settings, engines: settings.searchEngines)242        LunarHairline()243        SettingsFootnote(L("Add your own engine. Use {query} where the search text goes."))244        LunarTextField(L("Name"), text: $customName).accessibilityIdentifier("engine.custom.name")245        LunarTextField("https://example.com/search?q={query}", text: $customTemplate, icon: .symbol("link"))246            #if os(iOS)247            .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)248            #endif249            .accessibilityLabel(L("Search address template"))250            .accessibilityIdentifier("engine.custom.template")251        if let customError { Text(customError).lunarFont(.footnote).foregroundStyle(theme.danger) }252        Button(L("Add Search Engine")) { addEngine(settings) }253            .buttonStyle(.lunar(.secondary, size: .compact))254            .disabled(customName.isEmpty || customTemplate.isEmpty)255            .accessibilityIdentifier("engine.custom.add")256    }257258    private func addEngine(_ settings: AppSettings) {259        do {260            let engine = try settings.addCustomSearchEngine(name: customName, template: customTemplate)261            settings.searchEngineID = engine.id262            customName = ""; customTemplate = ""; customError = nil263        } catch .emptyName {264            customError = L("Give the engine a name.")265        } catch {266            customError = L("The address must start with http:// or https:// and contain {query}.")267        }268    }269}270271struct TabsSettingsSection: View {272    @Environment(\.lunarTheme) private var theme273    @Environment(\.horizontalSizeClass) private var sizeClass274    @Environment(BrowserStore.self) private var store275    let window: WindowModel276277    var body: some View {278        let settings = store.settings279        if showsLayoutChoice {280            // Three layouts fit as segments; with the ones features add, the choice becomes a menu.281            let layouts = store.registry.supportedLayouts282            let selection = Binding(get: { window.tabLayout }, set: { (mode: TabLayoutMode) in283                window.tabLayout = mode284                settings.defaultTabLayout = mode285            })286            if layouts.count <= 3 {287                LunarSegmentedControl(L("Tab layout"), selection: selection,288                                      segments: layouts.map { LunarSegment($0.localizedName, value: $0) })289                    .accessibilityIdentifier("settings.tabLayout")290            } else {291                Picker(L("Tab layout"), selection: selection) {292                    ForEach(layouts, id: \.self) { Text($0.localizedName).tag($0) }293                }294                .pickerStyle(.menu)295                .tint(theme.accent.color)296                .accessibilityIdentifier("settings.tabLayout")297            }298        }299        HStack {300            Text(L("Pages kept in memory")).lunarFont(.body).foregroundStyle(theme.textPrimary)301            Spacer()302            Text(verbatim: "\(settings.maximumLiveWebViews)").lunarFont(.bodyEmphasized).lunarTabularDigits()303                .foregroundStyle(theme.accent)304        }305        LunarSlider(L("Pages kept in memory"), value: Binding(get: { Double(settings.maximumLiveWebViews) },306                                                              set: { settings.maximumLiveWebViews = Int($0.rounded()) }),307                    in: 2...24, step: 1)308        SettingsFootnote(L("Other tabs are put to sleep and come back when you select them."))309    }310311    private var showsLayoutChoice: Bool {312        #if os(iOS)313        sizeClass == .regular314        #else315        true316        #endif317    }318}319320struct NewTabSettingsSection: View {321    @Environment(BrowserStore.self) private var store322323    var body: some View {324        @Bindable var settings = store.settings325        SettingsToggle(L("Animated starfield"), isOn: $settings.newTabStarfield, id: "settings.starfield")326        SettingsToggle(L("Favourites"), isOn: $settings.newTabShowsFavorites, id: "settings.favorites")327        SettingsToggle(L("Recent pages"), isOn: $settings.newTabShowsRecents, id: "settings.recents")328    }329}330331struct OneHandedSettingsSection: View {332    @Environment(BrowserStore.self) private var store333334    var body: some View {335        @Bindable var settings = store.settings336        SettingsToggle(L("Address bar at the top"), isOn: $settings.omniboxAtTop, id: "settings.omniboxTop")337        SettingsFootnote(L("By default the address bar stays at the bottom, within reach of your thumb."))338    }339}340341struct DownloadsSettingsSection: View {342    @Environment(BrowserStore.self) private var store343    @State private var asksWhereToSave = false344345    var body: some View {346        #if os(macOS)347        if let downloads = store.downloads {348            SettingsToggle(L("Ask where to save each file"), isOn: Binding(get: { asksWhereToSave }, set: { value in349                asksWhereToSave = value350                Task { try? await downloads.manager.setAsksEveryTime(value) }351            }), id: "settings.downloads.ask")352                .task { asksWhereToSave = await downloads.manager.asksEveryTime() }353            SettingsFootnote(L("Otherwise files go to your Downloads folder."))354        }355        #else356        SettingsFootnote(L("Files you download are saved in the Files app, under On My Device › ORIX Navigator › Downloads."))357        #endif358    }359}360361struct PrivacySettingsSection: View {362    @Environment(\.lunarTheme) private var theme363    @Environment(BrowserStore.self) private var store364    let window: WindowModel365    @State private var clearKinds: Set<BrowsingDataKind> = [.history, .cache]366    @State private var clearRange: BrowsingDataRange = .lastHour367    @State private var isClearing = false368369    var body: some View {370        @Bindable var settings = store.settings371        SettingsToggle(L("HTTPS-Only mode"), isOn: $settings.httpsOnly, id: "settings.httpsOnly")372        SettingsFootnote(L("Pages are requested over a secure connection; you are asked before anything loads without one."))373        LunarHairline()374        Text(L("Clear browsing data")).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary)375        ForEach(BrowsingDataKind.allCases) { kind in376            SettingsToggle(kind.localizedName, isOn: Binding(get: { clearKinds.contains(kind) }, set: { on in377                if on { clearKinds.insert(kind) } else { clearKinds.remove(kind) }378            }), id: "clear." + kind.rawValue)379        }380        Picker(L("Time range"), selection: $clearRange) {381            ForEach(BrowsingDataRange.allCases) { Text($0.localizedName).tag($0) }382        }383        .pickerStyle(.menu)384        .tint(theme.accent.color)385        .accessibilityIdentifier("clear.range")386        Button(isClearing ? L("Clearing…") : L("Clear Data")) { clear() }387            .buttonStyle(.lunar(.destructive, size: .compact))388            .disabled(clearKinds.isEmpty || isClearing)389            .accessibilityIdentifier("clear.button")390    }391392    private func clear() {393        isClearing = true394        let kinds = clearKinds, range = clearRange395        Task {396            await store.clearBrowsingData(kinds, range: range)397            isClearing = false398            window.showToast(L("Browsing data cleared"), status: .success)399        }400    }401}402403struct AboutSettingsSection: View {404    @Environment(\.lunarTheme) private var theme405    @State private var showsLicences = false406407    var body: some View {408        HStack(spacing: LunarSpacing.sm) {409            LunarMarkView(size: 44, showsGlow: false).accessibilityHidden(true)410            VStack(alignment: .leading, spacing: 1) {411                Text(verbatim: "ORIX Navigator").lunarFont(.headline).foregroundStyle(theme.textPrimary)412                Text(L("Version %@ (%@)", AppInfo.version, AppInfo.build)).lunarFont(.caption).lunarTabularDigits()413                    .foregroundStyle(theme.textSecondary)414                    .accessibilityIdentifier("settings.version")415            }416        }417        SettingsFootnote(L("No account. No telemetry. Your history, bookmarks and settings stay on this device."))418        Button { showsLicences.toggle() } label: {419            HStack {420                Text(L("Licences")).lunarFont(.body).foregroundStyle(theme.textPrimary)421                Spacer()422                LunarIconView(.symbol(showsLicences ? "chevron.up" : "chevron.down"), size: 12).foregroundStyle(theme.textTertiary)423            }424            .contentShape(Rectangle())425        }426        .buttonStyle(LunarPressStyle())427        .accessibilityValue(showsLicences ? L("Expanded") : L("Collapsed"))428        if showsLicences {429            SettingsFootnote(L("ORIX Navigator contains no third-party code. Pages are rendered by WebKit, the interface is built with SwiftUI and data is stored with SQLite, all provided by the operating system under Apple’s licence terms. WebKit and SQLite are open-source projects (webkit.org, sqlite.org)."))430        }431    }432}433434extension BrowsingDataKind {435    var localizedName: String {436        switch self {437        case .history: L("Browsing history")438        case .cookiesAndSiteData: L("Cookies and site data")439        case .cache: L("Cached files")440        case .closedTabs: L("Recently closed tabs")441        }442    }443}444445extension BrowsingDataRange {446    var localizedName: String {447        switch self {448        case .lastHour: L("Last hour")449        case .today: L("Today")450        case .lastWeek: L("Last 7 days")451        case .allTime: L("All time")452        }453    }454}455456enum AppInfo {457    static var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0" }458    static var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0" }459}460
Files main
Menu

Theme