SPB Git

Repository Public

ChartBlockModel.swift 12.2 KB 292 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/ChartBlockModel.swift3// Description: View model of a `chart` node: the data to plot (the node's table, or — for a chart fed by a database — the4//              live result of `POST /api/query` with the node's snapshot as the offline fallback and the freshness shown),5//              the editing operations of the data grid (cells, rows, columns, kind, axes) and a textual summary for6//              VoiceOver. Edits go back to the caller as updated node attributes.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesAPI13import SPNotesDocument14import SPNotesSync1516/// One mark of the plot.17public struct ChartMarkPoint: Identifiable, Sendable, Equatable {18    public var id: String19    public var series: String20    /// The X cell as text (category axis, labels).21    public var label: String22    /// The X cell as a number when the whole X column is numeric (scatter, numeric axes).23    public var x: Double?24    public var y: Double25}2627@Observable @MainActor28public final class ChartBlockModel {29    public enum DataOrigin: Equatable, Sendable {30        /// The table stored in the node.31        case node32        /// Live rows of the database (`fromCache` = the device's last copy of that answer).33        case live(Freshness)34        /// The database could not be asked and was never fetched: the node's snapshot is shown.35        case snapshot36    }3738    public private(set) var block: ChartBlock39    public private(set) var phase: LoadPhase = .idle40    public private(set) var freshness: Freshness?41    /// Why live data is not shown (calm: the snapshot is).42    public private(set) var liveFailure: FeatureFailure?43    public private(set) var origin: DataOrigin = .node44    public private(set) var liveColumns: [String] = []45    public private(set) var liveRows: [[ChartCell]] = []46    public private(set) var databaseName: String?47    public var isEditingData = false4849    @ObservationIgnored private let repositories: NotesRepositories?50    @ObservationIgnored private let onChange: (ChartBlock) -> Void5152    public init(block: ChartBlock, repositories: NotesRepositories? = nil, onChange: @escaping (ChartBlock) -> Void = { _ in }) {53        self.block = block54        self.repositories = repositories55        self.onChange = onChange56    }5758    public var isLive: Bool { block.source != nil }59    private var showsLive: Bool { if case .live = origin { return true }; return false }60    /// The table on screen.61    public var columns: [String] { showsLive ? liveColumns : block.columns }62    public var rows: [[ChartCell]] { showsLive ? liveRows : block.rows }63    /// Cells can be edited only when the node owns its data.64    public var canEditCells: Bool { !isLive }65    /// True when the live rows differ from the snapshot stored in the node.66    public var snapshotIsOutdated: Bool { showsLive && (liveColumns != block.columns || liveRows != block.rows) }6768    /// The node with the data on screen (axes resolved against it).69    var effective: ChartBlock {70        guard showsLive else { return block }71        var copy = block72        copy.columns = liveColumns73        copy.rows = liveRows74        return copy75    }7677    public var xColumn: String? { effective.resolvedX }78    public var yColumns: [String] { effective.resolvedY }79    public var hasData: Bool { !columns.isEmpty && !rows.isEmpty }8081    // MARK: Loading8283    public func load() async {84        guard let source = block.source, let repositories else {85            origin = .node86            phase = .loaded87            return88        }89        phase = .loading90        do {91            let result = try await repositories.knowledge.query(.database(source.databaseId, viewId: source.viewId, limit: 500))92            liveColumns = result.value.table.columns93            liveRows = result.value.table.rows.map { row in row.map(Self.cell) }94            databaseName = result.value.name95            let fresh = Freshness(result)96            freshness = fresh97            origin = .live(fresh)98            liveFailure = nil99            phase = .loaded100        } catch {101            // The snapshot stored in the node is the fallback: this is a state, not an error screen.102            let failure = FeatureFailure(error)103            liveFailure = failure104            origin = .snapshot105            freshness = nil106            phase = block.rows.isEmpty ? .failed(failure) : .loaded107        }108    }109110    static func cell(_ cell: LiveQueryCell) -> ChartCell {111        switch cell {112        case .null: return .null113        case .text(let text): return .string(text)114        case .number(let number): return .number(number)115        case .bool(let value): return .string(value ? "true" : "false")116        }117    }118119    // MARK: Plot120121    /// The marks: one per row and series with a numeric value.122    public var marks: [ChartMarkPoint] {123        let series = effective.series()124        let numericX = !(series.first?.points.isEmpty ?? true) && (series.first?.points.allSatisfy { $0.x.numericValue != nil } ?? false)125        return series.flatMap { one in126            one.points.enumerated().compactMap { index, point -> ChartMarkPoint? in127                guard let y = point.y, y.isFinite else { return nil }128                return ChartMarkPoint(id: "\(one.name)#\(index)", series: one.name, label: point.x.text.isEmpty ? String(index + 1) : point.x.text, x: numericX ? point.x.numericValue : nil, y: y)129            }130        }131    }132133    /// Pie: the first series, positive values only.134    public var slices: [ChartMarkPoint] {135        guard let first = yColumns.first else { return [] }136        return marks.filter { $0.series == first && $0.y > 0 }137    }138139    /// Rows whose value cannot be drawn in the current kind (non-numeric; negative or zero in a pie).140    public var skippedCount: Int {141        let seriesCount = max(1, yColumns.count)142        if block.kind == .pie { return rows.count - slices.count }143        return rows.count * seriesCount - marks.count144    }145146    public static func kindName(_ kind: ChartKind) -> String {147        switch kind {148        case .bar: return L("Barres")149        case .line: return L("Courbe")150        case .area: return L("Aires")151        case .pie: return L("Secteurs")152        case .scatter: return L("Nuage de points")153        default: return kind.rawValue154        }155    }156157    public static func format(_ value: Double) -> String {158        value.formatted(.number.precision(.fractionLength(0...3)).locale(FeatureStrings.locale))159    }160161    /// A sentence-level description of the chart (VoiceOver; also shown when there is nothing to plot).162    public var summary: String {163        let title = block.title.isEmpty ? L("Graphique sans titre") : block.title164        guard hasData, !marks.isEmpty else { return LF("%@ : aucune donnée numérique à tracer.", title) }165        var parts = [LF("%@, graphique en %@, %lld lignes.", title, Self.kindName(block.kind).lowercased(with: FeatureStrings.locale), rows.count)]166        for name in (block.kind == .pie ? Array(yColumns.prefix(1)) : yColumns) {167            let points = marks.filter { $0.series == name }168            guard let low = points.min(by: { $0.y < $1.y }), let high = points.max(by: { $0.y < $1.y }) else { continue }169            parts.append(LF("%@ : de %@ (%@) à %@ (%@).", name, Self.format(low.y), low.label, Self.format(high.y), high.label))170        }171        return parts.joined(separator: " ")172    }173174    // MARK: Editing (node attributes)175176    private func change(_ edit: (inout ChartBlock) -> Void) {177        var next = block178        edit(&next)179        guard next != block else { return }180        block = next181        onChange(block)182    }183184    public func setKind(_ kind: ChartKind) { change { $0.kind = kind } }185    public func setTitle(_ title: String) { change { $0.title = title } }186    public func setX(_ column: String) {187        guard columns.contains(column) else { return }188        change { block in189            block.x = column190            if block.y.contains(column) { block.y.removeAll { $0 == column } }191        }192    }193194    /// Adds or removes a column from the plotted series (at least one stays).195    public func toggleY(_ column: String) {196        guard columns.contains(column), column != xColumn else { return }197        var current = yColumns198        if current.contains(column) { current.removeAll { $0 == column } } else { current.append(column) }199        guard !current.isEmpty else { return }200        let ordered = columns.filter(current.contains)201        change { $0.y = ordered }202    }203204    /// What a typed cell becomes: empty → null, a number (decimal point or comma) → number, else text.205    public static func parse(_ text: String) -> ChartCell {206        let trimmed = text.trimmingCharacters(in: .whitespaces)207        if trimmed.isEmpty { return .null }208        if let number = Double(trimmed.replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")), number.isFinite { return .number(number) }209        return .string(text)210    }211212    /// The text a cell shows in the grid (numbers in the user's format).213    public static func display(_ cell: ChartCell) -> String {214        switch cell {215        case .null: return ""216        case .string(let text): return text217        case .number(let number): return number.formatted(.number.precision(.fractionLength(0...6)).grouping(.never).locale(FeatureStrings.locale))218        }219    }220221    public func setCell(row: Int, column: Int, _ text: String) {222        guard canEditCells, row < block.rows.count, column < block.columns.count else { return }223        change { block in224            var rows = block.rows225            while rows[row].count < block.columns.count { rows[row].append(.null) }226            rows[row][column] = Self.parse(text)227            block.rows = rows228        }229    }230231    public func addRow() {232        guard canEditCells, !block.columns.isEmpty else { return }233        change { $0.rows = $0.rows + [Array(repeating: ChartCell.null, count: $0.columns.count)] }234    }235236    public func removeRow(_ index: Int) {237        guard canEditCells, block.rows.indices.contains(index) else { return }238        change { block in239            var rows = block.rows240            rows.remove(at: index)241            block.rows = rows242        }243    }244245    /// Adds a column with a unique name (« Série 2 », « Série 3 »…).246    @discardableResult247    public func addColumn(named proposed: String? = nil) -> String? {248        guard canEditCells else { return nil }249        var name = proposed?.trimmingCharacters(in: .whitespaces) ?? ""250        if name.isEmpty || block.columns.contains(name) {251            var n = block.columns.count + 1252            repeat { name = block.columns.isEmpty ? L("Catégorie") : LF("Série %lld", n); n += 1 } while block.columns.contains(name)253        }254        change { block in255            block.columns = block.columns + [name]256            block.rows = block.rows.map { $0 + [.null] }257        }258        return name259    }260261    public func removeColumn(_ name: String) {262        guard canEditCells, let index = block.columns.firstIndex(of: name), block.columns.count > 1 else { return }263        change { block in264            block.columns = block.columns.filter { $0 != name }265            block.rows = block.rows.map { row in row.enumerated().filter { $0.offset != index }.map(\.element) }266            if block.x == name { block.x = nil }267            block.y = block.y.filter { $0 != name }268        }269    }270271    public func renameColumn(_ name: String, to proposed: String) {272        let newName = proposed.trimmingCharacters(in: .whitespaces)273        guard canEditCells, !newName.isEmpty, newName != name, !block.columns.contains(newName), block.columns.contains(name) else { return }274        change { block in275            block.columns = block.columns.map { $0 == name ? newName : $0 }276            if block.x == name { block.x = newName }277            block.y = block.y.map { $0 == name ? newName : $0 }278        }279    }280281    /// Stores the live rows as the node's snapshot (what offline devices and exports see). Explicit: looking at a chart282    /// never edits the note.283    public func updateSnapshot() {284        guard snapshotIsOutdated else { return }285        let columns = liveColumns, rows = liveRows286        change { block in287            block.columns = columns288            block.rows = rows289        }290    }291}292
Files main
Menu

Theme