Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/QueryViewBlockView.swift3// Description: Detail of a living block (`queryView`): the resolved rows as a list, a table (cards on a phone) or a4// board by status, with the date of the copy when offline, the count beyond the limit, and the settings5// of the node (title, source, limit, text / tag / status filters, database).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesAPI10import SPNotesDesign11import SPNotesDocument12import SPNotesSync13import SwiftUI1415public struct QueryViewBlockView: View {16 @State private var model: QueryViewBlockModel17 @State private var showsSettings: Bool18 @State private var draft: QueryViewSettings19 @Environment(\.featureNow) private var fixedNow20 @ScaledMetric(relativeTo: .footnote) private var tableRowHeight: CGFloat = 3421 @Environment(\.accessibilityReduceMotion) private var reduceMotion2223 public init(model: QueryViewBlockModel, showsSettings: Bool = false) {24 _model = State(initialValue: model)25 _showsSettings = State(initialValue: showsSettings)26 _draft = State(initialValue: model.settings)27 }2829 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, block: QueryViewBlock, hostPageId: String? = nil,30 onChange: ((QueryViewBlock) -> Void)? = nil) {31 self.init(model: QueryViewBlockModel(repositories: repositories, router: router, block: block, hostPageId: hostPageId, onChange: onChange))32 }3334 public var body: some View {35 BlockDetailContainer(title: model.title, systemImage: QueryViewLogic.sourceSymbol(model.block.source), subtitle: subtitle, accessory: {36 HStack(spacing: NVSpace.sm) {37 FeatureIconButton("slider.horizontal.3", label: showsSettings ? L("Masquer les réglages") : L("Réglages de la vue"), tone: showsSettings ? .accent : .neutral) {38 draft = model.settings39 withNVAnimation(.base, reduceMotion: reduceMotion) { showsSettings.toggle() }40 }41 FeatureIconButton("arrow.clockwise", label: L("Actualiser")) { Task { await model.load() } }42 }43 }) { sizeClass in44 VStack(alignment: .leading, spacing: NVSpace.lg) {45 FeatureStatusBanner(failure: model.rows.isEmpty ? nil : model.phase.failure, freshness: model.freshness) { Task { await model.load() } }46 if showsSettings { settings(compact: sizeClass.isCompact) }47 layoutSwitch48 results(compact: sizeClass.isCompact)49 }50 }51 .task { if model.phase == .idle { await model.load() } }52 }5354 private var subtitle: String? {55 guard model.problem == nil, model.result != nil else { return QueryViewLogic.sourceLabel(model.block.source) }56 var parts = [QueryViewLogic.sourceLabel(model.block.source)]57 if let name = model.result?.name, !name.isEmpty { parts.append(name) }58 parts.append(model.hiddenCount > 0 ? LF("%1$lld sur %2$lld", model.rows.count, model.total) : (model.rows.count == 1 ? L("1 élément") : LF("%lld éléments", model.rows.count)))59 return parts.joined(separator: " · ")60 }6162 private var layoutSwitch: some View {63 VStack(alignment: .leading, spacing: NVSpace.sm) {64 QueryChipFlow {65 ForEach(QueryLayout.known, id: \.self) { layout in66 NVChip(QueryViewLogic.layoutLabel(layout), systemImage: QueryViewLogic.layoutSymbol(layout), tone: .accent, isSelected: model.layout == layout) {67 model.setLayout(layout)68 }69 }70 }71 if model.block.source == .database, model.databaseId != nil {72 FeatureButton(L("Ouvrir la base"), systemImage: "arrow.up.right") { model.openDatabase() }73 }74 }75 }7677 // MARK: results7879 @ViewBuilder80 private func results(compact: Bool) -> some View {81 if let problem = model.problem {82 BlockNotice(systemImage: "questionmark.square.dashed", text: Self.text(problem), tone: .warning)83 } else if model.rows.isEmpty {84 switch model.phase {85 case .idle, .loading: FeatureLoadingView().frame(minHeight: 160)86 case .failed(let failure): FeatureFailureView(failure: failure) { Task { await model.load() } }.frame(minHeight: 220)87 case .loaded:88 NVEmptyState(systemImage: "tray", title: L("Aucun résultat"), message: L("Rien ne correspond à cette vue pour l'instant."))89 .frame(maxWidth: .infinity, minHeight: 200)90 }91 } else {92 switch model.layout {93 case .table: table(compact: compact)94 case .board: board(compact: compact)95 default: list(compact: compact)96 }97 if model.hiddenCount > 0 {98 Text(LF("%lld autres éléments au-delà de la limite de la vue.", model.hiddenCount)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)99 }100 }101 }102103 static func text(_ problem: QueryViewLogic.Problem) -> String {104 switch problem {105 case .unknownSource(let source): return LF("Cette vue utilise une source (« %@ ») que cette version de l'app ne connaît pas. Elle est conservée telle quelle.", source)106 case .needsDatabase: return L("Choisissez une base de données dans les réglages de la vue.")107 case .needsPage: return L("Les rétroliens ne se calculent que dans une page.")108 }109 }110111 private func list(compact: Bool) -> some View {112 VStack(spacing: 0) {113 ForEach(Array(model.rows.enumerated()), id: \.element.id) { index, row in114 QueryRowView(row: row, compact: compact, showsStatus: true) { model.open(row) }115 if index < model.rows.count - 1 { Rectangle().fill(NVColor.line).frame(height: 1).padding(.leading, NVSpace.md) }116 }117 }118 .nvCard()119 }120121 @ViewBuilder122 private func table(compact: Bool) -> some View {123 if let result = model.result {124 if compact {125 // A phone gets one card per row with its labelled values, not a shrunken grid.126 VStack(spacing: NVSpace.sm) {127 ForEach(Array(result.table.rows.enumerated()), id: \.offset) { index, cells in128 let row = index < model.rows.count ? model.rows[index] : nil129 Button { if let row { model.open(row) } } label: {130 VStack(alignment: .leading, spacing: NVSpace.xs) {131 ForEach(Array(result.table.columns.enumerated()), id: \.offset) { column, label in132 let text = Self.cell(result, cells, column)133 if column == 0 {134 Text(text.isEmpty ? L("Sans titre") : text).nvFont(.uiStrong).foregroundStyle(NVColor.fg).multilineTextAlignment(.leading)135 } else if !text.isEmpty {136 HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {137 Text(label).nvFont(.micro).foregroundStyle(NVColor.fgMuted).frame(width: 96, alignment: .leading)138 Text(text).nvFont(.ui).foregroundStyle(NVColor.fg).multilineTextAlignment(.leading)139 Spacer(minLength: 0)140 }141 }142 }143 }144 .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)145 .padding(NVSpace.md)146 .contentShape(Rectangle())147 }148 .buttonStyle(.plain)149 .disabled(row?.pageId == nil)150 .nvCard(radius: NVRadius.md)151 }152 }153 } else {154 // One VStack per column: every column takes the width of its widest single-line cell.155 ScrollView(.horizontal, showsIndicators: false) {156 HStack(alignment: .top, spacing: 0) {157 ForEach(Array(result.table.columns.enumerated()), id: \.offset) { column, label in158 VStack(alignment: .leading, spacing: 0) {159 Text(label).nvFont(.uiStrong).foregroundStyle(NVColor.fgMuted).lineLimit(1).fixedSize()160 .padding(.horizontal, NVSpace.md)161 .frame(minWidth: 96, maxWidth: .infinity, minHeight: tableRowHeight, alignment: .leading)162 .background(NVColor.bgSunken)163 ForEach(Array(result.table.rows.enumerated()), id: \.offset) { index, cells in164 let row = index < model.rows.count ? model.rows[index] : nil165 let text = Self.cell(result, cells, column)166 Rectangle().fill(NVColor.line).frame(height: 1)167 Group {168 if column == 0, let row, row.pageId != nil {169 Button { model.open(row) } label: {170 Text(text.isEmpty ? L("Sans titre") : text).nvFont(.uiStrong).foregroundStyle(NVColor.accent).lineLimit(1).fixedSize()171 }172 .buttonStyle(.plain)173 } else {174 Text(text.isEmpty ? " " : text).nvFont(column == 0 ? .uiStrong : .ui).foregroundStyle(NVColor.fg).lineLimit(1).fixedSize()175 }176 }177 .padding(.horizontal, NVSpace.md)178 .frame(maxWidth: .infinity, minHeight: tableRowHeight, alignment: .leading)179 }180 }181 .fixedSize(horizontal: true, vertical: false)182 }183 }184 .nvCard(radius: NVRadius.md)185 }186 }187 }188 }189190 static func cell(_ result: LiveQueryResult, _ cells: [LiveQueryCell], _ column: Int) -> String {191 guard column < cells.count else { return "" }192 let type = column < result.columns.count ? result.columns[column].type : LiveQueryColumnType.text193 return QueryViewLogic.cellText(cells[column], type: type)194 }195196 @ViewBuilder197 private func board(compact: Bool) -> some View {198 let groups = model.groups199 if compact {200 VStack(alignment: .leading, spacing: NVSpace.lg) {201 ForEach(groups) { group in boardColumn(group, compact: true) }202 }203 } else {204 ScrollView(.horizontal, showsIndicators: false) {205 HStack(alignment: .top, spacing: NVSpace.md) {206 ForEach(groups) { group in boardColumn(group, compact: false).frame(width: 280, alignment: .topLeading) }207 }208 }209 }210 }211212 private func boardColumn(_ group: QueryRowGroup, compact: Bool) -> some View {213 VStack(alignment: .leading, spacing: NVSpace.sm) {214 HStack(spacing: NVSpace.sm) {215 Text(QueryViewLogic.statusLabel(group.status)).nvFont(.uiStrong).foregroundStyle(NVColor.fg)216 Text("\(group.rows.count)").nvFont(.micro).foregroundStyle(NVColor.fgMuted)217 Spacer(minLength: 0)218 }219 .accessibilityElement(children: .combine)220 .accessibilityAddTraits(.isHeader)221 ForEach(group.rows) { row in222 QueryRowView(row: row, compact: true, showsStatus: false, touch: compact) { model.open(row) }223 .nvCard(radius: NVRadius.md)224 }225 }226 .padding(NVSpace.sm)227 .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.lg))228 }229230 // MARK: settings231232 private func settings(compact: Bool) -> some View {233 NVCard {234 VStack(alignment: .leading, spacing: NVSpace.md) {235 BlockSectionLabel(text: L("Réglages de la vue"))236 field(L("Titre")) { BlockTextField(placeholder: L("Titre de la vue"), text: $draft.title) }237 field(L("Source")) {238 QueryChipFlow {239 ForEach(QuerySource.known, id: \.self) { source in240 NVChip(QueryViewLogic.sourceLabel(source), systemImage: QueryViewLogic.sourceSymbol(source), tone: .accent, isSelected: draft.source == source) {241 draft.source = source242 if !QueryViewSettings.statusChoices(for: source).contains(draft.status) { draft.status = "" }243 }244 }245 }246 }247 if draft.source == .database {248 field(L("Base")) {249 if model.databases.isEmpty {250 Text(L("Aucune base de données sur cet appareil.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)251 } else {252 QueryChipFlow {253 ForEach(model.databases) { database in254 NVChip(database.name.isEmpty ? L("Sans titre") : database.name, tone: .accent, isSelected: draft.databaseId == database.id) { draft.databaseId = database.id }255 }256 }257 }258 }259 }260 let choices = QueryViewSettings.statusChoices(for: draft.source)261 if !choices.isEmpty {262 field(L("État")) {263 QueryChipFlow {264 ForEach(choices, id: \.self) { choice in265 NVChip(QueryViewSettings.statusChoiceLabel(choice, source: draft.source), tone: .accent, isSelected: draft.status == choice) { draft.status = choice }266 }267 }268 }269 }270 field(L("Texte")) { BlockTextField(placeholder: L("Contient…"), text: $draft.text) }271 if draft.source == .tasks || draft.source == .pages {272 field(L("Étiquette")) { BlockTextField(placeholder: L("Nom d'une étiquette"), text: $draft.tag) }273 }274 field(L("Limite")) {275 HStack(spacing: NVSpace.sm) {276 ForEach([10, 25, 50, 100], id: \.self) { limit in277 NVChip("\(limit)", tone: .accent, isSelected: draft.limit == limit) { draft.limit = limit }278 .accessibilityLabel(LF("%lld éléments au plus", limit))279 }280 if ![10, 25, 50, 100].contains(draft.limit) { NVChip("\(draft.limit)", tone: .accent, isSelected: true) }281 }282 }283 HStack(spacing: NVSpace.sm) {284 FeatureButton(L("Appliquer"), systemImage: "checkmark", kind: .primary) { Task { await model.apply(draft) } }285 FeatureButton(L("Annuler")) {286 draft = model.settings287 withNVAnimation(.base, reduceMotion: reduceMotion) { showsSettings = false }288 }289 }290 }291 }292 }293294 private func field<Content: View>(_ label: String, @ViewBuilder content: () -> Content) -> some View {295 VStack(alignment: .leading, spacing: NVSpace.xs) {296 Text(label).nvFont(.micro).foregroundStyle(NVColor.fgMuted)297 content()298 }299 }300}301302/// One resolved row: title, context line, status and due date.303struct QueryRowView: View {304 let row: QueryRowDisplay305 let compact: Bool306 let showsStatus: Bool307 /// 44 pt rows (nil = as `compact`). A board card is stacked like a phone row even on a wide screen.308 var touch: Bool?309 let action: () -> Void310311 var body: some View {312 Button(action: action) {313 HStack(alignment: .firstTextBaseline, spacing: NVSpace.md) {314 if row.status != nil || row.done {315 Image(systemName: row.done ? "checkmark.circle.fill" : (row.status == "doing" ? "circle.lefthalf.filled" : "circle"))316 .foregroundStyle(row.done ? NVColor.success : NVColor.fgMuted)317 .accessibilityHidden(true)318 } else if let icon = row.icon {319 Text(icon).accessibilityHidden(true)320 }321 VStack(alignment: .leading, spacing: NVSpace.xxs) {322 Text(row.title)323 .nvFont(.uiStrong)324 .foregroundStyle(row.done ? NVColor.fgMuted : NVColor.fg)325 .strikethrough(row.done)326 .multilineTextAlignment(.leading)327 if !row.subtitle.isEmpty {328 Text(row.subtitle).nvFont(.ui).foregroundStyle(NVColor.fgMuted).multilineTextAlignment(.leading)329 }330 if compact { meta }331 }332 Spacer(minLength: NVSpace.sm)333 if !compact { meta }334 if row.pageId != nil {335 Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(NVColor.fgFaint).accessibilityHidden(true)336 }337 }338 .padding(.horizontal, NVSpace.md)339 .padding(.vertical, NVSpace.sm)340 .frame(maxWidth: .infinity, minHeight: (touch ?? compact) ? 44 : 36, alignment: .leading)341 .contentShape(Rectangle())342 }343 .buttonStyle(.plain)344 .disabled(row.pageId == nil)345 .accessibilityElement(children: .combine)346 .accessibilityHint(row.pageId == nil ? "" : L("Ouvre la page"))347 }348349 @ViewBuilder350 private var meta: some View {351 HStack(spacing: NVSpace.sm) {352 if showsStatus, let status = row.status, !row.done {353 NVChip(QueryViewLogic.statusLabel(status), tone: status == "doing" ? .accent : .neutral)354 }355 if let due = row.due {356 HStack(spacing: NVSpace.xxs) {357 Image(systemName: row.overdue ? "exclamationmark.circle" : "calendar").accessibilityHidden(true)358 Text(FeatureFormat.day(due, timeZone: QueryViewLogic.utc))359 }360 .nvFont(.micro)361 .foregroundStyle(row.overdue ? NVColor.dangerText : NVColor.fgMuted)362 .accessibilityLabel(row.overdue ? LF("En retard, échéance le %@", FeatureFormat.day(due, timeZone: QueryViewLogic.utc)) : LF("Échéance le %@", FeatureFormat.day(due, timeZone: QueryViewLogic.utc)))363 }364 }365 }366}367368/// Wrapping row of chips.369struct QueryChipFlow: Layout {370 var spacing: CGFloat = NVSpace.sm371372 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {373 arrange(width: proposal.width ?? .infinity, subviews: subviews).size374 }375376 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {377 let result = arrange(width: bounds.width, subviews: subviews)378 for (index, origin) in result.origins.enumerated() {379 subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified)380 }381 }382383 private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint]) {384 var origins: [CGPoint] = []385 var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0386 for subview in subviews {387 let size = subview.sizeThatFits(.unspecified)388 if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }389 origins.append(CGPoint(x: x, y: y))390 x += size.width + spacing391 rowHeight = max(rowHeight, size.height)392 maxX = max(maxX, x - spacing)393 }394 return (CGSize(width: maxX, height: y + rowHeight), origins)395 }396}397