-
Notifications
You must be signed in to change notification settings - Fork 1
/
edc_test.js
539 lines (457 loc) · 13.1 KB
/
edc_test.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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/** LLAB AUTOBUILD WIP SCRIPT
*
* TODO: This script is NOT FINISHED
* run with `node edc_test.js UNIT_NUM`
*/
/*
Restructuring ideas:
- could use an object to hold global data?
- queue to write and process files
*/
// Default Node modules
var fs = require('fs');
var path = require('path');
var exec = require('child_process').execSync;
var process = require('process');
var cheerio = require('cheerio');
var mkdirp = require('mkdirp');
var llab = require('./lib/llab');
var css = require('./code/css')
var util = require('./code/util');
// Use an object like a hash.
var processedPaths = {};
BASEURL = '/bjc-r'; // MATCH LLAB.ROOTURL IN CURR REPO
// This is where a llab course CONTENT lives
// This should be a checked out state
curFolder = `curriculum${BASEURL}/`;
// This is where the edX XML folder will be.
baseOutput = './tmp';
function unitTopicFile(number) {
let unit_files = {
1: 'intro-loops',
2: 'conditionals-abstraction',
3: 'lists',
4: 'internet',
5: 'algorithms',
6: 'how-computers-work',
7: 'recursion-trees-fractals',
8: 'recursive-reporters',
};
return `${unit}-${unit_files[unit]}.topic`;
};
var cssRelPath = path.relative(
curFolder,
'curriculum/bjc-r/llab/css/default.css'
);
var CSSOptions = {
paths: [
// TODO: Use newer llab stuff?
// TODO: Exclude Bootstrap?
curFolder + '/llab/css/3.3.0/bootstrap-compiled.min.css',
curFolder + '/llab/css/default.css',
curFolder + '/css/bjc.css'
],
rules: [{
name: 'transform-urls',
// Params: llab base url, relative file paths
options: [BASEURL, cssRelPath]
}, {
name: 'rename-selectors',
options: ['.full', '.llab-full']
}, {
name: 'prefix-selectors',
options: '.llab-full'
// , exclude: /bootstrap/
}]
};
// GLOBAL -- FIXME
var relPath;
var dir;
var GROUP_BY_LAB = true;
// TODO: This seems redundant, mostly.
var PROCESS_FUNCTIONS = {
file: processFile,
quiz: processQuiz,
txt: processTxt,
markdown: processMarkdown,
external: processExternal,
script: processScript
};
// TODO: fixme (refactor to not make this a global)
var cssString = '';
function doWork(unit) {
topic = `nyc_bjc/${unitTopicFile(unit)}`;
output = `${baseOutput}/U${unit}`;
mkdirp.sync(output);
// edX static files directory.
mkdirp.sync(`${output}/static`);
topic = fs.readFileSync(util.topicPath(curFolder, topic));
topic = topic.toString();
data = llab.parse(topic);
// TODO: Extract into preable section.
CSS_FILE_NAME = 'bjc-edx.css';
fs.writeFileSync(
`${output}/static/${CSS_FILE_NAME}`,
css(CSSOptions)
);
cssString = `
<link rel="stylesheet" href="${util.edXPath(CSS_FILE_NAME)}">
<script src="${util.edXPath('edx-llab-hack.js')}"></script>\n
`;
fs.writeFileSync(
`${output}/static/edx-llab-hack.js`,
fs.readFileSync('edx-llab-hack.js')
);
data.topics.forEach(parseTopic);
console.log(`Unit ${unit} conversion is done!\n=============\n`);
}
function loadFile(path) {}
function parseTopic(topic, args) {
topic.contents.forEach(parseSection, args);
}
// TODO: Make this a config item
function shouldParse(title) {
return true;
}
function parseSection(section, skip) {
var title = section.title.trim();
if (!shouldParse(title)) {
console.log('skipping:', title);
return;
}
dir = output;
if (GROUP_BY_LAB) {
dir += `/${title}`;
}
mkdirp.sync(dir);
section.contents.forEach((item, index) => processCurriculumItem(item, index));
}
// This needs renamed...
function processCurriculumItem(item, index) {
if (!item.url || !item.url.startsWith(BASEURL)) {
return;
}
item.url = util.trimQuerystring(item.url);
file = item.url.replace(BASEURL, curFolder);
relPath = path.relative(curFolder, file);
// console.log(
// `Process Curriculum Item:
// url: ${item.url}
// file: ${file}
// relPath: ${relPath}
// found?: ${processedPaths[file] == 1}
// `);
// TODO: Why the first check??
if (!file.endsWith('.html') || processedPaths[file] == 1) {
return;
}
console.info('Reading: ', file);
processedPaths[file] = 1;
try {
html = fs.readFileSync(file);
} catch (err) {
console.log(err);
return;
}
parts = splitFile(html, index + 1, dir);
parts.forEach((part, partIdx) => {
var includeCSSLink = (partIdx === 0),
data = processItem(part, includeCSSLink),
folder = `${dir}/${part.directory}`;
mkdirp.sync(folder);
fs.writeFileSync(folder + part.path, data.content || data);
// console.log('Wrote: ', folder + part.path);
});
};
function processItem(item, options) {
return PROCESS_FUNCTIONS[item.type].apply(null, arguments);
}
function processFile(item, options) {
// FIXME -- this is a simplification for now.
return processHTML(item.content, options);
}
// TODO: These are simplifications.
// Some are just ID functions
// Rethink?
function processTxt(content) {
return content;
}
function processExternal(content) {
return content;
}
// TODO: This should take in quiz HTML
function processQuiz(content) {
return content;
}
function processMarkdown(content) {
return content;
}
function processScript(item) {
return item.content;
}
function processHTMLSegment(htmlContent, transformations) {
}
/** Does the work to modify a bunch of things to prep for edX
*
* @param {Cherrio-Object} The contents of the html file
*
*/
// TODO: This needs to take in an array of functions.
// TODO: rename this processHTMLSegment
function processHTML(html, writeCSS) {
var $, outerHTML, wrap;
$ = cheerio.load(html);
// Remove EDC's inline HTML comments.
[
'.comment',
'.todo',
'.commentBig'
].forEach(sel => $(sel).remove());
// Fix some of the EDC image elements with .button
// These conflict with edX.
$('.button').removeClass('button');
// Fix image URLs
$('img').each((_, elm) => {
let $elm = $(elm);
var img_addr = $elm.attr('src') || $elm.attr('data-gifffer'),
newPath;
if (!img_addr) {
console.log('ERROR');
console.log(elm);
return;
}
let external_link = img_addr.indexOf('://') !== -1;
if (external_link) {
return;
}
newPath = util.transformURL(BASEURL, relPath, img_addr);
$elm.attr('src', newPath);
let altText = $elm.attr('alt');
if (!altText) {
console.error(`Image is missing alt text:\n\t${newPath}`);
}
// Don't copy files more than once, minor optimization
if (!processedPaths[newPath]) {
fs.writeFileSync(
`${output}/${newPath}`,
fs.readFileSync(`curriculum${img_addr}`)
);
processedPaths[newPath] = 1;
}
});
// Create Real Heading Tags
let sectionHeadings = {
'.dialog': 'Thinking Out Loud',
'.forYouToDo': 'For You To Do',
'.ifTime': 'If There Is Time...',
'.takeItFurther': 'Take It Further',
'.time': 'If you are short on time, you can skip...'
};
let secetions = Object.keys(sectionHeadings);
secetions.forEach(section => {
$(section).each((index, elm) => {
let headingText = sectionHeadings[section];
if (index > 0) {
headingText += ` (Part ${index + 1})`;
}
$(elm).prepend(`<h3 class="sectionHeading">${headingText}</h3>`)
});
});
// Fixup "Vocabulary"
let vocabSections = [
'.vocab',
'.vocabBig',
'.vocabFullWidth'
].join(', ');
$(vocabSections).each((_, elm) => {
$(elm).prepend('<span class="vocab-header">Vocabulary</span>');
});
// Fix Snap! run links.
let allURLs = $('a');
allURLs.each((index, elm) => {
let $elm = $(elm);
var href = $elm.attr('href');
if (!href) { return; }
if (!$(elm).attr('title')) {
console.log(`\tURL needs title: ${href}, "${$(elm).text()}"`);
}
// log URLs that need modified inside edx
if (href.indexOf(BASEURL) == 0 && href.indexOf('.html') > 0) {
console.log(`\tNeed to fix path in edX: ${href}`);
processCurriculumItem({
url: href,
directory: 'extra-pages/',
});
}
// Handle Snap! URLs and projects.
if ($elm.hasClass('run')) {
let newPath = util.transformURL(BASEURL, relPath, href);
$elm.attr('target', '_blank').attr('href', newPath);
// TODO: extract to copy file function
if (newPath.indexOf('://') < 0 && !processedPaths[newPath]) {
href = util.trimQuerystring(href);
fs.writeFileSync(
`${output}/${newPath}`,
fs.readFileSync(`curriculum${href}`)
);
processedPaths[newPath] = 1;
}
}
});
// wrap content in div.llab-full
// TODO: Replace with cheerio called
wrap = '<div class="llab-full">\nCONTENT\n</div>';
outerHTML = wrap.replace(/CONTENT/, $.html());
if (writeCSS) {
outerHTML = cssString + outerHTML;
}
return outerHTML;
}
/*
Return a string of the CSS contensts and any JS contents that should appear
at the top of the page.
Typically this section only needs to appear once per edX 'vertical'
*/
function HTMLPreamble() {
}
/** Split a single curriculum page into components to be in a vertical.
*
* @param {string} the raw HTML file to be processed
*/
// TODO: Refactor this to return _less_ into.
// title:
// sections: {type:, content: }
function splitFile(html, page, dir) {
var $, output, title, quizzes, qzHTML, text;
// TODO: Move this to an object that manages the count when writing files.
output = [];
$ = cheerio.load(html);
// EDC Puts an <h2> at the beginning of every page.
title = $('h2').first().text();
// Remove the title because edX flags this.
$('h2').first().remove()
// Extract JS scripts from the head.
// TODO: Move to the 'preamble'
const giffer = 'window.onload = function() {Gifffer();}';
$('script').each(function(index, elm) {
// console.log('SCRIPT ELEMENT', $(elm).parent().name);
let contents = $(elm).html();
let hasContent = !$(elm).attr('src') && contents.length;
if (contents === giffer) { return; }
if (hasContent) {
console.log('Page has custom JS element');
num = output.length + 1;
let file = page + '-' + num + '-' + title + '.js';
file = util.edXFileName(file);
output.push({
type: 'script',
title: num + '-' + title,
content: `<script type="text/javascript">\n${contents}\n</script>`,
directory: 'html/',
path: file
});
}
})
text = $('body').html()
// parse quizes separately.
quizzes = $('.assessment-data');
if (quizzes.length) {
console.log(`Found ${quizzes.length} quizzes.`);
let num = output.length + 1;
file = `${page}-${num}-${title}.html`;
quizzes.each(function(index, elm) {
qzHTML = $.html(elm); // like a call to outerHTML()
command = 'python3 code/mc_parser.py \'' + qzHTML + '\'';
xml = exec(command).toString();
var idx = text.indexOf(qzHTML);
var before = text.slice(0, idx).trim();
if (before.length) {
$before = cheerio.load(before);
num = output.length + 1;
file = page + '-' + num + '-' + title + '.html';
file = util.edXFileName(file);
output.push({
type: 'file',
title: num + '-' + title,
content: before,
directory: 'html/',
path: file
}); // part before quiz
}
num = output.length + 1;
file = page + '-' + num + '-' + title + '.xml';
file = util.edXFileName(file);
output.push({
type: 'quiz',
title: num + '-' + 'Quiz-' + title,
content: xml,
directory: 'problem/',
path: file
}); // push quiz
text = text.slice(idx + qzHTML.length);
});
text = text.trim();
// Write any remaining content.
if (text.length) {
file = util.edXFileName(file);
output.push({
type: 'file',
title: title,
content: text,
directory: 'html/',
path: file
});
}
} else {
file = `${page}-${title}.html`;
}
file = util.edXFileName(file);
output.push({
type: 'file',
title: title,
content: text,
directory: 'html/',
path: file
});
return output;
}
// TODO: Document...
module.exports = function(path, sectionName, directory) {
// Globals
GROUP_BY_LAB = false;
// util.topicPath(curFolder, path) == assuming we have some folder.
topic = fs.readFileSync(path).toString();
data = llab.parse(topic);
output = directory;
var topic, data, result;
data.topics.forEach(function(topic) {
topic.contents.some(function(section) {
var title = section.title.trim();
found = title.indexOf(sectionName) != -1;
if (found) {
tmp = parseSection(section);
result = tmp;
return true;
}
});
});
return result;
}
//////////////////////////////////////////
if (process.argv.length > 2) {
var start = 2,
end = process.argv.length;
for (var arg = start; arg < end; arg += 1) {
var item = process.argv[arg];
try {
unit = parseInt(item);
console.log(`Trying to convert Unit ${unit}`);
doWork(unit);
} catch (e) {
console.log(`Error encountered for item ${item}`);
console.log(e);
}
}
console.log('Processed all items');
process.exit(0);
}