SPB Git

Repository Public

NoteListView.swift 13.5 KB 198 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/NoteListView.swift3// Description: Middle column: the notes of the selected list with search, filters, sorting, multi-selection, drag to folders and contextual actions.4import SwiftUI5import SPNotesStore6import SPNotesDesign7import UniformTypeIdentifiers89struct NoteListView: View {10    @Environment(AppEnvironment.self) private var env11    @Environment(WindowModel.self) private var window12    @FocusState private var searchFocused: Bool13    @State private var confirmPurge: [String] = []14    @State private var showFilters = false1516    var body: some View {17        @Bindable var window = window18        @Bindable var library = window.library19        VStack(spacing: 0) {20            searchField21            if showFilters { SearchFilterBar().transition(.opacity) }22            Divider().overlay(NVColor.line)23            if library.notes.isEmpty { emptyState }24            else {25                List(selection: $window.selectedNotes) {26                    ForEach(library.notes) { note in27                        NoteRow(note: note, hit: library.hits?.first { $0.id == note.id })28                            .tag(note.id)29                            .draggable(NoteDragItem(id: note.id, title: Format.title(note.title)))30                            .contextMenu { menu(for: note) }31                            .swipeActions(edge: .trailing) { Button(role: .destructive) { Task { await delete([note.id]) } } label: { Label("Supprimer", systemImage: "trash") } }32                    }33                }34                .listStyle(.inset)35                .onDeleteCommand { Task { await delete(Array(window.selectedNotes)) } }36                .accessibilityIdentifier("note-list")37            }38        }39        .navigationTitle(title)40        .toolbar {41            ToolbarItem {42                Menu {43                    Picker("Trier par", selection: Binding(get: { env.preferences.sort }, set: { env.preferences.sort = $0; library.sortChanged() })) { ForEach(NoteSort.allCases) { Text($0.label).tag($0) } }.pickerStyle(.inline)44                    Divider()45                    Toggle("Filtres de recherche", isOn: $showFilters.animation())46                } label: { Label("Trier et filtrer", systemImage: "line.3.horizontal.decrease.circle") }.help("Trier et filtrer")47            }48            ToolbarItem { Button { window.newNote() } label: { Label("Nouvelle note", systemImage: "square.and.pencil") }.help("Nouvelle note (⌘N)").accessibilityIdentifier("new-note") }49        }50        .onChange(of: window.focusSearch) { _, _ in searchFocused = true }51        .confirmationDialog(confirmPurge.count == 1 ? "Supprimer définitivement cette note ?" : "Supprimer définitivement \(confirmPurge.count) notes ?", isPresented: Binding(get: { !confirmPurge.isEmpty }, set: { if !$0 { confirmPurge = [] } })) {52            Button("Supprimer définitivement", role: .destructive) { let ids = confirmPurge; confirmPurge = []; Task { await window.library.purge(ids); window.selectedNotes.subtract(ids) } }53        } message: { Text("La note, ses sous-notes et ses fichiers disparaissent de ce Mac tout de suite, et du serveur à la prochaine synchronisation (une confirmation par clé d'accès sera demandée). Cette action est irréversible.") }54    }5556    private var title: String {57        switch window.library.selection {58        case .list(let l): [.all: "Toutes les notes", .recent: "Récentes", .pinned: "Épinglées", .favorites: "Favoris", .inbox: "Boîte de réception", .archived: "Archives", .trash: "Corbeille"][l] ?? "Notes"59        case .section(let s): LibraryModel.sections.first { $0.id == s }?.label ?? s60        case .folder(let id): flatFolders(window.library.folders).first { $0.id == id }.map { Format.title($0.title) } ?? "Dossier"61        case .tag(let t): "#" + t62        case .unsynced: "À synchroniser"63        }64    }65    private func flatFolders(_ nodes: [FolderNode]) -> [PageSummary] { nodes.flatMap { [$0.page] + flatFolders($0.children ?? []) } }6667    private var searchField: some View {68        @Bindable var library = window.library69        return HStack(spacing: NVSpace.sm) {70            Image(systemName: "magnifyingglass").foregroundStyle(NVColor.fgMuted)71            TextField("Rechercher", text: $library.query).textFieldStyle(.plain).focused($searchFocused)72                .onExitCommand { library.query = ""; searchFocused = false }73                .accessibilityIdentifier("search-field")74            if !library.query.isEmpty { Button { library.query = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(NVColor.fgMuted) }.buttonStyle(.plain).help("Effacer") }75        }76        .fieldSurface(focused: searchFocused)77        .padding(.horizontal, NVSpace.md).padding(.vertical, NVSpace.sm)78    }7980    @ViewBuilder private var emptyState: some View {81        if !window.library.query.isEmpty { EmptyState(symbol: "magnifyingglass", title: "Aucun résultat", message: "Aucune note ne contient « \(window.library.query) » dans cette liste.") }82        else if case .list(.trash) = window.library.selection { EmptyState(symbol: "trash", title: "Corbeille vide", message: "Les notes supprimées restent ici jusqu'à leur suppression définitive.") }83        else if !window.library.isLoaded { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }84        else { EmptyState(symbol: "note.text", title: "Aucune note ici", message: "Crée une note : elle est enregistrée sur ce Mac à chaque frappe, avec ou sans réseau.", action: ("Nouvelle note", { window.newNote() })) }85    }8687    private func delete(_ ids: [String]) async {88        guard !ids.isEmpty else { return }89        if case .list(.trash) = window.library.selection { confirmPurge = ids } else { await window.library.trash(ids); window.selectedNotes.subtract(ids); env.toasts.show(ids.count == 1 ? "Note placée dans la corbeille" : "\(ids.count) notes placées dans la corbeille", symbol: "trash") }90    }9192    @ViewBuilder private func menu(for note: PageSummary) -> some View {93        let ids = window.selectedNotes.contains(note.id) ? Array(window.selectedNotes) : [note.id]94        if note.deletedAt != nil {95            Button("Restaurer") { Task { await window.library.restore(ids) } }96            Button("Supprimer définitivement…", role: .destructive) { confirmPurge = ids }97        } else {98            Button("Ouvrir dans une nouvelle fenêtre") { OpenNoteWindow.open?(note.id) }99            Divider()100            Button(note.favorite ? "Retirer des favoris" : "Ajouter aux favoris") { Task { for id in ids { await window.library.setFavorite(id, !note.favorite) } } }101            Button(note.pinned ? "Désépingler" : "Épingler en haut") { Task { for id in ids { await window.library.setPinned(id, !note.pinned) } } }102            Button(note.archived ? "Désarchiver" : "Archiver") { Task { for id in ids { await window.library.setArchived(id, !note.archived) } } }103            Button(note.isFolder ? "Ne plus traiter comme un dossier" : "Transformer en dossier") { Task { await window.library.setFolder(note.id, !note.isFolder) } }104            Menu("Déplacer vers") {105                Button("Premier niveau") { Task { await window.library.move(ids, toParent: nil) } }106                ForEach(LibraryModel.sections, id: \.id) { s in Button("Espace « \(s.label) »") { Task { await window.library.move(ids, toParent: nil, section: s.id) } } }107                Divider()108                ForEach(flatFolders(window.library.folders).filter { !ids.contains($0.id) }.prefix(40)) { f in Button(f.title.isEmpty ? "Sans titre" : f.title) { Task { await window.library.move(ids, toParent: f.id) } } }109            }110            Button("Dupliquer") { Task { if let id = await window.library.duplicate(note.id) { window.open(id) } } }111            Menu("Exporter") { ForEach(ExportFormat.allCases) { f in Button(f.label) { Task { await Exporter(env: env).export(noteIds: ids, format: f) } } } }112            Divider()113            Button("Placer dans la corbeille", role: .destructive) { Task { await delete(ids) } }114        }115    }116}117118struct NoteRow: View {119    let note: PageSummary120    let hit: SearchHit?121    var body: some View {122        VStack(alignment: .leading, spacing: NVSpace.xs) {123            HStack(spacing: NVSpace.xs + NVSpace.xxs) {124                if let icon = note.icon, !icon.isEmpty { Text(icon).nvFont(.ui) }125                Group { if let hit, !hit.highlightedTitle.isEmpty { HighlightedText(marked: hit.highlightedTitle) } else { Text(displayTitle) } }126                    .font(NVFont.font(.h3, size: NVFont.Style.body.size())).lineLimit(1)127                Spacer(minLength: NVSpace.xs)128                if note.type == "canvas" { Image(systemName: "square.on.square.dashed").font(NVFont.fixed(.micro)).foregroundStyle(NVColor.fgMuted).help("Canvas") }129                if note.pinned { Image(systemName: "pin.fill").font(NVFont.fixed(.micro)).foregroundStyle(NVColor.fgMuted) }130                if note.favorite { Image(systemName: "star.fill").font(NVFont.fixed(.micro)).foregroundStyle(NVColor.warning) }131                SyncDot(state: note.syncState)132            }133            (Text(Format.short(note.updatedAt) + "  ").foregroundStyle(NVColor.fg.opacity(0.75)) + previewText.foregroundStyle(NVColor.fgMuted))134                .nvFont(.ui).lineLimit(2).fixedSize(horizontal: false, vertical: true)135            if !note.tags.isEmpty { Text(note.tags.prefix(4).map { "#" + $0 }.joined(separator: "  ")).nvFont(.micro).foregroundStyle(NVColor.accent).lineLimit(1) }136        }137        .padding(.vertical, NVSpace.xs)138        .accessibilityElement(children: .combine)139        .accessibilityLabel("\(displayTitle), modifiée \(Format.short(note.updatedAt))")140    }141    private var previewText: Text {142        if let hit, !hit.snippet.isEmpty { return SearchHit.segments(of: hit.snippet.replacingOccurrences(of: "\n", with: " ")).reduce(Text("")) { $0 + ($1.highlighted ? Text($1.text).bold().foregroundStyle(NVColor.accent) : Text($1.text)) } }143        return Text(note.preview.isEmpty ? "Aucun texte" : note.preview.replacingOccurrences(of: "\n", with: " "))144    }145    private var displayTitle: String { Format.title(note.title) }146}147148/// A note dragged out of the list: its id inside the app (folders, spaces), a Markdown file for the Finder and other apps.149struct NoteDragItem: Transferable, Codable {150    let id: String, title: String151    static var transferRepresentation: some TransferRepresentation {152        ProxyRepresentation(exporting: \.id)153        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { item in154            let url = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-drag-\(UUID().uuidString)", isDirectory: true)155            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)156            let file = url.appendingPathComponent(await NoteDragExport.fileName(item.title) + ".md")157            let data = await NoteDragExport.markdown(id: item.id)158            try (data ?? Data()).write(to: file)159            return SentTransferredFile(file)160        }161    }162}163@MainActor enum NoteDragExport {164    static func fileName(_ title: String) -> String { Exporter.fileName(title) }165    /// Markdown of a note with its front matter, as « Exporter en Markdown » writes it (pending typing is saved first).166    static func markdown(id: String) async -> Data? {167        guard let env = AppDelegate.environment, !env.isBlocked else { return nil }168        await env.existingSession(id)?.saveNow(reason: nil)169        guard let page = try? await env.store.page(id: id) else { return nil }170        return await Exporter(env: env).data(for: page, format: .markdown)171    }172}173174/// Combined filters of the local search (space, tag, dates, favourites).175struct SearchFilterBar: View {176    @Environment(AppEnvironment.self) private var env177    @Environment(WindowModel.self) private var window178    var body: some View {179        @Bindable var library = window.library180        ScrollView(.horizontal, showsIndicators: false) {181            HStack(spacing: 8) {182                Picker("Espace", selection: $library.filters.section) { Text("Tous les espaces").tag(String?.none); ForEach(LibraryModel.sections, id: \.id) { Text($0.label).tag(String?.some($0.id)) } }.labelsHidden().fixedSize()183                Menu(library.filters.tags.isEmpty ? "Tags" : library.filters.tags.map { "#" + $0 }.joined(separator: " ")) {184                    ForEach(library.tags) { t in Toggle(t.name, isOn: Binding(get: { library.filters.tags.contains(t.name) }, set: { on in if on { library.filters.tags.append(t.name) } else { library.filters.tags.removeAll { $0 == t.name } } })) }185                }.fixedSize()186                Picker("Période", selection: Binding(get: { period }, set: { setPeriod($0) })) { Text("Toutes dates").tag(0); Text("7 jours").tag(7); Text("30 jours").tag(30); Text("1 an").tag(365) }.labelsHidden().fixedSize()187                Toggle("Favoris", isOn: $library.filters.favoritesOnly).toggleStyle(.button)188                Toggle("Archives", isOn: $library.filters.includeArchived).toggleStyle(.button)189            }190            .controlSize(.small).padding(.horizontal, NVSpace.md).padding(.bottom, NVSpace.sm)191        }192    }193    private var period: Int { guard let d = window.library.filters.updatedAfter else { return 0 }; let days = Int(Date().timeIntervalSince(d) / 86_400 + 0.5); return [7, 30, 365].min { abs($0 - days) < abs($1 - days) } ?? 0 }194    private func setPeriod(_ days: Int) { window.library.filters.updatedAfter = days == 0 ? nil : Calendar.current.date(byAdding: .day, value: -days, to: Date()) }195}196197enum OpenNoteWindow { @MainActor static var open: ((String) -> Void)? }198
Files main
Menu

Theme