SPB Git

Repository Public

SearchScreen.swift 16.0 KB 266 lines swift

1// SP Drive iOS2// File: Features/Search/SearchScreen.swift3// Description: Search by name, type, extension, date, size, folder and favourites. Answers come at once from the local index (also offline);4//              with a connection the server's answer completes them.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPDriveNext9import SwiftUI1011struct SearchScreen: View {12    @Environment(AppModel.self) private var model13    @State private var actions = ItemActions()14    @State private var text = ""15    @State private var kind: FileKind?16    @State private var ext = ""17    @State private var starredOnly = false18    @State private var offlineOnly = false19    @State private var period: Period = .any20    @State private var size: SizeBand = .any21    @State private var scope: DriveItem?22    @State private var pickingScope = false23    @State private var remote: [DriveItem] = []24    @State private var searchingServer = false25    // SP Drive 2.0 (shown only when the server announces the feature)26    @State private var where_: SearchScope = .all27    @State private var contentHits: [NextFile] = []28    @State private var bySense = false29    @State private var senseHits: [SemanticHit] = []30    @State private var senseUnavailable = false3132    enum Period: String, CaseIterable, Identifiable {33        case any = "Toute date", week = "7 derniers jours", month = "30 derniers jours", year = "Cette année"34        var id: String { rawValue }35        var from: Date? {36            switch self {37            case .any: nil; case .week: Calendar.current.date(byAdding: .day, value: -7, to: .now); case .month: Calendar.current.date(byAdding: .day, value: -30, to: .now)38            case .year: Calendar.current.date(from: Calendar.current.dateComponents([.year], from: .now))39            }40        }41    }42    enum SizeBand: String, CaseIterable, Identifiable {43        case any = "Toute taille", small = "Moins de 1 Mo", medium = "1 à 100 Mo", large = "Plus de 100 Mo"44        var id: String { rawValue }45        var range: (Int64?, Int64?) {46            switch self { case .any: (nil, nil); case .small: (nil, 1_000_000); case .medium: (1_000_000, 100_000_000); case .large: (100_000_000, nil) }47        }48    }4950    private var hasCriteria: Bool { !text.trimmingCharacters(in: .whitespaces).isEmpty || kind != nil || !ext.isEmpty || starredOnly || offlineOnly || period != .any || size != .any || scope != nil }51    private var criteriaKey: String { "\(where_.rawValue)|\(bySense)|\(text)|\(kind?.rawValue ?? "")|\(ext)|\(starredOnly)|\(offlineOnly)|\(period.rawValue)|\(size.rawValue)|\(scope?.id ?? "")" }5253    private var local: [DriveItem] {54        _ = model.itemsVersion55        guard hasCriteria else { return [] }56        return model.store.search(text: text, kinds: kind.map { [$0] } ?? [], ext: ext.isEmpty ? nil : ext, starredOnly: starredOnly, within: scope?.id, from: period.from, minSize: size.range.0, maxSize: size.range.1, offlineOnly: offlineOnly)57    }5859    var body: some View {60        let local = local61        let known = Set(local.map(\.id))62        // the server may know items the mirror has not received yet; they are shown after the local answers63        let inContent = Set(contentHits.map(\.id)) // a 2.0 server also matches content in its default search: those are shown once, with their passage64        let extra = remote.filter { !known.contains($0.id) && !inContent.contains($0.id) && model.store.item($0.id) != nil }65        List {66            Section {67                ScrollView(.horizontal, showsIndicators: false) {68                    HStack(spacing: 8) {69                        Menu {70                            Picker("Type", selection: $kind) {71                                Text("Tous les types").tag(FileKind?.none)72                                ForEach(FileKind.allCases.filter { $0 != .other }, id: \.self) { Label($0.label, systemImage: $0.symbol).tag(FileKind?.some($0)) }73                            }74                        } label: { chip(kind?.label ?? "Type", active: kind != nil, symbol: "doc") }75                        Menu { Picker("Date", selection: $period) { ForEach(Period.allCases) { Text($0.rawValue).tag($0) } } } label: { chip(period == .any ? "Date" : period.rawValue, active: period != .any, symbol: "calendar") }76                        Menu { Picker("Taille", selection: $size) { ForEach(SizeBand.allCases) { Text($0.rawValue).tag($0) } } } label: { chip(size == .any ? "Taille" : size.rawValue, active: size != .any, symbol: "internaldrive") }77                        Button { pickingScope = true } label: { chip(scope?.name ?? "Dossier", active: scope != nil, symbol: "folder") }78                        Button { starredOnly.toggle() } label: { chip("Favoris", active: starredOnly, symbol: "star") }79                        Button { offlineOnly.toggle() } label: { chip("Sur l’appareil", active: offlineOnly, symbol: "arrow.down.circle") }80                        if model.next.has(.contentSearch), model.network.online {81                            Menu {82                                Picker("Chercher dans", selection: $where_) {83                                    Label("Noms et contenu", systemImage: "doc.text.magnifyingglass").tag(SearchScope.all)84                                    Label("Noms seulement", systemImage: "textformat").tag(SearchScope.name)85                                    Label("Contenu seulement", systemImage: "text.alignleft").tag(SearchScope.content)86                                }87                            } label: { chip(where_ == .all ? String(localized: "Noms et contenu") : where_ == .name ? String(localized: "Noms") : String(localized: "Contenu"), active: where_ != .all, symbol: "doc.text.magnifyingglass") }88                            .accessibilityIdentifier("search.scope")89                        }90                        if model.next.has(.semantic), model.network.online {91                            Button { bySense.toggle() } label: { chip(String(localized: "Par le sens"), active: bySense, symbol: "sparkle.magnifyingglass") }92                                .accessibilityIdentifier("search.semantic")93                                .accessibilityAddTraits(bySense ? .isSelected : [])94                        }95                        if hasCriteria { Button("Effacer") { kind = nil; ext = ""; starredOnly = false; offlineOnly = false; period = .any; size = .any; scope = nil }.font(.footnote) }96                    }97                    .padding(.vertical, 2)98                }99                .listRowInsets(EdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 0))100                .buttonStyle(.plain)101            }102            if !hasCriteria {103                let recents = model.store.recentSearches()104                if !recents.isEmpty {105                    Section("Recherches récentes") {106                        ForEach(recents, id: \.self) { r in Button { text = r } label: { Label(r, systemImage: "clock.arrow.circlepath") }.foregroundStyle(.primary) }107                    }108                }109            } else if bySense {110                senseSection111            } else if local.isEmpty && extra.isEmpty && contentHits.isEmpty {112                Section { EmptyState(symbol: "magnifyingglass", title: "Aucun résultat", message: model.network.online ? "Aucun élément ne correspond à ces critères." : "Aucun élément connu de cet appareil ne correspond. Hors ligne, seule la copie locale de l’index est consultée.") }113                    .listRowSeparator(.hidden)114            } else {115                if where_ != .content, !local.isEmpty { Section("\(local.count) résultat\(local.count > 1 ? "s" : "")") { ItemList(items: local, actions: actions) } }116                if !contentHits.isEmpty {117                    Section {118                        ForEach(contentHits) { hit in ContentHitRow(file: hit, actions: actions) }119                    } header: {120                        Text("Dans le contenu (\(contentHits.count))")121                    } footer: {122                        Text("Le texte des documents (et des images, par reconnaissance de caractères) est indexé sur le serveur MacLustr. Seuls tes propres fichiers sont cherchés.")123                    }124                }125                if !extra.isEmpty { Section("Aussi sur le serveur") { ItemList(items: extra, actions: actions) } }126            }127            if searchingServer { Section { HStack { ProgressView(); Text("Recherche sur le serveur…").font(.footnote).foregroundStyle(.secondary) } } }128        }129        .listStyle(.plain)130        .navigationTitle("Recherche")131        .searchable(text: $text, placement: .navigationBarDrawer(displayMode: .always), prompt: "Nom, extension (.pdf)…")132        .autocorrectionDisabled()133        .textInputAutocapitalization(.never)134        .onSubmit(of: .search) { model.store.rememberSearch(text) }135        .onChange(of: text) { _, t in136            // ".pdf" or "*.pdf" at the start is an extension filter137            if let m = t.wholeMatch(of: /\*?\.([A-Za-z0-9]{1,8})/) { ext = String(m.1) } else if ext == String(t.dropFirst(t.hasPrefix("*") ? 2 : 1)) || t.isEmpty { ext = "" }138        }139        .task(id: criteriaKey) { await searchServer() }140        .sheet(isPresented: $pickingScope) { FolderPicker(title: "Chercher dans", excluding: [], startAt: scope?.id) { id in scope = model.store.item(id).flatMap { $0.parentID == nil ? nil : $0 } } }141        .itemActions(actions)142    }143144    private func chip(_ label: String, active: Bool, symbol: String) -> some View {145        Label(label, systemImage: symbol).font(.footnote.weight(.medium)).lineLimit(1)146            .padding(.horizontal, 12).padding(.vertical, 7)147            .foregroundStyle(active ? Color.white : Color.primary)148            .background(active ? AnyShapeStyle(Theme.gradient) : AnyShapeStyle(.quaternary), in: Capsule())149    }150151    /// Results « by meaning »: passages close to the question, in the order the server ranked them. No score is shown: only the order means something.152    @ViewBuilder private var senseSection: some View {153        if senseUnavailable {154            Section { EmptyState(symbol: "sparkle.magnifyingglass", title: String(localized: "Recherche par le sens indisponible"), message: String(localized: "Le modèle de recherche du serveur ne répond pas pour l’instant. La recherche par noms et contenu fonctionne.")).listRowSeparator(.hidden) }155        } else if senseHits.isEmpty && !searchingServer {156            Section { EmptyState(symbol: "sparkle.magnifyingglass", title: String(localized: "Aucun passage proche"), message: String(localized: "Écris une question ou une idée ; la recherche par le sens trouve des passages qui en parlent, même avec d’autres mots (dans la même langue).")).listRowSeparator(.hidden) }157        } else {158            Section {159                ForEach(senseHits) { hit in160                    Button { open(hit.file) } label: {161                        VStack(alignment: .leading, spacing: 4) {162                            Label(hit.file.name, systemImage: hit.file.fileKind.symbol).font(.body.weight(.medium)).lineLimit(2)163                            Text(hit.passage.text).font(.footnote).foregroundStyle(.secondary).lineLimit(4)164                            if let page = hit.passage.page { Text("Page \(page)").font(.caption2).foregroundStyle(.tertiary) }165                        }166                    }167                    .buttonStyle(.plain)168                    .accessibilityIdentifier("sense.\(hit.file.name)")169                }170            } header: { Text("Passages les plus proches, du plus au moins pertinent") }171        }172    }173174    private func open(_ file: NextFile) {175        Task {176            if model.store.item(file.id) == nil { await model.engine.sync() }177            if let item = model.store.item(file.id) { actions.open(item, model: model) }178        }179    }180181    private func searchServer() async {182        remote = []183        contentHits = []184        senseHits = []185        senseUnavailable = false186        let q = text.trimmingCharacters(in: .whitespaces)187        if bySense {188            guard model.network.online, q.count >= 3 else { return }189            try? await Task.sleep(for: .milliseconds(450))190            guard !Task.isCancelled else { return }191            searchingServer = true192            defer { searchingServer = false }193            // the server's model may be busy (503, API-NEXT D23) or absent: both are « unavailable for now », and the lexical search still works194            do { let r = try await model.next.client.semanticSearch(q, limit: 12); if !Task.isCancelled { senseUnavailable = !r.available; senseHits = r.hits } }195            catch { if !Task.isCancelled, (error as? NextError) != .cancelled { senseUnavailable = true } }196            return197        }198        if model.next.has(.contentSearch), model.network.online, q.count >= 2, ext.isEmpty, !offlineOnly, scope == nil, where_ != .name {199            try? await Task.sleep(for: .milliseconds(350))200            guard !Task.isCancelled else { return }201            searchingServer = true202            var p = SearchParameters(q: q, scope: .content)203            p.starred = starredOnly ? true : nil; p.from = period.from; p.minSize = size.range.0; p.maxSize = size.range.1204            if let found = try? await model.next.client.search(p), !Task.isCancelled {205                contentHits = found.files.filter { f in kind.map { f.fileKind == $0 } ?? true }206                if contentHits.contains(where: { model.store.item($0.id) == nil }) { await model.engine.sync() }207            }208            searchingServer = false209            if where_ == .content { return }210        }211        let name = ext.isEmpty ? text.trimmingCharacters(in: .whitespaces) : ""212        guard model.network.online, name.count >= 2, !offlineOnly, scope == nil else { searchingServer = false; return }213        try? await Task.sleep(for: .milliseconds(350)) // wait for the typing to pause214        guard !Task.isCancelled else { return }215        searchingServer = true216        defer { searchingServer = false }217        var byName = SearchQuery()218        byName.text = name219        byName.starredOnly = starredOnly220        byName.from = period.from221        byName.minSize = size.range.0222        byName.maxSize = size.range.1223        if let found = try? await model.api.search(byName), !Task.isCancelled {224            remote = kind.map { k in found.filter { $0.kind == k } } ?? found225            // results the mirror does not hold yet arrive with the next pull226            if found.contains(where: { model.store.item($0.id) == nil }) { await model.engine.sync() }227        }228    }229}230231/// A file found by its content: the name, then the passage with the matched words highlighted.232struct ContentHitRow: View {233    @Environment(AppModel.self) private var model234    let file: NextFile235    let actions: ItemActions236237    var body: some View {238        Button {239            if let item = model.store.item(file.id) { actions.open(item, model: model) }240        } label: {241            HStack(alignment: .top, spacing: SPDTheme.Space.md) {242                if let item = model.store.item(file.id) { ItemThumbnail(item: item, size: 40) } else { KindIcon(kind: file.fileKind, size: 40) }243                VStack(alignment: .leading, spacing: 4) {244                    Text(file.name).font(.body).lineLimit(2)245                    if let match = file.match, match.snippet != nil { Text(Self.highlighted(match)).font(.footnote).foregroundStyle(.secondary).lineLimit(4) }246                    if let page = file.match?.page { Text("Page \(page)").font(.caption2).foregroundStyle(.tertiary) }247                }248            }249        }250        .buttonStyle(.plain)251        .accessibilityElement(children: .combine)252        .accessibilityIdentifier("hit.\(file.name)")253    }254255    /// The snippet with its matched words in bold on a tinted background (the server marks them with ⟦ ⟧).256    static func highlighted(_ match: SearchMatch) -> AttributedString {257        var out = AttributedString()258        for run in match.snippetRuns {259            var piece = AttributedString(run.text)260            if run.matched { piece.font = .footnote.weight(.bold); piece.foregroundColor = .primary; piece.backgroundColor = SPDTheme.Palette.brand.opacity(0.18) }261            out += piece262        }263        return out264    }265}266
Files main
Menu

Theme