Repository Public
1// SP Notes iOS2// File: Features/Search/SearchScreen.swift3// Description: Local, instant, offline search: results as you type (debounced) with the matches emphasised, combinable filter4// chips (section, folder, tags, date, favourites, pinned, archives) and the recent searches.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SPNotesStore10import SwiftUI1112struct SearchScreen: View {13 let initialQuery: String1415 @Environment(AppModel.self) private var app16 @Environment(ShellState.self) private var shell17 @State private var criteria = SearchCriteria()18 @State private var hits: [SPNotesStore.SearchHit] = []19 @State private var folderNames: [String: String] = [:]20 @State private var allTags: [TagInfo] = []21 @State private var recents = RecentSearches.load()22 @State private var limit = 5023 @State private var searched = false24 @State private var isSearchPresented = true25 @State private var showsFolderPicker = false26 @State private var showsCustomDates = false27 @State private var customFrom = Calendar.current.date(byAdding: .day, value: -7, to: .now) ?? .now28 @State private var customTo = Date.now2930 init(initialQuery: String = "") {31 self.initialQuery = initialQuery32 var criteria = SearchCriteria()33 criteria.query = initialQuery34 _criteria = State(initialValue: criteria)35 }3637 private struct SearchKey: Equatable { var criteria: SearchCriteria; var revision: Int; var limit: Int }3839 var body: some View {40 List {41 Section {42 filterBar43 .listRowInsets(EdgeInsets())44 .listRowSeparator(.hidden)45 .listRowBackground(Color.spBackground)46 }47 if let placeholder {48 placeholder49 .frame(maxWidth: .infinity)50 .listRowSeparator(.hidden)51 .listRowBackground(Color.spBackground)52 } else if criteria.isActive {53 Section {54 ForEach(hits) { hit in resultRow(hit) }55 if hits.count >= limit {56 Button("Afficher plus de résultats") { limit += 100 }57 .frame(maxWidth: .infinity, minHeight: 36)58 .listRowBackground(Color.spBackground)59 }60 } header: {61 if searched { Text(ResultsText.count(hits.count, capped: hits.count >= limit)).accessibilityIdentifier("search-count") }62 }63 } else if !recents.isEmpty {64 Section {65 ForEach(recents, id: \.self) { recent in66 Button { criteria.query = recent } label: {67 Label(recent, systemImage: "clock.arrow.circlepath").foregroundStyle(Color.spText).frame(minHeight: 30)68 }69 .listRowBackground(Color.spBackground)70 }71 .onDelete { offsets in72 recents.remove(atOffsets: offsets)73 RecentSearches.save(recents)74 }75 } header: {76 HStack {77 Text("Recherches récentes")78 Spacer()79 Button("Effacer") { recents = []; RecentSearches.save([]) }.font(.footnote)80 }81 }82 }83 }84 .listStyle(.plain)85 .scrollContentBackground(.hidden)86 .background(Color.spBackground)87 .scrollDismissesKeyboard(.immediately)88 .navigationTitle("Recherche")89 .navigationBarTitleDisplayMode(.inline)90 .searchable(text: $criteria.query, isPresented: $isSearchPresented, placement: .navigationBarDrawer(displayMode: .always), prompt: "Titre, texte ou tag")91 .onSubmit(of: .search) { remember() }92 .onChange(of: isSearchPresented) { _, presented in93 // On iPhone, closing an empty search goes back where the person came from instead of leaving an idle screen.94 if !presented, shell.isCompact, !criteria.isActive, case .search? = shell.path.last { shell.path.removeLast() }95 }96 .task(id: SearchKey(criteria: criteria, revision: app.feed.lists, limit: limit)) { await search() }97 .task(id: app.feed.lists) {98 allTags = ((try? await app.store.tags()) ?? []).filter { $0.count > 0 }99 folderNames = Dictionary(((try? await app.store.folderTree()) ?? []).map { ($0.id, AppModel.displayTitle($0.title)) }, uniquingKeysWith: { a, _ in a })100 }101 .sheet(isPresented: $showsFolderPicker) {102 NavigationStack {103 FolderPickerList(includeSections: false) { target, name in104 if case .folder(let id) = target { criteria.folderId = id; criteria.folderName = name }105 showsFolderPicker = false106 }107 .navigationTitle("Limiter à un dossier")108 .navigationBarTitleDisplayMode(.inline)109 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Annuler") { showsFolderPicker = false } } }110 }111 }112 .sheet(isPresented: $showsCustomDates) { customDates }113 }114115 /// What takes the place of the results when there is nothing to list (a row of the list, so it never covers the filters).116 private var placeholder: AnyView? {117 if criteria.isActive, searched, hits.isEmpty {118 return criteria.hasQuery119 ? AnyView(ContentUnavailableView.search(text: criteria.query))120 : AnyView(EmptyStateView(symbol: "line.3.horizontal.decrease.circle", title: "Aucune note ne correspond à ces filtres"))121 }122 if !criteria.isActive, recents.isEmpty {123 return AnyView(EmptyStateView(symbol: "magnifyingglass", title: "Cherche dans toutes tes notes", message: "La recherche se fait sur cet appareil : elle est instantanée et fonctionne hors ligne."))124 }125 return nil126 }127128 // MARK: results129130 private func resultRow(_ hit: SPNotesStore.SearchHit) -> some View {131 Button {132 remember()133 if hit.page.isFolder { shell.open(source: .folder(hit.page.id)) } else { shell.open(note: hit.page.id) }134 } label: {135 NoteRow(note: hit.page,136 folderName: hit.page.archived ? String(localized: "Archives") : hit.page.parentId.flatMap { folderNames[$0] },137 highlightedTitle: hit.highlightedTitle,138 highlightedSnippet: hit.snippet)139 }140 .buttonStyle(.plain)141 .accessibilityIdentifier("search-result")142 .listRowBackground(!shell.isCompact && shell.selectedNote == hit.page.id ? Color.accentColor.opacity(0.16) : Color.spBackground)143 }144145 private func search() async {146 guard criteria.isActive else { hits = []; searched = false; return }147 // Debounce: typing fast does not run a query per keystroke.148 try? await Task.sleep(for: .milliseconds(150))149 guard !Task.isCancelled else { return }150 let found = (try? await app.store.search(query: criteria.query, filters: criteria.storeFilters(), limit: limit)) ?? []151 guard !Task.isCancelled else { return }152 hits = found153 searched = true154 }155156 private func remember() {157 guard criteria.hasQuery else { return }158 recents = RecentSearches.adding(criteria.query, to: recents)159 RecentSearches.save(recents)160 }161162 // MARK: filters163164 private var filterBar: some View {165 ScrollView(.horizontal, showsIndicators: false) {166 HStack(spacing: 8) {167 Menu {168 Button("Toutes les sections") { criteria.section = nil }169 ForEach(NoteSection.editable + ["databases"], id: \.self) { section in170 Button { criteria.section = section } label: {171 if criteria.section == section { Label(NoteSection.title(section), systemImage: "checkmark") } else { Text(NoteSection.title(section)) }172 }173 }174 } label: { FilterChip(title: criteria.section.map(NoteSection.title) ?? String(localized: "Section"), symbol: "square.stack", isOn: criteria.section != nil, isMenu: true) }175 .accessibilityIdentifier("filter-section")176177 if let name = criteria.folderName, criteria.folderId != nil {178 Button { criteria.folderId = nil; criteria.folderName = nil } label: { FilterChip(title: name, symbol: "folder", isOn: true, isRemovable: true) }179 .accessibilityLabel("Retirer le filtre dossier \(name)")180 } else {181 Button { showsFolderPicker = true } label: { FilterChip(title: String(localized: "Dossier"), symbol: "folder", isOn: false, isMenu: true) }182 .accessibilityIdentifier("filter-folder")183 }184185 if !allTags.isEmpty || !criteria.tags.isEmpty {186 Menu {187 ForEach(allTags) { tag in188 Button {189 if let index = criteria.tags.firstIndex(of: tag.name) { criteria.tags.remove(at: index) } else { criteria.tags.append(tag.name) }190 } label: {191 if criteria.tags.contains(tag.name) { Label("#\(tag.name)", systemImage: "checkmark") } else { Text("#\(tag.name)") }192 }193 }194 if !criteria.tags.isEmpty { Divider(); Button("Aucun tag") { criteria.tags = [] } }195 } label: {196 FilterChip(title: criteria.tags.isEmpty ? String(localized: "Tags") : criteria.tags.map { "#\($0)" }.joined(separator: " "), symbol: "number", isOn: !criteria.tags.isEmpty, isMenu: true)197 }198 .menuActionDismissBehavior(.disabled)199 .accessibilityIdentifier("filter-tags")200 }201202 Menu {203 dateButton(.any, String(localized: "Toutes les dates"))204 dateButton(.today, String(localized: "Aujourd’hui"))205 dateButton(.last7Days, String(localized: "7 jours"))206 dateButton(.last30Days, String(localized: "30 jours"))207 Button("Personnalisé…") { showsCustomDates = true }208 } label: { FilterChip(title: criteria.dateRange.label, symbol: "calendar", isOn: criteria.dateRange != .any, isMenu: true) }209 .accessibilityIdentifier("filter-date")210211 Button { criteria.favoritesOnly.toggle() } label: { FilterChip(title: String(localized: "Favoris"), symbol: "star", isOn: criteria.favoritesOnly) }212 .accessibilityIdentifier("filter-favorites")213 .accessibilityAddTraits(criteria.favoritesOnly ? .isSelected : [])214 Button { criteria.pinnedOnly.toggle() } label: { FilterChip(title: String(localized: "Épinglées"), symbol: "pin", isOn: criteria.pinnedOnly) }215 .accessibilityIdentifier("filter-pinned")216 .accessibilityAddTraits(criteria.pinnedOnly ? .isSelected : [])217 Button { criteria.includeArchived.toggle() } label: { FilterChip(title: String(localized: "Inclure les archives"), symbol: "archivebox", isOn: criteria.includeArchived) }218 .accessibilityIdentifier("filter-archived")219 .accessibilityAddTraits(criteria.includeArchived ? .isSelected : [])220221 if criteria.hasFilters || criteria.includeArchived {222 Button("Tout effacer") { criteria.clearFilters() }.font(.subheadline).frame(minHeight: 44)223 }224 }225 .padding(.horizontal, 16)226 .padding(.vertical, 6)227 }228 .buttonStyle(.plain)229 }230231 private func dateButton(_ range: DateRangeFilter, _ title: String) -> some View {232 Button { criteria.dateRange = range } label: {233 if criteria.dateRange == range { Label(title, systemImage: "checkmark") } else { Text(title) }234 }235 }236237 private var customDates: some View {238 NavigationStack {239 Form {240 DatePicker("Du", selection: $customFrom, in: ...Date.now, displayedComponents: .date)241 DatePicker("Au", selection: $customTo, in: ...Date.now, displayedComponents: .date)242 Section { Text("Notes modifiées entre ces deux jours, inclus.").font(.footnote).foregroundStyle(Color.spTextSecondary) }243 }244 .navigationTitle("Période")245 .navigationBarTitleDisplayMode(.inline)246 .toolbar {247 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { showsCustomDates = false } }248 ToolbarItem(placement: .confirmationAction) {249 Button("Appliquer") { criteria.dateRange = .custom(from: customFrom, to: customTo); showsCustomDates = false }250 }251 }252 }253 .presentationDetents([.medium])254 }255}256257enum ResultsText {258 static func count(_ count: Int, capped: Bool) -> String {259 if capped { return String(localized: "Les \(count) premiers résultats") }260 switch count {261 case 0: return String(localized: "Aucun résultat")262 case 1: return String(localized: "1 résultat")263 default: return String(localized: "\(count) résultats")264 }265 }266}267268/// A filter of the search bar: outlined when off, filled when on (the state is also carried by the check mark).269struct FilterChip: View {270 let title: String271 var symbol: String272 var isOn: Bool273 var isMenu = false274 var isRemovable = false275276 var body: some View {277 HStack(spacing: 6) {278 Image(systemName: isOn && !isMenu && !isRemovable ? "checkmark" : symbol).font(.footnote.weight(.semibold))279 Text(title).font(.subheadline.weight(isOn ? .semibold : .regular)).lineLimit(1)280 if isMenu { Image(systemName: "chevron.down").font(.caption2.weight(.semibold)) }281 if isRemovable { Image(systemName: "xmark").font(.caption2.weight(.bold)) }282 }283 .foregroundStyle(isOn ? Color.spText : Color.spTextSecondary)284 .padding(.horizontal, 12)285 .frame(minHeight: 36)286 .background(isOn ? Color.accentColor.opacity(0.22) : Color.spSurface, in: Capsule())287 .overlay(Capsule().strokeBorder(isOn ? Color.accentColor.opacity(0.7) : Color.spBorder))288 .frame(minHeight: 44)289 .contentShape(Rectangle())290 }291}292