Source of browser.plp

<(common.inc.plp)><:
use 5.010;
use utf8;
use List::Util qw(sum max first);
no if $] >= 5.018, warnings => 'experimental::smartmatch';

Html({
	title => 'browser compatibility cheat sheet',
	version => '1.4',
	description => [
		"Compatibility table of new web features (HTML5, CSS3, SVG, Javascript)",
		"comparing support and usage share for all popular browser versions.",
	],
	keywords => [qw'
		web browser support compatibility usage matrix available feature
		html html5 css css3 svg javascript js dom mobile
		ie internet explorer firefox chrome safari webkit opera
	'],
	stylesheet => [qw'circus dark mono red light'],
	data => ['data/browser/support.inc.pl'],
});

say "<h1>Browser compatibility</h1>\n";

my $caniuse = do 'data/browser/support.inc.pl' or die $@ || $!;
$_->{verrelease} = {
	# mark last three (future) versions as unreleased, ensure current isn't
	map {
		$_->[-1] => 0, $_->[-2] => 0, $_->[-3] => 0,
		$_->[-4] => undef,
	} $_->{versions}
} for values %{ $caniuse->{agents} };

my %CSTATS = (
	'n'   => 'l1',
	'n d' => 'l2',
	'n x d' => 'l2 ex',
	'p d' => 'l2',
	'a d' => 'l2',
	'y'   => 'l5',
	'y x' => 'l5 ex',
	'a'   => 'l3',
	'a x' => 'l3 ex',
	'p j' => 'l2',
	'j'   => 'l2',
	'p'   => 'l2',
	'p p' => 'l2',
	'u'   => 'l0',
);
my %DSTATS = (
	u => 'unknown',
	n => 'unsupported',
	p => 'plugin required',
	j => 'javascript required',
	a => 'partial',
	y => 'supported',
	d => 'disabled by default',
	x => sub {
		join(' ',
			'requires prefix',
			map {"-$_-"}
			($caniuse->{agents}->{$_[0]}->{prefix_exceptions} // {})->{$_[1]}
			// $caniuse->{agents}->{$_[0]}->{prefix} // (),
		);
	},
);
my %PSTATS = (  # score percentage
	y => 1,  'y x' => .9,
	a => .5, 'a x' => .5, 'a d' => .1,
	j => .2, 'p j' => .2, 'n d' => .2, 'n x d' => .2,
	p => .2, 'p p' => .2, 'p d' => .1,
	n => 0,   u => 0,
);
my %CSTATUS = (
	unoff => 'l1', # unofficial
	wd    => 'l2', # draft
	cr    => 'l3', # candidate
	pr    => 'l3', # proposed
	rec   => 'l5', # recommendation
	ls    => 'l4', # whatwg
	ietf  => 'l0', # standard
	other => 'l0', # non-w3
);
my %versions;
if (my ($somerow) = values %{ $caniuse->{data} }) {
	while (my ($browser, $row) = each %{ $somerow->{stats} }) {
		$versions{$browser} = [ sort { paddedver($a) cmp paddedver($b) } keys %$row ];
	}
}

print <<'';
<p id="intro">Alternate rendition of Fyrd's <a href="http://caniuse.com/">when can I use...</a> page

my ($canihas, $usage);
my $minusage = $get{threshold} // .7;
given ($get{usage} // 'wm') {
	when (!$_) {
		# none
	}
	when (!m{ \A [a-z]\w+ (?:/\d[\d-]*\d)? \z }x) {
		printf "<p>Invalid browser usage data request: <em>%s</em>",
			'identifier must be alphanumeric name or <q>0</q>';
	}
	$canihas = do "data/browser/usage-$_.inc.pl" or do {
		printf "<p>Browser usage data not found: <em>%s</em>", $@ || $!;
		break;
	};
	$usage = $_;
	my $ref = $canihas->{-title} || 'unknown';
	$ref = sprintf '<a href="%s">%s</a>', $_, $ref
		for $canihas->{-site} || $canihas->{-source} || ();
	$ref .= " $_" for $canihas->{-date} || ();
	print "\nwith $ref browser usage statistics";
}

my @browsers;
if ($usage) { # first() does not work inside given >:(
	# adapt version usage to actual support data
	my %engineuse;  # prefix => usage sum
	for my $browser (keys %versions) {
		my $row = $canihas->{$browser} // {};
		my $verlist = $versions{$browser} or next;
		if ($minusage and sum(values %$row) < $minusage) {
			delete $versions{$browser};
			next;
		}
		my %supported = map { $_ => 1 } @$verlist;

		# cascade unknown versions
		$row->{$_} //= undef for @$verlist;  # ensure stable keys during iteration
		while (my ($version, $usage) = each %$row) {
			next if defined $supported{$version};
			my $next = first { paddedver($_) ge paddedver($version) } @$verlist
				or warn("No fallback found for $browser v$version; $usage% ignored"), next;
			$row->{$next} += $usage;
			$row->{$version} = 0;  # balance browser total
		}

		# build row list for each version
		if ($minusage) {
			my @vershown;  # $verlist replacement
			my ($rowusage, @verrow) = (0);  # replacement row tracking
			for (@$verlist) {
				push @verrow, $_;  # queue each version
				if (($rowusage += $row->{$_}) >= $minusage) {
					push @vershown, [@verrow];   # add row
					($rowusage, @verrow) = (0);  # reset row tracking
				}
			}
			push @vershown, \@verrow if @verrow;  # always add latest
			@$verlist = @vershown;
		}
		else {
			@$verlist = map { [$_] } @$verlist;
		}

		# reusable aggregates (grouped by prefix (engine) and browser)
		$engineuse{ $caniuse->{agents}->{$browser}->{prefix} } +=
		$row->{-total} = sum(values %$row);
	}

	# order browser columns by usage grouped by engine
	@browsers = sort {
		$engineuse{ $caniuse->{agents}->{$b}->{prefix} } <=>
		$engineuse{ $caniuse->{agents}->{$a}->{prefix} }
			||
		$canihas->{$b}->{-total} <=> $canihas->{$a}->{-total}
	} keys %versions;
}
else {
	# order browser columns by name grouped by engine
	@{$_} = map { [$_] } @{$_} for values %versions;
	@browsers = sort {
		$caniuse->{agents}->{$b}->{prefix} cmp
		$caniuse->{agents}->{$a}->{prefix}
			||
		$a cmp $b
	} keys %versions;
}
:>.
</p>

<:
$canihas ||= {
	map {
		$_ => +{
			map {
				my $zero = $#$_ - 2;  # baseline index
				($_->[$zero - 2] =>  .5), # past
				($_->[$zero - 1] => 10 ), # previous
				($_->[$zero + 2] =>  0 ), # future
				($_->[$zero + 1] =>  .5), # next
				($_->[$zero    ] => 30 ), # current
			} $caniuse->{agents}->{$_}->{versions}
		}
	} @browsers
}; # fallback hash based on release semantics
my $usagemax = (max(map { ref $_ eq 'HASH' && sum(values %$_) } values %$canihas) // 1) / 100;

my $usagepct = 1;  # score multiplier for 0..100 result
# normalise usage percentage to only include shown browsers
$usagepct = 100.01 / featurescore({  # yes for every possible version
	map { $_ => { map {$_ => 'y'} map { @{$_} } @{$versions{$_}} } } keys %versions
});

print '<table class="mapped">';
print '<col span="3">';  # should match first thead row
printf '<colgroup span="%d">', scalar @{ $versions{$_} } for @browsers;
say '</colgroup><col>';

my $header = join('',
	'<tr>',
	'<th colspan="3" rowspan="2">feature',
	(map {
		my $name = $caniuse->{agents}->{$_}->{browser};
		sprintf('<th colspan="%d" class="%s" title="%s">%s',
			scalar @{ $versions{$_} },
			join(' ', map {"b-a-$_"} grep {$_}
				$_, @{ $caniuse->{agents}->{$_} }{'prefix', 'type'},
			),
			join(' ',
				sprintf('%.1f%%', $canihas->{$_}->{-total} * $usagepct),
				$name,
			),
			do {
				length $name <= (3 * @{ $versions{$_} }) ? $name
					: $caniuse->{agents}->{$_}->{abbr};
			},
		)
	} @browsers),
	'<th rowspan="2">%',
);
print '<thead>', $header;
# preceding row without any colspan to work around gecko bug
print "\n<tr>";
for my $browser (@browsers) {
	for (@{ $versions{$browser} }) {
		my $lastver = $_->[-1];
		my $release = $caniuse->{agents}->{$browser}->{verrelease}->{$lastver};
		my $future = defined $release;
		printf('<td title="%s"%s>%s',
			join(' ',
				sprintf('%.1f%%', sum(@{ $canihas->{$browser} }{@$_}) * $usagepct),
				$future ? 'development' : (),
				'version ' . join(', ', @{$_}),
			),
			$future && ' class="ex"',
			showversions($lastver),
		);
	}
}
say '</thead>';
say '<tfoot>', $header;
{
	# prefix indicates browser family; count adjacent families
	my (@families, %familycount);
	for my $browser (@browsers) {
		my $family = $caniuse->{agents}->{$browser}->{prefix};
		push @families, $family unless $familycount{$family};
		$familycount{$family} += @{ $versions{$browser} };
	}

	print "\n", '<tr class="cat">';
	printf '<th colspan="%d">%s', $familycount{$_}, $_ for @families;
}
say '</tfoot>';

sub featurescore {
	# relative amount of support for given feature
	my $rank = 0;
	if (my $row = shift) {
		if ($canihas) {
			while (my ($browser, $versions) = each %$row) {
				ref $versions eq 'HASH' or next;
				while (my ($version, $status) = each %$versions) {
					$status =~ s/\h\#\d+//g;
					$rank += ($canihas->{$browser}->{$version} || .001) * $PSTATS{$status};
				}
			}
			return $rank;
		}

		while (my ($browser, $vercols) = each %versions) {
			my $div = 0;  # multiplier exponent (decreased to lower value)
			my @vers = map { $row->{$browser}->{$_} } @$vercols;
			if (my $current = $caniuse->{agents}->{$browser}->{versions}->[-3]) {
				my @future;  # find upcoming releases (after current)
				for (reverse @$vercols) {
					last if $_ eq $current;
					push @future, pop @vers;
					$_ eq 'u' and $_ = $vers[-1] for $future[-1];  # inherit latest value if unknown
				}
				splice @vers, -1, 0, @future;  # move ahead to decrease precedence
			}
			$rank += $PSTATS{$_} * 2**($div--) for reverse @vers;
		}
	}
	return $rank;
}

sub formatnotes {
	my @html = @_;
	for (@html) {
		s/\r\n?/\n/g;  # windows returns
		s/\h* $//gmx;  # trailing whitespace
		s/(?<= [^.\n]) $/./gmx;  # consistently end each line by a period
		Entity($_);
		s{  ` ([^`]*)  ` }{<code>$1</code>}gx;
		s{ \[ ([^]]*) \] \( ([^)]*) \) }{<a href="$2">$1</a>}gx;
	}
	return @html;
}

sub saytitlecol {
	my ($id) = @_;
	my $row = $caniuse->{data}->{$id};

	for ($row->{categories}) {
		my $cell = $_ ? lc $_->[0] : '-';
		$cell =~ s/ api$//;  # trim unessential fluff in 'js api'
		printf '<th title="%s">%s', join(' + ', @$_), $cell;
	}

	print '<td>', map {
		sprintf('<a href="%s" onclick="%s">%s</a>',
			"#$id",
			sprintf("try { %s; return false } catch(err) { return true }",
				"document.getElementById('$id').classList.toggle('target')",
			),
			Entity($_),
		);
	} $row->{title};
	print '<div class=aside>';
	print "<p>$_</p>"
		for formatnotes($row->{description}, $row->{notes} || ());
	if (my %notes = %{ $row->{notes_by_num} }) {
		say '<p>Browser-specific notes:';
		say "<br>#$_: ", formatnotes($notes{$_}) for sort keys %notes;
		say '</p>';
	}
	printf 'Resources: %s.', join(', ', map {
		sprintf '<a href="%s">%s</a>', EscapeHTML($_->{url}), EscapeHTML($_->{title})
	} @$_) for grep { @$_ } $row->{links} // ();
	printf '<br>Parent feature: %s.', join(', ', map {
		sprintf '<a href="%s">%s</a>', EscapeHTML("#$_"), $caniuse->{data}->{$_}->{title}
	} $_) for $row->{parent} || ();
	print '</div>';
}

sub saystatuscol {
	my ($id) = @_;
	my $row = $caniuse->{data}->{$id};

	for ($row->{status}) {
		my $cell = $_ // '-';
		$cell = sprintf '<a href="%s">%s</a>', $_, $cell for $row->{spec} // ();
		printf '<td title="%s" class="l %s">%s',
			$caniuse->{statuses}->{$_}, $CSTATUS{$_} // '', $cell;
	}
}

sub saybrowsercols {
	my ($id, $browser) = @_;
	my $feature = $caniuse->{data}->{$id};
	my $data = $feature->{stats}->{$browser};
	if (ref $data eq 'ARRAY') {
		# special case for unsupported
		my $release = $caniuse->{agents}->{$browser}->{verrelease};
		$data = {
			map { $_ => defined $release->{$_} ? 'u' : 'n' } keys %$release
		};
	}

	my ($prev, @span);
	for my $ver (@{ $versions{$browser} }, undef) {
		my $compare = (
			!defined $ver ? undef :      # last column if nameless
			ref $data ne 'HASH' ? '' :   # unclassified if no support hash
			$data->{ $ver->[-1] } // $prev  # known or inherit from predecessor
			// (grep { defined } @{$data}{ map { $_->[0] } @{ $versions{$browser} } })[0]
			   ~~ 'n' && 'n'             # first known version is unsupported
			|| 'u'                       # unsure
		);
		unless (!defined $prev or $prev ~~ $compare) {
			my $usage = sum(@{ $canihas->{$browser} }{ map { @{$_} } @span });

			# strip #\d note references from support class
			my @notes;
			push @notes, $feature->{notes_by_num}->{$1}
				while $prev =~ s/\h \# (\d+) \b//x;

			# prepare version hover details
			my $title = sprintf('%.1f%% %s', $usage * $usagepct, join(', ',
				map { ref $_ eq 'CODE' ? $_->($browser, $span[0]->[0]) : $_ }
				map { $DSTATS{$_} // () }
				map { split / /, $_ }
				$prev
			));
			$title .= "\n".EscapeHTML($_) for @notes;

			printf('<td class="%s" colspan="%d" title="%s">%s',
				join(' ',
					X => $CSTATS{$prev},
					!$usage ? ('p0') : ('p',
						sprintf('p%01d', $usage * ($usagepct - .0001) / 10),
						sprintf('p%02d', $usage * ($usagepct - .0001)),
					),
					sprintf('pp%02d', $usage / $usagemax),
				),
				scalar @span,
				$title,
				showversions($span[0]->[0], @span > 1 ? ($span[-1]->[-1]) : ()),
			);
			undef $prev;
			@span = ();
		}
		push @span, $ver && [ grep { $data->{ $_ } eq $data->{ $ver->[-1] } } @{$ver} ];
		$prev = $compare;
	}
}

sub sayusagecol {
	my ($id) = @_;
	print '<td>', int featurescore($caniuse->{data}->{$id}->{stats}) * $usagepct;
}

say '<tbody>';
for my $id (sort {
	    featurescore($caniuse->{data}->{$b}->{stats})
	<=> featurescore($caniuse->{data}->{$a}->{stats})
} keys %{ $caniuse->{data} }) {
	$caniuse->{data}->{$id}->{stats} or next;  # skip metadata [summary]
	printf '<tr id="%s">', $id;
	saytitlecol($id);
	saystatuscol($id);
	saybrowsercols($id, $_) for @browsers;
	sayusagecol($id);
	say '</tr>';
}
say '</tbody>';
say '</table>';

sub paddedver {
	# normalised version number comparable as string (cmp)
	shift =~ /(?:.*-|^)(\d*)(.*)/;
	# matched (major)(.minor) of last value in range (a-B)
	return sprintf('%02d', $1 || 99) . $2;
}

sub showversions {
	my @span = ($_[0], @_>1 ? $_[-1] : ());
	s/-.*// for $span[0];
	for (@span) {
		s/^\./0./;
		s/x$/.*/;
		s/.*-//;
	}
	return join('‒', @span);
}

:>
<hr>

<div class="legend">
	<table class="glyphs"><tr>
	<td class="X l5">supported
	<td class="X l3">partial
	<td class="X l2">optional
	<td class="X l1">missing
	<td class="X l0">unknown
	<td class="X ex">prefixed
	</table>

	<p><: if ($usage) { :>
		Usage percentage:
		<span class="  p0">0</span> -
		<span class="p p0 p00">.01</span> -
		<span class="p p0 p05">1-9</span> -
		<span class="p p1">10</span> -
		<span class="p p2">20</span> -
		<span class="p p5">majority</span>
<: } else { :>
		<table class="glyphs"><tr>
			<td class="p p1">previous version</td>
			<td class="p p3">current</td>
			<td class="p p0 p00">upcoming (within months)</td>
			<td class="  p0">future (within a year)</td>
		</table>
<: } :>	</p>

	<div class="right">
		<ul class="legend legend-set">
		<li>default <strong>style</strong> is
			<:= defined $get{style} && 'set to ' :><em><:= $style :></em>
		<li><strong>usage</strong> source is
			<:= !defined $get{usage} && 'default ' :><:= defined $usage ? "<em>$usage</em>" : 'not included (<em>0</em>)' :>
		<li>usage <strong>threshold</strong> is
			<:= defined $get{threshold} && 'changed to ' :><em><:= $minusage :>%</em>
		</ul>
	</div>
</div>

<script type="text/javascript" src="/searchlocal.js"></script>
<script type="text/javascript"> prependsearch(document.getElementById('intro')) </script>