Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/FeatureCharts/Tests/FeatureChartsTests/FigureTests.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 CoreGraphics88import Foundation89import ImageIO90import Testing91import SheetCore92import SheetCharts93import SheetUI94@testable import FeatureCharts9596@MainActor @Suite struct FigureTests {97 /// A session with a small table on "Data" and two chart objects bound to it.98 func make() -> (WorkbookSession, [ChartSpec]) {99 let s = WorkbookSession(workbook: Workbook(sheetNames: ["Data", "Other"]), locale: Locale(identifier: "en_US"))100 s.perform("fill") { e in101 for (c, h) in ["x", "y", "lo", "hi"].enumerated() { e.set(sheet: 0, row: 0, col: c, .value(.text(h))) }102 for r in 1...10 {103 e.set(sheet: 0, row: r, col: 0, .value(.number(Double(r))))104 e.set(sheet: 0, row: r, col: 1, .value(.number(Double(r * r))))105 e.set(sheet: 0, row: r, col: 2, .value(.number(Double(r * r) - 2)))106 e.set(sheet: 0, row: r, col: 3, .value(.number(Double(r * r) + 2)))107 }108 }109 let d = ChartBuilder.detect(AreaRef(sheet: 0, range: RangeRef(a1: "A1:B11")!), in: s.workbook)!110 var specs: [ChartSpec] = []111 for kind in [ChartKind.scatter, .line] {112 var spec = ChartBuilder.spec(kind, d)113 spec.title = kind.rawValue114 specs.append(spec)115 #expect(ChartInsertion.insert(spec, in: s) != nil)116 }117 s.engine.clearUndoHistory()118 return (s, specs)119 }120121 @Test func defaultDraftUsesWorkbookCharts() {122 let (s, _) = make()123 let d = FigureStudio.defaultDraft(for: s.workbook)124 #expect(d.rows == 2 && d.cols == 2 && d.panels.count == 4)125 #expect(d.panels.filter { !FigureStudio.isEmpty($0) }.map(\.chart.title) == ["scatter", "line"])126 #expect(FigureStudio.issues(d).isEmpty)127 #expect(FigureStudio.firstFreeCell(d) == nil)128 #expect(FigureStudio.matchingTemplate(d)?.id == "academic-double")129 // the session draft is created once and kept130 let first = FigureStudio.draft(in: s)131 #expect(FigureStudio.draft(in: s) == first)132 }133134 @Test func templateKeepsCharts() {135 let (s, _) = make()136 var d = FigureStudio.defaultDraft(for: s.workbook)137 d.title = "My figure"; d.panels[0].label = "X"138 let id = d.id139 let sci = FigureStudio.apply(FigureTemplates.scientificPublication, to: d)140 #expect(sci.id == id && sci.title == "My figure")141 #expect(sci.rows == 1 && sci.cols == 3 && sci.panels.count == 3)142 #expect(sci.panels.prefix(2).map(\.chart.title) == ["scatter", "line"] && sci.panels[0].label == "X")143 #expect(FigureStudio.isEmpty(sci.panels[2]))144 #expect(sci.typography.family == "Times New Roman" && abs(sci.widthMM - 174) < 1e-9)145 #expect(FigureStudio.issues(sci).isEmpty)146 // a one-cell template grows by rows instead of dropping charts147 let single = FigureStudio.apply(FigureTemplates.academicSingleColumn, to: d)148 #expect(single.cols == 1 && single.rows == 2 && single.panels.map(\.chart.title) == ["scatter", "line"])149 // same grid: placement and spans are preserved150 var spanned = d151 spanned.panels.removeLast(2); spanned.panels[0].colSpan = 2; spanned.panels[1].row = 1; spanned.panels[1].col = 0152 let again = FigureStudio.apply(FigureTemplates.academicDoubleColumn, to: spanned)153 #expect(again.panels.map(\.colSpan) == [2, 1] && again.panels[1].row == 1)154 }155156 @Test func gridAndSpanValidation() {157 var f = FigureSpec(rows: 2, cols: 2)158 let a = FigureStudio.addPanel(&f), b = FigureStudio.addPanel(&f)159 #expect(f.panels.map { [$0.row, $0.col] } == [[0, 0], [0, 1]])160 #expect(FigureStudio.issues(f).isEmpty)161 f.panels[0].colSpan = 2162 #expect(FigureStudio.issues(f) == [a: .overlaps(b), b: .overlaps(a)])163 f.panels[1].row = 1164 #expect(FigureStudio.issues(f).isEmpty)165 f.panels[1].rowSpan = 2166 #expect(FigureStudio.issues(f) == [b: .outsideGrid])167 f.panels[1] = FigureStudio.clamped(f.panels[1], rows: 2, cols: 2)168 #expect(f.panels[1].rowSpan == 1 && FigureStudio.issues(f).isEmpty)169 #expect(FigureStudio.firstFreeCell(f).map { [$0.row, $0.col] } == [1, 0])170 // shrinking the grid clamps panels with content and drops empty ones that fall outside171 var chart = ChartSpec(kind: .line); chart.series = [SeriesSpec(values: .literal([1, 2]))]172 f.panels[1].chart = chart173 FigureStudio.setGrid(&f, rows: 1, cols: 1)174 #expect(f.rows == 1 && f.cols == 1 && f.panels.count == 2)175 #expect(f.panels.allSatisfy { $0.row == 0 && $0.col == 0 && $0.rowSpan == 1 && $0.colSpan == 1 })176 FigureStudio.setGrid(&f, rows: 99, cols: 0)177 #expect(f.rows == FigureStudio.maxGrid && f.cols == 1)178 // a full grid grows by one row; assignment fills the first empty panel179 var g = FigureSpec(rows: 1, cols: 1)180 FigureStudio.addPanel(&g, chart: chart); FigureStudio.addPanel(&g)181 #expect(g.rows == 2 && g.panels[1].row == 1)182 let target = FigureStudio.assign(chart, to: nil, in: &g)183 #expect(target == g.panels[1].id && !FigureStudio.isEmpty(g.panels[1]) && g.panels[1].chart.id != chart.id)184 FigureStudio.movePanel(&g, id: target, by: -1)185 #expect(g.panels[0].id == target && FigureStudio.label(g, 0) == "(a)")186 g.panels[0].label = "Left"187 #expect(FigureStudio.label(g, 0) == "Left" && FigureStudio.label(g, 1) == "(b)")188 }189190 @Test func persistenceRoundTrip() {191 let (s, _) = make()192 let state = ChartsState.of(s)193 ChartsFeature.openFigureStudio(editing: nil, in: s)194 var draft = FigureStudio.draft(in: s)195 draft.title = "Results"; draft.shareY = true; draft.panels[0].colSpan = 1196 state.figureDraft = draft197 let before = s.sheet.meta.objects.count198 let object = FigureStudio.saveDraft(in: s)!199 #expect(object.kind == FigureSpec.objectKind && object.name == "Results")200 #expect(s.sheet.meta.objects.count == before + 1 && state.figureObjectID == object.id)201 #expect(abs(object.width - draft.width) < 1e-9 && abs(object.height - draft.height) < 1e-9)202 // reopening (double-click) gives back the same figure, charts embedded203 state.figureDraft = nil; state.figureObjectID = nil204 ChartsFeature.openFigureStudio(editing: s.sheet.meta.objects.last!, in: s)205 #expect(state.figureDraft == draft && state.figureObjectID == object.id)206 #expect(state.figureDraft?.panels.first?.chart.series.first?.values != nil)207 // updating keeps the object id and is found from another sheet208 s.activateSheet(1)209 state.figureDraft?.title = "Results v2"210 let updated = FigureStudio.saveDraft(in: s)!211 #expect(updated.id == object.id)212 #expect(s.workbook.sheets[0].meta.objects.filter { $0.kind == "figure" }.count == 1)213 #expect(ChartPayload.figure(s.workbook.sheets[0].meta.objects.last!)?.title == "Results v2")214 #expect(s.workbook.sheets[1].meta.objects.isEmpty)215 // undo: first the update, then the insertion216 s.undo()217 #expect(ChartPayload.figure(s.workbook.sheets[0].meta.objects.last!)?.title == "Results")218 s.undo()219 #expect(s.workbook.sheets[0].meta.objects.count == before)220 s.redo()221 #expect(s.workbook.sheets[0].meta.objects.last?.id == object.id)222 // saving after the object was deleted inserts it again on the active sheet223 s.undo()224 let again = FigureStudio.saveDraft(in: s)!225 #expect(s.workbook.sheets[1].meta.objects.map(\.id) == [again.id])226 }227228 @Test func savedFigureFollowsStructuralEdits() {229 let (s, _) = make()230 ChartsFeature.openFigureStudio(editing: nil, in: s)231 let object = FigureStudio.saveDraft(in: s)!232 s.perform("insert") { $0.insertRows(sheet: 0, at: 0, count: 3) }233 let moved = ChartPayload.figure(s.sheet.meta.objects.first { $0.id == object.id }!)!234 #expect(moved.panels[0].chart.series[0].values == .range(sheet: "Data", range: RangeRef(a1: "B5:B14")!))235 }236237 @Test func themeStoreRoundTrip() {238 let (s, _) = make()239 var figure = FigureTemplates.scientificPublication.makeFigure(charts: [])240 figure.shareX = true; figure.hGutter = 21241 var store = FigureThemeStore.load(from: s.workbook)242 #expect(store.styles.isEmpty && s.workbook.attachments[FigureThemeStore.attachmentKey] == nil)243 let blank = store.upsert(FigureStyle(name: " ", figure: figure))244 let first = store.upsert(FigureStyle(name: " Lab serif ", figure: figure))245 let second = store.upsert(FigureStyle(name: "Alpha", figure: FigureTemplates.dashboard.figure))246 #expect(!blank && first && second)247 store.save(to: s.workbook)248 let loaded = FigureThemeStore.load(from: s.workbook)249 #expect(loaded == store && loaded.styles.map(\.name) == ["Alpha", "Lab serif"])250 // apply to another figure: look changes, content and size do not251 var other = FigureTemplates.dashboard.makeFigure(charts: [ChartSpec(kind: .pie)], title: "T")252 let size = other.size253 loaded.style(named: "lab SERIF")!.apply(to: &other)254 #expect(other.theme == figure.theme && other.typography == figure.typography && other.panelLabelStyle == figure.panelLabelStyle)255 #expect(other.shareX && other.hGutter == 21 && other.size == size && other.title == "T" && other.panels.count == 1)256 // overwrite under the same name, then delete everything257 var changed = figure; changed.margin = 33258 var again = loaded259 again.upsert(FigureStyle(name: "LAB SERIF", figure: changed))260 #expect(again.styles.count == 2 && again.style(named: "Lab serif")?.margin == 33)261 again.remove(named: "alpha"); again.remove(named: "lab serif")262 again.save(to: s.workbook)263 #expect(s.workbook.attachments[FigureThemeStore.attachmentKey] == nil)264 }265266 @Test func sizesAndPixels() {267 let f = FigureTemplates.academicDoubleColumn.figure268 #expect(abs(FigureStudio.millimetres(f.width) - 183) < 1e-9 && abs(FigureStudio.points(millimetres: 25.4) - 72) < 1e-9)269 #expect(FigureStudio.sizeReadout(f).contains("183") && FigureStudio.sizeReadout(f).contains("mm"))270 let choices = FigureStudio.exportChoices271 #expect(choices.map(\.id) == ["pdf", "svg", "png-300", "png-600"])272 #expect(choices[0].pixels(f) == nil)273 let px300 = choices[2].pixels(f)!, px600 = choices[3].pixels(f)!274 #expect(px300.width == Int((183 / 25.4 * 300).rounded()) && px300.height == Int((130 / 25.4 * 300).rounded()))275 #expect(px600.width == Int((183 / 25.4 * 600).rounded()))276 }277278 @Test func exportDataIsValid() throws {279 let (s, _) = make()280 var figure = FigureStudio.defaultDraft(for: s.workbook)281 figure.title = "Export"282 let choices = FigureStudio.exportChoices283 let pdf = try #require(FigureStudio.exportData(figure, choice: choices[0], session: s))284 #expect(String(decoding: pdf.prefix(5), as: UTF8.self) == "%PDF-")285 let text = String(data: pdf, encoding: .isoLatin1) ?? ""286 #expect(text.contains("/Font") && !text.contains("/Subtype /Image"))287 let svg = try #require(FigureStudio.exportData(figure, choice: choices[1], session: s))288 let parser = XMLParser(data: svg)289 #expect(parser.parse() && String(decoding: svg, as: UTF8.self).contains("<text"))290 let png = try #require(FigureStudio.exportData(figure, choice: choices[2], session: s))291 let image = try #require(CGImageSourceCreateWithData(png as CFData, nil).flatMap { CGImageSourceCreateImageAtIndex($0, 0, nil) })292 let expected = choices[2].pixels(figure)!293 #expect(image.width == expected.width && image.height == expected.height)294 }295296 @Test func annotationHelpersAndPanelEditor() {297 let (s, specs) = make()298 let snap = ChartSnapshot.capture(specs, workbook: s.workbook)299 var chart = specs[0]300 #expect(FigureStudio.supportsAnnotations(chart) && FigureStudio.supportsTrendline(chart))301 FigureStudio.addMeanLine(&chart, source: snap)302 #expect(chart.annotations.last?.kind == .referenceLine && abs(chart.annotations.last!.value - 38.5) < 1e-9)303 FigureStudio.addQuartileBand(&chart, source: snap)304 let band = chart.annotations.last!305 #expect(band.kind == .band && band.value < band.value2 && band.value >= 1 && band.value2 <= 100)306 FigureStudio.addNote(&chart, text: "n = 10", source: snap)307 #expect(chart.annotations.last?.text == "n = 10" && chart.annotations.last?.y == 100 && chart.annotations.last?.x == 1)308 FigureStudio.setTrendline(&chart, .polynomial, order: 2)309 #expect(chart.series[0].trendline?.kind == .polynomial && chart.series[0].trendline?.showEquation == true && chart.series[0].trendline?.showR2 == true)310 FigureStudio.setTrendline(&chart, nil)311 #expect(chart.series[0].trendline == nil)312 let bandSet = FigureStudio.setConfidenceBand(&chart, sheet: "Data", range: RangeRef(a1: "C2:D11")!)313 #expect(bandSet)314 #expect(chart.series[0].lower == .range(sheet: "Data", range: RangeRef(a1: "C2:C11")!) && chart.series[0].upper == .range(sheet: "Data", range: RangeRef(a1: "D2:D11")!))315 let bandRefused = FigureStudio.setConfidenceBand(&chart, sheet: "Data", range: RangeRef(a1: "B2:D11")!)316 #expect(!bandRefused)317 #expect(!FigureStudio.supportsAnnotations(ChartSpec(kind: .pie, series: [SeriesSpec(values: .literal([1]))])))318319 // the panel editor reads and writes the chart inside the draft, without touching the sheet or its undo stack320 ChartsFeature.openFigureStudio(editing: nil, in: s)321 let draft = FigureStudio.draft(in: s)322 let panel = draft.panels[0]323 let editor = FigureStudio.panelEditor(panel.id, session: s)324 #expect(editor.spec == panel.chart)325 editor.apply("Title") { $0.title = "Edited" }326 for w in [1.0, 2.0, 3.0] { editor.live("Line Width") { $0.series[0].style.lineWidth = w } }327 editor.flush()328 let now = ChartsState.of(s).figureDraft!.panels[0].chart329 #expect(now.title == "Edited" && now.series[0].style.lineWidth == 3)330 #expect(!s.engine.canUndo && s.sheet.meta.objects.count == 2)331 }332}333