407 lines
25 KiB
Swift
407 lines
25 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import SwiftUI
|
||
|
||
private struct ArchiveCollection: Identifiable {
|
||
let id: String
|
||
let name: String
|
||
let children: [Self]?
|
||
|
||
static func tree(_ paths: [String]) -> [Self] {
|
||
var descendants: [String: Set<String>] = [:]
|
||
for path in paths {
|
||
var parent = ""
|
||
for component in path.split(separator: "/") {
|
||
let child = parent.isEmpty ? String(component) : parent + "/" + component
|
||
descendants[parent, default: []].insert(child); parent = child
|
||
}
|
||
}
|
||
func items(_ parent: String) -> [Self] {
|
||
(descendants[parent] ?? []).sorted { $0.localizedStandardCompare($1) == .orderedAscending }.map { path in
|
||
Self(id: path, name: String(path.split(separator: "/").last ?? ""), children: descendants[path] == nil ? nil : items(path))
|
||
}
|
||
}
|
||
return items("")
|
||
}
|
||
}
|
||
|
||
private struct ArchiveBrowseRequest: Equatable { let collection: String; let offset: Int; let retry: Int }
|
||
private struct ArchiveSearchRequest: Equatable { let query: String; let collection: String?; let offset: Int; let retry: Int }
|
||
private struct ArchiveResultGroup: Identifiable {
|
||
let document: ArchiveDocument
|
||
var hits: [ArchiveHit]
|
||
var id: String { document.id }
|
||
}
|
||
|
||
@MainActor
|
||
final class ArchiveLibraryQuery: ObservableObject {
|
||
@Published var text: String
|
||
init(_ text: String = "") { self.text = text }
|
||
}
|
||
|
||
private struct ArchiveVisibleRows: PreferenceKey {
|
||
static let defaultValue: [String: CGFloat] = [:]
|
||
static func reduce(value: inout [String: CGFloat], nextValue: () -> [String: CGFloat]) { value.merge(nextValue(), uniquingKeysWith: { _, last in last }) }
|
||
}
|
||
|
||
struct ArchiveLibraryView: View {
|
||
@State private var collection = ""
|
||
@State private var browseID: String?
|
||
@State private var browseOffset = 0
|
||
@State private var localScope = false
|
||
@ObservedObject private var navigation = ArchiveLibraryNavigation.shared
|
||
private let continuity: LibraryContinuityStore
|
||
@State private var browseTopID: String?
|
||
@State private var searchTopID: String?
|
||
@State private var restoreBrowseTop: String?
|
||
@State private var restoreSearchTop: String?
|
||
@State private var restoringSearchSelection = false
|
||
@State private var navigationDocument: ArchiveDocument?
|
||
@State private var navigationPage: Int?
|
||
@State private var navigationError: String?
|
||
@State private var collections: [ArchiveCollection] = []
|
||
@State private var documents: [ArchiveDocument] = []
|
||
@State private var hits: [ArchiveHit] = []
|
||
@State private var searchID: String?
|
||
@State private var searchOffset = 0
|
||
@StateObject private var archiveQuery: ArchiveLibraryQuery
|
||
@State private var browseMore = false
|
||
@State private var searchMore = false
|
||
@State private var browseBusy = true
|
||
@State private var searchBusy = false
|
||
@State private var browseError: String?
|
||
@State private var searchError: String?
|
||
@State private var retry = 0
|
||
@State private var compactReader = false
|
||
@State private var showCollections = false
|
||
@State private var searchBrowseCollection: String?
|
||
@State private var searchFolder: String?
|
||
@FocusState private var queryFocused: Bool
|
||
@StateObject private var browseReader: ArchiveReaderModel
|
||
@StateObject private var searchReader: ArchiveReaderModel
|
||
private let batch = 35
|
||
private let catalog: ArchiveLibraryCatalog
|
||
|
||
init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil,
|
||
continuity suppliedContinuity: LibraryContinuityStore? = nil) {
|
||
let continuity = suppliedContinuity ?? .shared
|
||
self.catalog = catalog; self.continuity = continuity
|
||
let saved = continuity.browse(for: "archive-main")
|
||
let defaults = UserDefaults.standard
|
||
_collection = State(initialValue: saved?.scope ?? defaults.string(forKey: "archive-library.collection") ?? "")
|
||
_browseID = State(initialValue: saved?.filters["browseID"] ?? defaults.string(forKey: "archive-library.browse-selection"))
|
||
_browseOffset = State(initialValue: saved?.pageOffset ?? max(0, defaults.integer(forKey: "archive-library.browse-offset")))
|
||
_localScope = State(initialValue: saved?.filters["localScope"].map { $0 == "true" } ?? defaults.bool(forKey: "archive-library.scope"))
|
||
_searchID = State(initialValue: saved?.filters["searchID"])
|
||
_searchOffset = State(initialValue: Int(saved?.filters["searchOffset"] ?? "0") ?? 0)
|
||
_searchFolder = State(initialValue: saved?.filters["searchFolder"])
|
||
_searchBrowseCollection = State(initialValue: saved?.filters["searchBrowseCollection"])
|
||
_browseTopID = State(initialValue: saved?.filters["browseTop"])
|
||
_searchTopID = State(initialValue: saved?.filters["searchTop"])
|
||
_restoreBrowseTop = State(initialValue: saved?.filters["browseTop"])
|
||
_restoreSearchTop = State(initialValue: saved?.filters["searchTop"])
|
||
_restoringSearchSelection = State(initialValue: saved?.filters["searchID"] != nil)
|
||
_browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity))
|
||
_archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery(saved?.query ?? ""))
|
||
_searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity))
|
||
}
|
||
|
||
private var query: String { archiveQuery.text }
|
||
private var searching: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
|
||
private var browseDocument: ArchiveDocument? { navigationDocument.flatMap { $0.id == browseID ? $0 : nil } ?? documents.first { $0.id == browseID } }
|
||
private var hit: ArchiveHit? { hits.first { $0.id == searchID } }
|
||
private var selected: ArchiveDocument? { searching ? hit?.document : browseDocument }
|
||
private var reader: ArchiveReaderModel { searching ? searchReader : browseReader }
|
||
private var requestedPage: Int {
|
||
if searching { return restoringSearchSelection ? hit.map { searchReader.savedPage(for: $0.document.id) } ?? 1 : hit?.locationNumber ?? 1 }
|
||
return navigationPage ?? browseID.map { browseReader.savedPage(for: $0) } ?? 1
|
||
}
|
||
private var browseState: LibraryBrowseState {
|
||
var state = LibraryBrowseState()
|
||
state.scope = collection; state.query = query; state.selectedID = searching ? searchID : browseID; state.pageOffset = browseOffset
|
||
state.filters = ["localScope": String(localScope), "searchOffset": String(searchOffset)]
|
||
for (key,value) in [("browseID",browseID),("searchID",searchID),("searchFolder",searchFolder),("searchBrowseCollection",searchBrowseCollection),("browseTop",browseTopID),("searchTop",searchTopID)] {
|
||
if let value { state.filters[key] = value }
|
||
}
|
||
return state
|
||
}
|
||
private var sidebarPath: String { searching ? (searchFolder ?? collection) : collection }
|
||
private var scopePath: String? {
|
||
if searching, let searchFolder, !searchFolder.isEmpty { return searchFolder }
|
||
return !collection.isEmpty ? collection : (searchBrowseCollection ?? browseDocument?.collection)
|
||
}
|
||
private var key: ArchiveSearchRequest { .init(query: query, collection: localScope ? scopePath : nil, offset: searchOffset, retry: retry) }
|
||
|
||
var body: some View {
|
||
GeometryReader { geometry in
|
||
let narrow = geometry.size.width < 790
|
||
let side = geometry.size.width >= 990
|
||
VStack(spacing: 0) {
|
||
header(narrow: narrow, sidebar: side)
|
||
Divider()
|
||
HSplitView {
|
||
if side { sidebar.frame(minWidth: 150, idealWidth: 180, maxWidth: 220) }
|
||
if !narrow || !compactReader { listing.frame(minWidth: narrow ? 180 : 220, idealWidth: 290, maxWidth: narrow ? .infinity : 365) }
|
||
if !narrow || compactReader {
|
||
// An empty reader must accept the full pane height, just like the PDF reader.
|
||
detail.frame(minWidth: narrow ? 230 : 330, maxWidth: .infinity, maxHeight: .infinity)
|
||
}
|
||
}
|
||
}.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
}
|
||
.frame(minWidth: 430, minHeight: 320)
|
||
.task(id: retry) {
|
||
do {
|
||
let paths = try await catalog.collections(); try Task.checkCancellation()
|
||
collections = ArchiveCollection.tree(paths)
|
||
let valid = Set(paths.flatMap { path -> [String] in
|
||
let parts = path.split(separator: "/")
|
||
guard !parts.isEmpty else { return [] }
|
||
return (1...parts.count).map { parts.prefix($0).joined(separator: "/") }
|
||
})
|
||
if !collection.isEmpty, !valid.contains(collection) {
|
||
collection = ""; browseID = nil; browseOffset = 0
|
||
}
|
||
}
|
||
catch { if !Task.isCancelled { browseError = error.localizedDescription } }
|
||
}
|
||
.task(id: ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)) { await loadBrowse() }
|
||
.task(id: key) { await loadSearch(key) }
|
||
.task(id: navigation.request?.id) { if let request = navigation.request { await openRequested(request) } }
|
||
.onChange(of: browseState) { _, value in continuity.setBrowse(value, for: "archive-main") }
|
||
.onChange(of: query) { old, new in
|
||
navigationError = nil
|
||
if old.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !new.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
|
||
searchBrowseCollection = browseDocument?.collection
|
||
if browseReader.progress != nil { browseReader.stop() }
|
||
}
|
||
restoringSearchSelection = false; restoreSearchTop = nil
|
||
searchID = nil; searchOffset = 0; compactReader = false; searchReader.reset()
|
||
if !searching { searchBrowseCollection = nil; searchFolder = nil }
|
||
}
|
||
.onChange(of: localScope) { _, _ in searchOffset = 0; searchID = nil; compactReader = false; searchReader.reset() }
|
||
.onChange(of: browseID) { _, id in
|
||
navigationError = nil
|
||
if id != navigationDocument?.id { navigationDocument = nil; navigationPage = nil }
|
||
if id == nil { browseReader.reset() }
|
||
else if !searching { compactReader = true }
|
||
}
|
||
.onChange(of: searchID) { _, id in
|
||
navigationError = nil
|
||
// Initial restoration sets State before observation starts. A later
|
||
// selection change (including keyboard arrows) is an explicit hit.
|
||
if id != nil { restoringSearchSelection = false }
|
||
if id == nil { searchReader.reset() }
|
||
else if searching { compactReader = true }
|
||
}
|
||
.onDisappear { continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint(); browseReader.stop(); searchReader.stop() }
|
||
.onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint() }
|
||
}
|
||
|
||
private func header(narrow: Bool, sidebar side: Bool) -> some View {
|
||
HStack {
|
||
if narrow, compactReader {
|
||
Button { compactReader = false } label: { Label(searching ? "Results" : "Browse", systemImage: "chevron.left") }
|
||
} else if !side {
|
||
Button { showCollections.toggle() } label: { Label("Collections", systemImage: "sidebar.left") }
|
||
.popover(isPresented: $showCollections) { sidebar.frame(width: 255, height: 360) }
|
||
}
|
||
HStack(spacing: 5) {
|
||
Button { queryFocused = true } label: { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) }
|
||
.buttonStyle(.plain).keyboardShortcut("f", modifiers: [.command, .shift]).accessibilityLabel("Focus Archive search")
|
||
TextField("Search Archive", text: $archiveQuery.text).textFieldStyle(.plain).focused($queryFocused)
|
||
.accessibilityLabel("Search Archive").accessibilityIdentifier("archive-search")
|
||
Button { archiveQuery.text = ""; queryFocused = true } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) }
|
||
.buttonStyle(.plain).accessibilityLabel("Clear Archive search")
|
||
.opacity(query.isEmpty ? 0 : 1).disabled(query.isEmpty).accessibilityHidden(query.isEmpty)
|
||
}.padding(6).background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
|
||
Picker("Search scope", selection: $localScope) {
|
||
Text("Entire Archive").tag(false)
|
||
Text(scopePath?.split(separator: "/").last.map(String.init) ?? "Current collection").tag(true).disabled(scopePath == nil)
|
||
}.labelsHidden().frame(width: narrow ? 115 : 160).accessibilityLabel("Archive search scope")
|
||
Button { MCPArchiveAccess.shared.show() } label: { Image(systemName: "link") }
|
||
.help("Archive Search connection for MCP").accessibilityLabel("Archive Search connection for MCP")
|
||
}.padding(8)
|
||
}
|
||
|
||
private var sidebar: some View {
|
||
VStack(alignment: .leading, spacing: 0) {
|
||
Button { chooseCollection("") } label: {
|
||
Label("All Documents", systemImage: "books.vertical")
|
||
.fontWeight(sidebarPath.isEmpty ? .semibold : .regular)
|
||
.frame(maxWidth: .infinity, alignment: .leading).padding(6)
|
||
.background(sidebarPath.isEmpty ? Color.accentColor.opacity(0.13) : .clear, in: RoundedRectangle(cornerRadius: 5))
|
||
}.buttonStyle(.plain).padding(7).accessibilityAddTraits(sidebarPath.isEmpty ? .isSelected : [])
|
||
List(selection: Binding<String?>(get: { sidebarPath.isEmpty ? nil : sidebarPath }, set: { if let value = $0 { chooseCollection(value) } })) {
|
||
Section("Collections") {
|
||
OutlineGroup(collections, children: \.children) { folder in
|
||
Label(folder.name, systemImage: folder.children == nil ? "folder" : "folder.fill").tag(folder.id)
|
||
}
|
||
}
|
||
}.listStyle(.sidebar).accessibilityLabel("Archive collections")
|
||
}
|
||
}
|
||
|
||
private func chooseCollection(_ path: String) {
|
||
showCollections = false; navigationError = nil; navigationDocument = nil; navigationPage = nil; restoreBrowseTop = nil; restoreSearchTop = nil
|
||
if searching {
|
||
if path != sidebarPath { searchID = nil; searchReader.reset() }
|
||
searchFolder = path; searchOffset = 0; localScope = !path.isEmpty; compactReader = false
|
||
return
|
||
}
|
||
guard path != collection else { return }
|
||
collection = path; browseID = nil; browseOffset = 0; compactReader = false; browseReader.reset()
|
||
}
|
||
|
||
private var listing: some View {
|
||
VStack(alignment: .leading, spacing: 0) {
|
||
HStack {
|
||
Text(searching ? "Matching pages" : (collection.isEmpty ? "All Documents" : String(collection.split(separator: "/").last ?? ""))).font(.headline)
|
||
Spacer()
|
||
if searching ? searchBusy : browseBusy { ProgressView().controlSize(.small) }
|
||
}.padding(10)
|
||
Divider()
|
||
if let error = searching ? searchError : browseError {
|
||
VStack(spacing: 8) { Text(error).multilineTextAlignment(.center); Button("Try Again") { retry += 1 } }.padding().frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
} else {
|
||
// Keeping the browse List mounted preserves its scroll position and selection through a search.
|
||
ZStack {
|
||
browseList.opacity(searching ? 0 : 1).allowsHitTesting(!searching).accessibilityHidden(searching).disabled(searching)
|
||
if searching { resultsList }
|
||
}
|
||
Divider()
|
||
HStack {
|
||
Button { moveBatch(-1) } label: { Image(systemName: "chevron.left") }.accessibilityLabel("Previous results").disabled((searching ? searchOffset : browseOffset) == 0)
|
||
let count = searching ? hits.count : documents.count
|
||
if count > 0 { let offset = searching ? searchOffset : browseOffset; Text("\(offset + 1)–\(offset + count)").font(.caption).monospacedDigit() }
|
||
Button { moveBatch(1) } label: { Image(systemName: "chevron.right") }.accessibilityLabel("Next results").disabled(!(searching ? searchMore : browseMore))
|
||
Spacer()
|
||
}.padding(8)
|
||
}
|
||
}
|
||
}
|
||
|
||
private var browseList: some View {
|
||
ScrollViewReader { proxy in
|
||
List(selection: $browseID) {
|
||
ForEach(documents) { doc in
|
||
VStack(alignment: .leading, spacing: 3) {
|
||
Text(doc.title).lineLimit(2)
|
||
Text(doc.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
|
||
}.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id).id(doc.id)
|
||
.background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [doc.id: value.frame(in: .named("archive-browse")).minY]) })
|
||
.simultaneousGesture(TapGesture().onEnded { browseID = doc.id; compactReader = true })
|
||
}
|
||
}.coordinateSpace(name: "archive-browse")
|
||
.onPreferenceChange(ArchiveVisibleRows.self) { rows in if !searching { browseTopID = topRow(rows) } }
|
||
.onChange(of: documents.map(\.id)) { _, ids in
|
||
if let target = restoreBrowseTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreBrowseTop = nil }
|
||
}
|
||
.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list")
|
||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||
.overlay { if documents.isEmpty, !browseBusy { ContentUnavailableView("No documents in this collection", systemImage: "books.vertical") } }
|
||
}
|
||
}
|
||
|
||
private var groups: [ArchiveResultGroup] {
|
||
var ordered: [ArchiveResultGroup] = []; var indices: [String: Int] = [:]
|
||
for item in hits {
|
||
if let index = indices[item.document.id] { ordered[index].hits.append(item) }
|
||
else { indices[item.document.id] = ordered.count; ordered.append(.init(document: item.document, hits: [item])) }
|
||
}
|
||
return ordered
|
||
}
|
||
private var resultsList: some View {
|
||
ScrollViewReader { proxy in
|
||
List(selection: $searchID) {
|
||
ForEach(groups) { group in
|
||
Section {
|
||
ForEach(group.hits) { result in
|
||
HStack { Text(result.locator); if result.ocr { Text("OCR").font(.caption).foregroundStyle(.secondary) } }
|
||
.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id).id(result.id)
|
||
.background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [result.id: value.frame(in: .named("archive-search")).minY]) })
|
||
.simultaneousGesture(TapGesture().onEnded { restoringSearchSelection = false; restoreSearchTop = nil; searchID = result.id; compactReader = true })
|
||
}
|
||
} header: { Text(group.document.title).lineLimit(3).textCase(nil) }
|
||
}
|
||
}.coordinateSpace(name: "archive-search")
|
||
.onPreferenceChange(ArchiveVisibleRows.self) { rows in if searching { searchTopID = topRow(rows) } }
|
||
.onChange(of: hits.map(\.id)) { _, ids in
|
||
if let target = restoreSearchTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreSearchTop = nil }
|
||
}
|
||
.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list")
|
||
.onKeyPress(.return, action: readSelectedWithKeyboard)
|
||
.overlay { if hits.isEmpty, !searchBusy { ContentUnavailableView("No matching pages", systemImage: "magnifyingglass") } }
|
||
}
|
||
}
|
||
private func topRow(_ positions: [String: CGFloat]) -> String? {
|
||
positions.filter { $0.value <= 0 }.max(by: { $0.value < $1.value })?.key ?? positions.min(by: { $0.value < $1.value })?.key
|
||
}
|
||
|
||
@ViewBuilder private var detail: some View {
|
||
if let navigationError {
|
||
ContentUnavailableView("Reference unavailable", systemImage: "book.closed", description: Text(navigationError))
|
||
} else if let selected {
|
||
ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog, resumesPosition: searching ? restoringSearchSelection : navigationPage == nil)
|
||
} else { ContentUnavailableView("Choose a document", systemImage: "book.pages", description: Text("Browse a collection or search the Archive.")) }
|
||
}
|
||
private func openRequested(_ request: ArchiveLibraryOpenRequest) async {
|
||
do {
|
||
guard let record = try await catalog.document(id: request.documentID),
|
||
request.expectedSHA256 == nil || request.expectedSHA256 == record.id,
|
||
request.location.map({ $0 > 0 && $0 <= (record.pageCount ?? 1_000_000) }) != false else {
|
||
throw ArchiveLibraryError.input("This reference no longer matches the installed Archive index. The software selection has not changed.")
|
||
}
|
||
guard let offset = try await catalog.browseOffset(documentID: record.id, collection: record.collection, batchSize: batch) else {
|
||
throw ArchiveLibraryError.input("The reference could not be located in the installed Archive collection.")
|
||
}
|
||
try Task.checkCancellation()
|
||
guard navigation.request?.id == request.id else { return }
|
||
navigationError = nil; archiveQuery.text = ""; collection = record.collection; browseOffset = offset
|
||
navigationDocument = record; navigationPage = request.location; browseID = record.id
|
||
restoreBrowseTop = record.id; compactReader = true
|
||
browseReader.open(record, page: request.location ?? browseReader.savedPage(for: record.id), resumePosition: request.location == nil)
|
||
navigation.consumed(request.id)
|
||
} catch {
|
||
guard !Task.isCancelled, navigation.request?.id == request.id else { return }
|
||
navigationError = error.localizedDescription; compactReader = true; navigation.consumed(request.id)
|
||
}
|
||
}
|
||
private func moveBatch(_ direction: Int) {
|
||
navigationError = nil; navigationDocument = nil; navigationPage = nil; restoringSearchSelection = false
|
||
restoreBrowseTop = nil; restoreSearchTop = nil
|
||
if searching { searchOffset = max(0, searchOffset + direction * batch); searchID = nil }
|
||
else { browseOffset = max(0, browseOffset + direction * batch); browseID = nil }
|
||
}
|
||
private func readSelectedWithKeyboard() -> KeyPress.Result {
|
||
guard selected != nil else { return .ignored }
|
||
// On compact layouts Return can reopen the current row after Back.
|
||
Task { @MainActor in compactReader = true }
|
||
return .handled
|
||
}
|
||
private func loadBrowse() async {
|
||
let request = ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)
|
||
browseBusy = true; browseError = nil
|
||
do {
|
||
let rows = try await catalog.browse(collection: collection.isEmpty ? nil : collection, limit: batch + 1, offset: browseOffset)
|
||
try Task.checkCancellation()
|
||
guard request == ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) else { return }
|
||
if rows.isEmpty, browseOffset > 0 { browseOffset = 0; browseID = nil; browseBusy = false; return }
|
||
documents = Array(rows.prefix(batch)); browseMore = rows.count > batch
|
||
if !documents.contains(where: { $0.id == browseID }) { browseID = nil }
|
||
browseBusy = false
|
||
} catch { if !Task.isCancelled { browseError = error.localizedDescription; browseBusy = false } }
|
||
}
|
||
private func loadSearch(_ request: ArchiveSearchRequest) async {
|
||
searchError = nil; hits = []; searchMore = false
|
||
guard searching else { searchBusy = false; return }
|
||
searchBusy = true
|
||
do {
|
||
try await Task.sleep(for: .milliseconds(180))
|
||
let rows = try await catalog.search(query: request.query, collection: request.collection, limit: batch + 1, offset: request.offset)
|
||
try Task.checkCancellation(); guard key == request else { return }
|
||
hits = Array(rows.prefix(batch)); searchMore = rows.count > batch
|
||
if !hits.contains(where: { $0.id == searchID }) { searchID = nil }; searchBusy = false
|
||
} catch { if !Task.isCancelled { searchError = error.localizedDescription; searchBusy = false } }
|
||
}
|
||
}
|