-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathChartLayoutResolverTest.java
More file actions
797 lines (688 loc) · 37.1 KB
/
Copy pathChartLayoutResolverTest.java
File metadata and controls
797 lines (688 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
package com.demcha.compose.document.chart;
import com.demcha.compose.document.node.LineNode;
import com.demcha.compose.document.node.ParagraphNode;
import com.demcha.compose.document.node.ShapeNode;
import com.demcha.compose.document.style.DocumentPaint;
import com.demcha.compose.document.style.DocumentTextStyle;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
/**
* Deterministic golden tests for {@link ChartLayoutResolver}. A
* font-independent fake {@link ChartTextMetrics} (5pt per char, 10pt line
* height) makes the emitted geometry exact, so these assert real positions and
* sizes with no rendering and no font dependency.
*/
class ChartLayoutResolverTest {
/** width = 5pt per char, line height = 10pt. */
private static final ChartTextMetrics METRICS = new ChartTextMetrics() {
@Override public double width(DocumentTextStyle style, String text) {
return (text == null ? 0 : text.length()) * 5.0;
}
@Override public double lineHeight(DocumentTextStyle style) {
return 10.0;
}
@Override public double descent(DocumentTextStyle style) {
return 2.0;
}
};
private static ChartStyle baseStyle() {
return ChartDefaults.DEFAULT_THEME.toChartStyle();
}
@Test
void groupedBarGeometryIsExact() {
ChartData data = ChartData.builder()
.categories("A", "B")
.series("S", 10.0, 20.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// 5 grid lines + 5 tick labels + 2 bars + 2 category labels.
assertThat(out).hasSize(14);
assertThat(count(out, ShapeNode.class)).isEqualTo(2);
assertThat(count(out, LineNode.class)).isEqualTo(5);
assertThat(count(out, ParagraphNode.class)).isEqualTo(7);
// Frame: leftGutter = widest tick ("20" => 10) + 4 = 14; plotBottomY = 14;
// plotTopY = 95; plotHeight = 81. Bars sit on the baseline.
ChartPrimitive barA = byName(out, "bar_c0_s0");
ChartPrimitive barB = byName(out, "bar_c1_s0");
assertThat(barA.y()).isCloseTo(14.0, within(1e-6));
assertThat(barB.y()).isCloseTo(14.0, within(1e-6));
// value 10 -> fraction 0.5 -> height 40.5; value 20 -> full plot height 81.
assertThat(barA.height()).isCloseTo(40.5, within(1e-6));
assertThat(barB.height()).isCloseTo(81.0, within(1e-6));
// Taller bar for the larger value.
assertThat(barB.height()).isGreaterThan(barA.height());
// Tick labels span 0..20 at evenly spaced y; each label's glyph-ink
// centre lands on its gridline. inkCentre = descent + 0.70*size/2
// = 2.0 + 0.70*8/2 = 4.8 for the 8pt axis style.
double inkCenter = 2.0 + 0.70 * 8.0 / 2.0;
ChartPrimitive tick0 = byName(out, "tick_0");
ChartPrimitive tick4 = byName(out, "tick_4");
assertThat(tick0.y() + inkCenter).isCloseTo(14.0, within(1e-6)); // bottom tick on baseline
assertThat(tick4.y() + inkCenter).isCloseTo(95.0, within(1e-6)); // top tick at plotTopY
}
@Test
void lineChartEmitsSegmentsAndNoBars() {
ChartData data = ChartData.builder()
.categories("A", "B", "C")
.series("S", 1.0, 3.0, 2.0)
.build();
ChartSpec.Line line = ChartSpec.line().data(data).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// No bars; one polyline of two segments for three points.
assertThat(count(out, ShapeNode.class)).isEqualTo(0);
assertThat(out.stream().filter(p -> p.node().name().startsWith("line_s0_seg")).count())
.isEqualTo(2);
// 3 category labels present.
assertThat(out.stream().filter(p -> p.node().name().startsWith("cat_")).count())
.isEqualTo(3);
}
@Test
void nullValueBreaksTheLine() {
ChartData data = ChartData.builder()
.categories("A", "B", "C")
.series(new ChartData.Series("S", java.util.Arrays.asList(1.0, null, 2.0)))
.build();
ChartSpec.Line line = ChartSpec.line().data(data).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// A->null and null->C both broken: zero connecting segments.
assertThat(out.stream().filter(p -> p.node().name().startsWith("line_s0_seg")).count())
.isZero();
}
@Test
void minimalChartHidesGridAxesButKeepsBarsAndValueLabels() {
ChartData data = ChartData.builder()
.categories("A", "B")
.series("S", 10.0, 20.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar()
.data(data)
.valueAxis(AxisSpec.builder().showGridLines(false).showTickLabels(false).build())
.showCategoryLabels(false)
.valueLabels(ValueLabelMode.OUTSIDE)
.build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// No grid lines, no numeric tick labels, no category labels.
assertThat(count(out, LineNode.class)).isZero();
assertThat(out.stream().anyMatch(p -> p.node().name().startsWith("tick_"))).isFalse();
assertThat(out.stream().anyMatch(p -> p.node().name().startsWith("cat_"))).isFalse();
// Only the bars and their value labels remain.
assertThat(count(out, ShapeNode.class)).isEqualTo(2);
assertThat(out.stream().filter(p -> p.node().name().startsWith("value_")).count())
.isEqualTo(2);
// With no tick labels the value axis reserves no left gutter: bars start at x≈0.
ChartPrimitive barA = byName(out, "bar_c0_s0");
assertThat(barA.x()).isLessThan(20.0);
}
@Test
void valueLabelsNoneEmitsNoValueText() {
ChartData data = ChartData.builder().categories("A").series("S", 5.0).build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).valueLabels(ValueLabelMode.NONE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
assertThat(out.stream().anyMatch(p -> p.node().name().startsWith("value_"))).isFalse();
}
@Test
void unsupportedFeaturesAreRejectedLoudly() {
ChartData data = ChartData.builder().categories("A").series("S", 1.0).build();
ChartSpec.Bar inside = ChartSpec.bar().data(data).valueLabels(ValueLabelMode.INSIDE).build();
org.junit.jupiter.api.Assertions.assertThrows(UnsupportedOperationException.class,
() -> ChartLayoutResolver.resolve(inside, baseStyle(),
ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS));
}
@Test
void horizontalBarsGrowRightFromTheLeftEdge() {
ChartData data = ChartData.builder().categories("A", "B").series("S", 10.0, 20.0).build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).horizontal(true).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
ChartPrimitive barA = byName(out, "bar_c0_s0");
ChartPrimitive barB = byName(out, "bar_c1_s0");
// Both start at the plot's left edge; the 20-bar is twice the 10-bar.
assertThat(barA.x()).isEqualTo(barB.x());
assertThat(barB.width()).isCloseTo(barA.width() * 2.0, within(1e-6));
// First category sits ABOVE the second (reading order).
assertThat(barA.y()).isGreaterThan(barB.y());
}
@Test
void stackedBarsAnchorAtZeroEvenWithAnExplicitPositiveAxisMin() {
// total 30, axis.min(10) — a positive floor used to lift the baseline
// while segments stayed measured from zero, so the stack overshot
// (~135 > 95). The floor is pinned to zero, so the stack fills exactly
// to the value-30 level at the plot top.
assertStackFillsToTheTotal(10.0);
}
@Test
void stackedBarsAnchorAtZeroEvenWithAnExplicitNegativeAxisMin() {
// total 30, axis.min(-10) — a negative floor used to anchor the stack
// below zero (top reached only ~75 < 95). Same zero-floor pin fixes it.
assertStackFillsToTheTotal(-10.0);
}
private static void assertStackFillsToTheTotal(double axisMin) {
ChartData data = ChartData.builder().categories("A")
.series("S1", 10.0).series("S2", 20.0).build(); // total 30
ChartSpec.Bar bar = ChartSpec.bar().data(data)
.grouping(BarGrouping.STACKED)
.valueAxis(AxisSpec.builder().min(axisMin).max(30.0).build())
.build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// Same frame as the grouped test: plotBottomY = 14, plotTopY = 95. With
// the floor at zero and max == total, the stack fills the whole plot.
double baseY = byName(out, "bar_c0_s0").y();
double stackTop = out.stream()
.filter(p -> p.node().name().startsWith("bar_c0_"))
.mapToDouble(p -> p.y() + p.height())
.max().orElseThrow();
assertThat(baseY).isCloseTo(14.0, within(1e-6));
assertThat(stackTop).isCloseTo(95.0, within(1e-6));
}
@Test
void stackedBarsLabelTheCategoryTotal() {
ChartData data = ChartData.builder().categories("A")
.series("S1", 10.0).series("S2", 20.0).build();
ChartSpec.Bar bar = ChartSpec.bar().data(data)
.grouping(BarGrouping.STACKED).valueLabels(ValueLabelMode.OUTSIDE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
ParagraphNode total = (ParagraphNode) byName(out, "total_c0").node();
assertThat(total.text()).isEqualTo("30");
}
@Test
void groupedBarsWithNegativeValuesMeasureFromTheNiceFloor() {
ChartData data = ChartData.builder()
.categories("A", "B")
.series("S", 10.0, -2.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// Domain [-2, 10] with the zero baseline rounds to the nice range
// [-5, 10]: the axis extends below zero and both bars anchor at the
// -5 floor, so the negative bar renders as a short positive-height
// column reaching its value level (no crash, no inverted geometry).
ChartPrimitive positive = byName(out, "bar_c0_s0");
ChartPrimitive negative = byName(out, "bar_c1_s0");
assertThat(negative.y()).isEqualTo(positive.y());
// fractionOf(10) = 1.0 vs fractionOf(-2) = 0.2 over [-5, 10].
assertThat(negative.height()).isCloseTo(positive.height() * 0.2, within(1e-9));
// The negative bound appears as a tick label.
assertThat(out.stream().anyMatch(p -> p.node() instanceof ParagraphNode pn
&& pn.name().startsWith("tick_") && "-5".equals(pn.text()))).isTrue();
}
@Test
void stackedBarsSkipNonPositiveSegments() {
ChartData data = ChartData.builder().categories("A")
.series("Up", 5.0)
.series("Down", -3.0)
.series("Zero", 0.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar().data(data)
.grouping(BarGrouping.STACKED).valueLabels(ValueLabelMode.OUTSIDE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
// Only the positive segment stacks; negative and zero segments are
// skipped and the category total counts the positives alone.
assertThat(out.stream().filter(p -> p.node().name().startsWith("bar_c0_")).count())
.isEqualTo(1);
byName(out, "bar_c0_s0");
ParagraphNode total = (ParagraphNode) byName(out, "total_c0").node();
assertThat(total.text()).isEqualTo("5");
}
@Test
void onePointLineEmitsItsMarkerButNoSegments() {
ChartData data = ChartData.builder().categories("A").series("S", 7.0).build();
ChartStyle style = baseStyle().mergedUnder(ChartStyle.builder()
.pointMarker(PointMarker.circle(5.0))
.build());
// smooth + area exercise the interpolation and fill paths with a
// single sample as well.
ChartSpec.Line line = ChartSpec.line().data(data)
.smooth(true).area(true)
.valueLabels(ValueLabelMode.OUTSIDE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, style, ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// No connecting stroke exists, but the lone point still gets its
// marker and value label.
assertThat(out.stream().noneMatch(p -> p.node().name().startsWith("line_s0_seg")))
.isTrue();
byName(out, "point_s0_c0");
ParagraphNode label = (ParagraphNode) byName(out, "value_s0_c0").node();
assertThat(label.text()).isEqualTo("7");
}
@Test
void veryLongCategoryLabelsKeepTheirSlotWidth() {
ChartData data = ChartData.builder()
.categories("Short", "An extremely long category label that far exceeds the slot")
.series("S", 10.0, 20.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// Category labels are slot-sized: a long text wraps/centres inside
// its category slot instead of widening the geometry.
ChartPrimitive shortLabel = byName(out, "cat_0");
ChartPrimitive longLabel = byName(out, "cat_1");
assertThat(longLabel.width()).isEqualTo(shortLabel.width());
assertThat(longLabel.x()).isGreaterThan(shortLabel.x());
}
@Test
void bottomLegendInTightWidthStillEmitsEveryEntry() {
ChartData data = ChartData.builder().categories("A")
.series("First series with a long name", 1.0)
.series("Second series with a long name", 2.0)
.series("Third series with a long name", 3.0)
.series("Fourth series with a long name", 4.0)
.series("Fifth series with a long name", 5.0)
.build();
ChartSpec.Bar bar = ChartSpec.bar().data(data)
.legend(LegendPosition.BOTTOM).build();
// 120pt is far too narrow for five long legend entries: layout must
// stay deterministic and keep every entry (overflow, not loss).
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 120.0, 100.0, METRICS);
double previousX = Double.NEGATIVE_INFINITY;
for (int s = 0; s < 5; s++) {
byName(out, "legend_swatch_" + s);
ChartPrimitive label = byName(out, "legend_label_" + s);
assertThat(label.x()).isGreaterThan(previousX);
previousX = label.x();
}
}
@Test
void areaFillsRenderUnderEveryStroke() {
ChartData data = ChartData.builder().categories("A", "B", "C")
.series("S1", 1.0, 3.0, 2.0).series("S2", 2.0, 1.0, 3.0).build();
ChartSpec.Line line = ChartSpec.line().data(data).area(true).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
long areas = out.stream()
.filter(p -> p.node() instanceof com.demcha.compose.document.node.PolygonNode)
.count();
assertThat(areas).isEqualTo(2);
// Every area polygon is emitted before the first stroke segment.
int firstSegment = Integer.MAX_VALUE;
int lastArea = -1;
for (int i = 0; i < out.size(); i++) {
String name = out.get(i).node().name();
if (name.startsWith("line_s")) {
firstSegment = Math.min(firstSegment, i);
}
if (name.startsWith("area_s")) {
lastArea = Math.max(lastArea, i);
}
}
assertThat(lastArea).isLessThan(firstSegment);
// The fill is the translucent series colour.
com.demcha.compose.document.node.PolygonNode area =
(com.demcha.compose.document.node.PolygonNode) byName(out, "area_s0_r0").node();
assertThat(area.fillColor().color().getAlpha()).isLessThan(255);
}
@Test
void smoothLineEmitsOneNativeBezierRun() {
ChartData data = ChartData.builder().categories("A", "B", "C")
.series("S", 1.0, 3.0, 2.0).build();
ChartSpec.Line line = ChartSpec.line().data(data).smooth(true).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
// No tessellated sub-segments — the whole run is one native path.
assertThat(out.stream().noneMatch(p -> p.node().name().startsWith("line_s0_seg")))
.isTrue();
com.demcha.compose.document.node.PathNode curve =
(com.demcha.compose.document.node.PathNode) byName(out, "line_s0_curve0").node();
// MoveTo plus one cubic span per data gap.
assertThat(curve.segments()).hasSize(3);
assertThat(curve.segments().get(0))
.isInstanceOf(com.demcha.compose.document.style.DocumentPathSegment.MoveTo.class);
assertThat(curve.segments().get(1))
.isInstanceOf(com.demcha.compose.document.style.DocumentPathSegment.CubicTo.class);
assertThat(curve.segments().get(2))
.isInstanceOf(com.demcha.compose.document.style.DocumentPathSegment.CubicTo.class);
assertThat(curve.stroke()).isNotNull();
assertThat(curve.fillColor()).isNull();
}
@Test
void smoothAreaClosesTheExactCurveDownToTheBaseline() {
ChartData data = ChartData.builder().categories("A", "B", "C")
.series("S", 1.0, 3.0, 2.0).build();
ChartSpec.Line line = ChartSpec.line().data(data).smooth(true).area(true).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
com.demcha.compose.document.node.PathNode area =
(com.demcha.compose.document.node.PathNode) byName(out, "area_s0_r0").node();
// moveTo + 2 cubic spans + 2 baseline edges + close.
assertThat(area.segments()).hasSize(6);
assertThat(area.segments().get(3))
.isInstanceOf(com.demcha.compose.document.style.DocumentPathSegment.LineTo.class);
assertThat(area.segments().get(5))
.isInstanceOf(com.demcha.compose.document.style.DocumentPathSegment.Close.class);
assertThat(area.fillColor()).isNotNull();
assertThat(area.fillColor().color().getAlpha()).isLessThan(255);
assertThat(area.stroke()).isNull();
// The curved fill still paints under the curved stroke.
int areaIndex = -1;
int curveIndex = -1;
for (int i = 0; i < out.size(); i++) {
String name = out.get(i).node().name();
if (name.equals("area_s0_r0")) {
areaIndex = i;
}
if (name.equals("line_s0_curve0")) {
curveIndex = i;
}
}
assertThat(areaIndex).isLessThan(curveIndex);
}
@Test
void twoPointSmoothRunFallsBackToAStraightSegment() {
ChartData data = ChartData.builder().categories("A", "B")
.series("S", 1.0, 3.0).build();
ChartSpec.Line line = ChartSpec.line().data(data).smooth(true).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
// A two-point run has no curvature to express — it stays a segment.
byName(out, "line_s0_seg0");
assertThat(out.stream().noneMatch(p -> p.node().name().startsWith("line_s0_curve")))
.isTrue();
}
@Test
void rightLegendReservesAColumnOutsideThePlot() {
ChartData data = ChartData.builder().categories("A", "B")
.series("Alpha", 1.0, 2.0).build();
ChartSpec.Bar bar = ChartSpec.bar().data(data).legend(LegendPosition.RIGHT).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
// The grid line spans the plot; the legend swatch starts right of it.
ChartPrimitive grid = byName(out, "grid_0");
ChartPrimitive swatch = byName(out, "legend_swatch_0");
assertThat(swatch.x()).isGreaterThan(grid.x() + grid.width());
}
@Test
void topLegendPlacesTheStripAboveThePlot() {
ChartData data = ChartData.builder().categories("A", "B")
.series("Alpha", 1.0, 2.0).build();
ChartSpec.Line line = ChartSpec.line().data(data).legend(LegendPosition.TOP).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
ChartPrimitive legendLabel = byName(out, "legend_label_0");
ChartPrimitive topGrid = byName(out, "grid_4"); // highest tick gridline
assertThat(legendLabel.y()).isGreaterThan(topGrid.y());
}
@Test
void explicitAxisBoundsAreHonored() {
ChartData data = ChartData.builder().categories("A", "B").series("S", 42.0, 58.0).build();
ChartSpec.Bar bar = ChartSpec.bar()
.data(data)
.valueAxis(AxisSpec.builder().baselineAtZero(false).min(40.0).max(60.0).build())
.build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
bar, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// With domain forced to [40,60], value 42 sits near the plot bottom — its
// bar is much shorter than 58's (with [0,60] they would be nearly equal).
ChartPrimitive barA = byName(out, "bar_c0_s0");
ChartPrimitive barB = byName(out, "bar_c1_s0");
assertThat(barA.height()).isLessThan(barB.height() * 0.25);
}
@Test
void pointMarkersRenderAsEllipsesAboveAllSegments() {
ChartData data = ChartData.builder()
.categories("A", "B", "C")
.series("S1", 1.0, 3.0, 2.0)
.series("S2", 2.0, 1.0, 3.0)
.build();
ChartStyle style = baseStyle().mergedUnder(ChartStyle.builder()
.pointMarker(PointMarker.ellipse(6.0, 4.0))
.valueLabelOffset(3.0)
.build());
ChartSpec.Line line = ChartSpec.line().data(data)
.valueLabels(ValueLabelMode.OUTSIDE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, style, ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
// One ellipse marker per data point, with the configured ellipse axes.
List<ChartPrimitive> markers = out.stream()
.filter(p -> p.node() instanceof com.demcha.compose.document.node.EllipseNode)
.toList();
assertThat(markers).hasSize(6);
assertThat(markers.get(0).width()).isEqualTo(6.0);
assertThat(markers.get(0).height()).isEqualTo(4.0);
// Joint legibility: every marker is emitted after every line segment.
int lastSegment = -1;
int firstMarker = Integer.MAX_VALUE;
for (int i = 0; i < out.size(); i++) {
String name = out.get(i).node().name();
if (name.startsWith("line_s")) {
lastSegment = Math.max(lastSegment, i);
}
if (name.startsWith("point_s")) {
firstMarker = Math.min(firstMarker, i);
}
}
assertThat(firstMarker).isGreaterThan(lastSegment);
// Value label sits at marker top + the configured offset.
ChartPrimitive marker = markers.get(0);
ChartPrimitive valueLabel = byName(out, "value_s0_c0");
double markerCenterY = marker.y() + marker.height() / 2.0;
assertThat(valueLabel.y()).isCloseTo(markerCenterY + 4.0 / 2.0 + 3.0, within(1e-6));
}
@Test
void closeSeriesLabelsFlipBelowAndGetHaloChips() {
// Two series nearly touching at the same category: their above-point
// labels would overlap, so the lower one must flip below its point.
ChartData data = ChartData.builder()
.categories("A")
.series("S1", 10.0)
.series("S2", 10.8)
.build();
ChartStyle style = baseStyle().mergedUnder(ChartStyle.builder()
.pointMarker(PointMarker.circle(4.0))
.valueLabelOffset(3.0)
.build());
ChartSpec.Line line = ChartSpec.line().data(data)
.valueLabels(ValueLabelMode.OUTSIDE).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
line, style, ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
ChartPrimitive marker1 = byName(out, "point_s0_c0");
ChartPrimitive label1 = byName(out, "value_s0_c0");
ChartPrimitive marker2 = byName(out, "point_s1_c0");
ChartPrimitive label2 = byName(out, "value_s1_c0");
// Higher point keeps its label above; the lower one flips below.
assertThat(label2.y()).isGreaterThan(marker2.y());
assertThat(label1.y() + label1.height()).isLessThan(marker1.y());
// The flipped boxes no longer overlap.
boolean overlap = label1.y() < label2.y() + label2.height()
&& label1.y() + label1.height() > label2.y();
assertThat(overlap).isFalse();
// Theme default paints a halo chip behind each label, just before it.
assertThat(out.stream().filter(p -> p.node().name().endsWith("_halo")).count())
.isEqualTo(2);
// Labels (and their halos) are emitted after every marker.
int lastMarker = -1;
int firstHalo = Integer.MAX_VALUE;
for (int i = 0; i < out.size(); i++) {
String name = out.get(i).node().name();
if (name.startsWith("point_s")) {
lastMarker = Math.max(lastMarker, i);
}
if (name.endsWith("_halo")) {
firstHalo = Math.min(firstHalo, i);
}
}
assertThat(firstHalo).isGreaterThan(lastMarker);
}
@Test
void markerFillAndStrokeOverridesApply() {
ChartData data = ChartData.builder().categories("A").series("S", 1.0).build();
DocumentPaint white = DocumentPaint.solid(
com.demcha.compose.document.style.DocumentColor.WHITE);
com.demcha.compose.document.style.DocumentStroke ring =
com.demcha.compose.document.style.DocumentStroke.of(
com.demcha.compose.document.style.DocumentColor.BLACK, 1.2);
ChartStyle style = baseStyle().mergedUnder(ChartStyle.builder()
.pointMarker(PointMarker.circle(5.0).withFill(white).withStroke(ring))
.build());
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
ChartSpec.line().data(data).build(), style,
ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
com.demcha.compose.document.node.EllipseNode markerNode = out.stream()
.filter(p -> p.node() instanceof com.demcha.compose.document.node.EllipseNode)
.map(p -> (com.demcha.compose.document.node.EllipseNode) p.node())
.findFirst().orElseThrow();
assertThat(markerNode.fillColor().color())
.isEqualTo(com.demcha.compose.document.style.DocumentColor.WHITE.color());
assertThat(markerNode.stroke()).isEqualTo(ring);
}
@Test
void verticalGridLinesEmitWhenStyled() {
ChartData data = ChartData.builder().categories("A", "B", "C").series("S", 1.0, 2.0, 3.0).build();
ChartStyle style = ChartDefaults.DEFAULT_THEME.toChartStyle().mergedUnder(
ChartStyle.builder()
.grid(new ChartStyle.GridStyle(
ChartDefaults.DEFAULT_GRID_STROKE, ChartDefaults.DEFAULT_GRID_STROKE))
.build());
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
ChartSpec.bar().data(data).build(), style,
ChartDefaults.DEFAULT_THEME, 200.0, 100.0, METRICS);
// Two inner boundaries for three categories.
assertThat(out.stream().filter(p -> p.node().name().startsWith("vgrid_")).count())
.isEqualTo(2);
}
@Test
void pieEmitsOneSectorPolygonPerSliceWithPercentLabels() {
ChartData data = ChartData.builder()
.categories("A", "B", "C")
.series("S", 25.0, 25.0, 50.0)
.build();
ChartSpec.Pie pie = ChartSpec.pie().data(data)
.sliceLabels(SliceLabelMode.PERCENT)
.legend(LegendPosition.BOTTOM)
.build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
pie, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS);
List<ChartPrimitive> sectors = out.stream()
.filter(p -> p.node() instanceof com.demcha.compose.document.node.PolygonNode)
.toList();
assertThat(sectors).hasSize(3);
// Solid pie sectors close through the centre point.
com.demcha.compose.document.node.PolygonNode first =
(com.demcha.compose.document.node.PolygonNode) sectors.get(0).node();
assertThat(first.points().get(first.points().size() - 1).x()).isEqualTo(0.5);
assertThat(first.points().get(first.points().size() - 1).y()).isEqualTo(0.5);
// The 50% slice tessellates roughly twice as many arc vertices as a 25% one.
com.demcha.compose.document.node.PolygonNode big =
(com.demcha.compose.document.node.PolygonNode) sectors.get(2).node();
assertThat(big.points().size()).isGreaterThan(first.points().size() + 20);
// Percent labels with the default percent format.
assertThat(out.stream().map(p -> p.node())
.filter(n -> n instanceof ParagraphNode pn && pn.name().startsWith("slice_label_"))
.map(n -> ((ParagraphNode) n).text()))
.containsExactlyInAnyOrder("25%", "25%", "50%");
// Legend lists CATEGORIES for a pie.
assertThat(out.stream().map(p -> p.node())
.filter(n -> n instanceof ParagraphNode pn && pn.name().startsWith("legend_label_"))
.map(n -> ((ParagraphNode) n).text()))
.containsExactly("A", "B", "C");
}
@Test
void donutSectorsAreRingsAndCenterTextRenders() {
ChartData data = ChartData.builder()
.categories("A", "B")
.series("S", 60.0, 40.0)
.build();
ChartSpec.Pie donut = ChartSpec.pie().data(data)
.donutRatio(0.5)
.centerText("100k")
.build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
donut, baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS);
com.demcha.compose.document.node.PolygonNode ring = out.stream()
.filter(p -> p.node() instanceof com.demcha.compose.document.node.PolygonNode)
.map(p -> (com.demcha.compose.document.node.PolygonNode) p.node())
.findFirst().orElseThrow();
// A ring sector has no centre vertex: every point sits at >= inner radius.
double minDistance = ring.points().stream()
.mapToDouble(pt -> Math.hypot(pt.x() - 0.5, pt.y() - 0.5))
.min().orElseThrow();
assertThat(minDistance).isGreaterThan(0.24);
// Centre KPI text present.
assertThat(out.stream().map(p -> p.node())
.anyMatch(n -> n instanceof ParagraphNode pn && pn.text().equals("100k")))
.isTrue();
}
@Test
void horizontalBarsEmitCategorySeparatorsWhenStyled() {
ChartData data = ChartData.builder().categories("A", "B", "C")
.series("S", 1.0, 2.0, 3.0).build();
ChartStyle style = baseStyle().mergedUnder(ChartStyle.builder()
.grid(new ChartStyle.GridStyle(
ChartDefaults.DEFAULT_GRID_STROKE, ChartDefaults.DEFAULT_GRID_STROKE))
.build());
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
ChartSpec.bar().data(data).horizontal(true).build(), style,
ChartDefaults.DEFAULT_THEME, 200.0, 120.0, METRICS);
assertThat(out.stream().filter(p -> p.node().name().startsWith("csep_")).count())
.isEqualTo(2);
}
@Test
void pieRightLegendReservesAColumnOutsideTheCircle() {
ChartData data = ChartData.builder().categories("Alpha", "Beta")
.series("S", 60.0, 40.0).build();
ChartSpec.Pie pie = ChartSpec.pie().data(data).legend(LegendPosition.RIGHT).build();
List<ChartPrimitive> out = ChartLayoutResolver.resolve(
pie, baseStyle(), ChartDefaults.DEFAULT_THEME, 220.0, 160.0, METRICS);
ChartPrimitive slice = byName(out, "slice_0");
ChartPrimitive swatch = byName(out, "legend_swatch_0");
// The legend column starts right of the circle's bounding box.
assertThat(swatch.x()).isGreaterThan(slice.x() + slice.width());
}
@Test
void sliceGapAndCounterClockwiseLayoutShiftSectorGeometry() {
ChartData data = ChartData.builder().categories("A", "B")
.series("S", 50.0, 50.0).build();
ChartSpec.Pie plain = ChartSpec.pie().data(data).build();
ChartSpec.Pie ccw = ChartSpec.pie().data(data).clockwise(false)
.startAngleDegrees(0.0).build();
ChartStyle gapped = baseStyle().mergedUnder(
ChartStyle.builder().sliceGapDegrees(10.0).build());
var plainSlice = (com.demcha.compose.document.node.PolygonNode)
byName(ChartLayoutResolver.resolve(plain, baseStyle(),
ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS), "slice_0").node();
var gappedSlice = (com.demcha.compose.document.node.PolygonNode)
byName(ChartLayoutResolver.resolve(plain, gapped,
ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS), "slice_0").node();
var ccwSlice = (com.demcha.compose.document.node.PolygonNode)
byName(ChartLayoutResolver.resolve(ccw, baseStyle(),
ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS), "slice_0").node();
// The pad angle trims the sector: its leading outer vertex moves.
assertThat(gappedSlice.points().get(0)).isNotEqualTo(plainSlice.points().get(0));
// Counter-clockwise from 0° starts at three o'clock going up:
// the first outer vertex sits at (1.0, 0.5).
assertThat(ccwSlice.points().get(0).x()).isCloseTo(1.0, within(1e-9));
assertThat(ccwSlice.points().get(0).y()).isCloseTo(0.5, within(1e-9));
}
@Test
void pieRejectsInvalidInputLoudly() {
ChartData twoSeries = ChartData.builder()
.categories("A").series("S1", 1.0).series("S2", 2.0).build();
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
() -> ChartSpec.pie().data(twoSeries).build());
ChartData negative = ChartData.builder().categories("A", "B").series("S", 5.0, -1.0).build();
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
() -> ChartLayoutResolver.resolve(ChartSpec.pie().data(negative).build(),
baseStyle(), ChartDefaults.DEFAULT_THEME, 200.0, 200.0, METRICS));
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
() -> ChartSpec.pie().data(ChartData.builder().categories("A").series("S", 1.0).build())
.centerText("x").build()); // centerText without a donut hole
}
private static long count(List<ChartPrimitive> out, Class<?> type) {
return out.stream().filter(p -> type.isInstance(p.node())).count();
}
private static ChartPrimitive byName(List<ChartPrimitive> out, String name) {
return out.stream().filter(p -> p.node().name().equals(name)).findFirst().orElseThrow();
}
}