SPB Git

Repository Public

SPBrowserMobileApp.swift 8.5 KB 192 lines swift

1import SwiftUI23@main4struct SPBrowserMobileApp: App {5    @State private var environment = MobileEnvironment()67    var body: some Scene {8        WindowGroup {9            SceneRoot(environment: environment)10        }11        .commands { BrowserCommands() }12    }13}1415/// One scene (an iPhone screen or an iPad window) with its own tabs.16struct SceneRoot: View {17    let environment: MobileEnvironment18    @State private var model: BrowserModel?19    @Environment(\.scenePhase) private var scenePhase2021    var body: some View {22        Group {23            if let model {24                BrowserView(model: model, environment: environment)25                    .focusedSceneValue(\.browserModel, model)26            } else {27                Color(.systemBackground)28            }29        }30        .preferredColorScheme(environment.colorScheme)31        .tint(Aura.Palette.accent)32        .auraRoot(decorative: environment.settings.ambientMotionEnabled)33        .onAppear {34            guard model == nil else { return }35            let created = environment.makeModel()36            model = created37            applyLaunchArguments(to: created)38        }39        .onChange(of: scenePhase) { _, phase in40            switch phase {41            case .active: environment.sceneBecameActive()42            case .background: environment.sceneWentToBackground(); model?.suspendBackgroundTabs()43            default: break44            }45        }46        .onOpenURL { url in47            guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { return }48            model?.open(url, inNewTab: true)49        }50    }51}5253extension SceneRoot {54    /// Launch arguments used by UI tests and screenshot scripts (only honoured with a throw-away data folder).55    ///   -SPBOpenURLs "url1,url2"   opens the addresses in tabs (the last one is shown)56    ///   -SPBShow tabs|settings|account|private|library|constellation|flow|canvas|portal|orbit|palette|focus|reader|compact57    ///   -SPBAmbient obsidian|aurora|liquid|cosmos|minimal   ambient theme of the start page58    func applyLaunchArguments(to model: BrowserModel) {59        guard environment.isTesting, !MobileEnvironment.isRunningUnitTests else { return }60        let defaults = UserDefaults.standard61        if let name = defaults.string(forKey: "SPBAmbient"), let theme = AmbientTheme(rawValue: name) { environment.settings.startPage.ambient = theme }62        var opened: [MobileTab] = []63        let show = defaults.string(forKey: "SPBShow")64        if show == "flow", let list = defaults.string(forKey: "SPBOpenURLs") {65            // For the Flow map the pages are visited as a path: the first one typed, the others opened from it.66            let urls = list.split(separator: ",").compactMap { URL(string: String($0)) }67            Task {68                guard let first = model.selectedTab, let start = urls.first else { return }69                first.load(start)70                try? await Task.sleep(for: .seconds(3))71                for url in urls.dropFirst() { model.newTab(url: url, select: false, after: first); try? await Task.sleep(for: .seconds(1.5)) }72                try? await Task.sleep(for: .seconds(1.5))73                model.perform(.showFlow)74            }75        } else if let list = defaults.string(forKey: "SPBOpenURLs") {76            let urls = list.split(separator: ",").compactMap { URL(string: String($0)) }77            for (index, url) in urls.enumerated() {78                if index == 0, let first = model.selectedTab, first.isBlank { first.load(url); opened.append(first) } else { opened.append(model.newTab(url: url)) }79            }80        }81        func after(_ seconds: Double, _ body: @escaping @MainActor () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { body() } }82        switch show {83        case "tabs":84            after(2.5) { model.selectedTab?.captureThumbnail() }85            after(3.5) { model.showsTabOverview = true }86        case "settings": model.showsSettings = true87        case "account": model.showsSettings = true; model.showsAccount = true88        case "private": model.setPrivate(true)89        case "library": model.library = .bookmarks90        case "constellation":91            // Each tab is shown once so that it has a thumbnail, as it would after normal use.92            Task {93                for tab in opened {94                    try? await Task.sleep(for: .seconds(2.2))95                    model.select(tab)96                }97                try? await Task.sleep(for: .seconds(2.5))98                model.perform(.showConstellation)99            }100        case "flow": if defaults.string(forKey: "SPBOpenURLs") == nil { after(2) { model.perform(.showFlow) } }101        case "canvas":102            after(3.5) {103                // A board with something on it: the pages just opened and a note.104                for tab in opened { model.select(tab); model.addCurrentPageToCanvas() }105                model.canvas.add(.note, text: L("Compare these before deciding."))106                model.canvas.flush()107                model.toast = nil108                model.perform(.showCanvas)109            }110        case "portal": after(1.5) { model.present(.portal) }111        case "orbit": after(3.5) { model.perform(.commandOrbit) }112        case "palette": after(3) { model.perform(.commandPalette) }113        case "focus": after(4) { model.selectedTab?.simulateScrollDown(by: 900); if !model.focusMode { model.toggleFocusMode() } }114        case "reader": after(5) { model.perform(.toggleReader) }115        case "compact": after(4) { model.selectedTab?.simulateScrollDown(by: 900) }116        default: break117        }118    }119}120121struct BrowserModelKey: FocusedValueKey { typealias Value = BrowserModel }122extension FocusedValues {123    var browserModel: BrowserModel? {124        get { self[BrowserModelKey.self] }125        set { self[BrowserModelKey.self] = newValue }126    }127}128129/// Hardware-keyboard shortcuts (iPad, or an iPhone with a keyboard), matching the Mac app. Every item runs through the130/// scene's command executor, with the default shortcut of the shared catalog.131struct BrowserCommands: Commands {132    @FocusedValue(\.browserModel) private var model133134    /// Commands that have a hardware-keyboard shortcut on iOS.135    static let shortcuts: [CommandID: KeyCombo] = {136        let commands: [CommandID] = [.newTab, .newPrivateWindow, .closeTab, .reopenClosedTab, .openLocation, .reload, .findInPage, .goBack, .goForward,137                                     .addBookmark, .showHistory, .showBookmarks, .nextTab, .previousTab, .commandOrbit, .commandPalette, .showConstellation,138                                     .showFlow, .showCanvas, .addToCanvas, .showPortal, .toggleFocusMode, .toggleReader]139        return Dictionary(uniqueKeysWithValues: commands.compactMap { command in command.defaultShortcut.map { (command, $0) } })140    }()141142    private static func keyboardShortcut(_ combo: KeyCombo?) -> KeyboardShortcut? {143        guard let combo, let character = combo.key.first, combo.key.count == 1 else { return nil }144        var modifiers: EventModifiers = []145        if combo.command { modifiers.insert(.command) }146        if combo.shift { modifiers.insert(.shift) }147        if combo.option { modifiers.insert(.option) }148        if combo.control { modifiers.insert(.control) }149        return KeyboardShortcut(KeyEquivalent(character), modifiers: modifiers)150    }151152    private func item(_ command: CommandID, _ title: String? = nil) -> some View {153        Button(title ?? command.title) { model?.perform(command) }.keyboardShortcut(Self.keyboardShortcut(Self.shortcuts[command]))154    }155156    var body: some Commands {157        CommandGroup(replacing: .newItem) {158            item(.newTab)159            item(.newPrivateWindow, L("New Private Tab"))160            item(.closeTab)161            item(.reopenClosedTab)162        }163        CommandMenu(L("Page")) {164            item(.openLocation)165            item(.reload)166            item(.findInPage)167            item(.goBack)168            item(.goForward)169            item(.toggleReader)170            item(.toggleFocusMode)171            Divider()172            item(.addBookmark)173            item(.showHistory)174            item(.showBookmarks)175            Divider()176            item(.nextTab)177            item(.previousTab)178            Button(L("Show All Tabs")) { model?.showsTabOverview = true }.keyboardShortcut("\\", modifiers: [.command, .shift])179        }180        CommandMenu("AURA") {181            item(.commandOrbit)182            item(.commandPalette)183            Divider()184            item(.showConstellation)185            item(.showFlow)186            item(.showCanvas)187            item(.addToCanvas)188            item(.showPortal)189        }190    }191}192
Files main
Menu

Theme