matcher.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. Locate anchors for annotations and prepare to display the annotations.
  6. For each annotation, if its URL matches this page,
  7. - get the ancestor whose ID matches the ID in the anchor
  8. - look for a <p> element whose content contains the anchor text
  9. That's considered a match. Then we:
  10. - highlight the anchor element
  11. - add an 'annotated' class to tell the selector to skip this element
  12. - embed the annottion text as a new attribute
  13. For all annotated elements:
  14. - bind 'mouseenter' and 'mouseleave' events to the element, to send 'show'
  15. and 'hide' messages back to the add-on.
  16. */
  17. self.on('message', function onMessage(annotations) {
  18. annotations.forEach(
  19. function(annotation) {
  20. if(annotation.url == document.location.toString()) {
  21. createAnchor(annotation);
  22. }
  23. });
  24. $('.annotated').css('border', 'solid 3px yellow');
  25. $('.annotated').bind('mouseenter', function(event) {
  26. self.port.emit('show', $(this).attr('annotation'));
  27. event.stopPropagation();
  28. event.preventDefault();
  29. });
  30. $('.annotated').bind('mouseleave', function() {
  31. self.port.emit('hide');
  32. });
  33. });
  34. function createAnchor(annotation) {
  35. annotationAnchorAncestor = $('#' + annotation.ancestorId)[0] || document.body;
  36. annotationAnchor = $(annotationAnchorAncestor).parent().find(
  37. ':contains("' + annotation.anchorText + '")').last();
  38. annotationAnchor.addClass('annotated');
  39. annotationAnchor.attr('annotation', annotation.annotationText);
  40. }