SPB Git

Repository Public

InspectorTests.swift 16.6 KB 304 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/FeatureCharts/Tests/FeatureChartsTests/InspectorTests.swift10// Module           : FeatureChartsTests11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import Testing89import SheetCore90import SheetCharts91import SheetUI92@testable import FeatureCharts9394@MainActor @Suite struct InspectorTests {95    /// Sheet "Data": A1:D5 = header row + 4 rows (Label, P, Q, R); F1:F5 a second numeric column.96    func make() -> (WorkbookSession, SheetObject, ChartEditor) {97        let s = WorkbookSession(workbook: Workbook(sheetNames: ["Data", "Other"]), locale: Locale(identifier: "en_US"))98        s.perform("fill") { e in99            for (c, h) in ["Label", "P", "Q", "R"].enumerated() { e.set(sheet: 0, row: 0, col: c, .value(.text(h))) }100            for r in 1...4 {101                e.set(sheet: 0, row: r, col: 0, .value(.text("L\(r)")))102                for c in 1...3 { e.set(sheet: 0, row: r, col: c, .value(.number(Double(r * 10 + c)))) }103                e.set(sheet: 0, row: r, col: 5, .value(.number(Double(r) * 1.5)))104            }105            e.set(sheet: 0, row: 0, col: 5, .value(.text("Extra")))106        }107        s.select(RangeRef(a1: "A1:C5")!)108        let d = ChartBuilder.detect(AreaRef(sheet: 0, range: RangeRef(a1: "A1:C5")!), in: s.workbook)!109        let object = ChartInsertion.insert(ChartBuilder.spec(.column, d), in: s)!110        s.engine.clearUndoHistory()111        return (s, object, ChartsState.of(s).editor(for: object.id)!)112    }113114    func stored(_ s: WorkbookSession, _ o: SheetObject) -> ChartSpec { ChartPayload.chart(s.sheet.meta.objects.first { $0.id == o.id }!)!.spec }115    func range(_ a1: String, sheet: String = "Data") -> DataRef { .range(sheet: sheet, range: RangeRef(a1: a1)!) }116117    @Test func editsRoundTripThroughTheObject() {118        let (s, o, editor) = make()119        #expect(editor.spec.series.count == 2)120        editor.apply("Chart Kind") { $0.kind = .line }121        editor.apply("Chart Title") { $0.title = "Revenue" }122        editor.apply("Stacking") { $0.options.stacking = .percent }123        editor.apply("Tick Format") { $0.yAxis.numberFormat = "#,##0.0"; $0.yAxis.min = 0; $0.yAxis.scale = .log10 }124        editor.apply("Trendline") { $0.series[0].trendline = .polynomial(3, showEquation: true, showR2: true) }125        editor.apply("Error Bars") { $0.series[1].errorBars = ErrorBarSpec(kind: .custom, plus: self.range("F2:F5")) }126        editor.apply("Add Annotation") { $0.annotations.append(.referenceLine(.horizontal, at: 25, label: "Target")) }127        let spec = stored(s, o)128        #expect(spec == editor.spec)129        #expect(spec.kind == .line && spec.title == "Revenue" && spec.options.stacking == .percent)130        #expect(spec.yAxis.numberFormat == "#,##0.0" && spec.yAxis.min == 0 && spec.yAxis.scale == .log10)131        #expect(spec.series[0].trendline?.order == 3 && spec.series[0].trendline?.showR2 == true)132        #expect(spec.series[1].errorBars?.plus == range("F2:F5"))133        #expect(spec.annotations.count == 1 && spec.annotations[0].value == 25)134        // the object takes the title as its name while it still had the default one135        #expect(s.sheet.meta.objects.first { $0.id == o.id }?.name == "Revenue")136        // an edit that changes nothing is not an undo step137        let before = editor.commitCount138        editor.apply("Chart Title") { $0.title = "Revenue" }139        #expect(editor.commitCount == before)140    }141142    @Test func undoAndRedoOfAnEdit() {143        let (s, o, editor) = make()144        editor.apply("Chart Kind") { $0.kind = .area }145        editor.applyValue("Pin Theme") { $0.pinTheme = true; $0.spec.theme = .publication }146        #expect(stored(s, o).kind == .area && editor.pinTheme && editor.spec.theme.name == "Publication")147        s.undo()148        #expect(stored(s, o).kind == .area && !editor.pinTheme && editor.spec.theme.name == "Light")149        s.undo()150        #expect(stored(s, o).kind == .column)151        s.redo(); s.redo()152        #expect(stored(s, o).kind == .area && editor.pinTheme)153    }154155    @Test func liveEditsCoalesceIntoOneUndoStep() {156        let (s, o, editor) = make()157        let id = editor.spec.series[0].id158        for i in 1...25 {159            editor.live("Line Width") { spec in spec.series[0].style.lineWidth = 1 + Double(i) * 0.1 }160            // the preview is visible in the object immediately, without an undo step161            #expect(stored(s, o).series[0].style.lineWidth == 1 + Double(i) * 0.1)162            #expect(!s.engine.canUndo)163        }164        #expect(editor.isLive)165        editor.flush()166        #expect(!editor.isLive && editor.commitCount == 1 && s.engine.canUndo)167        #expect(stored(s, o).series.first { $0.id == id }?.style.lineWidth == 3.5)168        s.undo()169        #expect(stored(s, o).series[0].style.lineWidth == nil)170        #expect(!s.engine.canUndo)171        s.redo()172        #expect(stored(s, o).series[0].style.lineWidth == 3.5)173        // a live gesture that ends where it began leaves no undo step; a new label starts a new step174        s.engine.clearUndoHistory()175        editor.live("Fill Opacity") { $0.series[0].style.fillOpacity = 0.4 }176        editor.live("Fill Opacity") { $0.series[0].style.fillOpacity = nil }177        editor.flush()178        #expect(!s.engine.canUndo)179        editor.live("Fill Opacity") { $0.series[0].style.fillOpacity = 0.4 }180        editor.live("Bar Gap") { $0.options.barGap = 0.5 }181        editor.apply("Chart Title") { $0.title = "T" }       // an ordinary edit flushes the gesture first182        #expect(editor.commitCount == 4)183        s.undo(); s.undo(); s.undo()184        #expect(stored(s, o).series[0].style.fillOpacity == nil && stored(s, o).options.barGap == ChartOptions().barGap && !s.engine.canUndo)185    }186187    @Test func rangeTextEditing() {188        let (s, _, editor) = make()189        var spec = editor.spec190        let id = spec.series[0].id191        #expect(ChartEdits.ref(spec.series[0], .values) == range("B2:B5"))192        #expect(ChartEdits.setRefText(&spec, series: id, field: .values, text: "D2:D5", currentSheet: "Data", workbook: s.workbook))193        #expect(spec.series[0].values == range("D2:D5"))194        #expect(ChartEdits.setRefText(&spec, series: id, field: .x, text: "other!$A$1:$A$4", currentSheet: "Data", workbook: s.workbook))195        #expect(spec.series[0].x == range("A1:A4", sheet: "Other"))196        #expect(ChartFormat.text(spec.series[0].x, currentSheet: "Data") == "Other!A1:A4")197        #expect(ChartEdits.setRefText(&spec, series: id, field: .errorPlus, text: "{1; 2; 3}", currentSheet: "Data", workbook: s.workbook))198        #expect(spec.series[0].errorBars?.plus == .literal([1, 2, 3]) && spec.series[0].errorBars?.kind == .custom)199        // invalid text is rejected and leaves the spec untouched200        let before = spec201        for bad in ["B2:", "Nowhere!A1:A3", "12abc", "{1; x}"] {202            #expect(!ChartEdits.setRefText(&spec, series: id, field: .values, text: bad, currentSheet: "Data", workbook: s.workbook))203        }204        #expect(!ChartEdits.setRefText(&spec, series: UUID(), field: .values, text: "A1", currentSheet: "Data", workbook: s.workbook))205        #expect(spec == before)206        // empty text clears the slot207        #expect(ChartEdits.setRefText(&spec, series: id, field: .x, text: "  ", currentSheet: "Data", workbook: s.workbook))208        #expect(spec.series[0].x == nil)209        for f in ChartEdits.Field.allCases {210            var one = SeriesSpec()211            ChartEdits.setRef(&one, f, range("C3"))212            #expect(ChartEdits.ref(one, f) == range("C3"))213        }214        #expect(NumberField.parse("") == .some(nil) && NumberField.parse(" 1,5 ") == .some(1.5) && NumberField.parse("abc") == nil)215    }216217    @Test func seriesListEdits() {218        let (s, _, editor) = make()219        var spec = editor.spec220        let ids = spec.series.map(\.id)221        // add the "Extra" column from a selection222        #expect(ChartEdits.addSeries(&spec, from: AreaRef(sheet: 0, range: RangeRef(a1: "F1:F5")!), in: s.workbook) == 1)223        #expect(spec.series.count == 3 && spec.series[2].values == range("F2:F5") && spec.series[2].nameRef == range("F1"))224        #expect(spec.categories == range("A2:A5"))225        #expect(ChartEdits.displayName(spec.series[2], index: 2, workbook: s.workbook) == "Extra")226        #expect(ChartEdits.displayName(SeriesSpec(), index: 4, workbook: s.workbook) == "Series 5")227        #expect(ChartEdits.addSeries(&spec, from: AreaRef(sheet: 1, range: RangeRef(a1: "A1:B3")!), in: s.workbook) == 0)228        // reorder229        #expect(!ChartEdits.moveSeries(&spec, id: ids[0], by: -1))230        #expect(ChartEdits.moveSeries(&spec, id: ids[0], by: 2))231        #expect(spec.series.map(\.id).last == ids[0] && spec.series.first?.id == ids[1])232        #expect(!ChartEdits.canMove(spec, id: ids[0], by: 1) && ChartEdits.canMove(spec, id: ids[0], by: -1))233        ChartEdits.removeSeries(&spec, id: ids[1])234        #expect(spec.series.count == 2 && !spec.series.contains { $0.id == ids[1] })235        // an empty chart takes the categories of the selection236        var empty = ChartSpec(kind: .line)237        #expect(ChartEdits.addSeries(&empty, from: AreaRef(sheet: 0, range: RangeRef(a1: "A1:D5")!), in: s.workbook) == 3)238        #expect(empty.categories == range("A2:A5") && empty.series.map(\.values) == [range("B2:B5"), range("C2:C5"), range("D2:D5")])239        var matrix = ChartSpec(kind: .heatmap)240        #expect(ChartEdits.addSeries(&matrix, from: AreaRef(sheet: 0, range: RangeRef(a1: "A1:D5")!), in: s.workbook) == 1)241        #expect(matrix.series[0].values == range("B2:D5") && matrix.rowLabels == range("A2:A5") && matrix.categories == range("B1:D1"))242    }243244    @Test func switchRowsAndColumns() {245        let (_, _, editor) = make()246        var spec = editor.spec                       // columns B and C, categories A2:A5, names B1 / C1247        let original = spec248        #expect(ChartEdits.switchRowsColumns(&spec))249        #expect(spec.series.count == 4)250        #expect(spec.series[0].values == range("B2:C2") && spec.series[3].values == range("B5:C5"))251        #expect(spec.series[1].nameRef == range("A3"))252        #expect(spec.categories == range("B1:C1"))253        // and back again254        #expect(ChartEdits.switchRowsColumns(&spec))255        #expect(spec.series.map(\.values) == original.series.map(\.values))256        #expect(spec.series.map(\.nameRef) == original.series.map(\.nameRef))257        #expect(spec.categories == original.categories)258        // not a contiguous block → refused, spec untouched259        var gap = original260        gap.series[1].values = range("F2:F5")261        let before = gap262        #expect(!ChartEdits.switchRowsColumns(&gap) && gap == before)263        var literal = original264        literal.series[0].values = .literal([1, 2, 3, 4])265        #expect(!ChartEdits.switchRowsColumns(&literal))266        var matrix = ChartSpec(kind: .heatmap, series: [SeriesSpec(values: range("B2:D5"))])267        #expect(!ChartEdits.switchRowsColumns(&matrix))268    }269270    @Test func annotationDefaultsAndLists() {271        let (s, _, editor) = make()272        let spec = editor.spec273        let data = ChartData.resolve(spec, source: ChartSnapshot.capture([spec], workbook: s.workbook))274        let line = ChartEdits.defaultAnnotation(.referenceLine, orientation: .horizontal, data: data, continuousX: false)275        #expect(line.kind == .referenceLine && line.orientation == .horizontal && line.value == 26.5)      // mean of 11…42276        let vertical = ChartEdits.defaultAnnotation(.referenceLine, orientation: .vertical, data: data, continuousX: false)277        #expect(vertical.value == 1.5)                                                                     // middle of 4 categories278        let band = ChartEdits.defaultAnnotation(.band, data: data, continuousX: false)279        #expect(band.value < band.value2 && band.value >= 11 && band.value2 <= 42)280        let note = ChartEdits.defaultAnnotation(.text, data: data, continuousX: false)281        #expect(note.y == 42 && !note.text.isEmpty)282        let emptyData = ChartData()283        #expect(ChartEdits.defaultAnnotation(.band, data: emptyData, continuousX: true).value == 0)284        #expect(ChartEdits.parseIndexList("1, 4;6 x 0") == [0, 3, 5])285        #expect(ChartEdits.parseNumberList("3; 1,5 2") == [1.5, 2, 3])286        #expect(ChartEdits.isColorBlindSafe(ChartTheme.okabeIto.palette) && ChartEdits.isColorBlindSafe(ChartPalette.tolBright) && !ChartEdits.isColorBlindSafe(ChartPalette.orix))287    }288289    @Test func fieldsAndApplicabilityCoverEveryKind() {290        for kind in ChartKind.allCases {291            #expect(!ChartEdits.fields(for: kind).isEmpty)292            #expect(ChartEdits.fields(for: kind).allSatisfy { !$0.title.isEmpty })293            // every kind is either styled per series or has its own option panel (or both)294            #expect(ChartEdits.hasSeriesStyle(kind) || InspectorKindOptions.applies(to: kind))295        }296        #expect(ChartEdits.fields(for: .candlestick) == [.open, .high, .low, .close] && ChartEdits.fields(for: .candlestick, seriesIndex: 1) == [.values])297        #expect(ChartEdits.fields(for: .bubble) == [.values, .x, .size])298        #expect(ChartEdits.canStack(.column) && !ChartEdits.canStack(.scatter) && ChartEdits.hasSecondaryAxis(.combo) && !ChartEdits.hasSecondaryAxis(.pie))299        #expect(ChartFormat.preview(code: "0.0%", sample: NumberFormatSample.value(for: AxisSpec(numberFormat: "0.0%"))).hasPrefix("12"))300        #expect(ChartFormat.preview(code: "").isEmpty)301        #expect(NumberFormatSample.value(for: AxisSpec(scale: .date)) > 40_000)302    }303}304
Files main
Menu

Theme