selector.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. The selector locates elements that are suitable for annotation and enables
  6. the user to select them.
  7. On 'mouseenter' events associated with <p> elements:
  8. - if the selector is active and the element is not already annotated
  9. - find the nearest ancestor which has an id attribute: this is supposed to
  10. make identification of this element more accurate
  11. - highlight the element
  12. - bind 'click' for the element to send a message back to the add-on, including
  13. all the information associated with the anchor.
  14. */
  15. var matchedElement = null;
  16. var originalBgColor = null;
  17. var active = false;
  18. function resetMatchedElement() {
  19. if (matchedElement) {
  20. matchedElement.css('background-color', originalBgColor);
  21. matchedElement.unbind('click.annotator');
  22. }
  23. }
  24. self.on('message', function onMessage(activation) {
  25. active = activation;
  26. if (!active) {
  27. resetMatchedElement();
  28. }
  29. });
  30. function getInnerText(element) {
  31. // jQuery.text() returns content of <script> tags, we need to ignore those
  32. var list = [];
  33. element.find("*").andSelf().contents()
  34. .filter(function () {
  35. return this.nodeType == 3 && this.parentNode.tagName != "SCRIPT";
  36. })
  37. .each(function () {
  38. list.push(this.nodeValue);
  39. });
  40. return list.join("");
  41. }
  42. $('*').mouseenter(function() {
  43. if (!active || $(this).hasClass('annotated')) {
  44. return;
  45. }
  46. resetMatchedElement();
  47. ancestor = $(this).closest("[id]");
  48. matchedElement = $(this).first();
  49. originalBgColor = matchedElement.css('background-color');
  50. matchedElement.css('background-color', 'yellow');
  51. matchedElement.bind('click.annotator', function(event) {
  52. event.stopPropagation();
  53. event.preventDefault();
  54. self.port.emit('show',
  55. [
  56. document.location.toString(),
  57. ancestor.attr("id"),
  58. getInnerText(matchedElement)
  59. ]
  60. );
  61. });
  62. });
  63. $('*').mouseout(function() {
  64. resetMatchedElement();
  65. });