Skip to content

Commit

Permalink
Implement find()
Browse files Browse the repository at this point in the history
  • Loading branch information
jdormit committed May 30, 2017
1 parent 176125e commit 3041e80
Showing 1 changed file with 72 additions and 9 deletions.
81 changes: 72 additions & 9 deletions src/section.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,80 @@ class Section {
return rendered;
}

/**
* Find a string in a section
* TODO: need reimplementation from v0.2
* @param {string} query [description]
* @return {[type]} [description]
*/
find(){
/**
* Find a string in a section
* @param {string} _query The query string to find
* @return {object[]} A list of matches, with form {cfi, excerpt}
*/
find(_query){
var section = this;
var matches = [];
var query = _query.toLowerCase();
var find = function(node){
var text = node.textContent.toLowerCase();
var range = section.document.createRange();
var cfi;
var pos;
var last = -1;
var excerpt;
var limit = 150;

}
while (pos != -1) {
// Search for the query
pos = text.indexOf(query, last + 1);

/**
if (pos != -1) {
// We found it! Generate a CFI
range = section.document.createRange();
range.setStart(node, pos);
range.setEnd(node, pos + query.length);

cfi = section.cfiFromRange(range);

// Generate the excerpt
if (node.textContent.length < limit) {
excerpt = node.textContent;
}
else {
excerpt = node.textContent.substring(pos - limit/2, pos + limit/2);
excerpt = "..." + excerpt + "...";
}

// Add the CFI to the matches list
matches.push({
cfi: cfi,
excerpt: excerpt
});
}

last = pos;
}
};

section.textSprint(section.document, function(node) {
find(node);
});

return matches;
};

textSprint(root, func) {
var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: function(node) {
if (node.data && ! /^\s*$/.test(node.data)) {
return NodeFilter.FILTER_ACCEPT;
} else {
return NodeFilter.FILTER_REJECT;
}
}
}, false);
var node;
while ((node = treeWalker.nextNode())) {
func(node);
}
};

/**
* Reconciles the current chapters layout properies with
* the global layout properities.
* @param {object} global The globa layout settings object, chapter properties string
Expand Down

0 comments on commit 3041e80

Please sign in to comment.