SPB Git

Repository Public

RootView.swift 10.7 KB 229 lines swift

1// SP Notes iOS2// File: Features/Root/RootView.swift3// Description: Root of one window: welcome screen or main interface by session state, the app lock above everything, the4//              appearance choice, the requests coming from outside the screens (widgets, Siri, links) and the app banner.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import CoreSpotlight9import SPNotesCore10import SwiftUI1112enum Appearance: String, CaseIterable, Identifiable {13    case system, light, dark14    var id: String { rawValue }15    var colorScheme: ColorScheme? {16        switch self { case .system: return nil; case .light: return .light; case .dark: return .dark }17    }18    var label: String {19        switch self {20        case .system: return String(localized: "Automatique")21        case .light: return String(localized: "Clair")22        case .dark: return String(localized: "Sombre")23        }24    }25}2627/// What a window is for.28enum SceneMode {29    /// The full interface (tabs on iPhone, columns on iPad).30    case shell31    /// One note in a window of its own (`WindowGroup(for: NoteWindowTarget.self)`).32    case noteWindow(Binding<NoteWindowTarget?>)3334    var kind: RouteCoordinator.SceneKind { if case .shell = self { return .shell } else { return .noteWindow } }35}3637struct RootView: View {38    var mode: SceneMode = .shell39    @Environment(AppModel.self) private var app40    @Environment(\.scenePhase) private var scenePhase41    @AppStorage("appearance") private var appearanceRaw = Appearance.system.rawValue42    @State private var shell = ShellState()43    /// The identity of this window for the route coordinator.44    @State private var sceneId = RouteCoordinator.SceneID()4546    var body: some View {47        ZStack {48            Group {49                if app.session == .signedOut {50                    WelcomeScreen()51                } else {52                    switch mode {53                    case .shell: MainInterface()54                    case .noteWindow(let target): NoteWindowScreen(target: target)55                    }56                }57            }58            .environment(shell)59            // Nothing below is reachable (touch, keyboard, VoiceOver) while locked.60            .disabled(app.lock.isLocked)61            .accessibilityHidden(app.lock.isLocked)6263            if app.lock.isLocked {64                LockScreen().transition(.opacity).zIndex(2)65            } else if app.lock.isEnabled, scenePhase != .active {66                PrivacyCover().zIndex(1)67            }68        }69        .overlay(alignment: .top) { bannerView }70        .animation(.default, value: app.banner)71        .preferredColorScheme((Appearance(rawValue: appearanceRaw) ?? .system).colorScheme)72        .background(KeyWindowObserver { app.routes.noteKey(sceneId) })73        .task {74            app.start()75            // Menus, context menus and bars are drawn by UIKit windows, which do not see the SwiftUI tint.76            if let accent = UIColor(named: "AccentColor") {77                UIWindow.appearance().tintColor = accent78                for case let scene as UIWindowScene in UIApplication.shared.connectedScenes { scene.windows.forEach { $0.tintColor = accent } }79            }80            if app.routes.onNeedsShell == nil {81                // a shell route arrived while only note windows are open: the system opens a main window (the first window group)82                app.routes.onNeedsShell = {83                    UIApplication.shared.activateSceneSession(for: UISceneSessionActivationRequest(role: .windowApplication)) { _ in }84                }85            }86        }87        .onAppear {88            // One registration per window: the coordinator delivers each route to exactly one of them.89            let shell = shell, app = app, isShell = mode.kind == .shell90            app.routes.register(sceneId, kind: mode.kind, isActive: scenePhase == .active) { route in91                if isShell { ShellRouting.handle(route, app: app, shell: shell) } else { ShellRouting.handleInNoteWindow(route, shell: shell) }92            }93            #if DEBUG94            if isShell, let text = ProcessInfo.processInfo.environment["SPNOTES_OPEN"], let url = URL(string: text), !DebugLaunch.opened {95                DebugLaunch.opened = true96                Task { try? await Task.sleep(for: .milliseconds(1500)); app.open(url: url, from: sceneId) }97            }98            #endif99        }100        .onDisappear { app.routes.unregister(sceneId) }101        .onChange(of: scenePhase) { _, phase in102            app.routes.setActive(sceneId, phase == .active)103            switch phase {104            case .background: app.lock.sceneDidEnterBackground(); app.sceneDidLeaveForeground()105            case .inactive: break106            case .active:107                app.lock.sceneWillEnterForeground()108                app.sceneDidBecomeActive()109            @unknown default: break110            }111        }112        // What comes from outside arrives in ONE window and is dispatched once, naming that window.113        .onOpenURL { app.open(url: $0, from: sceneId) }114        .onContinueUserActivity(NoteActivity.type) { app.continueActivity($0, from: sceneId) }115        .onContinueUserActivity(CSSearchableItemActionType) { app.continueActivity($0, from: sceneId) }116        .onContinueUserActivity(CSQueryContinuationActionType) { app.continueActivity($0, from: sceneId) }117        .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { app.continueActivity($0, from: sceneId) }118    }119120    @ViewBuilder private var bannerView: some View {121        if let banner = app.banner, !app.lock.isLocked {122            HStack(alignment: .top, spacing: 10) {123                Image(systemName: "exclamationmark.circle.fill").foregroundStyle(Color.spWarning).accessibilityHidden(true)124                Text(banner).font(.subheadline).foregroundStyle(Color.spText).fixedSize(horizontal: false, vertical: true)125                Spacer(minLength: 4)126                Button { app.banner = nil } label: {127                    Image(systemName: "xmark").font(.footnote.weight(.semibold)).foregroundStyle(Color.spTextSecondary)128                        .frame(width: 44, height: 44).contentShape(Rectangle())129                }130                .accessibilityLabel("Fermer le message")131            }132            .padding(.leading, 14).padding(.vertical, 4)133            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))134            .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Color.spBorder))135            .shadow(color: .black.opacity(0.12), radius: 12, y: 4)136            .padding(.horizontal, 16).padding(.top, 6)137            .frame(maxWidth: 560)138            .transition(.move(edge: .top).combined(with: .opacity))139            .accessibilityIdentifier("app-banner")140            .task(id: banner) {141                try? await Task.sleep(for: .seconds(6))142                if !Task.isCancelled, app.banner == banner { app.banner = nil }143            }144        }145    }146}147148#if DEBUG149/// Debug launch environment `SPNOTES_OPEN=<link>`: opens a link once after launch (screenshots, UI tests).150@MainActor enum DebugLaunch { static var opened = false }151#endif152153/// What a window does with a route (pure enough to test with a `ShellState`).154@MainActor155enum ShellRouting {156    /// The effect of a route on the navigation state. Returns true when a new note must be created (the caller does it).157    @discardableResult158    static func apply(_ route: AppRoute, to shell: ShellState) -> Bool {159        shell.sheet = nil160        shell.isPaletteOpen = false161        switch route {162        case .note(let id, let blockId): shell.open(note: id, blockId: blockId)163        case .newNote: return true164        case .search(let query): shell.openSearch(query)165        case .today: shell.go(to: .today)166        case .tasks: shell.go(to: .tasks)167        case .inbox: shell.go(to: .inbox)168        case .capture(let kind): shell.requestCapture(kind: kind)169        case .section(let id): if shell.sections.section(id: id) != nil { shell.go(to: .hosted(id)) }170        }171        return false172    }173174    static func handle(_ route: AppRoute, app: AppModel, shell: ShellState) {175        if apply(route, to: shell) { Task { await NoteCommands(app: app, shell: shell).newNote(in: nil) } }176    }177178    /// A note window only shows notes: the note is pushed in its own stack.179    static func handleInNoteWindow(_ route: AppRoute, shell: ShellState) {180        if case .note(let id, let blockId) = route { shell.open(note: id, blockId: blockId) }181    }182}183184/// Tells when the window of this view becomes the key window (the one the user interacts with).185struct KeyWindowObserver: UIViewRepresentable {186    let onKey: @MainActor () -> Void187188    func makeUIView(context: Context) -> Probe { Probe(onKey: onKey) }189    func updateUIView(_ view: Probe, context: Context) {}190191    final class Probe: UIView {192        private let onKey: @MainActor () -> Void193        private nonisolated(unsafe) var observer: NSObjectProtocol?194        private nonisolated(unsafe) var sceneObserver: NSObjectProtocol?195196        init(onKey: @escaping @MainActor () -> Void) {197            self.onKey = onKey198            super.init(frame: .zero)199            isUserInteractionEnabled = false200            isAccessibilityElement = false201            observer = NotificationCenter.default.addObserver(forName: UIWindow.didBecomeKeyNotification, object: nil, queue: .main) { [weak self] notification in202                let window = (notification.object as AnyObject?).map(ObjectIdentifier.init)203                MainActor.assumeIsolated {204                    guard let self, let own = self.window, window == ObjectIdentifier(own) else { return }205                    self.onKey()206                }207            }208            sceneObserver = NotificationCenter.default.addObserver(forName: UIScene.didActivateNotification, object: nil, queue: .main) { [weak self] notification in209                let scene = (notification.object as AnyObject?).map(ObjectIdentifier.init)210                MainActor.assumeIsolated { self?.takeKeyIfActivated(scene) }211            }212        }213214        /// A window whose scene comes (back) to the front takes the keyboard: after another window of the app is closed, UIKit215        /// can leave the app without a key window, and hardware shortcuts would then go nowhere.216        private func takeKeyIfActivated(_ scene: ObjectIdentifier?) {217            guard let window, let own = window.windowScene, scene == ObjectIdentifier(own), !window.isKeyWindow else { return }218            window.makeKey()219            onKey()220        }221222        @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }223        deinit {224            if let observer { NotificationCenter.default.removeObserver(observer) }225            if let sceneObserver { NotificationCenter.default.removeObserver(sceneObserver) }226        }227    }228}229
Files main
Menu

Theme