blib/lib/HTML/D3.pm

filter: Statementstmt 98.7% 871 / 882 Branchbran 95.8% 412 / 430 Conditioncond 78.7% 281 / 357 MC/DCmcdc 54.5% 109 / 200 Subroutinesub 98.1% 54 / 55 Podpod 100% 27 / 27 totaltotal 89.9% 1754 / 1951 CC 388 SCAR 33.2
CC
388
Cov
94%
render_scatter_chart_snippet
59.6
render_bar_chart_snippet
50.1
render_stacked_bar_snippet
40.9
CRAP 27.6
↑ Summary
1 package HTML::D3;
2  
3 31 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 31 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 31 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 31 ▶use Carp qw(carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 31 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 31 my $_JSON = JSON::MaybeXS->new(utf8 => 0);
11 31 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 31 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 31 ▶use Params::Validate::Strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 31 ▶use Scalar::Util qw(blessed looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 =head1 NAME
17  
18 HTML::D3 - A simple Perl module for generating charts using D3.js.
19  
20 =head1 VERSION
21  
22 Version 0.28
23  
24 =cut
25  
26 31 our $VERSION = '0.28';
27  
28 =head1 SYNOPSIS
29  
30 use HTML::D3;
31  
32 my $chart = HTML::D3->new(
33 width => 1024,
34 height => 768,
35 title => 'Sample Bar Chart'
36 );
37  
38 my $data = [
39 ['Category 1', 10],
40 ['Category 2', 20],
41 ['Category 3', 30]
42 ];
43  
44 my $html = $chart->render_bar_chart($data);
45 print $html;
46  
47 $chart = HTML::D3->new(title => 'Sales Data');
48  
49 $data = [
50 ['Product A', 100],
51 ['Product B', 150],
52 ['Product C', 200]
53 ];
54  
55 $html = $chart->render_line_chart($data);
56 print $html;
57  
58 =head1 DESCRIPTION
59  
60 HTML::D3 is a Perl module that provides functionality to create simple charts using D3.js.
61 The module generates HTML and JavaScript code to render the chart in a web browser.
62  
63 Text in a chart's data and options is written into a C<E<lt>scriptE<gt>> so that it
64 cannot end the script: C<E<lt>> is written as C<\u003c>, which JavaScript reads back
65 as the same character. An C<id> is written into an attribute, a selector and a
66 script, so it must be letters, digits, C<_> and C<->, not starting with a digit or
67 C<->. Any other C<id> is ignored and the method's default used, so read the id a
68 method actually used from the C<svg_id> or C<table_id> it returns.
69  
70 =head1 METHODS
71  
72 The C<=head3 API SPECIFICATION> subsections use L<Params::Validate::Strict>
73 schema syntax (C<< type => 'arrayref' >> etc.) as a documentation convention.
74 The module is also used at runtime in C<new()> to validate constructor
75 arguments; it is therefore a required runtime dependency. The schemas describe
76 the parameter contract in machine-readable notation and can be plumbed into a
77 WAF or test generator if desired.
78  
79 =head2 new
80  
81 my $chart = HTML::D3->new(%args);
82  
83 Creates a new HTML::D3 object.
84 Accepts the following optional arguments:
85  
86 =over 4
87  
88 =item * C<width> - The width of the chart (default: 800).
89  
90 =item * C<height> - The height of the chart (default: 600).
91  
92 =item * C<title> - The title of the chart (default: 'Chart').
93 It is plain text, escaped when it is written to the page: C<E<lt>> and C<&> appear
94 as themselves, and HTML in a title is shown rather than obeyed.
95  
96 =item * C<responsive> - If true, SVG elements are rendered with
97 C<viewBox> and C<width="100%"> instead of fixed pixel dimensions, so the
98 chart scales fluidly with its container; with no C<height> attribute, the
99 height follows the C<viewBox>'s proportions. (C<height="auto"> is not a
100 valid value for the attribute: Chromium logs an error for it and ignores it.)
101 For snippet methods the per-call C<< opts => { responsive => 1 } >>
102 takes precedence over this object-level setting (default: 0).
103  
104 =back
105  
106 =cut
107  
108 sub new
109 548 ▶{
Subroutine new: called CC=9 SCAR=22.0
Pod documented
110 548 my $class = shift;
111  
112 548 ▶ my $params = Params::Validate::Strict::validate_strict({
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
118430
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
113 args => Params::Get::get_params(undef, \@_) || {},
114 schema => {
115 height => {
116 type => 'integer',
117 optional => 1,
118 minimum => 1,
119 }, width => {
120 type => 'integer',
121 optional => 1,
122 minimum => 1,
123 }, title => {
124 type => 'string',
125 optional => 1,
126 }, responsive => {
127 type => 'boolean',
128 optional => 1,
129 }
130 }
131 });
132  
133 548 ▶ if(!defined($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $class) { } 2 546 548
elsif (builtin::blessed($class)) { } 4 542 546
134 2 ▶ if((scalar keys %{$params}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$params;} > 0) 1 1 2
135 1 carp(__PACKAGE__, ' use ->new() not ::new() to instantiate');
136 1 return;
137 }
138 # When called as HTML::D3::new(undef) with no args, default to the package.
139 # Passing args via ::new() is unsupported and carps above.
140 1 $class = __PACKAGE__;
141 } elsif(blessed($class)) {
142 4 return bless { %{$class}, %{$params} }, ref($class);
143 }
144  
145 543 $params = Object::Configure::configure($class, $params);
146  
147 return bless {
148 width => $params->{width} || 800,
149 height => $params->{height} || 600,
150 title => $params->{title} || 'Chart',
151 543 ▶ responsive => $params->{responsive} || 0,
Condition100%8/8
$params->{'width'} || 800
l!l
93450
$params->{'height'} || 600
l!l
93450
$params->{'title'} || 'Chart'
l!l
47496
$params->{'responsive'} || 0
l!l
15528
MC/DC100%1/1
$params->{'width'} || 800
$params->{'width'}
MC/DC100%1/1
$params->{'height'} || 600
$params->{'height'}
MC/DC100%1/1
$params->{'title'} || 'Chart'
$params->{'title'}
MC/DC100%1/1
$params->{'responsive'} || 0
$params->{'responsive'}
Truth table100%2/2
A
A= $params->{'width'}
Aresult
11
00
Truth table100%2/2
A
A= $params->{'height'}
Aresult
11
00
Truth table100%2/2
A
A= $params->{'title'}
Aresult
11
00
Truth table100%2/2
A
A= $params->{'responsive'}
Aresult
11
00
152 }, $class;
153 }
154  
155 # ─────────────────────────────────────────────────────────────────────────────
156 # The categorical colour schemes, written down once.
157 #
158 # The scheme names and the colours themselves live here and nowhere else. The
159 # snippets inline these colours as a JavaScript array - not as a d3.scheme*
160 # expression - so a page draws the exact numbers palette() hands a map, and a
161 # change to d3's own palette cannot move a chart's colours under it. Perl
162 # callers - a map, a legend, a static renderer - read the same colours through
163 # categorical_schemes(), palette() and colour_at(). A chart and a map of the
164 # same data therefore cannot disagree about what scheme 'set2' means, which two
165 # separate lists of names and colours eventually would.
166 #
167 # The colours are D3's own, in D3's order: the scheme arrays in
168 # d3-scale-chromatic 3.x, which is the version d3 v7 - what _head() loads -
169 # bundles. Each entry names the d3 scheme it transcribes, so the palette can be
170 # checked against the library (t/d3-schemes.t does that when Node and d3 are
171 # installed), but the chart does not depend on d3 for the numbers it draws.
172 31 my %CATEGORICAL_SCHEMES = (
173 tableau10 => {
174 colours => [ '#4e79a7', '#f28e2c', '#e15759', '#76b7b2', '#59a14f',
175 '#edc949', '#af7aa1', '#ff9da7', '#9c755f', '#bab0ab' ],
176 }, category10 => {
177 colours => [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
178 '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ],
179 }, set2 => {
180 colours => [ '#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3',
181 '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3' ],
182 }, set3 => {
183 colours => [ '#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3',
184 '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd',
185 '#ccebc5', '#ffed6f' ],
186 }, paired => {
187 colours => [ '#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99',
188 '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a',
189 '#ffff99', '#b15928' ],
190 },
191 );
192  
193 # The scheme a chart draws with when it is not told which one to use.
194 31 my $DEFAULT_CATEGORICAL_SCHEME = 'tableau10';
195  
196 # The palette the charts that offer no scheme option draw with: the pie family
197 # and the multi-series line charts that predate the option have always drawn
198 # category10. The colours are read from the definition above rather than
199 # written out again here, so that a chart with no choice and a chart told which
200 # scheme to use are the same palette and not two copies of it.
201 31 my $CATEGORY10_JS = _scheme_colours_js('category10');
202  
203 =head2 categorical_schemes
204  
205 my $names = HTML::D3->categorical_schemes();
206  
207 Returns an arrayref of the names of the categorical colour schemes this module
208 can draw with, sorted alphabetically: C<category10>, C<paired>, C<set2>,
209 C<set3> and C<tableau10>.
210 These are the names the C<scheme> and C<color_scheme> options accept.
211  
212 =cut
213  
214 sub categorical_schemes
215 3 ▶{
Subroutine categorical_schemes: called CC=1 SCAR=0.0
Pod documented
216 3 return [ sort keys %CATEGORICAL_SCHEMES ];
217 }
218  
219 =head2 palette
220  
221 my $colours = HTML::D3->palette('set2');
222  
223 Returns an arrayref of the colours of one scheme - the same colours, in the same
224 order, that a chart drawn with C<< scheme => 'set2' >> draws with.
225 A map, a legend or a static renderer can therefore colour the same data the way
226 the chart does, from Perl, without a browser:
227  
228 my $scheme = 'set2';
229 my $colours = HTML::D3->palette($scheme);
230 my $index = 0;
231 for my $category (@categories) {
232 printf "%s is %s\n", $category, HTML::D3->colour_at($scheme, $index++);
233 }
234  
235 Dies with C<Unknown scheme: E<lt>nameE<gt>> for a name that is not in
236 C<categorical_schemes()>, rather than quietly returning the default scheme's
237 colours, so that a misspelt scheme is found where it is asked for.
238 The arrayref returned is a copy: pushing onto it does not change the palette.
239  
240 =head2 colour_at
241  
242 my $fill = HTML::D3->colour_at('tableau10', $index);
243  
244 Returns the colour one scheme gives the C<$index>th category, counting from
245 zero, cyclically: an index past the end of the palette wraps around to its
246 start, which is how C<d3.scaleOrdinal> - what the snippets draw with - assigns
247 colours.
248 Colour 0 is the first colour of the scheme, the one C<render_histogram_snippet>
249 uses as the bar fill when it is given a C<scheme>.
250  
251 The British spelling matches the C<colour_by_series> option.
252 Dies with C<Unknown scheme: E<lt>nameE<gt>> for an unknown scheme, and with
253 C<Colour index must be a non-negative integer> for an index that is not one.
254  
255 =cut
256  
257 sub palette
258 31 ▶{
Subroutine palette: called CC=2 SCAR=7.0
Pod documented
259 31 my $self = shift;
260 31 ▶ my $params = Params::Validate::Strict::validate_strict({
Condition50%1/2
Params::Get::get_params("scheme", \@_) // {}
l!l
310
MC/DC0%0/1
Params::Get::get_params("scheme", \@_) // {}
Params::Get::get_params("scheme", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("scheme", \@_)
Aresult
11
00
261 args => Params::Get::get_params('scheme', \@_) // {},
262 schema => { scheme => { type => 'string' } },
263 });
264 31 return [ @{_categorical_scheme($params->{scheme})->{colours}} ];
265 }
266  
267 sub colour_at
268 28 ▶{
Subroutine colour_at: called CC=5 SCAR=16.8
Pod documented
269 28 my $self = shift;
270 28 my ($scheme, $index);
271 28 ▶ if (@_ == 1 && ref($_[0]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 0 28 28
Condition66%2/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
2710
MC/DC0%0/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
272 0 my $h = $_[0];
273 0 $scheme = $h->{scheme};
274 0 $index = $h->{index};
275 } else {
276 28 ($scheme, $index) = @_;
277 }
278 28 ▶ die 'Colour index must be a non-negative integer'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $index and $index =~ /\A[0-9]+\z/ 4 24 28
Condition100%3/3
defined $index and $index =~ /\A[0-9]+\z/
!ll&&!rl&&r
1324
MC/DC100%2/2
defined $index and $index =~ /\A[0-9]+\z/
defined $index $index =~ /\A[0-9]+\z/
Truth table100%3/3
A and B
A= defined $indexB= $index =~ /\A[0-9]+\z/
ABresult
0X0
100
111
279 unless defined($index) && $index =~ /\A[0-9]+\z/;
280 24 my $colours = _categorical_scheme($scheme)->{colours};
281 22 return $colours->[$index % scalar(@$colours)];
282 }
283  
284 =head2 render_bar_chart
285  
286 my $html = $chart->render_bar_chart($data);
287  
288 Generates HTML and JavaScript code to render a bar chart. Accepts the following arguments:
289  
290 =over 4
291  
292 =item * C<$data> - An array reference containing data points. Each data point should
293 be an array reference with two elements: the label (string) and the value (numeric).
294  
295 =back
296  
297 Returns a string containing the HTML and JavaScript code for the chart.
298  
299 =head3 Errors
300  
301 =over 4
302  
303 =item * Throws C<Data is not optional> when C<$data> is C<undef>.
304  
305 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
306  
307 =back
308  
309 =head3 API SPECIFICATION
310  
311 =head4 Input
312  
313 {
314 data => {
315 type => 'arrayref',
316 element_type => [ 'string', 'number' ]
317 }
318 }
319  
320 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
321 non-arrayref dies.
322  
323 =head4 Output
324  
325 Str -- complete HTML5 document starting with C<< <!DOCTYPE html> >>;
326 D3.js loaded from CDN; bar chart rendered with C<d3.scaleBand>.
327  
328 =cut
329  
330 # Method to render a bar chart with given data
331 14 ▶sub render_bar_chart {
Subroutine render_bar_chart: called CC=5 SCAR=16.1
Pod documented
332 14 my $self = shift;
333 14 ▶ my $first = @_ ? $_[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 14 0 14
334 14 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
140
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
335 14 ▶ if (!defined($raw->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw->{"data"}) 4 10 14
336 4 ▶ die(defined($first) ? 'Data must be an array of arrays' : 'Data is not optional');
Branch: 1 branch
BranchTrueFalseTotal
defined $first ? : 2 2 4
337 }
338 Params::Validate::Strict::validate_strict({
339 10 args => $raw,
340 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
341 unknown_parameter_handler => 'ignore',
342 });
343 8 my $data = $raw->{data};
344  
345 # Generate JSON representation of data
346 my $json_data = _script_json([
347 8 map { { label => $_->[0], value => $_->[1] } } @$data
348 ]);
349  
350 # Generate HTML and D3.js JavaScript for rendering the bar chart
351 8 my $html = $self->_preamble();
352 8 $html .= $self->_head();
353 8 $html .= <<"HTML";
354 <body>
355 8 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
356 8 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
357 <script>
358 const data = $json_data;
359  
360 const svg = d3.select("#chart");
361 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
362 const width = $self->{width} - margin.left - margin.right;
363 const height = $self->{height} - margin.top - margin.bottom;
364  
365 // Set up scales for x and y axes
366 const x = d3.scaleBand()
367 .domain(data.map(d => d.label))
368 .range([0, width])
369 .padding(0.1);
370  
371 const y = d3.scaleLinear()
372 .domain([0, d3.max(data, d => d.value)])
373 .nice()
374 .range([height, 0]);
375  
376 const chart = svg.append("g")
377 .attr("transform", `translate(\${margin.left},\${margin.top})`);
378  
379 // Add bars to the chart
380 chart.append("g")
381 .selectAll("rect")
382 .data(data)
383 .join("rect")
384 .attr("x", d => x(d.label))
385 .attr("y", d => y(d.value))
386 .attr("height", d => height - y(d.value))
387 .attr("width", x.bandwidth())
388 .attr("fill", "steelblue");
389  
390 // Add the y-axis
391 chart.append("g")
392 .call(d3.axisLeft(y));
393  
394 // Add the x-axis with labels rotated for better readability
395 chart.append("g")
396 .attr("transform", `translate(0,\${height})`)
397 .call(d3.axisBottom(x))
398 .selectAll("text")
399 .attr("transform", "rotate(-45)")
400 .style("text-anchor", "end");
401 </script>
402 </body>
403 </html>
404 HTML
405  
406 8 return $html;
407 }
408  
409 =head2 render_animated_bar_chart
410  
411 my $html = $chart->render_animated_bar_chart($data);
412  
413 Generates HTML and JavaScript code to render a bar chart where each bar grows
414 upward from the baseline on page load. Bars are staggered so they rise
415 one-after-another from left to right.
416 Accepts the following arguments:
417  
418 =over 4
419  
420 =item * C<$data> - An array reference of data points. Each data point is an
421 array reference with two elements: the label (string) and the value (numeric).
422  
423 =back
424  
425 Returns a string containing the complete HTML5 document.
426  
427 =head3 Errors
428  
429 =over 4
430  
431 =item * Throws C<Data is not optional> when C<$data> is C<undef>.
432  
433 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
434  
435 =back
436  
437 =head3 API SPECIFICATION
438  
439 =head4 Input
440  
441 {
442 data => { type => 'arrayref' },
443 }
444  
445 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
446 non-arrayref dies.
447  
448 =head4 Output
449  
450 Str -- complete HTML5 document; each bar animates from height=0 upward
451 using C<d3.transition()> with a staggered per-bar delay.
452  
453 =cut
454  
455 11 ▶sub render_animated_bar_chart {
Subroutine render_animated_bar_chart: called CC=5 SCAR=16.1
Pod documented
456 11 my $self = shift;
457 11 ▶ my $first = @_ ? $_[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 11 0 11
458 11 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
110
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
459 11 ▶ if (!defined($raw->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw->{"data"}) 4 7 11
460 4 ▶ die(defined($first) ? 'Data must be an array of arrays' : 'Data is not optional');
Branch: 1 branch
BranchTrueFalseTotal
defined $first ? : 2 2 4
461 }
462 Params::Validate::Strict::validate_strict({
463 7 args => $raw,
464 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
465 unknown_parameter_handler => 'ignore',
466 });
467 5 my $data = $raw->{data};
468  
469 my $json_data = _script_json([
470 5 map { { label => $_->[0], value => $_->[1] } } @$data
471 ]);
472  
473 5 my $html = $self->_preamble();
474 5 $html .= $self->_head();
475 5 $html .= <<"HTML";
476 <body>
477 5 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
478 5 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
479 <script>
480 const data = $json_data;
481  
482 const svg = d3.select("#chart");
483 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
484 const width = $self->{width} - margin.left - margin.right;
485 const height = $self->{height} - margin.top - margin.bottom;
486  
487 const x = d3.scaleBand()
488 .domain(data.map(d => d.label))
489 .range([0, width])
490 .padding(0.1);
491  
492 const y = d3.scaleLinear()
493 .domain([0, d3.max(data, d => d.value)])
494 .nice()
495 .range([height, 0]);
496  
497 const chart = svg.append("g")
498 .attr("transform", `translate(\${margin.left},\${margin.top})`);
499  
500 // Each bar starts at the baseline (y=height, height=0) and grows upward.
501 chart.append("g")
502 .selectAll("rect")
503 .data(data)
504 .join("rect")
505 .attr("x", d => x(d.label))
506 .attr("y", height)
507 .attr("height", 0)
508 .attr("width", x.bandwidth())
509 .attr("fill", "steelblue")
510 .transition()
511 .duration(800)
512 .delay((d, i) => i * 100)
513 .attr("y", d => y(d.value))
514 .attr("height", d => height - y(d.value));
515  
516 chart.append("g")
517 .call(d3.axisLeft(y));
518  
519 chart.append("g")
520 .attr("transform", `translate(0,\${height})`)
521 .call(d3.axisBottom(x))
522 .selectAll("text")
523 .attr("transform", "rotate(-45)")
524 .style("text-anchor", "end");
525 </script>
526 </body>
527 </html>
528 HTML
529  
530 5 return $html;
531 }
532  
533 =head2 render_line_chart
534  
535 my $html = $chart->render_line_chart($data);
536  
537 Generates HTML and JavaScript code to render a line chart. Accepts the following arguments:
538  
539 =over 4
540  
541 =item * C<$data> - An array reference containing data points. Each data point should
542 be an array reference with two elements: the label (string) and the value (numeric).
543  
544 =back
545  
546 Returns a string containing the HTML and JavaScript code for the chart.
547  
548 =head3 Errors
549  
550 =over 4
551  
552 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
553  
554 =back
555  
556 =head3 API SPECIFICATION
557  
558 =head4 Input
559  
560 {
561 data => { type => 'arrayref' },
562 }
563  
564 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
565 non-arrayref dies.
566  
567 =head4 Output
568  
569 Str -- complete HTML5 document; line chart with C<d3.scalePoint> and C<d3.line()>.
570  
571 =cut
572  
573 7 ▶sub render_line_chart {
Subroutine render_line_chart: called CC=3 SCAR=11.0
Pod documented
574 7 my $self = shift;
575 7 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
70
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
576 7 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 5 7
577 5 Params::Validate::Strict::validate_strict({
578 args => $raw,
579 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
580 unknown_parameter_handler => 'ignore',
581 });
582 5 my $data = $raw->{data};
583  
584 # Generate JSON for data
585 my $json_data = _script_json([
586 5 map { { label => $_->[0], value => $_->[1] } } @$data
587 ]);
588  
589 # Generate HTML and D3.js code
590 5 my $html = $self->_preamble();
591 5 $html .= $self->_head();
592 5 $html .= <<"HTML";
593 <body>
594 5 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
595 5 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
596 <script>
597 const data = $json_data;
598  
599 const svg = d3.select("#chart");
600 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
601 const width = $self->{width} - margin.left - margin.right;
602 const height = $self->{height} - margin.top - margin.bottom;
603  
604 const x = d3.scalePoint()
605 .domain(data.map(d => d.label))
606 .range([0, width]);
607  
608 const y = d3.scaleLinear()
609 .domain([0, d3.max(data, d => d.value)])
610 .nice()
611 .range([height, 0]);
612  
613 const chart = svg.append("g")
614 .attr("transform", `translate(\${margin.left},\${margin.top})`);
615  
616 // Draw line
617 const line = d3.line()
618 .x(d => x(d.label))
619 .y(d => y(d.value));
620  
621 chart.append("path")
622 .datum(data)
623 .attr("fill", "none")
624 .attr("stroke", "steelblue")
625 .attr("stroke-width", 2)
626 .attr("d", line);
627  
628 // Add points to the line
629 chart.selectAll("circle")
630 .data(data)
631 .join("circle")
632 .attr("cx", d => x(d.label))
633 .attr("cy", d => y(d.value))
634 .attr("r", 4)
635 .attr("fill", "steelblue");
636  
637 // Add axes
638 chart.append("g")
639 .call(d3.axisLeft(y));
640  
641 chart.append("g")
642 .attr("transform", `translate(0,\${height})`)
643 .call(d3.axisBottom(x))
644 .selectAll("text")
645 .attr("transform", "rotate(-45)")
646 .style("text-anchor", "end");
647 </script>
648 </body>
649 </html>
650 HTML
651  
652 5 return $html;
653 }
654  
655 =head2 render_animated_line_chart
656  
657 my $html = $chart->render_animated_line_chart($data);
658  
659 Generates HTML and JavaScript code to render a line chart where the line
660 draws itself from left to right on page load, followed by each data-point
661 circle fading in once the line is complete.
662 Accepts the following arguments:
663  
664 =over 4
665  
666 =item * C<$data> - An array reference of data points. Each data point is an
667 array reference with two elements: the label (string) and the value (numeric).
668  
669 =back
670  
671 Returns a string containing the complete HTML5 document.
672  
673 =head3 Errors
674  
675 =over 4
676  
677 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
678  
679 =back
680  
681 =head3 API SPECIFICATION
682  
683 =head4 Input
684  
685 {
686 data => { type => 'arrayref' },
687 }
688  
689 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
690 non-arrayref dies.
691  
692 =head4 Output
693  
694 Str -- complete HTML5 document; the line path animates via
695 C<stroke-dashoffset> with C<d3.easeLinear>; data-point circles
696 fade in with C<opacity> after the line transition completes.
697  
698 =cut
699  
700 8 ▶sub render_animated_line_chart {
Subroutine render_animated_line_chart: called CC=3 SCAR=11.0
Pod documented
701 8 my $self = shift;
702 8 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
80
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
703 8 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 5 8
704 5 Params::Validate::Strict::validate_strict({
705 args => $raw,
706 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
707 unknown_parameter_handler => 'ignore',
708 });
709 5 my $data = $raw->{data};
710  
711 my $json_data = _script_json([
712 5 map { { label => $_->[0], value => $_->[1] } } @$data
713 ]);
714  
715 5 my $html = $self->_preamble();
716 5 $html .= $self->_head();
717 5 $html .= <<"HTML";
718 <body>
719 5 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
720 5 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
721 <script>
722 const data = $json_data;
723  
724 const svg = d3.select("#chart");
725 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
726 const width = $self->{width} - margin.left - margin.right;
727 const height = $self->{height} - margin.top - margin.bottom;
728  
729 const x = d3.scalePoint()
730 .domain(data.map(d => d.label))
731 .range([0, width]);
732  
733 const y = d3.scaleLinear()
734 .domain([0, d3.max(data, d => d.value)])
735 .nice()
736 .range([height, 0]);
737  
738 const chart = svg.append("g")
739 .attr("transform", `translate(\${margin.left},\${margin.top})`);
740  
741 const line = d3.line()
742 .x(d => x(d.label))
743 .y(d => y(d.value));
744  
745 // Animate the line drawing left-to-right using stroke-dashoffset.
746 const path = chart.append("path")
747 .datum(data)
748 .attr("fill", "none")
749 .attr("stroke", "steelblue")
750 .attr("stroke-width", 2)
751 .attr("d", line);
752  
753 const totalLength = path.node().getTotalLength();
754  
755 path
756 .attr("stroke-dasharray", totalLength)
757 .attr("stroke-dashoffset", totalLength)
758 .transition()
759 .duration(1500)
760 .ease(d3.easeLinear)
761 .attr("stroke-dashoffset", 0);
762  
763 // Data-point circles fade in after the line finishes.
764 chart.selectAll("circle")
765 .data(data)
766 .join("circle")
767 .attr("cx", d => x(d.label))
768 .attr("cy", d => y(d.value))
769 .attr("r", 4)
770 .attr("fill", "steelblue")
771 .attr("opacity", 0)
772 .transition()
773 .delay(1500)
774 .duration(300)
775 .attr("opacity", 1);
776  
777 chart.append("g")
778 .call(d3.axisLeft(y));
779  
780 chart.append("g")
781 .attr("transform", `translate(0,\${height})`)
782 .call(d3.axisBottom(x))
783 .selectAll("text")
784 .attr("transform", "rotate(-45)")
785 .style("text-anchor", "end");
786 </script>
787 </body>
788 </html>
789 HTML
790  
791 5 return $html;
792 }
793  
794 =head2 render_pie_chart
795  
796 my $html = $chart->render_pie_chart($data);
797 my $html = $chart->render_pie_chart($data, { separator => ':' });
798  
799 Generates HTML and JavaScript code to render a pie chart.
800 Each slice is coloured with the ten hex values of C<d3.schemeCategory10>,
801 inlined into the page rather than read from D3's own palette (see L</palette>);
802 percentage labels appear inside each slice and a colour legend is shown to the
803 right of the pie.
804 Accepts the following arguments:
805  
806 =over 4
807  
808 =item * C<$data> - An array reference of data points. Each data point is an
809 array reference with two elements: the label (string) and the value (numeric).
810  
811 =item * C<%opts> - Optional hashref of options.
812  
813 =over 8
814  
815 =item * C<separator> (string, default C<'/'>) - Character shown between the
816 label and value in the SVG legend.
817  
818 =back
819  
820 =back
821  
822 Returns a string containing the complete HTML5 document.
823  
824 =head3 Errors
825  
826 =over 4
827  
828 =item * Throws C<Data is not optional> when C<$data> is C<undef>.
829  
830 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
831  
832 =back
833  
834 =head3 API SPECIFICATION
835  
836 =head4 Input
837  
838 {
839 data => {
840 type => 'arrayref',
841 element_type => [ 'string', 'number' ]
842 },
843 opts => { type => 'hashref', optional => 1, default => {} },
844 }
845  
846 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
847 non-arrayref dies.
848 Recognised C<opts> key: C<separator> (string, default C<'/'>)
849 - character shown between label and value in the SVG legend.
850  
851 =head4 Output
852  
853 Str -- complete HTML5 document; pie rendered with C<d3.pie()> and
854 C<d3.arc()>; slices coloured with category10's hex values,
855 inlined; percentage label inside each slice; legend to the right.
856  
857 =cut
858  
859 18 ▶sub render_pie_chart {
Subroutine render_pie_chart: called CC=6 SCAR=17.9
Pod documented
860 18 my $self = shift;
861 18 ▶ my $first = @_ ? $_[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 18 0 18
862 18 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
180
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
863 18 ▶ if (!defined($raw->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw->{"data"}) 4 14 18
864 4 ▶ die(defined($first) ? 'Data must be an array of arrays' : 'Data is not optional');
Branch: 1 branch
BranchTrueFalseTotal
defined $first ? : 2 2 4
865 }
866 Params::Validate::Strict::validate_strict({
867 14 args => $raw,
868 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
869 unknown_parameter_handler => 'ignore',
870 });
871 12 my $data = $raw->{data};
872 12 my $opts = {%$raw}; delete $opts->{data};
873  
874 12 ▶ my $separator = _js_any_string($opts->{separator} // '/');
Condition100%2/2
$opts->{"separator"} // "/"
l!l
66
MC/DC100%1/1
$opts->{"separator"} // "/"
$opts->{"separator"}
Truth table100%2/2
A
A= $opts->{"separator"}
Aresult
11
00
875  
876 my $json_data = _script_json([
877 12 map { { label => $_->[0], value => $_->[1] } } @$data
878 ]);
879  
880 12 my $html = $self->_preamble();
881 12 $html .= $self->_head();
882 12 $html .= <<"HTML";
883 <body>
884 12 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
885 12 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
886 <script>
887 const data = $json_data;
888  
889 const width = $self->{width};
890 const height = $self->{height};
891 const radius = Math.min(width, height) / 2 - 40;
892  
893 const color = d3.scaleOrdinal($CATEGORY10_JS);
894  
895 const pie = d3.pie()
896 .sort(null)
897 .value(d => d.value);
898  
899 const arc = d3.arc()
900 .innerRadius(0)
901 .outerRadius(radius);
902  
903 const labelArc = d3.arc()
904 .innerRadius(radius * 0.65)
905 .outerRadius(radius * 0.65);
906  
907 const total = d3.sum(data, d => d.value);
908  
909 const svg = d3.select("#chart");
910  
911 const pieGroup = svg.append("g")
912 .attr("transform", `translate(\${width * 0.45},\${height / 2})`);
913  
914 const arcs = pieGroup.selectAll(".arc")
915 .data(pie(data))
916 .join("g")
917 .attr("class", "arc");
918  
919 arcs.append("path")
920 .attr("d", arc)
921 .attr("fill", d => color(d.data.label))
922 .attr("stroke", "white")
923 .style("stroke-width", "2px");
924  
925 arcs.append("text")
926 .attr("transform", d => `translate(\${labelArc.centroid(d)})`)
927 .attr("text-anchor", "middle")
928 .attr("font-size", "11px")
929 .attr("fill", "white")
930 .attr("pointer-events", "none")
931 .text(d => Math.round(d.data.value / total * 100) + "%");
932  
933 // Legend
934 const legend = svg.append("g")
935 .attr("transform", `translate(\${width * 0.72},\${(height - data.length * 22) / 2})`);
936  
937 legend.selectAll("rect")
938 .data(pie(data))
939 .join("rect")
940 .attr("x", 0)
941 .attr("y", (d, i) => i * 22)
942 .attr("width", 14)
943 .attr("height", 14)
944 .attr("fill", d => color(d.data.label));
945  
946 legend.selectAll("text")
947 .data(pie(data))
948 .join("text")
949 .attr("x", 20)
950 .attr("y", (d, i) => i * 22 + 11)
951 .attr("font-size", "12px")
952 .text(d => `\${d.data.label} $separator \${d.data.value}`);
953 </script>
954 </body>
955 </html>
956 HTML
957  
958 12 return $html;
959 }
960  
961 =head2 render_animated_pie_chart
962  
963 my $html = $chart->render_animated_pie_chart($data);
964 my $html = $chart->render_animated_pie_chart($data, { separator => ':' });
965  
966 Generates HTML and JavaScript code to render an animated pie chart where each
967 slice fans out from zero angle on page load using C<attrTween> and
968 C<d3.interpolate>. Percentage labels fade in once all slices are drawn.
969 Accepts the following arguments:
970  
971 =over 4
972  
973 =item * C<$data> - An array reference of data points. Each data point is an
974 array reference with two elements: the label (string) and the value (numeric).
975  
976 =item * C<%opts> - Optional hashref of options.
977  
978 =over 8
979  
980 =item * C<separator> (string, default C<'/'>) - Character shown between the
981 label and value in the SVG legend.
982  
983 =back
984  
985 =back
986  
987 Returns a string containing the complete HTML5 document.
988  
989 =head3 Errors
990  
991 =over 4
992  
993 =item * Throws C<Data is not optional> when C<$data> is C<undef>.
994  
995 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
996  
997 =back
998  
999 =head3 API SPECIFICATION
1000  
1001 =head4 Input
1002  
1003 {
1004 data => {
1005 type => 'arrayref',
1006 element_type => [ 'string', 'number' ]
1007 },
1008 opts => { type => 'hashref', optional => 1, default => {} },
1009 }
1010  
1011 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
1012 non-arrayref dies.
1013 Recognised C<opts> key: C<separator> (string, default C<'/'>)
1014 - character shown between label and value in the SVG legend.
1015  
1016 =head4 Output
1017  
1018 Str -- complete HTML5 document; slices animate via C<attrTween> with
1019 C<d3.interpolate> (1000 ms); percentage labels fade in afterwards.
1020  
1021 =cut
1022  
1023 15 ▶sub render_animated_pie_chart {
Subroutine render_animated_pie_chart: called CC=6 SCAR=18.0
Pod documented
1024 15 my $self = shift;
1025 15 ▶ my $first = @_ ? $_[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 15 0 15
1026 15 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
150
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
1027 15 ▶ if (!defined($raw->{data})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $raw->{"data"}) 2 13 15
1028 2 ▶ die(defined($first) ? 'Data must be an array of arrays' : 'Data is not optional');
Branch: 1 branch
BranchTrueFalseTotal
defined $first ? : 0 2 2
1029 }
1030 Params::Validate::Strict::validate_strict({
1031 13 args => $raw,
1032 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
1033 unknown_parameter_handler => 'ignore',
1034 });
1035 11 my $data = $raw->{data};
1036 11 my $opts = {%$raw}; delete $opts->{data};
1037  
1038 11 ▶ my $separator = _js_any_string($opts->{separator} // '/');
Condition100%2/2
$opts->{"separator"} // "/"
l!l
56
MC/DC100%1/1
$opts->{"separator"} // "/"
$opts->{"separator"}
Truth table100%2/2
A
A= $opts->{"separator"}
Aresult
11
00
1039  
1040 my $json_data = _script_json([
1041 11 map { { label => $_->[0], value => $_->[1] } } @$data
1042 ]);
1043  
1044 11 my $html = $self->_preamble();
1045 11 $html .= $self->_head();
1046 11 $html .= <<"HTML";
1047 <body>
1048 11 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
1049 11 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
1050 <script>
1051 const data = $json_data;
1052  
1053 const width = $self->{width};
1054 const height = $self->{height};
1055 const radius = Math.min(width, height) / 2 - 40;
1056  
1057 const color = d3.scaleOrdinal($CATEGORY10_JS);
1058  
1059 const pie = d3.pie()
1060 .sort(null)
1061 .value(d => d.value);
1062  
1063 const arc = d3.arc()
1064 .innerRadius(0)
1065 .outerRadius(radius);
1066  
1067 const labelArc = d3.arc()
1068 .innerRadius(radius * 0.65)
1069 .outerRadius(radius * 0.65);
1070  
1071 const total = d3.sum(data, d => d.value);
1072  
1073 const svg = d3.select("#chart");
1074  
1075 const pieGroup = svg.append("g")
1076 .attr("transform", `translate(\${width * 0.45},\${height / 2})`);
1077  
1078 const arcs = pieGroup.selectAll(".arc")
1079 .data(pie(data))
1080 .join("g")
1081 .attr("class", "arc");
1082  
1083 // Each slice fans out from zero angle using attrTween.
1084 arcs.append("path")
1085 .attr("fill", d => color(d.data.label))
1086 .attr("stroke", "white")
1087 .style("stroke-width", "2px")
1088 .transition()
1089 .duration(1000)
1090 .attrTween("d", function(d) {
1091 const i = d3.interpolate({ startAngle: 0, endAngle: 0 }, d);
1092 return t => arc(i(t));
1093 });
1094  
1095 // Percentage labels fade in after slices finish drawing.
1096 arcs.append("text")
1097 .attr("transform", d => `translate(\${labelArc.centroid(d)})`)
1098 .attr("text-anchor", "middle")
1099 .attr("font-size", "11px")
1100 .attr("fill", "white")
1101 .attr("pointer-events", "none")
1102 .attr("opacity", 0)
1103 .text(d => Math.round(d.data.value / total * 100) + "%")
1104 .transition()
1105 .delay(1000)
1106 .duration(300)
1107 .attr("opacity", 1);
1108  
1109 // Legend
1110 const legend = svg.append("g")
1111 .attr("transform", `translate(\${width * 0.72},\${(height - data.length * 22) / 2})`);
1112  
1113 legend.selectAll("rect")
1114 .data(pie(data))
1115 .join("rect")
1116 .attr("x", 0)
1117 .attr("y", (d, i) => i * 22)
1118 .attr("width", 14)
1119 .attr("height", 14)
1120 .attr("fill", d => color(d.data.label));
1121  
1122 legend.selectAll("text")
1123 .data(pie(data))
1124 .join("text")
1125 .attr("x", 20)
1126 .attr("y", (d, i) => i * 22 + 11)
1127 .attr("font-size", "12px")
1128 .text(d => `\${d.data.label} $separator \${d.data.value}`);
1129 </script>
1130 </body>
1131 </html>
1132 HTML
1133  
1134 11 return $html;
1135 }
1136  
1137 =head2 render_pie_chart_snippet
1138  
1139 my $fragment = $chart->render_pie_chart_snippet(\@slices);
1140 my $fragment = $chart->render_pie_chart_snippet(\@slices, \%opts);
1141 # $fragment->{svg_id} - always 'pie_chart'
1142 # $fragment->{html} - embeddable fragment; caller must load D3 v7
1143  
1144 Generates an embeddable pie or donut chart fragment for use in existing HTML
1145 layouts. Returns C<{ svg_id =E<gt> 'pie_chart', html =E<gt> Str }>. The
1146 caller is responsible for loading D3 v7 before embedding the fragment.
1147  
1148 =head3 Data format
1149  
1150 Each element of C<\@slices> is C<[$label, $value]> or C<[$label, $value, \%extra]>.
1151 Negative values are silently converted to their absolute value. Zero-value
1152 slices are silently omitted. C<\%extra> key/value pairs are shown as
1153 additional rows in the hover tooltip.
1154  
1155 =head3 Options (C<\%opts>)
1156  
1157 =over 4
1158  
1159 =item * C<animated> (bool, default 0) - fan slices in from arc-length 0 on
1160 first render using C<attrTween> / C<d3.easeBackOut> (800 ms, staggered).
1161 Respects C<prefers-reduced-motion>.
1162  
1163 =item * C<donut> (bool, default 0) - render as a donut chart (inner radius
1164 38% of outer radius); the total sum appears in the centre hole.
1165  
1166 =item * C<sort_slices> (string, default C<'none'>) - C<'value'> for
1167 largest-first, C<'label'> for alphabetical, C<'none'> for input order.
1168  
1169 =item * C<max_slices> (int, default 0) - when E<gt> 0, only the top N-1
1170 slices are shown individually; the rest are collapsed into an C<"Other"> slice.
1171  
1172 =item * C<legend> (bool, default 1) - render an HTML legend panel beside the chart.
1173  
1174 =item * C<color_scheme> (string, default C<'tableau10'>) - D3 categorical
1175 colour scheme. Supported: C<tableau10>, C<category10>, C<set2>, C<set3>,
1176 C<paired> - the names C<categorical_schemes()> returns, whose colours C<palette()>
1177 makes available to Perl.
1178  
1179 =item * C<separator> (string, default C<'/'>) - Character shown between the
1180 label and value in each legend entry (e.g. C<'/'> produces
1181 C<Label / 12.34 (42.0%)>, C<':'> produces C<Label : 12.34 (42.0%)>).
1182  
1183 =back
1184  
1185 =head3 Errors
1186  
1187 =over 4
1188  
1189 =item * Throws C<Data must be an array of arrays> when C<\@slices> is not an ARRAY reference.
1190  
1191 =back
1192  
1193 =head3 API SPECIFICATION
1194  
1195 =head4 Input
1196  
1197 {
1198 data => { type => 'arrayref' },
1199 opts => { type => 'hashref', optional => 1, default => {} },
1200 }
1201  
1202 Each element of C<$data> is C<[ Str, Num ]> or C<[ Str, Num, HashRef ]>;
1203 passing C<undef> or a non-arrayref dies.
1204 Recognised C<opts> keys: C<animated> (boolean, default C<0>),
1205 C<donut> (boolean, default C<0>), C<sort_slices> (string: C<'value'>,
1206 C<'label'>, or C<'none'>; default C<'none'>), C<max_slices> (integer,
1207 default C<0>), C<legend> (boolean, default C<1>),
1208 C<color_scheme> (string, default C<'tableau10'>),
1209 C<separator> (string, default C<'/'> - shown between label and value in
1210 legend entries).
1211  
1212 =head4 Output
1213  
1214 HashRef -- C<{ svg_id =E<gt> 'pie_chart', html =E<gt> Str }>;
1215 embeddable fragment; no DOCTYPE, no page shell, no D3 CDN tag.
1216  
1217 =cut
1218  
1219 65 ▶sub render_pie_chart_snippet {
Subroutine render_pie_chart_snippet: called CC=30 SCAR=34.1
Pod documented
1220 65 my $self = shift;
1221 65 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
650
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
1222 65 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 62 65
1223 62 Params::Validate::Strict::validate_strict({
1224 args => $raw,
1225 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
1226 unknown_parameter_handler => 'ignore',
1227 });
1228 62 my $data = $raw->{data};
1229 62 my $opts = {%$raw}; delete $opts->{data};
1230  
1231 62 ▶ my $animated = $opts->{animated} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'animated'} ? : 4 58 62
1232 62 ▶ my $donut = $opts->{donut} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'donut'} ? : 4 58 62
1233 62 ▶ my $sort_slices = $opts->{sort_slices} // 'none';
Condition100%2/2
$opts->{"sort_slices"} // "none"
l!l
161
MC/DC100%1/1
$opts->{"sort_slices"} // "none"
$opts->{"sort_slices"}
Truth table100%2/2
A
A= $opts->{"sort_slices"}
Aresult
11
00
1234 62 ▶ my $max_slices = int($opts->{max_slices} // 0);
Condition100%2/2
$opts->{"max_slices"} // 0
l!l
260
MC/DC100%1/1
$opts->{"max_slices"} // 0
$opts->{"max_slices"}
Truth table100%2/2
A
A= $opts->{"max_slices"}
Aresult
11
00
1235 62 ▶ my $show_legend = exists $opts->{legend} ? ($opts->{legend} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'legend'} ? : 2 60 62
$opts->{'legend'} ? : 1 1 2
1236 62 my $color_scheme = _scheme_name($opts->{color_scheme});
1237 62 ▶ my $separator = _js_any_string($opts->{separator} // '/');
Condition100%2/2
$opts->{"separator"} // "/"
l!l
458
MC/DC100%1/1
$opts->{"separator"} // "/"
$opts->{"separator"}
Truth table100%2/2
A
A= $opts->{"separator"}
Aresult
11
00
1238 62 my $schemes_js = $self->_schemes_js('const');
1239 62 my $default_js = _default_scheme_js();
1240  
1241 # Normalise: absolute values, drop zeros, pull optional extra hashref
1242 62 my @slices;
1243 62 for my $pt (@$data) {
1244 167 ▶ my $val = abs($pt->[1] // 0);
Condition50%1/2
$pt->[1] // 0
l!l
1670
MC/DC0%0/1
$pt->[1] // 0
$pt->[1]
Truth table50%1/2
A
A= $pt->[1]
Aresult
11
00
1245 167 ▶ next if $val == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $val == 0 3 164 167
1246 164 my %s = (label => $pt->[0], value => $val);
1247 164 ▶ $s{extra} = $pt->[2] if ref($pt->[2]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $pt->[2] eq "HASH" 1 163 164
1248 164 push @slices, \%s;
1249 }
1250  
1251 # Sort before max_slices so the "top N" is stable
1252 62 ▶ if ($sort_slices eq 'value') {
Branch: 2 branches
BranchTrueFalseTotal
if ($sort_slices eq 'value') { } 1 61 62
elsif ($sort_slices eq 'label') { } 0 61 61
1253 1 @slices = sort { $b->{value} <=> $a->{value} } @slices;
1254 } elsif ($sort_slices eq 'label') {
1255 0 @slices = sort { $a->{label} cmp $b->{label} } @slices;
1256 }
1257  
1258 # Collapse tail into "Other"
1259 62 ▶ if ($max_slices >= 2 && scalar(@slices) > $max_slices) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_slices >= 2 and scalar @slices > $max_slices) 2 60 62
Condition66%2/3
$max_slices >= 2 and scalar @slices > $max_slices
!ll&&!rl&&r
6002
MC/DC50%1/2
$max_slices >= 2 and scalar @slices > $max_slices
$max_slices >= 2 scalar @slices > $max_slices
Truth table66%2/3
A and B
A= $max_slices >= 2B= scalar @slices > $max_slices
ABresult
0X0
100
111
1260 2 my @by_val = sort { $b->{value} <=> $a->{value} } @slices;
1261 2 my @top = @by_val[0 .. $max_slices - 2];
1262 2 my $other = 0;
1263 2 $other += $_->{value} for @by_val[$max_slices - 1 .. $#by_val];
1264 2 push @top, { label => 'Other', value => $other };
1265 2 @slices = @top;
1266 }
1267  
1268 62 my $json_data = _script_json(\@slices);
1269  
1270 62 ▶ my $svg_id = _chart_id($opts->{id}) // 'pie_chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "pie_chart"
l!l
656
MC/DC100%1/1
_chart_id($opts->{"id"}) // "pie_chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
1271 62 my $tip_id = $svg_id . '_tip';
1272 62 my $leg_id = $svg_id . '_legend';
1273 62 my $wrap_id = $svg_id . '_wrap';
1274 62 my $width = $self->{width};
1275 62 my $height = $self->{height};
1276 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
1277 62 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 2 60 62
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
1610
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
1278 : qq{width="$width" height="$height"};
1279  
1280 62 ▶ my $inner_radius_js = $donut ? 'radius * 0.38' : '0';
Branch: 1 branch
BranchTrueFalseTotal
$donut ? : 4 58 62
1281  
1282 # Animation initialisation (empty when not animated)
1283 62 ▶ my $anim_init_js = $animated
Branch: 1 branch
BranchTrueFalseTotal
$animated ? : 4 58 62
1284 ? 'var noAnim = window.matchMedia("(prefers-reduced-motion: reduce)").matches;' . "\n" .
1285 " let initialDrawDone = false;\n"
1286 : '';
1287  
1288 # Legend fade-in as part of the animation block
1289 62 ▶ my $legend_anim_js = ($animated && $show_legend) ? <<"LANIM" : '';
Branch: 1 branch
BranchTrueFalseTotal
$animated && $show_legend ? : 4 58 62
Condition66%2/3
$animated and $show_legend
!ll&&!rl&&r
5804
MC/DC50%1/2
$animated and $show_legend
$animated $show_legend
Truth table66%2/3
A and B
A= $animatedB= $show_legend
ABresult
0X0
100
111
1290 d3.select("#$leg_id")
1291 .style("opacity", 0)
1292 .transition()
1293 .delay(data.length * 60 + 100)
1294 .duration(300)
1295 .style("opacity", 1);
1296 LANIM
1297  
1298 # Path drawing code — animated vs plain
1299 62 my $anim_draw_js;
1300 62 ▶ if ($animated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($animated) { } 4 58 62
1301 4 $anim_draw_js = <<"ANIM_DRAW";
1302 if (!initialDrawDone && !noAnim) {
1303 paths.attr("d", arc({ startAngle: 0, endAngle: 0 }))
1304 .transition()
1305 .duration(800)
1306 .ease(d3.easeBackOut.overshoot(1.2))
1307 .delay((d, i) => Math.min(i * 60, 300))
1308 .attrTween("d", function(d) {
1309 var interp = d3.interpolate({ startAngle: 0, endAngle: 0 }, d);
1310 return function(t) { return arc(interp(t)); };
1311 });
1312 $legend_anim_js initialDrawDone = true;
1313 } else {
1314 paths.attr("d", arc);
1315 }
1316 ANIM_DRAW
1317 } else {
1318 58 $anim_draw_js = " paths.attr(\"d\", arc);\n";
1319 }
1320  
1321 # Centre label in donut hole
1322 62 ▶ my $donut_center_js = $donut ? <<'DONUT' : '';
Branch: 1 branch
BranchTrueFalseTotal
$donut ? : 4 58 62
1323 pieGroup.append("text")
1324 .attr("text-anchor", "middle")
1325 .attr("dominant-baseline", "middle")
1326 .attr("font-size", "16px")
1327 .attr("font-weight", "bold")
1328 .text(fmt(total));
1329 DONUT
1330  
1331 # HTML legend panel — built by D3 against the legend div
1332 # Single-quote heredoc so JS template-literal ${...} is preserved verbatim
1333 62 ▶ my $legend_section_js = $show_legend ? <<"LEGEND_JS" : '';
Branch: 1 branch
BranchTrueFalseTotal
$show_legend ? : 61 1 62
1334 d3.select("#$leg_id")
1335 .selectAll(".bi-pie-legend-entry")
1336 .data(pieSlices)
1337 .join("div")
1338 .attr("class", "bi-pie-legend-entry")
1339 .attr("data-slice-index", (d, i) => i)
1340 .html((d, i) => {
1341 const pct = (d.data.value / total * 100).toFixed(1);
1342 const sw = '<span class="bi-pie-swatch" style="background:' + color(d.data.label) + '"></span>';
1343 return sw + ' ' + d.data.label + ' $separator ' + fmt(d.data.value) + ' (' + pct + '%)';
1344 });
1345 LEGEND_JS
1346  
1347 62 ▶ my $legend_div_html = $show_legend
Branch: 1 branch
BranchTrueFalseTotal
$show_legend ? : 61 1 62
1348 ? qq( <div id="$leg_id" class="bi-pie-legend"></div>\n)
1349 : '';
1350  
1351 62 my $html = <<"HTML";
1352 <style>
1353 #$wrap_id {
1354 display: flex;
1355 flex-wrap: wrap;
1356 align-items: center;
1357 }
1358 .bi-pie-legend {
1359 padding-left: 16px;
1360 font-size: 13px;
1361 }
1362 .bi-pie-legend-entry {
1363 margin: 4px 0;
1364 white-space: nowrap;
1365 }
1366 .bi-pie-swatch {
1367 display: inline-block;
1368 width: 12px;
1369 height: 12px;
1370 border-radius: 2px;
1371 vertical-align: middle;
1372 margin-right: 4px;
1373 }
1374 .bi-pie-tooltip {
1375 position: absolute;
1376 background: rgba(255,255,255,0.95);
1377 border: 1px solid #ccc;
1378 border-radius: 4px;
1379 padding: 6px 10px;
1380 font-size: 12px;
1381 pointer-events: none;
1382 display: none;
1383 line-height: 1.6;
1384 }
1385 </style>
1386 <div id="$wrap_id">
1387 <svg id="$svg_id" $svg_attrs></svg>
1388 $legend_div_html</div>
1389 <div class="bi-pie-tooltip" id="$tip_id"></div>
1390 <script>
1391 const data = $json_data;
1392  
1393 function esc(s) {
1394 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1395 }
1396  
1397 $schemes_js
1398 const color = d3.scaleOrdinal(SCHEMES['$color_scheme'] || $default_js)
1399 .domain(data.map(d => d.label));
1400  
1401 const width = $width;
1402 const height = $height;
1403 const radius = Math.min(width, height) / 2 - 40;
1404 const innerRadius = $inner_radius_js;
1405  
1406 const arc = d3.arc().innerRadius(innerRadius).outerRadius(radius);
1407 const labelArc = d3.arc().innerRadius(radius * 0.7).outerRadius(radius * 0.7);
1408  
1409 const pie = d3.pie().sort(null).value(d => d.value);
1410 const pieSlices = pie(data);
1411  
1412 const total = d3.sum(data, d => d.value);
1413 const fmt = d3.format(",.2f");
1414  
1415 $anim_init_js
1416 const svg = d3.select("#$svg_id");
1417 const tooltip = d3.select("#$tip_id");
1418  
1419 const pieGroup = svg.append("g")
1420 .attr("transform", \`translate(\${$width * 0.5},\${$height / 2})\`);
1421  
1422 const arcs = pieGroup.selectAll(".arc")
1423 .data(pieSlices)
1424 .join("g")
1425 .attr("class", "arc");
1426  
1427 const paths = arcs.append("path")
1428 .attr("fill", d => color(d.data.label))
1429 .attr("stroke", "white")
1430 .style("stroke-width", "2px")
1431 .attr("data-label", d => d.data.label)
1432 .attr("data-value", d => d.data.value)
1433 .on("mouseover", function(event, d) {
1434 const pct = (d.data.value / total * 100).toFixed(1);
1435 let tip = "<b>" + esc(d.data.label) + "<\\/b><br>" +
1436 fmt(d.data.value) + " (" + pct + "%)";
1437 if (d.data.extra) {
1438 Object.entries(d.data.extra).forEach(([k, v]) => {
1439 tip += "<br>" + esc(k) + ": " + esc(v);
1440 });
1441 }
1442 tooltip.html(tip)
1443 .style("display", "block")
1444 .style("left", (event.pageX + 12) + "px")
1445 .style("top", (event.pageY - 24) + "px");
1446 })
1447 .on("mousemove", function(event) {
1448 tooltip.style("left", (event.pageX + 12) + "px")
1449 .style("top", (event.pageY - 24) + "px");
1450 })
1451 .on("mouseout", function() {
1452 tooltip.style("display", "none");
1453 });
1454  
1455 $anim_draw_js
1456 $donut_center_js
1457 $legend_section_js</script>
1458 HTML
1459  
1460 62 return { svg_id => $svg_id, html => $html };
1461 }
1462  
1463 =head2 render_heatmap_snippet
1464  
1465 my $fragment = $chart->render_heatmap_snippet(\@triples);
1466 my $fragment = $chart->render_heatmap_snippet(\@triples, \%opts);
1467 # $fragment->{svg_id} - always 'heatmap'
1468 # $fragment->{html} - embeddable fragment; caller must load D3 v7
1469  
1470 Generates an embeddable grid heatmap for use in existing HTML layouts.
1471 Each cell sits at the intersection of an X-axis label and a Y-axis label;
1472 its colour encodes the cell's numeric value using a sequential D3 colour
1473 scale. Returns C<{ svg_id =E<gt> 'heatmap', html =E<gt> Str }>. The
1474 caller is responsible for loading D3 v7 before embedding the fragment.
1475  
1476 =head3 Data format
1477  
1478 Each element of C<\@triples> is C<[$x_label, $y_label, $value]>.
1479 C<$value> must be numeric or C<undef> (C<undef> rows are silently
1480 skipped). Zero is a valid value and maps to the lightest cell colour.
1481 The caller is responsible for any aggregation: if multiple triples share
1482 the same (x_label, y_label) pair, the last one wins.
1483  
1484 =head3 Options (C<\%opts>)
1485  
1486 =over 4
1487  
1488 =item * C<color_scheme> (string, default C<'YlOrRd'>) - D3 sequential
1489 colour scheme. Supported: C<YlOrRd>, C<Blues>, C<Greens>, C<Purples>,
1490 C<RdPu>, C<YlGnBu>.
1491  
1492 =item * C<x_label> (string, default C<''>) - Axis title below the X axis.
1493 The value is JavaScript-escaped (backslash, double-quote, newline, carriage
1494 return, C<E<lt>>) before being embedded in the page; other characters are taken
1495 literally.
1496  
1497 =item * C<y_label> (string, default C<''>) - Axis title left of the Y axis.
1498 Same JS-escaping as C<x_label> applies.
1499  
1500 =item * C<val_label> (string, default C<'Value'>) - Tooltip value label.
1501 Same JS-escaping as C<x_label> applies.
1502  
1503 =item * C<show_values> (bool, default 0) - Print value inside each cell.
1504 Auto-suppressed when any cell is narrower than 28 px.
1505  
1506 =item * C<cell_padding> (int 0-8, default 2) - Gap in pixels between cells.
1507  
1508 =item * C<legend> (bool, default 1) - Render a colour-scale legend bar.
1509  
1510 =item * C<animated> (bool, default 0) - Fade cells in on first load.
1511 Respects C<prefers-reduced-motion>.
1512  
1513 =back
1514  
1515 =head3 Errors
1516  
1517 =over 4
1518  
1519 =item * Dies with C<Data must be an array of arrays> when C<\@triples>
1520 is not an ARRAY reference.
1521  
1522 =item * Dies with C<Each data point must be an array reference> when a
1523 triple element is not an arrayref.
1524  
1525 =item * Dies with C<Each data point must have at least 3 elements> when
1526 a triple has fewer than 3 elements.
1527  
1528 =item * Dies with C<Value must be numeric> when C<$value> is defined but
1529 not numeric.
1530  
1531 =item * Dies with C<Unknown color_scheme: E<lt>nameE<gt>> for an
1532 unsupported C<color_scheme> value.
1533  
1534 =item * Dies with C<cell_padding must be between 0 and 8> when
1535 C<cell_padding> is outside the valid range.
1536  
1537 =back
1538  
1539 =head3 Side Effects
1540  
1541 Appends a tooltip C<div> to the page when the fragment is rendered in
1542 the browser.
1543  
1544 =head3 API SPECIFICATION
1545  
1546 =head4 Input
1547  
1548 {
1549 data => { type => 'arrayref' },
1550 opts => { type => 'hashref', optional => 1, default => {} },
1551 }
1552  
1553 Each element of C<$data> is C<[ Str, Str, Num|undef ]>.
1554 Recognised C<opts> keys: C<color_scheme> (string, default C<'YlOrRd'>),
1555 C<x_label> (string, default C<''>), C<y_label> (string, default C<''>),
1556 C<val_label> (string, default C<'Value'>), C<show_values> (boolean,
1557 default C<0>), C<cell_padding> (integer 0-8, default C<2>),
1558 C<legend> (boolean, default C<1>), C<animated> (boolean, default C<0>).
1559  
1560 =head4 Output
1561  
1562 HashRef -- C<{ svg_id =E<gt> 'heatmap', html =E<gt> Str }>;
1563 embeddable fragment; no DOCTYPE, no page shell, no D3 CDN tag.
1564  
1565 =cut
1566  
1567 84 ▶sub render_heatmap_snippet {
Subroutine render_heatmap_snippet: called CC=28 SCAR=33.3
Pod documented
1568 84 my $self = shift;
1569 84 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
840
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
1570 84 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 81 84
1571 81 Params::Validate::Strict::validate_strict({
1572 args => $raw,
1573 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
1574 unknown_parameter_handler => 'ignore',
1575 });
1576 81 my $data = $raw->{data};
1577 81 my $opts = {%$raw}; delete $opts->{data};
1578  
1579 81 my %color_scheme_map = (
1580 YlOrRd => 'd3.interpolateYlOrRd',
1581 Blues => 'd3.interpolateBlues',
1582 Greens => 'd3.interpolateGreens',
1583 Purples => 'd3.interpolatePurples',
1584 RdPu => 'd3.interpolateRdPu',
1585 YlGnBu => 'd3.interpolateYlGnBu',
1586 );
1587  
1588 81 ▶ my $color_scheme = $opts->{color_scheme} // 'YlOrRd';
Condition100%2/2
$opts->{"color_scheme"} // "YlOrRd"
l!l
1566
MC/DC100%1/1
$opts->{"color_scheme"} // "YlOrRd"
$opts->{"color_scheme"}
Truth table100%2/2
A
A= $opts->{"color_scheme"}
Aresult
11
00
1589 die "Unknown color_scheme: $color_scheme"
1590 81 ▶ unless exists $color_scheme_map{$color_scheme};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $color_scheme_map{$color_scheme} 3 78 81
1591 78 my $d3_interpolator = $color_scheme_map{$color_scheme};
1592  
1593 78 ▶ my $cell_padding = defined($opts->{cell_padding}) ? int($opts->{cell_padding}) : 2;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'cell_padding'} ? : 5 73 78
1594 78 ▶ die 'cell_padding must be between 0 and 8'
Branch: 1 branch
BranchTrueFalseTotal
unless $cell_padding >= 0 and $cell_padding <= 8 5 73 78
Condition100%3/3
$cell_padding >= 0 and $cell_padding <= 8
!ll&&!rl&&r
2373
MC/DC100%2/2
$cell_padding >= 0 and $cell_padding <= 8
$cell_padding >= 0 $cell_padding <= 8
Truth table100%3/3
A and B
A= $cell_padding >= 0B= $cell_padding <= 8
ABresult
0X0
100
111
1595 unless $cell_padding >= 0 && $cell_padding <= 8;
1596  
1597 73 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
469
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
1598 73 ▶ my $y_label = $opts->{y_label} // '';
Condition100%2/2
$opts->{"y_label"} // ""
l!l
469
MC/DC100%1/1
$opts->{"y_label"} // ""
$opts->{"y_label"}
Truth table100%2/2
A
A= $opts->{"y_label"}
Aresult
11
00
1599 73 ▶ my $val_label = $opts->{val_label} // 'Value';
Condition100%2/2
$opts->{"val_label"} // "Value"
l!l
370
MC/DC100%1/1
$opts->{"val_label"} // "Value"
$opts->{"val_label"}
Truth table100%2/2
A
A= $opts->{"val_label"}
Aresult
11
00
1600 73 ▶ my $show_values = $opts->{show_values} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'show_values'} ? : 1 72 73
1601 73 ▶ my $legend = exists $opts->{legend} ? ($opts->{legend} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'legend'} ? : 4 69 73
$opts->{'legend'} ? : 1 3 4
1602 73 ▶ my $animated = $opts->{animated} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'animated'} ? : 4 69 73
1603  
1604 73 my @triples;
1605 73 for my $pt (@$data) {
1606 191 ▶ die 'Each data point must be an array reference'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pt eq "ARRAY" 3 188 191
1607 unless ref($pt) eq 'ARRAY';
1608 188 ▶ die 'Each data point must have at least 3 elements'
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$pt >= 3 5 183 188
1609 unless scalar(@$pt) >= 3;
1610 183 ▶ next unless defined $pt->[2];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pt->[2] 3 180 183
1611 180 ▶ die 'Value must be numeric' unless looks_like_number($pt->[2]);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($pt->[2]) 3 177 180
1612 177 push @triples, { x => $pt->[0], y => $pt->[1], v => $pt->[2] + 0 };
1613 }
1614  
1615 62 my $json_data = _script_json(\@triples);
1616  
1617 # encode_json only accepts refs; escape label strings manually for JS
1618 62 my ($x_label_esc, $y_label_esc, $val_label_esc) = map { _js_string($_) } ($x_label, $y_label, $val_label);
1619  
1620 62 ▶ my $svg_id = _chart_id($opts->{id}) // 'heatmap';
Condition100%2/2
_chart_id($opts->{"id"}) // "heatmap"
l!l
656
MC/DC100%1/1
_chart_id($opts->{"id"}) // "heatmap"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
1621 62 my $tip_id = $svg_id . '_tip';
1622  
1623 62 my $width = $self->{width};
1624 62 my $height = $self->{height};
1625 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
1626 62 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 59 62
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2600
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
1627 : qq{width="$width" height="$height"};
1628  
1629 62 my $margin_top = 30;
1630 62 ▶ my $margin_right = $legend ? 65 : 20;
Branch: 1 branch
BranchTrueFalseTotal
$legend ? : 59 3 62
1631 62 ▶ my $margin_bottom = $x_label ? 60 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 4 58 62
1632 62 ▶ my $margin_left = $y_label ? 80 : 60;
Branch: 1 branch
BranchTrueFalseTotal
$y_label ? : 4 58 62
1633 62 my $inner_w = $width - $margin_left - $margin_right;
1634 62 my $inner_h = $height - $margin_top - $margin_bottom;
1635  
1636 62 ▶ my $anim_block = $animated ? <<"ANIM" : '';
Branch: 1 branch
BranchTrueFalseTotal
$animated ? : 4 58 62
1637 var noAnim = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1638 if (!noAnim) {
1639 cellGs.attr("opacity", 0)
1640 .transition()
1641 .duration(300)
1642 .delay(function(d) { return yMap.get(d.y) * 50; })
1643 .attr("opacity", 1);
1644 }
1645 ANIM
1646  
1647 62 ▶ my $legend_block = $legend ? <<"LEGBLOCK" : '';
Branch: 1 branch
BranchTrueFalseTotal
$legend ? : 59 3 62
1648 {
1649 var defs = svg.append("defs");
1650 var lgId = "heatmap-lg";
1651 var lg = defs.append("linearGradient")
1652 .attr("id", lgId)
1653 .attr("x1", "0").attr("y1", "1")
1654 .attr("x2", "0").attr("y2", "0");
1655 for (var i = 0; i <= 6; i++) {
1656 lg.append("stop")
1657 .attr("offset", (i / 6 * 100) + "%")
1658 .attr("stop-color", colorScale(maxV * i / 6));
1659 }
1660 var lgX = margin.left + innerW + 15;
1661 var lgBarH = Math.min(innerH, 150);
1662 var lgBarY = margin.top + (innerH - lgBarH) / 2;
1663 svg.append("rect")
1664 .attr("x", lgX)
1665 .attr("y", lgBarY)
1666 .attr("width", 12)
1667 .attr("height", lgBarH)
1668 .attr("fill", "url(#" + lgId + ")");
1669 var lgScale = d3.scaleLinear().domain([0, maxV]).range([lgBarH, 0]);
1670 svg.append("g")
1671 .attr("transform", "translate(" + (lgX + 12) + "," + lgBarY + ")")
1672 .call(d3.axisRight(lgScale).ticks(4));
1673 }
1674 LEGBLOCK
1675  
1676 62 my $html = <<"HTML";
1677 <style>
1678 #$svg_id { display: block; }
1679 #$tip_id {
1680 position: absolute;
1681 background: rgba(255,255,255,0.95);
1682 border: 1px solid #ccc;
1683 border-radius: 4px;
1684 padding: 6px 10px;
1685 font-size: 12px;
1686 pointer-events: none;
1687 display: none;
1688 line-height: 1.6;
1689 }
1690 .hm-cell-text {
1691 font-size: 10px;
1692 fill: #222;
1693 pointer-events: none;
1694 text-anchor: middle;
1695 dominant-baseline: middle;
1696 }
1697 </style>
1698 <svg id="$svg_id" $svg_attrs></svg>
1699 <div id="$tip_id"></div>
1700 <script>
1701 (function() {
1702 var data = $json_data;
1703 var cellPad = $cell_padding;
1704 var showVals0 = $show_values;
1705 var xLabelStr = "$x_label_esc";
1706 var yLabelStr = "$y_label_esc";
1707 var valLabelStr = "$val_label_esc";
1708 var margin = { top: $margin_top, right: $margin_right, bottom: $margin_bottom, left: $margin_left };
1709 var innerW = $inner_w;
1710 var innerH = $inner_h;
1711  
1712 function esc(s) {
1713 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1714 }
1715  
1716 var xMap = new Map(), yMap = new Map();
1717 data.forEach(function(d) {
1718 if (!xMap.has(d.x)) xMap.set(d.x, xMap.size);
1719 if (!yMap.has(d.y)) yMap.set(d.y, yMap.size);
1720 });
1721 var xLabels = Array.from(xMap.keys());
1722 var yLabels = Array.from(yMap.keys());
1723  
1724 var maxV = d3.max(data, function(d) { return d.v; }) || 0;
1725 var colorScale = d3.scaleSequential($d3_interpolator)
1726 .domain(maxV === 0 ? [0, 1] : [0, maxV]);
1727  
1728 var xPad = Math.min(cellPad / Math.max(1, innerW / Math.max(1, xLabels.length)), 0.4);
1729 var yPad = Math.min(cellPad / Math.max(1, innerH / Math.max(1, yLabels.length)), 0.4);
1730  
1731 var xScale = d3.scaleBand().domain(xLabels).range([0, innerW]).paddingInner(xPad);
1732 var yScale = d3.scaleBand().domain(yLabels).range([0, innerH]).paddingInner(yPad);
1733  
1734 var showVals = showVals0 && xScale.bandwidth() >= 28 && yScale.bandwidth() >= 28;
1735  
1736 var svg = d3.select("#$svg_id");
1737 var g = svg.append("g")
1738 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
1739  
1740 g.append("g").attr("class", "hm-x-axis")
1741 .call(d3.axisTop(xScale).tickSize(0))
1742 .call(function(a) { a.select(".domain").remove(); });
1743 g.append("g").attr("class", "hm-y-axis")
1744 .call(d3.axisLeft(yScale).tickSize(0))
1745 .call(function(a) { a.select(".domain").remove(); });
1746  
1747 if (xLabelStr) {
1748 svg.append("text")
1749 .attr("x", margin.left + innerW / 2)
1750 .attr("y", $height - 4)
1751 .attr("text-anchor", "middle")
1752 .attr("font-size", "12px")
1753 .text(xLabelStr);
1754 }
1755 if (yLabelStr) {
1756 svg.append("text")
1757 .attr("transform", "rotate(-90)")
1758 .attr("x", -(margin.top + innerH / 2))
1759 .attr("y", 14)
1760 .attr("text-anchor", "middle")
1761 .attr("font-size", "12px")
1762 .text(yLabelStr);
1763 }
1764  
1765 var tip = d3.select("#$tip_id");
1766  
1767 var gridMap = new Map();
1768 data.forEach(function(d) { gridMap.set(d.x + "\\t" + d.y, d); });
1769 var cells = Array.from(gridMap.values());
1770  
1771 var cellGs = g.selectAll(".hm-cell")
1772 .data(cells)
1773 .join("g")
1774 .attr("class", "hm-cell")
1775 .attr("transform", function(d) {
1776 return "translate(" + xScale(d.x) + "," + yScale(d.y) + ")";
1777 });
1778  
1779 cellGs.append("rect")
1780 .attr("width", xScale.bandwidth())
1781 .attr("height", yScale.bandwidth())
1782 .attr("fill", function(d) { return colorScale(d.v); })
1783 .on("mouseover", function(event, d) {
1784 tip.html("X: " + esc(d.x) + "<br>Y: " + esc(d.y) + "<br>" + esc(valLabelStr) + ": " + d.v.toLocaleString())
1785 .style("display", "block")
1786 .style("left", (event.pageX + 12) + "px")
1787 .style("top", (event.pageY - 24) + "px");
1788 })
1789 .on("mousemove", function(event) {
1790 tip.style("left", (event.pageX + 12) + "px")
1791 .style("top", (event.pageY - 24) + "px");
1792 })
1793 .on("mouseout", function() { tip.style("display", "none"); });
1794  
1795 if (showVals) {
1796 cellGs.append("text")
1797 .attr("class", "hm-cell-text")
1798 .attr("x", xScale.bandwidth() / 2)
1799 .attr("y", yScale.bandwidth() / 2)
1800 .text(function(d) { return d.v.toLocaleString(); });
1801 }
1802  
1803 $legend_block
1804 $anim_block})();
1805 </script>
1806 HTML
1807  
1808 62 return { svg_id => $svg_id, html => $html };
1809 }
1810  
1811 =head2 render_bar_chart_snippet
1812  
1813 my $result = $chart->render_bar_chart_snippet(\@bars);
1814 my $result = $chart->render_bar_chart_snippet(\@bars, \%opts);
1815  
1816 Generates an embeddable D3.js v7 bar chart fragment. Returns a hashref
1817 C<{ svg_id =E<gt> 'bar_chart', html =E<gt> $str }> where C<$str> is a
1818 self-contained HTML fragment (no page shell, no D3 CDN tag) that the caller
1819 embeds directly after loading D3.js. C<$str> is a Perl character string
1820 with the UTF-8 flag set (or pure ASCII when all labels are ASCII).
1821  
1822 Each element of C<\@bars> is an array reference:
1823  
1824 [ $label, $value ]
1825 [ $label, $value, \%extra ]
1826  
1827 C<$label> is the category name (string); C<$value> is a non-negative number
1828 (negative values are silently converted to their absolute value); the optional
1829 C<\%extra> hashref supplies additional key/value pairs shown in the hover
1830 tooltip. Data points with an undefined C<$value> are silently skipped.
1831  
1832 =head3 Options (C<\%opts>)
1833  
1834 =over 4
1835  
1836 =item C<orientation> (string, default C<'vertical'>)
1837  
1838 C<'vertical'> draws bars rising from a horizontal category axis.
1839 C<'horizontal'> draws bars extending from a vertical category axis.
1840  
1841 =item C<sort_bars> (string, default C<'none'>)
1842  
1843 Sort order applied before rendering: C<'value'> sorts descending by bar
1844 height, C<'label'> sorts ascending alphabetically, C<'none'> preserves the
1845 input order.
1846  
1847 =item C<max_bars> (integer, default C<0>)
1848  
1849 When non-zero, only the first C<max_bars> entries (after any sort) are
1850 rendered; the remaining entries are collapsed into a single C<Other> bar
1851 whose value equals their sum. Zero means no limit.
1852  
1853 =item C<color> (string, default C<'steelblue'>)
1854  
1855 Either a CSS colour value (e.g. C<'steelblue'>, C<'#4e79a7'>) applied to all
1856 bars, or the special token C<'categorical'>, which colours each bar
1857 distinctively using D3's Tableau-10 palette.
1858  
1859 A value holding anything a CSS colour cannot, such as a quote or C<E<lt>>, is
1860 ignored and the default used.
1861  
1862 =item C<show_values> (bool, default C<0>)
1863  
1864 When true, the numeric value of each bar is printed above vertical bars or
1865 to the right of horizontal bars.
1866  
1867 =item C<animated> (bool, default C<0>)
1868  
1869 When true, bars grow from the baseline on page load: vertical bars rise from
1870 the bottom; horizontal bars extend from the left. An 800 ms D3 transition
1871 with a per-bar stagger up to 100 ms is used. The animation is suppressed
1872 when C<prefers-reduced-motion> is set in the viewer's OS.
1873  
1874 =item C<value_label> (string, default C<'Value'>)
1875  
1876 Label shown in the hover tooltip before the numeric value. The value is
1877 JavaScript-escaped before being embedded in the page.
1878  
1879 =item C<x_label> (string, default C<''>)
1880  
1881 When non-empty, a text label is rendered below the bottom axis. The value
1882 is JavaScript-escaped before being embedded in the page.
1883  
1884 =back
1885  
1886 =head3 Errors
1887  
1888 =over 4
1889  
1890 =item * Throws C<Data must be an array of arrays> when C<$data> is not an
1891 ARRAY reference.
1892  
1893 =item * Throws C<Each data point must be an array reference> when an element
1894 is not an array reference.
1895  
1896 =item * Throws C<Each data point must have at least 2 elements> when an
1897 element has fewer than 2 items.
1898  
1899 =item * Throws C<Value must be numeric> when a C<$value> is not a number.
1900  
1901 =item * Throws C<orientation must be 'vertical' or 'horizontal'> on an
1902 invalid orientation value.
1903  
1904 =item * Throws C<sort_bars must be 'value', 'label', or 'none'> on an
1905 invalid sort_bars value.
1906  
1907 =back
1908  
1909 =head3 API SPECIFICATION
1910  
1911 =head4 Input
1912  
1913 {
1914 data => { type => 'arrayref' },
1915 opts => { type => 'hashref', optional => 1 },
1916 orientation => { type => 'string', memberof => [ 'vertical', 'horizontal' ], optional => 1 },
1917 sort_bars => { type => 'string', memberof => [ 'value', 'label', 'none' ], optional => 1 }
1918 }
1919  
1920 Each element of C<$data>: C<[ Str, Num ]> or C<[ Str, Num, HashRef ]>;
1921 undef C<$value> silently skipped; negative C<$value> becomes positive.
1922  
1923 =head4 Output
1924  
1925 HashRef -- { svg_id => 'bar_chart', html => Str }
1926 html is a Perl character string (UTF-8 flag set, or pure ASCII).
1927  
1928 =cut
1929  
1930 114 ▶sub render_bar_chart_snippet {
Subroutine render_bar_chart_snippet: called CC=50 SCAR=39.1
Pod documented
1931 114 my $self = shift;
1932 114 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
1140
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
1933 114 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 111 114
1934 111 Params::Validate::Strict::validate_strict({
1935 args => $raw,
1936 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
1937 unknown_parameter_handler => 'ignore',
1938 });
1939 111 my $data = $raw->{data};
1940 111 my $opts = {%$raw}; delete $opts->{data};
1941  
1942 111 ▶ my $orientation = $opts->{orientation} // 'vertical';
Condition100%2/2
$opts->{"orientation"} // "vertical"
l!l
7104
MC/DC100%1/1
$opts->{"orientation"} // "vertical"
$opts->{"orientation"}
Truth table100%2/2
A
A= $opts->{"orientation"}
Aresult
11
00
1943 111 ▶ die "orientation must be 'vertical' or 'horizontal'"
Branch: 1 branch
BranchTrueFalseTotal
unless $orientation eq "vertical" or $orientation eq "horizontal" 3 108 111
Condition100%3/3
$orientation eq "vertical" or $orientation eq "horizontal"
l!l&&r!l&&!r
10443
MC/DC100%2/2
$orientation eq "vertical" or $orientation eq "horizontal"
$orientation eq "vertical" $orientation eq "horizontal"
Truth table100%3/3
A or B
A= $orientation eq "vertical"B= $orientation eq "horizontal"
ABresult
1X1
011
000
1944 unless $orientation eq 'vertical' || $orientation eq 'horizontal';
1945  
1946 108 ▶ my $sort_bars = $opts->{sort_bars} // 'none';
Condition100%2/2
$opts->{"sort_bars"} // "none"
l!l
1296
MC/DC100%1/1
$opts->{"sort_bars"} // "none"
$opts->{"sort_bars"}
Truth table100%2/2
A
A= $opts->{"sort_bars"}
Aresult
11
00
1947 die "sort_bars must be 'value', 'label', or 'none'"
1948 108 ▶ unless grep { $sort_bars eq $_ } qw(value label none);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$sort_bars eq $_;} "value", "label", "none" 3 105 108
1949  
1950 105 ▶ my $max_bars = int($opts->{max_bars} // 0);
Condition100%2/2
$opts->{"max_bars"} // 0
l!l
4101
MC/DC100%1/1
$opts->{"max_bars"} // 0
$opts->{"max_bars"}
Truth table100%2/2
A
A= $opts->{"max_bars"}
Aresult
11
00
1951 105 ▶ my $color = _css_colour($opts->{color}) // 'steelblue';
Condition100%2/2
_css_colour($opts->{"color"}) // "steelblue"
l!l
1194
MC/DC100%1/1
_css_colour($opts->{"color"}) // "steelblue"
_css_colour($opts->{"color"})
Truth table100%2/2
A
A= _css_colour($opts->{"color"})
Aresult
11
00
1952 105 ▶ my $show_values = $opts->{show_values} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'show_values'} ? : 4 101 105
1953 105 ▶ my $animated = $opts->{animated} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'animated'} ? : 4 101 105
1954 105 ▶ my $value_label = $opts->{value_label} // 'Value';
Condition100%2/2
$opts->{"value_label"} // "Value"
l!l
4101
MC/DC100%1/1
$opts->{"value_label"} // "Value"
$opts->{"value_label"}
Truth table100%2/2
A
A= $opts->{"value_label"}
Aresult
11
00
1955 105 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
798
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
1956  
1957 # Normalise data points; negative values become positive (bars show magnitude)
1958 105 my @bars;
1959 105 for my $pt (@$data) {
1960 322 ▶ die 'Each data point must be an array reference'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pt eq "ARRAY" 3 319 322
1961 unless ref($pt) eq 'ARRAY';
1962 319 ▶ die 'Each data point must have at least 2 elements'
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$pt >= 2 3 316 319
1963 unless scalar(@$pt) >= 2;
1964 316 ▶ next unless defined $pt->[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pt->[1] 3 313 316
1965 313 ▶ die 'Value must be numeric' unless looks_like_number($pt->[1]);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($pt->[1]) 3 310 313
1966 310 ▶ push @bars, {
Branch: 2 branches
BranchTrueFalseTotal
defined $pt->[0] ? : 310 0 310
scalar @$pt >= 3 && ref $pt->[2] eq 'HASH' ? : 3 307 310
Condition66%2/3
scalar @$pt >= 3 and ref $pt->[2] eq "HASH"
!ll&&!rl&&r
30703
MC/DC50%1/2
scalar @$pt >= 3 and ref $pt->[2] eq "HASH"
scalar @$pt >= 3 ref $pt->[2] eq "HASH"
Truth table66%2/3
A and B
A= scalar @$pt >= 3B= ref $pt->[2] eq "HASH"
ABresult
0X0
100
111
1967 label => defined($pt->[0]) ? "$pt->[0]" : '',
1968 value => abs($pt->[1] + 0),
1969 (scalar(@$pt) >= 3 && ref($pt->[2]) eq 'HASH'
1970 ? (extra => $pt->[2]) : ()),
1971 };
1972 }
1973  
1974 # Sort before optional truncation
1975 96 ▶ if ($sort_bars eq 'value') {
Branch: 2 branches
BranchTrueFalseTotal
if ($sort_bars eq 'value') { } 7 89 96
elsif ($sort_bars eq 'label') { } 2 87 89
1976 7 @bars = sort { $b->{value} <=> $a->{value} } @bars;
1977 } elsif ($sort_bars eq 'label') {
1978 2 @bars = sort { $a->{label} cmp $b->{label} } @bars;
1979 }
1980  
1981 # Truncate and collapse the tail into an "Other" bar
1982 96 ▶ if ($max_bars && scalar(@bars) > $max_bars) {
Branch: 1 branch
BranchTrueFalseTotal
if ($max_bars and scalar @bars > $max_bars) 4 92 96
Condition66%2/3
$max_bars and scalar @bars > $max_bars
!ll&&!rl&&r
9204
MC/DC50%1/2
$max_bars and scalar @bars > $max_bars
$max_bars scalar @bars > $max_bars
Truth table66%2/3
A and B
A= $max_barsB= scalar @bars > $max_bars
ABresult
0X0
100
111
1983 4 my @rest = splice @bars, $max_bars;
1984 4 my $other = 0;
1985 4 $other += $_->{value} for @rest;
1986 4 ▶ push @bars, { label => 'Other', value => $other } if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 4 0 4
1987 }
1988  
1989 # Serialise to JSON for embedding in the <script> block
1990 my $json_data = _script_json([map {
1991 96 my %h = (label => $_->{label}, value => $_->{value} + 0);
1992 306 ▶ $h{extra} = $_->{extra} if exists $_->{extra};
Branch: 1 branch
BranchTrueFalseTotal
if exists $_->{"extra"} 3 303 306
1993 306 \%h;
1994 } @bars]);
1995  
1996 # Escape strings for safe embedding inside JS double-quoted string literals
1997 96 my $js_esc = \&_js_string;
1998 96 my $value_label_esc = $js_esc->($value_label);
1999 96 my $x_label_esc = $js_esc->($x_label);
2000  
2001 96 ▶ my $is_categorical = ($color eq 'categorical') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$color eq 'categorical' ? : 5 91 96
2002 96 ▶ my $color_esc = $is_categorical ? 'steelblue' : $js_esc->($color);
Branch: 1 branch
BranchTrueFalseTotal
$is_categorical ? : 5 91 96
2003  
2004 96 ▶ my $svg_id = _chart_id($opts->{id}) // 'bar_chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "bar_chart"
l!l
690
MC/DC100%1/1
_chart_id($opts->{"id"}) // "bar_chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
2005 96 my $tip_id = $svg_id . '_tip';
2006  
2007 96 my $width = $self->{width};
2008 96 my $height = $self->{height};
2009 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
2010 96 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 5 91 96
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
4920
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
2011 : qq{width="$width" height="$height"};
2012  
2013 # Rotate x-axis labels when there are more than 8 vertical bars
2014 96 ▶ my $rotate_labels = ($orientation eq 'vertical' && scalar(@bars) > 8) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$orientation eq 'vertical' && scalar @bars > 8 ? : 3 93 96
Condition100%3/3
$orientation eq "vertical" and scalar @bars > 8
!ll&&!rl&&r
4893
MC/DC100%2/2
$orientation eq "vertical" and scalar @bars > 8
$orientation eq "vertical" scalar @bars > 8
Truth table100%3/3
A and B
A= $orientation eq "vertical"B= scalar @bars > 8
ABresult
0X0
100
111
2015  
2016 # Margins depend on orientation, label rotation, and optional features
2017 96 my ($margin_top, $margin_right, $margin_bottom, $margin_left);
2018 96 ▶ if ($orientation eq 'vertical') {
Branch: 1 branch
BranchTrueFalseTotal
if ($orientation eq 'vertical') { } 92 4 96
2019 92 $margin_top = 20;
2020 92 $margin_right = 20;
2021 92 ▶ $margin_bottom = $rotate_labels
Branch: 3 branches
BranchTrueFalseTotal
$rotate_labels ? : 3 89 92
$x_label ? : 0 3 3
$x_label ? : 6 83 89
2022 ? ($x_label ? 105 : 85)
2023 : ($x_label ? 55 : 40);
2024 92 $margin_left = 55;
2025 } else {
2026 4 $margin_top = 20;
2027 4 ▶ $margin_right = $show_values ? 60 : 20;
Branch: 1 branch
BranchTrueFalseTotal
$show_values ? : 1 3 4
2028 4 ▶ $margin_bottom = $x_label ? 55 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 1 3 4
2029 4 $margin_left = 130;
2030 }
2031 96 my $inner_w = $width - $margin_left - $margin_right;
2032 96 my $inner_h = $height - $margin_top - $margin_bottom;
2033  
2034 # JS colour initialiser and per-bar fill callback
2035 96 ▶ my $color_init_js = $is_categorical
Branch: 1 branch
BranchTrueFalseTotal
$is_categorical ? : 5 91 96
2036 ? 'var colorOf = d3.scaleOrdinal(' . _default_scheme_js() . ')'
2037 . ".domain(data.map(function(d){return d.label;}));"
2038 : "var colorOf = function() { return \"$color_esc\"; };";
2039 96 my $color_func_js = 'function(d) { return colorOf(d.label); }';
2040  
2041 # Rotate x-axis tick labels (vertical orientation with many bars only)
2042 96 ▶ my $rotate_block = $rotate_labels ? <<"ROT" : '';
Branch: 1 branch
BranchTrueFalseTotal
$rotate_labels ? : 3 93 96
2043 g.selectAll(".bc-x-axis text")
2044 .attr("transform", "rotate(-45)")
2045 .attr("text-anchor", "end")
2046 .attr("dx", "-0.6em")
2047 .attr("dy", "0.15em");
2048 ROT
2049  
2050 # Optional inline value labels rendered on each bar
2051 96 my $show_values_block = '';
2052 96 ▶ if ($show_values) {
Branch: 1 branch
BranchTrueFalseTotal
if ($show_values) 4 92 96
2053 4 ▶ if ($orientation eq 'vertical') {
Branch: 1 branch
BranchTrueFalseTotal
if ($orientation eq 'vertical') { } 3 1 4
2054 3 $show_values_block = <<"SVB";
2055 g.selectAll(".bc-val-text").data(data).join("text")
2056 .attr("class", "bc-val-text")
2057 .attr("x", function(d) { return xScale(d.label) + xScale.bandwidth() / 2; })
2058 .attr("y", function(d) { return yScale(d.value) - 4; })
2059 .attr("text-anchor", "middle")
2060 .attr("font-size", "11px")
2061 .attr("fill", "#333")
2062 .text(function(d) { return d.value.toLocaleString(); });
2063 SVB
2064 } else {
2065 1 $show_values_block = <<"SVB";
2066 g.selectAll(".bc-val-text").data(data).join("text")
2067 .attr("class", "bc-val-text")
2068 .attr("x", function(d) { return xScale(d.value) + 4; })
2069 .attr("y", function(d) { return yScale(d.label) + yScale.bandwidth() / 2; })
2070 .attr("dominant-baseline", "middle")
2071 .attr("font-size", "11px")
2072 .attr("fill", "#333")
2073 .text(function(d) { return d.value.toLocaleString(); });
2074 SVB
2075 }
2076 }
2077  
2078 # Optional text label below the bottom axis
2079 96 my $x_label_block = '';
2080 96 ▶ if ($x_label) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x_label) 7 89 96
2081 7 my $lx = $margin_left + int($inner_w / 2);
2082 7 my $ly = $height - 5;
2083 7 $x_label_block = <<"XLB";
2084 svg.append("text")
2085 .attr("x", $lx)
2086 .attr("y", $ly)
2087 .attr("text-anchor", "middle")
2088 .attr("font-size", "12px")
2089 .attr("fill", "#555")
2090 .text("$x_label_esc");
2091 XLB
2092 }
2093  
2094 # Optional grow-from-baseline animation on page load
2095 96 my $anim_block = '';
2096 96 ▶ if ($animated) {
Branch: 1 branch
BranchTrueFalseTotal
if ($animated) 4 92 96
2097 4 ▶ if ($orientation eq 'vertical') {
Branch: 1 branch
BranchTrueFalseTotal
if ($orientation eq 'vertical') { } 3 1 4
2098 3 $anim_block = <<"ANIM";
2099 var noAnim = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
2100 if (!noAnim) {
2101 var delayPer = data.length > 1 ? Math.min(100, 600 / (data.length - 1)) : 0;
2102 bars.attr("height", 0).attr("y", innerH)
2103 .transition().duration(800)
2104 .delay(function(d, i) { return i * delayPer; })
2105 .attr("height", function(d) { return Math.max(0, innerH - yScale(d.value)); })
2106 .attr("y", function(d) { return yScale(d.value); });
2107 }
2108 ANIM
2109 } else {
2110 1 $anim_block = <<"ANIM";
2111 var noAnim = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
2112 if (!noAnim) {
2113 var delayPer = data.length > 1 ? Math.min(100, 600 / (data.length - 1)) : 0;
2114 bars.attr("width", 0)
2115 .transition().duration(800)
2116 .delay(function(d, i) { return i * delayPer; })
2117 .attr("width", function(d) { return Math.max(0, xScale(d.value)); });
2118 }
2119 ANIM
2120 }
2121 }
2122  
2123 # Orientation-specific D3 scale/axis/bar JavaScript
2124 96 my $chart_js;
2125 96 ▶ if ($orientation eq 'vertical') {
Branch: 1 branch
BranchTrueFalseTotal
if ($orientation eq 'vertical') { } 92 4 96
2126 92 $chart_js = <<"JS";
2127 var g = svg.append("g")
2128 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
2129  
2130 var xScale = d3.scaleBand()
2131 .domain(data.map(function(d) { return d.label; }))
2132 .range([0, innerW])
2133 .padding(0.2);
2134 var yMax = d3.max(data, function(d) { return d.value; }) || 0;
2135 var yScale = d3.scaleLinear()
2136 .domain([0, yMax]).nice()
2137 .range([innerH, 0]);
2138  
2139 g.append("g").attr("class", "bc-x-axis")
2140 .attr("transform", "translate(0," + innerH + ")")
2141 .call(d3.axisBottom(xScale));
2142 g.append("g").attr("class", "bc-y-axis")
2143 .call(d3.axisLeft(yScale));
2144  
2145 $rotate_block var bars = g.selectAll(".bc-bar").data(data).join("rect")
2146 .attr("class", "bc-bar")
2147 .attr("x", function(d) { return xScale(d.label); })
2148 .attr("y", function(d) { return yScale(d.value); })
2149 .attr("width", xScale.bandwidth())
2150 .attr("height", function(d) { return Math.max(0, innerH - yScale(d.value)); })
2151 .attr("fill", $color_func_js)
2152 .attr("rx", 2)
2153 .on("mouseover", function(event, d) {
2154 var tc = "<strong>" + esc(d.label) + "<\\/strong><br>" + esc(valLabel) + ": " + d.value.toLocaleString();
2155 if (d.extra) {
2156 Object.entries(d.extra).forEach(function(kv) {
2157 tc += "<br>" + esc(kv[0]) + ": " + esc(String(kv[1]));
2158 });
2159 }
2160 tip.html(tc)
2161 .style("display", "block")
2162 .style("left", (event.pageX + 12) + "px")
2163 .style("top", (event.pageY - 24) + "px");
2164 })
2165 .on("mousemove", function(event) {
2166 tip.style("left", (event.pageX + 12) + "px")
2167 .style("top", (event.pageY - 24) + "px");
2168 })
2169 .on("mouseout", function() { tip.style("display", "none"); });
2170  
2171 $anim_block$show_values_block$x_label_block
2172 JS
2173 } else {
2174 4 $chart_js = <<"JS";
2175 var g = svg.append("g")
2176 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
2177  
2178 var yScale = d3.scaleBand()
2179 .domain(data.map(function(d) { return d.label; }))
2180 .range([0, innerH])
2181 .padding(0.2);
2182 var xMax = d3.max(data, function(d) { return d.value; }) || 0;
2183 var xScale = d3.scaleLinear()
2184 .domain([0, xMax]).nice()
2185 .range([0, innerW]);
2186  
2187 g.append("g").attr("class", "bc-x-axis")
2188 .attr("transform", "translate(0," + innerH + ")")
2189 .call(d3.axisBottom(xScale));
2190 g.append("g").attr("class", "bc-y-axis")
2191 .call(d3.axisLeft(yScale));
2192  
2193 var bars = g.selectAll(".bc-bar").data(data).join("rect")
2194 .attr("class", "bc-bar")
2195 .attr("x", 0)
2196 .attr("y", function(d) { return yScale(d.label); })
2197 .attr("width", function(d) { return Math.max(0, xScale(d.value)); })
2198 .attr("height", yScale.bandwidth())
2199 .attr("fill", $color_func_js)
2200 .attr("rx", 2)
2201 .on("mouseover", function(event, d) {
2202 var tc = "<strong>" + esc(d.label) + "<\\/strong><br>" + esc(valLabel) + ": " + d.value.toLocaleString();
2203 if (d.extra) {
2204 Object.entries(d.extra).forEach(function(kv) {
2205 tc += "<br>" + esc(kv[0]) + ": " + esc(String(kv[1]));
2206 });
2207 }
2208 tip.html(tc)
2209 .style("display", "block")
2210 .style("left", (event.pageX + 12) + "px")
2211 .style("top", (event.pageY - 24) + "px");
2212 })
2213 .on("mousemove", function(event) {
2214 tip.style("left", (event.pageX + 12) + "px")
2215 .style("top", (event.pageY - 24) + "px");
2216 })
2217 .on("mouseout", function() { tip.style("display", "none"); });
2218  
2219 $anim_block$show_values_block$x_label_block
2220 JS
2221 }
2222  
2223 96 my $html = <<"HTML";
2224 <style>
2225 #$svg_id { display: block; }
2226 #$tip_id {
2227 position: absolute;
2228 background: rgba(255,255,255,0.95);
2229 border: 1px solid #ccc;
2230 border-radius: 4px;
2231 padding: 6px 10px;
2232 font-size: 12px;
2233 pointer-events: none;
2234 display: none;
2235 line-height: 1.6;
2236 }
2237 .bc-bar { cursor: default; }
2238 .bc-bar:hover { opacity: 0.8; }
2239 .bc-val-text { pointer-events: none; }
2240 </style>
2241 <svg id="$svg_id" $svg_attrs></svg>
2242 <div id="$tip_id"></div>
2243 <script>
2244 (function() {
2245 var data = $json_data;
2246 var innerW = $inner_w;
2247 var innerH = $inner_h;
2248 var valLabel = "$value_label_esc";
2249 var margin = { top: $margin_top, right: $margin_right, bottom: $margin_bottom, left: $margin_left };
2250 $color_init_js
2251  
2252 function esc(s) {
2253 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2254 }
2255  
2256 var svg = d3.select("#$svg_id");
2257 var tip = d3.select("#$tip_id");
2258  
2259 $chart_js})();
2260 </script>
2261 HTML
2262  
2263 96 return { svg_id => $svg_id, html => $html };
2264 }
2265  
2266 =head2 render_line_chart_with_tooltips
2267  
2268 $html = $chart->render_line_chart_with_tooltips($data);
2269  
2270 Generates HTML and JavaScript code to render a line chart with mouseover tooltips.
2271 Accepts the following arguments:
2272  
2273 =over 4
2274  
2275 =item * C<$data> - An array reference containing data points. Each data point should
2276 be an array reference with two elements: the label (string) and the value (numeric).
2277  
2278 =back
2279  
2280 Returns a string containing the HTML and JavaScript code for the chart.
2281 The JavaScript tooltip strings use C<< <\/b> >> (with a backslash) rather than
2282 C<< </b> >> to satisfy html-tidy's requirement that C<< </ >> followed by a
2283 letter not appear literally inside C<< <script> >> blocks.
2284  
2285 =head3 Errors
2286  
2287 =over 4
2288  
2289 =item * Throws C<Data must be an array of arrays> when C<$data> is not an ARRAY reference.
2290  
2291 =back
2292  
2293 =head3 API SPECIFICATION
2294  
2295 =head4 Input
2296  
2297 {
2298 data => { type => 'arrayref' },
2299 }
2300  
2301 Each element of C<$data> is C<[ Str, Num ]>; passing C<undef> or a
2302 non-arrayref dies.
2303  
2304 =head4 Output
2305  
2306 Str -- complete HTML5 document; mouseover tooltip reveals label and value.
2307 Tooltip strings use C<< <\/b> >> not C<< </b> >>.
2308  
2309 =cut
2310  
2311 sub render_line_chart_with_tooltips
2312 6 ▶{
Subroutine render_line_chart_with_tooltips: called CC=3 SCAR=11.0
Pod documented
2313 6 my $self = shift;
2314 6 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
60
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
2315 6 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 4 6
2316 4 Params::Validate::Strict::validate_strict({
2317 args => $raw,
2318 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
2319 unknown_parameter_handler => 'ignore',
2320 });
2321 4 my $data = $raw->{data};
2322  
2323 # Generate JSON for data
2324 my $json_data = _script_json([
2325 4 map { { label => $_->[0], value => $_->[1] } } @$data
2326 ]);
2327  
2328 # Generate HTML and D3.js code
2329 4 my $html = $self->_preamble();
2330 4 $html .= <<"HTML";
2331 <head>
2332 <meta charset="UTF-8">
2333 <meta name="viewport" content="width=device-width, initial-scale=1.0">
2334 4 <title>@{[ $self->_title_html() ]}</title>
2335 <script src="https://d3js.org/d3.v7.min.js"></script>
2336 <style>
2337 .tooltip {
2338 position: absolute;
2339 background-color: white;
2340 border: 1px solid #ccc;
2341 padding: 5px;
2342 font-size: 12px;
2343 pointer-events: none;
2344 opacity: 0;
2345 transition: opacity 0.2s ease-in-out;
2346 }
2347 </style>
2348 </head>
2349 <body>
2350 4 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
2351 4 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
2352 <div class="tooltip" id="tooltip"></div>
2353 <script>
2354 const data = $json_data;
2355  
2356 const svg = d3.select("#chart");
2357 const tooltip = d3.select("#tooltip");
2358 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
2359 const width = $self->{width} - margin.left - margin.right;
2360 const height = $self->{height} - margin.top - margin.bottom;
2361  
2362 const x = d3.scalePoint()
2363 .domain(data.map(d => d.label))
2364 .range([0, width]);
2365  
2366 const y = d3.scaleLinear()
2367 .domain([0, d3.max(data, d => d.value)])
2368 .nice()
2369 .range([height, 0]);
2370  
2371 const chart = svg.append("g")
2372 .attr("transform", `translate(\${margin.left},\${margin.top})`);
2373  
2374 // Draw line
2375 const line = d3.line()
2376 .x(d => x(d.label))
2377 .y(d => y(d.value));
2378  
2379 chart.append("path")
2380 .datum(data)
2381 .attr("fill", "none")
2382 .attr("stroke", "steelblue")
2383 .attr("stroke-width", 2)
2384 .attr("d", line);
2385  
2386 // Add points to the line
2387 chart.selectAll("circle")
2388 .data(data)
2389 .join("circle")
2390 .attr("cx", d => x(d.label))
2391 .attr("cy", d => y(d.value))
2392 .attr("r", 4)
2393 .attr("fill", "steelblue")
2394 .on("mouseover", (event, d) => {
2395 tooltip.style("opacity", 1)
2396 .html(`Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>`)
2397 .style("left", (event.pageX + 10) + "px")
2398 .style("top", (event.pageY - 30) + "px");
2399 })
2400 .on("mousemove", (event) => {
2401 tooltip.style("left", (event.pageX + 10) + "px")
2402 .style("top", (event.pageY - 30) + "px");
2403 })
2404 .on("mouseout", () => {
2405 tooltip.style("opacity", 0);
2406 });
2407  
2408 // Add axes
2409 chart.append("g")
2410 .call(d3.axisLeft(y));
2411  
2412 chart.append("g")
2413 .attr("transform", `translate(0,\${height})`)
2414 .call(d3.axisBottom(x))
2415 .selectAll("text")
2416 .attr("transform", "rotate(-45)")
2417 .style("text-anchor", "end");
2418 </script>
2419 </body>
2420 </html>
2421 HTML
2422  
2423 4 return $html;
2424 }
2425  
2426 =head2 render_line_chart_snippet
2427  
2428 my $fragment = $chart->render_line_chart_snippet($data);
2429 my $fragment = $chart->render_line_chart_snippet($data, \%opts);
2430 # $fragment->{svg_id} - the id attribute of the <svg> element
2431 # $fragment->{html} - embeddable HTML fragment (style + svg + script)
2432  
2433 Generates an embeddable HTML fragment for a line chart with mouseover tooltips.
2434 Unlike C<render_line_chart_with_tooltips>, this method returns a fragment with
2435 no C<<!DOCTYPE>>, C<<html>>, C<<head>>, or C<<body>> wrapper, suitable for
2436 splicing directly into a Mojolicious TT (or any other) layout.
2437  
2438 The caller is responsible for loading D3 in the page C<<head>>, e.g.:
2439  
2440 <script src="https://d3js.org/d3.v7.min.js"></script>
2441  
2442 =head3 Arguments
2443  
2444 =over 4
2445  
2446 =item * C<$data> - An array reference of data points. Each point is an array
2447 reference with two required elements - the label (string) and the value
2448 (numeric) - and an optional third element: a hash reference of extra key/value
2449 pairs to display in the tooltip after the label and value rows.
2450  
2451 [$x, $y] # basic point
2452 [$x, $y, \%row] # point with extra tooltip data
2453  
2454 =item * C<\%opts> - Optional hash reference of rendering options:
2455  
2456 =over 4
2457  
2458 =item * C<id> (string, default C<'chart'>) - Override the C<id> attribute of
2459 the C<<svg>> element. Use this when embedding multiple charts on the same page.
2460  
2461 =item * C<responsive> (boolean, default C<0>) - If true, emit
2462 C<viewBox="0 0 W H" width="100%">, with no C<height>, instead of fixed pixel
2463 dimensions, so the chart scales with its container. Falls back to
2464 C<< $self->{responsive} >> when not set per call.
2465  
2466 =back
2467  
2468 =back
2469  
2470 =head3 Return value
2471  
2472 A hash reference with:
2473  
2474 =over 4
2475  
2476 =item * C<svg_id> - The C<id> attribute used on the C<<svg>> element.
2477  
2478 =item * C<html> - The embeddable fragment string (Perl character string).
2479  
2480 =back
2481  
2482 =head3 Errors
2483  
2484 =over 4
2485  
2486 =item * Dies with C<'Data must be an array of arrays'> when C<$data> is not an
2487 ARRAY reference.
2488  
2489 =back
2490  
2491 =head3 Side effects
2492  
2493 None. The method is read-only.
2494  
2495 =head3 API SPECIFICATION
2496  
2497 {
2498 data => { type => 'arrayref' },
2499 opts => {
2500 type => 'hashref',
2501 optional => 1,
2502 keys => {
2503 id => { type => 'string', optional => 1 },
2504 responsive => { type => 'boolean', optional => 1 },
2505 },
2506 },
2507 }
2508  
2509 =cut
2510  
2511 sub render_line_chart_snippet
2512 36 ▶{
Subroutine render_line_chart_snippet: called CC=7 SCAR=19.5
Pod documented
2513 36 my $self = shift;
2514 36 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
360
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
2515 36 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 33 36
2516 33 Params::Validate::Strict::validate_strict({
2517 args => $raw,
2518 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
2519 unknown_parameter_handler => 'ignore',
2520 });
2521 33 my $data = $raw->{data};
2522 33 my $opts = {%$raw}; delete $opts->{data};
2523  
2524 my $json_data = _script_json([
2525 map {
2526 33 my $point = { label => $_->[0], value => $_->[1] };
2527 78 ▶ $point->{extra} = $_->[2] if ref($_->[2]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_->[2] eq "HASH" 3 75 78
2528 78 $point
2529 } @$data
2530 ]);
2531  
2532 33 ▶ my $svg_id = _chart_id($opts->{id}) // 'chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "chart"
l!l
627
MC/DC100%1/1
_chart_id($opts->{"id"}) // "chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
2533 33 my $tip_id = $svg_id . '_tooltip';
2534 33 my $w = $self->{width};
2535 33 my $h = $self->{height};
2536 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
2537 33 ▶ ? qq{viewBox="0 0 $w $h" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 2 31 33
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
1320
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
2538 : qq{width="$w" height="$h" style="border: 1px solid black;"};
2539  
2540 33 my $html = <<"HTML";
2541 <style>
2542 .tooltip {
2543 position: absolute;
2544 background-color: white;
2545 border: 1px solid #ccc;
2546 padding: 5px;
2547 font-size: 12px;
2548 pointer-events: none;
2549 opacity: 0;
2550 transition: opacity 0.2s ease-in-out;
2551 }
2552 </style>
2553 <svg id="$svg_id" $svg_attrs></svg>
2554 <div class="tooltip" id="$tip_id"></div>
2555 <script>
2556 const data = $json_data;
2557  
2558 const svg = d3.select("#$svg_id");
2559 const tooltip = d3.select("#$tip_id");
2560 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
2561 const width = $w - margin.left - margin.right;
2562 const height = $h - margin.top - margin.bottom;
2563  
2564 const x = d3.scalePoint()
2565 .domain(data.map(d => d.label))
2566 .range([0, width]);
2567  
2568 const y = d3.scaleLinear()
2569 .domain([0, d3.max(data, d => d.value)])
2570 .nice()
2571 .range([height, 0]);
2572  
2573 const chart = svg.append("g")
2574 .attr("transform", `translate(\${margin.left},\${margin.top})`);
2575  
2576 const line = d3.line()
2577 .x(d => x(d.label))
2578 .y(d => y(d.value));
2579  
2580 chart.append("path")
2581 .datum(data)
2582 .attr("fill", "none")
2583 .attr("stroke", "steelblue")
2584 .attr("stroke-width", 2)
2585 .attr("d", line);
2586  
2587 chart.selectAll("circle")
2588 .data(data)
2589 .join("circle")
2590 .attr("cx", d => x(d.label))
2591 .attr("cy", d => y(d.value))
2592 .attr("r", 4)
2593 .attr("fill", "steelblue")
2594 .on("mouseover", (event, d) => {
2595 let ttHtml = `Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>`;
2596 if (d.extra) {
2597 Object.entries(d.extra).forEach(([k, v]) => {
2598 ttHtml += `<br>\${k}: <b>\${v}<\\/b>`;
2599 });
2600 }
2601 tooltip.style("opacity", 1)
2602 .html(ttHtml)
2603 .style("left", (event.pageX + 10) + "px")
2604 .style("top", (event.pageY - 30) + "px");
2605 })
2606 .on("mousemove", (event) => {
2607 tooltip.style("left", (event.pageX + 10) + "px")
2608 .style("top", (event.pageY - 30) + "px");
2609 })
2610 .on("mouseout", () => {
2611 tooltip.style("opacity", 0);
2612 });
2613  
2614 chart.append("g")
2615 .call(d3.axisLeft(y));
2616  
2617 chart.append("g")
2618 .attr("transform", `translate(0,\${height})`)
2619 .call(d3.axisBottom(x))
2620 .selectAll("text")
2621 .attr("transform", "rotate(-45)")
2622 .style("text-anchor", "end");
2623 </script>
2624 HTML
2625  
2626 33 return { svg_id => $svg_id, html => $html };
2627 }
2628  
2629 =head2 render_zoomable_line_chart_snippet
2630  
2631 my $fragment = $chart->render_zoomable_line_chart_snippet($data);
2632 my $fragment = $chart->render_zoomable_line_chart_snippet($data, { animated => 1 });
2633 # $fragment->{svg_id} - the id attribute of the <svg> element
2634 # $fragment->{html} - embeddable HTML fragment (style + button + svg + script)
2635  
2636 Like C<render_line_chart_snippet>, but adds brush-to-zoom: the user can drag
2637 across a range of the x-axis to zoom into that region. A I<Reset zoom> button
2638 (hidden until a zoom is active) returns the chart to its original extent.
2639 Subsequent brushes on the zoomed view zoom in further; Reset always returns to
2640 the full dataset.
2641  
2642 The caller is responsible for loading D3 in the page C<<head>>.
2643  
2644 Accepts the same arguments as C<render_line_chart_snippet>: an array reference
2645 of data points, each C<[$x, $y]> or C<[$x, $y, \%extra]>, plus an optional
2646 second argument C<$opts> (hashref).
2647  
2648 =head3 Options
2649  
2650 =over 4
2651  
2652 =item * C<animated> (boolean, default C<0>) - when true, the initial page load
2653 animates the line drawing left-to-right via the C<stroke-dashoffset> technique
2654 (1200 ms, C<d3.easeLinear>), then fades in data-point circles after the line
2655 finishes (300 ms after a 1200 ms delay). Respects
2656 C<prefers-reduced-motion>: when the user has requested reduced motion the line
2657 is drawn immediately at full opacity. Subsequent zoom and reset redraws are
2658 never animated regardless of this flag.
2659  
2660 =back
2661  
2662 =head3 API SPECIFICATION
2663  
2664 =head4 Input
2665  
2666 {
2667 data => { type => 'arrayref' },
2668 opts => { type => 'hashref', optional => 1, default => {} },
2669 }
2670  
2671 Each element of C<$data> is C<[ Str, Num ]> or C<[ Str, Num, HashRef ]>;
2672 passing C<undef> or a non-arrayref dies.
2673 Recognised C<opts> key: C<animated> (boolean, default C<0>).
2674  
2675 =head4 Output
2676  
2677 HashRef -- C<{ svg_id =E<gt> 'chart', html =E<gt> Str }>;
2678 embeddable fragment; no DOCTYPE, no page shell, no D3 CDN tag.
2679  
2680 =head3 Errors
2681  
2682 Dies with I<Data must be an array of arrays> if C<$data> is not an arrayref.
2683  
2684 =cut
2685  
2686 sub render_zoomable_line_chart_snippet
2687 43 ▶{
Subroutine render_zoomable_line_chart_snippet: called CC=9 SCAR=22.0
Pod documented
2688 43 my $self = shift;
2689 43 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
430
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
2690 43 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 5 38 43
2691 38 Params::Validate::Strict::validate_strict({
2692 args => $raw,
2693 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
2694 unknown_parameter_handler => 'ignore',
2695 });
2696 38 my $data = $raw->{data};
2697 38 my $opts = {%$raw}; delete $opts->{data};
2698  
2699 my $json_data = _script_json([
2700 map {
2701 38 my $point = { label => $_->[0], value => $_->[1] };
2702 101 ▶ $point->{extra} = $_->[2] if ref($_->[2]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_->[2] eq "HASH" 2 99 101
2703 101 $point
2704 } @$data
2705 ]);
2706  
2707 38 ▶ my $svg_id = _chart_id($opts->{id}) // 'chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "chart"
l!l
632
MC/DC100%1/1
_chart_id($opts->{"id"}) // "chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
2708 38 my $tip_id = $svg_id . '_tooltip';
2709 38 my $rst_id = $svg_id . '_reset';
2710 38 my $w = $self->{width};
2711 38 my $h = $self->{height};
2712 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
2713 38 ▶ ? qq{viewBox="0 0 $w $h" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 2 36 38
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
1370
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
2714 : qq{width="$w" height="$h" style="border: 1px solid black;"};
2715  
2716 # Single-quote heredoc so <\/b> is preserved verbatim in the output —
2717 # double-quote would require <\\/b> to survive Perl interpolation.
2718 38 my $circle_handlers = <<'HANDLERS';
2719 .on("mouseover", (event, d) => {
2720 let ttHtml = `Label: <b>${d.label}<\/b><br>Value: <b>${d.value}<\/b>`;
2721 if (d.extra) {
2722 Object.entries(d.extra).forEach(([k, v]) => {
2723 ttHtml += `<br>${k}: <b>${v}<\/b>`;
2724 });
2725 }
2726 tooltip.style("opacity", 1)
2727 .html(ttHtml)
2728 .style("left", (event.pageX + 10) + "px")
2729 .style("top", (event.pageY - 30) + "px");
2730 })
2731 .on("mousemove", (event) => {
2732 tooltip.style("left", (event.pageX + 10) + "px")
2733 .style("top", (event.pageY - 30) + "px");
2734 })
2735 .on("mouseout", () => {
2736 tooltip.style("opacity", 0);
2737 })
2738 HANDLERS
2739  
2740 38 ▶ my $init_flag = $opts->{animated} ? 'let initialDrawDone = false;' : '';
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'animated'} ? : 4 34 38
2741  
2742 38 my $redraw_body;
2743 38 ▶ if ($opts->{animated}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{'animated'}) { } 4 34 38
2744 4 $redraw_body = <<"ANIM";
2745 if (!initialDrawDone) {
2746 var prefersReduced = window.matchMedia &&
2747 window.matchMedia('(prefers-reduced-motion: reduce)').matches;
2748 linePath.datum(newData).attr("d", lineFn);
2749 if (prefersReduced) {
2750 linePath.attr("stroke-dasharray", null).attr("stroke-dashoffset", null);
2751 } else {
2752 const L = linePath.node().getTotalLength();
2753 linePath
2754 .attr("stroke-dasharray", L)
2755 .attr("stroke-dashoffset", L)
2756 .transition()
2757 .duration(1200)
2758 .ease(d3.easeLinear)
2759 .attr("stroke-dashoffset", 0);
2760 }
2761 chart.selectAll("circle.pt")
2762 .data(newData, d => d.label)
2763 .join(
2764 enter => enter.append("circle")
2765 .attr("class", "pt")
2766 .attr("r", 4)
2767 .attr("fill", "steelblue")
2768 .attr("cx", d => x(d.label))
2769 .attr("cy", d => y(d.value))
2770 .attr("opacity", prefersReduced ? 1 : 0)
2771 )
2772 $circle_handlers .transition()
2773 .duration(prefersReduced ? 0 : 300)
2774 .delay(prefersReduced ? 0 : 1200)
2775 .attr("opacity", 1);
2776 initialDrawDone = true;
2777 } else {
2778 linePath.datum(newData).transition(t).attr("d", lineFn);
2779 chart.selectAll("circle.pt")
2780 .data(newData, d => d.label)
2781 .join(
2782 enter => enter.append("circle")
2783 .attr("class", "pt")
2784 .attr("r", 4)
2785 .attr("fill", "steelblue")
2786 .attr("cx", d => x(d.label))
2787 .attr("cy", d => y(d.value))
2788 )
2789 $circle_handlers .transition(t)
2790 .attr("cx", d => x(d.label))
2791 .attr("cy", d => y(d.value));
2792 }
2793 ANIM
2794 } else {
2795 34 $redraw_body = <<"PLAIN";
2796 linePath.datum(newData).transition(t).attr("d", lineFn);
2797  
2798 chart.selectAll("circle.pt")
2799 .data(newData, d => d.label)
2800 .join(
2801 enter => enter.append("circle")
2802 .attr("class", "pt")
2803 .attr("r", 4)
2804 .attr("fill", "steelblue")
2805 .attr("cx", d => x(d.label))
2806 .attr("cy", d => y(d.value))
2807 )
2808 $circle_handlers .transition(t)
2809 .attr("cx", d => x(d.label))
2810 .attr("cy", d => y(d.value));
2811 PLAIN
2812 }
2813  
2814 38 my $html = <<"HTML";
2815 <style>
2816 .tooltip {
2817 position: absolute;
2818 background-color: white;
2819 border: 1px solid #ccc;
2820 padding: 5px;
2821 font-size: 12px;
2822 pointer-events: none;
2823 opacity: 0;
2824 transition: opacity 0.2s ease-in-out;
2825 }
2826 #$rst_id {
2827 display: none;
2828 margin-bottom: 4px;
2829 cursor: pointer;
2830 }
2831 .brush .selection {
2832 fill: steelblue;
2833 fill-opacity: 0.15;
2834 stroke: steelblue;
2835 stroke-width: 1;
2836 }
2837 </style>
2838 <button id="$rst_id">Reset zoom</button>
2839 <svg id="$svg_id" $svg_attrs></svg>
2840 <div class="tooltip" id="$tip_id"></div>
2841 <script>
2842 const allData = $json_data;
2843 let currentData = allData.slice();
2844  
2845 const svg = d3.select("#$svg_id");
2846 const tooltip = d3.select("#$tip_id");
2847 const resetBtn = d3.select("#$rst_id");
2848 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
2849 const width = $w - margin.left - margin.right;
2850 const height = $h - margin.top - margin.bottom;
2851  
2852 const chart = svg.append("g")
2853 .attr("transform", `translate(\${margin.left},\${margin.top})`);
2854  
2855 // Scales (domain set in redraw)
2856 const x = d3.scalePoint().range([0, width]);
2857 const y = d3.scaleLinear().range([height, 0]);
2858  
2859 const lineFn = d3.line()
2860 .x(d => x(d.label))
2861 .y(d => y(d.value));
2862  
2863 // Brush appended first so circles sit above it and receive mouse events
2864 const brush = d3.brushX()
2865 .extent([[0, 0], [width, height]])
2866 .on("end", brushed);
2867 const brushGroup = chart.append("g").attr("class", "brush").call(brush);
2868  
2869 const linePath = chart.append("path")
2870 .attr("fill", "none")
2871 .attr("stroke", "steelblue")
2872 .attr("stroke-width", 2);
2873  
2874 const yAxisG = chart.append("g");
2875 const xAxisG = chart.append("g").attr("transform", `translate(0,\${height})`);
2876  
2877 $init_flag
2878  
2879 function redraw(newData, ms) {
2880 x.domain(newData.map(d => d.label));
2881 y.domain([Math.min(0, d3.min(newData, d => d.value)), d3.max(newData, d => d.value)]).nice();
2882  
2883 const t = svg.transition().duration(ms);
2884  
2885 xAxisG.transition(t)
2886 .call(d3.axisBottom(x))
2887 .selectAll("text")
2888 .attr("transform", "rotate(-45)")
2889 .style("text-anchor", "end");
2890  
2891 yAxisG.transition(t).call(d3.axisLeft(y));
2892  
2893 $redraw_body }
2894  
2895 redraw(currentData, 0);
2896  
2897 function brushed(event) {
2898 if (!event.selection) return;
2899 const [x0, x1] = event.selection;
2900 const zoomed = currentData.filter(d => {
2901 const px = x(d.label);
2902 return px >= x0 - 1 && px <= x1 + 1;
2903 });
2904 brushGroup.call(brush.move, null); // clear brush rectangle
2905 if (zoomed.length < 2) return;
2906 currentData = zoomed;
2907 redraw(currentData, 500);
2908 resetBtn.style("display", "inline-block");
2909 }
2910  
2911 resetBtn.on("click", () => {
2912 currentData = allData.slice();
2913 redraw(currentData, 500);
2914 resetBtn.style("display", "none");
2915 });
2916 </script>
2917 HTML
2918  
2919 38 return { svg_id => $svg_id, html => $html };
2920 }
2921  
2922 =head2 render_multi_series_line_chart_with_tooltips
2923  
2924 $html = $chart->render_multi_series_line_chart_with_tooltips($data);
2925  
2926 Generates HTML and JavaScript code to render a chart of many lines with mouseover tooltips.
2927  
2928 Accepts the following arguments:
2929  
2930 =over 4
2931  
2932 =item * C<$data> - An array reference of series hashes. Each element is a hashref
2933 with a C<name> key (string) and a C<data> key (array reference of C<< {label, value} >>
2934 hashrefs).
2935  
2936 [
2937 { name => 'Series A', data => [{ label => 'Jan', value => 100 }, ...] },
2938 ...
2939 ]
2940  
2941 =back
2942  
2943 Returns a string containing the HTML and JavaScript code for the chart.
2944 Tooltip strings use C<< <\/b> >> rather than C<< </b> >> for html-tidy compliance.
2945  
2946 =head3 Errors
2947  
2948 =over 4
2949  
2950 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
2951  
2952 =back
2953  
2954 =head3 API SPECIFICATION
2955  
2956 =head4 Input
2957  
2958 {
2959 data => { type => 'arrayref' },
2960 }
2961  
2962 Each element of C<$data> is a hashref with keys C<name> (string) and
2963 C<data> (arrayref of hashrefs with C<label> and C<value> keys);
2964 passing C<undef> or a non-arrayref dies.
2965  
2966 =head4 Output
2967  
2968 Str -- complete HTML5 document; one coloured line per series with mouseover tooltips.
2969  
2970 =cut
2971  
2972 sub render_multi_series_line_chart_with_tooltips
2973 6 ▶{
Subroutine render_multi_series_line_chart_with_tooltips: called CC=3 SCAR=11.0
Pod documented
2974 6 my $self = shift;
2975 6 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
60
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
2976 6 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 4 6
2977 4 Params::Validate::Strict::validate_strict({
2978 args => $raw,
2979 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
2980 unknown_parameter_handler => 'ignore',
2981 });
2982 4 my $data = $raw->{data};
2983  
2984 4 my $json_data = _script_json($data);
2985  
2986 # Generate HTML and D3.js code
2987 4 my $html = $self->_preamble();
2988 4 $html .= <<"HTML";
2989 <head>
2990 <meta charset="UTF-8">
2991 <meta name="viewport" content="width=device-width, initial-scale=1.0">
2992 4 <title>@{[ $self->_title_html() ]}</title>
2993 <script src="https://d3js.org/d3.v7.min.js"></script>
2994 <style>
2995 .tooltip {
2996 position: absolute;
2997 background-color: white;
2998 border: 1px solid #ccc;
2999 padding: 5px;
3000 font-size: 12px;
3001 pointer-events: none;
3002 opacity: 0;
3003 transition: opacity 0.2s ease-in-out;
3004 }
3005 </style>
3006 </head>
3007 <body>
3008 4 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
3009 4 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
3010 <div class="tooltip" id="tooltip"></div>
3011 <script>
3012 const data = $json_data;
3013  
3014 const svg = d3.select("#chart");
3015 const tooltip = d3.select("#tooltip");
3016 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
3017 const width = $self->{width} - margin.left - margin.right;
3018 const height = $self->{height} - margin.top - margin.bottom;
3019  
3020 const chart = svg.append("g")
3021 .attr("transform", `translate(\${margin.left},\${margin.top})`);
3022  
3023 // Extract all labels and flatten them into a unique array
3024 const allLabels = Array.from(new Set(data.flatMap(series => series.data.map(d => d.label))));
3025  
3026 const x = d3.scalePoint()
3027 .domain(allLabels)
3028 .range([0, width]);
3029  
3030 const y = d3.scaleLinear()
3031 .domain([0, d3.max(data.flatMap(series => series.data.map(d => d.value)))])
3032 .nice()
3033 .range([height, 0]);
3034  
3035 // Define color scale for series
3036 const color = d3.scaleOrdinal($CATEGORY10_JS);
3037  
3038 // Add axes
3039 chart.append("g")
3040 .call(d3.axisLeft(y));
3041  
3042 chart.append("g")
3043 .attr("transform", `translate(0,\${height})`)
3044 .call(d3.axisBottom(x))
3045 .selectAll("text")
3046 .attr("transform", "rotate(-45)")
3047 .style("text-anchor", "end");
3048  
3049 // Draw lines for each series
3050 data.forEach((series, i) => {
3051 const line = d3.line()
3052 .x(d => x(d.label))
3053 .y(d => y(d.value));
3054  
3055 // Add line
3056 chart.append("path")
3057 .datum(series.data)
3058 .attr("fill", "none")
3059 .attr("stroke", color(i))
3060 .attr("stroke-width", 2)
3061 .attr("d", line);
3062  
3063 // Add points and tooltips
3064 chart.selectAll(\`circle.series-\${i}\`)
3065 .data(series.data)
3066 .join("circle")
3067 .attr("class", \`series-\${i}\`)
3068 .attr("cx", d => x(d.label))
3069 .attr("cy", d => y(d.value))
3070 .attr("r", 4)
3071 .attr("fill", color(i))
3072 .on("mouseover", (event, d) => {
3073 tooltip.style("opacity", 1)
3074 .html(\`Series: <b>\${series.name}<\\/b><br>Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>\`)
3075 .style("left", (event.pageX + 10) + "px")
3076 .style("top", (event.pageY - 30) + "px");
3077 })
3078 .on("mousemove", (event) => {
3079 tooltip.style("left", (event.pageX + 10) + "px")
3080 .style("top", (event.pageY - 30) + "px");
3081 })
3082 .on("mouseout", () => {
3083 tooltip.style("opacity", 0);
3084 });
3085 });
3086 </script>
3087 </body>
3088 </html>
3089 HTML
3090  
3091 4 return $html;
3092 }
3093  
3094 =head2 render_multi_series_line_chart_with_animated_tooltips
3095  
3096 $html = $chart->render_multi_series_line_chart_with_animated_tooltips($data);
3097  
3098 Generates HTML and JavaScript code to render a chart of many lines with animated mouseover tooltips.
3099  
3100 Accepts the following arguments:
3101  
3102 =over 4
3103  
3104 =item * C<$data> - Same format as C<render_multi_series_line_chart_with_tooltips>:
3105 an array reference of C<< { name, data } >> series hashes.
3106  
3107 =back
3108  
3109 Returns a string containing the complete HTML5 document.
3110 The tooltip appears with a CSS C<translateY> slide-in animation.
3111 Tooltip strings use C<< <\/b> >> for html-tidy compliance.
3112  
3113 =head3 Errors
3114  
3115 =over 4
3116  
3117 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
3118  
3119 =back
3120  
3121 =head3 API SPECIFICATION
3122  
3123 =head4 Input
3124  
3125 {
3126 data => { type => 'arrayref' },
3127 }
3128  
3129 Each element of C<$data> is a hashref with keys C<name> (string) and
3130 C<data> (arrayref of hashrefs with C<label> and C<value> keys);
3131 passing C<undef> or a non-arrayref dies.
3132  
3133 =head4 Output
3134  
3135 Str -- complete HTML5 document; animated tooltip uses CSS translateY transition.
3136  
3137 =cut
3138  
3139 sub render_multi_series_line_chart_with_animated_tooltips
3140 6 ▶{
Subroutine render_multi_series_line_chart_with_animated_tooltips: called CC=3 SCAR=11.0
Pod documented
3141 6 my $self = shift;
3142 6 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
60
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
3143 6 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 4 6
3144 4 Params::Validate::Strict::validate_strict({
3145 args => $raw,
3146 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
3147 unknown_parameter_handler => 'ignore',
3148 });
3149 4 my $data = $raw->{data};
3150  
3151 # Generate JSON for data
3152 4 my $json_data = _script_json($data);
3153  
3154 # Generate HTML and D3.js code
3155 4 my $html = $self->_preamble();
3156 4 $html .= <<"HTML";
3157 <head>
3158 <meta charset="UTF-8">
3159 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3160 4 <title>@{[ $self->_title_html() ]}</title>
3161 <script src="https://d3js.org/d3.v7.min.js"></script>
3162 <style>
3163 .tooltip {
3164 position: absolute;
3165 background-color: white;
3166 border: 1px solid #ccc;
3167 padding: 5px;
3168 font-size: 12px;
3169 pointer-events: none;
3170 opacity: 0;
3171 transform: translateY(-10px);
3172 transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
3173 }
3174 </style>
3175 </head>
3176 <body>
3177 4 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
3178 4 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
3179 <div class="tooltip" id="tooltip"></div>
3180 <script>
3181 const data = $json_data;
3182  
3183 const svg = d3.select("#chart");
3184 const tooltip = d3.select("#tooltip");
3185 const margin = { top: 20, right: 30, bottom: 40, left: 40 };
3186 const width = $self->{width} - margin.left - margin.right;
3187 const height = $self->{height} - margin.top - margin.bottom;
3188  
3189 const chart = svg.append("g")
3190 .attr("transform", `translate(\${margin.left},\${margin.top})`);
3191  
3192 // Extract all labels and flatten them into a unique array
3193 const allLabels = Array.from(new Set(data.flatMap(series => series.data.map(d => d.label))));
3194  
3195 const x = d3.scalePoint()
3196 .domain(allLabels)
3197 .range([0, width]);
3198  
3199 const y = d3.scaleLinear()
3200 .domain([0, d3.max(data.flatMap(series => series.data.map(d => d.value)))])
3201 .nice()
3202 .range([height, 0]);
3203  
3204 // Define color scale for series
3205 const color = d3.scaleOrdinal($CATEGORY10_JS);
3206  
3207 // Add axes
3208 chart.append("g")
3209 .call(d3.axisLeft(y));
3210  
3211 chart.append("g")
3212 .attr("transform", `translate(0,\${height})`)
3213 .call(d3.axisBottom(x))
3214 .selectAll("text")
3215 .attr("transform", "rotate(-45)")
3216 .style("text-anchor", "end");
3217  
3218 // Draw lines for each series
3219 data.forEach((series, i) => {
3220 const line = d3.line()
3221 .x(d => x(d.label))
3222 .y(d => y(d.value));
3223  
3224 // Add line
3225 chart.append("path")
3226 .datum(series.data)
3227 .attr("fill", "none")
3228 .attr("stroke", color(i))
3229 .attr("stroke-width", 2)
3230 .attr("d", line);
3231  
3232 // Add points and tooltips
3233 chart.selectAll(\`circle.series-\${i}\`)
3234 .data(series.data)
3235 .join("circle")
3236 .attr("class", \`series-\${i}\`)
3237 .attr("cx", d => x(d.label))
3238 .attr("cy", d => y(d.value))
3239 .attr("r", 4)
3240 .attr("fill", color(i))
3241 .on("mouseover", (event, d) => {
3242 tooltip.style("opacity", 1)
3243 .style("transform", "translateY(0)")
3244 .html(\`Series: <b>\${series.name}<\\/b><br>Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>\`)
3245 .style("left", (event.pageX + 10) + "px")
3246 .style("top", (event.pageY - 30) + "px");
3247 })
3248 .on("mousemove", (event) => {
3249 tooltip.style("left", (event.pageX + 10) + "px")
3250 .style("top", (event.pageY - 30) + "px");
3251 })
3252 .on("mouseout", () => {
3253 tooltip.style("opacity", 0)
3254 .style("transform", "translateY(-10px)");
3255 });
3256 });
3257 </script>
3258 </body>
3259 </html>
3260 HTML
3261  
3262 4 return $html;
3263 }
3264  
3265 =head2 render_multi_series_line_chart_with_legends
3266  
3267 $html = $chart->render_multi_series_line_chart_with_legends($data);
3268  
3269 Generates HTML and JavaScript code to render a chart of many lines with a static
3270 colour legend. Each series gets a labelled colour swatch in the legend area.
3271  
3272 Accepts the following arguments:
3273  
3274 =over 4
3275  
3276 =item * C<$data> - Same format as C<render_multi_series_line_chart_with_tooltips>:
3277 an array reference of C<< { name, data } >> series hashes.
3278  
3279 =back
3280  
3281 Returns a string containing the complete HTML5 document. The stylesheet defines
3282 a C<.legend> CSS class used by the D3-generated legend elements.
3283  
3284 =head3 Errors
3285  
3286 =over 4
3287  
3288 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
3289  
3290 =back
3291  
3292 =head3 API SPECIFICATION
3293  
3294 =head4 Input
3295  
3296 {
3297 data => { type => 'arrayref' },
3298 }
3299  
3300 Each element of C<$data> is a hashref with keys C<name> (string) and
3301 C<data> (arrayref of hashrefs with C<label> and C<value> keys);
3302 passing C<undef> or a non-arrayref dies.
3303  
3304 =head4 Output
3305  
3306 Str -- complete HTML5 document; static colour legend rendered as SVG C<g> elements
3307 with the C<.legend> CSS class applied via D3 C<.attr("class", "legend")>.
3308  
3309 =cut
3310  
3311 6 ▶sub render_multi_series_line_chart_with_legends {
Subroutine render_multi_series_line_chart_with_legends: called CC=3 SCAR=11.0
Pod documented
3312 6 my $self = shift;
3313 6 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
60
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
3314 6 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 4 6
3315 4 Params::Validate::Strict::validate_strict({
3316 args => $raw,
3317 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
3318 unknown_parameter_handler => 'ignore',
3319 });
3320 4 my $data = $raw->{data};
3321  
3322 # Generate JSON for data
3323 4 my $json_data = _script_json($data);
3324  
3325 # Generate HTML and D3.js code
3326 4 my $html = $self->_preamble();
3327 4 $html .= <<"HTML";
3328 <head>
3329 <meta charset="UTF-8">
3330 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3331 4 <title>@{[ $self->_title_html() ]}</title>
3332 <script src="https://d3js.org/d3.v7.min.js"></script>
3333 <style>
3334 .tooltip {
3335 position: absolute;
3336 background-color: white;
3337 border: 1px solid #ccc;
3338 padding: 5px;
3339 font-size: 12px;
3340 pointer-events: none;
3341 opacity: 0;
3342 transform: translateY(-10px);
3343 transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
3344 }
3345 .legend {
3346 font-size: 12px;
3347 cursor: pointer;
3348 }
3349 .legend rect {
3350 stroke-width: 1;
3351 stroke: #ccc;
3352 }
3353 </style>
3354 </head>
3355 <body>
3356 4 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
3357 4 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
3358 <div class="tooltip" id="tooltip"></div>
3359 <script>
3360 const data = $json_data;
3361  
3362 const svg = d3.select("#chart");
3363 const tooltip = d3.select("#tooltip");
3364 const margin = { top: 20, right: 120, bottom: 40, left: 40 };
3365 const width = $self->{width} - margin.left - margin.right;
3366 const height = $self->{height} - margin.top - margin.bottom;
3367  
3368 const chart = svg.append("g")
3369 .attr("transform", `translate(\${margin.left},\${margin.top})`);
3370  
3371 const legendArea = svg.append("g")
3372 .attr("transform", `translate(\${width + margin.left + 20},\${margin.top})`);
3373  
3374 // Extract all labels and flatten them into a unique array
3375 const allLabels = Array.from(new Set(data.flatMap(series => series.data.map(d => d.label))));
3376  
3377 const x = d3.scalePoint()
3378 .domain(allLabels)
3379 .range([0, width]);
3380  
3381 const y = d3.scaleLinear()
3382 .domain([0, d3.max(data.flatMap(series => series.data.map(d => d.value)))])
3383 .nice()
3384 .range([height, 0]);
3385  
3386 // Define color scale for series
3387 const color = d3.scaleOrdinal($CATEGORY10_JS);
3388  
3389 // Add axes
3390 chart.append("g")
3391 .call(d3.axisLeft(y));
3392  
3393 chart.append("g")
3394 .attr("transform", `translate(0,\${height})`)
3395 .call(d3.axisBottom(x))
3396 .selectAll("text")
3397 .attr("transform", "rotate(-45)")
3398 .style("text-anchor", "end");
3399  
3400 // Draw lines for each series
3401 data.forEach((series, i) => {
3402 const line = d3.line()
3403 .x(d => x(d.label))
3404 .y(d => y(d.value));
3405  
3406 // Add line
3407 chart.append("path")
3408 .datum(series.data)
3409 .attr("fill", "none")
3410 .attr("stroke", color(i))
3411 .attr("stroke-width", 2)
3412 .attr("class", \`line-\${i}\`)
3413 .attr("d", line);
3414  
3415 // Add points and tooltips
3416 chart.selectAll(\`circle.series-\${i}\`)
3417 .data(series.data)
3418 .join("circle")
3419 .attr("class", \`series-\${i}\`)
3420 .attr("cx", d => x(d.label))
3421 .attr("cy", d => y(d.value))
3422 .attr("r", 4)
3423 .attr("fill", color(i))
3424 .on("mouseover", (event, d) => {
3425 tooltip.style("opacity", 1)
3426 .style("transform", "translateY(0)")
3427 .html(\`Series: <b>\${series.name}<\\/b><br>Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>\`)
3428 .style("left", (event.pageX + 10) + "px")
3429 .style("top", (event.pageY - 30) + "px");
3430 })
3431 .on("mousemove", (event) => {
3432 tooltip.style("left", (event.pageX + 10) + "px")
3433 .style("top", (event.pageY - 30) + "px");
3434 })
3435 .on("mouseout", () => {
3436 tooltip.style("opacity", 0)
3437 .style("transform", "translateY(-10px)");
3438 });
3439 });
3440  
3441 // Add legend
3442 data.forEach((series, i) => {
3443 const legend = legendArea.append("g")
3444 .attr("transform", `translate(0, \${i * 20})`)
3445 .attr("class", "legend");
3446  
3447 legend.append("rect")
3448 .attr("width", 12)
3449 .attr("height", 12)
3450 .attr("fill", color(i));
3451  
3452 legend.append("text")
3453 .attr("x", 20)
3454 .attr("y", 10)
3455 .text(series.name)
3456 .style("alignment-baseline", "middle");
3457  
3458 // Optional: Interactive legend for toggling visibility (uncomment to use)
3459 // legend.on("click", () => {
3460 // const visible = d3.selectAll(\`path.line-\${i}\`).style("opacity") === "1" ? 0 : 1;
3461 // d3.selectAll(\`path.line-\${i}\`).style("opacity", visible);
3462 // d3.selectAll(\`circle.series-\${i}\`).style("opacity", visible);
3463 // });
3464 });
3465 </script>
3466 </body>
3467 </html>
3468 HTML
3469  
3470 4 return $html;
3471 }
3472  
3473 =head2 render_multi_series_line_chart_with_interactive_legends
3474  
3475 $html = $chart->render_multi_series_line_chart_with_interactive_legends($data);
3476  
3477 Generates HTML and JavaScript code to render a chart of many lines with interactive legends to filter, highlight or modify elements based on legend selections.
3478  
3479 Accepts the following arguments:
3480  
3481 =over 4
3482  
3483 =item * C<$data> - Same format as C<render_multi_series_line_chart_with_tooltips>:
3484 an array reference of C<< { name, data } >> series hashes.
3485  
3486 =back
3487  
3488 Returns a string containing the complete HTML5 document. Clicking a legend entry
3489 toggles that series' opacity using an C<isVisible> boolean flag in the D3 click
3490 handler (opacity is set to C<isVisible ? 0 : 1> on each click).
3491  
3492 =head3 Errors
3493  
3494 =over 4
3495  
3496 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
3497  
3498 =back
3499  
3500 =head3 API SPECIFICATION
3501  
3502 =head4 Input
3503  
3504 {
3505 data => { type => 'arrayref' },
3506 }
3507  
3508 Each element of C<$data> is a hashref with keys C<name> (string) and
3509 C<data> (arrayref of hashrefs with C<label> and C<value> keys);
3510 passing C<undef> or a non-arrayref dies.
3511  
3512 =head4 Output
3513  
3514 Str -- complete HTML5 document; legend clicks toggle series visibility.
3515 The C<isVisible> JS variable tracks current visibility state.
3516 Opacity toggled by C<isVisible ? 0 : 1>.
3517  
3518 =cut
3519  
3520 sub render_multi_series_line_chart_with_interactive_legends
3521 6 ▶{
Subroutine render_multi_series_line_chart_with_interactive_legends: called CC=3 SCAR=11.0
Pod documented
3522 6 my $self = shift;
3523 6 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
60
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
3524 6 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 4 6
3525 4 Params::Validate::Strict::validate_strict({
3526 args => $raw,
3527 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
3528 unknown_parameter_handler => 'ignore',
3529 });
3530 4 my $data = $raw->{data};
3531  
3532 # Generate JSON for data
3533 4 my $json_data = _script_json($data);
3534  
3535 # Generate HTML and D3.js code
3536 4 my $html = $self->_preamble();
3537 4 $html .= <<"HTML";
3538 <head>
3539 <meta charset="UTF-8">
3540 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3541 4 <title>@{[ $self->_title_html() ]}</title>
3542 <script src="https://d3js.org/d3.v7.min.js"></script>
3543 <style>
3544 .tooltip {
3545 position: absolute;
3546 background-color: white;
3547 border: 1px solid #ccc;
3548 padding: 5px;
3549 font-size: 12px;
3550 pointer-events: none;
3551 opacity: 0;
3552 transform: translateY(-10px);
3553 transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
3554 }
3555 .legend {
3556 font-size: 12px;
3557 cursor: pointer;
3558 }
3559 .legend rect {
3560 stroke-width: 1;
3561 stroke: #ccc;
3562 }
3563 </style>
3564 </head>
3565 <body>
3566 4 <h1 style="text-align: center;">@{[ $self->_title_html() ]}</h1>
3567 4 <svg id="chart" ${\ $self->_svg_attrs() }></svg>
3568 <div class="tooltip" id="tooltip"></div>
3569 <script>
3570 const data = $json_data;
3571  
3572 const svg = d3.select("#chart");
3573 const tooltip = d3.select("#tooltip");
3574 const margin = { top: 20, right: 150, bottom: 40, left: 40 };
3575 const width = $self->{width} - margin.left - margin.right;
3576 const height = $self->{height} - margin.top - margin.bottom;
3577  
3578 const chart = svg.append("g")
3579 .attr("transform", `translate(\${margin.left},\${margin.top})`);
3580  
3581 const legendArea = svg.append("g")
3582 .attr("transform", `translate(\${width + margin.left + 20},\${margin.top})`);
3583  
3584 // Extract all labels and flatten them into a unique array
3585 const allLabels = Array.from(new Set(data.flatMap(series => series.data.map(d => d.label))));
3586  
3587 const x = d3.scalePoint()
3588 .domain(allLabels)
3589 .range([0, width]);
3590  
3591 const y = d3.scaleLinear()
3592 .domain([0, d3.max(data.flatMap(series => series.data.map(d => d.value)))])
3593 .nice()
3594 .range([height, 0]);
3595  
3596 // Define color scale for series
3597 const color = d3.scaleOrdinal($CATEGORY10_JS);
3598  
3599 // Add axes
3600 chart.append("g")
3601 .call(d3.axisLeft(y));
3602  
3603 chart.append("g")
3604 .attr("transform", `translate(0,\${height})`)
3605 .call(d3.axisBottom(x))
3606 .selectAll("text")
3607 .attr("transform", "rotate(-45)")
3608 .style("text-anchor", "end");
3609  
3610 // Draw lines for each series
3611 data.forEach((series, i) => {
3612 const line = d3.line()
3613 .x(d => x(d.label))
3614 .y(d => y(d.value));
3615  
3616 // Add line
3617 chart.append("path")
3618 .datum(series.data)
3619 .attr("fill", "none")
3620 .attr("stroke", color(i))
3621 .attr("stroke-width", 2)
3622 .attr("class", \`line-\${i}\`)
3623 .attr("d", line);
3624  
3625 // Add points and tooltips
3626 chart.selectAll(\`circle.series-\${i}\`)
3627 .data(series.data)
3628 .join("circle")
3629 .attr("class", \`series-\${i}\`)
3630 .attr("cx", d => x(d.label))
3631 .attr("cy", d => y(d.value))
3632 .attr("r", 4)
3633 .attr("fill", color(i))
3634 .on("mouseover", (event, d) => {
3635 tooltip.style("opacity", 1)
3636 .style("transform", "translateY(0)")
3637 .html(\`Series: <b>\${series.name}<\\/b><br>Label: <b>\${d.label}<\\/b><br>Value: <b>\${d.value}<\\/b>\`)
3638 .style("left", (event.pageX + 10) + "px")
3639 .style("top", (event.pageY - 30) + "px");
3640 })
3641 .on("mousemove", (event) => {
3642 tooltip.style("left", (event.pageX + 10) + "px")
3643 .style("top", (event.pageY - 30) + "px");
3644 })
3645 .on("mouseout", () => {
3646 tooltip.style("opacity", 0)
3647 .style("transform", "translateY(-10px)");
3648 });
3649 });
3650  
3651 // Add legend with interactivity
3652 data.forEach((series, i) => {
3653 const legend = legendArea.append("g")
3654 .attr("transform", `translate(0, \${i * 20})`)
3655 .attr("class", "legend")
3656 .on("click", () => {
3657 const isVisible = d3.selectAll(\`path.line-\${i}\`).style("opacity") === "1";
3658  
3659 // Toggle visibility
3660 d3.selectAll(\`path.line-\${i}\`).style("opacity", isVisible ? 0 : 1);
3661 d3.selectAll(\`circle.series-\${i}\`).style("opacity", isVisible ? 0 : 1);
3662  
3663 // Dim legend if series is hidden
3664 legend.select("text").style("opacity", isVisible ? 0.5 : 1);
3665 });
3666  
3667 legend.append("rect")
3668 .attr("width", 12)
3669 .attr("height", 12)
3670 .attr("fill", color(i));
3671  
3672 legend.append("text")
3673 .attr("x", 20)
3674 .attr("y", 10)
3675 .text(series.name)
3676 .style("alignment-baseline", "middle");
3677 });
3678 </script>
3679 </body>
3680 </html>
3681 HTML
3682  
3683 4 return $html;
3684 }
3685  
3686 =head2 render_multi_series_line_chart_snippet
3687  
3688 my $fragment = $chart->render_multi_series_line_chart_snippet(\@series);
3689 my $fragment = $chart->render_multi_series_line_chart_snippet(\@series, \%opts);
3690 # $fragment->{svg_id} - the id attribute of the <svg> element
3691 # $fragment->{html} - embeddable HTML fragment (style + svg + script)
3692  
3693 Generates an embeddable multi-series line chart fragment. Unlike
3694 C<render_multi_series_line_chart_with_interactive_legends>, this method returns
3695 a bare fragment with no C<< <html> >>, C<< <head> >>, or C<< <body> >> wrapper;
3696 D3.js must be loaded by the host page.
3697  
3698 =head3 Arguments
3699  
3700 =over 4
3701  
3702 =item * C<\@series> - An array reference of series. Each series is a hash
3703 reference with a C<name> (string) and a C<data> array reference of
3704 C<< { label => Str, value => Num } >> points:
3705  
3706 [
3707 { name => 'North', data => [ { label => 'Jan', value => 12 }, ... ] },
3708 { name => 'South', data => [ { label => 'Jan', value => 8 }, ... ] },
3709 ]
3710  
3711 Series need not share labels: the X domain is the union of every series' labels,
3712 in first-seen order. One line and one set of dots is drawn per series, and a
3713 clickable legend toggles each series on and off.
3714  
3715 =item * C<\%opts> - Optional hash reference:
3716  
3717 =over 4
3718  
3719 =item * C<scheme> (string, default C<'tableau10'>) - D3 categorical colour
3720 scheme (for example C<'category10'>, C<'set2'>, C<'set3'>, C<'paired'>).
3721 C<categorical_schemes()> lists the names, and C<palette()> hands a Perl caller
3722 the colours of one.
3723  
3724 =item * C<x_label> (string, default C<''>) - Label shown below the X axis.
3725  
3726 =item * C<y_label> (string, default C<''>) - Label shown beside the Y axis.
3727  
3728 =item * C<animated> (boolean, default 0) - If true each line draws itself left
3729 to right by animating its stroke dash offset. Respects
3730 C<prefers-reduced-motion>.
3731  
3732 =item * C<responsive> (boolean, optional) - SVG responsive sizing override.
3733  
3734 =item * C<id> (string, default C<'chart'>) - C<id> of the C<<svg>> element.
3735  
3736 =back
3737  
3738 =back
3739  
3740 Returns C<< { svg_id => 'chart', html => Str } >>.
3741  
3742 =head3 Errors
3743  
3744 =over 4
3745  
3746 =item * Throws C<Data must be an array of series> when C<\@series> is not an
3747 ARRAY reference.
3748  
3749 =item * Throws C<Each series must be a hashref with name and data> when a
3750 series is not a hashref, has no C<name>, or has a C<data> that is not an ARRAY
3751 reference.
3752  
3753 =back
3754  
3755 =head3 API SPECIFICATION
3756  
3757 =head4 Input
3758  
3759 {
3760 data => { type => 'arrayref' },
3761 opts => {
3762 type => 'hashref',
3763 optional => 1,
3764 keys => {
3765 scheme => { type => 'string', optional => 1, default => 'tableau10' },
3766 x_label => { type => 'string', optional => 1, default => '' },
3767 y_label => { type => 'string', optional => 1, default => '' },
3768 animated => { type => 'boolean', optional => 1, default => 0 },
3769 responsive => { type => 'boolean', optional => 1 },
3770 id => { type => 'string', optional => 1, default => 'chart' },
3771 },
3772 },
3773 }
3774  
3775 =head4 Output
3776  
3777 HashRef -- { svg_id => 'chart', html => Str }
3778  
3779 =cut
3780  
3781 sub render_multi_series_line_chart_snippet
3782 31 ▶{
Subroutine render_multi_series_line_chart_snippet: called CC=19 SCAR=29.5
Pod documented
3783 31 my $self = shift;
3784 31 ▶ my $raw = Params::Get::get_params('series_data', \@_) // {};
Condition50%1/2
Params::Get::get_params("series_data", \@_) // {}
l!l
310
MC/DC0%0/1
Params::Get::get_params("series_data", \@_) // {}
Params::Get::get_params("series_data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("series_data", \@_)
Aresult
11
00
3785 31 ▶ die 'Data must be an array of series' unless ref($raw->{series_data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"series_data"} eq "ARRAY" 1 30 31
3786 30 Params::Validate::Strict::validate_strict({
3787 args => $raw,
3788 schema => { series_data => { type => 'arrayref', error_msg => 'Data must be an array of series' } },
3789 unknown_parameter_handler => 'ignore',
3790 });
3791 30 my $series_data = $raw->{series_data};
3792 30 my $opts = {%$raw}; delete $opts->{series_data};
3793 30 for my $s (@$series_data) {
3794 die 'Each series must be a hashref with name and data'
3795 36 ▶ unless ref($s) eq 'HASH' && defined $s->{name} && ref($s->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $s eq "HASH" and defined $s->{"name"} and ref $s->{"data"} eq "ARRAY" 3 33 36
Condition100%6/6
ref $s eq "HASH" and defined $s->{"name"} and ref $s->{"data"} eq "ARRAY"
!ll&&!rl&&r
2133
ref $s eq "HASH" and defined $s->{"name"}
!ll&&!rl&&r
1134
MC/DC100%3/3
ref $s eq "HASH" and defined $s->{"name"} and ref $s->{"data"} eq "ARRAY"
ref $s eq "HASH" defined $s->{"name"} ref $s->{"data"} eq "ARRAY"
Truth table100%4/4
A and B and C
A= ref $s eq "HASH"B= defined $s->{"name"}C= ref $s->{"data"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
3796 }
3797  
3798 27 my $json_data = _script_json($series_data);
3799  
3800 27 ▶ my $scheme = $opts->{scheme} // $DEFAULT_CATEGORICAL_SCHEME;
Condition66%2/3
$opts->{"scheme"} // $DEFAULT_CATEGORICAL_SCHEME
l!l&&r!l&&!r
7200
MC/DC0%0/2
$opts->{"scheme"} // $DEFAULT_CATEGORICAL_SCHEME
$opts->{"scheme"} $DEFAULT_CATEGORICAL_SCHEME
Truth table66%2/3
A // B
A= $opts->{"scheme"}B= $DEFAULT_CATEGORICAL_SCHEME
ABresult
1X1
011
000
3801 27 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
324
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
3802 27 ▶ my $y_label = $opts->{y_label} // '';
Condition100%2/2
$opts->{"y_label"} // ""
l!l
324
MC/DC100%1/1
$opts->{"y_label"} // ""
$opts->{"y_label"}
Truth table100%2/2
A
A= $opts->{"y_label"}
Aresult
11
00
3803 27 ▶ my $animated = $opts->{animated} // 0;
Condition100%2/2
$opts->{"animated"} // 0
l!l
126
MC/DC100%1/1
$opts->{"animated"} // 0
$opts->{"animated"}
Truth table100%2/2
A
A= $opts->{"animated"}
Aresult
11
00
3804 27 ▶ my $svg_id = _chart_id($opts->{id}) // 'chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "chart"
l!l
522
MC/DC100%1/1
_chart_id($opts->{"id"}) // "chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
3805 27 my $tip_id = $svg_id . '_tip';
3806  
3807 27 my $scheme_js = _scheme_js($scheme);
3808  
3809 27 my $js_esc = \&_js_string;
3810  
3811 27 my $x_label_esc = $js_esc->($x_label);
3812 27 my $y_label_esc = $js_esc->($y_label);
3813  
3814 27 my $width = $self->{width};
3815 27 my $height = $self->{height};
3816 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
3817 27 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 24 27
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2250
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
3818 : qq{width="$width" height="$height"};
3819  
3820 27 my $margin_right = 150; # room for legend
3821 27 ▶ my $margin_left = $y_label ? 60 : 45;
Branch: 1 branch
BranchTrueFalseTotal
$y_label ? : 3 24 27
3822 27 my $margin_top = 20;
3823 27 ▶ my $margin_bottom = $x_label ? 60 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 3 24 27
3824 27 my $inner_w = $width - $margin_left - $margin_right;
3825 27 my $inner_h = $height - $margin_top - $margin_bottom;
3826  
3827 27 ▶ my $x_label_block = $x_label ? <<"XLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 3 24 27
3828 g.append("text")
3829 .attr("class","msl-axis-label")
3830 .attr("x", innerW / 2)
3831 .attr("y", innerH + (margin.bottom - 10))
3832 .attr("text-anchor","middle")
3833 .text("$x_label_esc");
3834 XLB
3835  
3836 27 ▶ my $y_label_block = $y_label ? <<"YLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$y_label ? : 3 24 27
3837 g.append("text")
3838 .attr("class","msl-axis-label")
3839 .attr("transform","rotate(-90)")
3840 .attr("x", -innerH / 2)
3841 .attr("y", -(margin.left - 14))
3842 .attr("text-anchor","middle")
3843 .text("$y_label_esc");
3844 YLB
3845  
3846 27 ▶ my $anim_block = $animated ? <<"ANIM" : '';
Branch: 1 branch
BranchTrueFalseTotal
$animated ? : 1 26 27
3847 var noAnim = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
3848 if (!noAnim) {
3849 g.selectAll(".msl-line")
3850 .each(function() {
3851 var totalLen = this.getTotalLength();
3852 d3.select(this)
3853 .attr("stroke-dasharray", totalLen)
3854 .attr("stroke-dashoffset", totalLen)
3855 .transition().duration(1200).ease(d3.easeLinear)
3856 .attr("stroke-dashoffset", 0);
3857 });
3858 }
3859 ANIM
3860  
3861 27 my $html = <<"HTML";
3862 <style>
3863 #$tip_id {
3864 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
3865 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
3866 display:none;line-height:1.6;
3867 }
3868 .msl-axis-label{font-size:11px;fill:#555;}
3869 .msl-line{fill:none;stroke-width:2;}
3870 .msl-dot{cursor:default;}
3871 .msl-leg-item{cursor:pointer;}
3872 </style>
3873 <svg id="$svg_id" $svg_attrs></svg>
3874 <div id="$tip_id"></div>
3875 <script>
3876 (function(){
3877 var series = $json_data;
3878 var margin = {top:$margin_top,right:$margin_right,bottom:$margin_bottom,left:$margin_left};
3879 var innerW = $inner_w;
3880 var innerH = $inner_h;
3881 var svg = d3.select("#$svg_id");
3882 var g = svg.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
3883 var tip = d3.select("#$tip_id");
3884  
3885 function esc(s) {
3886 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3887 }
3888  
3889 var allLabels = Array.from(new Set(series.flatMap(function(s){return s.data.map(function(d){return d.label;});})));
3890 var allVals = series.flatMap(function(s){return s.data.map(function(d){return d.value;});});
3891  
3892 var xScale = d3.scalePoint().domain(allLabels).range([0,innerW]);
3893 var yScale = d3.scaleLinear()
3894 .domain([Math.min(0,d3.min(allVals)), d3.max(allVals)]).nice()
3895 .range([innerH,0]);
3896  
3897 var color = d3.scaleOrdinal($scheme_js).domain(series.map(function(s){return s.name;}));
3898  
3899 g.append("g").attr("transform","translate(0,"+innerH+")")
3900 .call(d3.axisBottom(xScale))
3901 .selectAll("text").attr("transform","rotate(-45)").style("text-anchor","end");
3902 g.append("g").call(d3.axisLeft(yScale).ticks(6));
3903  
3904 $x_label_block
3905 $y_label_block
3906  
3907 var lineGen = d3.line()
3908 .x(function(d){return xScale(d.label);})
3909 .y(function(d){return yScale(d.value);});
3910  
3911 series.forEach(function(s,i){
3912 g.append("path")
3913 .datum(s.data)
3914 .attr("class","msl-line")
3915 .attr("stroke",color(s.name))
3916 .attr("d",lineGen);
3917  
3918 g.selectAll(".msl-dot-"+i)
3919 .data(s.data).join("circle")
3920 .attr("class","msl-dot msl-dot-"+i)
3921 .attr("cx",function(d){return xScale(d.label);})
3922 .attr("cy",function(d){return yScale(d.value);})
3923 .attr("r",4)
3924 .attr("fill",color(s.name))
3925 .on("mouseover",function(event,d){
3926 tip.style("display","block")
3927 .html("<b>"+esc(d.label)+"<\\/b><br\/>"+esc(s.name)+": <b>"+d.value+"<\\/b>");
3928 })
3929 .on("mousemove",function(event){
3930 tip.style("left",(event.pageX+12)+"px").style("top",(event.pageY-24)+"px");
3931 })
3932 .on("mouseout",function(){tip.style("display","none");});
3933 });
3934  
3935 // Legend
3936 var legG = svg.append("g")
3937 .attr("transform","translate("+(margin.left+innerW+12)+","+margin.top+")");
3938 series.forEach(function(s,i){
3939 var row = legG.append("g")
3940 .attr("class","msl-leg-item")
3941 .attr("transform","translate(0,"+(i*18)+")")
3942 .on("click",function(){
3943 var lines = g.selectAll(".msl-line").filter(function(d,j){return j===i;});
3944 var dots = g.selectAll(".msl-dot-"+i);
3945 var vis = lines.style("opacity") !== "0";
3946 lines.style("opacity", vis ? 0 : 1);
3947 dots.style("opacity", vis ? 0 : 1);
3948 row.select("text").style("opacity", vis ? 0.4 : 1);
3949 });
3950 row.append("rect").attr("width",11).attr("height",11).attr("fill",color(s.name)).attr("rx",2);
3951 row.append("text").attr("x",15).attr("y",10)
3952 .style("font-size","11px").style("fill","#444")
3953 .text(s.name.length>14?s.name.slice(0,13)+"…":s.name);
3954 });
3955  
3956 $anim_block
3957 })();
3958 </script>
3959 HTML
3960  
3961 27 return { svg_id => $svg_id, html => $html };
3962 }
3963  
3964 =head2 render_scatter_chart_snippet
3965  
3966 my $fragment = $chart->render_scatter_chart_snippet($data);
3967 my $fragment = $chart->render_scatter_chart_snippet($data, \%opts);
3968 # $fragment->{svg_id} - the id attribute of the <svg> element
3969 # $fragment->{html} - embeddable HTML fragment (style + svg + script)
3970  
3971 Generates an embeddable HTML fragment for a scatter plot with mouseover
3972 tooltips. Returns a fragment with no C<<!DOCTYPE>>, C<<html>>, C<<head>>, or
3973 C<<body>> wrapper; the caller is responsible for loading D3 in the page.
3974  
3975 =head3 Arguments
3976  
3977 =over 4
3978  
3979 =item * C<$data> - An array reference of data points. Each point is an array
3980 reference with two required numeric elements (x, y), an optional third hash
3981 reference of extra key/value pairs shown as extra tooltip rows, and an optional
3982 fourth hash reference carrying the C<series> (colour group) and C<size> (bubble
3983 radius) dimensions:
3984  
3985 [$x, $y] # basic point
3986 [$x, $y, \%row] # point with extra tooltip data
3987 [$x, $y, \%row, { series => 'North', size => 42 }] # colour and size
3988  
3989 =item * C<\%opts> - Optional hash reference:
3990  
3991 =over 4
3992  
3993 =item * C<id> (string, default C<'scatter_chart'>) - C<id> of the C<<svg>> element.
3994  
3995 =item * C<color> (CSS colour or C<'categorical'>, default C<'steelblue'>) -
3996 Fill colour for the data points. C<'categorical'> uses the Tableau-10 palette.
3997 A value holding anything a CSS colour cannot, such as a quote or C<E<lt>>, is
3998 ignored and the default used.
3999  
4000 =item * C<x_label> (string, default C<''>) - Label for the X axis.
4001  
4002 =item * C<y_label> (string, default C<''>) - Label for the Y axis.
4003  
4004 =item * C<value_label> (string, default C<'Value'>) - Prefix for the tooltip value row.
4005  
4006 =item * C<colour_by_series> (boolean, default 0) - Colour each point by its
4007 C<series> value instead of by point index, and draw a legend listing the series
4008 to the right of the plot. Ignored for points with no C<series> value.
4009  
4010 =item * C<scheme> (string, default C<'tableau10'>) - D3 categorical colour
4011 scheme used when C<colour_by_series> is set, for example C<'category10'>,
4012 C<'set2'>, C<'set3'>, or C<'paired'>.
4013 C<categorical_schemes()> lists the names, and C<palette()> hands a Perl caller
4014 the colours of one.
4015  
4016 =item * C<series_col> (string, default C<'Series'>) - Row label for the series
4017 value in the tooltip.
4018  
4019 =item * C<size_col> (string, default C<'Size'>) - Row label for the size value
4020 in the tooltip.
4021  
4022 =item * C<radius_range> (arrayref of two numbers, default C<[3, 15]>) - Pixel
4023 radii mapped from the smallest and largest observed C<size> value. The mapping
4024 is by area (C<d3.scaleSqrt>), so a point twice as large is drawn with four
4025 times the area. A point with no C<size> value is drawn at the lower radius.
4026  
4027 =item * C<animated> (boolean, default 0) - If true, circles fade in from
4028 opacity 0 on page load (400 ms). Respects C<prefers-reduced-motion>.
4029  
4030 =item * C<responsive> (boolean, default 0) - See C<render_bar_chart_snippet>.
4031  
4032 =back
4033  
4034 =back
4035  
4036 =head3 Return value
4037  
4038 A hash reference with C<svg_id> (string) and C<html> (Perl character string).
4039  
4040 =head3 Errors
4041  
4042 =over 4
4043  
4044 =item * Dies with C<'Data must be an array of arrays'> when C<$data> is not an ARRAY ref.
4045  
4046 =item * Dies with C<'Each data point must be an array reference'> when an element is not an ARRAY ref.
4047  
4048 =item * Dies with C<'Each data point must have at least 2 elements'> when a point has fewer than 2 items.
4049  
4050 =item * Dies with C<'X value must be numeric'> when the x element is not a number.
4051  
4052 =item * Dies with C<'Y value must be numeric'> when the y element is not a number.
4053  
4054 =back
4055  
4056 =head3 API SPECIFICATION
4057  
4058 {
4059 data => { type => 'arrayref' },
4060 opts => {
4061 type => 'hashref',
4062 optional => 1,
4063 keys => {
4064 id => { type => 'string', optional => 1 },
4065 color => { type => 'string', optional => 1, default => 'steelblue' },
4066 x_label => { type => 'string', optional => 1, default => '' },
4067 y_label => { type => 'string', optional => 1, default => '' },
4068 value_label => { type => 'string', optional => 1, default => 'Value' },
4069 colour_by_series => { type => 'boolean', optional => 1, default => 0 },
4070 scheme => { type => 'string', optional => 1, default => 'tableau10' },
4071 series_col => { type => 'string', optional => 1, default => '' },
4072 size_col => { type => 'string', optional => 1, default => '' },
4073 radius_range => { type => 'arrayref', optional => 1, default => [3, 15] },
4074 animated => { type => 'boolean', optional => 1, default => 0 },
4075 responsive => { type => 'boolean', optional => 1, default => 0 },
4076 },
4077 },
4078 }
4079  
4080 =cut
4081  
4082 sub render_scatter_chart_snippet
4083 74 ▶{
Subroutine render_scatter_chart_snippet: called CC=58 SCAR=40.9
Pod documented
4084 74 my $self = shift;
4085 74 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
740
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
4086 74 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 71 74
4087 71 Params::Validate::Strict::validate_strict({
4088 args => $raw,
4089 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
4090 unknown_parameter_handler => 'ignore',
4091 });
4092 71 my $data = $raw->{data};
4093 71 my $opts = {%$raw}; delete $opts->{data};
4094  
4095 71 ▶ my $color = _css_colour($opts->{color}) // 'steelblue';
Condition100%2/2
_css_colour($opts->{"color"}) // "steelblue"
l!l
665
MC/DC100%1/1
_css_colour($opts->{"color"}) // "steelblue"
_css_colour($opts->{"color"})
Truth table100%2/2
A
A= _css_colour($opts->{"color"})
Aresult
11
00
4096 71 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
467
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
4097 71 ▶ my $y_label = $opts->{y_label} // '';
Condition100%2/2
$opts->{"y_label"} // ""
l!l
467
MC/DC100%1/1
$opts->{"y_label"} // ""
$opts->{"y_label"}
Truth table100%2/2
A
A= $opts->{"y_label"}
Aresult
11
00
4098 71 ▶ my $value_label = $opts->{value_label} // 'Value';
Condition50%1/2
$opts->{"value_label"} // "Value"
l!l
071
MC/DC0%0/1
$opts->{"value_label"} // "Value"
$opts->{"value_label"}
Truth table50%1/2
A
A= $opts->{"value_label"}
Aresult
11
00
4099 71 ▶ my $animated = $opts->{animated} // 0;
Condition100%2/2
$opts->{"animated"} // 0
l!l
368
MC/DC100%1/1
$opts->{"animated"} // 0
$opts->{"animated"}
Truth table100%2/2
A
A= $opts->{"animated"}
Aresult
11
00
4100 71 ▶ my $colour_by_series = $opts->{colour_by_series} // 0;
Condition100%2/2
$opts->{"colour_by_series"} // 0
l!l
962
MC/DC100%1/1
$opts->{"colour_by_series"} // 0
$opts->{"colour_by_series"}
Truth table100%2/2
A
A= $opts->{"colour_by_series"}
Aresult
11
00
4101 71 ▶ my $scheme = $opts->{scheme} // $DEFAULT_CATEGORICAL_SCHEME;
Condition66%2/3
$opts->{"scheme"} // $DEFAULT_CATEGORICAL_SCHEME
l!l&&r!l&&!r
7640
MC/DC0%0/2
$opts->{"scheme"} // $DEFAULT_CATEGORICAL_SCHEME
$opts->{"scheme"} $DEFAULT_CATEGORICAL_SCHEME
Truth table66%2/3
A // B
A= $opts->{"scheme"}B= $DEFAULT_CATEGORICAL_SCHEME
ABresult
1X1
011
000
4102 71 ▶ my $series_col = $opts->{series_col} // '';
Condition100%2/2
$opts->{"series_col"} // ""
l!l
170
MC/DC100%1/1
$opts->{"series_col"} // ""
$opts->{"series_col"}
Truth table100%2/2
A
A= $opts->{"series_col"}
Aresult
11
00
4103 71 ▶ my $size_col = $opts->{size_col} // '';
Condition100%2/2
$opts->{"size_col"} // ""
l!l
368
MC/DC100%1/1
$opts->{"size_col"} // ""
$opts->{"size_col"}
Truth table100%2/2
A
A= $opts->{"size_col"}
Aresult
11
00
4104 71 ▶ my $radius_range = $opts->{radius_range} // [3, 15];
Condition100%2/2
$opts->{"radius_range"} // [3, 15]
l!l
170
MC/DC100%1/1
$opts->{"radius_range"} // [3, 15]
$opts->{"radius_range"}
Truth table100%2/2
A
A= $opts->{"radius_range"}
Aresult
11
00
4105  
4106 71 my $js_esc = \&_js_string;
4107  
4108 # The scheme's colours as a JS array, from the one definition rather than
4109 # from the spelling of the name.
4110 71 my $scheme_js = _scheme_js($scheme);
4111  
4112 71 my @points;
4113 71 for my $pt (@$data) {
4114 142 ▶ die 'Each data point must be an array reference' unless ref($pt) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pt eq "ARRAY" 3 139 142
4115 139 ▶ die 'Each data point must have at least 2 elements' unless scalar(@$pt) >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$pt >= 2 3 136 139
4116 136 ▶ die 'X value must be numeric' unless looks_like_number($pt->[0]);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($pt->[0]) 3 133 136
4117 133 ▶ die 'Y value must be numeric' unless looks_like_number($pt->[1]);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($pt->[1]) 3 130 133
4118 130 my $p = { x => $pt->[0] + 0, y => $pt->[1] + 0 };
4119 130 ▶ $p->{extra} = $pt->[2] if ref($pt->[2]) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $pt->[2] eq "HASH" 15 115 130
4120 130 ▶ if (ref($pt->[3]) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pt->[3] eq "HASH") 13 117 130
4121 13 ▶ $p->{series} = $pt->[3]{series} if defined $pt->[3]{series};
Branch: 1 branch
BranchTrueFalseTotal
if defined $pt->[3]{"series"} 10 3 13
4122 13 ▶ $p->{size} = $pt->[3]{size}+0 if defined $pt->[3]{size} && looks_like_number($pt->[3]{size});
Branch: 1 branch
BranchTrueFalseTotal
if defined $pt->[3]{"size"} and &looks_like_number($pt->[3]{"size"}) 4 9 13
Condition100%3/3
defined $pt->[3]{"size"} and &looks_like_number($pt->[3]{"size"})
!ll&&!rl&&r
814
MC/DC100%2/2
defined $pt->[3]{"size"} and &looks_like_number($pt->[3]{"size"})
defined $pt->[3]{"size"} &looks_like_number($pt->[3]{"size"})
Truth table100%3/3
A and B
A= defined $pt->[3]{"size"}B= &looks_like_number($pt->[3]{"size"})
ABresult
0X0
100
111
4123 }
4124 130 push @points, $p;
4125 }
4126  
4127 # Collect series names and size range for JS initialisation.
4128 59 my %seen_series;
4129 my @series_names;
4130 59 my ($size_min, $size_max);
4131 59 for my $p (@points) {
4132 130 ▶ if (defined $p->{series} && !$seen_series{$p->{series}}++) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p->{"series"} and not $seen_series{$p->{"series"}}++) 10 120 130
Condition66%2/3
defined $p->{"series"} and not $seen_series{$p->{"series"}}++
!ll&&!rl&&r
120010
MC/DC50%1/2
defined $p->{"series"} and not $seen_series{$p->{"series"}}++
defined $p->{"series"} not $seen_series{$p->{"series"}}++
Truth table66%2/3
A and not(B)
A= defined $p->{"series"}B= not $seen_series{$p->{"series"}}++
ABresult
0X0
100
111
4133 10 push @series_names, $p->{series};
4134 }
4135 130 ▶ if (defined $p->{size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p->{"size"}) 4 126 130
4136 4 ▶ $size_min = $p->{size} if !defined $size_min || $p->{size} < $size_min;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $size_min or $p->{"size"} < $size_min 2 2 4
Condition66%2/3
not defined $size_min or $p->{"size"} < $size_min
l!l&&r!l&&!r
202
MC/DC50%1/2
not defined $size_min or $p->{"size"} < $size_min
not defined $size_min $p->{"size"} < $size_min
Truth table66%2/3
not(A) or B
A= not defined $size_minB= $p->{"size"} < $size_min
ABresult
1X1
011
000
4137 4 ▶ $size_max = $p->{size} if !defined $size_max || $p->{size} > $size_max;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $size_max or $p->{"size"} > $size_max 4 0 4
Condition66%2/3
not defined $size_max or $p->{"size"} > $size_max
l!l&&r!l&&!r
220
MC/DC0%0/2
not defined $size_max or $p->{"size"} > $size_max
not defined $size_max $p->{"size"} > $size_max
Truth table66%2/3
not(A) or B
A= not defined $size_maxB= $p->{"size"} > $size_max
ABresult
1X1
011
000
4138 }
4139 }
4140 # Colour and size are independent dimensions: a point may carry both.
4141 59 ▶ my $has_series = $colour_by_series && @series_names;
Condition100%3/3
$colour_by_series && @series_names
!ll&&!rl&&r
5018
MC/DC100%2/2
$colour_by_series && @series_names
$colour_by_series @series_names
Truth table100%3/3
A && B
A= $colour_by_seriesB= @series_names
ABresult
0X0
100
111
4142 59 my $has_size = defined $size_min;
4143  
4144 59 my $json_data = _script_json(\@points);
4145 59 my $json_series = _script_json(\@series_names);
4146 59 my $x_label_esc = $js_esc->($x_label);
4147 59 my $y_label_esc = $js_esc->($y_label);
4148 59 my $val_label_esc = $js_esc->($value_label);
4149 59 ▶ my $series_lbl_esc = $js_esc->($series_col || 'Series');
Condition100%2/2
$series_col || 'Series'
l!l
158
MC/DC100%1/1
$series_col || 'Series'
$series_col
Truth table100%2/2
A
A= $series_col
Aresult
11
00
4150 59 ▶ my $size_lbl_esc = $js_esc->($size_col || 'Size');
Condition100%2/2
$size_col || 'Size'
l!l
356
MC/DC100%1/1
$size_col || 'Size'
$size_col
Truth table100%2/2
A
A= $size_col
Aresult
11
00
4151  
4152 59 ▶ my $is_categorical = ($color eq 'categorical') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$color eq 'categorical' ? : 0 59 59
4153 59 ▶ my $color_esc = ($is_categorical || $has_series) ? 'steelblue' : $js_esc->($color);
Branch: 1 branch
BranchTrueFalseTotal
$is_categorical || $has_series ? : 8 51 59
Condition66%2/3
$is_categorical or $has_series
l!l&&r!l&&!r
0851
MC/DC50%1/2
$is_categorical or $has_series
$is_categorical $has_series
Truth table66%2/3
A or B
A= $is_categoricalB= $has_series
ABresult
1X1
011
000
4154  
4155 59 ▶ my $svg_id = _chart_id($opts->{id}) // 'scatter_chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "scatter_chart"
l!l
752
MC/DC100%1/1
_chart_id($opts->{"id"}) // "scatter_chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
4156 59 my $tip_id = $svg_id . '_tip';
4157 59 my $leg_id = $svg_id . '_leg';
4158  
4159 59 my $width = $self->{width};
4160 59 my $height = $self->{height};
4161  
4162 # Reserve right margin for legend when series colouring is active.
4163 59 ▶ my $margin_right = $has_series ? 140 : 20;
Branch: 1 branch
BranchTrueFalseTotal
$has_series ? : 8 51 59
4164 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
4165 59 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 4 55 59
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
3560
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
4166 : qq{width="$width" height="$height"};
4167  
4168 59 ▶ my $margin_bottom = $x_label ? 60 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 4 55 59
4169 59 ▶ my $margin_left = $y_label ? 70 : 50;
Branch: 1 branch
BranchTrueFalseTotal
$y_label ? : 4 55 59
4170 59 my $margin_top = 20;
4171 59 my $inner_w = $width - $margin_left - $margin_right;
4172 59 my $inner_h = $height - $margin_top - $margin_bottom;
4173  
4174 # Color initialisation JS.
4175 59 my $color_init_js;
4176 59 ▶ if ($has_series) {
Branch: 2 branches
BranchTrueFalseTotal
if ($has_series) { } 8 51 59
elsif ($is_categorical) { } 0 51 51
4177 8 $color_init_js = "var seriesNames = $json_series;\n"
4178 . " var color = d3.scaleOrdinal(${scheme_js}).domain(seriesNames);";
4179 } elsif ($is_categorical) {
4180 0 $color_init_js = 'var color = d3.scaleOrdinal(' . _default_scheme_js() . ').domain(data.map(function(d,i){return i;}));';
4181 } else {
4182 51 $color_init_js = "var color = function() { return \"$color_esc\"; };";
4183 }
4184  
4185 # Size scale JS (bubble mode).
4186 59 ▶ my $r_min = $radius_range->[0] // 3;
Condition50%1/2
$radius_range->[0] // 3
l!l
590
MC/DC0%0/1
$radius_range->[0] // 3
$radius_range->[0]
Truth table50%1/2
A
A= $radius_range->[0]
Aresult
11
00
4187 59 ▶ my $r_max = $radius_range->[1] // 15;
Condition50%1/2
$radius_range->[1] // 15
l!l
590
MC/DC0%0/1
$radius_range->[1] // 15
$radius_range->[1]
Truth table50%1/2
A
A= $radius_range->[1]
Aresult
11
00
4188 59 my $size_init_js = '';
4189 59 my $radius_js = '5';
4190 59 ▶ if ($has_size && defined $size_min) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_size and defined $size_min) 2 57 59
Condition66%2/3
$has_size and defined $size_min
!ll&&!rl&&r
5702
MC/DC50%1/2
$has_size and defined $size_min
$has_size defined $size_min
Truth table66%2/3
A and B
A= $has_sizeB= defined $size_min
ABresult
0X0
100
111
4191 2 my $smin = $size_min + 0;
4192 2 my $smax = $size_max + 0;
4193 2 $size_init_js = "var rScale = d3.scaleSqrt().domain([$smin,$smax]).range([$r_min,$r_max]).clamp(true);";
4194 2 $radius_js = 'function(d){return d.size!=null?rScale(d.size):' . $r_min . ';}';
4195 }
4196  
4197 # Series colouring: color by d.series; fallback to default.
4198 59 ▶ my $fill_js = $has_series
Branch: 1 branch
BranchTrueFalseTotal
$has_series ? : 8 51 59
4199 ? 'function(d){return d.series!=null?color(d.series):"' . $color_esc . '";}'
4200 : 'function(d,i){return color(i);}';
4201  
4202 59 ▶ my $anim_block = $animated ? <<"ANIM" : '';
Branch: 1 branch
BranchTrueFalseTotal
$animated ? : 3 56 59
4203 var noAnim = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
4204 if (!noAnim) {
4205 circles.attr("opacity", 0)
4206 .transition()
4207 .duration(400)
4208 .delay(function(d, i) { return i * 10; })
4209 .attr("opacity", 0.8);
4210 } else {
4211 circles.attr("opacity", 0.8);
4212 }
4213 ANIM
4214  
4215 59 ▶ my $x_label_block = $x_label ? <<"XLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 4 55 59
4216 g.append("text")
4217 .attr("class", "sc-axis-label")
4218 .attr("x", $inner_w / 2)
4219 .attr("y", $inner_h + ($margin_bottom - 10))
4220 .attr("text-anchor", "middle")
4221 .text("$x_label_esc");
4222 XLB
4223  
4224 59 ▶ my $y_label_block = $y_label ? <<"YLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$y_label ? : 4 55 59
4225 g.append("text")
4226 .attr("class", "sc-axis-label")
4227 .attr("transform", "rotate(-90)")
4228 .attr("x", -$inner_h / 2)
4229 .attr("y", -($margin_left - 15))
4230 .attr("text-anchor", "middle")
4231 .text("$y_label_esc");
4232 YLB
4233  
4234 # Legend block (only when colour_by_series is true and we have series names).
4235 59 ▶ my $legend_block = $has_series ? <<"LEG" : '';
Branch: 1 branch
BranchTrueFalseTotal
$has_series ? : 8 51 59
4236 var legendG = svg.append("g")
4237 .attr("transform","translate(" + ($margin_left + $inner_w + 12) + "," + $margin_top + ")");
4238 var seriesNamesForLeg = $json_series;
4239 seriesNamesForLeg.forEach(function(name, i){
4240 var row = legendG.append("g").attr("transform","translate(0," + (i*18) + ")");
4241 row.append("rect").attr("width",11).attr("height",11).attr("fill",color(name)).attr("rx",2);
4242 row.append("text").attr("x",15).attr("y",10).style("font-size","11px").style("fill","#444")
4243 .text(name.length>14?name.slice(0,13)+"…":name);
4244 });
4245 LEG
4246  
4247 59 ▶ my $series_tip_js = $has_series
Branch: 1 branch
BranchTrueFalseTotal
$has_series ? : 8 51 59
Condition100%2/2
$series_col || 'Series'
l!l
17
MC/DC100%1/1
$series_col || 'Series'
$series_col
Truth table100%2/2
A
A= $series_col
Aresult
11
00
4248 ? 'if(d.series!=null){tipHtml+="<br>"+esc("' . $js_esc->($series_col || 'Series') . '")+": "+esc(String(d.series));}'
4249 : '';
4250 59 ▶ my $size_tip_js = $has_size
Branch: 1 branch
BranchTrueFalseTotal
$has_size ? : 2 57 59
Condition50%1/2
$size_col || 'Size'
l!l
20
MC/DC0%0/1
$size_col || 'Size'
$size_col
Truth table50%1/2
A
A= $size_col
Aresult
11
00
4251 ? 'if(d.size!=null){tipHtml+="<br>"+esc("' . $js_esc->($size_col || 'Size') . '")+": "+esc(String(d.size));}'
4252 : '';
4253  
4254 59 my $html = <<"HTML";
4255 <style>
4256 #$tip_id {
4257 position: absolute;
4258 background: rgba(255,255,255,0.95);
4259 border: 1px solid #ccc;
4260 border-radius: 4px;
4261 padding: 6px 10px;
4262 font-size: 12px;
4263 pointer-events: none;
4264 display: none;
4265 line-height: 1.6;
4266 }
4267 .sc-circle { cursor: default; }
4268 .sc-axis-label { font-size: 11px; fill: #555; }
4269 </style>
4270 <svg id="$svg_id" $svg_attrs></svg>
4271 <div id="$tip_id"></div>
4272 <script>
4273 (function() {
4274 var data = $json_data;
4275 var margin = { top: $margin_top, right: $margin_right, bottom: $margin_bottom, left: $margin_left };
4276 var innerW = $inner_w;
4277 var innerH = $inner_h;
4278 var valLabel = "$val_label_esc";
4279 $color_init_js
4280 $size_init_js
4281  
4282 function esc(s) {
4283 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
4284 }
4285  
4286 var svg = d3.select("#$svg_id");
4287 var tip = d3.select("#$tip_id");
4288  
4289 var g = svg.append("g")
4290 .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
4291  
4292 var xExt = d3.extent(data, function(d) { return d.x; });
4293 var yExt = d3.extent(data, function(d) { return d.y; });
4294 var xPad = (xExt[1] - xExt[0]) * 0.05 || 1;
4295 var yPad = (yExt[1] - yExt[0]) * 0.05 || 1;
4296  
4297 var xScale = d3.scaleLinear()
4298 .domain([xExt[0] - xPad, xExt[1] + xPad])
4299 .range([0, innerW]);
4300  
4301 var yScale = d3.scaleLinear()
4302 .domain([yExt[0] - yPad, yExt[1] + yPad])
4303 .nice()
4304 .range([innerH, 0]);
4305  
4306 g.append("g")
4307 .attr("transform", "translate(0," + innerH + ")")
4308 .call(d3.axisBottom(xScale).ticks(6));
4309  
4310 g.append("g")
4311 .call(d3.axisLeft(yScale).ticks(6));
4312  
4313 var circles = g.selectAll(".sc-circle")
4314 .data(data)
4315 .join("circle")
4316 .attr("class", "sc-circle")
4317 .attr("cx", function(d) { return xScale(d.x); })
4318 .attr("cy", function(d) { return yScale(d.y); })
4319 .attr("r", $radius_js)
4320 .attr("fill", $fill_js)
4321 .attr("stroke", "white")
4322 .attr("stroke-width", 0.5)
4323 .on("mouseover", function(event, d) {
4324 var tipHtml = "<b>" + esc(String(d.x)) + "<\\/b>, <b>" + esc(String(d.y)) + "<\\/b>";
4325 if (d.extra) {
4326 Object.entries(d.extra).forEach(function(kv) {
4327 tipHtml += "<br>" + esc(kv[0]) + ": " + esc(kv[1]);
4328 });
4329 }
4330 $series_tip_js
4331 $size_tip_js
4332 tip.html(tipHtml)
4333 .style("display", "block")
4334 .style("left", (event.pageX + 12) + "px")
4335 .style("top", (event.pageY - 24) + "px");
4336 })
4337 .on("mousemove", function(event) {
4338 tip.style("left", (event.pageX + 12) + "px")
4339 .style("top", (event.pageY - 24) + "px");
4340 })
4341 .on("mouseout", function() {
4342 tip.style("display", "none");
4343 });
4344  
4345 $anim_block$x_label_block$y_label_block$legend_block})();
4346 </script>
4347 HTML
4348  
4349 59 return { svg_id => $svg_id, html => $html };
4350 }
4351  
4352 =head2 render_table_snippet
4353  
4354 my $fragment = $chart->render_table_snippet($data);
4355 my $fragment = $chart->render_table_snippet($data, \%opts);
4356 # $fragment->{table_id} - the id attribute of the <table> element
4357 # $fragment->{html} - embeddable HTML fragment (style + table + script)
4358  
4359 Generates an embeddable HTML fragment for a sortable, filterable data table.
4360 Returns a fragment with no page-shell wrapper; the caller loads D3 if needed.
4361  
4362 =head3 Arguments
4363  
4364 =over 4
4365  
4366 =item * C<$data> - An array reference of row array references. The first row
4367 is treated as the header row. Every subsequent row must have the same number
4368 of columns as the header.
4369  
4370 [ ['Name', 'Value', 'Category'], # header
4371 ['Alpha', 300, 'A'],
4372 ['Beta', 150, 'B'],
4373 ]
4374  
4375 =item * C<\%opts> - Optional hash reference:
4376  
4377 =over 4
4378  
4379 =item * C<id> (string, default C<'data_table'>) - C<id> of the C<<table>> element.
4380  
4381 =item * C<sortable> (boolean, default 1) - If true, clicking a column header
4382 sorts the table by that column (toggle ascending/descending).
4383  
4384 =item * C<caption> (string, default C<''>) - Optional C<<caption>> element text.
4385  
4386 =back
4387  
4388 =back
4389  
4390 =head3 Return value
4391  
4392 A hash reference with C<table_id> (string) and C<html> (Perl character string).
4393 Note: returns C<table_id>, not C<svg_id>, because this method renders an HTML
4394 table rather than an SVG chart.
4395  
4396 =head3 Errors
4397  
4398 =over 4
4399  
4400 =item * Dies with C<'Data must be an array of arrays'> when C<$data> is not an ARRAY ref.
4401  
4402 =item * Dies with C<'Data must have at least one row (header row)'> when C<$data> is empty.
4403  
4404 =item * Dies with C<'Each row must be an array reference'> when a row is not an ARRAY ref.
4405  
4406 =back
4407  
4408 =head3 API SPECIFICATION
4409  
4410 {
4411 data => { type => 'arrayref' },
4412 opts => {
4413 type => 'hashref',
4414 optional => 1,
4415 keys => {
4416 id => { type => 'string', optional => 1, default => 'data_table' },
4417 sortable => { type => 'boolean', optional => 1, default => 1 },
4418 caption => { type => 'string', optional => 1, default => '' },
4419 },
4420 },
4421 }
4422  
4423 =cut
4424  
4425 sub render_table_snippet
4426 40 ▶{
Subroutine render_table_snippet: called CC=15 SCAR=27.1
Pod documented
4427 40 my $self = shift;
4428 40 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
400
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
4429 40 ▶ die 'Data must be an array of arrays' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 3 37 40
4430 37 Params::Validate::Strict::validate_strict({
4431 args => $raw,
4432 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of arrays' } },
4433 unknown_parameter_handler => 'ignore',
4434 });
4435 37 my $data = $raw->{data};
4436 37 my $opts = {%$raw}; delete $opts->{data};
4437 37 ▶ die 'Data must have at least one row (header row)' unless @$data;
Branch: 1 branch
BranchTrueFalseTotal
unless @$data 3 34 37
4438 34 ▶ die 'Each row must be an array reference' unless ref($data->[0]) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->[0] eq "ARRAY" 3 31 34
4439  
4440 31 ▶ my $sortable = exists($opts->{sortable}) ? $opts->{sortable} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'sortable'} ? : 3 28 31
4441 31 ▶ my $caption = $opts->{caption} // '';
Condition100%2/2
$opts->{"caption"} // ""
l!l
328
MC/DC100%1/1
$opts->{"caption"} // ""
$opts->{"caption"}
Truth table100%2/2
A
A= $opts->{"caption"}
Aresult
11
00
4442 31 ▶ my $table_id = _chart_id($opts->{id}) // 'data_table';
Condition100%2/2
_chart_id($opts->{"id"}) // "data_table"
l!l
724
MC/DC100%1/1
_chart_id($opts->{"id"}) // "data_table"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
4443  
4444 31 my $js_esc = \&_js_string;
4445  
4446 172 ▶ my $html_esc = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
4447 172 ▶ my $s = shift // '';
Condition50%1/2
shift() // ""
l!l
1720
MC/DC0%0/1
shift() // ""
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
4448 172 $s =~ s/&/&amp;/g;
4449 172 $s =~ s/</&lt;/g;
4450 172 $s =~ s/>/&gt;/g;
4451 172 return $s;
4452 31 };
4453  
4454 31 my $headers = $data->[0];
4455 31 my @rows = @{$data}[1 .. $#$data];
4456  
4457 31 for my $row (@rows) {
4458 50 ▶ die 'Each row must be an array reference' unless ref($row) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" 2 48 50
4459 }
4460  
4461 my $json_data = _script_json([
4462 map {
4463 29 my @row = @$_;
4464 \@row
4465 77 } @$data
4466 ]);
4467  
4468 29 ▶ my $caption_html = $caption
Branch: 1 branch
BranchTrueFalseTotal
$caption ? : 3 26 29
4469 ? '<caption>' . $html_esc->($caption) . '</caption>'
4470 : '';
4471  
4472 29 ▶ my $sort_th_class = $sortable ? ' class="dt-sortable"' : '';
Branch: 1 branch
BranchTrueFalseTotal
$sortable ? : 26 3 29
4473 29 ▶ my $sort_cursor_css = $sortable ? 'cursor:pointer; user-select:none;' : '';
Branch: 1 branch
BranchTrueFalseTotal
$sortable ? : 26 3 29
4474  
4475 29 my @th_cells = map { '<th' . $sort_th_class . '>' . $html_esc->($_) . '</th>' } @$headers;
4476 29 my $thead_html = '<tr>' . join('', @th_cells) . '</tr>';
4477  
4478 29 my @tbody_rows;
4479 29 for my $row (@rows) {
4480 48 my @tds = map { '<td>' . $html_esc->($_) . '</td>' } @$row;
4481 48 push @tbody_rows, '<tr>' . join('', @tds) . '</tr>';
4482 }
4483 29 my $tbody_html = join("\n ", @tbody_rows);
4484  
4485 29 ▶ my $sort_script = $sortable ? <<"SORT" : '';
Branch: 1 branch
BranchTrueFalseTotal
$sortable ? : 26 3 29
4486 var sortState = { col: -1, asc: true };
4487 var tbody = table.select('tbody');
4488 table.selectAll('th.dt-sortable').on('click', function(event, colIdx) {
4489 if (sortState.col === colIdx) {
4490 sortState.asc = !sortState.asc;
4491 } else {
4492 sortState.col = colIdx;
4493 sortState.asc = true;
4494 }
4495 var rows = tbody.selectAll('tr').data();
4496 rows.sort(function(a, b) {
4497 var va = a[colIdx], vb = b[colIdx];
4498 var na = parseFloat(va), nb = parseFloat(vb);
4499 if (!isNaN(na) && !isNaN(nb)) { va = na; vb = nb; }
4500 if (va < vb) return sortState.asc ? -1 : 1;
4501 if (va > vb) return sortState.asc ? 1 : -1;
4502 return 0;
4503 });
4504 tbody.selectAll('tr').data(rows).join('tr')
4505 .selectAll('td').data(function(d) { return d.slice(1); }).join('td')
4506 .text(function(d) { return d; });
4507 table.selectAll('th.dt-sortable')
4508 .attr('data-sort', function(d, i) {
4509 return i === sortState.col ? (sortState.asc ? 'asc' : 'desc') : null;
4510 });
4511 });
4512 SORT
4513  
4514 29 my $html = <<"HTML";
4515 <style>
4516 #$table_id {
4517 border-collapse: collapse;
4518 width: 100%;
4519 font-size: 13px;
4520 }
4521 #$table_id caption { font-weight: bold; margin-bottom: 6px; text-align: left; }
4522 #$table_id th, #$table_id td { border: 1px solid #ccc; padding: 6px 10px; text-align: left; }
4523 #$table_id th { background: #f5f5f5; $sort_cursor_css }
4524 #$table_id th[data-sort="asc"]::after { content: " \\25B2"; font-size: 10px; }
4525 #$table_id th[data-sort="desc"]::after { content: " \\25BC"; font-size: 10px; }
4526 #$table_id tr:nth-child(even) { background: #fafafa; }
4527 #$table_id tr:hover { background: #f0f4ff; }
4528 </style>
4529 <table id="$table_id">
4530 $caption_html<thead>
4531 $thead_html</thead>
4532 <tbody>
4533 $tbody_html</tbody>
4534 </table>
4535 <script>
4536 (function() {
4537 var allData = $json_data;
4538 var table = d3.select("#$table_id");
4539 var headers = allData[0];
4540 $sort_script})();
4541 </script>
4542 HTML
4543  
4544 29 return { table_id => $table_id, html => $html };
4545 }
4546  
4547 =head2 render_stacked_bar_snippet
4548  
4549 my $result = $chart->render_stacked_bar_snippet(\@rows, \%opts);
4550  
4551 Generates an embeddable stacked bar chart (no page shell, no CDN tag).
4552  
4553 Each element of C<\@rows> is a hashref with three keys named by C<opts>:
4554 C<cat_col> (the X-axis grouping), C<seg_col> (the stacking segment), and
4555 C<val_col> (the numeric measure). Multiple rows sharing the same
4556 cat+seg combination are summed.
4557  
4558 Accepted C<\%opts> keys:
4559  
4560 =over 4
4561  
4562 =item * C<cat_col> (string, default C<'cat'>) - row key for the X-axis category.
4563  
4564 =item * C<seg_col> (string, default C<'seg'>) - row key for the stacking segment.
4565  
4566 =item * C<val_col> (string, default C<'val'>) - row key for the numeric value.
4567  
4568 =item * C<orient> (string C<'v'> or C<'h'>, default C<'v'>) - bar orientation.
4569  
4570 =item * C<scheme> (string, default C<'tableau10'>) - D3 categorical colour scheme.
4571 Supported: C<tableau10>, C<category10>, C<set2>, C<set3>, C<paired> - the names
4572 C<categorical_schemes()> returns, whose colours C<palette()> makes available to
4573 Perl.
4574  
4575 =item * C<x_label> (string, optional) - axis label shown below the category axis.
4576  
4577 =item * C<sort> (string, optional) - sort categories: C<'value'> (desc total)
4578 or C<'label'> (alpha).
4579  
4580 =item * C<id> (string, optional) - override the default C<svg_id> value.
4581  
4582 =item * C<responsive> (boolean, optional) - SVG responsive sizing override.
4583  
4584 =back
4585  
4586 Returns C<{ svg_id =E<gt> 'stacked_bar', html =E<gt> Str }>.
4587  
4588 =head3 Errors
4589  
4590 =over 4
4591  
4592 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
4593  
4594 =item * Throws C<Each data point must be a hash reference> when a row is not a hashref.
4595  
4596 =item * Throws C<Value must be numeric> when a value field is not a number.
4597  
4598 =item * Throws C<orient must be 'v' or 'h'> for an invalid C<orient> value.
4599  
4600 =item * Throws C<sort must be 'value' or 'label'> for an invalid C<sort> value.
4601  
4602 =back
4603  
4604 =head3 API SPECIFICATION
4605  
4606 =head4 Input
4607  
4608 {
4609 data => { type => 'arrayref' },
4610 opts => {
4611 type => 'hashref',
4612 optional => 1,
4613 keys => {
4614 cat_col => { type => 'string', optional => 1, default => 'cat' },
4615 seg_col => { type => 'string', optional => 1, default => 'seg' },
4616 val_col => { type => 'string', optional => 1, default => 'val' },
4617 orient => { type => 'string', optional => 1, default => 'v' },
4618 scheme => { type => 'string', optional => 1, default => 'tableau10' },
4619 x_label => { type => 'string', optional => 1, default => '' },
4620 sort => { type => 'string', optional => 1 },
4621 id => { type => 'string', optional => 1, default => 'stacked_bar' },
4622 responsive => { type => 'boolean', optional => 1 },
4623 },
4624 },
4625 }
4626  
4627 =head4 Output
4628  
4629 HashRef -- { svg_id => Str, html => Str }
4630  
4631 =cut
4632  
4633 sub render_stacked_bar_snippet
4634 42 ▶{
Subroutine render_stacked_bar_snippet: called CC=40 SCAR=37.1
Pod documented
4635 42 my $self = shift;
4636 42 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
420
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
4637 42 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 1 41 42
4638 41 Params::Validate::Strict::validate_strict({
4639 args => $raw,
4640 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
4641 unknown_parameter_handler => 'ignore',
4642 });
4643 41 my $data = $raw->{data};
4644 41 my $opts = {%$raw}; delete $opts->{data};
4645  
4646 41 ▶ my $cat_col = $opts->{cat_col} // 'cat';
Condition50%1/2
$opts->{"cat_col"} // "cat"
l!l
041
MC/DC0%0/1
$opts->{"cat_col"} // "cat"
$opts->{"cat_col"}
Truth table50%1/2
A
A= $opts->{"cat_col"}
Aresult
11
00
4647 41 ▶ my $seg_col = $opts->{seg_col} // 'seg';
Condition50%1/2
$opts->{"seg_col"} // "seg"
l!l
041
MC/DC0%0/1
$opts->{"seg_col"} // "seg"
$opts->{"seg_col"}
Truth table50%1/2
A
A= $opts->{"seg_col"}
Aresult
11
00
4648 41 ▶ my $val_col = $opts->{val_col} // 'val';
Condition50%1/2
$opts->{"val_col"} // "val"
l!l
041
MC/DC0%0/1
$opts->{"val_col"} // "val"
$opts->{"val_col"}
Truth table50%1/2
A
A= $opts->{"val_col"}
Aresult
11
00
4649 41 ▶ my $orient = $opts->{orient} // 'v';
Condition100%2/2
$opts->{"orient"} // "v"
l!l
239
MC/DC100%1/1
$opts->{"orient"} // "v"
$opts->{"orient"}
Truth table100%2/2
A
A= $opts->{"orient"}
Aresult
11
00
4650 41 my $scheme = _scheme_name($opts->{scheme});
4651 41 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
338
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
4652 41 my $sort_by = $opts->{sort};
4653 41 my $schemes_js = $self->_schemes_js('var');
4654 41 my $default_js = _default_scheme_js();
4655  
4656 41 ▶ die "orient must be 'v' or 'h'"
Branch: 1 branch
BranchTrueFalseTotal
unless $orient eq "v" or $orient eq "h" 1 40 41
Condition100%3/3
$orient eq "v" or $orient eq "h"
l!l&&r!l&&!r
3911
MC/DC100%2/2
$orient eq "v" or $orient eq "h"
$orient eq "v" $orient eq "h"
Truth table100%3/3
A or B
A= $orient eq "v"B= $orient eq "h"
ABresult
1X1
011
000
4657 unless $orient eq 'v' || $orient eq 'h';
4658 40 ▶ die "sort must be 'value' or 'label'"
Branch: 1 branch
BranchTrueFalseTotal
if defined $sort_by and $sort_by ne "value" and $sort_by ne "label" 1 39 40
Condition100%6/6
defined $sort_by and $sort_by ne "value" and $sort_by ne "label"
!ll&&!rl&&r
3811
defined $sort_by and $sort_by ne "value"
!ll&&!rl&&r
3712
MC/DC100%3/3
defined $sort_by and $sort_by ne "value" and $sort_by ne "label"
defined $sort_by $sort_by ne "value" $sort_by ne "label"
Truth table100%4/4
A and B and C
A= defined $sort_byB= $sort_by ne "value"C= $sort_by ne "label"
ABCresult
0XX0
10X0
1100
1111
4659 if defined($sort_by) && $sort_by ne 'value' && $sort_by ne 'label';
4660  
4661 39 my (%cats_seen, %segs_seen, %pivot, @cat_order);
4662 39 for my $row (@$data) {
4663 90 ▶ die 'Each data point must be a hash reference' unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 89 90
4664 89 ▶ die "Value must be numeric" unless looks_like_number($row->{$val_col} // 'x');
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number(scalar($row->{$val_col} // "x")) 1 88 89
Condition50%1/2
$row->{$val_col} // "x"
l!l
890
MC/DC0%0/1
$row->{$val_col} // "x"
$row->{$val_col}
Truth table50%1/2
A
A= $row->{$val_col}
Aresult
11
00
4665 88 ▶ my ($cat, $seg, $val) = ($row->{$cat_col} // '', $row->{$seg_col} // '', $row->{$val_col} + 0);
Condition50%2/4
$row->{$cat_col} // ""
l!l
880
$row->{$seg_col} // ""
l!l
880
MC/DC0%0/1
$row->{$cat_col} // ""
$row->{$cat_col}
MC/DC0%0/1
$row->{$seg_col} // ""
$row->{$seg_col}
Truth table50%1/2
A
A= $row->{$cat_col}
Aresult
11
00
Truth table50%1/2
A
A= $row->{$seg_col}
Aresult
11
00
4666 88 ▶ push @cat_order, $cat unless $cats_seen{$cat}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $cats_seen{$cat}++ 58 30 88
4667 88 $segs_seen{$seg} = 1;
4668 88 ▶ $pivot{$cat}{$seg} = ($pivot{$cat}{$seg} // 0) + $val;
Condition50%1/2
$pivot{$cat}{$seg} // 0
l!l
088
MC/DC0%0/1
$pivot{$cat}{$seg} // 0
$pivot{$cat}{$seg}
Truth table50%1/2
A
A= $pivot{$cat}{$seg}
Aresult
11
00
4669 }
4670  
4671 37 my @segs = keys %segs_seen;
4672 37 my @cats = @cat_order;
4673  
4674 37 ▶ if (defined $sort_by && $sort_by eq 'label') {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $sort_by and $sort_by eq 'label') { } 1 36 37
elsif (defined $sort_by and $sort_by eq 'value') { } 1 70 71
Condition100%3/3
defined $sort_by and $sort_by eq "label"
!ll&&!rl&&r
3511
MC/DC100%2/2
defined $sort_by and $sort_by eq "label"
defined $sort_by $sort_by eq "label"
Truth table100%3/3
A and B
A= defined $sort_byB= $sort_by eq "label"
ABresult
0X0
100
111
4675 1 @cats = sort @cats;
4676 ▶ } elsif (defined $sort_by && $sort_by eq 'value') {
Condition66%2/3
defined $sort_by and $sort_by eq "value"
!ll&&!rl&&r
3501
MC/DC50%1/2
defined $sort_by and $sort_by eq "value"
defined $sort_by $sort_by eq "value"
Truth table66%2/3
A and B
A= defined $sort_byB= $sort_by eq "value"
ABresult
0X0
100
111
4677 @cats = sort {
4678 1 my ($ta, $tb) = (0, 0);
4679 3 ▶ $ta += ($pivot{$a}{$_} // 0) for @segs;
Condition50%1/2
$pivot{$a}{$_} // 0
l!l
60
MC/DC0%0/1
$pivot{$a}{$_} // 0
$pivot{$a}{$_}
Truth table50%1/2
A
A= $pivot{$a}{$_}
Aresult
11
00
4680 3 ▶ $tb += ($pivot{$b}{$_} // 0) for @segs;
Condition50%1/2
$pivot{$b}{$_} // 0
l!l
60
MC/DC0%0/1
$pivot{$b}{$_} // 0
$pivot{$b}{$_}
Truth table50%1/2
A
A= $pivot{$b}{$_}
Aresult
11
00
4681 3 $tb <=> $ta
4682 } @cats;
4683 }
4684  
4685 my @rows = map {
4686 37 my $cat = $_;
4687 58 my %r = (cat => $cat);
4688 58 ▶ $r{$_} = ($pivot{$cat}{$_} // 0) for @segs;
Condition100%2/2
$pivot{$cat}{$_} // 0
l!l
883
MC/DC100%1/1
$pivot{$cat}{$_} // 0
$pivot{$cat}{$_}
Truth table100%2/2
A
A= $pivot{$cat}{$_}
Aresult
11
00
4689 58 \%r
4690 } @cats;
4691  
4692 37 my $json_data = _script_json(\@rows);
4693 37 my $json_segs = _script_json(\@segs);
4694  
4695 37 my $js_esc = \&_js_string;
4696  
4697 37 my $x_label_esc = $js_esc->($x_label);
4698 37 ▶ my $svg_id = _chart_id($opts->{id}) // 'stacked_bar';
Condition100%2/2
_chart_id($opts->{"id"}) // "stacked_bar"
l!l
532
MC/DC100%1/1
_chart_id($opts->{"id"}) // "stacked_bar"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
4699 37 my $tip_id = $svg_id . '_tip';
4700 37 my $width = $self->{width};
4701 37 my $height = $self->{height};
4702 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
4703 37 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 34 37
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2350
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
4704 : qq{width="$width" height="$height"};
4705  
4706 37 ▶ my $is_v = ($orient eq 'v') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$orient eq 'v' ? : 36 1 37
4707 37 my $margin_top = 20;
4708 37 my $margin_right = 130;
4709 37 ▶ my $margin_bottom = $is_v ? ($x_label ? 60 : 40) : 40;
Branch: 2 branches
BranchTrueFalseTotal
$is_v ? : 36 1 37
$x_label ? : 3 33 36
4710 37 ▶ my $margin_left = $is_v ? 55 : 130;
Branch: 1 branch
BranchTrueFalseTotal
$is_v ? : 36 1 37
4711 37 my $inner_w = $width - $margin_left - $margin_right;
4712 37 my $inner_h = $height - $margin_top - $margin_bottom;
4713 37 my $legend_x = $margin_left + $inner_w + 12;
4714  
4715 37 ▶ my $x_label_block = $x_label ? <<"XLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 3 34 37
4716 g.append("text")
4717 .attr("class","sb-axis-label")
4718 .attr("x", innerW / 2)
4719 .attr("y", innerH + (margin.bottom - 10))
4720 .attr("text-anchor","middle")
4721 .text("$x_label_esc");
4722 XLB
4723  
4724 37 my ($scales_js, $axes_js, $rect_attrs_js);
4725 37 ▶ if ($is_v) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_v) { } 36 1 37
4726 36 $scales_js = <<'SCALES';
4727 var xScale = d3.scaleBand()
4728 .domain(data.map(function(d){return d.cat;}))
4729 .range([0, innerW]).padding(0.2);
4730 var yScale = d3.scaleLinear()
4731 .domain([0, d3.max(stackedData[stackedData.length-1], function(d){return d[1];})])
4732 .nice().range([innerH, 0]);
4733 SCALES
4734 36 $axes_js = <<'AXES';
4735 g.append("g").attr("class","sb-x-axis")
4736 .attr("transform","translate(0,"+innerH+")").call(d3.axisBottom(xScale));
4737 g.append("g").attr("class","sb-y-axis").call(d3.axisLeft(yScale).ticks(6));
4738 AXES
4739 36 $rect_attrs_js = <<'RECTS';
4740 .attr("x", function(d){return xScale(d.data.cat);})
4741 .attr("y", function(d){return yScale(d[1]);})
4742 .attr("height", function(d){return Math.max(0, yScale(d[0]) - yScale(d[1]));})
4743 .attr("width", xScale.bandwidth())
4744 RECTS
4745 } else {
4746 1 $scales_js = <<'SCALES';
4747 var yScale = d3.scaleBand()
4748 .domain(data.map(function(d){return d.cat;}))
4749 .range([0, innerH]).padding(0.2);
4750 var xScale = d3.scaleLinear()
4751 .domain([0, d3.max(stackedData[stackedData.length-1], function(d){return d[1];})])
4752 .nice().range([0, innerW]);
4753 SCALES
4754 1 $axes_js = <<'AXES';
4755 g.append("g").attr("class","sb-x-axis")
4756 .attr("transform","translate(0,"+innerH+")").call(d3.axisBottom(xScale).ticks(6));
4757 g.append("g").attr("class","sb-y-axis").call(d3.axisLeft(yScale));
4758 AXES
4759 1 $rect_attrs_js = <<'RECTS';
4760 .attr("y", function(d){return yScale(d.data.cat);})
4761 .attr("x", function(d){return xScale(d[0]);})
4762 .attr("width", function(d){return Math.max(0, xScale(d[1]) - xScale(d[0]));})
4763 .attr("height", yScale.bandwidth())
4764 RECTS
4765 }
4766  
4767 37 my $html = <<"HTML";
4768 <style>
4769 #$tip_id {
4770 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
4771 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
4772 display:none;line-height:1.6;
4773 }
4774 .sb-axis-label{font-size:11px;fill:#555;}
4775 .sb-legend-item{cursor:pointer;}
4776 </style>
4777 <svg id="$svg_id" $svg_attrs></svg>
4778 <div id="$tip_id"></div>
4779 <script>
4780 (function(){
4781 var data = $json_data;
4782 var segs = $json_segs;
4783 var margin = {top:$margin_top,right:$margin_right,bottom:$margin_bottom,left:$margin_left};
4784 var innerW = $inner_w;
4785 var innerH = $inner_h;
4786 $schemes_js
4787 var color = d3.scaleOrdinal(SCHEMES['$scheme'] || $default_js).domain(segs);
4788 var hidden = {};
4789 var svg = d3.select("#$svg_id");
4790 var g = svg.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
4791 var tip = d3.select("#$tip_id");
4792 var stackFn = d3.stack().order(d3.stackOrderNone).offset(d3.stackOffsetNone);
4793 var stackedData = stackFn.keys(segs)(data);
4794 $scales_js
4795 $axes_js
4796 $x_label_block
4797 function redraw(){
4798 var vis = segs.filter(function(s){return !hidden[s];});
4799 var sd = stackFn.keys(vis)(data);
4800 var layers = g.selectAll(".sb-layer").data(sd, function(d){return d.key;});
4801 var entered = layers.enter().append("g").attr("class","sb-layer")
4802 .attr("fill",function(d){return color(d.key);});
4803 entered.merge(layers)
4804 .selectAll(".sb-rect").data(function(d){return d;})
4805 .join("rect").attr("class","sb-rect")
4806 $rect_attrs_js
4807 .on("mouseover",function(event,d){
4808 var seg = d3.select(this.parentNode).datum().key;
4809 tip.style("display","block")
4810 .html("<b>"+d.data.cat+"<\\/b><br\/>"+seg+": "+(d[1]-d[0]));
4811 })
4812 .on("mousemove",function(event){
4813 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
4814 })
4815 .on("mouseout",function(){tip.style("display","none");});
4816 layers.exit().remove();
4817 }
4818 redraw();
4819 var legend = svg.append("g").attr("transform","translate($legend_x,$margin_top)");
4820 segs.forEach(function(seg,i){
4821 var item = legend.append("g").attr("class","sb-legend-item")
4822 .attr("transform","translate(0,"+(i*20)+")")
4823 .on("click",function(){
4824 hidden[seg] = !hidden[seg];
4825 d3.select(this).select("rect").attr("opacity",hidden[seg]?0.3:1);
4826 d3.select(this).select("text").attr("opacity",hidden[seg]?0.4:1);
4827 redraw();
4828 });
4829 item.append("rect").attr("width",12).attr("height",12).attr("y",-10)
4830 .attr("fill",color(seg));
4831 item.append("text").attr("x",16).attr("font-size","11px").attr("fill","#333")
4832 .text(seg);
4833 });
4834 })();
4835 </script>
4836 HTML
4837  
4838 37 return { svg_id => $svg_id, html => $html };
4839 }
4840  
4841 =head2 render_combo_snippet
4842  
4843 my $result = $chart->render_combo_snippet(\@rows, \%opts);
4844  
4845 Generates an embeddable combo chart: bars for one measure on the left Y
4846 axis, a line for another measure on the right Y axis, sharing the same
4847 X (category) axis.
4848  
4849 Each element of C<\@rows> is a hashref with at least three keys named by
4850 C<opts>: C<x_col> (X-axis label), C<bar_col> (bar measure), and
4851 C<line_col> (line measure).
4852  
4853 Accepted C<\%opts> keys:
4854  
4855 =over 4
4856  
4857 =item * C<x_col> (string, default C<'x'>) - row key for the X-axis label.
4858  
4859 =item * C<bar_col> (string, default C<'bar_val'>) - row key for the bar measure.
4860  
4861 =item * C<line_col> (string, default C<'line_val'>) - row key for the line measure.
4862  
4863 =item * C<bar_label> (string, default C<'Bar'>) - legend/axis label for bars.
4864  
4865 =item * C<line_label> (string, default C<'Line'>) - legend/axis label for line.
4866  
4867 =item * C<bar_color> (string, optional CSS colour, default C<'steelblue'>) - bar fill.
4868 A value holding anything a CSS colour cannot, such as a quote or C<E<lt>>, is
4869 ignored and the default used.
4870  
4871 =item * C<line_color> (string, optional CSS colour, default C<'#e15759'>) - line stroke.
4872 Checked as C<bar_color> is.
4873  
4874 =item * C<id> (string, optional) - override the default C<svg_id> value.
4875  
4876 =item * C<responsive> (boolean, optional) - SVG responsive sizing override.
4877  
4878 =back
4879  
4880 Returns C<{ svg_id =E<gt> 'combo_chart', html =E<gt> Str }>.
4881  
4882 =head3 Errors
4883  
4884 =over 4
4885  
4886 =item * Throws C<Data must be an array of hashes> when C<$data> is not an ARRAY reference.
4887  
4888 =item * Throws C<Each data point must be a hash reference> when a row is not a hashref.
4889  
4890 =item * Throws C<Bar value must be numeric> when a bar value field is not a number.
4891  
4892 =item * Throws C<Line value must be numeric> when a line value field is not a number.
4893  
4894 =back
4895  
4896 =head3 API SPECIFICATION
4897  
4898 =head4 Input
4899  
4900 {
4901 data => { type => 'arrayref' },
4902 opts => {
4903 type => 'hashref',
4904 optional => 1,
4905 keys => {
4906 x_col => { type => 'string', optional => 1, default => 'x' },
4907 bar_col => { type => 'string', optional => 1, default => 'bar_val' },
4908 line_col => { type => 'string', optional => 1, default => 'line_val' },
4909 bar_label => { type => 'string', optional => 1, default => 'Bar' },
4910 line_label => { type => 'string', optional => 1, default => 'Line' },
4911 bar_color => { type => 'string', optional => 1, default => 'steelblue' },
4912 line_color => { type => 'string', optional => 1, default => '#e15759' },
4913 id => { type => 'string', optional => 1, default => 'combo_chart' },
4914 responsive => { type => 'boolean', optional => 1 },
4915 },
4916 },
4917 }
4918  
4919 =head4 Output
4920  
4921 HashRef -- { svg_id => Str, html => Str }
4922  
4923 =cut
4924  
4925 sub render_combo_snippet
4926 52 ▶{
Subroutine render_combo_snippet: called CC=20 SCAR=30.0
Pod documented
4927 52 my $self = shift;
4928 52 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
520
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
4929 52 ▶ die 'Data must be an array of hashes' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 1 51 52
4930 51 Params::Validate::Strict::validate_strict({
4931 args => $raw,
4932 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of hashes' } },
4933 unknown_parameter_handler => 'ignore',
4934 });
4935 51 my $data = $raw->{data};
4936 51 my $opts = {%$raw}; delete $opts->{data};
4937  
4938 51 ▶ my $x_col = $opts->{x_col} // 'x';
Condition100%2/2
$opts->{"x_col"} // "x"
l!l
150
MC/DC100%1/1
$opts->{"x_col"} // "x"
$opts->{"x_col"}
Truth table100%2/2
A
A= $opts->{"x_col"}
Aresult
11
00
4939 51 ▶ my $bar_col = $opts->{bar_col} // 'bar_val';
Condition100%2/2
$opts->{"bar_col"} // "bar_val"
l!l
150
MC/DC100%1/1
$opts->{"bar_col"} // "bar_val"
$opts->{"bar_col"}
Truth table100%2/2
A
A= $opts->{"bar_col"}
Aresult
11
00
4940 51 ▶ my $line_col = $opts->{line_col} // 'line_val';
Condition100%2/2
$opts->{"line_col"} // "line_val"
l!l
150
MC/DC100%1/1
$opts->{"line_col"} // "line_val"
$opts->{"line_col"}
Truth table100%2/2
A
A= $opts->{"line_col"}
Aresult
11
00
4941 51 ▶ my $bar_label = $opts->{bar_label} // 'Bar';
Condition100%2/2
$opts->{"bar_label"} // "Bar"
l!l
348
MC/DC100%1/1
$opts->{"bar_label"} // "Bar"
$opts->{"bar_label"}
Truth table100%2/2
A
A= $opts->{"bar_label"}
Aresult
11
00
4942 51 ▶ my $line_label = $opts->{line_label} // 'Line';
Condition100%2/2
$opts->{"line_label"} // "Line"
l!l
348
MC/DC100%1/1
$opts->{"line_label"} // "Line"
$opts->{"line_label"}
Truth table100%2/2
A
A= $opts->{"line_label"}
Aresult
11
00
4943 51 ▶ my $bar_color = _css_colour($opts->{bar_color}) // 'steelblue';
Condition100%2/2
_css_colour($opts->{"bar_color"}) // "steelblue"
l!l
744
MC/DC100%1/1
_css_colour($opts->{"bar_color"}) // "steelblue"
_css_colour($opts->{"bar_color"})
Truth table100%2/2
A
A= _css_colour($opts->{"bar_color"})
Aresult
11
00
4944 51 ▶ my $line_color = _css_colour($opts->{line_color}) // '#e15759';
Condition100%2/2
_css_colour($opts->{"line_color"}) // "#e15759"
l!l
744
MC/DC100%1/1
_css_colour($opts->{"line_color"}) // "#e15759"
_css_colour($opts->{"line_color"})
Truth table100%2/2
A
A= _css_colour($opts->{"line_color"})
Aresult
11
00
4945  
4946 51 my @points;
4947 51 for my $row (@$data) {
4948 70 ▶ die 'Each data point must be a hash reference' unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 69 70
4949 69 ▶ die 'Bar value must be numeric' unless looks_like_number($row->{$bar_col} // 'x');
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number(scalar($row->{$bar_col} // "x")) 1 68 69
Condition50%1/2
$row->{$bar_col} // "x"
l!l
690
MC/DC0%0/1
$row->{$bar_col} // "x"
$row->{$bar_col}
Truth table50%1/2
A
A= $row->{$bar_col}
Aresult
11
00
4950 68 ▶ die 'Line value must be numeric' unless looks_like_number($row->{$line_col} // 'x');
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number(scalar($row->{$line_col} // "x")) 1 67 68
Condition50%1/2
$row->{$line_col} // "x"
l!l
680
MC/DC0%0/1
$row->{$line_col} // "x"
$row->{$line_col}
Truth table50%1/2
A
A= $row->{$line_col}
Aresult
11
00
4951 push @points, {
4952 x => defined($row->{$x_col}) ? "$row->{$x_col}" : '',
4953 bar => $row->{$bar_col} + 0,
4954 67 ▶ line => $row->{$line_col} + 0,
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{$x_col} ? : 67 0 67
4955 };
4956 }
4957  
4958 48 my $json_data = _script_json(\@points);
4959  
4960 48 my $js_esc = \&_js_string;
4961  
4962 48 my $bar_label_esc = $js_esc->($bar_label);
4963 48 my $line_label_esc = $js_esc->($line_label);
4964 48 my $bar_color_esc = $js_esc->($bar_color);
4965 48 my $line_color_esc = $js_esc->($line_color);
4966  
4967 48 ▶ my $svg_id = _chart_id($opts->{id}) // 'combo_chart';
Condition100%2/2
_chart_id($opts->{"id"}) // "combo_chart"
l!l
543
MC/DC100%1/1
_chart_id($opts->{"id"}) // "combo_chart"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
4968 48 my $tip_id = $svg_id . '_tip';
4969 48 my $width = $self->{width};
4970 48 my $height = $self->{height};
4971 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
4972 48 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 45 48
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2460
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
4973 : qq{width="$width" height="$height"};
4974  
4975 48 my $margin_top = 20;
4976 48 my $margin_right = 70;
4977 48 my $margin_bottom = 55;
4978 48 my $margin_left = 60;
4979 48 my $inner_w = $width - $margin_left - $margin_right;
4980 48 my $inner_h = $height - $margin_top - $margin_bottom;
4981  
4982 48 my $html = <<"HTML";
4983 <style>
4984 #$tip_id {
4985 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
4986 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
4987 display:none;line-height:1.6;
4988 }
4989 .cc-axis-label{font-size:11px;fill:#555;}
4990 .cc-dot{cursor:default;}
4991 </style>
4992 <svg id="$svg_id" $svg_attrs></svg>
4993 <div id="$tip_id"></div>
4994 <script>
4995 (function(){
4996 var data = $json_data;
4997 var margin = {top:$margin_top,right:$margin_right,bottom:$margin_bottom,left:$margin_left};
4998 var innerW = $inner_w;
4999 var innerH = $inner_h;
5000 var barLabel = "$bar_label_esc";
5001 var lineLabel = "$line_label_esc";
5002 var barColor = "$bar_color_esc";
5003 var lineColor = "$line_color_esc";
5004 var svg = d3.select("#$svg_id");
5005 var g = svg.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
5006 var tip = d3.select("#$tip_id");
5007  
5008 var xScale = d3.scaleBand()
5009 .domain(data.map(function(d){return d.x;}))
5010 .range([0, innerW]).padding(0.25);
5011 var yLeft = d3.scaleLinear()
5012 .domain([0, d3.max(data,function(d){return d.bar;})]).nice()
5013 .range([innerH, 0]);
5014 var yRight = d3.scaleLinear()
5015 .domain([d3.min(data,function(d){return d.line;}), d3.max(data,function(d){return d.line;})])
5016 .nice().range([innerH, 0]);
5017  
5018 g.append("g").attr("class","cc-x-axis")
5019 .attr("transform","translate(0,"+innerH+")").call(d3.axisBottom(xScale));
5020 g.append("g").attr("class","cc-y-left").call(d3.axisLeft(yLeft).ticks(6));
5021 g.append("g").attr("class","cc-y-right")
5022 .attr("transform","translate("+innerW+",0)").call(d3.axisRight(yRight).ticks(6));
5023  
5024 // Left axis label
5025 g.append("text").attr("class","cc-axis-label")
5026 .attr("transform","rotate(-90)")
5027 .attr("x",-innerH/2).attr("y",-(margin.left-15))
5028 .attr("text-anchor","middle").text(barLabel);
5029 // Right axis label
5030 svg.append("text").attr("class","cc-axis-label")
5031 .attr("transform","rotate(90)")
5032 .attr("x",(margin.top+innerH/2)).attr("y",-(margin.left+innerW+margin.right-15))
5033 .attr("text-anchor","middle").text(lineLabel);
5034 // X axis label
5035 g.append("text").attr("class","cc-axis-label")
5036 .attr("x",innerW/2).attr("y",innerH+(margin.bottom-12))
5037 .attr("text-anchor","middle").text(barLabel+" vs "+lineLabel);
5038  
5039 // Bars
5040 g.selectAll(".cc-bar").data(data).join("rect")
5041 .attr("class","cc-bar")
5042 .attr("x",function(d){return xScale(d.x);})
5043 .attr("y",function(d){return yLeft(d.bar);})
5044 .attr("width",xScale.bandwidth())
5045 .attr("height",function(d){return innerH - yLeft(d.bar);})
5046 .attr("fill",barColor).attr("opacity",0.8)
5047 .on("mouseover",function(event,d){
5048 tip.style("display","block")
5049 .html("<b>"+d.x+"<\\/b><br\/>"+barLabel+": "+d.bar+"<br\/>"+lineLabel+": "+d.line);
5050 })
5051 .on("mousemove",function(event){
5052 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
5053 })
5054 .on("mouseout",function(){tip.style("display","none");});
5055  
5056 // Line path
5057 var line = d3.line()
5058 .x(function(d){return xScale(d.x) + xScale.bandwidth()/2;})
5059 .y(function(d){return yRight(d.line);});
5060 g.append("path").datum(data)
5061 .attr("fill","none").attr("stroke",lineColor).attr("stroke-width",2.5)
5062 .attr("d",line);
5063  
5064 // Dots
5065 g.selectAll(".cc-dot").data(data).join("circle")
5066 .attr("class","cc-dot")
5067 .attr("cx",function(d){return xScale(d.x) + xScale.bandwidth()/2;})
5068 .attr("cy",function(d){return yRight(d.line);})
5069 .attr("r",4).attr("fill",lineColor).attr("stroke","#fff").attr("stroke-width",1.5)
5070 .on("mouseover",function(event,d){
5071 tip.style("display","block")
5072 .html("<b>"+d.x+"<\\/b><br\/>"+barLabel+": "+d.bar+"<br\/>"+lineLabel+": "+d.line);
5073 })
5074 .on("mousemove",function(event){
5075 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
5076 })
5077 .on("mouseout",function(){tip.style("display","none");});
5078  
5079 // Legend
5080 var lg = svg.append("g").attr("transform","translate("+(margin.left+8)+","+(margin.top+8)+")");
5081 lg.append("rect").attr("width",12).attr("height",12).attr("fill",barColor).attr("opacity",0.8);
5082 lg.append("text").attr("x",16).attr("y",10).attr("font-size","11px").attr("fill","#333").text(barLabel);
5083 var lg2 = svg.append("g").attr("transform","translate("+(margin.left+8)+","+(margin.top+26)+")");
5084 lg2.append("line").attr("x1",0).attr("y1",6).attr("x2",12).attr("y2",6)
5085 .attr("stroke",lineColor).attr("stroke-width",2.5);
5086 lg2.append("circle").attr("cx",6).attr("cy",6).attr("r",4).attr("fill",lineColor);
5087 lg2.append("text").attr("x",16).attr("y",10).attr("font-size","11px").attr("fill","#333").text(lineLabel);
5088 })();
5089 </script>
5090 HTML
5091  
5092 48 return { svg_id => $svg_id, html => $html };
5093 }
5094  
5095 =head2 render_treemap_snippet
5096  
5097 my $result = $chart->render_treemap_snippet(\@rows_or_tree, \%opts);
5098  
5099 Generates an embeddable treemap (no page shell, no CDN tag).
5100 Leaf area is proportional to the numeric measure.
5101  
5102 Accepts two data formats:
5103  
5104 =over 4
5105  
5106 =item * B<Flat path> (arrayref of hashrefs): each row must have a C<path>
5107 key (e.g. C<'Root/A/X'>) and a C<value> key. The module converts this
5108 to a D3 stratify hierarchy in JS. Override the path separator with
5109 C<opts-E<gt>{path_sep}>.
5110  
5111 =item * B<Nested tree> (hashref): a pre-built D3-compatible hierarchy
5112 with C<name>/C<children>/C<value> structure. Passed directly to
5113 C<d3.hierarchy()>.
5114  
5115 =back
5116  
5117 Accepted C<\%opts> keys:
5118  
5119 =over 4
5120  
5121 =item * C<path_sep> (string, default C<'/'>) - path separator (flat format only).
5122  
5123 =item * C<scheme> (string, default C<'tableau10'>) - D3 categorical colour scheme.
5124 Supported: C<tableau10>, C<category10>, C<set2>, C<set3>, C<paired> - the names
5125 C<categorical_schemes()> returns, whose colours C<palette()> makes available to
5126 Perl.
5127  
5128 =item * C<label> (boolean, default C<1>) - show node labels inside cells.
5129  
5130 =item * C<id> (string, optional) - override the default C<svg_id> value.
5131  
5132 =item * C<responsive> (boolean, optional) - SVG responsive sizing override.
5133  
5134 =back
5135  
5136 Returns C<{ svg_id =E<gt> 'treemap', html =E<gt> Str }>.
5137  
5138 =head3 Errors
5139  
5140 =over 4
5141  
5142 =item * Throws C<Data must be an array of hashes or a hash tree>
5143 when C<$data> is neither an ARRAY nor a HASH reference.
5144  
5145 =item * Throws C<Each flat row must be a hash reference> when a flat row is not a hashref.
5146  
5147 =item * Throws C<Each flat row must have a 'path' key> when a flat row lacks C<path>.
5148  
5149 =item * Throws C<Each flat row must have a numeric 'value' key> when a value is not numeric.
5150  
5151 =back
5152  
5153 =head3 API SPECIFICATION
5154  
5155 =head4 Input
5156  
5157 {
5158 data => { type => 'arrayref | hashref' },
5159 opts => {
5160 type => 'hashref',
5161 optional => 1,
5162 keys => {
5163 path_sep => { type => 'string', optional => 1, default => '/' },
5164 scheme => { type => 'string', optional => 1, default => 'tableau10' },
5165 label => { type => 'boolean', optional => 1, default => 1 },
5166 id => { type => 'string', optional => 1, default => 'treemap' },
5167 responsive => { type => 'boolean', optional => 1 },
5168 },
5169 },
5170 }
5171  
5172 =head4 Output
5173  
5174 HashRef -- { svg_id => Str, html => Str }
5175  
5176 =cut
5177  
5178 sub render_treemap_snippet
5179 39 ▶{
Subroutine render_treemap_snippet: called CC=20 SCAR=30.0
Pod documented
5180 39 my $self = shift;
5181 39 ▶ my $first = @_ ? $_[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 39 0 39
5182 39 my $raw;
5183 # A lone hashref argument is valid treemap data (hash tree), not named args
5184 39 ▶ if (ref($first) eq 'HASH' && @_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $first eq 'HASH' and @_ == 1) { } 1 38 39
Condition66%2/3
ref $first eq "HASH" and @_ == 1
!ll&&!rl&&r
3801
MC/DC50%1/2
ref $first eq "HASH" and @_ == 1
ref $first eq "HASH" @_ == 1
Truth table66%2/3
A and B
A= ref $first eq "HASH"B= @_ == 1
ABresult
0X0
100
111
5185 1 $raw = { data => $first };
5186 } else {
5187 38 ▶ $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
380
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
5188 }
5189 die 'Data must be an array of hashes or a hash tree'
5190 39 ▶ unless ref($raw->{data}) eq 'ARRAY' || ref($raw->{data}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" or ref $raw->{"data"} eq "HASH" 1 38 39
Condition100%3/3
ref $raw->{"data"} eq "ARRAY" or ref $raw->{"data"} eq "HASH"
l!l&&r!l&&!r
3711
MC/DC100%2/2
ref $raw->{"data"} eq "ARRAY" or ref $raw->{"data"} eq "HASH"
ref $raw->{"data"} eq "ARRAY" ref $raw->{"data"} eq "HASH"
Truth table100%3/3
A or B
A= ref $raw->{"data"} eq "ARRAY"B= ref $raw->{"data"} eq "HASH"
ABresult
1X1
011
000
5191 38 Params::Validate::Strict::validate_strict({
5192 args => $raw,
5193 schema => { data => { type => ['arrayref', 'hashref'], error_msg => 'Data must be an array of hashes or a hash tree' } },
5194 unknown_parameter_handler => 'ignore',
5195 });
5196 38 my $data = $raw->{data};
5197 38 my $opts = {%$raw}; delete $opts->{data};
5198  
5199 38 ▶ my $path_sep = $opts->{path_sep} // '/';
Condition100%2/2
$opts->{"path_sep"} // "/"
l!l
335
MC/DC100%1/1
$opts->{"path_sep"} // "/"
$opts->{"path_sep"}
Truth table100%2/2
A
A= $opts->{"path_sep"}
Aresult
11
00
5200 38 my $scheme = _scheme_name($opts->{scheme});
5201 38 ▶ my $label = exists($opts->{label}) ? ($opts->{label} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $opts->{'label'} ? : 2 36 38
$opts->{'label'} ? : 1 1 2
5202 38 my $schemes_js = $self->_schemes_js('var');
5203 38 my $default_js = _default_scheme_js();
5204  
5205 38 my $js_esc = \&_js_string;
5206  
5207 38 my ($json_data, $build_js);
5208 38 ▶ if (ref($data) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq 'ARRAY') { } 37 1 38
5209 37 for my $row (@$data) {
5210 62 ▶ die 'Each flat row must be a hash reference' unless ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 1 61 62
5211 61 ▶ die "Each flat row must have a 'path' key" unless exists $row->{path};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{"path"} 1 60 61
5212 die "Each flat row must have a numeric 'value' key"
5213 60 ▶ unless looks_like_number($row->{value} // 'x');
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number(scalar($row->{"value"} // "x")) 1 59 60
Condition50%1/2
$row->{"value"} // "x"
l!l
600
MC/DC0%0/1
$row->{"value"} // "x"
$row->{"value"}
Truth table50%1/2
A
A= $row->{"value"}
Aresult
11
00
5214 }
5215 34 my @flat = map { { path => "$_->{path}", value => $_->{value} + 0 } } @$data;
5216 34 $json_data = _script_json(\@flat);
5217 34 my $sep_esc = $js_esc->($path_sep);
5218 34 $build_js = <<"BUILDJS";
5219 var sep = "$sep_esc";
5220 var nodeMap = {};
5221 rawData.forEach(function(r){
5222 var parts = r.path.split(sep);
5223 var id = r.path;
5224 if(!nodeMap[id]){ nodeMap[id] = {id:id, value:r.value}; }
5225 for(var i = parts.length-1; i >= 1; i--){
5226 var pid = parts.slice(0,i).join(sep);
5227 if(!nodeMap[pid]){ nodeMap[pid] = {id:pid, value:0}; }
5228 }
5229 var root0 = parts[0];
5230 if(!nodeMap[root0]){ nodeMap[root0] = {id:root0, value:0}; }
5231 });
5232 var nodes = Object.values(nodeMap).map(function(n){
5233 var parts = n.id.split(sep);
5234 return {id:n.id, parentId: parts.length>1 ? parts.slice(0,parts.length-1).join(sep) : null, value:n.value};
5235 });
5236 var root = d3.stratify().id(function(d){return d.id;})
5237 .parentId(function(d){return d.parentId;})(nodes)
5238 .sum(function(d){return d.value || 0;})
5239 .sort(function(a,b){return b.value - a.value;});
5240 BUILDJS
5241 } else {
5242 1 $json_data = _script_json($data);
5243 1 $build_js = <<'BUILDJS';
5244 var root = d3.hierarchy(rawData)
5245 .sum(function(d){return d.value || 0;})
5246 .sort(function(a,b){return b.value - a.value;});
5247 BUILDJS
5248 }
5249  
5250 35 ▶ my $svg_id = _chart_id($opts->{id}) // 'treemap';
Condition100%2/2
_chart_id($opts->{"id"}) // "treemap"
l!l
530
MC/DC100%1/1
_chart_id($opts->{"id"}) // "treemap"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
5251 35 my $tip_id = $svg_id . '_tip';
5252 35 my $width = $self->{width};
5253 35 my $height = $self->{height};
5254 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
5255 35 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 32 35
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2330
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
5256 : qq{width="$width" height="$height"};
5257  
5258 35 ▶ my $label_block = $label ? <<"LBLJS" : '';
Branch: 1 branch
BranchTrueFalseTotal
$label ? : 34 1 35
5259 cell.append("text")
5260 .attr("class","tm-label")
5261 .attr("x",4).attr("y",14)
5262 .attr("font-size","11px").attr("fill","#fff")
5263 .text(function(d){
5264 var w = d.x1 - d.x0, h = d.y1 - d.y0;
5265 if(w < 24 || h < 14){ return ""; }
5266 var name = d.id ? d.id.split(sep||"/").pop() : (d.data.name||"");
5267 return name;
5268 })
5269 .each(function(d){
5270 var w = d.x1 - d.x0 - 6;
5271 var self2 = d3.select(this);
5272 var text = self2.text();
5273 while(self2.node().getComputedTextLength && self2.node().getComputedTextLength() > w && text.length > 1){
5274 text = text.slice(0,-1);
5275 self2.text(text + "…");
5276 }
5277 });
5278 LBLJS
5279  
5280 35 my $html = <<"HTML";
5281 <style>
5282 #$tip_id {
5283 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
5284 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
5285 display:none;line-height:1.6;
5286 }
5287 .tm-cell{stroke:#fff;stroke-width:1;}
5288 .tm-label{pointer-events:none;}
5289 </style>
5290 <svg id="$svg_id" $svg_attrs></svg>
5291 <div id="$tip_id"></div>
5292 <script>
5293 (function(){
5294 var rawData = $json_data;
5295 $schemes_js
5296 var color = d3.scaleOrdinal(SCHEMES['$scheme'] || $default_js);
5297 35 var sep = "${\$js_esc->($path_sep)}";
5298 var svg = d3.select("#$svg_id");
5299 var tip = d3.select("#$tip_id");
5300 $build_js
5301 var layout = d3.treemap().tile(d3.treemapSquarify)
5302 .size([$width, $height]).paddingOuter(2).paddingInner(1)(root);
5303 var leaves = root.leaves();
5304 var cell = svg.selectAll(".tm-cell-g")
5305 .data(leaves).join("g").attr("class","tm-cell-g")
5306 .attr("transform",function(d){return "translate("+d.x0+","+d.y0+")";});
5307 cell.append("rect")
5308 .attr("class","tm-cell")
5309 .attr("width",function(d){return Math.max(0,d.x1-d.x0);})
5310 .attr("height",function(d){return Math.max(0,d.y1-d.y0);})
5311 .attr("fill",function(d){
5312 var anc = d; while(anc.depth > 1){ anc = anc.parent; }
5313 return color(anc.id || anc.data.name || "");
5314 })
5315 .on("mouseover",function(event,d){
5316 var name = d.id ? d.id.split(sep).pop() : (d.data.name||"");
5317 tip.style("display","block")
5318 .html("<b>"+name+"<\\/b><br\/>"+d.value);
5319 })
5320 .on("mousemove",function(event){
5321 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
5322 })
5323 .on("mouseout",function(){tip.style("display","none");});
5324 $label_block
5325 })();
5326 </script>
5327 HTML
5328  
5329 35 return { svg_id => $svg_id, html => $html };
5330 }
5331  
5332 =head2 render_histogram_snippet
5333  
5334 my $result = $chart->render_histogram_snippet(\@values, \%opts);
5335  
5336 Generates an embeddable frequency histogram (no page shell, no CDN tag).
5337 C<\@values> is an arrayref of numeric scalars (already extracted and
5338 coerced by the caller).
5339  
5340 Accepted C<\%opts> keys:
5341  
5342 =over 4
5343  
5344 =item * C<bins> (integer or C<undef>, default C<20>) - number of bins.
5345 Pass C<undef> for automatic bin count using Sturges' rule:
5346 C<ceil(log2(n) + 1)>. Ignored when C<binned> is set.
5347  
5348 =item * C<binned> (boolean, default 0) - treat C<$data> as pre-computed bins
5349 rather than as raw values. Each element is a hashref with a C<count> and
5350 either a C<label> or a numeric C<lo>/C<hi> pair from which the label C<[lo,hi)>
5351 is derived:
5352  
5353 { label => '[0,10)', count => 3 }
5354 { lo => 10, hi => 20, count => 5 }
5355  
5356 The caller owns the binning, so C<d3.bin()> is never called: one bar is drawn
5357 per entry, in the order supplied, and the supplied counts are authoritative.
5358  
5359 The bin labels are drawn rotated. The plot gives up as much room as they need,
5360 up to half the chart's height and a quarter of its width, so that they and
5361 C<x_label> do not overlap and stay inside the chart.
5362  
5363 =item * C<scheme> (string, optional) - D3 categorical colour scheme (for example
5364 C<'tableau10'> or C<'category10'>) whose first colour is used as the bar fill
5365 when C<color> is not given.
5366 That colour is C<colour_at($scheme, 0)>, so a caller shading the same data by
5367 hand starts from the same colour the bars do.
5368  
5369 =item * C<x_label> (string, optional) - label shown below the X axis.
5370  
5371 =item * C<color> (string, default C<'steelblue'>) - bar fill colour.
5372 A value holding anything a CSS colour cannot, such as a quote or C<E<lt>>, is
5373 ignored and the default used.
5374  
5375 =item * C<id> (string, optional) - override the default C<svg_id> value.
5376  
5377 =item * C<responsive> (boolean, optional) - SVG responsive sizing override.
5378  
5379 =back
5380  
5381 Returns C<{ svg_id =E<gt> 'histogram', html =E<gt> Str }>.
5382  
5383 =head3 Errors
5384  
5385 =over 4
5386  
5387 =item * Throws C<Data must be an array of numeric values> when C<$data> is
5388 not an ARRAY reference.
5389  
5390 =item * Throws C<Each value must be numeric> when any element is non-numeric.
5391  
5392 =item * Throws C<bins must be a positive integer> when C<bins> is defined
5393 but not a positive integer.
5394  
5395 =item * Throws C<Data must contain at least one bin> when C<binned> is set and
5396 C<$data> holds no bins.
5397  
5398 =item * Throws C<Each pre-binned entry must be a hash reference> when a
5399 pre-binned element is not a hashref.
5400  
5401 =item * Throws C<Bin count must be numeric> when a pre-binned C<count> is
5402 missing or not numeric.
5403  
5404 =item * Throws C<Bin count must not be negative> when a pre-binned C<count> is
5405 negative.
5406  
5407 =item * Throws C<Each pre-binned entry must have a label or numeric lo and hi>
5408 when a pre-binned entry has neither a C<label> nor a numeric C<lo>/C<hi> pair.
5409  
5410 =back
5411  
5412 =head3 API SPECIFICATION
5413  
5414 =head4 Input
5415  
5416 {
5417 data => { type => 'arrayref' },
5418 opts => {
5419 type => 'hashref',
5420 optional => 1,
5421 keys => {
5422 bins => { type => 'integer', optional => 1, default => 20 },
5423 binned => { type => 'boolean', optional => 1, default => 0 },
5424 x_label => { type => 'string', optional => 1, default => '' },
5425 color => { type => 'string', optional => 1, default => 'steelblue' },
5426 scheme => { type => 'string', optional => 1 },
5427 id => { type => 'string', optional => 1, default => 'histogram' },
5428 responsive => { type => 'boolean', optional => 1 },
5429 },
5430 },
5431 }
5432  
5433 =head4 Output
5434  
5435 HashRef -- { svg_id => Str, html => Str }
5436  
5437 =cut
5438  
5439 # _render_histogram_binned($self, \@bins, \%opts)
5440 # Internal helper for the binned => 1 path of render_histogram_snippet.
5441 # $bins: [ {label=>'[0,10)',count=>N}, ... ] or [ {lo=>0,hi=>10,count=>N}, ... ]
5442 sub _render_histogram_binned
5443 26 ▶{
Subroutine _render_histogram_binned: called CC=24 SCAR=31.8
5444 26 my ($self, $bins, $opts) = @_;
5445  
5446 26 my $js_esc = \&_js_string;
5447  
5448 26 ▶ die 'Data must contain at least one bin' unless @$bins;
Branch: 1 branch
BranchTrueFalseTotal
unless @$bins 1 25 26
5449  
5450 25 my @norm;
5451 25 for my $b (@$bins) {
5452 37 ▶ die 'Each pre-binned entry must be a hash reference'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $b eq "HASH" 1 36 37
5453 unless ref($b) eq 'HASH';
5454 die 'Bin count must be numeric'
5455 36 ▶ unless defined($b->{count}) && looks_like_number($b->{count});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $b->{"count"} and &looks_like_number($b->{"count"}) 2 34 36
Condition100%3/3
defined $b->{"count"} and &looks_like_number($b->{"count"})
!ll&&!rl&&r
1134
MC/DC100%2/2
defined $b->{"count"} and &looks_like_number($b->{"count"})
defined $b->{"count"} &looks_like_number($b->{"count"})
Truth table100%3/3
A and B
A= defined $b->{"count"}B= &looks_like_number($b->{"count"})
ABresult
0X0
100
111
5456 34 ▶ die 'Bin count must not be negative' unless $b->{count} + 0 >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $b->{"count"} + 0 >= 0 1 33 34
5457  
5458 33 ▶ my $lo = (defined($b->{lo}) && looks_like_number($b->{lo})) ? $b->{lo} + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $b->{'lo'} && &looks_like_number($b->{'lo'}) ? : 13 20 33
Condition66%2/3
defined $b->{"lo"} and &looks_like_number($b->{"lo"})
!ll&&!rl&&r
20013
MC/DC50%1/2
defined $b->{"lo"} and &looks_like_number($b->{"lo"})
defined $b->{"lo"} &looks_like_number($b->{"lo"})
Truth table66%2/3
A and B
A= defined $b->{"lo"}B= &looks_like_number($b->{"lo"})
ABresult
0X0
100
111
5459 33 ▶ my $hi = (defined($b->{hi}) && looks_like_number($b->{hi})) ? $b->{hi} + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $b->{'hi'} && &looks_like_number($b->{'hi'}) ? : 12 21 33
Condition66%2/3
defined $b->{"hi"} and &looks_like_number($b->{"hi"})
!ll&&!rl&&r
21012
MC/DC50%1/2
defined $b->{"hi"} and &looks_like_number($b->{"hi"})
defined $b->{"hi"} &looks_like_number($b->{"hi"})
Truth table66%2/3
A and B
A= defined $b->{"hi"}B= &looks_like_number($b->{"hi"})
ABresult
0X0
100
111
5460  
5461 33 my $label = $b->{label};
5462 33 ▶ if(!defined($label) || !length($label)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $label and length $label) 4 29 33
Condition66%2/3
defined $label and length $label
!ll&&!rl&&r
4029
MC/DC50%1/2
defined $label and length $label
defined $label length $label
Truth table66%2/3
A and B
A= defined $labelB= length $label
ABresult
0X0
100
111
5463 4 ▶ die 'Each pre-binned entry must have a label or numeric lo and hi'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lo and defined $hi 2 2 4
Condition100%3/3
defined $lo and defined $hi
!ll&&!rl&&r
112
MC/DC100%2/2
defined $lo and defined $hi
defined $lo defined $hi
Truth table100%3/3
A and B
A= defined $loB= defined $hi
ABresult
0X0
100
111
5464 unless defined($lo) && defined($hi);
5465 2 $label = sprintf('[%g,%g)', $lo, $hi);
5466 }
5467  
5468 31 push @norm, { label => "$label", count => $b->{count} + 0 };
5469 }
5470  
5471 19 my $json_data = _script_json(\@norm);
5472  
5473 19 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
217
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
5474 19 ▶ my $svg_id = _chart_id($opts->{id}) // 'histogram';
Condition100%2/2
_chart_id($opts->{"id"}) // "histogram"
l!l
118
MC/DC100%1/1
_chart_id($opts->{"id"}) // "histogram"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
5475 19 my $tip_id = $svg_id . '_tip';
5476 19 my $width = $self->{width};
5477 19 my $height = $self->{height};
5478 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
5479 19 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 16 19
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2170
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
5480 : qq{width="$width" height="$height"};
5481  
5482 19 ▶ my $margin_bottom = $x_label ? 60 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 2 17 19
5483 19 my $margin_left = 55;
5484 19 my $margin_top = 20;
5485 19 my $margin_right = 20;
5486 19 my $inner_w = $width - $margin_left - $margin_right;
5487 19 my $inner_h = $height - $margin_top - $margin_bottom;
5488  
5489 19 my $x_label_esc = $js_esc->($x_label);
5490  
5491 # The rotated tick labels hang below the axis and out to its left by however
5492 # long they are, which is only known once they are drawn, so the script
5493 # measures them and takes the room out of the plot. This is what keeps the
5494 # axis label clear of them.
5495 #
5496 # The label also carries its font as attributes, because an SVG saved from the
5497 # page leaves the stylesheet behind.
5498 19 ▶ my $x_label_room = $x_label ? 24 : 4;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 2 17 19
5499  
5500 # Bar fill: an explicit colour wins, otherwise the first colour of the
5501 # requested D3 categorical scheme, otherwise the default colour.
5502 19 my $fill_js = '"steelblue"';
5503 19 my $colour = _css_colour($opts->{color});
5504 19 ▶ if(defined $colour) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $colour) { } 2 17 19
elsif (defined $opts->{'scheme'}) { } 8 9 17
5505 2 $fill_js = '"' . $js_esc->($colour) . '"';
5506 } elsif(defined $opts->{scheme}) {
5507 # The scheme's first colour, which is the one colour_at($scheme, 0)
5508 # reports to a Perl caller colouring the same data by hand.
5509 8 $fill_js = _scheme_js($opts->{scheme}) . '[0]';
5510 }
5511  
5512 19 ▶ my $x_label_block = $x_label ? <<"XLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 2 17 19
5513 g.append("text")
5514 .attr("class","hg-axis-label")
5515 .attr("font-size","11px")
5516 .attr("font-family","sans-serif")
5517 .attr("x", innerW / 2)
5518 .attr("y", innerH + (margin.bottom - 10))
5519 .attr("text-anchor","middle")
5520 .text("$x_label_esc");
5521 XLB
5522  
5523 19 my $html = <<"HTML";
5524 <style>
5525 #$tip_id {
5526 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
5527 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
5528 display:none;line-height:1.6;
5529 }
5530 .hg-axis-label{font-size:11px;fill:#555;}
5531 .hg-bar{cursor:default;}
5532 </style>
5533 <svg id="$svg_id" $svg_attrs></svg>
5534 <div id="$tip_id"></div>
5535 <script>
5536 (function(){
5537 var bins = $json_data;
5538 var margin = {top:$margin_top,right:$margin_right,bottom:$margin_bottom,left:$margin_left};
5539 var innerW = $inner_w;
5540 var innerH = $inner_h;
5541 var svg = d3.select("#$svg_id");
5542 var g = svg.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
5543 var tip = d3.select("#$tip_id");
5544  
5545 function esc(s) {
5546 return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5547 }
5548  
5549 var xScale = d3.scaleBand()
5550 .domain(bins.map(function(d){return d.label;}))
5551 .range([0, innerW])
5552 .padding(0.05);
5553  
5554 var xAxis = g.append("g").attr("class","hg-x-axis");
5555 function drawXAxis() {
5556 xAxis.attr("transform","translate(0,"+innerH+")")
5557 .call(d3.axisBottom(xScale))
5558 .selectAll("text")
5559 .attr("transform","rotate(-45)")
5560 .style("text-anchor","end");
5561 }
5562 drawXAxis();
5563  
5564 var axisBox = xAxis.node().getBBox();
5565 margin.bottom = Math.max(margin.bottom, Math.min(Math.ceil(axisBox.height) + $x_label_room, $height / 2));
5566 margin.left = Math.max(margin.left, Math.min(Math.ceil(-axisBox.x) + 4, $width / 4));
5567 innerW = $width - margin.left - margin.right;
5568 innerH = $height - margin.top - margin.bottom;
5569 g.attr("transform","translate("+margin.left+","+margin.top+")");
5570 xScale.range([0, innerW]);
5571 drawXAxis();
5572  
5573 var yScale = d3.scaleLinear()
5574 .domain([0, d3.max(bins, function(d){return d.count;})]).nice()
5575 .range([innerH, 0]);
5576  
5577 g.append("g").attr("class","hg-y-axis").call(d3.axisLeft(yScale).ticks(6));
5578  
5579 $x_label_block
5580 g.selectAll(".hg-bar").data(bins).join("rect")
5581 .attr("class","hg-bar")
5582 .attr("x",function(d){return xScale(d.label);})
5583 .attr("y",function(d){return yScale(d.count);})
5584 .attr("width",xScale.bandwidth())
5585 .attr("height",function(d){return innerH - yScale(d.count);})
5586 .attr("fill",$fill_js)
5587 .on("mouseover",function(event,d){
5588 tip.style("display","block")
5589 .html("<b>"+esc(d.label)+"<\\/b><br\/>Count: "+d.count);
5590 })
5591 .on("mousemove",function(event){
5592 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
5593 })
5594 .on("mouseout",function(){tip.style("display","none");});
5595 })();
5596 </script>
5597 HTML
5598  
5599 19 return { svg_id => $svg_id, html => $html };
5600 }
5601  
5602 sub render_histogram_snippet
5603 69 ▶{
Subroutine render_histogram_snippet: called CC=20 SCAR=30.0
Pod documented
5604 69 my $self = shift;
5605 69 ▶ my $raw = Params::Get::get_params('data', \@_) // {};
Condition50%1/2
Params::Get::get_params("data", \@_) // {}
l!l
690
MC/DC0%0/1
Params::Get::get_params("data", \@_) // {}
Params::Get::get_params("data", \@_)
Truth table50%1/2
A
A= Params::Get::get_params("data", \@_)
Aresult
11
00
5606 69 ▶ die 'Data must be an array of numeric values' unless ref($raw->{data}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw->{"data"} eq "ARRAY" 2 67 69
5607 67 Params::Validate::Strict::validate_strict({
5608 args => $raw,
5609 schema => { data => { type => 'arrayref', error_msg => 'Data must be an array of numeric values' } },
5610 unknown_parameter_handler => 'ignore',
5611 });
5612 67 my $data = $raw->{data};
5613 67 my $opts = {%$raw}; delete $opts->{data};
5614  
5615 # Pre-binned path: the caller has already computed the bins.
5616 67 ▶ if ($opts->{binned}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"binned"}) 26 41 67
5617 26 return $self->_render_histogram_binned($data, $opts);
5618 }
5619  
5620 41 ▶ my $bins_opt = exists($opts->{bins}) ? $opts->{bins} : 20;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'bins'} ? : 5 36 41
5621 41 ▶ if (defined $bins_opt) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bins_opt) 40 1 41
5622 40 ▶ die 'bins must be a positive integer'
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($bins_opt) and $bins_opt == int $bins_opt and $bins_opt >= 1 3 37 40
Condition83%5/6
&looks_like_number($bins_opt) and $bins_opt == int $bins_opt and $bins_opt >= 1
!ll&&!rl&&r
1237
&looks_like_number($bins_opt) and $bins_opt == int $bins_opt
!ll&&!rl&&r
1039
MC/DC66%2/3
&looks_like_number($bins_opt) and $bins_opt == int $bins_opt and $bins_opt >= 1
&looks_like_number($bins_opt) $bins_opt == int $bins_opt $bins_opt >= 1
Truth table75%3/4
A and B and C
A= &looks_like_number($bins_opt)B= $bins_opt == int $bins_optC= $bins_opt >= 1
ABCresult
0XX0
10X0
1100
1111
5623 unless looks_like_number($bins_opt) && $bins_opt == int($bins_opt) && $bins_opt >= 1;
5624 }
5625  
5626 38 my @values;
5627 38 for my $v (@$data) {
5628 307 ▶ die 'Each value must be numeric' unless looks_like_number($v // 'x');
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number(scalar($v // "x")) 1 306 307
Condition50%1/2
$v // "x"
l!l
3070
MC/DC0%0/1
$v // "x"
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
5629 306 push @values, $v + 0;
5630 }
5631  
5632 37 my $json_data = _script_json(\@values);
5633  
5634 37 my $js_esc = \&_js_string;
5635  
5636 37 ▶ my $x_label = $opts->{x_label} // '';
Condition100%2/2
$opts->{"x_label"} // ""
l!l
334
MC/DC100%1/1
$opts->{"x_label"} // ""
$opts->{"x_label"}
Truth table100%2/2
A
A= $opts->{"x_label"}
Aresult
11
00
5637 37 ▶ my $color = _css_colour($opts->{color}) // 'steelblue';
Condition100%2/2
_css_colour($opts->{"color"}) // "steelblue"
l!l
730
MC/DC100%1/1
_css_colour($opts->{"color"}) // "steelblue"
_css_colour($opts->{"color"})
Truth table100%2/2
A
A= _css_colour($opts->{"color"})
Aresult
11
00
5638  
5639 37 my $x_label_esc = $js_esc->($x_label);
5640 37 my $color_esc = $js_esc->($color);
5641  
5642 37 ▶ my $svg_id = _chart_id($opts->{id}) // 'histogram';
Condition100%2/2
_chart_id($opts->{"id"}) // "histogram"
l!l
532
MC/DC100%1/1
_chart_id($opts->{"id"}) // "histogram"
_chart_id($opts->{"id"})
Truth table100%2/2
A
A= _chart_id($opts->{"id"})
Aresult
11
00
5643 37 my $tip_id = $svg_id . '_tip';
5644 37 my $width = $self->{width};
5645 37 my $height = $self->{height};
5646 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
5647 37 ▶ ? qq{viewBox="0 0 $width $height" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 3 34 37
Condition66%2/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
2350
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table66%2/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
5648 : qq{width="$width" height="$height"};
5649  
5650 37 my $margin_top = 20;
5651 37 my $margin_right = 20;
5652 37 ▶ my $margin_bottom = $x_label ? 60 : 40;
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 3 34 37
5653 37 my $margin_left = 55;
5654 37 my $inner_w = $width - $margin_left - $margin_right;
5655 37 my $inner_h = $height - $margin_top - $margin_bottom;
5656  
5657 37 ▶ my $bins_js = defined($bins_opt)
Branch: 1 branch
BranchTrueFalseTotal
defined $bins_opt ? : 36 1 37
5658 ? "var numBins = $bins_opt;"
5659 : 'var numBins = Math.ceil(Math.log2(values.length) + 1);';
5660  
5661 37 ▶ my $x_label_block = $x_label ? <<"XLB" : '';
Branch: 1 branch
BranchTrueFalseTotal
$x_label ? : 3 34 37
5662 g.append("text")
5663 .attr("class","hg-axis-label")
5664 .attr("x", innerW / 2)
5665 .attr("y", innerH + (margin.bottom - 10))
5666 .attr("text-anchor","middle")
5667 .text("$x_label_esc");
5668 XLB
5669  
5670 37 my $html = <<"HTML";
5671 <style>
5672 #$tip_id {
5673 position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;
5674 border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;
5675 display:none;line-height:1.6;
5676 }
5677 .hg-axis-label{font-size:11px;fill:#555;}
5678 .hg-bar{cursor:default;}
5679 </style>
5680 <svg id="$svg_id" $svg_attrs></svg>
5681 <div id="$tip_id"></div>
5682 <script>
5683 (function(){
5684 var values = $json_data;
5685 var margin = {top:$margin_top,right:$margin_right,bottom:$margin_bottom,left:$margin_left};
5686 var innerW = $inner_w;
5687 var innerH = $inner_h;
5688 $bins_js
5689 var svg = d3.select("#$svg_id");
5690 var g = svg.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
5691 var tip = d3.select("#$tip_id");
5692  
5693 var xScale = d3.scaleLinear()
5694 .domain([d3.min(values), d3.max(values)]).nice()
5695 .range([0, innerW]);
5696  
5697 var binner = d3.bin().domain(xScale.domain()).thresholds(xScale.ticks(numBins));
5698 var bins = binner(values);
5699  
5700 var yScale = d3.scaleLinear()
5701 .domain([0, d3.max(bins, function(d){return d.length;})]).nice()
5702 .range([innerH, 0]);
5703  
5704 g.append("g").attr("class","hg-x-axis")
5705 .attr("transform","translate(0,"+innerH+")").call(d3.axisBottom(xScale));
5706 g.append("g").attr("class","hg-y-axis").call(d3.axisLeft(yScale).ticks(6));
5707  
5708 $x_label_block
5709 g.selectAll(".hg-bar").data(bins).join("rect")
5710 .attr("class","hg-bar")
5711 .attr("x",function(d){return xScale(d.x0)+1;})
5712 .attr("y",function(d){return yScale(d.length);})
5713 .attr("width",function(d){return Math.max(0, xScale(d.x1)-xScale(d.x0)-2);})
5714 .attr("height",function(d){return innerH - yScale(d.length);})
5715 .attr("fill","$color_esc")
5716 .on("mouseover",function(event,d){
5717 tip.style("display","block")
5718 .html("<b>"+d.x0.toFixed(2)+" – "+d.x1.toFixed(2)+"<\\/b><br\/>Count: "+d.length);
5719 })
5720 .on("mousemove",function(event){
5721 tip.style("left",(event.offsetX+12)+"px").style("top",(event.offsetY-28)+"px");
5722 })
5723 .on("mouseout",function(){tip.style("display","none");});
5724 })();
5725 </script>
5726 HTML
5727  
5728 37 return { svg_id => $svg_id, html => $html };
5729 }
5730  
5731 # The definition of one scheme, by name, or a die that names what was asked for.
5732 sub _categorical_scheme
5733 1043 ▶{
Subroutine _categorical_scheme: called CC=4 SCAR=13.9
5734 1043 my $scheme = shift;
5735  
5736 die 'Unknown scheme: ' . (defined($scheme) ? $scheme : '(none)')
5737 1043 ▶ unless defined($scheme) && exists($CATEGORICAL_SCHEMES{$scheme});
Branch: 2 branches
BranchTrueFalseTotal
unless defined $scheme and exists $CATEGORICAL_SCHEMES{$scheme} 5 1038 1043
defined $scheme ? : 4 1 5
Condition100%3/3
defined $scheme and exists $CATEGORICAL_SCHEMES{$scheme}
!ll&&!rl&&r
141038
MC/DC100%2/2
defined $scheme and exists $CATEGORICAL_SCHEMES{$scheme}
defined $scheme exists $CATEGORICAL_SCHEMES{$scheme}
Truth table100%3/3
A and B
A= defined $schemeB= exists $CATEGORICAL_SCHEMES{$scheme}
ABresult
0X0
100
111
5738  
5739 1038 return $CATEGORICAL_SCHEMES{$scheme};
5740 }
5741  
5742 # A scheme's colours as JavaScript source: a literal array, in the scheme's
5743 # order, built from the one definition. The snippets inline this rather than a
5744 # d3.scheme* expression, so the browser draws the numbers palette() handed a
5745 # map, and an upgrade of d3 cannot change a chart's colours.
5746 sub _scheme_colours_js
5747 988 ▶{
Subroutine _scheme_colours_js: called CC=1 SCAR=0.0
5748 988 my $scheme = shift;
5749  
5750 988 return '[' . join(', ', map { "'$_'" } @{_categorical_scheme($scheme)->{colours}}) . ']';
5751 }
5752  
5753 # The colours of a scheme as a JS array, or the default scheme's for a name that
5754 # is not one. The snippets used to capitalise the name they were handed and
5755 # look up the expression that spelling produced, which turned a name they did
5756 # not know into an undefined function in the browser; drawing with the
5757 # documented default is what the snippets that look their scheme up in a table
5758 # have always done.
5759 sub _scheme_js
5760 106 ▶{
Subroutine _scheme_js: called CC=2 SCAR=6.9
5761 106 my $scheme = shift;
5762  
5763 # exists() first: naming a scheme that is not one must not add it to the
5764 # vocabulary, which is what dereferencing the missing entry would do.
5765 106 ▶ return exists($CATEGORICAL_SCHEMES{$scheme})
Branch: 1 branch
BranchTrueFalseTotal
exists $CATEGORICAL_SCHEMES{$scheme} ? : 103 3 106
5766 ? _scheme_colours_js($scheme)
5767 : _default_scheme_js();
5768 }
5769  
5770 # The name to write into a snippet's SCHEMES['...'] lookup: the one asked for if
5771 # it is a scheme, otherwise the default. The name is written into a script, and
5772 # it often comes from a request or a saved chart, so only the names in the
5773 # definition above ever reach the page. An unknown name was always going to draw
5774 # the default colours; this makes sure it can do nothing else.
5775 sub _scheme_name
5776 141 ▶{
Subroutine _scheme_name: called CC=3 SCAR=11.0
5777 141 my $scheme = shift;
5778  
5779 141 ▶ return defined($scheme) && exists($CATEGORICAL_SCHEMES{$scheme})
Branch: 1 branch
BranchTrueFalseTotal
defined $scheme && exists $CATEGORICAL_SCHEMES{$scheme} ? : 18 123 141
Condition100%3/3
defined $scheme and exists $CATEGORICAL_SCHEMES{$scheme}
!ll&&!rl&&r
1081518
MC/DC100%2/2
defined $scheme and exists $CATEGORICAL_SCHEMES{$scheme}
defined $scheme exists $CATEGORICAL_SCHEMES{$scheme}
Truth table100%3/3
A and B
A= defined $schemeB= exists $CATEGORICAL_SCHEMES{$scheme}
ABresult
0X0
100
111
5780 ? $scheme
5781 : $DEFAULT_CATEGORICAL_SCHEME;
5782 }
5783  
5784 # A chart's id, or undef for one that is not usable, so that the caller's default
5785 # applies. An id is written into an attribute, a stylesheet selector and a script
5786 # all at once; one of these characters is safe in all three and can be selected
5787 # with "#id".
5788 sub _chart_id
5789 584 ▶{
Subroutine _chart_id: called CC=3 SCAR=11.0
5790 584 my $id = shift;
5791  
5792 584 ▶ return unless defined($id);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 454 130 584
5793 130 ▶ return $id =~ m{\A[A-Za-z_][A-Za-z0-9_-]*\z} ? $id : undef;
Branch: 1 branch
BranchTrueFalseTotal
$id =~ /\A[A-Za-z_][A-Za-z0-9_-]*\z/ ? : 70 60 130
5794 }
5795  
5796 # Nothing written into a <script> may end it. The HTML parser looks for "</script"
5797 # and "<!--" before any JavaScript is read, so quoting cannot help: "<" has to be
5798 # written as an escape, which JavaScript reads back as the same character. The two
5799 # line separators are newlines to older JavaScript.
5800 sub _script_safe
5801 2101 ▶{
Subroutine _script_safe: called CC=1 SCAR=0.0
5802 2101 my $text = shift;
5803  
5804 2101 $text =~ s/</\\u003c/g;
5805 2101 $text =~ s/\x{2028}/\\u2028/g;
5806 2101 $text =~ s/\x{2029}/\\u2029/g;
5807 2101 return $text;
5808 }
5809  
5810 # Data as JSON that is safe to write into a <script>.
5811 sub _script_json
5812 744 ▶{
Subroutine _script_json: called CC=1 SCAR=0.0
5813 744 return _script_safe($_JSON->encode($_[0]));
5814 }
5815  
5816 # Text as the inside of a double-quoted JavaScript string in a <script>.
5817 sub _js_string
5818 1357 ▶{
Subroutine _js_string: called CC=1 SCAR=0.0
5819 1357 my $s = shift;
5820  
5821 1357 $s =~ s/\\/\\\\/g;
5822 1357 $s =~ s/"/\\"/g;
5823 1357 $s =~ s/\n/\\n/g;
5824 1357 $s =~ s/\r/\\r/g;
5825 1357 return _script_safe($s);
5826 }
5827  
5828 # Text as the inside of a JavaScript string of any kind, for a value written into a
5829 # single-quoted string or a template literal, where "$" and the other quotes count.
5830 sub _js_any_string
5831 85 ▶{
Subroutine _js_any_string: called CC=1 SCAR=0.0
5832 85 my $s = _js_string(shift);
5833  
5834 85 $s =~ s/(['`\$])/\\$1/g;
5835 85 return $s;
5836 }
5837  
5838 # A colour fit to write into a page, or undef for one that is not, so that the
5839 # caller's default applies. The characters are those of a CSS colour - a name, a
5840 # hex value, or rgb(), hsl() and the like - and none of them can end a JavaScript
5841 # string, an attribute or a script element.
5842 sub _css_colour
5843 334 ▶{
Subroutine _css_colour: called CC=3 SCAR=11.0
5844 334 my $colour = shift;
5845  
5846 334 ▶ return unless defined($colour);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $colour 268 66 334
5847 66 ▶ return $colour =~ m{\A[#0-9A-Za-z_ (),.%/-]+\z} ? $colour : undef;
Branch: 1 branch
BranchTrueFalseTotal
$colour =~ m[\A[#0-9A-Za-z_ (),.%/-]+\z] ? : 40 26 66
5848 }
5849  
5850 # The chart's title as text for the page. The object keeps what it was given.
5851 sub _title_html
5852 133 ▶{
Subroutine _title_html: called CC=1 SCAR=0.0
5853 133 my $self = shift;
5854  
5855 133 my $title = $self->{title};
5856 133 $title =~ s/&/&amp;/g;
5857 133 $title =~ s/</&lt;/g;
5858 133 $title =~ s/>/&gt;/g;
5859 133 $title =~ s/"/&quot;/g;
5860 133 $title =~ s/'/&#39;/g;
5861 133 return $title;
5862 }
5863  
5864 sub _default_scheme_js
5865 149 ▶{
Subroutine _default_scheme_js: called CC=1 SCAR=0.0
5866 149 return _scheme_colours_js($DEFAULT_CATEGORICAL_SCHEME);
5867 }
5868  
5869 # The table the snippets look a scheme up in, built from the definition above, so
5870 # that a scheme added there is understood by every snippet that offers a scheme
5871 # rather than by the ones somebody remembered to edit. Each value is the
5872 # scheme's colours as a literal array: the same numbers palette() returns.
5873 sub _schemes_js
5874 141 ▶{
Subroutine _schemes_js: called CC=1 SCAR=0.0
5875 141 my ($self, $declaration) = @_;
5876  
5877 return $declaration . ' SCHEMES = { '
5878 141 . join(', ', map { "$_: " . _scheme_colours_js($_) } sort keys %CATEGORICAL_SCHEMES)
5879 . ' };';
5880 }
5881  
5882 sub _preamble
5883 67 ▶{
Subroutine _preamble: called CC=1 SCAR=0.0
5884 67 my $html = <<'HTML';
5885 <!DOCTYPE html>
5886 <html lang="en">
5887 HTML
5888 67 return $html;
5889 }
5890  
5891 sub _head
5892 47 ▶{
Subroutine _head: called CC=1 SCAR=0.0
5893 47 my $self = shift;
5894  
5895 47 my $html = <<"HTML";
5896 <head>
5897 <meta charset="UTF-8">
5898 <meta name="viewport" content="width=device-width, initial-scale=1.0">
5899 47 <title>@{[ $self->_title_html() ]}</title>
5900 <script src="https://d3js.org/d3.v7.min.js"></script>
5901 </head>
5902 HTML
5903 47 return $html;
5904 }
5905  
5906 sub _svg_attrs
5907 66 ▶{
Subroutine _svg_attrs: called CC=3 SCAR=11.1
5908 66 my ($self, $override) = @_;
5909 66 ▶ my $responsive = defined($override) ? $override : $self->{responsive};
Branch: 1 branch
BranchTrueFalseTotal
defined $override ? : 0 66 66
5910 66 ▶ return $responsive
Branch: 1 branch
BranchTrueFalseTotal
$responsive ? : 2 64 66
5911 ? qq{viewBox="0 0 $self->{width} $self->{height}" width="100%"}
5912 : qq{width="$self->{width}" height="$self->{height}" style="border: 1px solid black;"};
5913 }
5914  
5915 # _render_snippet_shell($opts, $container_id, $script)
5916 # Used exclusively by new snippet methods (scatter, table).
5917 # Returns a minimal HTML fragment with a container div and the provided script block.
5918 sub _render_snippet_shell
5919 0 ▶{
Subroutine _render_snippet_shell: not called CC=3 SCAR=24.8
5920 0 my ($self, $opts, $container_id, $script) = @_;
5921 0 my $w = $self->{width};
5922 0 my $h = $self->{height};
5923 my $svg_attrs = ($opts->{responsive} // $self->{responsive})
5924 0 ▶ ? qq{viewBox="0 0 $w $h" width="100%"}
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'responsive'} // $self->{'responsive'} ? : 0 0 0
Condition0%0/3
$opts->{"responsive"} // $self->{"responsive"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts->{"responsive"} // $self->{"responsive"}
$opts->{"responsive"} $self->{"responsive"}
Truth table0%0/3
A // B
A= $opts->{"responsive"}B= $self->{"responsive"}
ABresult
1X1
011
000
5925 : qq{width="$w" height="$h"};
5926 0 return <<"SHELL";
5927 <div id="${container_id}_wrap" style="position:relative;">
5928 <svg id="$container_id" $svg_attrs></svg>
5929 <div id="${container_id}_tip" style="position:absolute;background:rgba(255,255,255,0.95);border:1px solid #ccc;border-radius:4px;padding:6px 10px;font-size:12px;pointer-events:none;display:none;line-height:1.6;"></div>
5930 </div>
5931 $script
5932 SHELL
5933 }
5934  
5935 =head1 SUPPORT
5936  
5937 This module is provided as-is without any warranty.
5938  
5939 Please report any bugs or feature requests to C<bug-html-d3 at rt.cpan.org>,
5940 or through the web interface at
5941 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=HTML-D3>.
5942 I will be notified, and then you'll
5943 automatically be notified of progress on your bug as I make changes.
5944  
5945 You can find documentation for this module with the perldoc command.
5946  
5947 perldoc HTML::D3
5948  
5949 You can also look for information at:
5950  
5951 =head1 BUGS
5952  
5953 It would help to have the render routine to return the head and body components separately.
5954  
5955 =head1 SEE ALSO
5956  
5957 =over 4
5958  
5959 =item * L<Configure an Object at Runtime|Object::Configure>
5960  
5961 =item * L<Test Dashboard|https://nigelhorne.github.io/HTML-D3/coverage/>
5962  
5963 =back
5964  
5965 =head1 AUTHOR
5966  
5967 Nigel Horne <njh@nigelhorne.com>
5968  
5969 =encoding UTF-8
5970  
5971 =head1 FORMAL SPECIFICATION
5972  
5973 =head2 render_bar_chart
5974  
5975 render_bar_chart : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
5976  
5977 pre data = undef ⇒ die "Data is not optional"
5978 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
5979 post result ∈ Str
5980 post "<!DOCTYPE" ⊆ result
5981 post ∀ d ∈ data . d[0] ⊆ result
5982  
5983 =head2 render_line_chart
5984  
5985 render_line_chart : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
5986  
5987 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
5988 post result ∈ Str
5989 post "<!DOCTYPE" ⊆ result
5990 post "d3.scalePoint" ⊆ result ∧ "d3.line()" ⊆ result
5991  
5992 =head2 render_animated_bar_chart
5993  
5994 render_animated_bar_chart : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
5995  
5996 pre data = undef ⇒ die "Data is not optional"
5997 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
5998 post result ∈ Str
5999 post "<!DOCTYPE" ⊆ result
6000 post ".transition()" ⊆ result ∧ ".delay(" ⊆ result
6001  
6002 =head2 render_animated_line_chart
6003  
6004 render_animated_line_chart : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6005  
6006 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6007 post result ∈ Str
6008 post "<!DOCTYPE" ⊆ result
6009 post "stroke-dashoffset" ⊆ result ∧ "d3.easeLinear" ⊆ result
6010  
6011 =head2 render_pie_chart
6012  
6013 render_pie_chart : HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → Str ∪ ⊥
6014  
6015 pre data = undef ⇒ die "Data is not optional"
6016 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6017 post result ∈ Str
6018 post "<!DOCTYPE" ⊆ result
6019 post "d3.pie()" ⊆ result ∧ "d3.arc()" ⊆ result ∧ "'#1f77b4'" ⊆ result
6020 -- category10's colours, inlined: no d3.scheme* is read
6021 post opts.separator = S ⇒ " S " ⊆ result (SVG legend: label S value)
6022  
6023 =head2 render_animated_pie_chart
6024  
6025 render_animated_pie_chart : HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → Str ∪ ⊥
6026  
6027 pre data = undef ⇒ die "Data is not optional"
6028 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6029 post result ∈ Str
6030 post "<!DOCTYPE" ⊆ result
6031 post "attrTween" ⊆ result ∧ "d3.interpolate" ⊆ result
6032 post opts.separator = S ⇒ " S " ⊆ result (SVG legend: label S value)
6033  
6034 =head2 render_line_chart_snippet
6035  
6036 render_line_chart_snippet :
6037 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6038  
6039 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6040 post result ∈ HashRef
6041 post result.svg_id = opts.id // "chart"
6042 post result.html ∈ Str
6043 post "<!DOCTYPE" ∉ result.html
6044  
6045 =head2 render_zoomable_line_chart_snippet
6046  
6047 render_zoomable_line_chart_snippet :
6048 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6049  
6050 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6051 post result ∈ HashRef
6052 post result.svg_id = opts.id // "chart"
6053 post result.html ∈ Str
6054 post "<!DOCTYPE" ∉ result.html
6055 post "d3.brushX()" ⊆ result.html
6056 post opts.animated = 1 ⇒ "stroke-dashoffset" ⊆ result.html
6057 ∧ "initialDrawDone" ⊆ result.html
6058  
6059 =head2 render_pie_chart_snippet
6060  
6061 render_pie_chart_snippet :
6062 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6063  
6064 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6065 pre ∀ d ∈ data . d[1] < 0 ⇒ d[1] := |d[1]| -- negative → absolute
6066 pre ∀ d ∈ data . d[1] = 0 ⇒ d ∉ result -- zero → omitted
6067 post result ∈ HashRef
6068 post result.svg_id = "pie_chart"
6069 post result.html ∈ Str
6070 post "<!DOCTYPE" ∉ result.html
6071 post "d3.pie()" ⊆ result.html ∧ "schemeTableau10" ⊆ result.html
6072 post opts.color_scheme = S ∧ S ∈ categorical_schemes()
6073 ⇒ the D3 expression of S ⊆ result.html
6074 post opts.color_scheme ∉ categorical_schemes()
6075 ⇒ "schemeTableau10" ⊆ result.html -- the default scheme
6076 post opts.animated = 1 ⇒ "attrTween" ⊆ result.html
6077 ∧ "initialDrawDone" ⊆ result.html
6078 post opts.donut = 1 ⇒ "innerRadius" ⊆ result.html
6079 post opts.max_slices = N ∧ N ≥ 2 ∧ |data| > N
6080 ⇒ |result_slices| = N ∧ "Other" ∈ result_labels
6081 post opts.separator = S ⇒ " S " ⊆ result.html (HTML legend: label S value (pct%))
6082  
6083 =head2 render_heatmap_snippet
6084  
6085 render_heatmap_snippet :
6086 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6087  
6088 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6089 pre ∃ pt ∈ data . ref(pt) ≠ 'ARRAY'
6090 ⇒ die "Each data point must be an array reference"
6091 pre ∃ pt ∈ data . |pt| < 3 ⇒ die "Each data point must have at least 3 elements"
6092 pre ∃ pt ∈ data . defined(pt[2]) ∧ ¬numeric(pt[2])
6093 ⇒ die "Value must be numeric"
6094 pre opts.color_scheme = S ∧ S ∉ {YlOrRd,Blues,Greens,Purples,RdPu,YlGnBu}
6095 ⇒ die "Unknown color_scheme: S"
6096 pre opts.cell_padding = N ∧ (N < 0 ∨ N > 8)
6097 ⇒ die "cell_padding must be between 0 and 8"
6098 pre ∀ pt ∈ data . pt[2] = undef ⇒ pt ∉ result -- undef rows skipped
6099 pre ∃ pt₁,pt₂ ∈ data . pt₁[0]=pt₂[0] ∧ pt₁[1]=pt₂[1]
6100 ⇒ last-write wins
6101 post result ∈ HashRef
6102 post result.svg_id = "heatmap"
6103 post result.html ∈ Str
6104 post "<!DOCTYPE" ∉ result.html
6105 post "scaleSequential" ⊆ result.html
6106 post opts.animated = 1 ⇒ "prefers-reduced-motion" ⊆ result.html
6107 post opts.legend = 1 ⇒ "linearGradient" ⊆ result.html
6108  
6109 =head2 render_bar_chart_snippet
6110  
6111 render_bar_chart_snippet :
6112 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6113  
6114 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6115 pre ∃ pt ∈ data . ref(pt) ≠ 'ARRAY'
6116 ⇒ die "Each data point must be an array reference"
6117 pre ∃ pt ∈ data . |pt| < 2 ⇒ die "Each data point must have at least 2 elements"
6118 pre ∃ pt ∈ data . defined(pt[1]) ∧ ¬numeric(pt[1])
6119 ⇒ die "Value must be numeric"
6120 pre opts.orientation ∉ {'vertical','horizontal'}
6121 ⇒ die "orientation must be 'vertical' or 'horizontal'"
6122 pre opts.sort_bars ∉ {'value','label','none'}
6123 ⇒ die "sort_bars must be 'value', 'label', or 'none'"
6124 pre ∀ pt ∈ data . pt[1] < 0 ⇒ pt[1] := |pt[1]| -- negative → absolute
6125 pre ∀ pt ∈ data . pt[1] = undef ⇒ pt ∉ result -- undef rows skipped
6126 post result ∈ HashRef
6127 post result.svg_id = opts.id // "bar_chart"
6128 post result.html ∈ Str
6129 post "<!DOCTYPE" ∉ result.html
6130 post "d3.scaleBand" ⊆ result.html ∧ "d3.scaleLinear" ⊆ result.html
6131 post opts.animated = 1 ⇒ "prefers-reduced-motion" ⊆ result.html
6132 post opts.color = 'categorical' ⇒ the default scheme's expression
6133 ("schemeTableau10") ⊆ result.html
6134 post opts.max_bars = N ∧ N ≥ 2 ∧ |data| > N
6135 ⇒ |result_bars| = N ∧ "Other" ∈ result_labels
6136  
6137 =head2 render_multi_series_line_chart_snippet
6138  
6139 render_multi_series_line_chart_snippet :
6140 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6141  
6142 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of series"
6143 pre ∃ s ∈ data . ref(s) ≠ 'HASH'
6144 ⇒ die "Each series must be a hashref with name and data"
6145 pre ∃ s ∈ data . ¬defined(s.name) ∨ ref(s.data) ≠ 'ARRAY'
6146 ⇒ die "Each series must be a hashref with name and data"
6147 post result ∈ HashRef
6148 post result.svg_id = opts.id // "chart"
6149 post result.html ∈ Str
6150 post "<!DOCTYPE" ∉ result.html
6151 post "d3.scalePoint" ⊆ result.html ∧ "d3.scaleLinear" ⊆ result.html
6152 post "d3.line()" ⊆ result.html
6153 post #{path ∈ result.html : class = "msl-line"} = |data| -- one path per series
6154 post opts.x_label ≠ '' ⇒ "msl-axis-label" ⊆ result.html
6155 post opts.y_label ≠ '' ⇒ "msl-axis-label" ⊆ result.html
6156 post opts.scheme = S ∧ S ∈ categorical_schemes()
6157 ⇒ the colours of S, as a JS array, ⊆ result.html
6158 post opts.scheme ∉ categorical_schemes()
6159 ⇒ the default scheme's colours ⊆ result.html
6160 -- not a d3.scheme<S> expression
6161 post opts.animated = 1 ⇒ "stroke-dashoffset" ⊆ result.html
6162 ∧ "prefers-reduced-motion" ⊆ result.html
6163  
6164 =head2 render_scatter_chart_snippet
6165  
6166 render_scatter_chart_snippet :
6167 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6168  
6169 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6170 pre ∃ pt ∈ data . ref(pt) ≠ 'ARRAY'
6171 ⇒ die "Each data point must be an array reference"
6172 pre ∃ pt ∈ data . |pt| < 2 ⇒ die "Each data point must have at least 2 elements"
6173 pre ∃ pt ∈ data . ¬numeric(pt[0])
6174 ⇒ die "X value must be numeric"
6175 pre ∃ pt ∈ data . ¬numeric(pt[1])
6176 ⇒ die "Y value must be numeric"
6177 post result ∈ HashRef
6178 post result.svg_id = opts.id // "scatter_chart"
6179 post result.html ∈ Str
6180 post "<!DOCTYPE" ∉ result.html
6181 post "d3.scaleLinear" ⊆ result.html
6182 post opts.animated = 1 ⇒ "prefers-reduced-motion" ⊆ result.html
6183 post opts.colour_by_series = 1 ∧ ∃ pt ∈ data . defined(pt[3].series)
6184 ⇒ "scaleOrdinal" ⊆ result.html
6185 ∧ "seriesNames" ⊆ result.html
6186 ∧ legend drawn (margin right = 140)
6187 post opts.colour_by_series = 1 ∧ opts.scheme = S ∧ S ∈ categorical_schemes()
6188 ⇒ the D3 expression of S ⊆ result.html
6189 post opts.colour_by_series = 1 ∧ opts.scheme ∉ categorical_schemes()
6190 ⇒ the default scheme's expression ⊆ result.html
6191 post ∃ pt ∈ data . defined(pt[3].size)
6192 ⇒ "d3.scaleSqrt" ⊆ result.html ∧ "rScale" ⊆ result.html
6193 post opts.radius_range = [A,B]
6194 ⇒ "range([A,B])" ⊆ result.html
6195 post ∀ pt ∈ data . pt[3].size = undef
6196 ⇒ "rScale" ∉ result.html -- fixed radius
6197  
6198 =head2 render_table_snippet
6199  
6200 render_table_snippet :
6201 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6202  
6203 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6204 pre |data| = 0 ⇒ die "Data must have at least one row (header row)"
6205 pre ∃ row ∈ data . ref(row) ≠ 'ARRAY'
6206 ⇒ die "Each row must be an array reference"
6207 post result ∈ HashRef
6208 post result.table_id = opts.id // "data_table"
6209 post result.html ∈ Str
6210 post "<!DOCTYPE" ∉ result.html
6211 post opts.sortable ≠ 0 ⇒ "dt-sortable" ⊆ result.html
6212  
6213 =head2 render_stacked_bar_snippet
6214  
6215 render_stacked_bar_snippet :
6216 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6217  
6218 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6219 pre ∃ row ∈ data . ref(row) ≠ 'HASH'
6220 ⇒ die "Each data point must be a hash reference"
6221 pre ∃ row ∈ data . ¬numeric(row[val_col])
6222 ⇒ die "Value must be numeric"
6223 pre opts.orient ∉ {'v','h'} ⇒ die "orient must be 'v' or 'h'"
6224 pre defined(opts.sort) ∧ opts.sort ∉ {'value','label'}
6225 ⇒ die "sort must be 'value' or 'label'"
6226 post result ∈ HashRef
6227 post result.svg_id = opts.id // "stacked_bar"
6228 post result.html ∈ Str
6229 post "<!DOCTYPE" ∉ result.html
6230 post "d3.stack()" ⊆ result.html
6231 post "SCHEMES" ⊆ result.html
6232 post opts.scheme = S ∧ S ∈ categorical_schemes()
6233 ⇒ the D3 expression of S ⊆ result.html
6234 post opts.scheme ∉ categorical_schemes()
6235 ⇒ the default scheme's expression ⊆ result.html
6236  
6237 =head2 render_combo_snippet
6238  
6239 render_combo_snippet :
6240 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6241  
6242 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6243 pre ∃ row ∈ data . ref(row) ≠ 'HASH'
6244 ⇒ die "Each data point must be a hash reference"
6245 pre ∃ row ∈ data . ¬numeric(row[bar_col])
6246 ⇒ die "Bar value must be numeric"
6247 pre ∃ row ∈ data . ¬numeric(row[line_col])
6248 ⇒ die "Line value must be numeric"
6249 post result ∈ HashRef
6250 post result.svg_id = opts.id // "combo_chart"
6251 post result.html ∈ Str
6252 post "<!DOCTYPE" ∉ result.html
6253 post "d3.scaleBand" ⊆ result.html ∧ "d3.scaleLinear" ⊆ result.html
6254 post "axisRight" ⊆ result.html
6255 post "</b>" ∉ result.html ∧ "<\/b>" ∈ result.html
6256  
6257 =head2 render_treemap_snippet
6258  
6259 render_treemap_snippet :
6260 HTML::D3 × (ArrayRef | HashRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6261  
6262 pre ref(data) ∉ {'ARRAY','HASH'}
6263 ⇒ die "Data must be an array of hashes or a hash tree"
6264 pre ref(data) = 'ARRAY' ∧ ∃ row ∈ data . ref(row) ≠ 'HASH'
6265 ⇒ die "Each flat row must be a hash reference"
6266 pre ref(data) = 'ARRAY' ∧ ∃ row ∈ data . ¬exists(row.path)
6267 ⇒ die "Each flat row must have a 'path' key"
6268 pre ref(data) = 'ARRAY' ∧ ∃ row ∈ data . ¬numeric(row.value)
6269 ⇒ die "Each flat row must have a numeric 'value' key"
6270 post result ∈ HashRef
6271 post result.svg_id = opts.id // "treemap"
6272 post result.html ∈ Str
6273 post "<!DOCTYPE" ∉ result.html
6274 post "d3.treemap()" ⊆ result.html
6275 post ref(data) = 'ARRAY' ⇒ "d3.stratify()" ⊆ result.html
6276 post ref(data) = 'HASH' ⇒ "d3.hierarchy(" ⊆ result.html
6277 post opts.scheme = S ∧ S ∈ categorical_schemes()
6278 ⇒ the D3 expression of S ⊆ result.html
6279 post opts.scheme ∉ categorical_schemes()
6280 ⇒ the default scheme's expression ⊆ result.html
6281  
6282 =head2 render_histogram_snippet
6283  
6284 render_histogram_snippet :
6285 HTML::D3 × (ArrayRef | undef) × (HashRef | undef) → HashRef ∪ ⊥
6286  
6287 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of numeric values"
6288 pre ∃ v ∈ data . ¬numeric(v) ⇒ die "Each value must be numeric"
6289 pre defined(opts.bins) ∧ (¬integer(opts.bins) ∨ opts.bins < 1)
6290 ⇒ die "bins must be a positive integer"
6291 pre opts.binned = 1 ∧ |data| = 0
6292 ⇒ die "Data must contain at least one bin"
6293 pre opts.binned = 1 ∧ ∃ b ∈ data . ref(b) ≠ 'HASH'
6294 ⇒ die "Each pre-binned entry must be a hash reference"
6295 pre opts.binned = 1 ∧ ∃ b ∈ data . ¬numeric(b.count)
6296 ⇒ die "Bin count must be numeric"
6297 pre opts.binned = 1 ∧ ∃ b ∈ data . b.count < 0
6298 ⇒ die "Bin count must not be negative"
6299 pre opts.binned = 1 ∧ ∃ b ∈ data . ¬defined(b.label) ∧ ¬(numeric(b.lo) ∧ numeric(b.hi))
6300 ⇒ die "Each pre-binned entry must have a label or numeric lo and hi"
6301 pre opts.binned = 1 ∧ ¬defined(b.label) ∧ numeric(b.lo) ∧ numeric(b.hi)
6302 ⇒ b.label := "[lo,hi)"
6303 post result ∈ HashRef
6304 post result.svg_id = opts.id // "histogram"
6305 post result.html ∈ Str
6306 post "<!DOCTYPE" ∉ result.html
6307 post opts.binned ≠ 1 ⇒ "d3.bin()" ⊆ result.html
6308 post opts.binned = 1 ⇒ "d3.bin()" ∉ result.html ∧ "scaleBand" ⊆ result.html
6309 post opts.color defined ⇒ c(clone) -- explicit colour is the bar fill
6310 post opts.color = undef ∧ opts.scheme = S ∧ S ∈ categorical_schemes()
6311 ⇒ the D3 expression of S subscripted "[0]"
6312 ⊆ result.html -- colour_at(S, 0)
6313 post opts.color = undef ∧ opts.scheme ∉ categorical_schemes()
6314 ⇒ the default scheme's first colour ⊆ result.html
6315 post opts.bins = undef ⇒ "Math.log2" ⊆ result.html
6316 post opts.x_label ≠ '' ⇒ "hg-axis-label" ⊆ result.html
6317  
6318 =head2 render_line_chart_with_tooltips
6319  
6320 render_line_chart_with_tooltips : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6321  
6322 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of arrays"
6323 post result ∈ Str
6324 post "<!DOCTYPE" ⊆ result
6325 post "mouseover" ⊆ result
6326 post "</b>" ∉ result ∧ "<\/b>" ∈ result
6327  
6328 =head2 render_multi_series_line_chart_with_tooltips
6329  
6330 render_multi_series_line_chart_with_tooltips : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6331  
6332 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6333 post result ∈ Str
6334 post "<!DOCTYPE" ⊆ result
6335 post "</b>" ∉ result ∧ "<\/b>" ∈ result
6336  
6337 =head2 render_multi_series_line_chart_with_animated_tooltips
6338  
6339 render_multi_series_line_chart_with_animated_tooltips : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6340  
6341 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6342 post result ∈ Str
6343 post "<!DOCTYPE" ⊆ result
6344 post "translateY" ⊆ result
6345 post "</b>" ∉ result ∧ "<\/b>" ∈ result
6346  
6347 =head2 render_multi_series_line_chart_with_legends
6348  
6349 render_multi_series_line_chart_with_legends : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6350  
6351 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6352 post result ∈ Str
6353 post "<!DOCTYPE" ⊆ result
6354 post ".legend" ⊆ result
6355  
6356 =head2 render_multi_series_line_chart_with_interactive_legends
6357  
6358 render_multi_series_line_chart_with_interactive_legends : HTML::D3 × (ArrayRef | undef) → Str ∪ ⊥
6359  
6360 pre ref(data) ≠ 'ARRAY' ⇒ die "Data must be an array of hashes"
6361 post result ∈ Str
6362 post "<!DOCTYPE" ⊆ result
6363 post "isVisible" ⊆ result
6364 post "isVisible ? 0 : 1" ⊆ result
6365 post ".legend" ⊆ result
6366  
6367 =head1 LICENSE AND COPYRIGHT
6368  
6369 Copyright 2025-2026 Nigel Horne.
6370  
6371 Usage is subject to the GPL2 licence terms.
6372 If you use it,
6373 please let me know.
6374  
6375 =cut
6376  
6377 31 1;
↑ Summary