Repository Public
1// SP Notes iOS2// File: Features/Root/SidebarView.swift3// Description: The iPad sidebar: search, today, smart lists with counts, inbox, tasks, the hosted sections, the folder tree by section, the tags. Rows accept dropped4// notes (move into a folder or section, favourite, archive, trash).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI1011struct SidebarView: View {12 @Environment(AppModel.self) private var app13 @Environment(ShellState.self) private var shell14 @State private var counts: ListCounts?15 @State private var tree: [String: [FolderNode]] = [:]16 @State private var tags: [TagInfo] = []17 @State private var openTasks = 018 @State private var expanded: Set<String> = []19 @AppStorage("sidebar.sections.collapsed") private var collapsedSections = ""2021 var body: some View {22 @Bindable var shell = shell23 List(selection: $shell.sidebar) {24 Section {25 FolderRow(title: String(localized: "Rechercher"), symbol: "magnifyingglass").tag(SidebarItem.search).accessibilityIdentifier("sidebar-search")26 FolderRow(title: String(localized: "Aujourd’hui"), symbol: "sun.max").tag(SidebarItem.today).accessibilityIdentifier("sidebar-today")27 smart(.all, counts?.all ?? 0)28 smart(.favorites, counts?.favorites ?? 0)29 FolderRow(title: SmartList.inbox.title, symbol: SmartList.inbox.symbol, count: counts?.inbox ?? 0).tag(SidebarItem.inbox).accessibilityIdentifier("sidebar-inbox")30 FolderRow(title: String(localized: "Tâches"), symbol: "checklist", count: openTasks).tag(SidebarItem.tasks).accessibilityIdentifier("sidebar-tasks")31 }32 // the sections hosted from SPNotesFeatures: only those whose screen is registered and that the server offers33 let hosted = shell.sections.available34 if !hosted.isEmpty {35 Section("Explorer") {36 ForEach(hosted, id: \.id) { section in37 FolderRow(title: section.title, symbol: section.symbol).tag(SidebarItem.hosted(section.id)).accessibilityIdentifier("sidebar-hosted-\(section.id)")38 }39 }40 }41 Section {42 ForEach(NoteSection.editable, id: \.self) { section in43 let nodes = tree[section] ?? []44 if nodes.isEmpty {45 sectionRow(section)46 } else {47 DisclosureGroup(isExpanded: expansion("section:\(section)", defaultOpen: true)) {48 ForEach(nodes) { node in folderRows(node) }49 } label: { sectionRow(section) }50 }51 }52 } header: {53 HStack {54 Text("Dossiers")55 Spacer()56 Button { shell.sheet = NewFolderTarget.sheet(for: shell.currentSource) } label: {57 Image(systemName: "folder.badge.plus").frame(minWidth: 44, minHeight: 32, alignment: .trailing)58 }59 .accessibilityLabel("Nouveau dossier")60 .accessibilityIdentifier("new-folder")61 }62 }63 if !tags.isEmpty {64 Section("Tags") {65 ForEach(tags) { tag in66 FolderRow(title: tag.name, symbol: "number", count: tag.count)67 .tag(SidebarItem.source(.tag(tag.name)))68 }69 }70 }71 Section {72 smart(.archived, counts?.archived ?? 0)73 smart(.trash, counts?.trash ?? 0)74 }75 if app.session == .expired {76 Section { SessionExpiredBanner().padding(.vertical, 4).selectionDisabled() }77 }78 }79 .listStyle(.sidebar)80 .navigationTitle("SP Notes")81 .toolbar {82 ToolbarItem(placement: .topBarLeading) {83 Button { shell.sheet = .settings } label: { Label("Réglages", systemImage: "gearshape") }.accessibilityIdentifier("settings")84 }85 ToolbarItem(placement: .topBarTrailing) { SyncIndicator() }86 }87 .task(id: app.feed.structure &+ app.feed.tags) { await load() }88 .task(id: app.feed.entities("task") &+ app.feed.resetGeneration) { openTasks = ((try? await app.repositories.tasks.list(.open)) ?? []).count }89 }9091 private func smart(_ list: SmartList, _ count: Int) -> some View {92 FolderRow(title: list.title, symbol: list.symbol, count: count)93 .tag(SidebarItem.source(.smart(list)))94 .accessibilityIdentifier("sidebar-\(list.rawValue)")95 .modifier(NoteDropTarget(source: .smart(list)))96 }9798 private func sectionRow(_ section: String) -> some View {99 FolderRow(title: NoteSection.title(section), symbol: NoteSection.symbol(section))100 .tag(SidebarItem.source(.section(section)))101 .accessibilityIdentifier("sidebar-section-\(section)")102 .modifier(NoteDropTarget(source: .section(section)))103 .contextMenu {104 Button { shell.sheet = .newFolder(parentId: nil, section: section) } label: { Label("Nouveau dossier", systemImage: "folder.badge.plus") }105 }106 }107108 private func folderRows(_ node: FolderNode) -> AnyView {109 let row = FolderRow(title: node.title)110 .tag(SidebarItem.source(.folder(node.id)))111 .modifier(NoteDropTarget(source: .folder(node.id)))112 .contextMenu {113 Button { shell.sheet = .renameFolder(id: node.id, title: node.title) } label: { Label("Renommer", systemImage: "pencil") }114 Button { shell.sheet = .move([node.id]) } label: { Label("Déplacer…", systemImage: "folder") }115 Button { shell.sheet = .newFolder(parentId: node.id, section: node.folder.section) } label: { Label("Nouveau sous-dossier", systemImage: "folder.badge.plus") }116 }117 if node.children.isEmpty { return AnyView(row) }118 return AnyView(DisclosureGroup(isExpanded: expansion(node.id, defaultOpen: false)) {119 ForEach(node.children) { child in folderRows(child) }120 } label: { row })121 }122123 /// Disclosure state: sections are open unless closed, folders closed unless opened.124 private func expansion(_ key: String, defaultOpen: Bool) -> Binding<Bool> {125 Binding(126 get: { defaultOpen ? !collapsedSections.split(separator: ",").contains(Substring(key)) : expanded.contains(key) },127 set: { open in128 if defaultOpen {129 var closed = Set(collapsedSections.split(separator: ",").map(String.init))130 if open { closed.remove(key) } else { closed.insert(key) }131 collapsedSections = closed.sorted().joined(separator: ",")132 } else if open { expanded.insert(key) } else { expanded.remove(key) }133 })134 }135136 private func load() async {137 if let fresh = try? await app.store.counts() { counts = fresh }138 let folders = (try? await app.store.folderTree()) ?? []139 tree = FolderTree.build(folders)140 tags = ((try? await app.store.tags()) ?? []).filter { $0.count > 0 }141 // Keep the folder shown reachable: open its ancestors.142 if case .source(.folder(let id))? = shell.sidebar {143 let byId = Dictionary(folders.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })144 var parent = byId[id]?.parentId145 while let current = parent, byId[current] != nil, expanded.insert(current).inserted { parent = byId[current]?.parentId }146 }147 }148}149150/// Lets a sidebar row receive dragged notes.151struct NoteDropTarget: ViewModifier {152 let source: NoteSource153 @Environment(AppModel.self) private var app154 @Environment(ShellState.self) private var shell155 @State private var targeted = false156157 func body(content: Content) -> some View {158 if NoteCommands.accepts(dropOn: source) {159 content160 .dropDestination(for: NoteTransfer.self) { items, _ in161 let ids = items.flatMap(\.ids)162 guard !ids.isEmpty else { return false }163 Task { await NoteCommands(app: app, shell: shell).drop(ids, on: source) }164 return true165 } isTargeted: { targeted = $0 }166 .listRowBackground(targeted ? Color.accentColor.opacity(0.22) : nil)167 } else {168 content169 }170 }171}172