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/ViewerTests.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 Testing90import SheetCore91import SheetCharts92import SheetUI93@testable import FeatureCharts9495@MainActor @Suite struct ViewerTests {96 /// Month | North | Central | Total(formula of North+Central scaled by F1)97 func makeSession() -> WorkbookSession {98 let wb = Workbook(sheetNames: ["Sales", "Other"])99 let s = WorkbookSession(workbook: wb, locale: Locale(identifier: "en_US"))100 s.perform("fill") { e in101 for (c, h) in ["Month", "North", "Central", "Total"].enumerated() { e.set(sheet: 0, row: 0, col: c, .value(.text(h))) }102 for r in 1...6 {103 e.set(sheet: 0, row: r, col: 0, .value(.text("M\(r)")))104 e.set(sheet: 0, row: r, col: 1, .value(.number(Double(10 * r))))105 e.set(sheet: 0, row: r, col: 2, .value(.number(Double(5 * r + 1))))106 _ = e.setFormula(sheet: 0, row: r, col: 3, "=(B\(r + 1)+C\(r + 1))*$F$1")107 }108 e.set(sheet: 0, row: 0, col: 5, .value(.number(2)))109 }110 s.engine.clearUndoHistory()111 return s112 }113114 func range(_ a1: String, sheet: String = "Sales") -> DataRef { .range(sheet: sheet, range: RangeRef(a1: a1)!) }115116 func columnSpec(_ kind: ChartKind = .column) -> ChartSpec {117 ChartSpec(kind: kind, series: [SeriesSpec(name: "North", values: range("B2:B7")), SeriesSpec(name: "Central", values: range("C2:C7")),118 SeriesSpec(name: "Total", values: range("D2:D7"))], categories: range("A2:A7"))119 }120121 func layout(_ spec: ChartSpec, _ s: WorkbookSession, viewport: ChartViewport? = nil) -> (ChartLayout, ChartData) {122 let snap = ChartSnapshot.capture([spec], workbook: s.workbook)123 let data = ChartData.resolve(spec, source: snap)124 return (ChartRenderer.scene(spec, data: data, size: CGSize(width: 640, height: 400), measure: CoreTextMeasurer(), viewport: viewport).layout, data)125 }126127 // MARK: Linking128129 @Test func linksCategoryChartsToValueCells() {130 let spec = columnSpec()131 #expect(ChartLinking.sourceCell(spec: spec, seriesIndex: 1, pointIndex: 3) == LinkedCell(sheet: "Sales", cell: CellRef(a1: "C5")!))132 #expect(ChartLinking.sourceCell(spec: spec, seriesIndex: 0, pointIndex: 0)?.text == "Sales!B2")133 #expect(ChartLinking.sourceCell(spec: spec, seriesIndex: 0, pointIndex: 6) == nil) // past the range134 #expect(ChartLinking.sourceCell(spec: spec, seriesIndex: 7, pointIndex: 0) == nil)135 // a series laid out in a row136 var rows = ChartSpec(kind: .line, series: [SeriesSpec(values: range("B3:D3"))])137 #expect(ChartLinking.sourceCell(spec: rows, seriesIndex: 0, pointIndex: 2)?.cell == CellRef(a1: "D3")!)138 rows.series[0].values = .literal([1, 2, 3])139 #expect(ChartLinking.sourceCell(spec: rows, seriesIndex: 0, pointIndex: 1) == nil)140 }141142 @Test func linksSpecialKinds() {143 // pie: first series only144 var pie = columnSpec(.pie)145 #expect(ChartLinking.sourceCell(spec: pie, seriesIndex: 0, pointIndex: 4)?.cell == CellRef(a1: "B6")!)146 pie.kind = .treemap147 #expect(ChartLinking.sourceCell(spec: pie, seriesIndex: 0, pointIndex: 1)?.cell == CellRef(a1: "B3")!)148 // matrix in one 2-D range: row-major index149 let heat = ChartSpec(kind: .heatmap, series: [SeriesSpec(values: range("B2:D7"))])150 #expect(ChartLinking.sourceCell(spec: heat, seriesIndex: 0, pointIndex: 2 * 3 + 1)?.cell == CellRef(a1: "C4")!)151 #expect(ChartLinking.sourceCell(spec: heat, seriesIndex: 0, pointIndex: 18) == nil)152 // matrix as one series per row153 let rows = ChartSpec(kind: .contour, series: [SeriesSpec(values: range("B2:D2")), SeriesSpec(values: range("B3:D3"))])154 #expect(ChartLinking.sourceCell(spec: rows, seriesIndex: 0, pointIndex: 1 * 3 + 2)?.cell == CellRef(a1: "D3")!)155 // clipped open-ended range: the effective shape decides156 let open = ChartSpec(kind: .heatmap, series: [SeriesSpec(values: range("B:D"))])157 #expect(ChartLinking.sourceCell(spec: open, seriesIndex: 0, pointIndex: 4, shape: { _ in (7, 3) })?.cell == CellRef(a1: "C2")!)158 // candlestick: the close price; overlays: their values159 let candle = ChartSpec(kind: .candlestick, series: [SeriesSpec(open: range("B2:B7"), high: range("D2:D7"), low: range("C2:C7"), close: range("B2:B7", sheet: "Other")),160 SeriesSpec(values: range("D2:D7"))])161 #expect(ChartLinking.sourceCell(spec: candle, seriesIndex: 0, pointIndex: 2) == LinkedCell(sheet: "Other", cell: CellRef(a1: "B4")!))162 #expect(ChartLinking.sourceCell(spec: candle, seriesIndex: 1, pointIndex: 2)?.cell == CellRef(a1: "D4")!)163 // summarising kinds have no single source cell164 for kind in [ChartKind.histogram, .density, .boxPlot, .violin] {165 #expect(ChartLinking.sourceCell(spec: columnSpec(kind), seriesIndex: 0, pointIndex: 0) == nil)166 }167 #expect(LinkedCell(sheet: "My Sheet", cell: CellRef(0, 0)).text == "'My Sheet'!A1")168 }169170 @Test func everyHitItemOfACategoryChartLinksToItsCell() {171 let s = makeSession()172 let spec = columnSpec(.line)173 let (l, _) = layout(spec, s)174 #expect(l.hitItems.count == 18)175 for item in l.hitItems {176 let cell = ChartLinking.sourceCell(spec: spec, seriesIndex: item.seriesIndex, pointIndex: item.pointIndex)177 #expect(cell != nil)178 if let cell { #expect(s.sheet.value(cell.cell.row, cell.cell.col).numberValue == item.y) }179 }180 }181182 // MARK: Viewport183184 @Test func zoomKeepsThePointUnderThePointer() throws {185 let s = makeSession()186 var spec = ChartSpec(kind: .scatter, series: [SeriesSpec(values: range("C2:C7"), x: range("B2:B7"))])187 let (l, _) = layout(spec, s)188 let p = CGPoint(x: l.plotRect.minX + l.plotRect.width * 0.3, y: l.plotRect.minY + l.plotRect.height * 0.6)189 let before = try #require(l.dataPoint(at: p))190 let full = try #require(l.viewport)191 let v = try #require(ViewportMath.zoom(l, factor: 2, at: p))192 #expect(abs((v.x!.upperBound - v.x!.lowerBound) - (full.x!.upperBound - full.x!.lowerBound) / 2) < 1e-9)193 #expect(abs((v.y!.upperBound - v.y!.lowerBound) - (full.y!.upperBound - full.y!.lowerBound) / 2) < 1e-9)194 let (zoomed, _) = layout(spec, s, viewport: v)195 let after = try #require(zoomed.dataPoint(at: p))196 #expect(abs(after.x - before.x) < 1e-6 && abs(after.y - before.y) < 1e-6)197 // zooming back out restores the window, and "covers" detects it198 let back = try #require(ViewportMath.zoom(zoomed, factor: 0.5, at: p))199 #expect(abs(back.x!.lowerBound - full.x!.lowerBound) < 1e-6 && abs(back.y!.upperBound - full.y!.upperBound) < 1e-6)200 #expect(!ViewportMath.covers(v, full))201 #expect(ViewportMath.covers(ChartViewport(x: (full.x!.lowerBound - 1)...(full.x!.upperBound + 1), y: full.y), full))202 #expect(ViewportMath.zoom(l, factor: 0, at: p) == nil)203 // log axis: the zoom is symmetric in log space204 spec.xAxis.scale = .log10205 let (ll, _) = layout(spec, s)206 let lp = CGPoint(x: ll.plotRect.midX, y: ll.plotRect.midY)207 let anchor = try #require(ll.dataPoint(at: lp))208 let lv = try #require(ViewportMath.zoom(ll, factor: 4, at: lp))209 #expect(abs(log(anchor.x / lv.x!.lowerBound) - log(lv.x!.upperBound / anchor.x)) < 1e-6)210 #expect(lv.x!.lowerBound > 0)211 }212213 @Test func panAndRectangleZoom() throws {214 let s = makeSession()215 let spec = ChartSpec(kind: .scatter, series: [SeriesSpec(values: range("C2:C7"), x: range("B2:B7"))])216 let (l, _) = layout(spec, s)217 let full = try #require(l.viewport)218 let a = CGPoint(x: l.plotRect.midX, y: l.plotRect.midY), b = CGPoint(x: a.x + 40, y: a.y - 25)219 let v = try #require(ViewportMath.pan(l, from: a, to: b))220 // same spans, and the data that was under `a` is now under `b`221 #expect(abs((v.x!.upperBound - v.x!.lowerBound) - (full.x!.upperBound - full.x!.lowerBound)) < 1e-9)222 let (pl, _) = layout(spec, s, viewport: v)223 let d0 = try #require(l.dataPoint(at: a)), d1 = try #require(pl.dataPoint(at: b))224 #expect(abs(d0.x - d1.x) < 1e-6 && abs(d0.y - d1.y) < 1e-6)225226 let rect = CGRect(x: l.plotRect.minX + 50, y: l.plotRect.minY + 30, width: 120, height: 80)227 let z = try #require(ViewportMath.zoom(l, to: rect))228 let tl = try #require(l.dataPoint(at: CGPoint(x: rect.minX, y: rect.minY))), br = try #require(l.dataPoint(at: CGPoint(x: rect.maxX, y: rect.maxY)))229 #expect(abs(z.x!.lowerBound - min(tl.x, br.x)) < 1e-9 && abs(z.x!.upperBound - max(tl.x, br.x)) < 1e-9)230 #expect(abs(z.y!.lowerBound - min(tl.y, br.y)) < 1e-9 && abs(z.y!.upperBound - max(tl.y, br.y)) < 1e-9)231 // a negative-size rectangle is the same rectangle; a tiny one is a click232 #expect(ViewportMath.zoom(l, to: CGRect(x: rect.maxX, y: rect.maxY, width: -rect.width, height: -rect.height)) == z)233 #expect(ViewportMath.zoom(l, to: CGRect(x: rect.minX, y: rect.minY, width: 3, height: 80)) == nil)234 // charts without axes cannot zoom235 let (pie, _) = layout(columnSpec(.pie), s)236 #expect(ViewportMath.zoom(pie, factor: 2, at: CGPoint(x: 100, y: 100)) == nil)237 #expect(ViewportMath.pan(pie, from: .zero, to: CGPoint(x: 5, y: 5)) == nil)238 // exports bake the window into continuous axes only239 var baked = spec240 ViewportMath.bake(z, into: &baked, layout: l)241 #expect(baked.xAxis.min == z.x!.lowerBound && baked.yAxis.max == z.y!.upperBound)242 var band = columnSpec()243 let (bl, _) = layout(band, s)244 ViewportMath.bake(ChartViewport(x: 1...3, y: 0...50), into: &band, layout: bl)245 #expect(band.xAxis.min == nil && band.yAxis.max == 50)246 }247248 // MARK: Visibility249250 @Test func hidingSeriesKeepsColoursAndMapsIndices() {251 var spec = columnSpec()252 spec.series[2].style.color = RGBA(hex: 0x123456)253 let (out, map) = SeriesVisibility.apply(spec, hidden: [0])254 #expect(map == [1, 2])255 #expect(out.series.map(\.name) == ["Central", "Total"])256 #expect(out.series[0].style.color == spec.theme.color(1))257 #expect(out.series[1].style.color == RGBA(hex: 0x123456))258 #expect(out.legend.showForSingleSeries)259 // nothing hidden, everything hidden, or a kind without per-series marks: unchanged260 #expect(SeriesVisibility.apply(spec, hidden: []).spec == spec)261 #expect(SeriesVisibility.apply(spec, hidden: [0, 1, 2]).map == [0, 1, 2])262 #expect(SeriesVisibility.apply(columnSpec(.pie), hidden: [0]).map == [0, 1, 2])263 #expect(!SeriesVisibility.canToggle(.heatmap) && !SeriesVisibility.canToggle(.candlestick) && SeriesVisibility.canToggle(.scatter))264 #expect(SeriesVisibility.color(spec, 2) == RGBA(hex: 0x123456) && SeriesVisibility.color(spec, 0) == spec.theme.color(0))265 }266267 // MARK: Tooltip268269 @Test func sharedTooltipListsEverySeriesWithAxisFormats() throws {270 let s = makeSession()271 var spec = columnSpec()272 spec.yAxis.numberFormat = "0.0"273 let (l, data) = layout(spec, s)274 let item = try #require(l.item(series: 1, point: 2))275 let tip = try #require(ChartTooltip.make(spec: spec, data: data, layout: l, at: item.anchor))276 #expect(tip.title == "M3")277 #expect(tip.rows.map(\.name) == ["North", "Central", "Total"])278 // rendered by SheetFormat with the axis code (decimal separator of the current locale)279 let shown = [30.0, 16, 92].map { ChartFormat.display($0, code: "0.0") }280 #expect(tip.rows.map(\.value) == shown && shown[0].count == 4)281 #expect(tip.rows.map(\.emphasized) == [false, true, false])282 #expect(tip.primary.seriesIndex == 1 && tip.primary.pointIndex == 2 && tip.items.count == 3)283 #expect(tip.text == "M3\nNorth: \(shown[0])\nCentral: \(shown[1])\nTotal: \(shown[2])")284 // far outside the chart: nothing285 #expect(ChartTooltip.make(spec: spec, data: data, layout: l, at: CGPoint(x: -400, y: -400)) == nil)286 // secondary-axis series use the secondary format287 spec.kind = .combo288 spec.series[2].axis = .secondary; spec.series[2].kind = .line289 spec.y2Axis = AxisSpec(numberFormat: "0%")290 let (cl, cdata) = layout(spec, s)291 let total = try #require(cl.item(series: 2, point: 0))292 let ctip = ChartTooltip.make(spec: spec, data: cdata, layout: cl, primary: total)293 #expect(ctip.rows.last?.value == "3200%")294 }295296 @Test func tooltipsOfOtherKinds() throws {297 let s = makeSession()298 // scatter: x and y of the single point299 var scatter = ChartSpec(kind: .scatter, series: [SeriesSpec(name: "Central", values: range("C2:C7"), x: range("B2:B7"))])300 scatter.xAxis.title = "North"301 var (l, data) = layout(scatter, s)302 var item = try #require(l.item(series: 0, point: 4))303 var tip = try #require(ChartTooltip.make(spec: scatter, data: data, layout: l, at: item.anchor))304 #expect(tip.title == "Central" && tip.rows.map(\.name) == ["North", "y"] && tip.rows.map(\.value) == ["50", "26"])305 // pie: value and share306 let pie = columnSpec(.pie)307 (l, data) = layout(pie, s)308 item = try #require(l.item(series: 0, point: 5))309 tip = ChartTooltip.make(spec: pie, data: data, layout: l, primary: item)310 #expect(tip.title == "M6" && tip.rows[0].value == "60")311 #expect(tip.rows[1].value == (60.0 / 210.0).formatted(.percent.precision(.fractionLength(1))))312 // heatmap: row and column labels313 var heat = ChartSpec(kind: .heatmap, series: [SeriesSpec(values: range("B2:D7"))], categories: range("B1:D1"))314 heat.rowLabels = range("A2:A7")315 (l, data) = layout(heat, s)316 item = try #require(l.item(series: 0, point: 1 * 3 + 2))317 tip = ChartTooltip.make(spec: heat, data: data, layout: l, primary: item)318 #expect(tip.title == "M2 · Total" && tip.rows[0].value == "62")319 // candlestick: the four prices320 let candle = ChartSpec(kind: .candlestick, series: [SeriesSpec(open: range("B2:B7"), high: range("D2:D7"), low: range("C2:C7"), close: range("B2:B7"))], categories: range("A2:A7"))321 (l, data) = layout(candle, s)322 item = try #require(l.item(series: 0, point: 1))323 tip = ChartTooltip.make(spec: candle, data: data, layout: l, primary: item)324 #expect(tip.title == "M2" && tip.rows.count == 4 && tip.rows.map(\.value) == ["20", "62", "11", "20"])325 // histogram: a bin and its count326 let hist = ChartSpec(kind: .histogram, series: [SeriesSpec(name: "North", values: range("B2:B7"))])327 (l, data) = layout(hist, s)328 item = try #require(l.hitItems.first)329 tip = ChartTooltip.make(spec: hist, data: data, layout: l, primary: item)330 #expect(tip.title == "North" && tip.rows.count == 2)331 }332333 // MARK: What-if slider334335 @Test func snappingAndDefaultRanges() {336 #expect(WhatIfSlider.snap(0.234, minimum: 0, maximum: 1, step: 0.05) == 0.25)337 #expect(WhatIfSlider.snap(0.3, minimum: 0, maximum: 1, step: 0.1) == 0.3)338 #expect(WhatIfSlider.snap(7, minimum: 0, maximum: 5, step: 1) == 5)339 #expect(WhatIfSlider.snap(-3, minimum: 0, maximum: 5, step: 1) == 0)340 #expect(WhatIfSlider.snap(12.4, minimum: 10, maximum: 20, step: 3) == 13)341 #expect(WhatIfSlider.snap(19.9, minimum: 10, maximum: 20, step: 3) == 19)342 #expect(WhatIfSlider.snap(2.345, minimum: 0, maximum: 5, step: 0) == 2.345)343 #expect(WhatIfSlider.snap(3, minimum: 5, maximum: 0, step: 1) == 3) // swapped bounds344 #expect(WhatIfSlider.snap(.nan, minimum: 1, maximum: 5, step: 1) == 1)345 let r = WhatIfSlider.defaultRange(for: 200)346 #expect(r.minimum == 100 && r.maximum == 300 && r.step == 2)347 #expect(WhatIfSlider.defaultRange(for: 0) == (0, 1, 0.01))348 #expect(WhatIfSlider.defaultRange(for: 0.08) == (0, 1, 0.01))349 let n = WhatIfSlider.defaultRange(for: -40)350 #expect(n.minimum == -60 && n.maximum == -20)351 }352353 @Test func targetMustBeANumericInputCell() {354 let s = makeSession()355 let w = WhatIfSlider(session: s)356 #expect(!w.setTarget(text: "D2")) // formula357 #expect(w.message != nil && w.target == nil)358 #expect(!w.setTarget(text: "A2")) // text359 #expect(!w.setTarget(text: "B2:B4")) // not a single cell360 #expect(!w.setTarget(text: "Nowhere!B2"))361 #expect(w.setTarget(text: "Sales!F1"))362 #expect(w.message == nil && w.value == 2 && w.targetText == "Sales!F1")363 #expect(w.minimum == 1 && w.maximum == 3)364 s.select(cell: CellRef(a1: "B3")!)365 #expect(w.useSelection() && w.value == 20 && w.targetText == "Sales!B3")366 // the cell turns into text: the target is dropped on refresh367 s.perform("edit") { $0.set(sheet: 0, row: 2, col: 1, .value(.text("x"))) }368 w.refresh()369 #expect(w.target == nil)370 }371372 @Test func oneDragIsOneUndoStepAndRecalculatesDependents() {373 let s = makeSession()374 let w = WhatIfSlider(session: s)375 #expect(w.setTarget(text: "F1"))376 w.minimum = 0; w.maximum = 10; w.step = 0.5377 #expect(s.sheet.value(1, 3) == .number(32)) // (10 + 6) × 2378 #expect(!s.engine.canUndo)379 let changes = s.engine.changeCount380 let revision = s.contentRevision381 w.begin()382 for raw in [2.4, 3.1, 4.76, 6.2, 7.49] {383 w.drag(to: raw)384 // live: the cell and its dependents follow every step, without touching the undo history385 #expect(s.sheet.value(0, 5) == .number(w.value))386 #expect(s.sheet.value(1, 3) == .number(16 * w.value))387 #expect(!s.engine.canUndo && s.engine.changeCount == changes)388 }389 #expect(w.value == 7.5 && w.isDragging)390 #expect(s.contentRevision > revision) // charts were told to redraw391 w.end()392 #expect(!w.isDragging)393 #expect(s.engine.changeCount == changes + 1)394 #expect(s.engine.undoLabel == "What-If Slider")395 #expect(s.sheet.value(0, 5) == .number(7.5) && s.sheet.value(6, 3) == .number((60 + 31) * 7.5))396 s.undo()397 #expect(s.sheet.value(0, 5) == .number(2) && s.sheet.value(1, 3) == .number(32))398 #expect(!s.engine.canUndo) // exactly one step399 w.refresh()400 #expect(w.value == 2)401 s.redo()402 #expect(s.sheet.value(0, 5) == .number(7.5))403 }404405 @Test func dragBackToTheOriginalLeavesNoUndoStep() {406 let s = makeSession()407 let w = WhatIfSlider(session: s)408 #expect(w.setTarget(text: "F1"))409 w.minimum = 0; w.maximum = 10; w.step = 1410 w.drag(to: 9); w.drag(to: 2)411 w.end()412 #expect(!s.engine.canUndo && s.sheet.value(0, 5) == .number(2))413 // values outside the range are clamped; a typed value is one step414 w.drag(to: 99); w.end()415 #expect(s.sheet.value(0, 5) == .number(10))416 w.commit(4.4)417 #expect(s.sheet.value(0, 5) == .number(4) && w.value == 4)418 s.undo(); s.undo()419 #expect(s.sheet.value(0, 5) == .number(2) && !s.engine.canUndo)420 }421422 // MARK: Viewer model423424 func place(_ spec: ChartSpec, _ s: WorkbookSession) -> SheetObject {425 let o = SheetObject(id: spec.id, kind: ChartSpec.objectKind, name: "Chart", x: 10, y: 10, width: 400, height: 260, payload: ChartPayload.encode(ChartValue(spec: spec))!)426 s.addObject(o)427 return o428 }429430 @Test func modelFramesLinkingAndExport() throws {431 let s = makeSession()432 let o = place(columnSpec(.line), s)433 ChartsState.of(s).viewerObjectID = o.id434 let m = ChartViewerModel(session: s)435 m.sync()436 let size = CGSize(width: 600, height: 380)437 let f = try #require(m.frame(size: size, dark: false))438 #expect(f.map == [0, 1, 2] && f.seriesNames == ["North", "Central", "Total"] && f.layout.hitItems.count == 18)439 // hiding the first series: the drawn series 0 is the original series 1, and linking goes through the map440 m.toggleSeries(0)441 let g = try #require(m.frame(size: size, dark: false))442 #expect(g.map == [1, 2] && g.layout.hitItems.count == 12 && g.seriesNames == ["North", "Central", "Total"])443 let item = try #require(g.layout.item(series: 0, point: 3))444 #expect(m.link(item))445 #expect(m.linked?.text == "Sales!C5 = 21" && s.statusMessage == "Sales!C5 = 21")446 // the last visible series cannot be hidden447 m.toggleSeries(1); m.toggleSeries(2)448 #expect(m.hidden == [0, 1])449 // a what-if edit changes the frame without any explicit invalidation450 #expect(m.whatIf.setTarget(text: "F1"))451 let before = try #require(m.frame(size: size, dark: false)).layout.hitItems.compactMap(\.y)452 m.whatIf.drag(to: 3)453 let during = try #require(m.frame(size: size, dark: false)).layout.hitItems.compactMap(\.y)454 #expect(before != during && during.first == 48)455 m.whatIf.end()456 // export: light theme, visible series only, zoom baked in457 m.hidden = [0]458 m.viewport = ChartViewport(x: 1...3, y: 5...40)459 _ = m.frame(size: size, dark: true)460 let job = try #require(m.exportJob())461 #expect(job.spec.series.count == 2 && !job.spec.theme.isDark && job.size == CGSize(width: 400, height: 260))462 #expect(job.spec.yAxis.min == 5 && job.spec.yAxis.max == 40 && job.spec.xAxis.min == nil)463 m.useCustomSize = true; m.customWidth = 900; m.customHeight = 10464 #expect(m.exportSize == CGSize(width: 900, height: 40))465 let png = try #require(ChartExporter.data(job.spec, source: job.snapshot, size: job.size, format: .png, scale: 2, formatter: job.formatter))466 #expect(png.starts(with: [0x89, 0x50, 0x4E, 0x47]))467 // reveal: closes the studio and selects the cell on its sheet468 s.studioPane = ChartsFeature.viewerPaneID469 s.activateSheet(1)470 m.revealLinked()471 #expect(s.studioPane == nil && s.sheetIndex == 0 && s.selection.active == CellRef(a1: "C5")!)472 // another chart resets the view state; a deleted chart gives no frame473 let other = place(columnSpec(.column), s)474 ChartsState.of(s).viewerObjectID = other.id475 m.sync()476 #expect(m.viewport == nil && m.hidden.isEmpty && m.linked == nil)477 s.removeObject(other.id)478 #expect(m.frame(size: size, dark: false) == nil)479 }480481 @Test func summarisingMarksDoNotLink() throws {482 let s = makeSession()483 let o = place(columnSpec(.histogram), s)484 ChartsState.of(s).viewerObjectID = o.id485 let m = ChartViewerModel(session: s)486 m.sync()487 let f = try #require(m.frame(size: CGSize(width: 500, height: 300), dark: false))488 let item = try #require(f.layout.hitItems.first)489 #expect(!m.link(item) && m.linked == nil)490 }491}492