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