Repository Public
1// SP Notes iOS2// File: Features/Root/ShellState.swift3// Description: Navigation state of one window (scene): what is shown in the stack on iPhone or in the three columns on iPad,4// the sheets, and the transient toast. One instance per scene, so several iPad windows are independent.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Observation9import SPNotesCore10import SwiftUI1112/// The title shown for a note (the server's "Untitled" is « Sans titre »); same rule as `AppModel.displayTitle`, usable off the main actor.13enum NoteTitle {14 static func display(_ title: String) -> String { title == "Untitled" || title.isEmpty ? String(localized: "Sans titre") : title }15}1617/// Where a list of notes comes from.18enum NoteSource: Hashable, Sendable {19 case smart(SmartList)20 case section(String)21 case folder(String)22 case tag(String)2324 /// Stable text form, for `@SceneStorage`.25 var storageKey: String {26 switch self {27 case .smart(let list): return "smart:\(list.rawValue)"28 case .section(let name): return "section:\(name)"29 case .folder(let id): return "folder:\(id)"30 case .tag(let name): return "tag:\(name)"31 }32 }3334 init?(storageKey: String) {35 guard let colon = storageKey.firstIndex(of: ":") else { return nil }36 let kind = storageKey[..<colon], value = String(storageKey[storageKey.index(after: colon)...])37 guard !value.isEmpty else { return nil }38 switch kind {39 case "smart": guard let list = SmartList(rawValue: value) else { return nil }; self = .smart(list)40 case "section": self = .section(value)41 case "folder": self = .folder(value)42 case "tag": self = .tag(value)43 default: return nil44 }45 }46}4748/// The sections of the workspace a note can live in.49enum NoteSection {50 /// Sections the app can file notes in (`databases` is read-only here).51 static let editable = ["notes", "documents", "projects", "research"]5253 static func title(_ section: String) -> String {54 switch section {55 case "notes": return String(localized: "Notes")56 case "documents": return String(localized: "Documents")57 case "projects": return String(localized: "Projets")58 case "research": return String(localized: "Recherche")59 case "databases": return String(localized: "Bases de données")60 default: return section.capitalized61 }62 }6364 static func symbol(_ section: String) -> String {65 switch section {66 case "notes": return "note.text"67 case "documents": return "doc.text"68 case "projects": return "hammer"69 case "research": return "books.vertical"70 case "databases": return "tablecells"71 default: return "square.stack"72 }73 }74}7576extension SmartList {77 var title: String {78 switch self {79 case .all: return String(localized: "Toutes les notes")80 case .recent: return String(localized: "Récentes")81 case .pinned: return String(localized: "Épinglées")82 case .favorites: return String(localized: "Favoris")83 case .inbox: return String(localized: "Boîte de réception")84 case .archived: return String(localized: "Archives")85 case .trash: return String(localized: "Corbeille")86 }87 }8889 var symbol: String {90 switch self {91 case .all: return "note.text"92 case .recent: return "clock"93 case .pinned: return "pin"94 case .favorites: return "star"95 case .inbox: return "tray"96 case .archived: return "archivebox"97 case .trash: return "trash"98 }99 }100}101102/// The tabs of the iPhone interface. `capture` is an action, never a selection.103enum ShellTab: String, CaseIterable, Hashable, Sendable {104 case today, notes, capture, search, more105106 var title: String {107 switch self {108 case .today: return String(localized: "Aujourd’hui")109 case .notes: return String(localized: "Notes")110 case .capture: return String(localized: "Capture")111 case .search: return String(localized: "Recherche")112 case .more: return String(localized: "Plus")113 }114 }115116 var symbol: String {117 switch self {118 case .today: return "sun.max"119 case .notes: return "note.text"120 case .capture: return "plus.circle.fill"121 case .search: return "magnifyingglass"122 case .more: return "ellipsis.circle"123 }124 }125126 /// The tabs that hold a navigation stack.127 static let destinations: [ShellTab] = [.today, .notes, .search, .more]128}129130/// A screen pushed on a navigation stack of the iPhone interface.131enum Destination: Hashable {132 case list(NoteSource)133 case folders134 case tags135 case search(String)136 case note(String, isNew: Bool)137 case tasks138 case inbox139 /// A section hosted from `SPNotesFeatures` (`HostedSection.id`).140 case hosted(String)141}142143/// What the iPad sidebar selects — also the typed "place" of a window, whatever its layout.144enum SidebarItem: Hashable, Sendable {145 case source(NoteSource)146 case search147 case today148 case tasks149 case inbox150 case hosted(String)151152 var storageKey: String {153 switch self {154 case .source(let source): return source.storageKey155 case .search: return "search"156 case .today: return "today"157 case .tasks: return "tasks"158 case .inbox: return "inbox"159 case .hosted(let id): return "hosted:\(id)"160 }161 }162163 init?(storageKey: String) {164 switch storageKey {165 case "search": self = .search166 case "today": self = .today167 case "tasks": self = .tasks168 case "inbox": self = .inbox169 default:170 if storageKey.hasPrefix("hosted:") {171 let id = String(storageKey.dropFirst("hosted:".count))172 guard !id.isEmpty else { return nil }173 self = .hosted(id)174 return175 }176 guard let source = NoteSource(storageKey: storageKey) else { return nil }177 self = .source(source)178 }179 }180}181182enum ShellSheet: Identifiable {183 case move([String])184 case tags([String])185 case settings186 case syncDetails187 case newFolder(parentId: String?, section: String)188 case renameFolder(id: String, title: String)189190 var id: String {191 switch self {192 case .move(let ids): return "move:" + ids.joined(separator: ",")193 case .tags(let ids): return "tags:" + ids.joined(separator: ",")194 case .settings: return "settings"195 case .syncDetails: return "sync"196 case .newFolder(let parent, let section): return "new-folder:\(parent ?? section)"197 case .renameFolder(let id, _): return "rename:\(id)"198 }199 }200}201202/// A short confirmation at the bottom of the window, optionally with an undo.203struct Toast: Identifiable {204 let id = UUID()205 var message: String206 var actionTitle: String?207 var action: (@MainActor () -> Void)?208}209210/// "Show this block of the note": the token makes two requests for the same block distinct.211struct NoteReveal: Equatable, Sendable {212 var blockId: String213 var token: Int214}215216/// A request to capture something (the centre button, ⌥⌘N, `spnotes://capture`, the palette). See `CaptureHook`.217struct ShellCaptureRequest: Equatable, Sendable {218 var kind: String?219 var token: Int220}221222@MainActor223@Observable224final class ShellState {225 /// True when the window is narrow (iPhone, iPad Slide Over): tabs, one navigation stack per tab.226 var isCompact = true227 // iPhone228 var tab: ShellTab = .today { didSet { if tab != oldValue { navigated = true } } }229 /// One navigation path per tab: switching tabs keeps each stack where it was.230 var paths: [ShellTab: [Destination]] = [.notes: [.list(.smart(.all))]] { didSet { if paths != oldValue { navigated = true } } }231 // iPad232 var sidebar: SidebarItem? = .source(.smart(.all))233 var selectedNote: String?234 var searchQuery = ""235 /// Notes just created in this window: the editor opens them ready to type.236 private(set) var freshNotes: Set<String> = []237 /// Per note, the block to scroll to (deep links, citations, backlinks, tasks). Kept across compact/regular adaptation.238 private(set) var reveals: [String: NoteReveal] = [:]239 private var revealCounter = 0240241 var sheet: ShellSheet?242 var toast: Toast?243 var isPaletteOpen = false244 /// What a hosted section should show when it appears (set by `ShellFeatureRouter.openDatabase / openCanvas`).245 var pendingHostedItem: HostedItem?246 /// In a note window: the note the window is for (the root of its stack).247 var rootNote: String?248 private(set) var captureRequest: ShellCaptureRequest?249 /// The Quick Capture sheet of this window (Features/Capture), presented by `MainInterface`.250 var quickCapture: CaptureRequest?251 /// The sections hosted from `SPNotesFeatures` (empty until their screens are registered).252 @ObservationIgnored var sections: HostedSectionRegistry253 /// The router of this window for the hosted screens. They hold it weakly: the shell keeps it alive.254 @ObservationIgnored private var hostedRouter: ShellFeatureRouter?255 func featureRouter(app: AppModel) -> ShellFeatureRouter {256 if let hostedRouter { return hostedRouter }257 let router = ShellFeatureRouter(shell: self, app: app)258 hostedRouter = router259 return router260 }261 /// False until the user (or a route, or a restoration) navigated: the first adaptation then keeps each layout's default place.262 @ObservationIgnored private var navigated = false263264 init(sections: HostedSectionRegistry? = nil) { self.sections = sections ?? .shared }265266 /// The navigation path of the selected tab (iPhone).267 var path: [Destination] {268 get { paths[tab] ?? [] }269 set { paths[tab] = newValue }270 }271272 // MARK: navigation273274 func open(note id: String, isNew: Bool = false, blockId: String? = nil) {275 navigated = true276 if isNew { freshNotes.insert(id) }277 if let blockId, !blockId.isEmpty {278 revealCounter += 1279 reveals[id] = NoteReveal(blockId: blockId, token: revealCounter)280 }281 if isCompact {282 if tab == .capture { tab = .notes }283 if id == rootNote { path = []; return } // a note window asked for its own note: back to it284 if case .note(id, _)? = path.last { return }285 path.append(.note(id, isNew: isNew))286 } else {287 selectedNote = id288 }289 }290291 func isFresh(_ id: String) -> Bool { freshNotes.contains(id) }292 func reveal(for id: String) -> NoteReveal? { reveals[id] }293294 func open(source: NoteSource) {295 navigated = true296 if isCompact { path.append(.list(source)) } else { sidebar = .source(source); selectedNote = nil }297 }298299 /// Goes to a list: back to it when it is already in the stack (breadcrumb), otherwise forward.300 func jump(to source: NoteSource) {301 if isCompact, let index = path.lastIndex(of: .list(source)) { path.removeSubrange((index + 1)...) } else { open(source: source) }302 }303304 func openSearch(_ query: String = "") {305 navigated = true306 searchQuery = query307 if isCompact {308 tab = .search309 paths[.search] = []310 } else {311 sidebar = .search312 }313 }314315 /// Goes to a place of the app, whatever the layout (routes, command palette, ⌘1…9, the « Plus » list).316 func go(to item: SidebarItem) {317 navigated = true318 if case .search = item { openSearch(searchQuery); return }319 if isCompact {320 let (tab, path) = Self.compactPlace(for: item)321 self.tab = tab322 paths[tab] = path323 } else {324 sidebar = item325 }326 }327328 /// The place shown, whatever the layout (state restoration, adaptation, the menus' check marks).329 var location: SidebarItem? {330 guard isCompact else { return sidebar }331 return Self.place(tab: tab, path: path)332 }333334 /// The note shown, whatever the layout.335 var currentNote: String? {336 guard isCompact else { return selectedNote }337 for destination in path.reversed() { if case .note(let id, _) = destination { return id } }338 return nil339 }340341 /// The note left the list it was shown from (trashed, purged): stop showing it.342 func close(note id: String) {343 if selectedNote == id { selectedNote = nil }344 for tab in paths.keys { paths[tab]?.removeAll { if case .note(id, _) = $0 { return true } else { return false } } }345 reveals[id] = nil346 }347348 /// The source in which a new note should be created, from what the window shows.349 var currentSource: NoteSource? {350 if isCompact {351 for destination in path.reversed() { if case .list(let source) = destination { return source } }352 return nil353 }354 if case .source(let source)? = sidebar { return source }355 return nil356 }357358 func show(_ message: String, actionTitle: String? = nil, action: (@MainActor () -> Void)? = nil) {359 toast = Toast(message: message, actionTitle: actionTitle, action: action)360 }361362 /// Asks for a capture (see `CaptureHook`): the one entry point of the centre button, ⌥⌘N, the palette and `spnotes://capture`.363 func requestCapture(kind: String? = nil) {364 revealCounter += 1365 captureRequest = ShellCaptureRequest(kind: kind, token: revealCounter)366 }367368 // MARK: places369370 /// Where a place lives in the iPhone tabs.371 static func compactPlace(for item: SidebarItem) -> (ShellTab, [Destination]) {372 switch item {373 case .today: return (.today, [])374 case .source(let source): return (.notes, [.list(source)])375 case .search: return (.search, [])376 case .tasks: return (.more, [.tasks])377 case .inbox: return (.more, [.inbox])378 case .hosted(let id): return (.more, [.hosted(id)])379 }380 }381382 /// The place a tab and its path show (nil: a screen that is not a place of its own, such as the « Plus » list).383 static func place(tab: ShellTab, path: [Destination]) -> SidebarItem? {384 for destination in path.reversed() {385 switch destination {386 case .list(let source): return .source(source)387 case .search: return .search388 case .tasks: return .tasks389 case .inbox: return .inbox390 case .hosted(let id): return .hosted(id)391 case .note, .folders, .tags: continue392 }393 }394 switch tab {395 case .today: return .today396 case .notes: return .source(.smart(.all))397 case .search: return .search398 case .more, .capture: return nil399 }400 }401402 // MARK: restoration403404 /// Puts a window back where it was (`@SceneStorage`): the place, then the note.405 func restore(location: SidebarItem?, note: String?) {406 if let location {407 if isCompact {408 let (tab, path) = Self.compactPlace(for: location)409 self.tab = tab410 paths[tab] = path411 if case .search = location { paths[.search] = [] }412 } else {413 sidebar = location414 }415 navigated = true416 }417 if let note, currentNote == nil { open(note: note) }418 }419420 // MARK: size class changes421422 /// Carries what is shown from one layout to the other when the window is resized across the compact/regular limit423 /// (Split View, Slide Over, Stage Manager): the place, the note and its pending block, the search text.424 func adapt(toCompact compact: Bool) {425 guard compact != isCompact else { return }426 let note = currentNote427 let place = location428 isCompact = compact429 guard navigated else { return } // nothing shown yet: each layout starts at its own default place430 if compact {431 if let place {432 let (tab, path) = Self.compactPlace(for: place)433 self.tab = tab434 paths[tab] = path435 }436 if let note { path.append(.note(note, isNew: false)) }437 } else {438 if let place { sidebar = place } else if sidebar == nil { sidebar = .source(.smart(.all)) }439 selectedNote = note440 // the stacks are rebuilt from the place when the window gets narrow again441 for tab in paths.keys { paths[tab]?.removeAll { if case .note = $0 { return true } else { return false } } }442 }443 }444}445