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