SPB Git

Repository Public

LibraryModel.swift 11.9 KB 197 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Home/LibraryModel.swift3// Description: Observable picture of the library for the sidebar and the note list (smart lists, sections, folders, tags, search) and every organisational action, all against the local store.4import SwiftUI5import SPNotesDocument6import SPNotesStore7import SPNotesSync89enum SidebarItem: Hashable {10    case list(SmartList), section(String), folder(String), tag(String), unsynced11}1213struct FolderNode: Identifiable, Hashable {14    var id: String { page.id }15    var page: PageSummary16    var children: [FolderNode]?17    static func == (a: FolderNode, b: FolderNode) -> Bool { a.page == b.page && a.children == b.children }18    func hash(into h: inout Hasher) { h.combine(page.id) }19}2021@Observable final class LibraryModel {22    var selection: SidebarItem = .list(.all) { didSet { if selection != oldValue { Task { await reloadNotes() } } } }23    var query = "" { didSet { if query != oldValue { scheduleSearch() } } }24    private(set) var notes: [PageSummary] = []25    private(set) var hits: [SearchHit]?26    private(set) var counts = Counts()27    /// Sidebar counters (the store's `ListCounts`, copied into a type the app can create empty).28    struct Counts: Equatable { var all = 0, pinned = 0, favorites = 0, inbox = 0, archived = 0, trash = 0, pending = 0, conflicts = 029        init() {}30        init(_ c: ListCounts) { all = c.all; pinned = c.pinned; favorites = c.favorites; inbox = c.inbox; archived = c.archived; trash = c.trash; pending = c.pending; conflicts = c.conflicts } }31    private(set) var tags: [TagInfo] = []32    private(set) var folders: [FolderNode] = []33    private(set) var isLoaded = false34    @ObservationIgnored weak var env: AppEnvironment?35    /// False for the per-window instances: only the shared model tells the open notes and the caches about store changes.36    @ObservationIgnored var notifiesSessions = true37    @ObservationIgnored private var didStart = false38    @ObservationIgnored private let store: NotesStore39    @ObservationIgnored private let preferences: Preferences40    @ObservationIgnored private var watcher: Task<Void, Never>?41    @ObservationIgnored private var reloadTask: Task<Void, Never>?42    @ObservationIgnored private var searchTask: Task<Void, Never>?4344    static let sections: [(id: String, label: String, symbol: String)] = [("notes", "Notes", "note.text"), ("documents", "Documents", "doc.text"), ("projects", "Projets", "folder.badge.gearshape"), ("research", "Recherche", "graduationcap")]4546    init(store: NotesStore, preferences: Preferences) { self.store = store; self.preferences = preferences }4748    func start() async {49        guard !didStart else { return }; didStart = true50        await reload()51        watcher = Task { [weak self] in52            guard let self else { return }53            for await change in await self.store.changes() { self.handle(change) }54        }55    }5657    private func handle(_ change: StoreChange) {58        switch change {59        case .pages(let ids):60            if notifiesSessions { for id in ids { if let s = env?.existingSession(id) { Task { await s.storeChanged() } } }; env?.platform.pagesChanged(Array(ids)) }61            scheduleReload()62        case .reset: if notifiesSessions { for s in env?.openSessions ?? [] { Task { await s.storeChanged() } }; env?.platform.libraryReset() }; scheduleReload()63        case .tags, .conflicts, .queue: scheduleReload()64        case .attachments: if notifiesSessions { ImageCache.shared.noteFilesChanged() }65        default: break66        }67    }68    private func scheduleReload() {69        reloadTask?.cancel()70        reloadTask = Task { [weak self] in try? await Task.sleep(for: .milliseconds(120)); if !Task.isCancelled { await self?.reload() } }71    }7273    func reload() async {74        if let c = try? await store.counts() { counts = Counts(c) }75        tags = (try? await store.tags()) ?? tags76        let flat = (try? await store.folderTree()) ?? []77        folders = Self.tree(flat)78        await reloadNotes()79        isLoaded = true80    }8182    static func tree(_ flat: [PageSummary]) -> [FolderNode] {83        let ids = Set(flat.map(\.id))84        var byParent: [String?: [PageSummary]] = [:]85        for p in flat { byParent[p.parentId.flatMap { ids.contains($0) ? $0 : nil }, default: []].append(p) }86        func build(_ parent: String?, depth: Int) -> [FolderNode] {87            guard depth < 12 else { return [] }88            return (byParent[parent] ?? []).sorted { $0.position < $1.position }.map { p in let kids = build(p.id, depth: depth + 1); return FolderNode(page: p, children: kids.isEmpty ? nil : kids) }89        }90        return build(nil, depth: 0)91    }9293    func reloadNotes() async {94        if !query.trimmingCharacters(in: .whitespaces).isEmpty { await runSearch(); return }95        hits = nil96        var list: [PageSummary]97        switch selection {98        case .list(let l): list = (try? await store.summaries(list: l, limit: 2000)) ?? []99        case .section(let s): list = (try? await store.summaries(list: .all, section: s, limit: 2000)) ?? []100        case .folder(let id): list = (try? await store.children(of: id)) ?? []101        case .tag(let t): list = (try? await store.summaries(tag: t, limit: 2000)) ?? []102        case .unsynced:103            list = []104            for p in (try? await store.pagesNeedingPush(limit: 500, includeConflicts: true)) ?? [] { if let s = try? await store.summary(id: p.page.id) { list.append(s) } }105        }106        notes = sorted(list)107    }108    private func sorted(_ list: [PageSummary]) -> [PageSummary] {109        if case .list(.recent) = selection { return list }110        if case .list(.trash) = selection { return list }111        let pinnedFirst: (PageSummary, PageSummary) -> Bool? = { a, b in a.pinned == b.pinned ? nil : a.pinned }112        switch preferences.sort {113        case .modified: return list.sorted { pinnedFirst($0, $1) ?? ($0.updatedAt > $1.updatedAt) }114        case .title: return list.sorted { pinnedFirst($0, $1) ?? ($0.title.localizedStandardCompare($1.title) == .orderedAscending) }115        case .manual: return list.sorted { pinnedFirst($0, $1) ?? ($0.position < $1.position) }116        }117    }118    func sortChanged() { notes = sorted(notes) }119120    // MARK: Search121122    var filters = SearchFilters() { didSet { if filters != oldValue { scheduleSearch() } } }123    private func scheduleSearch() {124        searchTask?.cancel()125        searchTask = Task { [weak self] in try? await Task.sleep(for: .milliseconds(90)); if !Task.isCancelled { await self?.reloadNotes() } }126    }127    private func runSearch() async {128        var f = filters129        switch selection {130        case .section(let s): f.section = f.section ?? s131        case .folder(let id): f.folderId = f.folderId ?? id132        case .tag(let t): if !f.tags.contains(t) { f.tags.append(t) }133        case .list(.favorites): f.favoritesOnly = true134        case .list(.pinned): f.pinnedOnly = true135        case .list(.archived): f.includeArchived = true136        case .list(.trash): f.includeTrash = true137        default: break138        }139        let q = query140        let result = (try? await store.search(query: q, filters: f, limit: 200)) ?? []141        guard q == query else { return }142        hits = result; notes = result.map(\.page)143    }144    /// Notes whose title matches, for the « @ » menu and the quick-open palette.145    func quickFind(_ text: String, limit: Int = 12) async -> [PageSummary] {146        if text.trimmingCharacters(in: .whitespaces).isEmpty { return Array(((try? await store.summaries(list: .recent, limit: limit)) ?? []).prefix(limit)) }147        return ((try? await store.search(query: text, limit: limit)) ?? []).map(\.page)148    }149150    // MARK: Actions (all local first; the sync engine sends them)151152    private func changed() { env?.syncMonitor.localChange() }153    private func report(_ error: Error) { env?.toasts.error(error) }154155    @discardableResult156    func newNote(title: String = "", content: NoteDocument? = nil, parentId: String? = nil, asFolder: Bool = false, tags: [String] = [], inbox: Bool = false) async -> String? {157        guard env?.isBlocked != true else { return nil }   // the database is not open: nothing may be written158        var parent = parentId; var section: String?159        if parent == nil, !inbox { switch selection { case .folder(let id): parent = id; case .section(let s): section = s; default: break } }160        var doc = content ?? NoteDocument(); doc.ensureBlockIds()161        let digest = ContentDigest(document: doc)162        var allTags = tags; if case .tag(let t) = selection, !inbox { allTags.append(t) }163        let draft = NewPage(parentId: parent, section: section, title: title, icon: asFolder ? "📁" : nil, content: (try? doc.jsonData()) ?? NewPage.emptyDocument, properties: Data(asFolder ? #"{"folder":true}"#.utf8 : "{}".utf8), plainText: digest.plainText, wordCount: digest.wordCount, preview: digest.preview, tags: allTags, inboxAt: inbox ? Date() : nil, captureKind: inbox ? "note" : nil)164        do { let p = try await store.createPage(draft); changed(); return p.id } catch { report(error); return nil }165    }166    func trash(_ ids: [String]) async { for id in ids { await env?.existingSession(id)?.saveNow(reason: nil); do { _ = try await store.trash(id: id) } catch { report(error) } }; changed() }167    func restore(_ ids: [String]) async { for id in ids { do { _ = try await store.restore(id: id) } catch { report(error) } }; changed() }168    /// Permanent deletion. The local copy goes at once; the server asks for a fresh passkey when the action is sent.169    func purge(_ ids: [String]) async {170        for id in ids {171            do { let r = try await store.purge(id: id); for f in r.orphanedFiles { env?.files.remove(relativePath: f) }; for p in r.pageIds { env?.forget(noteId: p) } } catch { report(error) }172        }173        changed()174    }175    func duplicate(_ id: String) async -> String? { await env?.existingSession(id)?.saveNow(reason: nil); do { let p = try await store.duplicate(id: id); changed(); return p.id } catch { report(error); return nil } }176    func setPinned(_ id: String, _ on: Bool) async { do { _ = try await store.setPinned(id: id, on); changed() } catch { report(error) } }177    func setFavorite(_ id: String, _ on: Bool) async { await env?.existingSession(id)?.saveNow(reason: nil); do { _ = try await store.setFavorite(id: id, on); changed() } catch { report(error) } }178    func setArchived(_ id: String, _ on: Bool) async { do { _ = try await store.setArchived(id: id, on); changed() } catch { report(error) } }179    func setFolder(_ id: String, _ on: Bool) async { await env?.existingSession(id)?.saveNow(reason: nil); do { _ = try await store.setFolder(id: id, on); changed() } catch { report(error) } }180    func setIcon(_ id: String, _ icon: String?) async { do { _ = try await store.setIcon(id: id, icon); changed() } catch { report(error) } }181    func setTags(_ id: String, _ names: [String]) async { do { _ = try await store.setTags(id: id, names: names); changed() } catch { report(error) } }182    func rename(_ id: String, to title: String) async {183        if let s = env?.existingSession(id) { s.title = title; await s.saveNow(reason: nil); return }184        guard let p = try? await store.page(id: id) else { return }185        do { _ = try await store.updateContent(id: id, title: title, plainText: p.plainText, wordCount: p.wordCount, preview: p.preview); changed() } catch { report(error) }186    }187    /// Moves notes into a folder (nil = top level) or a section. A note is never moved into itself or its descendants.188    func move(_ ids: [String], toParent parent: String?, section: String? = nil) async {189        for id in ids where id != parent {190            if let parent, let chain = try? await store.ancestors(of: parent), chain.contains(where: { $0.id == id }) { continue }191            do { _ = try await store.move(id: id, parentId: parent, section: section) } catch { report(error) }192        }193        changed()194    }195    func emptyTrash() async { let all = (try? await store.summaries(list: .trash, limit: 5000)) ?? []; await purge(all.map(\.id)) }196}197
Files main
Menu

Theme