view release on metacpan or search on metacpan
lib/Database/BI/Controller/Dashboard.pm view on Meta::CPAN
for my $pname (sort keys %param_defs) {
my $def = ref $param_defs{$pname} eq 'HASH' ? $param_defs{$pname} : {};
my $type = $def->{type} // 'string';
my $default = $def->{default} // '';
my $raw = $lookup->("p.$pname");
my $val = defined $raw ? $raw : $default;
if ($type eq 'number') {
require Scalar::Util;
# looks_like_number accepts these, and every comparison with NaN is
# false, so it would walk straight past min and max below.
unless (Scalar::Util::looks_like_number($val) && $val !~ /\A\s*[-+]?(?:nan|inf)/i) {
push @errors, sprintf(_message_text('error_param_type'), $pname);
next;
}
$val = $val + 0;
my ($lo, $hi) = ($def->{min}, $def->{max});
if (defined $lo && $val < $lo) {
push @errors, sprintf(_message_text('error_param_range'),
$pname, $lo, defined $hi ? $hi : '+inf');
lib/Database/BI/Model/Boundary.pm view on Meta::CPAN
=head3 API SPECIFICATION
=head4 INPUT
lat : number -90 .. 90
lon : number -180 .. 180
Domains: each is a plain decimal, an optional minus and ASCII digits with an
optional fraction (1, -1.5, 12.345678). A plus sign, a bare point (.5, 5.),
an exponent, spaces, a newline, a comma, NaN, Inf and non-ASCII digits are
not numbers here. The edges -90, 90, -180 and 180 are in; anything past
them, however slightly (90.0001), is out, even if it would round to an edge.
=head4 OUTPUT
The point rounded to three decimal places, as C<"lat,lon">: what the cache is
keyed by and all of the point that is sent. Undef for a point out of range.
=cut
# Rounding is to three places.
is $key->(0.0004, 0.0004), '0.000,0.000', '0.0004 rounds down';
is $key->(0.0006, 0.0006), '0.001,0.001', '0.0006 rounds up';
};
subtest 'DOMAIN 15 point_key format: plain decimals against everything else' => sub {
my $key = sub { Database::BI::Model::Boundary->point_key(@_) };
for my $good ('1', '1.5', '-1.5', '0', '-0', '0.0', '12.345678', '007') {
ok defined $key->($good, $good), 'a plain decimal: ' . $good;
}
for my $bad ('+1', '.5', '5.', '1e2', '1E2', ' 1', '1 ', "1\n", '1,5', '0x1', 'NaN', 'Inf', '', '--1', '1-', "\x{661}", "1\x{FF11}", "\x{1F600}", "1\x{202E}", "\x{0301}1", "\x{FC}") {
is $key->($bad, 0), undef, 'not a plain decimal: ' . $shown->($bad);
}
is $key->(undef, 0), undef, 'undef latitude';
is $key->(0, undef), undef, 'undef longitude';
};
# -- DOMAIN 16 ------------------------------------------------------
# Boundary settings: ranks 8, 10 or 12; country codes of two letters;
# online_max a whole number from 0.
subtest 'DOMAIN 16 ranks, codes and online_max' => sub {
t/edge_cases.t view on Meta::CPAN
is $verdict, 0, 'no against ' . (ref $stored || (defined $stored ? length($stored) . ' bytes' : 'undef'));
is Database::BI::Password::is_password_hash($stored), 0, '... which is not a hash';
}
my @list = Database::BI::Password::verify_password('secret', $good);
is scalar(@list), 1, 'in list context it still gives one value';
};
subtest 'Util: numbers and timestamps that are not what they look like' => sub {
require Database::BI::Util;
my $num = \&Database::BI::Util::parse_number;
for my $bad (undef, '', ' ', '--1', '1-', '1.2.3', '.', '-', '1e', 'e5', 'NaN', 'nan', 'Inf', '-inf', '1e999', '-1e999',
'9' x 400, "1\0", "\0", $INVALID_UTF8, '1' . (',' x 1000) . 'a', '(' x 5000, '$' x 5000, ('1 ' x 100_000) . 'x') {
my $v = within_budget('parse_number', sub { $num->($bad) });
is $v, undef, 'not a number: ' . (defined $bad ? (length($bad) > 20 ? length($bad) . ' bytes' : "'" . ($bad =~ s/[^\x20-\x7e]/?/gr) . "'") : 'undef');
}
is $num->($circular), undef, 'a reference is not a number' or 1;
is $num->('1' x 300), '1' x 300 + 0, 'the longest plain integer is read';
is $num->('0'), 0, 'zero is a number, not an absent value';
is $num->('-0'), 0, 'minus zero is zero';
is $num->(' 1 234,5 '), undef, 'a thousands space with a decimal comma is not guessed at' if 0;
my @list = $num->('x');
t/function.t view on Meta::CPAN
is $number->($_), $reads{$_}, "'$_' is read" for sort grep { !/[^\x00-\x7F]/ } keys %reads;
is $number->("\xC2\xA35"), 5, 'a pound sign as UTF-8 bytes';
is $number->("\x{20AC}7"), 7, 'a decoded euro sign';
};
# Why: this is the test of what a chart will total. A code column read as numbers
# is a meaningless measure, and an unknown code must not pass for a currency.
subtest 'Util::parse_number -- text that merely holds digits' => sub {
is $number->($_), undef, "'$_' is not a number" for
'', 'abc', 'SKU123', 'SKU 100', '100 SKU', 'A1', 'AB-100', 'R2D2', 'v1.2', '12/25/2025', '2026-05-20',
'10:30', '1.2.3', '--5', '-', '.', '()', 'USD', 'USD USD', 'Widget 2', '1e', 'e5', '0x10', 'Inf', 'NaN';
is $number->(undef), undef, 'nor is nothing';
is $number->('1e999'), undef, 'nor is what would be infinity';
is $number->('-1e999'), undef, 'in either direction';
is $number->('9' x 400), undef, 'however it is spelled';
# The limit is a double's, which is the browser's, on every perl. A perl
# built with -Duselongdouble or -Dusequadmath holds these as finite
# numbers, and passed them through until GitHub issue 6.
ok defined $number->('1.79e308'), 'the largest a double holds is a number';
is $number->('1.8e308'), undef, 'one past it is not, whatever this perl holds';
is $number->('-1.8e308'), undef, '... nor below';
t/function.t view on Meta::CPAN
is_deeply [ $F{_pagination}->(dash_controller($app, '/?page=3&per_page=10')) ], [ 3, 10, 20 ], 'as asked';
is_deeply [ $F{_pagination}->(dash_controller($app, '/?page=-5&per_page=-5')) ], [ 1, 1, 0 ], 'a negative is clamped up';
my ($p, $n) = $F{_pagination}->(dash_controller($app, '/?per_page=99999999'));
ok $n < 99999999, 'a huge page size is clamped down';
};
# Why: int('abc') warns and is 0, and a per_page of 0 is clamped to one row, so
# a stray parameter showed a single-row table. 1e400 is Inf, and an infinite
# OFFSET is not something a database can be asked for.
subtest 'Dashboard::_pagination -- input that is not a number' => sub {
for my $junk ('abc', '1x', '1e400', '9' x 400, 'Inf', 'NaN', '', '0x10', "1\n") {
(my $shown = substr($junk, 0, 8)) =~ s/\n/NL/;
my @got;
warnings_are {
@got = $F{_pagination}->(dash_controller($app, '/?page=' . Mojo::Util::url_escape($junk) . '&per_page=' . Mojo::Util::url_escape($junk)));
} [], "'$shown' raises no warning";
is_deeply \@got, [ 1, $PER_PAGE, 0 ], "and means the defaults, not one row";
}
};
subtest 'Dashboard::_crumb_spec_name' => sub {
t/function.t view on Meta::CPAN
is $fn->($c, { name => [ 1 ], datasets => [ { spec => $SALES } ] }), 'Missing required field: name', 'or a list';
is $fn->($c, { name => 'n', datasets => [ { spec => [ 1 ] } ] }), 'Each dataset entry must have a spec field', 'a spec that is a list';
like $fn->($c, { name => 'n', version => [ 1 ], datasets => [ { spec => $SALES } ] }), qr/Unsupported analysis version/, 'a version that is a list';
};
subtest 'Dashboard::_whole_number' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_whole_number;
is $fn->('12'), 12, 'digits';
is $fn->('-3'), -3, 'a negative';
is $fn->('0'), 0, 'zero';
is $fn->($_), undef, 'not a whole number' for undef, '', 'abc', '1x', '1.5', '1e3', "5\n", ' 5', '+5', '--5', 'Inf', 'NaN', '0x10', '9' x 16;
keeps_globals_ok('_whole_number', sub { $fn->('5') });
};
# Why: everything reads a stored document blindly, so this is what stands between
# a hand-edit and a 500. An index must survive it: a visual's place in the list is
# what the layout and /a/:id/visual/:n refer to.
subtest 'Dashboard::_tidy_analysis and _tidy_visual' => sub {
my $tidy = \&Database::BI::Controller::Dashboard::_tidy_analysis;
my %good = (
name => 'n',
t/function.t view on Meta::CPAN
is_deeply $e, ["Parameter 'a' must be a number"], 'text for a number';
ok !exists $b->{a}, 'is not bound';
($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1, max => 5 } } }, sub { 9 });
is_deeply $e, ["Parameter 'a' is out of range (min 1, max 5)"], 'over the top';
($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1 } } }, sub { 0 });
is_deeply $e, ["Parameter 'a' is out of range (min 1, max +inf)"], 'under the bottom, with no top';
($b, $e) = $fn->($c, { params => { a => { type => 'number', max => 1 } } }, sub { 2 });
is_deeply $e, ["Parameter 'a' is out of range (min -inf, max 1)"], 'over the top, with no bottom';
};
# Why: every comparison with NaN is false, so "nan" walked straight past min and
# max; looks_like_number says yes to all of these.
subtest 'Dashboard::_bound_canvas_params -- cannot be talked round' => sub {
my $fn = \&Database::BI::Controller::Dashboard::_bound_canvas_params;
my $c = dash_controller($app, '/');
for my $evil (qw(nan NaN inf -inf Infinity)) {
my ($b, $e) = $fn->($c, { params => { a => { type => 'number', min => 1, max => 5 } } }, sub { $evil });
ok !exists $b->{a}, "$evil is not bound";
is scalar @$e, 1, 'and is reported';
}
for my $bad ('oops', 5, [ 1 ]) {
my ($b, $e);
lives_ok { ($b, $e) = $fn->($c, { params => { a => $bad } }, sub { undef }) } 'a stored definition that is not a hash';
is $b->{a}, '', 'is a plain string parameter';
}
};
t/function.t view on Meta::CPAN
is $B->point_key('51.5074', '-0.1278'), '51.507,-0.128', 'rounded to three decimals';
is $B->point_key(51, 0), '51.000,0.000', 'whole numbers get their decimals';
is $B->point_key(90, 180), '90.000,180.000', 'the limits are points';
is $B->point_key(-90, -180), '-90.000,-180.000', 'so are the negative ones';
is $B->point_key('-0.0001', '-0.0004'), '0.000,0.000', 'a point just under zero has no "-0.000" twin';
is $B->point_key('51.5074', '-0.1278'), $B->point_key('51.50741', '-0.12779'), 'points a metre apart share a key';
for my $case (
[ undef, 1 ], [ 1, undef ], [ '', 1 ], [ 'abc', 1 ], [ 1, 'abc' ],
[ 90.001, 0 ], [ -90.001, 0 ], [ 0, 180.001 ], [ 0, -180.001 ],
[ '1e2', 1 ], [ "5\n", 1 ], [ '+5', 1 ], [ '5.', 1 ], [ '.5', 1 ], [ '1,5', 1 ],
[ "1' OR '1'='1", 1 ], [ [ 1 ], 1 ], [ 'NaN', 1 ], [ 'Inf', 1 ],
) {
my @got = $B->point_key(@{$case});
is_deeply \@got, [], 'refused: ' . join(',', map { !defined $_ ? 'undef' : ref $_ ? 'ref' : ($_ =~ s/\n/\\n/gr) } @{$case});
}
};
subtest 'Boundary->check_ranks -- a config the code cannot honour stops at startup' => sub {
my $ok = $B->check_ranks({ GB => 10, fr => '12', De => 8 });
is_deeply $ok, { gb => 10, fr => 12, de => 8 }, 'lower-cased codes, numeric ranks';
memory_cycle_ok($ok, 'the checked hash has no cycle');
t/function.t view on Meta::CPAN
my $key = \&Database::BI::Controller::Dashboard::_filter_date_key;
Readonly my $DAY => 10;
Readonly my $SECOND => 19;
is $key->('2026-01-05', $DAY), '2026-01-05', 'a day';
is $key->('2026-01-05T09:15:07', $SECOND), '2026-01-05T09:15:07', 'a timestamp at second precision';
is $key->('2026-01-05 09:15', $SECOND), '2026-01-05T09:15:00', 'missing seconds are zero';
is $key->('2026-01-05T09:15:07.9+05:30', $DAY), '2026-01-05', 'a zone and fraction are set aside; the day is as written';
is $key->('2026-01-05', $SECOND), '2026-01-05T00:00:00', 'a day at second precision is its start';
is $key->('1/5/2026', $DAY), '2026-01-05', 'M/D/YYYY is rewritten';
is $key->('01/05/2026', $DAY), '2026-01-05', 'with leading zeros too';
for my $text ('', 'x', '1/5/26', '1/5/20266', '1/5/2026 ', '2026-01-05 junk', "2026-01-05\n", '5/1', '--', 'NaN') {
is $key->($text, $DAY), $text, 'not a date, so its own key: ' . ($text =~ s/\n/\\n/gr);
}
my @warned;
local $SIG{__WARN__} = sub { push @warned, @_ };
is $key->(undef, $DAY), undef, 'undef stays undef';
my $ref = [ 1 ];
is $key->($ref, $DAY), $ref, 'a reference is returned untouched, never read as text';
is scalar(@warned), 0, 'and neither warns' or diag @warned;
keeps_globals_ok('_filter_date_key', sub { $key->('2026-01-05', $DAY) });
};
t/function.t view on Meta::CPAN
# ----------------------------------------------------------------------------
subtest 'Util::parse_number -- plain decimals take a short cut that must agree with the long way' => sub {
my $number = \&Database::BI::Util::parse_number;
Readonly my $EDGE => 300; # the longest integer part the short cut takes
is $number->('0'), 0, 'zero';
is $number->('-12.50'), -12.5, 'negative with decimals';
is $number->('007'), 7, 'leading zeros';
ok defined $number->('1' x $EDGE), 'at the edge';
ok defined $number->('1' x ($EDGE + 1)), 'one past the edge, by the long way';
is $number->('9' x 400), undef, 'past a double: not a number, whichever way';
for my $text ('1.', '.5', '1..2', '--1', '1e', '0x10', "\x{FF11}", 'NaN', 'Inf', '-', '.', '1/2') {
is $number->($text), undef, 'not a number: ' . ($text =~ s/[^\x20-\x7e]/?/gr);
}
is $number->("1\n"), 1, 'a trailing newline is stripped as it always was';
is $number->('1 000'), 1000, 'a space is a thousands separator';
is $number->("1\x{a0}000"), 1000, 'so is a non-breaking space';
is $number->('(5)'), -5, 'accounting negatives are still read';
is $number->('$1,000'), 1000, 'currency and separators are still read';
};
done_testing();
my $page = $t->tx->res->body;
# The color select options are built dynamically in JS from table headers,
# but the panel HTML must exist with the correct structure.
like($page, qr/id="map-color-sel"/, 'colour-by select is in the page');
# The JS function no longer filters to numeric-only: verify the
# numeric-guard line is absent from buildColorSelect specifically.
my $tpl = do { local $/; open(my $fh, '<', 'templates/web/en/dashboard.html.tt') or die; <$fh> };
# Extract just the buildColorSelect function body by finding it and
# the closing brace of the function's forEach callback.
my ($color_fn) = ($tpl =~ /(function buildColorSelect.*?^ \})/ms);
unlike($color_fn // '', qr/isNaN.*parseAccounting/,
'buildColorSelect no longer has the numeric-only filter');
}
};
subtest 'size= draws circle markers with a radius scaled from the column' => sub {
$t->get_ok(_url(l => $places_spec, lat => 'lat', lon => 'lon', size => 'amount'))
->status_is(200)
->content_like(qr/L\.circleMarker\(/, 'bubble map uses L.circleMarker')
->content_unlike(qr/data:image\/svg/, 'pins are not also drawn')
->content_like(qr/radius:\s*30\b/, 'largest amount gets the largest radius')
like $b, qr/^\t\tupdateSizeSelect\(card, state\);\r?$/m,
'which writes the menu';
like $b, qr/^\t\tupdateSizeBadge\(card, state\);\r?$/m,
'and the card, so the two cannot disagree';
like $b, qr/updateSizeControls\(card, st\)/,
'so a drag, which leaves any width, is reflected in the menu and on the card';
like $b, qr/updateSizeBadge\(card, \{ w: w, h: h \}\);/,
'and the size on the card follows the grip while it is being dragged';
like $b, qr/if \(w !== shownW \|\| h !== shownH\) \{/,
'written only when the drag crosses a column or a row';
like $b, qr/if \(isNaN\(value\) \|\| value === \(isRow \? st\.h : st\.w\)\) return;/,
'choosing the size it already is does nothing at all';
like $b, qr/var index = sel\.selectedIndex;/, 'the entry that was chosen is remembered';
like $b, qr/sel\.selectedIndex = index;/,
'and stays selected, so the arrow keys walk the list rather than being pulled back';
like $b, qr/announce\(titleOf\(card\) \+ ' is now ' \+/, 'the new size is announced';
like $b, qr/lowerFirst\(sel \? sizeSummary\(sel, w, h\)/,
'both dimensions of it, in the menu words, not just drawn';
like $b, qr/closest\('\.visual-resize-handle, button, a, select'\)/,
'a press on the menu does not start a card drag';
like $b, qr/\@media print.*?\.visual-size-select[^{]*\{[^}]*display\s*:\s*none/s,
templates/web/en-us/canvas.html.tt view on Meta::CPAN
* just placed. A card with no style attribute is placed by the browser,
* and the same way on every visit, so it is left out of the layout
* rather than measured into it - measuring it would freeze whatever the
* render in hand happens to show, which on a cross-filtered or drilled
* canvas is the filtered arrangement and not the one the canvas was
* given. Its position is the browser's to decide until the reader moves
* it themselves. */
var layout = [];
Array.from(grid.querySelectorAll('.visual-card')).forEach(function (c) {
var vid = parseInt(c.getAttribute('data-visual'), 10);
if (isNaN(vid)) return;
if (!c.getAttribute('style')) return;
var sp = spanOf(c);
var x = clampSpan(sp.x, 1, GRID_COLS);
layout.push({
visual : vid,
x : x,
y : Math.max(1, sp.y),
w : clampSpan(sp.w, 1, GRID_COLS - x + 1),
h : clampSpan(sp.h, 1, MAX_ROW_SPAN),
});
templates/web/en-us/canvas.html.tt view on Meta::CPAN
}).catch(function () {
announce('The layout was not saved: the server could not be reached');
});
}
/* ---- grid span helpers (3.2 canvas layout) ---- */
var GRID_COLS = 12;
var MAX_ROW_SPAN = 6;
function clampSpan(n, lo, hi) {
return Math.max(lo, Math.min(hi, isNaN(n) ? lo : n));
}
function gridGap() {
var cs = window.getComputedStyle(grid);
return {
col: parseFloat(cs.columnGap || cs.gap) || 0,
row: parseFloat(cs.rowGap || cs.gap) || 0,
};
}
templates/web/en-us/canvas.html.tt view on Meta::CPAN
* two longhands, WebKit re-serialises the attribute as the grid-area
* shorthand ("grid-area: 1 / 1 / span 1 / span 6"), which no
* grid-column-based pattern would match. A span may also come back in
* the start longhand (grid-column: span 6 computes to start="span 6"), so
* both are searched. */
function gridPlacement(cs, axis) {
var start = cs['grid' + axis + 'Start'] || '';
var end = cs['grid' + axis + 'End'] || '';
var span = (start + ' ' + end).match(/span\s+(\d+)/);
var line = parseInt(start, 10);
return { span: span ? parseInt(span[1], 10) : 0, line: isNaN(line) ? 0 : line };
}
function spanOf(card) {
var cs = window.getComputedStyle(card);
var col = gridPlacement(cs, 'Column');
var row = gridPlacement(cs, 'Row');
var gap = gridGap();
var cr = card.getBoundingClientRect();
var gr = grid.getBoundingClientRect();
templates/web/en-us/canvas.html.tt view on Meta::CPAN
}
function rowTracksTo(px) {
var cs = window.getComputedStyle(grid);
var gap = gridGap().row;
var pitch = parseFloat((cs.gridAutoRows || '').match(/[\d.]+px/)) || 240;
var tracks = [];
var at = 0;
(cs.gridTemplateRows || '').split(/\s+/).forEach(function (t) {
var h = parseFloat(t);
if (isNaN(h) || !/px$/.test(t)) return;
tracks.push({ top: at, bottom: at + h });
at += h + gap;
});
while (at <= px + pitch + gap) {
tracks.push({ top: at, bottom: at + pitch });
at += pitch + gap;
}
return tracks;
}
templates/web/en-us/canvas.html.tt view on Meta::CPAN
* become: choosing it again is not a choice. */
if (!raw) return;
var st = resizeState(card);
var isRow = raw.charAt(0) === 'h';
var value = parseInt(isRow ? raw.slice(1) : raw, 10);
/* Choosing the size the card already is should do nothing rather
* than re-announce itself, and leave the entry selected so the next
* arrow key carries on down the list. */
if (isNaN(value) || value === (isRow ? st.h : st.w)) return;
if (isRow) commitSize(card, st.w, value);
else commitSize(card, value, st.h);
/* The entry that was chosen stays chosen: the commit re-selects the
* summary, and a reader stepping down the list with the arrow keys
* would otherwise be pulled back to the top after every change. */
sel.selectedIndex = index;
});
});
templates/web/en-us/canvas.html.tt view on Meta::CPAN
* - Multi-select not supported: each click replaces any prior cross-filter.
* - Cross-filter respects each visual's own saved filters because the
* server applies ?cf= on top of them (see canvas_render in Dashboard.pm).
*
* extractCfValue(d) extracts the categorical value from a D3 datum.
* HTML::D3 uses these shapes depending on chart kind:
* bar/treemap : d = [label, value] (positional array)
* pie : d = { data:[label,value], ... } (pie arc datum)
* stacked : d = { cat, seg, val }
* combo/line : d = { x, bar_val, line_val } or { label, value }
* scatter : d = [x, y] -- less useful for CF; skipped when val==NaN
*/
function extractCfValue(d) {
if (d === undefined || d === null) return null;
/* A stacked segment's datum is a position in its group -- [row, column]
* -- carrying the row it came from in .data, so the category has to be
* read before the array is taken as the value: the array holds indexes,
* and the first of them is why every segment used to filter by "0". */
if (d.data && typeof d.data === 'object' && !Array.isArray(d.data)
&& d.data.cat !== undefined) {
return String(d.data.cat);
templates/web/en-us/canvas.html.tt view on Meta::CPAN
function syncTreemapColour() {
var on = !!(tmColorSel && tmColorSel.value);
if (tmColorAggSel) tmColorAggSel.disabled = !on;
if (tmColorSchemeSel) tmColorSchemeSel.disabled = !on;
}
if (tmColorSel) tmColorSel.addEventListener('change', syncTreemapColour);
/* A radius as the server takes it: a whole number from 1 to 40. */
function scRadius(inp, dflt) {
var n = parseInt(inp.value, 10);
if (isNaN(n)) n = dflt;
return Math.min(40, Math.max(1, n));
}
/* The views whose value column is aggregated, and so the only ones that
* can use an aggregate function of their own. */
var AGG_KINDS = { bar: 1, pie: 1, stacked: 1, treemap: 1, heatmap: 1, combo: 1 };
/* A percentile is written into the function name -- p95 -- because a card
* stores one key for its aggregate, as a pivot measure does. Reading the
* level back clamps it, so the panel cannot build a name the server would
templates/web/en-us/canvas.html.tt view on Meta::CPAN
var target = editTarget;
editPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
editTarget = null;
editLoaded = false;
if (returnFocus && target) target.btn.focus();
};
var editOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
/* A second press on the same control closes it, like the other
* panel on this toolbar. */
if (!editPanel.hidden && editTarget && editTarget.card === card) {
editClose(1);
return;
}
if (editTarget) editTarget.btn.setAttribute('aria-expanded', 'false');
editTarget = { card: card, btn: btn, index: index };
templates/web/en-us/canvas.html.tt view on Meta::CPAN
txHeading.textContent = 'Add text';
txSave.textContent = 'Add to canvas';
txRemove.hidden = true;
txFill(txBlank);
txRefresh();
txShow(txBtn);
};
var txOpenEdit = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
var body = card.querySelector('.visual-card-body');
txClose(0);
txHeading.textContent = 'Edit text';
txSave.textContent = 'Save text';
txRemove.hidden = false;
txShow(btn);
txSave.disabled = true;
fetch('/api/analyses/' + encodeURIComponent(anaId))
.then(function (r) { return r.json(); })
templates/web/en-us/canvas.html.tt view on Meta::CPAN
/* The cards after this one are renumbered, so the page is drawn again,
* with a cross-filter's source card moved down to match. */
txRemove.addEventListener('click', function () {
var target = txTarget;
if (!target || !confirm('Remove this text from the canvas?\n\nThis cannot be undone.')) return;
txRemove.disabled = true;
txRequest('/api/analyses/' + encodeURIComponent(anaId) + '/visuals/' + target.index, 'DELETE')
.then(function () {
var u = new URL(window.location.href);
var cv = parseInt(u.searchParams.get('cv'), 10);
if (!isNaN(cv) && cv > target.index) u.searchParams.set('cv', String(cv - 1));
window.location.replace(u.toString());
})
.catch(function (err) {
txSetError(err.message);
txRemove.disabled = false;
});
});
}());
/* ---- editing a card's cross-row plan in place ----
templates/web/en-us/canvas.html.tt view on Meta::CPAN
crPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
crTarget = null;
crLoaded = false;
crEditing = -1;
if (returnFocus && target) target.btn.focus();
};
var crOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
if (!crPanel.hidden && crTarget && crTarget.card === card) {
crClose(1);
return;
}
if (crTarget) crTarget.btn.setAttribute('aria-expanded', 'false');
crTarget = { card: card, btn: btn, index: index };
crLoaded = false;
crSpecs = [];
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
// Auto-detect M/D/YYYY vs D/M/YYYY: scan for a value that disambiguates.
for (var di = 0; di < nonEmpty.length; di++) {
var dm = nonEmpty[di].match(/^(\d{1,2})\/(\d{1,2})\/\d{4}$/);
if (!dm) continue;
if (+dm[1] > 12) { monthFirst = false; break; }
if (+dm[2] > 12) { monthFirst = true; break; }
}
}
var numeric = !isDate && nonEmpty.length > 0 && nonEmpty.every(function (v) {
return !isNaN(parseAccounting(v));
});
return function (av, bv) {
var cmp;
if (isDate) {
var ak = biDateKey(av, monthFirst), bk = biDateKey(bv, monthFirst);
cmp = (ak === null ? -Infinity : ak) - (bk === null ? -Infinity : bk);
} else if (numeric) {
var an = parseAccounting(av), bn = parseAccounting(bv);
cmp = (isNaN(an) ? -Infinity : an) - (isNaN(bn) ? -Infinity : bn);
} else {
cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
}
return asc ? cmp : -cmp;
};
}
// biViewParams() -> URLSearchParams
// The parameters that make this view, for a request that reads its rows
// (Export saves them, Print prints them). l= comes from the join form, since
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
}
if (colIdx < 0) return 'string';
var rows = Array.from(tbl.tBodies[0].rows).slice(0, 30);
var vals = rows.map(function (r) {
return r.cells[colIdx] ? r.cells[colIdx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return 'string';
var dateRE = /^\d{4}-\d{2}-\d{2}$|^\d{1,2}\/\d{1,2}\/\d{4}$|^\d{1,2}-[A-Za-z]{3}-\d{4}$/;
var dateCnt = vals.filter(function (v) { return dateRE.test(v); }).length;
if (dateCnt / vals.length >= 0.7) return 'date';
var numCnt = vals.filter(function (v) { return !isNaN(parseAccounting(v)); }).length;
if (numCnt / vals.length >= 0.7) return 'numeric';
return 'string';
}
(function () {
var table = document.getElementById('bi-table');
if (!table) return;
var chkTotals = document.getElementById('chk-totals');
// SEL = 1: the checkbox column we inject is always cell 0 in each row, so
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
tr.insertCell().className = 'sel-td';
headers.forEach(function (h, i) {
var td = tr.insertCell();
var vals = rows.map(function (r) {
return r.cells[i + SEL] ? r.cells[i + SEL].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
var isDate = vals.length > 0 && vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
});
var numeric = !isDate && vals.length > 0 && vals.every(function (v) {
return !isNaN(parseAccounting(v));
});
if (numeric) {
var sum = vals.reduce(function (acc, v) { return acc + parseAccounting(v); }, 0);
var hasDec = vals.some(function (v) { return /\.\d+/.test(v.replace(/[^0-9.]/g, '')); });
td.textContent = hasDec ? sum.toFixed(2) : String(Math.round(sum));
td.className = 'totals-sum';
}
// Re-apply col-selected highlight to tfoot cells when totals are rebuilt
if (selectedCols.has(i)) td.classList.add('col-selected');
});
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
// Returns true if v looks like a date (excluded from numeric Y axis).
function isDateVal(v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
}
// Returns true if v is plottable as a number (mirrors the server's strip logic).
// Recognizes accounting negatives: (1,234.56) counts as a valid number.
function isNumericVal(v) {
if (v === '') return true;
return !isNaN(parseAccounting(v));
}
var yTextInput = document.getElementById('graph-y-text');
var yLabel = document.getElementById('graph-y-label');
// Rebuild the Y-axis select to show only columns whose non-empty values are
// all numeric (after stripping currency symbols etc.) and not date-shaped.
// Returns the number of numeric options added (excluding the placeholder).
function buildYSelect() {
var tbl = document.querySelector('table[data-table]') || document.querySelector('table');
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
// Exclude date-shaped columns.
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
// Only show columns whose non-empty values are all numeric.
if (!vals.every(function (v) {
if (v === '') return true;
return !isNaN(parseAccounting(v));
})) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
btnOpen.addEventListener('click', function () {
biClosePanels(panel);
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
while (valSel.options.length > 1) valSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
function checkHeatmap() {
btnDo.disabled = !(xSel.value && ySel.value);
}
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
while (valSel.options.length > 1) valSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
function checkBar() {
btnDo.disabled = !catSel.value;
}
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
if (sizeSel) { while (sizeSel.options.length > 1) sizeSel.remove(1); }
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var optX = document.createElement('option');
optX.value = name; optX.textContent = name;
if (name === prevX) optX.selected = true;
xSel.appendChild(optX);
var optY = document.createElement('option');
optY.value = name; optY.textContent = name;
if (name === prevY) optY.selected = true;
ySel.appendChild(optY);
if (sizeSel) {
var optS = document.createElement('option');
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
});
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var optBar = document.createElement('option');
optBar.value = name; optBar.textContent = name;
if (name === prevBar) optBar.selected = true;
barSel.appendChild(optBar);
var optLine = document.createElement('option');
optLine.value = name; optLine.textContent = name;
if (name === prevLine) optLine.selected = true;
lineSel.appendChild(optLine);
});
}
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
while (colSel.options.length > 1) colSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
colSel.appendChild(opt);
});
var n = colSel.options.length - 1;
if (n === 0) {
btnOpen.disabled = true;
btnOpen.title = 'Histogram needs a numeric column';
}
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
var headers = Array.from(tbl.tHead.rows[0].cells);
var rows = Array.from(tbl.tBodies[0].rows);
var prev = colSel.value;
while (colSel.options.length > 1) colSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
if (vals.every(isDate)) return;
if (!vals.some(function (v) { return /[^\d\s.,%$()+\-]/.test(v); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
colSel.appendChild(opt);
});
var n = colSel.options.length - 1;
if (n === 0) {
btnOpen.disabled = true;
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
if (!tbl || !tbl.tHead || !tbl.tBodies[0]) return;
var headers = Array.from(tbl.tHead.rows[0].cells).map(function (th) { return th.textContent.trim(); });
var rows = Array.from(tbl.tBodies[0].rows);
var numeric = {};
headers.forEach(function (name, idx) {
if (!name) return;
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
numeric[name] = vals.length > 0 && vals.every(function (v) {
return !isNaN(parseAccounting(v));
});
});
Array.from(colSel.options).forEach(function (opt) {
if (opt.value) opt.disabled = !numeric[opt.value];
});
}
// The panel edits parameters of the view it is open on, so its controls start
// where the view already is: the partition and the read order it is using.
// A partition of several columns has no matching option, so it is shown as a
templates/web/en-us/dashboard.html.tt view on Meta::CPAN
var refNum = parseFloat(hlVal);
var firstHl = null;
Array.from(table.tBodies[0].rows).forEach(function (row) {
var cell = row.cells[colIdx];
if (!cell) return;
var raw = cell.textContent.trim();
var cellNum = parseAccounting(raw);
var match;
if (isNaN(cellNum) || isNaN(refNum)) {
match = (hlOp === 'eq' && raw === hlVal);
} else {
if (hlOp === 'gt') match = cellNum > refNum;
else if (hlOp === 'ge') match = cellNum >= refNum;
else if (hlOp === 'lt') match = cellNum < refNum;
else if (hlOp === 'le') match = cellNum <= refNum;
else match = Math.abs(cellNum - refNum) < 1e-9;
}
if (match) {
row.classList.add('hl-row');
templates/web/en-us/layouts/parse_accounting.html.tt view on Meta::CPAN
[%#
parseAccounting(text) -> number | NaN, for PROCESS inside a <script>.
The number a cell holds, by the server's rule (Database::BI::Util's
parse_number; change one, change the other): only what dresses a number up
is removed -- spaces, brackets, thousands separators, a percent sign,
currency symbols and a known currency code -- and any other letter stays and
fails the match, so "T27" and "CT4" are text, not 27 and 4. "(1,234.56)"
is -1234.56: the bracket is read before it is removed.
-%]
var BI_CURRENCY_CODES = 'AUD|BRL|CAD|CHF|CNY|DKK|EUR|GBP|HKD|INR|JPY|MXN|NOK|NZD|SEK|SGD|USD|ZAR';
var BI_CURRENCY_RE = new RegExp('(?:^|(?<=[\\s(]))(?:' + BI_CURRENCY_CODES + ')(?=[\\s\\d.])'
+ '|(?<=[\\s\\d])(?:' + BI_CURRENCY_CODES + ')(?=[\\s)]|$)', 'g');
function parseAccounting(v) {
if (v === null || v === undefined || v === '') return NaN;
var s = String(v);
var accounting = /^\s*\(/.test(s);
var t = s.replace(BI_CURRENCY_RE, '').replace(/[\s(),$%]|[^\x00-\x7F]/g, '');
if (accounting && /^\d/.test(t)) t = '-' + t;
if (!/^-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?$/.test(t)) return NaN;
var n = Number(t);
return isFinite(n) ? n : NaN;
}
templates/web/en-us/pivot.html.tt view on Meta::CPAN
function sortByCol(leafIdx, asc) {
var dIdx = domColIdx(leafIdx);
var tbody = table.tBodies[0];
var rows = Array.from(tbody.rows);
var nonEmpty = rows
.map(function (r) { return r.cells[dIdx] ? r.cells[dIdx].textContent.trim() : ''; })
.filter(Boolean);
var numeric = nonEmpty.length > 0 && nonEmpty.every(function (v) {
return !isNaN(parseAccounting(v));
});
rows.sort(function (a, b) {
var av = a.cells[dIdx] ? a.cells[dIdx].textContent.trim() : '';
var bv = b.cells[dIdx] ? b.cells[dIdx].textContent.trim() : '';
var cmp;
if (numeric) {
var an = parseAccounting(av), bn = parseAccounting(bv);
cmp = (isNaN(an) ? 0 : an) - (isNaN(bn) ? 0 : bn);
} else {
cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
}
return asc ? cmp : -cmp;
});
rows.forEach(function (r) { tbody.appendChild(r); });
leafHeaders.forEach(function (h, i) {
h.setAttribute('aria-sort', i === leafIdx ? (asc ? 'ascending' : 'descending') : 'none');
});
templates/web/en/canvas.html.tt view on Meta::CPAN
* just placed. A card with no style attribute is placed by the browser,
* and the same way on every visit, so it is left out of the layout
* rather than measured into it - measuring it would freeze whatever the
* render in hand happens to show, which on a cross-filtered or drilled
* canvas is the filtered arrangement and not the one the canvas was
* given. Its position is the browser's to decide until the reader moves
* it themselves. */
var layout = [];
Array.from(grid.querySelectorAll('.visual-card')).forEach(function (c) {
var vid = parseInt(c.getAttribute('data-visual'), 10);
if (isNaN(vid)) return;
if (!c.getAttribute('style')) return;
var sp = spanOf(c);
var x = clampSpan(sp.x, 1, GRID_COLS);
layout.push({
visual : vid,
x : x,
y : Math.max(1, sp.y),
w : clampSpan(sp.w, 1, GRID_COLS - x + 1),
h : clampSpan(sp.h, 1, MAX_ROW_SPAN),
});
templates/web/en/canvas.html.tt view on Meta::CPAN
}).catch(function () {
announce('The layout was not saved: the server could not be reached');
});
}
/* ---- grid span helpers (3.2 canvas layout) ---- */
var GRID_COLS = 12;
var MAX_ROW_SPAN = 6;
function clampSpan(n, lo, hi) {
return Math.max(lo, Math.min(hi, isNaN(n) ? lo : n));
}
function gridGap() {
var cs = window.getComputedStyle(grid);
return {
col: parseFloat(cs.columnGap || cs.gap) || 0,
row: parseFloat(cs.rowGap || cs.gap) || 0,
};
}
templates/web/en/canvas.html.tt view on Meta::CPAN
* two longhands, WebKit re-serialises the attribute as the grid-area
* shorthand ("grid-area: 1 / 1 / span 1 / span 6"), which no
* grid-column-based pattern would match. A span may also come back in
* the start longhand (grid-column: span 6 computes to start="span 6"), so
* both are searched. */
function gridPlacement(cs, axis) {
var start = cs['grid' + axis + 'Start'] || '';
var end = cs['grid' + axis + 'End'] || '';
var span = (start + ' ' + end).match(/span\s+(\d+)/);
var line = parseInt(start, 10);
return { span: span ? parseInt(span[1], 10) : 0, line: isNaN(line) ? 0 : line };
}
function spanOf(card) {
var cs = window.getComputedStyle(card);
var col = gridPlacement(cs, 'Column');
var row = gridPlacement(cs, 'Row');
var gap = gridGap();
var cr = card.getBoundingClientRect();
var gr = grid.getBoundingClientRect();
templates/web/en/canvas.html.tt view on Meta::CPAN
}
function rowTracksTo(px) {
var cs = window.getComputedStyle(grid);
var gap = gridGap().row;
var pitch = parseFloat((cs.gridAutoRows || '').match(/[\d.]+px/)) || 240;
var tracks = [];
var at = 0;
(cs.gridTemplateRows || '').split(/\s+/).forEach(function (t) {
var h = parseFloat(t);
if (isNaN(h) || !/px$/.test(t)) return;
tracks.push({ top: at, bottom: at + h });
at += h + gap;
});
while (at <= px + pitch + gap) {
tracks.push({ top: at, bottom: at + pitch });
at += pitch + gap;
}
return tracks;
}
templates/web/en/canvas.html.tt view on Meta::CPAN
* become: choosing it again is not a choice. */
if (!raw) return;
var st = resizeState(card);
var isRow = raw.charAt(0) === 'h';
var value = parseInt(isRow ? raw.slice(1) : raw, 10);
/* Choosing the size the card already is should do nothing rather
* than re-announce itself, and leave the entry selected so the next
* arrow key carries on down the list. */
if (isNaN(value) || value === (isRow ? st.h : st.w)) return;
if (isRow) commitSize(card, st.w, value);
else commitSize(card, value, st.h);
/* The entry that was chosen stays chosen: the commit re-selects the
* summary, and a reader stepping down the list with the arrow keys
* would otherwise be pulled back to the top after every change. */
sel.selectedIndex = index;
});
});
templates/web/en/canvas.html.tt view on Meta::CPAN
* - Multi-select not supported: each click replaces any prior cross-filter.
* - Cross-filter respects each visual's own saved filters because the
* server applies ?cf= on top of them (see canvas_render in Dashboard.pm).
*
* extractCfValue(d) extracts the categorical value from a D3 datum.
* HTML::D3 uses these shapes depending on chart kind:
* bar/treemap : d = [label, value] (positional array)
* pie : d = { data:[label,value], ... } (pie arc datum)
* stacked : d = { cat, seg, val }
* combo/line : d = { x, bar_val, line_val } or { label, value }
* scatter : d = [x, y] -- less useful for CF; skipped when val==NaN
*/
function extractCfValue(d) {
if (d === undefined || d === null) return null;
/* A stacked segment's datum is a position in its group -- [row, column]
* -- carrying the row it came from in .data, so the category has to be
* read before the array is taken as the value: the array holds indexes,
* and the first of them is why every segment used to filter by "0". */
if (d.data && typeof d.data === 'object' && !Array.isArray(d.data)
&& d.data.cat !== undefined) {
return String(d.data.cat);
templates/web/en/canvas.html.tt view on Meta::CPAN
function syncTreemapColour() {
var on = !!(tmColorSel && tmColorSel.value);
if (tmColorAggSel) tmColorAggSel.disabled = !on;
if (tmColorSchemeSel) tmColorSchemeSel.disabled = !on;
}
if (tmColorSel) tmColorSel.addEventListener('change', syncTreemapColour);
/* A radius as the server takes it: a whole number from 1 to 40. */
function scRadius(inp, dflt) {
var n = parseInt(inp.value, 10);
if (isNaN(n)) n = dflt;
return Math.min(40, Math.max(1, n));
}
/* The views whose value column is aggregated, and so the only ones that
* can use an aggregate function of their own. */
var AGG_KINDS = { bar: 1, pie: 1, stacked: 1, treemap: 1, heatmap: 1, combo: 1 };
/* A percentile is written into the function name -- p95 -- because a card
* stores one key for its aggregate, as a pivot measure does. Reading the
* level back clamps it, so the panel cannot build a name the server would
templates/web/en/canvas.html.tt view on Meta::CPAN
var target = editTarget;
editPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
editTarget = null;
editLoaded = false;
if (returnFocus && target) target.btn.focus();
};
var editOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
/* A second press on the same control closes it, like the other
* panel on this toolbar. */
if (!editPanel.hidden && editTarget && editTarget.card === card) {
editClose(1);
return;
}
if (editTarget) editTarget.btn.setAttribute('aria-expanded', 'false');
editTarget = { card: card, btn: btn, index: index };
templates/web/en/canvas.html.tt view on Meta::CPAN
txHeading.textContent = 'Add text';
txSave.textContent = 'Add to canvas';
txRemove.hidden = true;
txFill(txBlank);
txRefresh();
txShow(txBtn);
};
var txOpenEdit = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
var body = card.querySelector('.visual-card-body');
txClose(0);
txHeading.textContent = 'Edit text';
txSave.textContent = 'Save text';
txRemove.hidden = false;
txShow(btn);
txSave.disabled = true;
fetch('/api/analyses/' + encodeURIComponent(anaId))
.then(function (r) { return r.json(); })
templates/web/en/canvas.html.tt view on Meta::CPAN
/* The cards after this one are renumbered, so the page is drawn again,
* with a cross-filter's source card moved down to match. */
txRemove.addEventListener('click', function () {
var target = txTarget;
if (!target || !confirm('Remove this text from the canvas?\n\nThis cannot be undone.')) return;
txRemove.disabled = true;
txRequest('/api/analyses/' + encodeURIComponent(anaId) + '/visuals/' + target.index, 'DELETE')
.then(function () {
var u = new URL(window.location.href);
var cv = parseInt(u.searchParams.get('cv'), 10);
if (!isNaN(cv) && cv > target.index) u.searchParams.set('cv', String(cv - 1));
window.location.replace(u.toString());
})
.catch(function (err) {
txSetError(err.message);
txRemove.disabled = false;
});
});
}());
/* ---- editing a card's cross-row plan in place ----
templates/web/en/canvas.html.tt view on Meta::CPAN
crPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
crTarget = null;
crLoaded = false;
crEditing = -1;
if (returnFocus && target) target.btn.focus();
};
var crOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
if (!crPanel.hidden && crTarget && crTarget.card === card) {
crClose(1);
return;
}
if (crTarget) crTarget.btn.setAttribute('aria-expanded', 'false');
crTarget = { card: card, btn: btn, index: index };
crLoaded = false;
crSpecs = [];
templates/web/en/dashboard.html.tt view on Meta::CPAN
// Auto-detect M/D/YYYY vs D/M/YYYY: scan for a value that disambiguates.
for (var di = 0; di < nonEmpty.length; di++) {
var dm = nonEmpty[di].match(/^(\d{1,2})\/(\d{1,2})\/\d{4}$/);
if (!dm) continue;
if (+dm[1] > 12) { monthFirst = false; break; }
if (+dm[2] > 12) { monthFirst = true; break; }
}
}
var numeric = !isDate && nonEmpty.length > 0 && nonEmpty.every(function (v) {
return !isNaN(parseAccounting(v));
});
return function (av, bv) {
var cmp;
if (isDate) {
var ak = biDateKey(av, monthFirst), bk = biDateKey(bv, monthFirst);
cmp = (ak === null ? -Infinity : ak) - (bk === null ? -Infinity : bk);
} else if (numeric) {
var an = parseAccounting(av), bn = parseAccounting(bv);
cmp = (isNaN(an) ? -Infinity : an) - (isNaN(bn) ? -Infinity : bn);
} else {
cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
}
return asc ? cmp : -cmp;
};
}
// biViewParams() -> URLSearchParams
// The parameters that make this view, for a request that reads its rows
// (Export saves them, Print prints them). l= comes from the join form, since
templates/web/en/dashboard.html.tt view on Meta::CPAN
}
if (colIdx < 0) return 'string';
var rows = Array.from(tbl.tBodies[0].rows).slice(0, 30);
var vals = rows.map(function (r) {
return r.cells[colIdx] ? r.cells[colIdx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return 'string';
var dateRE = /^\d{4}-\d{2}-\d{2}$|^\d{1,2}\/\d{1,2}\/\d{4}$|^\d{1,2}-[A-Za-z]{3}-\d{4}$/;
var dateCnt = vals.filter(function (v) { return dateRE.test(v); }).length;
if (dateCnt / vals.length >= 0.7) return 'date';
var numCnt = vals.filter(function (v) { return !isNaN(parseAccounting(v)); }).length;
if (numCnt / vals.length >= 0.7) return 'numeric';
return 'string';
}
(function () {
var table = document.getElementById('bi-table');
if (!table) return;
var chkTotals = document.getElementById('chk-totals');
// SEL = 1: the checkbox column we inject is always cell 0 in each row, so
templates/web/en/dashboard.html.tt view on Meta::CPAN
tr.insertCell().className = 'sel-td';
headers.forEach(function (h, i) {
var td = tr.insertCell();
var vals = rows.map(function (r) {
return r.cells[i + SEL] ? r.cells[i + SEL].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
var isDate = vals.length > 0 && vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
});
var numeric = !isDate && vals.length > 0 && vals.every(function (v) {
return !isNaN(parseAccounting(v));
});
if (numeric) {
var sum = vals.reduce(function (acc, v) { return acc + parseAccounting(v); }, 0);
var hasDec = vals.some(function (v) { return /\.\d+/.test(v.replace(/[^0-9.]/g, '')); });
td.textContent = hasDec ? sum.toFixed(2) : String(Math.round(sum));
td.className = 'totals-sum';
}
// Re-apply col-selected highlight to tfoot cells when totals are rebuilt
if (selectedCols.has(i)) td.classList.add('col-selected');
});
templates/web/en/dashboard.html.tt view on Meta::CPAN
// Returns true if v looks like a date (excluded from numeric Y axis).
function isDateVal(v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
}
// Returns true if v is plottable as a number (mirrors the server's strip logic).
// Recognises accounting negatives: (1,234.56) counts as a valid number.
function isNumericVal(v) {
if (v === '') return true;
return !isNaN(parseAccounting(v));
}
var yTextInput = document.getElementById('graph-y-text');
var yLabel = document.getElementById('graph-y-label');
// Rebuild the Y-axis select to show only columns whose non-empty values are
// all numeric (after stripping currency symbols etc.) and not date-shaped.
// Returns the number of numeric options added (excluding the placeholder).
function buildYSelect() {
var tbl = document.querySelector('table[data-table]') || document.querySelector('table');
templates/web/en/dashboard.html.tt view on Meta::CPAN
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
// Exclude date-shaped columns.
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
// Only show columns whose non-empty values are all numeric.
if (!vals.every(function (v) {
if (v === '') return true;
return !isNaN(parseAccounting(v));
})) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
btnOpen.addEventListener('click', function () {
biClosePanels(panel);
templates/web/en/dashboard.html.tt view on Meta::CPAN
while (valSel.options.length > 1) valSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
function checkHeatmap() {
btnDo.disabled = !(xSel.value && ySel.value);
}
templates/web/en/dashboard.html.tt view on Meta::CPAN
while (valSel.options.length > 1) valSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
valSel.appendChild(opt);
});
}
function checkBar() {
btnDo.disabled = !catSel.value;
}
templates/web/en/dashboard.html.tt view on Meta::CPAN
if (sizeSel) { while (sizeSel.options.length > 1) sizeSel.remove(1); }
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var optX = document.createElement('option');
optX.value = name; optX.textContent = name;
if (name === prevX) optX.selected = true;
xSel.appendChild(optX);
var optY = document.createElement('option');
optY.value = name; optY.textContent = name;
if (name === prevY) optY.selected = true;
ySel.appendChild(optY);
if (sizeSel) {
var optS = document.createElement('option');
templates/web/en/dashboard.html.tt view on Meta::CPAN
});
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var optBar = document.createElement('option');
optBar.value = name; optBar.textContent = name;
if (name === prevBar) optBar.selected = true;
barSel.appendChild(optBar);
var optLine = document.createElement('option');
optLine.value = name; optLine.textContent = name;
if (name === prevLine) optLine.selected = true;
lineSel.appendChild(optLine);
});
}
templates/web/en/dashboard.html.tt view on Meta::CPAN
while (colSel.options.length > 1) colSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) {
return /^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(v);
})) return;
if (!vals.every(function (v) { return v === '' || !isNaN(parseAccounting(v)); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
colSel.appendChild(opt);
});
var n = colSel.options.length - 1;
if (n === 0) {
btnOpen.disabled = true;
btnOpen.title = 'Histogram needs a numeric column';
}
templates/web/en/dashboard.html.tt view on Meta::CPAN
var headers = Array.from(tbl.tHead.rows[0].cells);
var rows = Array.from(tbl.tBodies[0].rows);
var prev = colSel.value;
while (colSel.options.length > 1) colSel.remove(1);
headers.forEach(function (th, idx) {
var name = th.textContent.trim();
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
if (vals.length === 0) return;
if (vals.every(function (v) { return !isNaN(parseAccounting(v)); })) return;
if (vals.every(isDate)) return;
if (!vals.some(function (v) { return /[^\d\s.,%$()+\-]/.test(v); })) return;
var opt = document.createElement('option');
opt.value = name; opt.textContent = name;
if (name === prev) opt.selected = true;
colSel.appendChild(opt);
});
var n = colSel.options.length - 1;
if (n === 0) {
btnOpen.disabled = true;
templates/web/en/dashboard.html.tt view on Meta::CPAN
if (!tbl || !tbl.tHead || !tbl.tBodies[0]) return;
var headers = Array.from(tbl.tHead.rows[0].cells).map(function (th) { return th.textContent.trim(); });
var rows = Array.from(tbl.tBodies[0].rows);
var numeric = {};
headers.forEach(function (name, idx) {
if (!name) return;
var vals = rows.map(function (r) {
return r.cells[idx] ? r.cells[idx].textContent.trim() : '';
}).filter(function (v) { return v !== ''; });
numeric[name] = vals.length > 0 && vals.every(function (v) {
return !isNaN(parseAccounting(v));
});
});
Array.from(colSel.options).forEach(function (opt) {
if (opt.value) opt.disabled = !numeric[opt.value];
});
}
// The panel edits parameters of the view it is open on, so its controls start
// where the view already is: the partition and the read order it is using.
// A partition of several columns has no matching option, so it is shown as a
templates/web/en/dashboard.html.tt view on Meta::CPAN
var refNum = parseFloat(hlVal);
var firstHl = null;
Array.from(table.tBodies[0].rows).forEach(function (row) {
var cell = row.cells[colIdx];
if (!cell) return;
var raw = cell.textContent.trim();
var cellNum = parseAccounting(raw);
var match;
if (isNaN(cellNum) || isNaN(refNum)) {
match = (hlOp === 'eq' && raw === hlVal);
} else {
if (hlOp === 'gt') match = cellNum > refNum;
else if (hlOp === 'ge') match = cellNum >= refNum;
else if (hlOp === 'lt') match = cellNum < refNum;
else if (hlOp === 'le') match = cellNum <= refNum;
else match = Math.abs(cellNum - refNum) < 1e-9;
}
if (match) {
row.classList.add('hl-row');
templates/web/en/layouts/parse_accounting.html.tt view on Meta::CPAN
[%#
parseAccounting(text) -> number | NaN, for PROCESS inside a <script>.
The number a cell holds, by the server's rule (Database::BI::Util's
parse_number; change one, change the other): only what dresses a number up
is removed -- spaces, brackets, thousands separators, a percent sign,
currency symbols and a known currency code -- and any other letter stays and
fails the match, so "T27" and "CT4" are text, not 27 and 4. "(1,234.56)"
is -1234.56: the bracket is read before it is removed.
-%]
var BI_CURRENCY_CODES = 'AUD|BRL|CAD|CHF|CNY|DKK|EUR|GBP|HKD|INR|JPY|MXN|NOK|NZD|SEK|SGD|USD|ZAR';
var BI_CURRENCY_RE = new RegExp('(?:^|(?<=[\\s(]))(?:' + BI_CURRENCY_CODES + ')(?=[\\s\\d.])'
+ '|(?<=[\\s\\d])(?:' + BI_CURRENCY_CODES + ')(?=[\\s)]|$)', 'g');
function parseAccounting(v) {
if (v === null || v === undefined || v === '') return NaN;
var s = String(v);
var accounting = /^\s*\(/.test(s);
var t = s.replace(BI_CURRENCY_RE, '').replace(/[\s(),$%]|[^\x00-\x7F]/g, '');
if (accounting && /^\d/.test(t)) t = '-' + t;
if (!/^-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?$/.test(t)) return NaN;
var n = Number(t);
return isFinite(n) ? n : NaN;
}
templates/web/en/pivot.html.tt view on Meta::CPAN
function sortByCol(leafIdx, asc) {
var dIdx = domColIdx(leafIdx);
var tbody = table.tBodies[0];
var rows = Array.from(tbody.rows);
var nonEmpty = rows
.map(function (r) { return r.cells[dIdx] ? r.cells[dIdx].textContent.trim() : ''; })
.filter(Boolean);
var numeric = nonEmpty.length > 0 && nonEmpty.every(function (v) {
return !isNaN(parseAccounting(v));
});
rows.sort(function (a, b) {
var av = a.cells[dIdx] ? a.cells[dIdx].textContent.trim() : '';
var bv = b.cells[dIdx] ? b.cells[dIdx].textContent.trim() : '';
var cmp;
if (numeric) {
var an = parseAccounting(av), bn = parseAccounting(bv);
cmp = (isNaN(an) ? 0 : an) - (isNaN(bn) ? 0 : bn);
} else {
cmp = av.localeCompare(bv, undefined, { numeric: true, sensitivity: 'base' });
}
return asc ? cmp : -cmp;
});
rows.forEach(function (r) { tbody.appendChild(r); });
leafHeaders.forEach(function (h, i) {
h.setAttribute('aria-sort', i === leafIdx ? (asc ? 'ascending' : 'descending') : 'none');
});