SPB Git

Repository Public

MainView.swift 13.6 KB 231 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Home/MainView.swift3// Description: Main window: the sidebar (library, sharing, activity), the section shown next to it, the command palette above, the sheets, and the message banner.4import SPDriveCore5import SPDriveNext6import SPDriveSync7import SwiftUI89struct MainView: View {10    @Environment(AppModel.self) private var model11    @Environment(Navigator.self) private var nav12    @Environment(\.openSettings) private var openSettings1314    var body: some View {15        @Bindable var nav = nav16        let openConflicts = model.conflicts.filter(\.isOpen).count17        NavigationSplitView {18            List(selection: Binding(get: { nav.section }, set: { if let s = $0 { nav.section = s } })) {19                Section("Bibliothèque") { row(.drive); row(.recent); row(.favorites); row(.offline) }20                // SP Drive 2.0: listed only when the connected server offers them21                if model.isAvailable(.collections) {22                    Section("Collections") {23                        ForEach(model.collections) { c in24                            Button { nav.collectionID = c.id; nav.section = .collections } label: {25                                Label { Text(c.name).lineLimit(1) } icon: { Image(systemName: CollectionLook.symbol(c.icon)).foregroundStyle(CollectionLook.color(c.color)) }.badge(c.count ?? 0)26                            }27                            .buttonStyle(.plain)28                            .listRowBackground(nav.section == .collections && (nav.collectionID ?? model.collections.first?.id) == c.id ? RoundedRectangle(cornerRadius: 6).fill(SPDTheme.selection).padding(.horizontal, 10) : nil)29                            .contextMenu { Button("Modifier la règle…") { nav.sheet = .collection(c) } }30                            .accessibilityIdentifier("sidebar-collection")31                        }32                        Button { nav.sheet = .collection(nil) } label: { Label("Nouvelle collection…", systemImage: "plus") }.buttonStyle(.plain).foregroundStyle(SPDTheme.textSecondary)33                    }34                }35                Section("Partage") {36                    row(.shared)37                    if model.isAvailable(.sharedWithMe) { row(.sharedWithMe, badge: model.grants.count) }38                    row(.portals)39                }40                Section("Activité") {41                    row(.transfers, badge: model.status.transfers.running + model.status.transfers.queued)42                    if openConflicts > 0 || nav.section == .conflicts { row(.conflicts, badge: openConflicts) } // shown when there is something to settle43                    if model.isAvailable(.activity) { row(.activity) }44                    row(.trash)45                }46                Section("Ce Mac") { row(.storage) }47                if model.isAvailable(.admin) { Section("Serveur") { row(.admin) } }48            }49            .listStyle(.sidebar)50            .navigationSplitViewColumnWidth(min: 200, ideal: 224, max: 300)51            .safeAreaInset(edge: .bottom, spacing: 0) { SidebarFooter(model: model, nav: nav) }52        } detail: {53            VStack(spacing: 0) {54                ZStack(alignment: .bottom) {55                    Group {56                        switch nav.section {57                        case .drive, .recent, .favorites, .offline, .trash: BrowserView()58                        case .shared: SharesView()59                        case .portals: PortalsView()60                        case .transfers, .downloads: TransfersView()61                        case .conflicts: ConflictsView()62                        case .storage: StorageView()63                        case .collections: CollectionsView()64                        case .sharedWithMe: SharedWithMeView()65                        case .activity: ActivityView()66                        case .admin: AdminView()67                        }68                    }69                    .frame(maxWidth: .infinity, maxHeight: .infinity)70                    BannerView()71                }72                FinderEnableBanner()73            }74            .spdMotion(.reveal, value: model.banner)75        }76        .overlay(alignment: .top) {77            if nav.showPalette {78                ZStack(alignment: .top) {79                    Color.black.opacity(0.14).ignoresSafeArea().onTapGesture { nav.showPalette = false }80                    CommandPalette(model: model, nav: nav).padding(.top, 72)81                }82                .transition(.opacity.combined(with: .scale(scale: 0.98, anchor: .top)))83            }84        }85        .spdMotion(.reveal, value: nav.showPalette)86        .sheet(item: $nav.sheet) { kind in87            Group {88                switch kind {89                case .newFolder(let parent): NameSheet(title: "Nouveau dossier", initial: "Nouveau dossier", action: "Créer") { if let f = model.createFolder(in: parent, name: $0) { nav.selection = [f.id] } }90                case .rename(let item): NameSheet(title: "Renommer « \(item.name) »", initial: item.name, action: "Renommer", selectStem: !item.isFolder) { model.rename(item, to: $0) }91                case .move(let items): MoveSheet(items: items)92                case .share(let item): ShareSheet(item: item)93                case .portal(let folder): PortalSheet(folder: folder)94                case .versions(let item): if model.meta.api >= 2 { VersionsTimeline(model: model, nav: nav, item: item) } else { VersionsSheet(item: item) }95                case .members(let folder): MembersSheet(model: model, nav: nav, folder: folder)96                case .collection(let c): CollectionEditor(model: model, nav: nav, existing: c)97                case .suggest(let items): SuggestionsSheet(model: model, nav: nav, items: items)98                case .ask(let item): AskView(model: model, nav: nav, item: item, onOpen: { nav.sheet = nil }, onClose: { nav.sheet = nil }).frame(width: 620, height: 640)99                case .conflict(let c): ConflictSheet(model: model, nav: nav, conflict: c)100                }101            }102            .environment(model).environment(nav)103        }104        .confirmationDialog("Supprimer définitivement \(nav.confirmPurge.count) élément(s) ?", isPresented: Binding(get: { !nav.confirmPurge.isEmpty }, set: { if !$0 { nav.confirmPurge = [] } })) {105            Button("Supprimer définitivement", role: .destructive) { let items = nav.confirmPurge; nav.confirmPurge = []; Task { await model.purge(items) } }106            Button("Annuler", role: .cancel) { nav.confirmPurge = [] }107        } message: { Text("Cette action est irréversible : les fichiers et toutes leurs versions seront effacés de SP Drive.") }108        .confirmationDialog("Vider la corbeille ?", isPresented: $nav.confirmEmptyTrash) {109            Button("Vider la corbeille", role: .destructive) { Task { await model.emptyTrash() } }110            Button("Annuler", role: .cancel) {}111        } message: { Text("Tout le contenu de la corbeille sera effacé définitivement de SP Drive.") }112    }113    private func row(_ item: SidebarItem, badge: Int = 0) -> some View {114        Label(item.title, systemImage: item.symbol).badge(badge).tag(item).accessibilityIdentifier("sidebar-\(item.rawValue)")115    }116}117118/// Shown while macOS keeps the Finder location off: only the person can turn it on, in System Settings.119struct FinderEnableBanner: View {120    @Environment(AppModel.self) private var model121    @AppStorage("finderBannerDismissed") private var dismissed = false122    var body: some View {123        if model.finderRegistered, !model.finderEnabled, !dismissed {124            HStack(spacing: SPDTheme.Space.md) {125                Image(systemName: "folder.badge.questionmark").font(.title2).foregroundStyle(SPDTheme.brand)126                VStack(alignment: .leading, spacing: 2) {127                    Text("Activez SP Drive dans le Finder").font(SPDTheme.Typo.bodyStrong)128                    Text("macOS demande votre accord : Réglages Système › Général › Ouverture et extensions › Fournisseurs de fichiers, puis activez « \(AppEnvironment.productName) ». D’ici là, vos fichiers restent accessibles dans cette fenêtre.").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.textSecondary)129                }130                Spacer()131                Button("Ouvrir les Réglages Système") { DriveDomain.shared.openSystemSettings() }.buttonStyle(.borderedProminent)132                Button { dismissed = true } label: { Image(systemName: "xmark") }.buttonStyle(.plain).accessibilityLabel("Masquer")133            }134            .padding(.horizontal, SPDTheme.Space.lg).padding(.vertical, 10).background(SPDTheme.brandWash)135            .overlay(alignment: .top) { Rectangle().fill(SPDTheme.hairline).frame(height: 1) }136            .task { await model.watchFinderState() }137            .accessibilityIdentifier("finder-enable-banner")138        }139    }140}141142/// Bottom of the sidebar: sync state and storage in one glance; a click opens the transfer centre.143struct SidebarFooter: View {144    let model: AppModel145    let nav: Navigator146    var body: some View {147        VStack(alignment: .leading, spacing: 6) {148            Rectangle().fill(SPDTheme.hairline).frame(height: 1)149            Button { nav.section = .transfers } label: {150                HStack(spacing: 6) {151                    SyncStatusIcon(status: model.status)152                    VStack(alignment: .leading, spacing: 0) {153                        Text(SyncStatusText.title(model.status)).font(SPDTheme.Typo.callout).lineLimit(1)154                        if model.status.transfers.speed > 1024 { Text(Fmt.speed(model.status.transfers.speed) + (model.secondsRemaining.map { " · " + Fmt.duration($0) } ?? "")).font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textTertiary).monospacedDigit() }155                    }156                    Spacer()157                }.contentShape(Rectangle())158            }159            .buttonStyle(.plain).help(SyncStatusText.detail(model.status))160            .accessibilityElement(children: .combine).accessibilityIdentifier("sync-status")161            if let q = model.quota, q.limit > 0 {162                Button { nav.section = .storage } label: {163                    VStack(alignment: .leading, spacing: 3) {164                        QuotaBar(used: q.used, limit: q.limit)165                        Text("\(Fmt.bytes(q.free)) libres sur \(Fmt.bytes(q.limit))").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)166                    }.contentShape(Rectangle())167                }.buttonStyle(.plain)168            }169        }170        .padding(.horizontal, 14).padding(.bottom, 10)171        .background(.bar) // rows of a long sidebar scroll under it172    }173}174175/// A slim storage meter; turns to the warning colour (with a symbol next to it where shown) above 90 %.176struct QuotaBar: View {177    let used: Int64, limit: Int64178    var body: some View {179        let f = limit > 0 ? min(1, Double(used) / Double(limit)) : 0180        GeometryReader { g in181            ZStack(alignment: .leading) {182                Capsule().fill(SPDTheme.hairline)183                Capsule().fill(f > 0.9 ? SPDTheme.warning : SPDTheme.brand).frame(width: max(f > 0 ? 4 : 0, g.size.width * f))184            }185        }186        .frame(height: 4).spdMotion(.progress, value: used)187        .accessibilityElement().accessibilityLabel("Stockage").accessibilityValue("\(Int(f * 100)) % utilisés")188    }189}190191enum SyncStatusText {192    static func title(_ s: SyncStatus) -> String {193        switch s.phase {194        case .offline: return s.pendingOperations > 0 ? "Hors ligne · \(s.pendingOperations) en attente" : "Hors ligne"195        case .paused: return "Synchronisation en pause"196        case .needsLogin: return "Reconnexion requise"197        case .error: return "Erreur de synchronisation"198        case .syncing: return "Synchronisation…"199        case .idle:200            let active = s.transfers.running + s.transfers.queued201            if active > 0 { return "\(active) transfert\(active > 1 ? "s" : "") en cours" }202            if s.pendingOperations > 0 { return "\(s.pendingOperations) opération(s) en attente" }203            if s.openConflicts > 0 { return "\(s.openConflicts) conflit\(s.openConflicts > 1 ? "s" : "") à régler" }204            return "À jour"205        }206    }207    static func detail(_ s: SyncStatus) -> String {208        if let e = s.lastError, s.phase != .idle { return e }209        if let d = s.lastSync { return "Dernière synchronisation \(Fmt.relative(d))" }210        return "Jamais synchronisé"211    }212    /// How this Mac learns of changes made elsewhere.213    static func channel(_ s: SyncStatus) -> String {214        switch s.events { case .stream: "Changements reçus en direct"; case .polling: "Vérification toutes les 30 s"; case .off: "Écoute arrêtée" }215    }216}217struct SyncStatusIcon: View {218    let status: SyncStatus219    var body: some View {220        let busy = status.phase == .syncing || status.transfers.running > 0221        let (symbol, color): (String, Color) = {222            switch status.phase {223            case .offline: ("icloud.slash", SPDTheme.textSecondary); case .paused: ("pause.circle", SPDTheme.textSecondary); case .needsLogin: ("person.crop.circle.badge.exclamationmark", SPDTheme.warning)224            case .error: ("exclamationmark.icloud", SPDTheme.warning); case .syncing: ("arrow.triangle.2.circlepath", SPDTheme.brand)225            case .idle: status.transfers.running > 0 ? ("arrow.triangle.2.circlepath", SPDTheme.brand) : status.openConflicts > 0 ? ("exclamationmark.triangle", SPDTheme.warning) : ("checkmark.icloud", SPDTheme.positive)226            }227        }()228        Image(systemName: symbol).foregroundStyle(color).symbolEffect(.pulse, isActive: busy && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion).accessibilityHidden(true)229    }230}231
Files main
Menu

Theme