Skip to content

Instantly share code, notes, and snippets.

@TimothyJones
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TimothyJones/b48dfd4fe3e7666ac815 to your computer and use it in GitHub Desktop.
Save TimothyJones/b48dfd4fe3e7666ac815 to your computer and use it in GitHub Desktop.
Alveo document annotations highlighting
// This gist provides an example of doing highlighting for
// Alveo annotations within a document displayed in a <pre> tag.
// It can be used at display time in the browser (with the right API calls).
// Although jQuery is used, it's not required except for the page update at the end
// Insert method for strings
String.prototype.insert = function (index, string) {
if (index > 0) {
if (index > this.length) {
return this + string;
}
return this.substring(0, index) + string + this.substring(index, this.length);
}
else
return string + this;
};
$(function() {
// ****** Preconditions *******
// Ultimately, these bits will be replaced by API requests
var txt = /* The source document */
var ann = /* the annotations json object for this doucment */
// This code assumes that annotations are character offsets not byte offsets
// ******* Config *********
var startTag = "<mark>"; // Start tag to highlight with
var endTag = "</mark>"; // End tag to highlight with
var label = "overlap"; // Label to highlight
// Code below
// These store the locations in the source document for the start and end of each
// offset annotation
var startTags = [];
var endTags = [];
// Returns the translated position for a particular offset from the source document.
// Takes the document location for the annotation, and returns the place in the
// current document (once currently inserted tags are accounted for).
var posFor = function(pos) {
var offset = 0;
for(var i = 0; i < startTags.length ; i++) {
if(startTags[i] <= pos ) {
offset += startTag.length;
}
}
for(var i = 0; i < endTags.length ; i++) {
if(endTags[i] <= pos ) {
offset += endTag.length;
}
}
return pos + offset;
}
// Iterate over all the annotations
ann["alveo:annotations"].forEach(function(val) {
if(val.label == label) {
var start = parseInt(val.start,10);
var end = parseInt(val.end,10);
txt = txt.insert(posFor(start),startTag); // Insert the start tag
startTags.push(start); // Remember the location
txt = txt.insert(posFor(end),endTag);
endTags.push(end);
}
});
// Update the document in the view
$("pre").html(txt); // needs to be a pre element
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment