blib/lib/HTML/D3.pm

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