Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Notes9// File : Features/Editor/Blocks/DataBlockSheets.swift10// Description : Sheets of the blocks that point at other data: `queryView`11// (source, filter, layout, limit, title + the rows the12// server resolves), `blockRef` (the referenced block read13// from the local store, open the note at it, embed / link)14// and `canvasLink` (the target page, open it).15// Module : Features16// Repository : https://git.spboucher.ai/sp-notes-ios17// Created : 2026-11-1918// Last Modified : 2026-11-1919//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SPNotesCore93import SPNotesDesign94import SwiftUI9596struct QueryViewBlockSheet: View {97 let original: QueryViewBlock98 let context: BlockDetailContext99 @State private var block: QueryViewBlock100 @State private var state: BlockCardStore.QueryState?101 @State private var isLoading = false102103 init(block: QueryViewBlock, context: BlockDetailContext) {104 original = block105 self.context = context106 _block = State(initialValue: block)107 }108109 private var sources: [QuerySource] { QuerySource.known.contains(block.source) ? QuerySource.known : [block.source] + QuerySource.known }110 private var layouts: [QueryLayout] { QueryLayout.known.contains(block.layout) ? QueryLayout.known : [block.layout] + QueryLayout.known }111112 private func filterBinding(_ keyPath: WritableKeyPath<QueryFilter, String?>) -> Binding<String> {113 Binding(get: { block.filter[keyPath: keyPath] ?? "" }, set: { value in114 var filter = block.filter115 let trimmed = value.trimmingCharacters(in: .whitespaces)116 guard (filter[keyPath: keyPath] ?? "") != trimmed else { return }117 filter[keyPath: keyPath] = trimmed.isEmpty ? nil : trimmed118 block.filter = filter119 })120 }121122 var body: some View {123 BlockSheetScaffold(title: String(localized: "Vue dynamique"), isEditable: context.isEditable, onCancel: context.dismiss,124 onDone: { context.finish(block.node(), original: original.node()) }, onDelete: context.delete) {125 Form {126 Section("Vue") {127 TextField("Titre", text: Binding(get: { block.title }, set: { if $0 != block.title { block.title = $0 } })).accessibilityIdentifier("query-title")128 Picker("Source", selection: Binding(get: { block.source }, set: { if $0 != block.source { block.source = $0 } })) {129 ForEach(sources, id: \.self) { Text(BlockLabels.querySource($0)).tag($0) }130 }131 .accessibilityIdentifier("query-source")132 Picker("Disposition", selection: Binding(get: { block.layout }, set: { if $0 != block.layout { block.layout = $0 } })) {133 ForEach(layouts, id: \.self) { Text(BlockLabels.queryLayout($0)).tag($0) }134 }135 Stepper(value: Binding(get: { block.limit }, set: { if $0 != block.limit { block.limit = $0 } }), in: 1...500, step: 5) {136 LabeledContent("Limite", value: "\(block.limit)")137 }138 }139 .disabled(!context.isEditable)140 Section {141 TextField("Tag", text: filterBinding(\.tag)).textInputAutocapitalization(.never).autocorrectionDisabled()142 TextField("État (open, done, all…)", text: filterBinding(\.status)).textInputAutocapitalization(.never).autocorrectionDisabled()143 TextField("Section", text: filterBinding(\.section)).textInputAutocapitalization(.never).autocorrectionDisabled()144 TextField("Texte contenu", text: filterBinding(\.text))145 } header: { Text("Filtre") } footer: {146 if block.source == .database, block.databaseId == nil { Text("Le choix de la base de données se fait sur le Web pour l’instant.") }147 }148 .disabled(!context.isEditable)149 Section {150 switch state {151 case .rows(let result)?:152 if result.rows.isEmpty { Text("Aucun résultat").foregroundStyle(NVColor.fgMuted) }153 ForEach(Array(result.rows.prefix(50).enumerated()), id: \.offset) { _, row in154 VStack(alignment: .leading, spacing: 2) {155 Text(row.first ?? "").nvFont(.body).foregroundStyle(NVColor.fg)156 let rest = zip(result.columns.dropFirst(), row.dropFirst()).filter { !$0.1.isEmpty }.map { "\($0.0) : \($0.1)" }.joined(separator: " · ")157 if !rest.isEmpty { Text(rest).nvFont(.ui).foregroundStyle(NVColor.fgMuted) }158 }159 }160 if result.fromCache {161 Text("Mis à jour \(result.fetchedAt.formatted(.relative(presentation: .named)))").nvFont(.ui).foregroundStyle(NVColor.fgMuted).accessibilityIdentifier("query-cache-date")162 }163 case .unavailable(let reason)?:164 BlockNotice(text: reason, symbol: "icloud.slash")165 case nil:166 HStack { ProgressView(); Text("Lecture des résultats…").foregroundStyle(NVColor.fgMuted) }167 }168 } header: {169 HStack {170 Text("Résultats")171 Spacer()172 Button { Task { await load(forcing: true) } } label: { Image(systemName: "arrow.clockwise") }173 .disabled(isLoading)174 .accessibilityLabel("Actualiser les résultats")175 }176 }177 }178 }179 .task(id: block.cardKey) { await load(forcing: false) }180 }181182 private func load(forcing: Bool) async {183 isLoading = true184 defer { isLoading = false }185 let resolver = BlockCardResolver(app: context.app, noteId: context.noteId, store: BlockCardStore())186 let result = await resolver.rows(for: block.cardKey, policy: forcing ? .networkFirst : .cacheFirst(maxAge: Staleness.query))187 if !Task.isCancelled { state = result }188 }189}190191struct BlockRefSheet: View {192 let original: BlockRefBlock193 let context: BlockDetailContext194 @State private var block: BlockRefBlock195 @State private var target: BlockCardStore.BlockTarget?196197 init(block: BlockRefBlock, context: BlockDetailContext) {198 original = block199 self.context = context200 _block = State(initialValue: block)201 }202203 private var isMissing: Bool { target != nil && (target?.pageTitle == nil || target?.text == nil) }204205 var body: some View {206 BlockSheetScaffold(title: String(localized: "Référence de bloc"), isEditable: context.isEditable, onCancel: context.dismiss,207 onDone: { context.finish(block.node(), original: original.node()) }, onDelete: context.delete) {208 Form {209 Section("Bloc référencé") {210 if let target {211 if let title = target.pageTitle { Label(title, systemImage: "doc.text").nvFont(.uiStrong).foregroundStyle(NVColor.fg) }212 if let text = target.text, target.pageTitle != nil {213 Text(text.isEmpty ? String(localized: "(bloc vide)") : text).nvFont(.body).foregroundStyle(NVColor.fg).textSelection(.enabled)214 .accessibilityIdentifier("blockref-text")215 } else {216 BlockNotice(text: String(localized: "Référence introuvable"), symbol: "exclamationmark.triangle").accessibilityIdentifier("blockref-missing")217 }218 } else {219 ProgressView()220 }221 }222 if let pageId = block.pageId, target?.pageTitle != nil {223 Section {224 Button {225 let route = AppRoute.note(pageId, blockId: isMissing ? nil : block.blockId)226 context.dismiss()227 context.open(route)228 } label: { Label("Ouvrir la note", systemImage: "arrow.up.forward.square") }229 .accessibilityIdentifier("blockref-open")230 }231 }232 Section {233 Picker("Affichage", selection: Binding(get: { block.mode }, set: { if $0 != block.mode { block.mode = $0 } })) {234 Text("Contenu intégré").tag(BlockRefMode.embed)235 Text("Lien seul").tag(BlockRefMode.link)236 if !BlockRefMode.known.contains(block.mode) { Text(block.mode.rawValue).tag(block.mode) }237 }238 .pickerStyle(.segmented)239 .accessibilityIdentifier("blockref-mode")240 } footer: { Text("Le contenu affiché est toujours celui du bloc d’origine : il se modifie dans sa note.") }241 .disabled(!context.isEditable)242 }243 }244 .task {245 guard let pageId = block.pageId else { target = BlockCardStore.BlockTarget(pageTitle: nil, text: nil); return }246 target = await BlockCardResolver(app: context.app, noteId: context.noteId, store: BlockCardStore()).target(pageId: pageId, blockId: block.blockId)247 }248 }249}250251struct CanvasLinkSheet: View {252 let block: CanvasLinkBlock253 let context: BlockDetailContext254 /// nil = still reading; .some(nil) = no such page here.255 @State private var title: String??256257 var body: some View {258 BlockSheetScaffold(title: "Canvas", isEditable: context.isEditable, onCancel: context.dismiss, onDone: nil, onDelete: context.delete) {259 Form {260 Section("Cible") {261 switch title {262 case .some(.some(let title)): Label(title, systemImage: "rectangle.3.group").nvFont(.uiStrong).foregroundStyle(NVColor.fg).accessibilityIdentifier("canvas-title")263 case .some(.none): BlockNotice(text: String(localized: "Canvas introuvable sur cet appareil"), symbol: "exclamationmark.triangle")264 case .none: ProgressView()265 }266 }267 if let pageId = block.pageId, case .some(.some) = title {268 Section {269 Button {270 context.dismiss()271 context.open(.note(pageId))272 } label: { Label("Ouvrir le canvas", systemImage: "arrow.up.forward.square") }273 .accessibilityIdentifier("canvas-open")274 }275 }276 }277 }278 .task {279 guard let pageId = block.pageId, let page = try? await context.app.store.page(id: pageId), page.deletedAt == nil else { title = .some(nil); return }280 title = .some(AppModel.displayTitle(page.title))281 }282 }283}284