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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview This file is the controller for generating extension
* doc pages.
*
* It expects to have available via XHR (relative path):
* 1) API_TEMPLATE which is the main template for the api pages.
* 2) The files located at MODULE_SCHEMAS which are shared with the extension
* system and defines the methods and events contained in one api.
* 3) (Possibly) A static version of the current page url in /static/. I.e.
* if called as ../foo.html, it will look for ../static/foo.html.
*
* The "shell" page may have a renderering already contained within it so that
* the docs can be indexed.
*
*/
var API_TEMPLATE = 'template/api_template.html';
var MODULE_SCHEMAS = [
'../api/alarms.json', // autogenerated
'../api/bookmarks.json',
'../api/browser_action.json',
'../api/browsing_data.json',
'../api/chrome_auth_private.json',
'../api/chromeos_info_private.json',
'../api/content_settings.json',
'../api/context_menus.json',
'../api/cookies.json',
'../api/debugger.json',
'../api/declarative.json',
'../api/declarative_web_request.json',
'../api/devtools.json',
'../api/experimental_accessibility.json',
'../api/experimental_app.json',
'../api/experimental_bookmark_manager.json',
'../api/experimental_downloads.json',
'../api/experimental_font_settings.json',
'../api/experimental_identity.json',
'../api/experimental_infobars.json',
'../api/experimental_input_ui.json',
'../api/experimental_input_virtual_keyboard.json',
'../api/experimental_keybinding.json',
'../api/experimental_media_galleries.json',
'../api/experimental_offscreen_tabs.json',
'../api/experimental_processes.json',
'../api/experimental_rlz.json',
'../api/experimental_runtime.json',
'../api/experimental_speech_input.json',
'../api/extension.json',
'../api/file_browser_handler.json',
'../api/file_browser_private.json',
'../api/history.json',
'../api/i18n.json',
'../api/idle.json',
'../api/input_ime.json',
'../api/input_method_private.json',
'../api/managed_mode_private.json',
'../api/management.json',
'../api/media_player_private.json',
'../api/metrics_private.json',
'../api/omnibox.json',
'../api/page_action.json',
'../api/page_actions.json',
'../api/page_capture.json',
'../api/permissions.json',
'../api/privacy.json',
'../api/proxy.json',
'../api/storage.json',
'../api/system_private.json',
'../api/tabs.json',
'../api/test.json',
'../api/top_sites.json',
'../api/tts.json',
'../api/tts_engine.json',
'../api/types.json',
'../api/web_navigation.json',
'../api/web_request.json',
'../api/web_socket_proxy_private.json',
'../api/webstore.json',
'../api/webstore_private.json',
'../api/windows.json',
]
var PERMISSION_FEATURES = '../api/_permission_features.json';
var DEVTOOLS_SCHEMA = '../api/devtools_api.json';
var USE_DEVTOOLS_SCHEMA =
/devtools[^/]*\.html/.test(location.pathname);
var API_MODULE_PREFIX = 'chrome.';
var SAMPLES = 'samples.json';
var REQUEST_TIMEOUT = 2000;
function staticResource(name) { return 'static/' + name + '.html'; }
// Base name of this page. (i.e. 'tabs', 'overview', etc...).
var pageBase;
// Data to feed as context into the template.
var pageData = {};
// The full extension api schema
var schema;
// List of Chrome extension samples.
var samples;
// Mappings of api calls to URLs
var apiMapping;
// The current module for this page (if this page is an api module);
var module;
// Mapping from typeId to module.
var typeModule = {};
// Auto-created page name as default
var pageName;
// If this page is an apiModule, the name of the api module
var apiModuleName;
// Permission information according to PERMISSION_FEATURES.
var permissionFeatures = {};
// Visits each item in the list in-order. Stops when f returns any truthy
// value and returns that node.
Array.prototype.select = function(f) {
for (var i = 0; i < this.length; i++) {
if (f(this[i], i))
return this[i];
}
}
// Assigns all keys & values of |obj2| to |obj1|.
function extend(obj, obj2) {
for (var k in obj2) {
obj[k] = obj2[k];
}
}
/*
* Main entry point for composing the page. It will fetch its template,
* the extension api, and attempt to fetch the matching static content.
* It will insert the static content, if any, prepare its pageData then
* render the template from |pageData|.
*/
function renderPage() {
// The page name minus the '.html' extension.
pageBase = document.location.href.match(/\/([^\/]*)\.html/)[1];
if (!pageBase) {
alert('Empty page name for: ' + document.location.href);
return;
}
pageName = pageBase.replace(/([A-Z])/g, ' $1');
pageName = pageName.substring(0, 1).toUpperCase() + pageName.substring(1);
// Fetch the api template and insert into the <body>.
fetchContent(API_TEMPLATE, function(templateContent) {
document.getElementsByTagName('body')[0].innerHTML = templateContent;
fetchStatic();
}, function(error) {
alert('Failed to load ' + API_TEMPLATE + '. ' + error);
});
}
function fetchStatic() {
// Fetch the static content and insert into the 'static' <div>.
fetchContent(staticResource(pageBase), function(overviewContent) {
document.getElementById('static').innerHTML = overviewContent;
fetchPermissionFeatures();
}, function(error) {
// Not fatal. Some api pages may not have matching static content.
fetchPermissionFeatures();
});
}
function fetchPermissionFeatures() {
// Fetch the permissionFeatures of features.
fetchContent(PERMISSION_FEATURES, function(content) {
permissionFeatures = JSON.parse(JSON.minify(content));
fetchSchema();
}, function(error) {
alert('Failed to load ' + PERMISSION_FEATURES + '. ' + error);
});
}
function fetchSchema() {
// Now the page is composed with the authored content, we fetch the schema
// and populate the templates.
var is_experimental_index = /\/experimental\.html$/.test(location.pathname);
var schemas_to_retrieve = [];
if (!USE_DEVTOOLS_SCHEMA || is_experimental_index)
schemas_to_retrieve = schemas_to_retrieve.concat(MODULE_SCHEMAS);
if (USE_DEVTOOLS_SCHEMA || is_experimental_index)
schemas_to_retrieve.push(DEVTOOLS_SCHEMA);
var schemas_retrieved = 0;
schema = [];
function onSchemaContent(content) {
if (content)
schema = schema.concat(JSON.parse(JSON.minify(content)));
if (++schemas_retrieved < schemas_to_retrieve.length)
return;
if (pageName.toLowerCase() == 'samples') {
fetchSamples();
} else {
renderTemplate();
}
}
schemas_to_retrieve.forEach(function(schema_path) {
fetchContent(schema_path, onSchemaContent, function(path, error) {
console.error('Failed to load schema', path, error);
onSchemaContent();
});
});
}
function fetchSamples() {
// If we're rendering the samples directory, fetch the samples manifest.
fetchContent(SAMPLES, function(sampleManifest) {
var data = JSON.parse(JSON.minify(sampleManifest));
samples = data.samples;
apiMapping = data.api;
renderTemplate();
}, function(error) {
renderTemplate();
});
}
/**
* Fetches |url| and returns its text contents from the xhr.responseText in
* onSuccess(content)
*/
function fetchContent(url, onSuccess, onError) {
var localUrl = url;
var xhr = new XMLHttpRequest();
var abortTimerId = window.setTimeout(function() {
xhr.abort();
console.log('XHR Timed out');
}, REQUEST_TIMEOUT);
function handleError(error) {
window.clearTimeout(abortTimerId);
if (onError) {
onError(error);
// Some cases result in multiple error handings. Only fire the callback
// once.
onError = undefined;
}
}
try {
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status < 300 && xhr.responseText) {
window.clearTimeout(abortTimerId);
onSuccess(xhr.responseText);
} else {
handleError('Failure to fetch content: ' + xhr.status);
}
}
}
xhr.onerror = handleError;
xhr.open('GET', url, true);
xhr.send(null);
} catch(e) {
console.log('ex: ' + e);
console.error('exception: ' + e);
handleError();
}
}
function renderTemplate() {
schema.forEach(function(mod) {
if (mod.namespace == pageBase) {
// Do not render page for modules which have documentation disabled.
if (disableDocs(mod))
return;
// This page is an api page. Setup types and apiDefinition.
module = mod;
apiModuleName = API_MODULE_PREFIX + module.namespace;
pageData.apiDefinition = module;
}
if (mod.types) {
mod.types.forEach(function(type) {
typeModule[type.id] = mod;
});
}
});
/**
* Special pages like the samples gallery may want to modify their template
* data to include additional information. This hook allows a page template
* to specify code that runs in the context of the api_page_generator.js
* file before the jstemplate is rendered.
*
* To specify such code, the page template should include a script block with
* a type of "text/prerenderjs" containing the code to be executed. Note that
* linking to an external file is not supported - code must be accessible
* via the script block's innerText property.
*
* Code that is run this way may modify the data sent to jstemplate by
* modifying the window.pageData variable. This code will also have access
* to any methods declared in the api_page_generator.js file. The code
* does not need to return any specific value to function.
*
* Note that code specified in this manner will be removed before the
* template is rendered, and will therefore not be exposed to the end user
* in the final rendered template.
*/
var preRender = document.querySelectorAll('script[type="text/prerenderjs"]');
Array.prototype.slice.call(preRender).forEach(function(element) {
element.parentElement.removeChild(element);
eval(element.innerText);
});
// Render to template
var input = new JsEvalContext(pageData);
var output = document.getElementsByTagName('body')[0];
jstProcess(input, output);
selectCurrentPageOnLeftNav();
// Set a `meta` description if the page we're currently generating has a
// module name.
// TODO(mkwst): Come up with something clever for the other types of pages.
if (getModuleName()) {
var m = document.createElement('meta');
var desc = 'Documentation for the ' + getModuleName() +
' module, which is part of the Google Chrome ' +
' extension APIs.';
m.setAttribute('name', 'description');
m.setAttribute('content', desc);
document.head.appendChild(m);
}
document.title = getPageTitle();
// Show
if (window.postRender)
window.postRender();
if (parent && parent.done)
parent.done();
}
function cleanupJstemplateMess(root) {
var jsattributes = ['jscontent', 'jsselect', 'jsdisplay', 'transclude',
'jsvalues', 'jsvars', 'jseval', 'jsskip', 'jstcache',
'jsinstance'];
var nodes = root.getElementsByTagName('*');
var displayNone = [];
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i]
// Delete nodes which are hidden. There are lots of these since jsdisplay
// just hides nodes, not deletes them.
if (n.style && n.style.display === 'none') {
displayNone.push(n);
continue;
}
// Delete empty style attributes (this can happen when jsdisplay causes
// display values other than 'none').
var styleAttribute = n.getAttribute('style');
if (typeof(styleAttribute) === 'string' && styleAttribute.trim() === '') {
n.removeAttribute('style');
}
// Remove jstemplate attributes from nodes that stick around.
jsattributes.forEach(function(attributeName) {
n.removeAttribute(attributeName);
});
}
displayNone.forEach(function(element) {
element.parentElement.removeChild(element);
});
}
// Strip empty lines, primarily so that elements which are jsdisplay=false and
// removed leave no whitespace-trace.
function stripEmptyLines(string) {
function notEmpty(s) {
return s.trim().length > 0;
}
return string.split('\n').filter(notEmpty).join('\n');
}
function serializePage() {
cleanupJstemplateMess(document);
var s = new XMLSerializer();
return stripEmptyLines(s.serializeToString(document));
}
function evalXPathFromNode(expression, node) {
var results = document.evaluate(expression, node, null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var retval = [];
while(n = results.iterateNext()) {
retval.push(n);
}
return retval;
}
function evalXPathFromId(expression, id) {
return evalXPathFromNode(expression, document.getElementById(id));
}
// Select the current page on the left nav. Note: if already rendered, this
// will not effect any nodes.
function selectCurrentPageOnLeftNav() {
function finalPathPart(str) {
var pathParts = str.split(/\//);
var lastPart = pathParts[pathParts.length - 1];
return lastPart.split(/\?/)[0];
}
var pageBase = finalPathPart(document.location.href);
evalXPathFromId('.//li/a', 'gc-toc').select(function(node) {
if (pageBase == finalPathPart(node.href)) {
var parent = node.parentNode;
if (node.firstChild.nodeName == 'DIV') {
node.firstChild.className = 'leftNavSelected';
} else {
parent.className = 'leftNavSelected';
}
parent.removeChild(node);
parent.insertBefore(node.firstChild, parent.firstChild);
return true;
}
});
}
/*
* Template Callout Functions
* The jstProcess() will call out to these functions from within the page
* template
*/
function filterDocumented(things) {
return !things ? [] : things.filter(function(thing) {
return !disableDocs(thing);
});
}
function stableAPIs() {
return schema.filter(function(module) {
return !disableDocs(module) &&
module.namespace.indexOf('experimental') < 0;
}).map(function(module) {
return module.namespace;
}).sort();
}
function experimentalAPIs() {
return schema.filter(function(module) {
return !disableDocs(module) &&
module.namespace.indexOf('experimental') == 0;
}).map(function(module) {
return module.namespace;
}).sort();
}
function getDataFromPageHTML(id) {
var node = document.getElementById(id);
if (!node)
return;
return node.innerHTML;
}
function isArray(type) {
return type.type == 'array';
}
function isFunction(type) {
return type.type == 'function';
}
function getTypeRef(type) {
return type['$ref'];
}
function getTypeByName(typeName) {
var module = typeModule[typeName] || {};
for (var type in module.types) {
if (module.types.hasOwnProperty(type) && type.id === typeName)
return type;
}
return undefined;
}
function getDescription(typeName) {
var type = getTypeByName(typeName);
if (!type)
return undefined;
return type.description;
}
function getEnumValues(enumList, type) {
if (type === 'string') {
enumList = enumList.map(function(e) { return '"' + e + '"'});
}
var retval = enumList.join(', ');
return '[' + retval + ']';
}
function showPageTOC() {
return module || getDataFromPageHTML('pageData-showTOC');
}
function showSideNav() {
return getDataFromPageHTML('pageData-showSideNav') != 'false';
}
function getStaticTOC() {
var staticHNodes = evalXPathFromId('.//h2|h3', 'static');
var retval = [];
var lastH2;
staticHNodes.forEach(function(n, i) {
var anchorName = n.id || n.nodeName + '-' + i;
if (!n.id) {
var a = document.createElement('a');
a.name = anchorName;
n.parentNode.insertBefore(a, n);
}
var dataNode = { name: n.innerHTML, href: anchorName };
if (n.nodeName == 'H2') {
retval.push(dataNode);
lastH2 = dataNode;
lastH2.children = [];
} else {
lastH2.children.push(dataNode);
}
});
return retval;
}
// This function looks in the description for strings of the form
// "$ref:TYPE_ID" (where TYPE_ID is something like "Tab" or "HistoryItem") and
// substitutes a link to the documentation for that type.
function substituteTypeRefs(description) {
var regexp = /\$ref\:\w+/g;
var matches = description.match(regexp);
if (!matches) {
return description;
}
var result = description;
for (var i = 0; i < matches.length; i++) {
var type = matches[i].split(':')[1];
var page = null;
try {
page = getTypeRefPage({'$ref': type});
} catch (error) {
console.log('substituteTypeRefs couldn\'t find page for type ' + type);
continue;
}
var replacement = '<a href="' + page + '#type-' + type + '">' + type +
'</a>';
result = result.replace(matches[i], replacement);
}
return result;
}
function getTypeRefPage(type) {
return typeModule[type.$ref].namespace + '.html';
}
function getPageName() {
var pageDataName = getDataFromPageHTML('pageData-name');
// Allow empty string to be explitly set via pageData.
if (pageDataName == '') {
return pageDataName;
}
return pageDataName || apiModuleName || pageName;
}
function getPageTitle() {
var pageName = getPageName();
var pageTitleSuffix = 'Google Chrome Extensions - Google Code';
if (pageName == '') {
return pageTitleSuffix;
}
return pageName + ' - ' + pageTitleSuffix;
}
function getModuleName() {
return (module && typeof module.namespace) ?
API_MODULE_PREFIX + module.namespace : '';
}
function getFullyQualifiedFunctionName(scope, func) {
return (getObjectName(scope) || getModuleName()) + '.' + func.name;
}
function getObjectName(typeName) {
return typeName.charAt(0).toLowerCase() + typeName.substring(1);
}
function isExperimentalAPIPage() {
return (getPageName().indexOf('.experimental.') >= 0 &&
getPageName().indexOf('.experimental.*') < 0);
}
function getPermittedChannels() {
var allChannels = ['trunk', 'canary', 'dev', 'beta', 'stable'];
var maximumSupportedChannel = 4; // index in allChannels
// Check for all required permissions of an API, whether their governing
// feature is limited to a specific release channel.
var requiredPermissions = module.documentation_permissions_required || [];
for (var i = 0; i < requiredPermissions.length; ++i) {
var permissionName = requiredPermissions[i];
var supportedChannel = (permissionFeatures[permissionName] || {}).channel ||
'stable';
for (var j = 0; j < allChannels.length; ++j) {
if (supportedChannel === allChannels[j]) {
maximumSupportedChannel = Math.min(maximumSupportedChannel, j);
break;
}
}
}
// Return a list of all supported channels.
return allChannels.slice(0, maximumSupportedChannel + 1);
}
function isPermittedOnChannel(channel) {
var permittedChannels = getPermittedChannels();
for (var i = 0; i < permittedChannels.length; ++i) {
if (permittedChannels[i] === channel) {
return true;
}
}
return false;
}
function hasCallback(parameters) {
return (parameters.length > 0 &&
parameters[parameters.length - 1].type == 'function');
}
function getCallbackParameters(parameters) {
return parameters[parameters.length - 1];
}
function getAnchorName(type, name, scope) {
return type + '-' + (scope ? scope + '-' : '') + name;
}
function shouldExpandObject(object) {
return object.properties ||
(object.items && object.items.properties);
}
function getPropertyListFromObject(object) {
var propertyList = [];
var properties = object.properties;
if (!properties && object.type === 'array' && object.items) {
properties = object.items.properties;
}
for (var p in properties) {
var prop = properties[p];
// Do not render properties with documentation disabled.
if (disableDocs(prop)) {
continue;
}
prop.name = p;
propertyList.push(prop);
}
return propertyList;
}
function getTypeName(schema) {
if (schema.$ref)
return schema.$ref;
if (schema.choices) {
var typeNames = [];
schema.choices.forEach(function(c) {
typeNames.push(getTypeName(c));
});
return typeNames.join(' or ');
}
if (schema.type == 'array')
return 'array of ' + getTypeName(schema.items);
if (schema.isInstanceOf)
return schema.isInstanceOf;
return schema.type;
}
function hasPrimitiveValue(schema) {
var type = typeof(schema.value);
return type === 'string' || type === 'number';
}
function getPrimitiveValue(schema) {
switch (typeof(schema.value)) {
case 'string':
return '"' + schema.value + '"';
case 'number':
// Comma-separate large numbers (e.g. 5,000,000), easier to read.
var value = String(schema.value);
var groupsOfThree = [];
while (value.length > 3) {
groupsOfThree.unshift(value.slice(value.length - 3));
value = value.slice(0, value.length - 3);
}
groupsOfThree.unshift(value);
return groupsOfThree.join(',');
}
return undefined;
}
function getSignatureString(parameters) {
if (!parameters)
return '';
var retval = [];
filterDocumented(parameters).forEach(function(param, i) {
retval.push(getTypeName(param) + ' ' + param.name);
});
return retval.join(', ');
}
function getOptionalSignatureSubstring(parameters) {
if (!parameters)
return '';
return ', ' + getSignatureString(parameters);
}
function sortByName(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
function disableDocs(obj) {
return !!obj.nodoc;
}
|