summaryrefslogtreecommitdiffstats
path: root/lib/parse/lex.js
diff options
context:
space:
mode:
authorAaron O'Mullan <aaron.omullan@friendco.de>2014-04-12 01:50:48 -0700
committerAaron O'Mullan <aaron.omullan@friendco.de>2014-04-12 01:50:48 -0700
commit6173fb76ad3d9ad9357389021aa347df3b1bde92 (patch)
treeb73929b036c03ce961feee64e9e1044cdffb12d6 /lib/parse/lex.js
parentca25511d7a7ca436bf20d12bd847328faae987d6 (diff)
downloadgitbook-6173fb76ad3d9ad9357389021aa347df3b1bde92.zip
gitbook-6173fb76ad3d9ad9357389021aa347df3b1bde92.tar.gz
gitbook-6173fb76ad3d9ad9357389021aa347df3b1bde92.tar.bz2
Refactor, document, improve section type detection
Especially for quiz types
Diffstat (limited to 'lib/parse/lex.js')
-rw-r--r--lib/parse/lex.js63
1 files changed, 45 insertions, 18 deletions
diff --git a/lib/parse/lex.js b/lib/parse/lex.js
index a9ff1ba..813dd33 100644
--- a/lib/parse/lex.js
+++ b/lib/parse/lex.js
@@ -18,37 +18,64 @@ function splitSections(nodes) {
}
function isQuizNode(node) {
- return /^[(\[][ x][)\]]/.test(node.text || node);
+ return (/^[(\[][ x][)\]]/).test(node.text || node);
}
-// What is the type of this section
-function sectionType(nodes, idx) {
+function isExercise(nodes) {
var codeType = { type: 'code' };
// Number of code nodes in section
var len = _.filter(nodes, codeType).length;
- if(
+ return (
// Got 3 or 4 code blocks
(len === 3 || len === 4) &&
// Ensure all nodes are at the end
_.all(_.last(nodes, len), codeType)
- )
- {
- return 'exercise';
+ );
+}
+
+function isQuiz(nodes) {
+ if (nodes.length < 3) {
+ return false;
}
- if (nodes.length > 2) {
- var potentialQuizNodes = nodes.slice(nodes[0].type === 'paragraph' ? 1 : 0);
- if (_.some(potentialQuizNodes, { type: 'blockquote_start' })) {
- for (var i = 0; i < potentialQuizNodes.length; i++) {
- var node = potentialQuizNodes[i];
- if ((node.type === 'list_item_start' && isQuizNode(potentialQuizNodes[i+1])) ||
- (node.type === 'table' && _.every(potentialQuizNodes[i].cells[0].slice(1), isQuizNode))){
- return 'quiz'
- }
- }
- }
+ // Support having a first paragraph block
+ // before our series of questions
+ var quizNodes = nodes.slice(nodes[0].type === 'paragraph' ? 1 : 0);
+
+ // No questions
+ if (!_.some(quizNodes, { type: 'blockquote_start' })) {
+ return false;
+ }
+
+ // Check if section has list of questions
+ // or table of questions
+ var listIdx = _.findIndex(quizNodes, { type: 'list_item_start' });
+ var tableIdx = _.findIndex(quizNodes, { type: 'table' });
+
+ if(
+ // List of questions
+ listIdx !== -1 && isQuizNode(quizNodes[listIdx + 1]) &&
+
+ // Table of questions
+ (
+ tableIdx !== -1 &&
+ _.every(quizNodes[tableIdx].cells[0].slice(1), isQuizNode)
+ )
+ ) {
+ return true;
+ }
+
+ return false;
+}
+
+// What is the type of this section
+function sectionType(nodes, idx) {
+ if(isExercise(nodes)) {
+ return 'exercise';
+ } else if(isQuiz(nodes)) {
+ return 'quiz';
}
return 'normal';