style: common cat class for category table headers
[sheet.git] / browser.plp
1 <(common.inc.plp)><:
2 use 5.010;
3 use utf8;
4 use List::Util qw(sum max first);
5
6 Html({
7         title => 'browser compatibility cheat sheet',
8         version => 'v1.0',
9         description => [
10                 "Compatibility table of new web features (HTML5, CSS3, SVG, Javascript)",
11                 "comparing support and usage share for all popular browser versions.",
12         ],
13         keywords => [qw'
14                 web browser support compatibility usage available feature
15                 html html5 css css3 svg javascript js dom mobile
16                 ie internet explorer firefox chrome safari webkit opera
17         '],
18         stylesheet => [qw'circus dark mono red light'],
19         data => ['browser-support.inc.pl'],
20 });
21
22 say "<h1>Browser compatibility</h1>\n";
23
24 my $caniuse = do 'browser-support.inc.pl' or die $! || $@;
25 $_->{verrelease} = {
26         # mark last three (future) versions as unreleased, ensure current isn't
27         map {
28                 $_->[-1] => 0, $_->[-2] => 0, $_->[-3] => 0,
29                 $_->[-4] => undef,
30         } $_->{versions}
31 } for values %{ $caniuse->{agents} };
32
33 my %CSTATS = (
34         'n'   => 'l1',
35         'n d' => 'l2',
36         'n x d' => 'l2 ex',
37         'p d' => 'l2',
38         'a d' => 'l2',
39         'y'   => 'l5',
40         'y x' => 'l5 ex',
41         'a'   => 'l3',
42         'a x' => 'l3 ex',
43         'p j' => 'l2',
44         'j'   => 'l2',
45         'p'   => 'l2',
46         'p p' => 'l2',
47         'u'   => 'l0',
48 );
49 my %DSTATS = (
50         u => 'unknown',
51         n => 'unsupported',
52         p => 'plugin required',
53         j => 'javascript required',
54         a => 'partial',
55         y => 'supported',
56         d => 'disabled by default',
57         x => sub {
58                 join(' ',
59                         'requires prefix',
60                         (map "-$_-", $caniuse->{agents}->{$_[0]}->{prefix} // ()),
61                 );
62         },
63 );
64 my %CSTATUS = (
65         unoff => 'l1', # unofficial
66         wd    => 'l3', # draft
67         cr    => 'l4', # candidate
68         pr    => 'l4', # proposed
69         rec   => 'l5', # recommendation
70         other => 'l2', # non-w3
71         ietf  => 'l5', # standard
72 );
73 my %versions;
74 if (my ($somerow) = values %{ $caniuse->{data} }) {
75         while (my ($browser, $row) = each %{ $somerow->{stats} }) {
76                 $versions{$browser} = [ sort { paddedver($a) cmp paddedver($b) } keys %$row ];
77         }
78 }
79
80 print <<'';
81 <p id="intro">Alternate rendition of Fyrd's <a href="http://caniuse.com/">when can I use...</a> page
82
83 my ($canihas, $usage);
84 my $minusage = $get{threshold} // .5;
85 given ($get{usage} // 'wm') {
86         when (!$_) {
87                 # none
88         }
89         when (!/^[a-z][\w-]+$/) {
90                 printf "<p>Invalid browser usage data request: <em>%s</em>",
91                         'identifier must be alphanumeric name or <q>0</q>';
92         }
93         $canihas = do "browser-usage-$_.inc.pl" or do {
94                 printf "<p>Browser usage data not found: <em>%s</em>", $! || $@;
95                 break;
96         };
97         $usage = $_;
98         my $ref = $canihas->{-title} || 'unknown';
99         $ref = sprintf '<a href="%s">%s</a>', $_, $ref
100                 for $canihas->{-site} || $canihas->{-source} || ();
101         $ref .= " $_" for $canihas->{-date} || ();
102         print "\nwith $ref browser usage statistics";
103 }
104
105 my @browsers;
106 if ($usage) { # first() does not work inside given >:(
107         # adapt version usage to actual support data
108         my %engineuse;  # prefix => usage sum
109         for my $browser (keys %versions) {
110                 my $row = $canihas->{$browser} // {};
111                 my $verlist = $versions{$browser} or next;
112                 if ($minusage and sum(values %$row) < $minusage) {
113                         delete $versions{$browser};
114                         next;
115                 }
116                 my %supported = map { $_ => 1 } @$verlist;
117
118                 # cascade unknown versions
119                 $row->{$_} //= undef for @$verlist;  # ensure stable keys during iteration
120                 while (my ($version, $usage) = each %$row) {
121                         next if defined $supported{$version};
122                         my $next = first { paddedver($_) ge paddedver($version) } @$verlist
123                                 or warn("No fallback found for $browser v$version; $usage% ignored"), next;
124                         $row->{$next} += $usage;
125                         $row->{$version} = 0;  # balance browser total
126                 }
127
128                 # build row list for each version
129                 if ($minusage) {
130                         my @vershown;  # $verlist replacement
131                         my ($rowusage, @verrow) = (0);  # replacement row tracking
132                         for (@$verlist) {
133                                 push @verrow, $_;  # queue each version
134                                 if (($rowusage += $row->{$_}) >= $minusage) {
135                                         push @vershown, [@verrow];   # add row
136                                         ($rowusage, @verrow) = (0);  # reset row tracking
137                                 }
138                         }
139                         push @vershown, \@verrow if @verrow;  # always add latest
140                         @$verlist = @vershown;
141                 }
142                 else {
143                         @$verlist = map { [$_] } @$verlist;
144                 }
145
146                 # reusable aggregates (grouped by prefix (engine) and browser)
147                 $engineuse{ $caniuse->{agents}->{$browser}->{prefix} } +=
148                 $row->{-total} = sum(values %$row);
149         }
150
151         # order browser columns by usage grouped by engine
152         @browsers = sort {
153                 $engineuse{ $caniuse->{agents}->{$b}->{prefix} } <=>
154                 $engineuse{ $caniuse->{agents}->{$a}->{prefix} }
155                         ||
156                 $canihas->{$b}->{-total} <=> $canihas->{$a}->{-total}
157         } keys %versions;
158 }
159 else {
160         # order browser columns by name grouped by engine
161         @browsers = sort {
162                 $caniuse->{agents}->{$b}->{prefix} cmp
163                 $caniuse->{agents}->{$a}->{prefix}
164                         ||
165                 $a cmp $b
166         } keys %versions;
167 }
168 :>.
169 </p>
170
171 <:
172 $canihas ||= {
173         map {
174                 $_ => +{
175                         map {
176                                 my $zero = $#$_ - 2;  # baseline index
177                                 ($_->[$zero - 2] =>  .5), # past
178                                 ($_->[$zero - 1] => 10 ), # previous
179                                 ($_->[$zero + 2] =>  0 ), # future
180                                 ($_->[$zero + 1] =>  .5), # next
181                                 ($_->[$zero    ] => 30 ), # current
182                         } $caniuse->{agents}->{$_}->{versions}
183                 }
184         } @browsers
185 }; # fallback hash based on release semantics
186 my $usagemax = (max(map { ref $_ eq 'HASH' && sum(values %$_) } values %$canihas) // 1) / 100;
187
188 my $usagepct = 1;  # score multiplier for 0..100 result
189 # normalise usage percentage to only include shown browsers
190 $usagepct = 100.01 / featurescore({  # yes for every possible version
191         map { $_ => { map {$_ => 'y'} map { @{$_} } @{$versions{$_}} } } keys %versions
192 });
193
194 print '<table class="mapped">';
195 print '<col span="3">';  # should match first thead row
196 printf '<colgroup span="%d">', scalar @{ $versions{$_} } for @browsers;
197 say '</colgroup><col>';
198
199 my $header = join('',
200         '<tr>',
201         '<th colspan="3">feature',
202         (map {
203                 my $name = $caniuse->{agents}->{$_}->{browser};
204                 sprintf('<th colspan="%d" class="%s" title="%s">%s',
205                         scalar @{ $versions{$_} },
206                         join(' ', map {"b-a-$_"} grep {$_}
207                                 $_, @{ $caniuse->{agents}->{$_} }{'prefix', 'type'},
208                         ),
209                         join(' ',
210                                 sprintf('%.1f%%', $canihas->{$_}->{-total} * $usagepct),
211                                 $name,
212                         ),
213                         do {
214                                 length $name < 3 + @{ $versions{$_} }*2 ? $name
215                                         : $caniuse->{agents}->{$_}->{abbr};
216                         },
217                 )
218         } @browsers),
219         '<th>%',
220 );
221 print '<thead>', $header;
222 # preceding row without any colspan to work around gecko bug
223 print "\n<tr>";
224 print '<td>' x 3;
225 for my $browser (@browsers) {
226         for (@{ $versions{$browser} }) {
227                 my $lastver = $_->[-1];
228                 my $release = $caniuse->{agents}->{$browser}->{verrelease}->{$lastver};
229                 my $future = defined $release;
230                 printf('<td title="%s"%s>%s',
231                         join(' ',
232                                 sprintf('%.1f%%', sum(@{ $canihas->{$browser} }{@$_}) * $usagepct),
233                                 $future ? 'development' : (),
234                                 'version ' . join(', ', @{$_}),
235                         ),
236                         $future && ' class="ex"',
237                         showversions($lastver),
238                 );
239         }
240 }
241 print '<td>' x 1;
242 say '</thead>';
243 say '<tfoot>', $header, '</tfoot>';
244
245 sub featurescore {
246         # relative amount of support for given feature
247         state $statspts = { y=>1, 'y x'=>1, a=>.5, 'a x'=>.5, j=>.2, 'p j'=>.2, 'p p'=>.2, p=>.1 };
248         my $rank = 0;
249         if (my $row = shift) {
250                 if ($canihas) {
251                         while (my ($browser, $versions) = each %$row) {
252                                 ref $versions eq 'HASH' or next;
253                                 while (my ($version, $_) = each %$versions) {
254                                         $rank += ($canihas->{$browser}->{$version} || .001) * $statspts->{$_};
255                                 }
256                         }
257                         return $rank;
258                 }
259
260                 while (my ($browser, $vercols) = each %versions) {
261                         my $div = 0;  # multiplier exponent (decreased to lower value)
262                         my @vers = map { $row->{$browser}->{$_} } @$vercols;
263                         if (my $current = $caniuse->{agents}->{$browser}->{versions}->[-3]) {
264                                 my @future;  # find upcoming releases (after current)
265                                 for (reverse @$vercols) {
266                                         last if $_ eq $current;
267                                         push @future, pop @vers;
268                                         $_ eq 'u' and $_ = $vers[-1] for $future[-1];  # inherit latest value if unknown
269                                 }
270                                 splice @vers, -1, 0, @future;  # move ahead to decrease precedence
271                         }
272                         $rank += $statspts->{$_} * 2**($div--) for reverse @vers;
273                 }
274         }
275         return $rank;
276 }
277
278 sub saytitlecol {
279         my ($id) = @_;
280         my $row = $caniuse->{data}->{$id};
281
282         for ($row->{categories}) {
283                 my $cell = $_ ? lc $_->[0] : '-';
284                 $cell =~ s/ api$//;  # trim unessential fluff in 'js api'
285                 printf '<th title="%s">%s', join(' + ', @$_), $cell;
286         }
287
288         print '<td>', map {
289                 sprintf('<a href="%s" onclick="%s">%s</a>',
290                         "#$id",
291                         sprintf("try { %s; return false } catch(err) { return true }",
292                                 "document.getElementById('$id').classList.toggle('target')",
293                         ),
294                         Entity($_),
295                 );
296         } $row->{title};
297         print '<div class=aside>';
298         s/\.?$/./, print "<p>$_</p>" for map { ref $_ ? @$_ : $_ || () }
299                 Entity($row->{description}),
300                 map { s/\s*\n/\n<br>/g; $_ } $row->{notes};
301         printf 'Resources: %s.', join(', ', map {
302                 sprintf '<a href="%s">%s</a>', EscapeHTML($_->{url}), $_->{title}
303         } @$_) for grep { @$_ } $row->{links} // ();
304         printf '<br>Parent feature: %s.', join(', ', map {
305                 sprintf '<a href="%s">%s</a>', EscapeHTML("#$_"), $caniuse->{data}->{$_}->{title}
306         } $_) for $row->{parent} || ();
307         print '</div>';
308 }
309
310 sub saystatuscol {
311         my ($id) = @_;
312         my $row = $caniuse->{data}->{$id};
313
314         for ($row->{status}) {
315                 my $cell = $_ // '-';
316                 $cell = sprintf '<a href="%s">%s</a>', $_, $cell for $row->{spec} // ();
317                 printf '<td title="%s" class="l %s">%s',
318                         $caniuse->{statuses}->{$_}, $CSTATUS{$_} // '', $cell;
319         }
320 }
321
322 sub saybrowsercols {
323         my ($id, $browser) = @_;
324         my $feature = $caniuse->{data}->{$id};
325         my $data = $feature->{stats}->{$browser};
326         if (ref $data eq 'ARRAY') {
327                 # special case for unsupported
328                 my $release = $caniuse->{agents}->{$browser}->{verrelease};
329                 $data = {
330                         map { $_ => defined $release->{$_} ? 'u' : 'n' } keys %$release
331                 };
332         }
333
334         my ($prev, @span);
335         for my $ver (@{ $versions{$browser} }, undef) {
336                 my $compare = (
337                         !defined $ver ? undef :      # last column if nameless
338                         ref $data ne 'HASH' ? '' :   # unclassified if no support hash
339                         $data->{ $ver->[-1] } // $prev  # known or inherit from predecessor
340                         // (grep { defined } @{$data}{ map { $_->[0] } @{ $versions{$browser} } })[0]
341                            ~~ 'n' && 'n'             # first known version is unsupported
342                         || 'u'                       # unsure
343                 );
344                 unless (!defined $prev or $prev ~~ $compare) {
345                         my $usage = sum(@{ $canihas->{$browser} }{ map { @{$_} } @span });
346
347                         # strip #\d note references from support class
348                         my @notes;
349                         push @notes, $feature->{notes_by_num}->{$1}
350                                 while $prev =~ s/\h \# (\d+) \b//x;
351
352                         # prepare version hover details
353                         my $title = sprintf('%.1f%% %s', $usage * $usagepct, join(', ',
354                                 map { ref $_ eq 'CODE' ? $_->($browser) : $_ }
355                                 map { $DSTATS{$_} // () }
356                                 map { split / /, $_ }
357                                 $prev
358                         ));
359                         $title .= "\n".EscapeHTML($_) for @notes;
360
361                         printf('<td class="%s" colspan="%d" title="%s">%s',
362                                 join(' ',
363                                         X => $CSTATS{$prev},
364                                         !$usage ? ('p0') : ('p',
365                                                 sprintf('p%01d', $usage * ($usagepct - .0001) / 10),
366                                                 sprintf('p%02d', $usage * ($usagepct - .0001)),
367                                         ),
368                                         sprintf('pp%02d', $usage / $usagemax),
369                                 ),
370                                 scalar @span,
371                                 $title,
372                                 showversions($span[0]->[0], @span > 1 ? ($span[-1]->[-1]) : ()),
373                         );
374                         undef $prev;
375                         @span = ();
376                 }
377                 push @span, $ver && [ grep { $data->{ $_ } eq $data->{ $ver->[-1] } } @{$ver} ];
378                 $prev = $compare;
379         }
380 }
381
382 sub sayusagecol {
383         my ($id) = @_;
384         print '<td>', int featurescore($caniuse->{data}->{$id}->{stats}) * $usagepct;
385 }
386
387 say '<tbody>';
388 for my $id (sort {
389             featurescore($caniuse->{data}->{$b}->{stats})
390         <=> featurescore($caniuse->{data}->{$a}->{stats})
391 } keys %{ $caniuse->{data} }) {
392         $caniuse->{data}->{$id}->{stats} or next;  # skip metadata [summary]
393         printf '<tr id="%s">', $id;
394         saytitlecol($id);
395         saystatuscol($id);
396         saybrowsercols($id, $_) for @browsers;
397         sayusagecol($id);
398         say '</tr>';
399 }
400 say '</tbody>';
401 say '</table>';
402
403 sub paddedver {
404         # normalised version number comparable as string (cmp)
405         shift =~ /(?:.*-|^)(\d*)(.*)/;
406         # matched (major)(.minor) of last value in range (a-B)
407         return sprintf('%02d', $1 || 99) . $2;
408 }
409
410 sub showversions {
411         my @span = ($_[0], @_>1 ? $_[-1] : ());
412         s/-.*// for $span[0];
413         for (@span) {
414                 s/^\./0./;
415                 s/x$/.*/;
416                 s/.*-//;
417         }
418         return join('‒', @span);
419 }
420
421 :>
422 <hr>
423
424 <div class="legend">
425         <table class="glyphs"><tr>
426         <td class="X l5">supported
427         <td class="X l3">partial
428         <td class="X l2">optional
429         <td class="X l1">missing
430         <td class="X l0">unknown
431         <td class="X ex">prefixed
432         </table>
433
434         <p><: if ($usage) { :>
435                 Usage percentage:
436                 <span class="  p0">0</span> -
437                 <span class="p p0 p00">.01</span> -
438                 <span class="p p0 p05">1-9</span> -
439                 <span class="p p1">10</span> -
440                 <span class="p p2">20</span> -
441                 <span class="p p5">majority</span>
442 <: } else { :>
443                 <table class="glyphs"><tr>
444                         <td class="p p1">previous version</td>
445                         <td class="p p3">current</td>
446                         <td class="p p0 p00">upcoming (within months)</td>
447                         <td class="  p0">future (within a year)</td>
448                 </table>
449 <: } :> </p>
450
451         <div class="right">
452                 <ul class="legend legend-set">
453                 <li>default <strong>style</strong> is
454                         <:= defined $get{style} && 'set to ' :><em><:= $style :></em>
455                 <li><strong>usage</strong> source is
456                         <:= !defined $get{usage} && 'default ' :><:= defined $usage ? "<em>$usage</em>" : 'not included (<em>0</em>)' :>
457                 <li>usage <strong>threshold</strong> is
458                         <:= defined $get{threshold} && 'changed to ' :><em><:= $minusage :>%</em>
459                 </ul>
460         </div>
461 </div>
462
463 <script type="text/javascript" src="/searchlocal.js"></script>
464 <script type="text/javascript"> prependsearch(document.getElementById('intro')) </script>
465