-
Notifications
You must be signed in to change notification settings - Fork 372
/
Copy pathexamples.js
466 lines (401 loc) · 12.4 KB
/
examples.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
/**
* @namespace aria
*/
'use strict';
var aria = aria || {};
/* ---------------------------------------------------------------- */
/* ARIA Widget Namespace */
/* ---------------------------------------------------------------- */
aria.widget = aria.widget || {};
/* ---------------------------------------------------------------- */
/* Source code generators */
/* ---------------------------------------------------------------- */
// Default indentation according to the ARIA Practices Code Guide:
// https://github.com/w3c/aria-practices/wiki/Code-Guide.
var DEFAULT_INDENT = ' ';
// Void elements according to “HTML 5.3: The HTML Syntax”:
// https://w3c.github.io/html/syntax.html#void-elements.
var VOID_ELEMENTS = [
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'param',
'source',
'track',
'wbr',
];
/**
* Creates a slider widget using ARIA
*
* @property {Array} location Object containing the keyCodes used by the slider widget
* @property {Array} code JQuery node object
* @constructor SourceCode
* @memberof aria.widget
*/
aria.widget.SourceCode = function () {
this.location = new Array();
this.code = new Array();
this.exampleHeader = new Array();
this.resources = new Array();
};
/**
* Adds source code
*
* @param {string} locationId - ID of `code` element that will display the example html
* @param {string} codeID - ID of element containing only and all of the html used to render the example widget
* @param {string} exampleHeaderId - ID of header element under which the "Open in Codepen" button belongs
* @param {string} cssJsFilesId - ID of element containing links to all the relevent js and css files used for the example widget
*
* @method add
* @memberof aria.widget.SourceCode
*/
aria.widget.SourceCode.prototype.add = function (
locationId,
codeId,
exampleHeaderId,
cssJsFilesId
) {
this.location[this.location.length] = locationId;
this.code[this.code.length] = codeId;
this.exampleHeader[this.exampleHeader.length] = exampleHeaderId;
this.resources[this.resources.length] = cssJsFilesId;
};
/**
* Generates HTML content for source code
*
* @method make
* @memberof aria.widget.SourceCode
*/
aria.widget.SourceCode.prototype.make = function () {
for (var i = 0; i < this.location.length; i++) {
var sourceCodeNode = document.getElementById(this.location[i]);
var nodeCode = document.getElementById(this.code[i]);
sourceCodeNode.className = 'sourcecode';
this.createCode(sourceCodeNode, nodeCode, 0, true);
// Remove unnecessary `<br>` element.
if (sourceCodeNode.innerHTML.startsWith('<br>')) {
sourceCodeNode.innerHTML = sourceCodeNode.innerHTML.replace('<br>', '');
}
// Adds the "Open In CodePen" button by the example header
if (this.exampleHeader[i]) {
addOpenInCodePenForm(
i,
this.exampleHeader[i],
this.code[i],
this.resources[i]
);
}
}
};
/**
* Creates the HTML for one node
*
* @param {HTMLElement} sourceCodeNode element to put the source code in
* @param {Object} node DOM Element node to use to generate the source code
* @param {Number} indentLevel Level of indentation
* @param {Boolean} skipFirst Whether to skip the first node
*
* @method createCode
* @memberof aria.widget.SourceCode
*/
aria.widget.SourceCode.prototype.createCode = function (
sourceCodeNode,
node,
indentLevel,
skipFirst
) {
if (!skipFirst) {
var openTag = '';
var nodeNameStr = node.nodeName.toLowerCase();
openTag += '<br/>' + indentation(indentLevel) + '<' + nodeNameStr;
var wrapAttributes = node.attributes.length > 2;
for (var attrPos = 0; attrPos < node.attributes.length; attrPos++) {
if (!wrapAttributes || attrPos === 0) {
openTag += ' ';
}
var attributeValue = sanitizeNodeValue(node.attributes[attrPos].value);
openTag +=
node.attributes[attrPos].nodeName + '="' + attributeValue + '"';
if (wrapAttributes && attrPos !== node.attributes.length - 1) {
openTag += '<br/>' + indentation(indentLevel);
openTag += ' '.repeat(nodeNameStr.length + 2);
}
}
openTag += '>';
sourceCodeNode.innerHTML += openTag;
indentLevel++;
}
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes[i];
switch (childNode.nodeType) {
case Node.ELEMENT_NODE:
this.createCode(sourceCodeNode, childNode, indentLevel, false);
break;
case Node.TEXT_NODE:
if (hasText(childNode.nodeValue)) {
var textNodeContent = sanitizeNodeValue(childNode.nodeValue).trim();
textNodeContent = indentLines(
textNodeContent,
indentation(indentLevel)
);
sourceCodeNode.innerHTML += '<br/>' + textNodeContent;
}
break;
case Node.COMMENT_NODE:
if (hasText(childNode.nodeValue)) {
var commentNodeContent = sanitizeNodeValue(childNode.nodeValue);
commentNodeContent = '<!--' + commentNodeContent + '-->';
commentNodeContent = indentLines(
commentNodeContent,
indentation(indentLevel)
);
sourceCodeNode.innerHTML += '<br/>' + commentNodeContent;
}
break;
}
}
if (!skipFirst && !VOID_ELEMENTS.includes(node.tagName.toLowerCase())) {
indentLevel--;
var closeTag = '</' + node.nodeName.toLowerCase() + '>';
if (node.childNodes.length > 0) {
sourceCodeNode.innerHTML += '<br/>' + indentation(indentLevel);
}
sourceCodeNode.innerHTML += closeTag;
}
};
/**
* Returns the indentation string based on a given indent level.
*
* @param {Number} indentLevel
* @returns {String}
*/
function indentation(indentLevel) {
return DEFAULT_INDENT.repeat(indentLevel);
}
/**
* Tests whether the input string contains any non-whitespace character.
*
* `\S`: Any non-whitespace character
*
* Examples:
*
* ```
* hasText('\t\n\r ');
* //> false
*
* hasText('\tcontent\n\r ');
* //> true
* ```
*
* @param {String} nodeContent content of a node to test for whitespace characters
* @returns {Boolean}
*/
function hasText(nodeContent) {
if (typeof nodeContent !== 'string') {
return false;
}
return /\S/.test(nodeContent);
}
/**
* Replaces the characters `<` and `>` with their respective HTML entities.
*
* @param {String} textContent
* @returns {String}
*/
function sanitizeNodeValue(textContent) {
if (typeof textContent !== 'string') {
return '';
}
var output = stripIndentation(textContent);
return output
.replace(new RegExp('<', 'g'), '<')
.replace(new RegExp('>', 'g'), '>');
}
/**
* Strips any leading indentation from the text content of a node.
*
* @param {String} textContent
* @returns {String}
*/
function stripIndentation(textContent) {
var textIndentation = detectIndentation(textContent);
if (textIndentation === 0) {
return textContent;
}
var firstLine = textContent.substring(0, textContent.indexOf('\n'));
var lines = textContent.split('\n').slice(1);
lines = lines.map(function (line) {
if (line === '') {
return line;
}
return line.substring(textIndentation);
});
return firstLine + '\n' + lines.join('\n');
}
/**
* Determines the indentation level of text content.
*
* Algorithm:
*
* **Case 1: `textContent` is on the same line as opening and closing tag**:
*
* In other words, the text doesn’t contain any newline. Return 0.
*
* **Case 2: `textContent` is on the same line as opening tag**:
*
* We already know there is atleast one newline, because case 1 didn’t return.
* We can now find the first indented line that contains any non-whitespace
* character in order to determine present indentation.
*
* 1. Starting from the position after the first newline, iterate over each
* character in `textContent`.
* 2. If the character is a non-whitespace (i.e. `/\S/`), `break`.
* 3. If the character is a newline, reset the indentation level and
* `continue`.
* 4. Increment the indentation level.
*
* Return the indentation level.
*
* @param {String} textContent
* @returns {Number} The level of indentation
*/
function detectIndentation(textContent) {
// Case 1
if (!textContent.includes('\n')) {
return 0;
}
// Case 2
var indentationLevel = 0;
for (var i = textContent.indexOf('\n') + 1; i < textContent.length; i++) {
if (/\S/.test(textContent[i])) {
break;
}
if (textContent[i] === '\n') {
indentationLevel = 0;
continue;
}
indentationLevel++;
}
return indentationLevel;
}
/**
* Prepends each line of a string with the provided indentation string.
*
* @param {String} input
* @param {String} indentation
* @returns {String}
*/
function indentLines(input, indentation) {
var lines = input.split('\n');
lines = lines.map(function (line) {
return indentation + line;
});
return lines.join('\n');
}
/**
* Creates and adds an "Open in CodePen" button
*
* @param {String} exampleIndex - the example number, if there are multiple examples
* @param {String} exampleHeaderId - the example header to place the button next to
* @param {String} exampleCodeId - the example html code
* @param {String} exampleFilesId - the element containing all relevent CSS and JS file
*/
function addOpenInCodePenForm(
exampleIndex,
exampleHeaderId,
exampleCodeId,
exampleFilesId
) {
var jsonInputId = 'codepen-data-ex-' + exampleIndex;
var buttonId = exampleCodeId + '-codepenbutton';
var form = document.createElement('form');
form.setAttribute('action', 'https://codepen.io/pen/define');
form.setAttribute('method', 'POST');
form.setAttribute('target', '_blank');
var input = document.createElement('input');
input.setAttribute('id', jsonInputId);
input.setAttribute('type', 'hidden');
input.setAttribute('name', 'data');
var button = document.createElement('button');
button.innerText = 'Open In CodePen';
button.id = buttonId;
button.style.display = 'none';
form.appendChild(input);
form.appendChild(button);
var exampleHeader = document.getElementById(exampleHeaderId);
exampleHeader.parentNode.insertBefore(form, exampleHeader.nextSibling);
// Correct the indentation for the example html
var indentedExampleHtml = document.getElementById(exampleCodeId).innerHTML;
indentedExampleHtml = indentedExampleHtml.replace(/^\n+/, '');
var indentation = indentedExampleHtml.match(/^\s+/)[0];
var exampleHtml = indentedExampleHtml.replace(
new RegExp('^' + indentation, 'gm'),
''
);
var path = location.pathname.split('/');
var filename =
path.length > 0 ? path[path.length - 1].replace('.html', '') : '';
var postJson = {
title: filename,
html: exampleHtml,
css: '',
js: '',
head: '<base href="' + location.href + '">',
css_external:
location.origin +
'/examples/css/core.css;' +
'https://www.w3.org/StyleSheets/TR/2016/base.css',
};
var totalFetchedFiles = 0;
var fileLinks = document.querySelectorAll('#' + exampleFilesId + ' a');
for (let fileLink of fileLinks) {
var request = new XMLHttpRequest();
request.open('GET', fileLink.href, true);
request.onload = function () {
var href = this.responseURL;
if (this.status >= 200 && this.status < 400) {
if (href.indexOf('css') !== -1) {
postJson.css = postJson.css.concat(this.response);
}
if (href.indexOf('js') !== -1) {
postJson.js = postJson.js.concat(this.response);
}
totalFetchedFiles++;
} else {
console.warn(
"Not showing 'Open in Codepen' button. Could not load resource: " +
href
);
}
};
request.onerror = function () {
console.warn(
"Not showing 'Open in Codepen' button. Could not load resource: " +
fileLink.href
);
};
request.send();
}
var timerId = setInterval(() => {
if (totalFetchedFiles === fileLinks.length) {
clearInterval(timerId);
document.getElementById(jsonInputId).value = JSON.stringify(postJson);
var button = document.getElementById(buttonId);
button.style.display = '';
}
}, 500);
setTimeout(() => {
clearInterval(timerId);
console.warn(
"Not showing 'Open in Codepen' button. Timeout when loading resource."
);
}, 10000);
}
var sourceCode = new aria.widget.SourceCode();