SPB Git

Repository Public

MainInterface.swift 11.7 KB 254 lines swift

1// SP Notes iOS2// File: Features/Root/MainInterface.swift3// Description: The main interface of a window, adaptive: tabs (Aujourd’hui · Notes · Capture · Recherche · Plus), each with its4//              own navigation stack, when the width is compact (iPhone); a sidebar and columns when it is regular (iPad). Owns5//              the sheets, the toast, the command palette, the capture hook, the menus' target and the state restoration.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import SwiftUI1213struct MainInterface: View {14    @Environment(AppModel.self) private var app15    @Environment(ShellState.self) private var shell16    @Environment(\.horizontalSizeClass) private var sizeClass17    @Environment(\.scenePhase) private var scenePhase18    @Environment(\.supportsMultipleWindows) private var supportsMultipleWindows19    @Environment(\.openWindow) private var openWindow20    @SceneStorage("shell.sidebar") private var storedSidebar = ""21    @SceneStorage("shell.note") private var storedNote = ""22    @State private var restored = false2324    private var actions: ShellActions {25        var actions = ShellActions(app: app, shell: shell)26        if supportsMultipleWindows {27            let openWindow = openWindow28            actions.openNoteWindow = { target in openWindow(value: target) }29        }30        return actions31    }3233    var body: some View {34        @Bindable var shell = shell35        Group {36            if shell.isCompact { CompactShell() } else { RegularShell() }37        }38        .overlay(alignment: .bottom) { ToastView(bottomPadding: shell.isCompact ? 64 : 14) }39        .nvAnimation(.base, value: shell.toast?.id)40        .overlay { CommandPaletteOverlay(actions: actions) }41        // the menus (`ShellCommands`) and their shortcuts act on the key window through this value42        .focusedSceneValue(\.shellActions, actions)43        .onChange(of: scenePhase, initial: true) { _, phase in44            if phase == .active { ShellActions.lastActive = actions }45        }46        .onDisappear { if ShellActions.lastActive?.shell === shell { ShellActions.lastActive = nil } }47        .sheet(item: $shell.sheet) { sheet in48            Group {49                switch sheet {50                case .move(let ids): MoveNoteSheet(noteIds: ids)51                case .tags(let ids): TagEditorSheet(noteIds: ids)52                case .settings: SettingsScreen()53                case .syncDetails: SyncDetailsSheet()54                case .newFolder(let parentId, let section): FolderNameSheet(mode: .create(parentId: parentId, section: section))55                case .renameFolder(let id, let title): FolderNameSheet(mode: .rename(id: id, current: title))56                }57            }58            .environment(shell)59        }60        .onChange(of: sizeClass, initial: true) { _, new in61            shell.adapt(toCompact: new != .regular)62            restoreIfNeeded()63        }64        .onChange(of: shell.location) { _, new in if restored { storedSidebar = new?.storageKey ?? "" } }65        .onChange(of: shell.currentNote) { _, new in if restored { storedNote = new ?? "" } }66        .onChange(of: shell.captureRequest) { _, request in67            if let request { CaptureHook.present(request, app: app, shell: shell) }68        }69        .quickCapture(item: Bindable(shell).quickCapture)70        // what the server offers decides which hosted sections exist (read from the cached answer: no request here)71        .task(id: app.feed.cache &+ app.feed.resetGeneration) { shell.sections.update(features: await app.repositories.features()) }72    }7374    /// Puts this window back where it was (place and note), in either layout.75    private func restoreIfNeeded() {76        guard !restored else { return }77        restored = true78        let place = SidebarItem(storageKey: storedSidebar)79        let noteId = storedNote80        if let place {81            // a hosted section that no longer exists is not restored82            if case .hosted(let id) = place, shell.sections.section(id: id) == nil {} else { shell.restore(location: place, note: nil) }83        }84        if !noteId.isEmpty, shell.currentNote == nil {85            Task {86                if let page = try? await app.store.summary(id: noteId), page.deletedAt == nil, shell.currentNote == nil { shell.restore(location: nil, note: noteId) }87            }88        }89    }90}9192/// The transient confirmation at the bottom of a window, with its optional undo.93struct ToastView: View {94    var bottomPadding: CGFloat95    @Environment(ShellState.self) private var shell9697    var body: some View {98        if let toast = shell.toast {99            HStack(spacing: 14) {100                Text(toast.message).font(.subheadline.weight(.medium)).foregroundStyle(.white)101                if let title = toast.actionTitle, let action = toast.action {102                    Button {103                        action()104                        shell.toast = nil105                    } label: {106                        Text(title).font(.subheadline.weight(.bold)).foregroundStyle(NVColor.Token.accent.color(for: .dark))107                            .frame(minWidth: 44, minHeight: 44).contentShape(Rectangle())108                    }109                    .accessibilityIdentifier("toast-action")110                }111            }112            .padding(.horizontal, 18)113            .padding(.vertical, toast.action == nil ? 13 : 2)114            .background(Color(white: 0.13).opacity(0.96), in: Capsule())115            .overlay(Capsule().strokeBorder(.white.opacity(0.12)))116            .shadow(color: .black.opacity(0.25), radius: 14, y: 6)117            .padding(.bottom, bottomPadding)118            .padding(.horizontal, 16)119            .transition(.move(edge: .bottom).combined(with: .opacity))120            .accessibilityElement(children: .contain)121            .accessibilityIdentifier("toast")122            .task(id: toast.id) {123                try? await Task.sleep(for: .seconds(toast.action == nil ? 2.5 : 5))124                if !Task.isCancelled, shell.toast?.id == toast.id { shell.toast = nil }125            }126        }127    }128}129130enum NewFolderTarget {131    /// A new folder goes where the window is: inside the folder shown, in the section shown, or in Notes.132    @MainActor static func sheet(for source: NoteSource?) -> ShellSheet {133        switch source {134        case .folder(let id)?: return .newFolder(parentId: id, section: "notes")135        case .section(let section)? where NoteSection.editable.contains(section): return .newFolder(parentId: nil, section: section)136        default: return .newFolder(parentId: nil, section: "notes")137        }138    }139}140141/// The screens a navigation stack of the shell can push.142struct ShellDestinations: ViewModifier {143    func body(content: Content) -> some View {144        content.navigationDestination(for: Destination.self) { destination in145            switch destination {146            case .list(let source): NoteListView(source: source)147            case .folders: FoldersScreen()148            case .tags: TagsScreen()149            case .search(let query): SearchScreen(initialQuery: query)150            case .note(let id, let isNew): NoteScreenHost(noteId: id, isNew: isNew).fluidDestination(id: id)151            case .tasks: TasksScreen()152            case .inbox: InboxScreen()153            case .hosted(let id): HostedSectionView(id: id)154            }155        }156    }157}158159// MARK: - iPhone160161struct CompactShell: View {162    @Environment(ShellState.self) private var shell163164    var body: some View {165        // Capture is an action in the middle of the bar, never a selected tab.166        let selection = Binding<ShellTab>(get: { shell.tab }, set: { new in167            if new == .capture { shell.requestCapture() } else { shell.tab = new }168        })169        TabView(selection: selection) {170            Tab(ShellTab.today.title, systemImage: ShellTab.today.symbol, value: ShellTab.today) { stack(.today) { TodayScreen() } }171            Tab(ShellTab.notes.title, systemImage: ShellTab.notes.symbol, value: ShellTab.notes) { stack(.notes) { NotesLibraryScreen() } }172            // CAPTURE HOOK: the centre button (see `CaptureHook`)173            Tab(ShellTab.capture.title, systemImage: ShellTab.capture.symbol, value: ShellTab.capture) { Color.clear }174            Tab(ShellTab.search.title, systemImage: ShellTab.search.symbol, value: ShellTab.search) {175                stack(.search) { SearchScreen(initialQuery: shell.searchQuery).id(shell.searchQuery) }176            }177            Tab(ShellTab.more.title, systemImage: ShellTab.more.symbol, value: ShellTab.more) { stack(.more) { MoreScreen() } }178        }179    }180181    /// One navigation stack per tab, each with its own path (kept while another tab is shown).182    private func stack<Root: View>(_ tab: ShellTab, @ViewBuilder root: () -> Root) -> some View {183        NavigationStack(path: Binding(get: { shell.paths[tab] ?? [] }, set: { shell.paths[tab] = $0 })) {184            root().modifier(ShellDestinations())185        }186        .fluidNavigationHost() // Fluid Navigation: rows and the notes they open share a namespace (Components/SignatureMotions.swift)187    }188}189190// MARK: - iPad191192struct RegularShell: View {193    @Environment(AppModel.self) private var app194    @Environment(ShellState.self) private var shell195    @State private var visibility = NavigationSplitViewVisibility.all196197    /// A hosted section that takes the whole area right of the sidebar (graph, canvas, databases…).198    private var wideSection: String? {199        guard case .hosted(let id)? = shell.sidebar, shell.sections.section(id: id)?.layout == .wide else { return nil }200        return id201    }202203    var body: some View {204        Group {205            if let wideSection {206                NavigationSplitView(columnVisibility: $visibility) {207                    SidebarView().navigationSplitViewColumnWidth(min: 260, ideal: 300, max: 360)208                } detail: {209                    NavigationStack { HostedSectionView(id: wideSection).navigationBarTitleDisplayMode(.inline) }210                }211            } else {212                NavigationSplitView(columnVisibility: $visibility) {213                    SidebarView().navigationSplitViewColumnWidth(min: 260, ideal: 300, max: 360)214                } content: {215                    NavigationStack { content.navigationBarTitleDisplayMode(.inline) }216                        .navigationSplitViewColumnWidth(min: 300, ideal: 380, max: 480)217                } detail: {218                    NavigationStack { detail }219                }220            }221        }222        .navigationSplitViewStyle(.balanced)223    }224225    @ViewBuilder private var content: some View {226        switch shell.sidebar {227        case .source(let source)?: NoteListView(source: source).id(source)228        case .search?: SearchScreen(initialQuery: shell.searchQuery).id(shell.searchQuery)229        case .today?: TodayScreen()230        case .tasks?: TasksScreen()231        case .inbox?: InboxScreen()232        case .hosted(let id)?: HostedSectionView(id: id)233        case nil: EmptyStateView(symbol: "sidebar.left", title: "Choisis une liste")234        }235    }236237    @ViewBuilder private var detail: some View {238        if let id = shell.selectedNote {239            NoteScreenHost(noteId: id, isNew: shell.isFresh(id)).id(id)240        } else {241            EmptyStateView(symbol: "note.text", title: "Aucune note sélectionnée", message: "Choisis une note dans la liste, ou crée-en une avec ⌘N.", actionTitle: "Nouvelle note") {242                Task { await NoteCommands(app: app, shell: shell).newNote(in: shell.currentSource) }243            }244            .background(Color.spBackground)245            // a note dragged from a list (or from another window) and dropped here opens246            .dropDestination(for: NoteTransfer.self) { items, _ in247                guard let id = items.flatMap(\.ids).first else { return false }248                shell.open(note: id)249                return true250            }251        }252    }253}254
Files main
Menu

Theme