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