Repository Public
1// SP Drive iOS2// File: Features/Home/RootView.swift3// Description: Top of the interface: launch, sign-in, the main navigation (tab bar on iPhone, sidebar and columns on iPad), the lock screen.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SPDriveNext8import SwiftUI910struct RootView: View {11 @Environment(AppModel.self) private var model12 @Environment(\.scenePhase) private var scenePhase1314 var body: some View {15 @Bindable var model = model16 ZStack {17 switch model.phase {18 case .launching: LaunchView()19 case .signedOut: SignInView()20 case .signedIn: MainView()21 }22 if model.lock.isLocked && model.phase == .signedIn { LockView().transition(.opacity) }23 // the app switcher must not show file names while the lock is on24 if model.lock.isEnabled && scenePhase != .active && model.phase == .signedIn { PrivacyCover() }25 }26 .animation(.default, value: model.phase)27 .animation(.default, value: model.lock.isLocked)28 .toast($model.toast)29 .tint(SPDTheme.Palette.brand)30 .preferredColorScheme(AppConfiguration.forcedScheme)31 }32}3334struct LaunchView: View {35 var body: some View {36 ZStack { Color("LaunchBackground").ignoresSafeArea(); Image("Mark").accessibilityLabel("SP Drive") }37 }38}3940struct PrivacyCover: View {41 var body: some View {42 ZStack { Rectangle().fill(.regularMaterial).ignoresSafeArea(); Image("Mark") }43 }44}4546struct LockView: View {47 @Environment(AppModel.self) private var model48 var body: some View {49 ZStack {50 Color("LaunchBackground").ignoresSafeArea()51 VStack(spacing: 24) {52 Image("Mark")53 Text("SP Drive est verrouillé").font(.title3.weight(.semibold))54 Button { Task { await model.lock.unlock() } } label: { Label("Déverrouiller avec \(model.lock.kindLabel)", systemImage: model.lock.kind == .faceID ? "faceid" : "touchid") }55 .buttonStyle(GradientButtonStyle()).frame(maxWidth: 320)56 .accessibilityIdentifier("unlock")57 if let e = model.lock.lastError { Text(e).font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center) }58 }59 .padding(32)60 }61 .task { await model.lock.unlock() }62 }63}6465/// Sections of the app, shared by the tab bar and the sidebar.66enum AppSection: String, CaseIterable, Identifiable, Hashable {67 case drive, recent, shared, favorites, offline, transfers, trash, problems, settings68 // SP Drive 2.0 — each exists only when the server announces its feature69 case ask, collections, sharedWithMe, activity, storage70 var id: String { rawValue }71 var title: String {72 switch self {73 case .drive: String(localized: "Mon Drive"); case .recent: String(localized: "Récents"); case .shared: String(localized: "Partagés"); case .favorites: String(localized: "Favoris"); case .offline: String(localized: "Hors ligne")74 case .transfers: String(localized: "Transferts"); case .trash: String(localized: "Corbeille"); case .problems: String(localized: "Conflits et problèmes"); case .settings: String(localized: "Paramètres")75 case .ask: String(localized: "Demander à mon Drive"); case .collections: String(localized: "Collections"); case .sharedWithMe: String(localized: "Partagés avec moi"); case .activity: String(localized: "Activité"); case .storage: String(localized: "Stockage")76 }77 }78 var symbol: String {79 switch self {80 case .drive: "folder.fill"; case .recent: "clock.fill"; case .shared: "link"; case .favorites: "star.fill"; case .offline: "arrow.down.circle.fill"81 case .transfers: "arrow.up.arrow.down.circle.fill"; case .trash: "trash.fill"; case .problems: "exclamationmark.triangle.fill"; case .settings: "gearshape.fill"82 case .ask: "sparkles"; case .collections: "sparkles.rectangle.stack.fill"; case .sharedWithMe: "person.2.fill"; case .activity: "clock.arrow.circlepath"; case .storage: "chart.pie.fill"83 }84 }85 /// The feature a 2.0 section needs from the server (nil = always there).86 var feature: ServerMeta.Feature? {87 switch self { case .ask: .ai; case .collections: .collections; case .sharedWithMe: .collab; case .activity: .activity; case .storage: .storage; default: nil }88 }89 /// The 2.0 sections this server supports, in display order.90 @MainActor static func nextSections(_ next: NextCenter) -> [AppSection] { [AppSection.ask, .collections, .sharedWithMe, .activity, .storage].filter { $0.feature.map(next.has) ?? true }91 }92}9394/// Navigation state of one window (scene): each window has its own place in the app.95@MainActor @Observable96final class SceneNavigation {97 var tab = "drive"98 var section: AppSection? = .drive99 /// Path of the « Mon Drive » stack, so a deep link can open a folder.100 var drivePath: [FolderRoute] = []101 var searching = false102 var showingShortcuts = false103104 /// Goes to a folder of the Drive: the chain of its ancestors becomes the navigation path.105 func open(folder id: String, store: DriveStore) {106 let chain = store.path(to: id).dropFirst().filter(\.isFolder).map { FolderRoute(id: $0.id) }107 tab = "drive"; section = .drive108 drivePath = Array(chain)109 }110}111112struct MainView: View {113 @Environment(AppModel.self) private var model114 @Environment(\.horizontalSizeClass) private var sizeClass115 @State private var nav = SceneNavigation()116117 var body: some View {118 Group {119 if sizeClass == .regular { PadShell() } else { PhoneShell() }120 }121 .environment(nav)122 .onReceive(NotificationCenter.default.publisher(for: .driveCommand)) { note in123 switch note.object as? DriveCommand {124 case .sync: Task { await model.refresh() }125 case .shortcuts: nav.showingShortcuts = true126 case .transfers: model.pendingRoute = .transfers127 default: break128 }129 }130 .onChange(of: model.pendingRoute, initial: true) { _, route in handle(route) }131 .sheet(isPresented: $nav.showingShortcuts) { ShortcutsSheet() }132 }133134 /// Deep links and widget taps. Routes a screen must consume itself (transfers) are left pending for it.135 private func handle(_ route: AppRoute?) {136 guard let route else { return }137 switch route {138 case .transfers:139 if sizeClass == .regular { nav.section = .transfers; model.pendingRoute = nil }140 return141 case .folder(let id):142 if model.store.item(id)?.isFolder == true { nav.open(folder: id, store: model.store) }143 case .file(let id):144 if let item = model.store.item(id), let parent = item.parentID {145 nav.open(folder: parent, store: model.store)146 Task { try? await Task.sleep(for: .milliseconds(500)); NotificationCenter.default.post(name: .openDriveItem, object: item.id) }147 }148 case .upload, .scan:149 nav.tab = "drive"; nav.section = .drive150 let command: DriveCommand = route == .upload ? .importFiles : .scan151 Task { try? await Task.sleep(for: .milliseconds(400)); NotificationCenter.default.post(name: .driveCommand, object: command) }152 case .recent: nav.tab = "recent"; nav.section = .recent153 case .storage: nav.tab = "more"; nav.section = .settings154 case .search: nav.tab = "search"; nav.searching = true155 }156 model.pendingRoute = nil157 }158}159160/// The screen of one section, inside its own navigation stack.161struct SectionStack: View {162 let section: AppSection163 @Environment(SceneNavigation.self) private var nav164 @State private var path: [FolderRoute] = []165 @Namespace private var zoom166167 var body: some View {168 @Bindable var nav = nav169 NavigationStack(path: section == .drive ? $nav.drivePath : $path) {170 Group {171 switch section {172 case .drive: DriveRootScreen()173 case .recent: RecentScreen()174 case .shared: SharedScreen()175 case .favorites: FavoritesScreen()176 case .offline: OfflineScreen()177 case .transfers: TransfersScreen()178 case .trash: TrashScreen()179 case .problems: ProblemsScreen()180 case .settings: SettingsScreen()181 default: section.nextScreen182 }183 }184 .folderDestinations()185 }186 .environment(\.zoomNamespace, zoom)187 }188}189190struct FolderRoute: Hashable, Codable {191 let id: String192 /// The folder was opened from a card: it grows out of it.193 var zoom = false194}195196extension View {197 /// Destinations shared by every stack: a folder, and the sections reachable from « Plus ».198 func folderDestinations() -> some View {199 navigationDestination(for: FolderRoute.self) { route in FolderScreen(folderID: route.id).zoomDestination(route.id, enabled: route.zoom) }200 .navigationDestination(for: AppSection.self) { s in201 switch s {202 case .shared: SharedScreen()203 case .favorites: FavoritesScreen()204 case .transfers: TransfersScreen()205 case .trash: TrashScreen()206 case .problems: ProblemsScreen()207 case .settings: SettingsScreen()208 default: s.nextScreen209 }210 }211 }212}213214extension AppSection {215 /// The screen of a 2.0 section.216 @MainActor @ViewBuilder var nextScreen: some View {217 switch self {218 case .ask: AskScreen(scope: AskScope(kind: .all, name: ""))219 case .collections: CollectionsScreen()220 case .sharedWithMe: SharedWithMeScreen()221 case .activity: ActivityScreen(source: .account)222 case .storage: StorageCenter()223 default: EmptyView()224 }225 }226}227228// MARK: iPhone229230struct PhoneShell: View {231 @Environment(AppModel.self) private var model232 @Environment(SceneNavigation.self) private var nav233234 var body: some View {235 @Bindable var nav = nav236 TabView(selection: $nav.tab) {237 Tab("Mon Drive", systemImage: "folder.fill", value: "drive") { SectionStack(section: .drive).transferPillInset() }238 Tab("Récents", systemImage: "clock.fill", value: "recent") { SectionStack(section: .recent).transferPillInset() }239 Tab("Hors ligne", systemImage: "arrow.down.circle.fill", value: "offline") { SectionStack(section: .offline).transferPillInset() }240 Tab("Plus", systemImage: "ellipsis.circle.fill", value: "more") { MoreStack().transferPillInset() }.badge(model.problemCount)241 Tab("Recherche", systemImage: "magnifyingglass", value: "search", role: .search) { SearchStack() }242 }243 .sensoryFeedback(.selection, trigger: nav.tab)244 .onReceive(NotificationCenter.default.publisher(for: .driveCommand)) { note in245 if note.object as? DriveCommand == .search { nav.tab = "search" }246 }247 }248}249250private struct SearchStack: View {251 @Namespace private var zoom252 var body: some View {253 NavigationStack { SearchScreen().folderDestinations() }.environment(\.zoomNamespace, zoom)254 }255}256257extension View {258 /// The transfer pill sits above the tab bar, inside the safe area of the tab's content (lists scroll clear of it).259 func transferPillInset() -> some View { safeAreaInset(edge: .bottom, spacing: 0) { TransferPill() } }260}261262/// « Plus »: the sections that do not fit in the tab bar, one tap away.263struct MoreStack: View {264 @Environment(AppModel.self) private var model265 @Namespace private var zoom266 var body: some View {267 NavigationStack {268 List {269 Section {270 row(.favorites)271 row(.shared)272 row(.transfers, count: model.activeTransferCount)273 row(.trash)274 }275 if model.problemCount > 0 { Section { row(.problems, count: model.problemCount, tint: .orange) } }276 let next = AppSection.nextSections(model.next)277 if !next.isEmpty { Section { ForEach(next) { row($0) } } }278 Section { row(.settings) }279 }280 .navigationTitle("Plus")281 .folderDestinations()282 }283 .environment(\.zoomNamespace, zoom)284 }285286 private func row(_ s: AppSection, count: Int = 0, tint: Color = Color("AccentColor")) -> some View {287 NavigationLink(value: s) {288 Label { Text(s.title) } icon: { Image(systemName: s.symbol).foregroundStyle(tint) }.badge(count)289 }290 .accessibilityIdentifier("more.\(s.rawValue)")291 }292}293294// MARK: iPad295296/// Sidebar, browser, and (inside the browser) an inspector column: three columns on a wide window, fewer as it narrows.297struct PadShell: View {298 @Environment(AppModel.self) private var model299 @Environment(SceneNavigation.self) private var nav300 @Environment(\.openWindow) private var openWindow301 @State private var columns: NavigationSplitViewVisibility = .all302303 var body: some View {304 @Bindable var nav = nav305 NavigationSplitView(columnVisibility: $columns) {306 List(selection: $nav.section) {307 Section("Fichiers") { ForEach([AppSection.drive, .recent, .favorites, .shared, .offline]) { row($0) } }308 Section("Activité") {309 row(.transfers, count: model.activeTransferCount)310 row(.problems, count: model.problemCount)311 row(.trash)312 }313 let next = AppSection.nextSections(model.next)314 if !next.isEmpty { Section("Drive 2.0") { ForEach(next) { row($0) } } }315 Section { row(.settings) }316 }317 .navigationTitle("SP Drive")318 .safeAreaInset(edge: .bottom) { SidebarStatus().padding(12) }319 .toolbar {320 ToolbarItem { Button { nav.searching = true } label: { Label("Rechercher", systemImage: "magnifyingglass") } }321 }322 } detail: {323 // one stack per section: switching sections does not lose the place in the folder tree324 SectionStack(section: nav.section ?? .drive).id(nav.section ?? .drive)325 }326 .navigationSplitViewStyle(.balanced)327 // the pill floats over the whole window, at the bottom trailing corner (inside a column of the split view it is not rendered)328 .overlay(alignment: .bottomTrailing) { TransferPill().frame(maxWidth: 420).padding(.bottom, 4) }329 .sheet(isPresented: $nav.searching) { NavigationStack { SearchScreen().toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { nav.searching = false } } }.folderDestinations() } }330 .onReceive(NotificationCenter.default.publisher(for: .driveCommand)) { note in331 switch note.object as? DriveCommand {332 case .search: nav.searching = true333 case .newWindow: openWindow(id: "browser", value: nav.drivePath.last?.id ?? model.rootID ?? "")334 case .toggleSidebar: columns = columns == .detailOnly ? .all : .detailOnly335 default: break336 }337 }338 }339340 private func row(_ s: AppSection, count: Int = 0) -> some View {341 Label(s.title, systemImage: s.symbol).badge(count).tag(s).hoverEffect(.highlight).accessibilityIdentifier("sidebar.\(s.rawValue)")342 // dropping items on « Mon Drive » moves them to the root; on « Corbeille » trashes them343 .dropDestination(for: DraggedItem.self) { dragged, _ in drop(dragged, on: s) }344 }345346 private func drop(_ dragged: [DraggedItem], on section: AppSection) -> Bool {347 let ids = dragged.map(\.id)348 switch section {349 case .drive:350 guard let root = model.rootID else { return false }351 Task { await model.perform(success: String(localized: "Déplacé dans Mon Drive")) { try await model.engine.move(ids, to: root) } }352 case .favorites: Task { await model.perform(success: String(localized: "Ajouté aux favoris")) { try await model.engine.setStarred(ids, true) } }353 case .offline: Task { for id in ids { await model.perform { try await model.engine.pin(id) } } }354 case .trash: Task { await model.perform(success: String(localized: "Déplacé dans la corbeille")) { try await model.engine.trash(ids) } }355 default: return false356 }357 return true358 }359}360361/// A secondary window (iPad): one folder of the Drive, browsed on its own.362struct BrowserWindow: View {363 @Environment(AppModel.self) private var model364 let folderID: String365 @State private var nav = SceneNavigation()366 @State private var path: [FolderRoute] = []367 @Namespace private var zoom368369 var body: some View {370 Group {371 if model.phase == .signedIn, let root = model.store.item(folderID)?.id ?? model.rootID {372 NavigationStack(path: $path) { FolderScreen(folderID: root).folderDestinations() }373 .environment(\.zoomNamespace, zoom)374 .transferPillInset()375 } else {376 EmptyState(symbol: "person.crop.circle.badge.exclamationmark", title: String(localized: "Connexion requise"), message: String(localized: "Connecte-toi dans la fenêtre principale de SP Drive."))377 }378 }379 .environment(nav)380 .toast(Bindable(model).toast)381 .tint(Color("AccentColor"))382 }383}384385/// The keyboard shortcuts, listed (⌘/). The system's own overlay (hold ⌘) shows the same commands from the menu bar.386struct ShortcutsSheet: View {387 @Environment(\.dismiss) private var dismiss388 var body: some View {389 NavigationStack {390 List {391 ForEach(DriveShortcut.groups, id: \.title) { group in392 Section(LocalizedStringKey(group.title)) {393 ForEach(group.items) { s in394 LabeledContent { Text(s.keys).font(.body.monospaced().weight(.medium)).foregroundStyle(.secondary) } label: { Label(LocalizedStringKey(s.title), systemImage: s.symbol) }395 }396 }397 }398 }399 .navigationTitle("Raccourcis clavier")400 .navigationBarTitleDisplayMode(.inline)401 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.keyboardShortcut(.cancelAction) } }402 }403 .presentationDetents([.medium, .large])404 }405}406407/// Sync state and storage, always visible at the bottom of the sidebar.408struct SidebarStatus: View {409 @Environment(AppModel.self) private var model410 var body: some View {411 VStack(alignment: .leading, spacing: 8) {412 SyncStatusLabel()413 if let q = model.account?.quota, q.limit > 0 {414 ProgressView(value: min(1, Double(q.used) / Double(q.limit))).tint(Color("AccentColor"))415 Text("\(q.used.byteString) sur \(q.limit.byteString)").font(.caption2).foregroundStyle(.secondary)416 }417 }418 .padding(12)419 .frame(maxWidth: .infinity, alignment: .leading)420 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))421 }422}423424struct SyncStatusLabel: View {425 @Environment(AppModel.self) private var model426 var body: some View {427 Group {428 if !model.network.online { Label("Hors ligne", systemImage: "wifi.slash").foregroundStyle(.orange) }429 else {430 switch model.syncStatus {431 case .syncing: Label("Synchronisation…", systemImage: "arrow.triangle.2.circlepath")432 case .offline: Label("MacLustr injoignable", systemImage: "wifi.exclamationmark").foregroundStyle(.orange)433 case .error(let m): Label(m, systemImage: "exclamationmark.triangle").foregroundStyle(.red)434 case .idle(let last): Label(last.map { "À jour · \($0.shortRelative)" } ?? "Jamais synchronisé", systemImage: "checkmark.icloud")435 }436 }437 }438 .font(.caption.weight(.medium))439 .foregroundStyle(.secondary)440 .accessibilityIdentifier("syncStatus")441 }442}443