This repository has been archived by the owner on Jun 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathCompat.ejs
713 lines (618 loc) · 21 KB
/
Compat.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
<%
/*
Retrieves MDN compat data for a given feature
Parameters
$0 – A query string indicating for which feature to retrieve compat data for.
$1 – A depth setting indicating how deep sub features should be added to the table
(flattened, default: 1, first level of sub feature data will be included).
Example calls
{{compat("webextensions.api.alarms")}}
{{compat("webextensions.api.alarms.Alarm")}}
{{compat("webextensions.manifest")}}
{{compat("webextensions.manifest.applications")}}
{{compat("css.properties.background-attachment")}}
{{compat("css.selectors.any-link")}}
{{compat("css.at-rules.font-face")}}
{{compat("http.headers.Cache-Control")}}
{{compat("http.status.404")}}
{{compat("http.method.CONNECT")}}
{{compat("api.WebGL2RenderingContext")}}
{{compat("api.WebGL2RenderingContext.beginQuery")}}
{{compat("html.elements.input")}}
{{compat("html.elements.link", 2)}}
{{compat("webextensions.api.alarms", 3)}}
*/
const bcd = require('@mdn/browser-compat-data');
var query = $0;
var depth = $1 || 1;
var output = '';
var category = query.split(".")[0];
var legendItems = new Set(); // entries will be unique
var compatStrings = string.deserialize(await template('L10n:CompatTable'));
var localize = mdn.getLocalString;
var s_no_data_found = mdn.localString({
'en-US': `No compatibility data found. Please contribute data for "${query}" (depth: ${depth}) to the <a href="https://github.com/mdn/browser-compat-data">MDN compatibility data repository</a>.`
});
const browsers = {
"desktop": ['chrome', 'edge', 'firefox', 'ie', 'opera', 'safari'],
"mobile": ['webview_android', 'chrome_android', 'firefox_android', 'opera_android', 'safari_ios', 'samsunginternet_android'],
"server": ['nodejs'],
"webextensions-desktop": ['chrome', 'edge', 'firefox', 'opera', 'safari'],
"webextensions-mobile": ['firefox_android']
};
let bcCategory = 'web';
let platforms = ['desktop', 'mobile'];
let displayBrowsers = [...browsers["desktop"], ...browsers["mobile"]];
if (category === 'javascript') {
bcCategory = 'js';
displayBrowsers.push(...browsers["server"]);
platforms.push('server');
}
if (category === 'webextensions') {
bcCategory = 'ext';
displayBrowsers = [...browsers["webextensions-desktop"], ...browsers["webextensions-mobile"]];
platforms = ['webextensions-desktop', 'webextensions-mobile'];
}
/**
* Writes the text label for each cell, and relevant icon/platform class
*/
function writeLabel(iconSlug, type, replacer) {
let iconTitle = localize(compatStrings, 'bc_icon_name_' + iconSlug).replace('$1$', replacer);
let output = '';
if (type === 'platform') {
output += `<span>${iconTitle}</span>`;
} else {
output += `<span class="bc-head-txt-label bc-head-icon-${iconSlug}">${iconTitle}</span>`;
}
return output;
}
function writeIcon(iconSlug, replacer, isLegend) {
let iconName = localize(compatStrings, 'bc_icon_name_' + iconSlug).replace('$1$', replacer);
let iconTitle = localize(compatStrings, 'bc_icon_title_' + iconSlug).replace('$1$', replacer);
if (isLegend) {
iconName = localize(compatStrings, 'legend_' + iconSlug);
iconTitle = iconName;
}
// there is no iconTitle, fall back to iconName
if (iconTitle === 'bc_icon_title_' + iconSlug) {
iconTitle = iconName;
}
let output = '';
output += `<abbr class="only-icon" title="${iconTitle}">`;
output += `<span>${iconName}</span>`;
output += `<i aria-hidden="true" class="ic-${iconSlug}"></i>`;
output += '</abbr>';
return output;
}
function writeFeatureName(row, feature) {
let desc = '';
let featureIcons = '';
let experimentalIcon = '';
let deprecatedIcon = '';
let nonStandardIcon = '';
let label = Object.keys(row)[0];
if (feature.description) {
// Un-nested features need no prefixing
if (label.indexOf('.') === -1) {
desc += feature.description;
// otherwise add a prefix so that we know where this belongs to (e.g. "parse: ISO 8601 format")
} else {
desc += `<code>${label.slice(0, label.lastIndexOf('.'))}</code>: ${feature.description}`;
}
} else {
desc += `<code>${Object.keys(row)[0]}</code>`;
}
// Add relative MDN url, but don't link to the current page
if (feature.mdn_url) {
let href = feature.mdn_url.replace('https://developer.mozilla.org', '');
if (feature.mdn_url.includes('#') && href.split('#')[0] === '/docs/' + env.slug) {
href = feature.mdn_url.substring(feature.mdn_url.indexOf('#'))
}
if (href !== '/docs/' + env.slug) {
if (href[0] === '/') href = '/' + env.locale + href;
desc = `<a href="${href}">${desc}</a>`;
}
}
if (feature.hasOwnProperty('status')) {
if (feature.status.experimental === true) {
experimentalIcon = writeIcon('experimental');
legendItems.add('experimental');
}
if (feature.status.deprecated === true) {
deprecatedIcon = writeIcon('deprecated');
legendItems.add('deprecated');
}
if (feature.status.standard_track === false) {
nonStandardIcon = writeIcon('non-standard');
legendItems.add('non-standard');
}
if (experimentalIcon || deprecatedIcon || nonStandardIcon) {
featureIcons += ' <div class="bc-icons">';
featureIcons += experimentalIcon;
featureIcons += deprecatedIcon;
featureIcons += nonStandardIcon;
featureIcons += '</div>';
}
}
return desc + featureIcons;
}
/*
Returns the string to appear in the table cell, like "Yes", "No" or "?", "Partial"
or the version number
`added` and `removed` are either null, true, false or a string containing a version number
`partial` is either null, true, or false indicating partial_implementation
*/
function getCellString(added, removed, partial) {
let output = '';
switch (added) {
case null:
output = `<abbr title="${localize(compatStrings, 'supportsShort_unknown_title')}">
${localize(compatStrings, 'supportsShort_unknown')}
</abbr>`;
break;
case true:
output = `<abbr title="${localize(compatStrings, 'supportsLong_yes')}"
class="bc-level-yes only-icon">
<span>${localize(compatStrings, 'supportsLong_yes')}</span>
</abbr>
${localize(compatStrings, 'supportsShort_yes')}`;
break;
case false:
output = `<abbr title="${localize(compatStrings, 'supportsLong_no')}"
class="bc-level-no only-icon">
<span>${localize(compatStrings, 'supportsLong_no')}</span>
</abbr>
${localize(compatStrings, 'supportsShort_no')}`;
break;
default:
output = `<abbr title="${localize(compatStrings, 'supportsLong_yes')}"
class="bc-level-yes only-icon">
<span>${localize(compatStrings, 'supportsLong_yes')}</span>
</abbr>
${added}`;
}
if (removed) {
output = `<abbr title="${localize(compatStrings, 'supportsLong_no')}"
class="bc-level-no only-icon">
<span>${localize(compatStrings, 'supportsLong_no')}</span>
</abbr>`;
// We don't know when supported started
if (typeof(added) === 'boolean' && added) {
output += '?'
} else { // We know when
output += added
}
output += ' — ';
// We don't know when supported ended
if (typeof(removed) === 'boolean' && removed) {
output += '?'
} else { // We know when
output += removed;
}
// removed wins over partial
} else if (partial) {
output = `<abbr title="${localize(compatStrings, 'supportsLong_partial')}"
class="bc-level-partial only-icon">
<span>${localize(compatStrings, 'supportsLong_partial')}</span>
</abbr>`;
// Display "Partial" instead of "Yes", "No", or "?" if we have no version string
if (typeof(added) !== 'string') {
output += localize(compatStrings, 'supportsShort_partial');
} else {
output += added;
}
}
return output;
}
/*
Given the support information for a browser, this returns
a CSS class to apply to the table cell.
`supportData` is a (or an array of) support_statement(s)
*/
function getSupportClass(supportInfo) {
let cssClass = 'unknown';
if (Array.isArray(supportInfo)) {
// the first entry should be the most relevant/recent and will be treated as "the truth"
checkSupport(supportInfo[0].version_added,
supportInfo[0].version_removed,
supportInfo[0].partial_implementation);
} else if (supportInfo) { // there is just one support statement
checkSupport(supportInfo.version_added,
supportInfo.version_removed,
supportInfo.partial_implementation);
} else { // this browser has no info, it's unknown
return 'unknown';
}
function checkSupport(added, removed, partial) {
if (added === null) {
cssClass = 'unknown';
} else if (added) {
cssClass = 'yes';
if (removed) {
cssClass = 'no';
}
} else {
cssClass = 'no';
}
if (partial && !removed) {
cssClass = 'partial';
}
}
return cssClass;
}
/*
Generate the note for a browser flag or preference
First checks version_added and version_removed to create a string indicating when
a preference setting is present. Then creates a (browser specific) string
for either a preference flag or a compile flag.
// TODO Need to localize this
`supportData` is a support_statement
`browserId` is a compat_block browser ID
*/
function writeFlagsNote(supportData, browserId) {
let output = '';
const firefoxPrefs = ' To change preferences in Firefox, visit about:config.';
const chromePrefs = ' To change preferences in Chrome, visit chrome://flags.';
if (typeof(supportData.version_added) === 'string') {
output = `From version ${supportData.version_added}`;
}
if (typeof(supportData.version_removed) === 'string') {
if (output) {
output += ' ';
output += `until version ${supportData.version_removed} (exclusive)`;
} else {
output = `Until version ${supportData.version_removed} (exclusive)`;
}
}
let start = 'This';
if (output) {
output += ':';
start = ' this';
}
start += ' feature is behind the ';
let flagsText = '';
let settings = '';
for (i = 0; i < supportData.flags.length; i++) {
let flag = supportData.flags[i];
let nameString = `<code>${flag.name}</code>`;
// value_to_set is optional
let valueToSet = '';
if (flag.value_to_set) {
valueToSet = ` (needs to be set to <code>${flag.value_to_set}</code>)`;
}
let typeString = '';
if (flag.type === 'preference') {
switch (browserId) {
case 'firefox':
case 'firefox_android':
settings = firefoxPrefs;
break;
case 'chrome':
case 'chrome_android':
settings = chromePrefs;
break;
}
typeString = ` preference${valueToSet}`;
}
if (flag.type === 'compile_flag') {
typeString = ` compile flag${valueToSet}`;
}
if (flag.type === 'runtime_flag') {
typeString = ` runtime flag${valueToSet}`;
}
flagsText += nameString + typeString;
if (i != supportData.flags.length - 1) {
flagsText += ' and the ';
} else {
flagsText += '.';
}
}
output += start + flagsText + settings;
return output;
}
/*
Generates icons for the main cell
`supportData` is a support_statement
*/
function writeCellIcons(support) {
let output = '<div class="bc-icons">';
if (Array.isArray(support)) {
// the first entry should be the most relevant/recent and will be used for the main cell
support = support[0];
}
if (support.prefix) {
output += writeIcon('prefix', support.prefix) + ' ';
legendItems.add('prefix');
}
if (support.notes) {
output += writeIcon('footnote') + ' ';
legendItems.add('footnote');
}
if (support.alternative_name) {
output += writeIcon('altname', support.alternative_name) + ' ';
legendItems.add('altname');
}
if (support.flags) {
output += writeIcon('disabled') + ' ';
legendItems.add('disabled');
}
output += '</div>';
return output;
}
/*
Create notes section
`supportData` is a support_statement
`browserId` is a compat_block browser ID
*/
function writeNotes(support, browserId) {
let output = '<section class="bc-history" aria-hidden="true"><dl>';
if (Array.isArray(support)) {
for (supportItem of support) {
writeSingleNote(supportItem, browserId);
}
} else {
writeSingleNote(support, browserId);
}
function writeSingleNote(support) {
let notes = [];
output += `<dt class="bc-supports-${getSupportClass(support)} bc-supports">`;
output += getCellString(support.version_added,
support.version_removed,
support.partial_implementation);
output += writeCellIcons(support);
output += '</dt>';
if (support.prefix) {
notes.push({
icon: writeIcon('prefix', support.prefix),
text: localize(compatStrings, 'bc_icon_title_prefix').replace('$1$', support.prefix)
});
}
if (support.notes) {
if (Array.isArray(support.notes)) {
for (let note of support.notes) {
notes.push({
icon: writeIcon('footnote'),
text: note
});
}
} else {
notes.push({
icon: writeIcon('footnote'),
text: support.notes
});
}
}
if (support.alternative_name) {
notes.push({
icon: writeIcon('altname', support.alternative_name),
text: localize(compatStrings, 'bc_icon_title_altname').replace('$1$', support.alternative_name)
});
}
if (support.flags) {
notes.push({
icon: writeIcon('disabled'),
text: writeFlagsNote(support, browserId)
});
}
if (notes.length > 0) {
for (let note of notes) {
output += '<dd>';
output += note.icon;
output += ' ' + note.text;
output += '</dd>';
}
} else {
output += '<dd></dd>';
}
}
output += '</dl></section>';
return output;
}
/**
* Formats the `browserNameKey` for display in the UI
* @param {String} browserNameKey - The browser name
* @returns Correctly formatted browser name
*/
function getFormattedBrowserName(browserNameKey) {
let firstChar;
switch(browserNameKey) {
case 'chrome':
case 'edge':
case 'firefox':
case 'opera':
case 'safari':
firstChar = browserNameKey.charAt(0);
return browserNameKey.replace(firstChar, firstChar.toUpperCase());
case 'ie':
return browserNameKey.toUpperCase();
case 'webview_android':
return 'WebView Android';
case 'chrome_android':
return 'Chrome Android';
case 'firefox_android':
return 'Firefox Android';
case 'opera_android':
return 'Opera Android';
case 'safari_ios':
return 'Safari iOS';
case 'samsunginternet_android':
return 'Samsung Internet Android';
default:
return browserNameKey;
}
}
/*
For a single row, write all the cells that contain support data.
(That is, every cell in the row except the first column, which contains
the feature name)
*/
function writeCompatCells(supportData) {
let output = '';
for (let browserNameKey of displayBrowsers) {
let needsNotes = false;
let support = supportData[browserNameKey];
let supportInfo = '';
if (support) {
if (Array.isArray(support)) {
// Take first support data
supportInfo += getCellString(support[0].version_added,
support[0].version_removed,
support[0].partial_implementation);
needsNotes = true;
} else {
supportInfo += getCellString(support.version_added,
support.version_removed,
support.partial_implementation);
if (support.notes || support.prefix || support.flags || support.alternative_name) {
needsNotes = true;
}
}
} else { // browsers are optional in the data, display them as "?" in our table
supportInfo += getCellString(null);
}
let browserName = getFormattedBrowserName(browserNameKey);
let supportClass = getSupportClass(support);
output += `<td class="bc-supports-${supportClass} bc-browser-${browserNameKey}`;
legendItems.add('support_' + supportClass);
if (needsNotes) {
output += ' bc-has-history';
}
output += `"><span class="bc-browser-name">${browserName}</span>${supportInfo}`;
if (needsNotes) {
output += writeCellIcons(support);
output += writeNotes(support, browserNameKey);
}
output += '</td>';
}
return output;
}
function writeCompatFeatureRow() {
let output = '';
for (let row of features) {
output += '<tr>';
let feature = Object.keys(row).map((k) => row[k])[0];
output += `<th scope="row">${writeFeatureName(row, feature)}</th>`;
output += writeCompatCells(feature.support);
output += '</tr>';
}
return output;
}
function writeCompatBody() {
let output = '<tbody>';
output += writeCompatFeatureRow()
output += '</tbody>';
return output;
}
function writeCompatPlatformsRow() {
let output = '<tr class="bc-platforms">';
output += '<td></td>';
for (let platform of platforms) {
let platformCount = Object.keys(browsers[platform]).length;
let platformId = platform.replace('webextensions-', '');
output += `<th colspan="${platformCount}" class="bc-platform-${platformId}">`;
output += writeLabel(platformId, 'platform');
output += '</th>';
}
output += '</tr>';
return output;
}
function writeCompatBrowsersRow() {
let output = '<tr class="bc-browsers">';
output += '<td></td>';
for (let browser of displayBrowsers) {
output += `<th class="bc-browser-${browser}">`;
output += writeLabel(browser);
output += '</th>';
}
output += '</tr>';
return output;
}
function writeCompatHead() {
let output = '<thead>';
output += writeCompatPlatformsRow();
output += writeCompatBrowsersRow();
output += '</thead>';
return output;
}
function writeLegend () {
let output = '<section class="bc-legend">';
output += `<h3 class="offscreen">${localize(compatStrings, 'legend')}</h3>`;
output += '<dl>';
let sortOrder = ['support_yes', 'support_partial', 'support_no', 'support_unknown',
'experimental', 'non-standard', 'deprecated',
'footnote', 'disabled', 'altname', 'prefix'];
let sortedLegendItems = Array.from(legendItems).sort(function(a, b) {
return sortOrder.indexOf(a) - sortOrder.indexOf(b);
});
for (let item of sortedLegendItems) {
// handle support cells
if (item.indexOf('support_') !== -1) {
let supportType = item.substring(item.indexOf('_') + 1);
output += `<dt><span class="bc-supports-${supportType} bc-supports">
<abbr title="${localize(compatStrings, 'supportsLong_' + supportType)}"
class="bc-level bc-level-${supportType} only-icon">
<span>${localize(compatStrings, 'supportsLong_' + supportType)}</span>
</abbr></span></dt>`;
output += `<dd>${localize(compatStrings, 'supportsLong_' + supportType)}</dd>`;
// handle icons
} else {
output += `<dt>${writeIcon(item, '', true)}</dt>`;
output += `<dd>${localize(compatStrings, 'legend_' + item)}</dd>`;
}
}
output += '</dl>';
output +='</section>';
return output;
}
/*
Get compat data using a query string like "webextensions.api.alarms"
*/
function getData(queryString, obj) {
let data = queryString.split('.').reduce(function(prev, curr) {
return prev ? prev[curr] : undefined
}, obj);
// Return a private copy of the data. Otherwise changes made here
// can affect later invocations of the macro
return data ? JSON.parse(JSON.stringify(data)) : data;
}
/*
Get features that should be displayed according to the query and the depth setting
Flatten them into a features array
*/
function traverseFeatures(obj, depth, identifier) {
depth--;
if (depth >= 0) {
for (let i in obj) {
if (!!obj[i] && typeof(obj[i])=="object" && i !== '__compat') {
if (obj[i].__compat) {
features.push({[identifier + i]: obj[i].__compat});
}
traverseFeatures(obj[i], depth, i + '.');
}
}
}
}
var compatData = getData(query, bcd);
var features = [];
var identifier = query.split(".").pop();
if (!compatData) {
output = s_no_data_found;
} else if (compatData.__compat) {
features.push({[identifier]: compatData.__compat});
}
traverseFeatures(compatData, depth, '');
if (features.length > 0) {
output = `<div class="bc-data" id="bcd:${query}">`;
output += '<a class="bc-github-link" href="https://github.com/mdn/browser-compat-data">Update compatibility data on GitHub</a>';
output += `<table class="bc-table bc-table-${bcCategory}">`;
output += writeCompatHead();
output += writeCompatBody();
output += '</table>';
output += writeLegend();
output += '</div>';
} else {
output = s_no_data_found;
}
%>
<%-output%>