Skip to content
Snippets Groups Projects
Commit 318f992f authored by Sven Kästle's avatar Sven Kästle
Browse files

feat: hovering over an annotation will highlight the corresponding text

parent 022c3600
No related branches found
No related tags found
No related merge requests found
$(document).ready(function() { // set color, userId and targetId
var userId = 11;
var targetId = 200;
var color = getRandomColor();
// declare document text
var documentText;
console.log("start ready function"); /**
* This function will fire when the DOM is ready
*/
$(document).ready(function() {
/**
* Context menu handler
*/
$.contextMenu({ $.contextMenu({
selector: '.context-menu-one', selector: '.context-menu-one',
callback: function(key, options) { callback: function(key, options) {
console.log("start annotation"); // close context menu
window.close;
var text = generateId(6); // initialize selected body
var user = generateId(1).toUpperCase(); var body = getSelectedText();
var color = getRandomColor();
$.fn.addAnnotation(user, text, color); // if user selected something
if (body.length > 0) {
// annotationPostRequest
var request = {
userId: userId,
targetId: targetId,
body: body,
startCharacter: window.getSelection().getRangeAt(0).startOffset,
endCharacter: window.getSelection().getRangeAt(0).endOffset
};
console.log(request);
createAnnotation(request, function(response) {
// display the new annotation
displayAnnotation(response);
});
}
window.close;
}, },
items: { items: {
"annotation": {name: "Annotation", icon: "edit"} "annotation": {name: "Annotation", icon: "edit"}
} }
}); });
/*
* PAGE LOADED
*/
documentText = $('#documentText').html();
// fetch annotations from server on page start
getAnnotations(targetId, function (response) {
// iterate over annotations and display each
$.each(response, function (i, annotation) {
displayAnnotation(annotation);
})
});
$('.context-menu-one').on('click', function(e){ });
console.log('clicked', this);
})
$.fn.addAnnotation = function(title, text, color) {
var list = $('#annotations')
var selection = getSelectedText()
if (selection.length > 0) { /**
* POST: Save an annotation in the database
*
* @param annotationPostRequest
* @param responseHandler
*/
function createAnnotation(annotationPostRequest, responseHandler) {
var url = "http://localhost:8080/rest/annotations/";
var json = JSON.stringify(annotationPostRequest);
$.ajax({
url: url,
type: "POST",
data: json,
contentType: "application/json",
dataType: "json",
success: function (response) {
responseHandler(response);
}
});
}
var replacement = $('<span></span>').css('background-color', color).html(selection); /**
* PATCH: Alter an annotation
*
* @param annotationPatchRequest
* @param responseHandler
*/
function alterAnnotation(id, annotationPatchRequest, responseHandler) {
var url = "http://localhost:8080/rest/annotations/" + id;
var json = JSON.stringify(annotationPatchRequest);
$.ajax({
url: url,
type: "PATCH",
data: json,
contentType: "application/json",
dataType: "json",
success: function (response) {
responseHandler(response);
}
});
}
var replacementHtml = $('<div>').append(replacement.clone()).remove().html(); /**
* GET: Get all annotations for a specific target
*
*
* @param targetId
* @param responseHandler
*/
function getAnnotations(targetId, responseHandler) {
var url = "http://localhost:8080/rest/annotations/target/" + targetId;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function (response) {
// sort the responding annotations by timestamp (DESC)
response.sort(function (a, b) {
return a.timestamp - b.timestamp;
});
// handle the response
responseHandler(response);
}
});
}
$('#hiho').html( $('#hiho').html().replace(selection, replacementHtml) ); /**
* Display annotation in the list
*
* @param annotation the annotation to be displayed
*/
function displayAnnotation(annotation) {
// fetch list of annotations
var list = $('#annotations')
// insert spacing if we need one
if ($('#annotations li').filter( ".listelement" ).length > 0) {
list.prepend(
$('<li>').attr('class', 'spacing')
)
}
if ($('#annotations li').filter( ".listelement" ).length > 0) { // insert annotation card
list.prepend( list.prepend(
$('<li>').attr('class', 'spacing') $('<li>').mouseenter(function () {
addHighlightedText(annotation.startCharacter, annotation.endCharacter);
}).mouseleave(function () {
deleteHighlightedText();
}).data(annotation).attr('class', 'listelement').attr('id', annotation.id).append(
$('<div>').attr('class', 'card').append(
$('<div>').attr('class', 'cardAvatar').css('background-color', color).append(
$('<b>').append(annotation.id.substr(0,1))
) )
} ).append(
$('<div>').attr('class', 'cardContent').append(
list.prepend( $('<span>').append(annotation.body.substring(0, 5) + "...")
$('<li>').attr('class', 'listelement').append(
$('<div>').attr('class', 'card').append(
$('<div>').attr('class', 'cardAvatar').css('background-color', color).append(
$('<b>').append(title)
)
).append(
$('<div>').attr('class', 'cardContent').append(
$('<span>').append(selection.substring(0, 5) + "...")
)
)
) )
); )
} )
} );
}
console.log("end ready function"); /**
}); * Add a highlighted text at specific position
*
* @param startCharacter the offset of the start character
* @param endCharacter the offset of the end character
*/
function addHighlightedText(startCharacter, endCharacter) {
// create <span> tag with the annotated text
var replacement = $('<span></span>').css('background-color', color).html(documentText.slice(startCharacter, endCharacter));
// wrap an <p> tag around the replacement, get its parent (the <p>) and ask for the html
var replacementHtml = replacement.wrap('<p/>').parent().html();
// insert the replacementHtml
var newDocument = documentText.slice(0, startCharacter) + replacementHtml + documentText.slice(endCharacter);
// set new document text
$('#documentText').html(newDocument);
}
/**
* Restore the base text
*/
function deleteHighlightedText() {
$('#documentText').html(documentText);
}
/**
* Get the text value of the selected text
*
* @returns {*} the text
*/
function getSelectedText() { function getSelectedText() {
if(window.getSelection){ if(window.getSelection){
return window.getSelection().toString(); return window.getSelection().toString();
...@@ -74,20 +210,15 @@ function getSelectedText() { ...@@ -74,20 +210,15 @@ function getSelectedText() {
} }
} }
function generateId(length) { /**
var id = ""; * Generate a random color of the format 'rgb(r, g, b)'
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; *
* @returns {string} the new color
for (var i = 0; i < length; i++) { */
id += possible.charAt(Math.floor(Math.random() * possible.length));
}
return id;
}
function getRandomColor() { function getRandomColor() {
return 'rgb(' + return 'rgb(' +
(Math.floor(Math.random()*56)+170) + ', ' + (Math.floor(Math.random()*56)+170) + ', ' +
(Math.floor(Math.random()*56)+170) + ', ' + (Math.floor(Math.random()*56)+170) + ', ' +
(Math.floor(Math.random()*56)+170) + (Math.floor(Math.random()*56)+170) +
')'; ')';
} }
\ No newline at end of file
...@@ -59,7 +59,7 @@ ...@@ -59,7 +59,7 @@
<div class="mainpage"> <div class="mainpage">
<div class="leftcolumn"> <div class="leftcolumn">
<div class="leftcontent "> <div class="leftcontent ">
<div class="text context-menu-one" id="hiho"> <div class="text context-menu-one" id="documentText">
Style never met and those among great. At no or september sportsmen he perfectly happiness attending. Depending listening delivered off new she procuring satisfied sex existence. Person plenty answer to exeter it if. Law use assistance especially resolution cultivated did out sentiments unsatiable. Way necessary had intention happiness but september delighted his curiosity. Furniture furnished or on strangers neglected remainder engrossed. Shot what able cold new the see hold. Friendly as an betrayed formerly he. Morning because as to society behaved moments. Put ladies design mrs sister was. Play on hill felt john no gate. Am passed figure to marked in. Prosperous middletons is ye inhabiting as assistance me especially. For looking two cousins regular amongst. Style never met and those among great. At no or september sportsmen he perfectly happiness attending. Depending listening delivered off new she procuring satisfied sex existence. Person plenty answer to exeter it if. Law use assistance especially resolution cultivated did out sentiments unsatiable. Way necessary had intention happiness but september delighted his curiosity. Furniture furnished or on strangers neglected remainder engrossed. Shot what able cold new the see hold. Friendly as an betrayed formerly he. Morning because as to society behaved moments. Put ladies design mrs sister was. Play on hill felt john no gate. Am passed figure to marked in. Prosperous middletons is ye inhabiting as assistance me especially. For looking two cousins regular amongst.
</div> </div>
</div> </div>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment