Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/QueryViewBlockModel.swift3// Description: View model of a living block (`queryView` node, SPEC §2 / API-NEXT §4.7): builds the `POST /api/query`4// body from the node, resolves it through `KnowledgeRepository.query` (server-computed, cached with its5// date for offline), and turns the rows into a small display model for the list / table / board layouts.6// The row rules follow the web client (`src/lib/editor/query.ts`): board = grouped by status in order of7// first appearance, overdue = past the end of the due day.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Observation13import SPNotesAPI14import SPNotesDocument15import SPNotesSync1617/// One row as the layouts show it.18public struct QueryRowDisplay: Identifiable, Equatable, Sendable {19 public var id: String20 public var title: String21 public var subtitle: String22 public var icon: String?23 public var status: String?24 public var done: Bool25 public var due: Date?26 public var overdue: Bool27 /// The page to open; nil = the row opens nothing (a task or a reference without page).28 public var pageId: String?29 public var blockId: String?30}3132public struct QueryRowGroup: Identifiable, Equatable, Sendable {33 /// The raw status; nil = rows without a status.34 public var status: String?35 public var rows: [QueryRowDisplay]36 public var id: String { status ?? "\u{0}none" }37}3839public enum QueryViewLogic {40 public enum Problem: Error, Equatable, Sendable {41 /// A source written by a newer editor.42 case unknownSource(String)43 /// `database` without a database.44 case needsDatabase45 /// `backlinks` outside a page.46 case needsPage47 }4849 /// The request of a node, or why it cannot be asked. Empty filter values are omitted, as on the web.50 public static func liveQuery(for block: QueryViewBlock, hostPageId: String?) -> Result<LiveQuery, Problem> {51 guard block.source.isKnown else { return .failure(.unknownSource(block.source.rawValue)) }52 let f = block.filter53 func clean(_ value: String?) -> String? {54 guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil }55 return value56 }57 let filter = LiveQueryFilter(tag: clean(f.tag), section: clean(f.section), status: clean(f.status), parentId: clean(f.parentId), text: clean(f.text),58 dueBefore: clean(f.dueBefore), dueAfter: clean(f.dueAfter))59 let isEmpty = filter == LiveQueryFilter()60 var query = LiveQuery(source: block.source.rawValue, limit: min(500, max(1, block.limit)), filter: isEmpty ? nil : filter)61 switch block.source {62 case .database:63 guard let id = block.databaseId else { return .failure(.needsDatabase) }64 query.databaseId = id65 query.viewId = block.viewId66 case .backlinks:67 guard let hostPageId, !hostPageId.isEmpty else { return .failure(.needsPage) }68 query.pageId = hostPageId69 default: break70 }71 return .success(query)72 }7374 public static func rows(_ result: LiveQueryResult, now: Date) -> [QueryRowDisplay] {75 result.rows.map { row in76 let status = nonEmpty(row.string("status"))77 let done = row.bool("done") == true || row.bool("checked") == true || ["done", "completed", "closed"].contains((status ?? "").lowercased())78 let due = row.date("dueAt") ?? row.date("due")79 let title = nonEmpty(row.string("title")) ?? nonEmpty(row.string("name")) ?? nonEmpty(row.string("citeKey")) ?? L("Sans titre")80 let pageId = row.pageId ?? (result.source == LiveQuerySource.pages || result.source == LiveQuerySource.backlinks ? row.id : nil)81 return QueryRowDisplay(id: row.id, title: title, subtitle: subtitle(row, source: result.source), icon: nonEmpty(row.string("icon")), status: status, done: done,82 due: due, overdue: isOverdue(due: due, done: done, now: now), pageId: pageId, blockId: nonEmpty(row.string("blockId")))83 }84 }8586 static func subtitle(_ row: LiveQueryRow, source: String) -> String {87 switch source {88 case LiveQuerySource.references:89 let authors = row.strings("authors") ?? []90 let names = authors.prefix(3).joined(separator: ", ") + (authors.count > 3 ? " et al." : "")91 let year = row.number("year").map { String(Int($0)) } ?? ""92 return [names, year, row.string("journal") ?? ""].filter { !$0.isEmpty }.joined(separator: " · ")93 case LiveQuerySource.tasks:94 return [row.string("pageTitle") ?? "", row.string("project") ?? ""].filter { !$0.isEmpty }.joined(separator: " · ")95 case LiveQuerySource.pages, LiveQuerySource.backlinks:96 return sectionLabel(row.string("section"))97 default:98 return ""99 }100 }101102 /// Board layout: grouped by status, in order of first appearance; rows without a status in one group.103 public static func groups(_ rows: [QueryRowDisplay]) -> [QueryRowGroup] {104 var order: [String?] = []105 var buckets: [String?: [QueryRowDisplay]] = [:]106 for row in rows {107 if buckets[row.status] == nil { order.append(row.status) }108 buckets[row.status, default: []].append(row)109 }110 return order.map { QueryRowGroup(status: $0, rows: buckets[$0] ?? []) }111 }112113 /// Past the end of its due day (the day of the stored instant in UTC: a bare day is noon UTC on the server).114 public static func isOverdue(due: Date?, done: Bool, now: Date) -> Bool {115 guard let due, !done else { return false }116 var calendar = Calendar(identifier: .gregorian)117 calendar.timeZone = utc118 guard let end = calendar.date(byAdding: .day, value: 1, to: calendar.startOfDay(for: due)) else { return false }119 return now >= end120 }121122 static let utc = TimeZone(identifier: "UTC") ?? .gmt123124 public static func statusLabel(_ status: String?) -> String {125 switch status {126 case nil, "": return L("Sans état")127 case "todo": return L("À faire")128 case "doing": return L("En cours")129 case "done": return L("Terminée")130 default: return status ?? ""131 }132 }133134 /// The French name of the server's fixed choices (task status and priority, page section); anything else as sent.135 public static func selectLabel(_ value: String) -> String {136 switch value {137 case "todo", "doing", "done": return statusLabel(value)138 case "low": return L("Basse")139 case "medium": return L("Moyenne")140 case "high": return L("Haute")141 case "notes", "projects", "journal", "research": return sectionLabel(value)142 default: return value143 }144 }145146 public static func sectionLabel(_ section: String?) -> String {147 switch section {148 case "notes": return L("Notes")149 case "projects": return L("Projets")150 case "journal": return L("Journal")151 case "research": return L("Recherche")152 case nil, "": return ""153 default: return section ?? ""154 }155 }156157 public static func sourceLabel(_ source: QuerySource) -> String {158 switch source {159 case .tasks: return L("Tâches")160 case .pages: return L("Pages")161 case .database: return L("Base de données")162 case .references: return L("Références")163 case .backlinks: return L("Rétroliens")164 default: return source.rawValue165 }166 }167168 public static func sourceSymbol(_ source: QuerySource) -> String {169 switch source {170 case .tasks: return "checklist"171 case .pages: return "doc.text"172 case .database: return "tablecells"173 case .references: return "books.vertical"174 case .backlinks: return "arrow.uturn.backward"175 default: return "questionmark.square.dashed"176 }177 }178179 public static func layoutLabel(_ layout: QueryLayout) -> String {180 switch layout {181 case .list: return L("Liste")182 case .table: return L("Tableau")183 case .board: return L("Tableau kanban")184 default: return layout.rawValue185 }186 }187188 public static func layoutSymbol(_ layout: QueryLayout) -> String {189 switch layout {190 case .table: return "tablecells"191 case .board: return "rectangle.split.3x1"192 default: return "list.bullet"193 }194 }195196 /// The text of a table cell for a column type: dates as days, booleans as words, the rest as sent.197 public static func cellText(_ cell: LiveQueryCell, type: String) -> String {198 switch cell {199 case .null: return ""200 case .bool(let value): return value ? L("Oui") : L("Non")201 case .number: return cell.text ?? ""202 case .text(let text):203 if type == LiveQueryColumnType.date, let date = APIDate.parse(text) { return FeatureFormat.day(date, timeZone: utc) }204 if type == LiveQueryColumnType.select { return selectLabel(text) }205 return text206 }207 }208209 private static func nonEmpty(_ value: String?) -> String? {210 guard let value, !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return nil }211 return value212 }213}214215@Observable @MainActor216public final class QueryViewBlockModel {217 public private(set) var block: QueryViewBlock218 public private(set) var phase: LoadPhase = .idle219 public private(set) var freshness: Freshness?220 public private(set) var result: LiveQueryResult?221 public private(set) var rows: [QueryRowDisplay] = []222 /// The node cannot be asked as it is (unknown source, missing database or page).223 public private(set) var problem: QueryViewLogic.Problem?224 /// Local databases, for the settings of a `database` source.225 public private(set) var databases: [DatabaseInfo] = []226 public var onChange: ((QueryViewBlock) -> Void)?227228 private let knowledge: KnowledgeRepository229 private let databasesRepository: DatabasesRepository230 private weak var router: (any FeatureRouter)?231 private let hostPageId: String?232 private let now: @Sendable () -> Date233234 /// - Parameter hostPageId: the page that contains the block (the subject of a `backlinks` source).235 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, block: QueryViewBlock, hostPageId: String? = nil,236 now: @escaping @Sendable () -> Date = { Date() }, onChange: ((QueryViewBlock) -> Void)? = nil) {237 knowledge = repositories.knowledge238 databasesRepository = repositories.databases239 self.router = router240 self.block = block241 self.hostPageId = hostPageId242 self.now = now243 self.onChange = onChange244 }245246 public var title: String { block.title.isEmpty ? QueryViewLogic.sourceLabel(block.source) : block.title }247 public var layout: QueryLayout { block.layout.isKnown ? block.layout : .list }248 public var groups: [QueryRowGroup] { QueryViewLogic.groups(rows) }249 public var total: Int { result?.total ?? rows.count }250 /// Rows the server has beyond the node's `limit`.251 public var hiddenCount: Int { max(0, total - rows.count) }252 public var databaseId: String? { result?.databaseId ?? block.databaseId }253254 public func load() async {255 databases = (try? await databasesRepository.list()) ?? []256 switch QueryViewLogic.liveQuery(for: block, hostPageId: hostPageId) {257 case .failure(let problem):258 self.problem = problem259 result = nil260 rows = []261 freshness = nil262 phase = .loaded263 case .success(let query):264 problem = nil265 phase = .loading266 do {267 let cached = try await knowledge.query(query)268 result = cached.value269 rows = QueryViewLogic.rows(cached.value, now: now())270 freshness = Freshness(cached)271 phase = .loaded272 } catch {273 phase = .failed(FeatureFailure(error))274 }275 }276 }277278 public func open(_ row: QueryRowDisplay) {279 guard let pageId = row.pageId else { return }280 router?.openPage(id: pageId, blockId: row.blockId)281 }282283 public func openDatabase() {284 guard let databaseId else { return }285 router?.openDatabase(id: databaseId)286 }287288 /// Changes how the same rows are laid out (an edit of the node; nothing to ask again).289 public func setLayout(_ layout: QueryLayout) {290 guard layout != block.layout else { return }291 block.layout = layout292 onChange?(block)293 }294295 /// Applies edited settings to the node, hands it to the editor and resolves it again.296 public func apply(_ settings: QueryViewSettings) async {297 var next = block298 next.title = settings.title.trimmingCharacters(in: .whitespacesAndNewlines)299 next.source = settings.source300 next.limit = settings.limit301 var filter = next.filter302 filter.text = Self.clean(settings.text)303 filter.tag = Self.clean(settings.tag)304 filter.status = Self.clean(settings.status)305 next.filter = filter306 if settings.source == .database {307 if settings.databaseId != next.databaseId { next.viewId = nil }308 next.databaseId = settings.databaseId309 }310 guard next != block else { return }311 block = next312 onChange?(block)313 await load()314 }315316 public var settings: QueryViewSettings {317 QueryViewSettings(title: block.title, source: block.source, limit: block.limit, text: block.filter.text ?? "", tag: block.filter.tag ?? "",318 status: block.filter.status ?? "", databaseId: block.databaseId)319 }320321 private static func clean(_ value: String) -> String? {322 let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)323 return trimmed.isEmpty ? nil : trimmed324 }325}326327/// The editable part of a `queryView` node (the other filter keys are kept untouched).328public struct QueryViewSettings: Equatable, Sendable {329 public var title: String330 public var source: QuerySource331 public var limit: Int332 public var text: String333 public var tag: String334 public var status: String335 public var databaseId: String?336337 public init(title: String, source: QuerySource, limit: Int, text: String, tag: String, status: String, databaseId: String?) {338 self.title = title339 self.source = source340 self.limit = limit341 self.text = text342 self.tag = tag343 self.status = status344 self.databaseId = databaseId345 }346347 /// The `status` values the server understands for a source (API-NEXT §4.7); empty = its default.348 public static func statusChoices(for source: QuerySource) -> [String] {349 switch source {350 case .tasks: return ["", "todo", "doing", "done", "all"]351 case .pages: return ["", "archived", "pinned", "all"]352 default: return []353 }354 }355356 public static func statusChoiceLabel(_ value: String, source: QuerySource) -> String {357 switch value {358 case "": return source == .tasks ? L("Ouvertes") : L("Actives")359 case "all": return L("Toutes")360 case "archived": return L("Archivées")361 case "pinned": return L("Épinglées")362 default: return QueryViewLogic.statusLabel(value)363 }364 }365}366