-
-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathdocs.js
520 lines (450 loc) · 15.8 KB
/
docs.js
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
const gulp = require('gulp');
const livingcss = require('gulp-livingcss');
const replace = require('gulp-replace');
const path = require('path');
const marked = require('marked');
const pkg = require('../package.json');
const fs = require('fs');
const glob = require('glob');
const optionalRegex = /^\[.*\]$/;
const kontraTypesRegex = new RegExp(
`(${glob
.sync('src/*.js')
.map(fileName => getPageName(path.basename(fileName, '.js')))
.sort((a, b) => b.length - a.length)
.join('|')})`,
'g'
);
const packageVersionRegex = /__packageVersion__/g;
const excludeCodeRegex = /\s*\/\/ exclude-code:start[\s\S]*?\/\/ exclude-code:end/g;
const excludeScriptRegex = /\s*\/\/ exclude-script:start[\r\n]([\s\S]*?[\r\n])\/\/ exclude-script:end[\r\n]/g;
const codeRegex = /<pre>[\s\S]*?<code class="(.*)">([\s\S]*?)<\/code><\/pre>/g;
const importRegex = /import \{(.*)\} from .+kontra.+?;/g;
let uuid = 0;
let navbar;
function getPageName(file) {
return file[0].toUpperCase() + file.substring(1);
}
/**
* Sort sections by name
* @param {Object} a
* @param {Object} b
*/
function sortByName(a, b) {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}
// hack to add @section and @page to every jsdoc section without explicitly
// having to add them to every block :)
function addSectionAndPage() {
let description = path.basename(this.file, '.js');
let property = this.block.property;
let fn = this.block.function;
let clas = this.block.class;
let sectionName = property ? property.name : fn ? fn : clas ? clas : description;
// TODO: temporary fix for `length` name (zero-width space added to end)
if (sectionName === 'length') {
sectionName = 'length';
}
// don't add multiple section tags
let section = this.comment.tags.find(tag => tag.tag === 'section');
if (!section) {
this.comment.tags.push({
tag: 'section',
description: sectionName,
type: '',
name: '',
source: `@section ${sectionName}`
});
}
// don't add multiple page tags
let page = this.comment.tags.find(tag => tag.tag === 'page');
if (!page) {
this.comment.tags.push({
tag: 'page',
description: getPageName(description),
type: '',
name: '',
source: `@page ${description}`
});
}
this.comment.description = this.comment.description;
}
/**
* Create a tab panel to show the different ways to load the library automatically from the code output of a section description. Don't do this for any code output that has '// exclude-tablist'
* @param {Object} section
*/
function buildImports(section) {
section.description = section.description.replace(codeRegex, (match, className) => {
if (className === 'language-js' && !match.includes('// exclude-tablist')) {
let globalImport = match.replace(importRegex, `let {$1} = kontra`);
let esImport = match.replace(importRegex, `import {$1} from 'path/to/kontra.mjs'`);
let bundlerImport = match;
return `<div class="tablist">
<ul role="tablist">
<li role="presentation" data-tab="global">
<button role="tab" id="${section.id}-global-tab">Global Object</button>
</li>
<li role="presentation" data-tab="es">
<button role="tab" id="${section.id}-es-tab">ES Module Import</button>
</li>
<li role="presentation" data-tab="bundle">
<button role="tab" id="${section.id}-bundle-tab">Module Bundler</button>
</li>
<li role="presentation"></li>
</ul>
<section role="tabpanel" aria-labelledby=${section.id}-global-tab data-tabpanel="global">${globalImport}</section>
<section role="tabpanel" aria-labelledby=${section.id}-es-tab data-tabpanel="es">${esImport}</section>
<section role="tabpanel" aria-labelledby=${section.id}-bundle-tab data-tabpanel="bundle">${bundlerImport}</section>
</div>`;
} else {
return match.replace('// exclude-tablist\n', '');
}
});
}
/**
* Parse kontra defined types and turn them into links.
* @param {String} string - The string containing the kontra type.
* @param {Boolean} isArray - If the type is an array.
*/
function resolveKontraType(string, isArray) {
return string.replace(kontraTypesRegex, function (match, p1) {
let url = p1;
// if (isArray) {
// url = url;
// }
url = url[0].toLowerCase() + url.slice(1);
return `<a href="api/${url}">${p1}</a>`;
});
}
/**
* Parse information about the type.
* @param {String} type - The JSDoc type string.
* @returns {String}
*/
function parseType(type) {
// parse typescript specific typings
if (type.startsWith('(')) {
type = 'Function';
} else if (type.startsWith('...')) {
type = type.replace('...', 'A list of ');
// make the type plural instead of an array for reset parameters
type = type.replace(/(\w+)\[\]$/, '$1s');
// parse array types
type = type.replace(/(\w+)\[\]/g, function (match, p1, index) {
return `Array of ${p1}s`;
});
// remove ending array for rest parameters
type = type.replace(/\[\]$/, '');
}
if (type.includes('{')) {
type = type.replace(/\{[^}]*\}+/g, 'Object');
}
// parse OR types
if (type.includes('|')) {
let types = type.split('|');
// don't put a OR between two types that are the same
let equal = true;
let firstType = types[0].substr(types[0].indexOf('(') + 1);
for (let i = 1; i < types.length; i++) {
let nextType = types[i];
if (nextType.includes(')')) {
nextType = nextType.substring(0, nextType.lastIndexOf(')'));
}
equal = equal && (firstType === nextType);
}
if (equal) {
type = types[0];
}
else {
type = types.join(' or ');
}
}
// parse array types
let isArray = false;
if (type.includes('[]')) {
isArray = true;
type = type.replace(/(\w+)\[\]/g, function (match, p1, index) {
return `${index === 0 ? 'A' : 'a'}n Array of ${p1}s`;
});
}
type = resolveKontraType(type, isArray);
// parse any types
type = type.replace('*', type.startsWith('*') ? 'Any type' : 'any type');
return type;
}
let tags = {
// output information about the parameter
param: function () {
let { name, description, type } = this.tag;
let paramValue = '';
let entry = {};
// used to display the list of parameters in the function title
// (e.g. myFunc(a, b[, c]) )
this.block.paramList = this.block.paramList || '';
// optional param
if (optionalRegex.test(name)) {
name = name.substring(1, name.length - 1);
entry.optional = true;
}
// default param
if (name.indexOf('=') !== -1) {
let parts = name.split('=');
name = parts[0];
entry.default = parts[1];
}
// rest param
if (type.indexOf('...') !== -1) {
name = '...' + name;
}
// build paramList
if (entry.optional) {
paramValue += '[';
}
if (this.block.paramList.length >= 1) {
paramValue += ', ';
}
paramValue += name;
if (entry.optional) {
paramValue += ']';
}
type = parseType(type);
description = `<em>${type}</em>. ${description}${
entry.default ? ` Defaults to \`${entry.default}\`.` : ''
}`;
entry.name = name;
entry.description = marked(description);
entry.type = type;
this.block.param = this.block.param || [];
this.block.param.push(entry);
// don't list nested params (e.g. properties.foo.bar)
if (name.indexOf('.') === -1 || name.startsWith('...')) {
this.block.paramList += paramValue;
}
},
// output information about the returns value
returns: function () {
let type = parseType(this.tag.type);
let description = this.tag.description;
this.block.returns = {
name: '',
description: marked(`<em>${type}</em>. ${description}`),
type: type
};
},
// create a canvas element and code block that shows code and it actually
// working as written.
example: function () {
let width = 600;
let height = 200;
if (this.tag.type) {
let parts = this.tag.type.split('x');
width = parts[0];
height = parts[1];
}
/**
* The @example tags creates the canvas and context objects, and makes them available in the code block and script. Typically the context is used to make sure kontra draws to the right canvas if there are multiple canvases on the page.
*
* Since the kontra.js file is loaded as a global, examples can't import it, but the code should show it being imported. To handle this, there are two special comments that will be filtered out in either the code block or the script.
*
* To exclude code from the code block, use the comments `// exclude-code:start` and `// exclude-code:end`. All lines between the two comments will not be displayed in the code block but will be run in the script. Typically setup code and setting the correct context will be put in the exclude comments.
*
* To exclude code form the script, use the comments `// exclude-script:start` and `// exclude-script:end`. All lines between the two comments will not be run in the script but will be show in the code block. Typically the ES import syntax is excluded will be put in the exclude comments so the script doesn't try to import from the global kontra object.
*/
let id = `game-canvas-${uuid++}`;
let codeOutput = this.tag.description
.trim()
.replace(excludeCodeRegex, '')
.replace(excludeScriptRegex, '$1');
let globalImport = codeOutput.replace(importRegex, `let {$1} = kontra`);
let esImport = codeOutput.replace(importRegex, `import {$1} from 'path/to/kontra.mjs'`);
let bundlerImport = codeOutput;
this.block.example = {
id: id,
scriptOutput: `(function() {
kontra.init("${id}");
var canvas = document.querySelector("#${id}");
canvas.width = ${width};
canvas.height = ${height};
var context = canvas.getContext("2d");
${this.tag.description.replace(excludeScriptRegex, '')}
})();`,
globalOutput: globalImport,
esOutput: esImport,
bundleOutput: bundlerImport
};
},
// automatically make @class, @function, @property, and @sectionName add
// their own @section and @page tags for ease of use
class: function () {
this.block.class = this.tag.description;
addSectionAndPage.call(this);
},
extends: function () {
this.block.extends = parseType(this.tag.description);
},
function: function () {
this.block.function = this.tag.description;
addSectionAndPage.call(this);
},
property: function () {
let type = parseType(this.tag.type);
this.block.property = {
name: this.tag.description,
description: marked(this.tag.description),
type: type
};
// add type to the front of the description
this.comment.description = `<em>${type}</em>. ${this.comment.description[0].toUpperCase()}${this.comment.description.substr(1)}`;
addSectionAndPage.call(this);
},
sectionName: function () {
this.comment.tags.push({
tag: 'section',
description: this.tag.description,
type: '',
name: '',
source: `@section ${this.tag.description}`
});
addSectionAndPage.call(this);
},
// put the package version anywhere there is `{{ packageVersion }}` in the
// description. primarily used for the download page
packageVersion: function () {
this.block.description = this.block.description.replace(
packageVersionRegex,
pkg.version
);
},
// read a separate file for docs
docs: function () {
let contents = fs.readFileSync(this.tag.description);
let parseComments = require(path.join(require.resolve('livingcss'), '../lib/parseComments.js'));
let livingCSSTags = require(path.join(require.resolve('livingcss'), '../lib/tags.js'));
let tagList = {
...livingCSSTags,
example: tags.example,
sectionName: tags.sectionName
};
parseComments(contents.toString(), this.tag.description, tagList, {
pages: this.pages,
sections: this.sections
});
}
};
function livingcssPreprocess(context, template, Handlebars) {
try {
if (context.navbar) {
// remove the .html from the nav item urls
context.navbar.forEach(navItem => {
navItem.url = navItem.url.replace('.html', '');
// fix lower casing of names
if (navItem.url === 'gameloop') navItem.url = 'gameLoop';
else if (navItem.url === 'spritesheet') navItem.url = 'spriteSheet';
else if (navItem.url === 'tileengine') navItem.url = 'tileEngine';
else if (navItem.url === 'gameobject') navItem.url = 'gameObject';
});
context.navbar.sort(sortByName);
navbar = context.navbar;
}
// fix lower casing of names
if (context.id === 'gameloop') context.id = 'gameLoop';
else if (context.id === 'spritesheet') context.id = 'spriteSheet';
else if (context.id === 'tileengine') context.id = 'tileEngine';
else if (context.id === 'gameobject') context.id = 'gameObject';
// create 4 different sections that can be used to organize the page
context.otherSections = [];
context.methods = [];
context.properties = [];
context.methodsAndProperties = [];
context.sections.forEach((section, index) => {
// sort by methods and properties
if (section.function) {
context.methods.push(section);
context.methodsAndProperties.push(section);
} else if (section.property) {
context.properties.push(section);
context.methodsAndProperties.push(section);
}
// the first section is always the description of the API
else if (index > 0) {
context.otherSections.push(section);
section.link = section.name.toLowerCase().replace(/ /g, '-');
}
context.methods.sort(sortByName);
context.properties.sort(sortByName);
context.methodsAndProperties.sort(sortByName);
buildImports(section);
});
// load all handlebar partials
return livingcss.utils.readFileGlobs('docs/template/partials/*.hbs', function (data, file) {
// make the name of the partial the name of the file
var partialName = path.basename(file, path.extname(file));
Handlebars.registerPartial(partialName, data);
});
} catch (e) {
console.log(e);
throw e;
}
}
function buildPages() {
navbar.forEach(navItem => {
navItem.selected = false;
});
return gulp
.src('docs/pages/*.js')
.pipe(
livingcss('docs', {
loadcss: false,
template: 'docs/template/template.hbs',
tags: { ...tags },
preprocess: function (context, template, Handlebars) {
context.navbar = navbar;
context.otherSections = context.sections.slice(1);
context['nav-' + context.id] = true;
context.sections.forEach(section => {
buildImports(section);
});
// load all handlebar partials
return livingcss.utils.readFileGlobs(
'docs/template/partials/*.hbs',
function (data, file) {
// make the name of the partial the name of the file
var partialName = path.basename(file, path.extname(file));
Handlebars.registerPartial(partialName, data);
}
);
}
})
)
.pipe(gulp.dest('docs'));
}
function buildApi() {
uuid = 0;
return gulp
.src('src/*.js')
.pipe(
livingcss('docs/api', {
loadcss: false,
template: 'docs/template/template.hbs',
tags: { ...tags },
preprocess: livingcssPreprocess
})
)
.pipe(gulp.dest('docs/api'));
}
function buildServiceWorker() {
const staticCacheName = /kontra-docs-v([\d.]+)/;
return gulp
.src('docs/service-worker.js')
.pipe(replace(staticCacheName, (match, p1) => {
return match.replace(p1, pkg.version);
}))
.pipe(gulp.dest('docs'));
}
gulp.task('build:docs', gulp.series(buildApi, buildPages, buildServiceWorker));
gulp.task('watch:docs', function () {
gulp.watch(
['src/*.js', 'docs/pages/*.js', 'docs/api_docs/*.js', 'docs/template/**/*.hbs'],
gulp.series('build:docs')
);
});