notePreviewer.directive.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // TODO: 使用一个 div 容器作为 previewer,而不是两个
  2. angular.module('kityminderEditor')
  3. .directive('notePreviewer', ['$sce', 'valueTransfer', function($sce, valueTransfer) {
  4. return {
  5. restrict: 'A',
  6. templateUrl: 'ui/directive/notePreviewer/notePreviewer.html',
  7. link: function(scope, element) {
  8. var minder = scope.minder;
  9. var $container = element.parent();
  10. var $previewer = element.children();
  11. scope.showNotePreviewer = false;
  12. marked.setOptions({
  13. gfm: true,
  14. tables: true,
  15. breaks: true,
  16. pedantic: false,
  17. sanitize: true,
  18. smartLists: true,
  19. smartypants: false
  20. });
  21. var previewTimer;
  22. minder.on('shownoterequest', function(e) {
  23. previewTimer = setTimeout(function() {
  24. preview(e.node, e.keyword);
  25. }, 300);
  26. });
  27. minder.on('hidenoterequest', function() {
  28. clearTimeout(previewTimer);
  29. scope.showNotePreviewer = false;
  30. //scope.$apply();
  31. });
  32. var previewLive = false;
  33. $(document).on('mousedown mousewheel DOMMouseScroll', function() {
  34. if (!previewLive) return;
  35. scope.showNotePreviewer = false;
  36. scope.$apply();
  37. });
  38. element.on('mousedown mousewheel DOMMouseScroll', function(e) {
  39. e.stopPropagation();
  40. });
  41. function preview(node, keyword) {
  42. var icon = node.getRenderer('NoteIconRenderer').getRenderShape();
  43. var b = icon.getRenderBox('screen');
  44. var note = node.getData('note');
  45. $previewer[0].scrollTop = 0;
  46. var html = marked(note);
  47. if (keyword) {
  48. html = html.replace(new RegExp('(' + keyword + ')', 'ig'), '<span class="highlight">$1</span>');
  49. }
  50. scope.noteContent = $sce.trustAsHtml(html);
  51. scope.$apply(); // 让浏览器重新渲染以获取 previewer 提示框的尺寸
  52. var cw = $($container[0]).width();
  53. var ch = $($container[0]).height();
  54. var pw = $($previewer).outerWidth();
  55. var ph = $($previewer).outerHeight();
  56. var x = b.cx - pw / 2 - $container[0].offsetLeft;
  57. var y = b.bottom + 10 - $container[0].offsetTop;
  58. if (x < 0) x = 10;
  59. if (x + pw > cw) x = b.left - pw - 10 - $container[0].offsetLeft;
  60. if (y + ph > ch) y = b.top - ph - 10 - $container[0].offsetTop;
  61. scope.previewerStyle = {
  62. 'left': Math.round(x) + 'px',
  63. 'top': Math.round(y) + 'px'
  64. };
  65. scope.showNotePreviewer = true;
  66. var view = $previewer[0].querySelector('.highlight');
  67. if (view) {
  68. view.scrollIntoView();
  69. }
  70. previewLive = true;
  71. scope.$apply();
  72. }
  73. }
  74. }
  75. }]);