Repository Public
1// SP Notes iOS2// File: Features/Notes/NoteListView.swift3// Description: The list of notes of one source (smart list, section, folder, tag): paged rows, sort, pull to refresh, swipes,4// context menu, multiple selection with bulk actions, drag and drop, and the specific actions of the inbox,5// the archive and the trash.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SwiftUI1112struct NoteListView: View {13 let source: NoteSource1415 @Environment(AppModel.self) private var app16 @Environment(ShellState.self) private var shell17 @Environment(\.supportsMultipleWindows) private var supportsMultipleWindows18 @Environment(\.openWindow) private var openWindow19 @AppStorage("list.sort") private var sortRaw = NoteSort.modified.rawValue20 @State private var model: NoteListModel21 @State private var isSelecting = false22 @State private var selection: Set<String> = []23 @State private var purgeRequest: PurgeRequest?24 @State private var trashedChoice: PageSummary?25 @State private var folderDeletion: FolderDeletion?26 @State private var confirmEmptyTrash = false27 @State private var isConfirmingDeletions = false2829 struct PurgeRequest: Identifiable { let id = UUID(); var ids: [String]; var all = false }30 struct FolderDeletion: Identifiable { let id = UUID(); var folder: PageSummary; var count: Int }3132 init(source: NoteSource) {33 self.source = source34 _model = State(initialValue: NoteListModel(source: source))35 }3637 private var commands: NoteCommands { NoteCommands(app: app, shell: shell) }38 private var sort: NoteSort { NoteSort(rawValue: sortRaw) ?? .modified }39 private var isTrash: Bool { source == .smart(.trash) }40 private var isArchive: Bool { source == .smart(.archived) }41 private var isInbox: Bool { source == .smart(.inbox) }42 private var canCreate: Bool {43 switch source {44 case .smart(.all), .smart(.favorites), .folder, .tag: return !model.missing45 case .section(let section): return NoteSection.editable.contains(section)46 default: return false47 }48 }49 private struct ReloadKey: Equatable { var revision: Int; var sort: String }5051 var body: some View {52 List {53 if isTrash, app.syncStatus.needsReauth { reauthBanner }54 if shell.isCompact, case .folder = source, model.folder != nil { breadcrumb }55 if !model.folders.isEmpty {56 Section {57 ForEach(model.folders) { folder in folderRow(folder) }58 } header: {59 if !model.notes.isEmpty { Text("Dossiers") }60 }61 }62 Section {63 ForEach(Array(model.notes.enumerated()), id: \.element.id) { index, note in64 row(note).fluidSource(id: note.id).livingRow(index: index, isSelecting: isSelecting)65 }66 if model.hasMore {67 HStack { Spacer(); ProgressView(); Spacer() }68 .listRowSeparator(.hidden)69 .id(model.notes.count)70 .task(id: model.notes.count) { await model.loadMore(store: app.store) }71 }72 } header: {73 if !model.folders.isEmpty, !model.notes.isEmpty { Text("Notes") }74 }75 }76 .listStyle(.plain)77 .scrollContentBackground(.hidden)78 .background(Color.spBackground)79 .overlay { if model.isEmpty { emptyState } }80 .refreshable { await app.syncAndWait() }81 .navigationTitle(isSelecting ? SelectionText.count(selection.count) : title)82 .toolbar { toolbar }83 .toolbar(isSelecting ? .visible : .automatic, for: .bottomBar)84 .task(id: ReloadKey(revision: app.feed.lists, sort: sortRaw)) {85 await model.reload(store: app.store, sort: sort)86 selection.formIntersection(Set(model.notes.map(\.id)))87 }88 .dropDestination(for: String.self) { texts, _ in89 // a note dragged from one of our own lists also carries its address as text: that is not a text to make a note of90 guard canCreate, let text = texts.first(where: { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }), !NoteTransfer.isOwnReference(text) else { return false }91 Task { await app.attempt { shell.open(note: try await app.createNote(in: source, markdown: text)) } }92 return true93 }94 .confirmationDialog("Supprimer définitivement ?", isPresented: Binding(get: { purgeRequest != nil }, set: { if !$0 { purgeRequest = nil } }), titleVisibility: .visible, presenting: purgeRequest) { request in95 Button(request.all ? "Vider la corbeille" : "Supprimer définitivement", role: .destructive) {96 Task {97 if request.all { await app.emptyTrash() } else { await commands.purge(request.ids) }98 endSelection()99 }100 }101 Button("Annuler", role: .cancel) {}102 } message: { _ in103 Text("C’est irréversible sur cet appareil. Sur le serveur, la suppression définitive sera terminée quand tu l’auras confirmée avec ta clé d’accès.")104 }105 .confirmationDialog(trashedChoice.map { AppModel.displayTitle($0.title) } ?? "", isPresented: Binding(get: { trashedChoice != nil }, set: { if !$0 { trashedChoice = nil } }), titleVisibility: .visible, presenting: trashedChoice) { note in106 Button("Restaurer") { Task { await commands.restore([note.id]) } }107 Button("Supprimer définitivement", role: .destructive) { purgeRequest = PurgeRequest(ids: [note.id]) }108 Button("Annuler", role: .cancel) {}109 } message: { _ in110 Text("Cet élément est dans la corbeille. Restaure-le pour l’ouvrir.")111 }112 .confirmationDialog("Supprimer ce dossier ?", isPresented: Binding(get: { folderDeletion != nil }, set: { if !$0 { folderDeletion = nil } }), titleVisibility: .visible, presenting: folderDeletion) { deletion in113 Button("Mettre à la corbeille", role: .destructive) {114 Task {115 await commands.trash([deletion.folder.id])116 if source == .folder(deletion.folder.id), shell.isCompact, !shell.path.isEmpty { shell.path.removeLast() }117 }118 }119 Button("Annuler", role: .cancel) {}120 } message: { deletion in121 Text(FolderDeletionText.message(count: deletion.count))122 }123 }124125 // MARK: rows126127 private func row(_ note: PageSummary) -> some View {128 Button { tap(note) } label: {129 HStack(spacing: 12) {130 if isSelecting {131 Image(systemName: selection.contains(note.id) ? "checkmark.circle.fill" : "circle")132 .font(.title3)133 .foregroundStyle(selection.contains(note.id) ? Color.accentColor : Color.spMuted)134 .accessibilityLabel(selection.contains(note.id) ? Text("Sélectionnée") : Text("Non sélectionnée"))135 }136 NoteRow(note: note,137 folderName: NoteArrangement.mixesFolders(source) ? note.parentId.flatMap { model.folderNames[$0] } : nil,138 date: isTrash ? note.deletedAt : (isInbox ? note.inboxAt : nil))139 }140 }141 .buttonStyle(.plain)142 .accessibilityIdentifier("note-row")143 .listRowBackground(!shell.isCompact && shell.selectedNote == note.id && !isSelecting ? Color.accentColor.opacity(0.16) : Color.spBackground)144 .swipeActions(edge: .trailing, allowsFullSwipe: true) { trailingSwipe(note) }145 .swipeActions(edge: .leading, allowsFullSwipe: true) { leadingSwipe(note) }146 .contextMenu { if !isSelecting { contextMenu(note) } }147 .draggable(NoteTransfer(ids: [note.id]))148 }149150 private func folderRow(_ folder: PageSummary) -> some View {151 Button { shell.open(source: .folder(folder.id)) } label: {152 HStack {153 FolderRow(folder: folder)154 if shell.isCompact { Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Color.spMuted).accessibilityHidden(true) }155 }156 }157 .buttonStyle(.plain)158 .accessibilityIdentifier("folder-row")159 .listRowBackground(Color.spBackground)160 .contextMenu { FolderMenu(folder: folder) { requestDeletion(of: folder) } }161 .swipeActions(edge: .trailing) {162 Button(role: .destructive) { requestDeletion(of: folder) } label: { Label("Supprimer", systemImage: "trash") }163 Button { shell.sheet = .move([folder.id]) } label: { Label("Déplacer", systemImage: "folder") }.tint(.indigo)164 }165 .draggable(NoteTransfer(ids: [folder.id]))166 .dropDestination(for: NoteTransfer.self) { items, _ in167 let ids = items.flatMap(\.ids).filter { $0 != folder.id }168 guard !ids.isEmpty else { return false }169 Task { await commands.drop(ids, on: .folder(folder.id)) }170 return true171 }172 }173174 private func tap(_ note: PageSummary) {175 if isSelecting {176 if !selection.insert(note.id).inserted { selection.remove(note.id) }177 } else if isTrash {178 trashedChoice = note179 } else if note.isFolder {180 shell.open(source: .folder(note.id))181 } else {182 shell.open(note: note.id)183 }184 }185186 @ViewBuilder private func trailingSwipe(_ note: PageSummary) -> some View {187 if isTrash {188 Button { purgeRequest = PurgeRequest(ids: [note.id]) } label: { Label("Supprimer définitivement", systemImage: "trash.slash") }.tint(Color.spDanger)189 } else {190 Button(role: .destructive) { Task { await commands.trash([note.id]) } } label: { Label("Supprimer", systemImage: "trash") }191 if isInbox {192 Button { Task { await commands.setArchived([note.id], true) } } label: { Label("Archiver", systemImage: "archivebox") }.tint(.gray)193 } else if !isArchive {194 Button { shell.sheet = .move([note.id]) } label: { Label("Déplacer", systemImage: "folder") }.tint(.indigo)195 }196 }197 }198199 @ViewBuilder private func leadingSwipe(_ note: PageSummary) -> some View {200 if isTrash {201 Button { Task { await commands.restore([note.id]) } } label: { Label("Restaurer", systemImage: "arrow.uturn.backward") }.tint(Color.spSuccess)202 } else if isArchive {203 Button { Task { await commands.setArchived([note.id], false) } } label: { Label("Désarchiver", systemImage: "tray.and.arrow.up") }.tint(Color.spSuccess)204 } else if isInbox {205 Button { Task { await commands.file(note) } } label: { Label("Classer", systemImage: "tray.and.arrow.down") }.tint(Color.spSuccess)206 } else {207 Button { Task { await commands.togglePin(note) } } label: { Label(note.pinned ? "Désépingler" : "Épingler", systemImage: note.pinned ? "pin.slash" : "pin") }.tint(.orange)208 Button { Task { await commands.toggleFavorite(note) } } label: { Label(note.favorite ? "Retirer des favoris" : "Favori", systemImage: note.favorite ? "star.slash" : "star") }.tint(.yellow)209 }210 }211212 @ViewBuilder private func contextMenu(_ note: PageSummary) -> some View {213 if isTrash {214 Button { Task { await commands.restore([note.id]) } } label: { Label("Restaurer", systemImage: "arrow.uturn.backward") }215 Button(role: .destructive) { purgeRequest = PurgeRequest(ids: [note.id]) } label: { Label("Supprimer définitivement", systemImage: "trash.slash") }216 } else {217 if supportsMultipleWindows, !note.isFolder {218 Button { openWindow(value: NoteWindowTarget(noteId: note.id)) } label: { Label("Ouvrir dans une nouvelle fenêtre", systemImage: "macwindow.badge.plus") }219 }220 if isInbox {221 Menu {222 ForEach(NoteSection.editable, id: \.self) { section in223 Button { Task { await commands.file(note, section: section) } } label: { Label(NoteSection.title(section), systemImage: NoteSection.symbol(section)) }224 }225 } label: { Label("Classer dans…", systemImage: "tray.and.arrow.down") }226 }227 Button { Task { await commands.togglePin(note) } } label: { Label(note.pinned ? "Désépingler" : "Épingler", systemImage: note.pinned ? "pin.slash" : "pin") }228 Button { Task { await commands.toggleFavorite(note) } } label: { Label(note.favorite ? "Retirer des favoris" : "Favori", systemImage: note.favorite ? "star.slash" : "star") }229 Button { shell.sheet = .move([note.id]) } label: { Label("Déplacer…", systemImage: "folder") }230 Button { shell.sheet = .tags([note.id]) } label: { Label("Tags…", systemImage: "number") }231 if !note.isFolder {232 Button { Task { await commands.duplicate(note) } } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }233 ShareLink(item: NoteTextShare(id: note.id, app: app), preview: SharePreview(AppModel.displayTitle(note.title))) { Label("Partager", systemImage: "square.and.arrow.up") }234 }235 Divider()236 Button { Task { await commands.setArchived([note.id], !note.archived) } } label: { Label(note.archived ? "Désarchiver" : "Archiver", systemImage: "archivebox") }237 Button(role: .destructive) { Task { await commands.trash([note.id]) } } label: { Label("Supprimer", systemImage: "trash") }238 }239 }240241 private func requestDeletion(of folder: PageSummary) {242 Task { folderDeletion = FolderDeletion(folder: folder, count: await app.descendantCount(of: folder.id)) }243 }244245 // MARK: pieces246247 private var title: String {248 switch source {249 case .smart(let list): return list.title250 case .section(let section): return NoteSection.title(section)251 case .folder: return model.folder.map { AppModel.displayTitle($0.title) } ?? String(localized: "Dossier")252 case .tag(let tag): return "#\(tag)"253 }254 }255256 private var breadcrumb: some View {257 ScrollView(.horizontal, showsIndicators: false) {258 HStack(spacing: 6) {259 if let folder = model.folder {260 crumb(NoteSection.title(folder.section)) { shell.jump(to: .section(folder.section)) }261 ForEach(model.breadcrumb) { ancestor in262 Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Color.spMuted).accessibilityHidden(true)263 crumb(AppModel.displayTitle(ancestor.title)) { shell.jump(to: .folder(ancestor.id)) }264 }265 Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Color.spMuted).accessibilityHidden(true)266 Text(AppModel.displayTitle(folder.title)).font(.subheadline.weight(.semibold)).foregroundStyle(Color.spText)267 }268 }269 .padding(.vertical, 6)270 }271 .listRowSeparator(.hidden)272 .listRowBackground(Color.spBackground)273 .accessibilityIdentifier("breadcrumb")274 }275276 private func crumb(_ title: String, action: @escaping () -> Void) -> some View {277 Button(title, action: action).font(.subheadline).buttonStyle(.borderless).frame(minHeight: 44)278 }279280 private var reauthBanner: some View {281 VStack(alignment: .leading, spacing: 10) {282 Label("Confirme avec ta clé d’accès pour terminer les suppressions définitives", systemImage: "key.fill")283 .font(.subheadline.weight(.medium)).foregroundStyle(Color.spText)284 Button {285 Task {286 isConfirmingDeletions = true287 defer { isConfirmingDeletions = false }288 do { try await app.confirmPendingDeletions() } catch {289 if let message = SignInFailure(error).message { app.banner = message }290 }291 }292 } label: {293 if isConfirmingDeletions { ProgressView() } else { Text("Confirmer") }294 }295 .buttonStyle(.borderedProminent)296 .disabled(isConfirmingDeletions || !app.network.isOnline)297 if !app.network.isOnline { Text("Disponible une fois en ligne.").font(.footnote).foregroundStyle(Color.spTextSecondary) }298 }299 .padding(.vertical, 6)300 .listRowBackground(Color.spSurface2)301 .accessibilityIdentifier("reauth-banner")302 }303304 @ViewBuilder private var emptyState: some View {305 switch source {306 case .smart(.inbox): EmptyStateView(symbol: "tray", title: "Boîte de réception vide", message: "Les captures rapides et ce que tu partages vers SP Notes arrivent ici.")307 case .smart(.favorites): EmptyStateView(symbol: "star", title: "Aucun favori", message: "Marque une note comme favorite pour la retrouver ici.")308 case .smart(.archived): EmptyStateView(symbol: "archivebox", title: "Aucune archive", message: "Les notes archivées quittent les listes mais restent dans la recherche si tu le demandes.")309 case .smart(.trash): EmptyStateView(symbol: "trash", title: "Corbeille vide", message: "Les notes supprimées restent ici jusqu’à leur suppression définitive.")310 case .tag(let tag): EmptyStateView(symbol: "number", title: "Aucune note avec #\(tag)")311 case .folder where model.missing: EmptyStateView(symbol: "folder.badge.questionmark", title: "Ce dossier n’existe plus", message: "Il a été supprimé, ici ou sur un autre appareil.")312 case .folder: EmptyStateView(symbol: "folder", title: "Dossier vide", message: "Crée une note ici ou déplaces-y des notes.", actionTitle: "Nouvelle note") { Task { await commands.newNote(in: source) } }313 default: EmptyStateView(symbol: "note.text", title: "Aucune note", message: "Tes notes sont enregistrées sur cet appareil et se synchronisent quand tu es connecté.", actionTitle: canCreate ? "Nouvelle note" : nil) { Task { await commands.newNote(in: source) } }314 }315 }316317 // MARK: toolbar and selection318319 @ToolbarContentBuilder private var toolbar: some ToolbarContent {320 if isSelecting {321 ToolbarItem(placement: .topBarLeading) {322 Button(selection.count == model.notes.count ? "Tout désélectionner" : "Tout sélectionner") {323 selection = selection.count == model.notes.count ? [] : Set(model.notes.map(\.id))324 }325 }326 ToolbarItem(placement: .confirmationAction) { Button("OK") { endSelection() }.accessibilityIdentifier("selection-done") }327 ToolbarItemGroup(placement: .bottomBar) { bulkBar }328 } else {329 if canCreate {330 ToolbarItem(placement: .primaryAction) { NewNoteButton(source: source) }331 }332 ToolbarItem(placement: .topBarTrailing) {333 Menu {334 if !model.notes.isEmpty {335 Button { isSelecting = true } label: { Label("Sélectionner", systemImage: "checkmark.circle") }336 }337 if NoteArrangement.sortable(source) {338 Picker(selection: $sortRaw) {339 ForEach(NoteSort.allCases) { Text($0.label).tag($0.rawValue) }340 } label: { Label("Trier par", systemImage: "arrow.up.arrow.down") }341 .pickerStyle(.menu)342 }343 switch source {344 case .section(let section) where NoteSection.editable.contains(section):345 Button { shell.sheet = .newFolder(parentId: nil, section: section) } label: { Label("Nouveau dossier", systemImage: "folder.badge.plus") }346 case .folder:347 if let folder = model.folder {348 Divider()349 FolderMenu(folder: folder) { requestDeletion(of: folder) }350 }351 case .smart(.trash):352 Button(role: .destructive) { purgeRequest = PurgeRequest(ids: [], all: true) } label: { Label("Vider la corbeille", systemImage: "trash.slash") }353 .disabled(model.notes.isEmpty)354 default: EmptyView()355 }356 } label: { Label("Options de la liste", systemImage: "ellipsis.circle") }357 .accessibilityIdentifier("list-options")358 }359 }360 }361362 @ViewBuilder private var bulkBar: some View {363 let ids = Array(selection)364 if isTrash {365 Button("Restaurer") { Task { await commands.restore(ids); endSelection() } }.disabled(ids.isEmpty).tint(Color.accentColor)366 Spacer()367 Button("Supprimer", role: .destructive) { purgeRequest = PurgeRequest(ids: ids) }.disabled(ids.isEmpty).tint(Color.spDanger)368 } else {369 Button { shell.sheet = .move(ids) } label: { Label("Déplacer", systemImage: "folder") }.disabled(ids.isEmpty).tint(Color.accentColor)370 Spacer()371 Button { shell.sheet = .tags(ids) } label: { Label("Tags", systemImage: "number") }.disabled(ids.isEmpty).tint(Color.accentColor)372 Spacer()373 Button { Task { await commands.setArchived(ids, !isArchive); endSelection() } } label: { Label(isArchive ? "Désarchiver" : "Archiver", systemImage: "archivebox") }.disabled(ids.isEmpty).tint(Color.accentColor)374 Spacer()375 Button(role: .destructive) { Task { await commands.trash(ids); endSelection() } } label: { Label("Supprimer", systemImage: "trash") }.disabled(ids.isEmpty).tint(Color.spDanger)376 }377 }378379 private func endSelection() { isSelecting = false; selection = [] }380}381382enum SelectionText {383 static func count(_ count: Int) -> String {384 switch count {385 case 0: return String(localized: "Aucune sélection")386 case 1: return String(localized: "1 sélectionnée")387 default: return String(localized: "\(count) sélectionnées")388 }389 }390}391392enum FolderDeletionText {393 /// Says honestly what goes to the trash with the folder.394 static func message(count: Int) -> String {395 switch count {396 case 0: return String(localized: "Le dossier est vide. Il ira dans la corbeille, d’où tu pourras le restaurer.")397 case 1: return String(localized: "Le dossier et l’élément qu’il contient iront dans la corbeille, d’où tu pourras les restaurer.")398 default: return String(localized: "Le dossier et les \(count) éléments qu’il contient iront dans la corbeille, d’où tu pourras les restaurer.")399 }400 }401}402403/// Rename / move / delete, for a folder row and for the menu of the folder shown.404struct FolderMenu: View {405 let folder: PageSummary406 let onDelete: () -> Void407 @Environment(ShellState.self) private var shell408409 var body: some View {410 Button { shell.sheet = .renameFolder(id: folder.id, title: AppModel.displayTitle(folder.title)) } label: { Label("Renommer", systemImage: "pencil") }411 Button { shell.sheet = .move([folder.id]) } label: { Label("Déplacer…", systemImage: "folder") }412 Button { shell.sheet = .newFolder(parentId: folder.id, section: folder.section) } label: { Label("Nouveau sous-dossier", systemImage: "folder.badge.plus") }413 Divider()414 Button(role: .destructive, action: onDelete) { Label("Supprimer", systemImage: "trash") }415 }416}417