]> BookStack Code Mirror - bookstack/blob - resources/assets/js/directives.js
Merge pull request #13 from BookStackApp/master
[bookstack] / resources / assets / js / directives.js
1 "use strict";
2 const DropZone = require("dropzone");
3 const MarkdownIt = require("markdown-it");
4 const mdTasksLists = require('markdown-it-task-lists');
5 const code = require('./code');
6
7 module.exports = function (ngApp, events) {
8
9     /**
10      * Common tab controls using simple jQuery functions.
11      */
12     ngApp.directive('tabContainer', function() {
13         return {
14             restrict: 'A',
15             link: function (scope, element, attrs) {
16                 const $content = element.find('[tab-content]');
17                 const $buttons = element.find('[tab-button]');
18
19                 if (attrs.tabContainer) {
20                     let initial = attrs.tabContainer;
21                     $buttons.filter(`[tab-button="${initial}"]`).addClass('selected');
22                     $content.hide().filter(`[tab-content="${initial}"]`).show();
23                 } else {
24                     $content.hide().first().show();
25                     $buttons.first().addClass('selected');
26                 }
27
28                 $buttons.click(function() {
29                     let clickedTab = $(this);
30                     $buttons.removeClass('selected');
31                     $content.hide();
32                     let name = clickedTab.addClass('selected').attr('tab-button');
33                     $content.filter(`[tab-content="${name}"]`).show();
34                 });
35             }
36         };
37     });
38
39     /**
40      * Sub form component to allow inner-form sections to act like their own forms.
41      */
42     ngApp.directive('subForm', function() {
43         return {
44             restrict: 'A',
45             link: function (scope, element, attrs) {
46                 element.on('keypress', e => {
47                     if (e.keyCode === 13) {
48                         submitEvent(e);
49                     }
50                 });
51
52                 element.find('button[type="submit"]').click(submitEvent);
53
54                 function submitEvent(e) {
55                     e.preventDefault();
56                     if (attrs.subForm) scope.$eval(attrs.subForm);
57                 }
58             }
59         };
60     });
61
62     /**
63      * DropZone
64      * Used for uploading images
65      */
66     ngApp.directive('dropZone', [function () {
67         return {
68             restrict: 'E',
69             template: `
70             <div class="dropzone-container">
71                 <div class="dz-message">{{message}}</div>
72             </div>
73             `,
74             scope: {
75                 uploadUrl: '@',
76                 eventSuccess: '=',
77                 eventError: '=',
78                 uploadedTo: '@',
79             },
80             link: function (scope, element, attrs) {
81                 scope.message = attrs.message;
82                 if (attrs.placeholder) element[0].querySelector('.dz-message').textContent = attrs.placeholder;
83                 let dropZone = new DropZone(element[0].querySelector('.dropzone-container'), {
84                     url: scope.uploadUrl,
85                     init: function () {
86                         let dz = this;
87                         dz.on('sending', function (file, xhr, data) {
88                             let token = window.document.querySelector('meta[name=token]').getAttribute('content');
89                             data.append('_token', token);
90                             let uploadedTo = typeof scope.uploadedTo === 'undefined' ? 0 : scope.uploadedTo;
91                             data.append('uploaded_to', uploadedTo);
92                         });
93                         if (typeof scope.eventSuccess !== 'undefined') dz.on('success', scope.eventSuccess);
94                         dz.on('success', function (file, data) {
95                             $(file.previewElement).fadeOut(400, function () {
96                                 dz.removeFile(file);
97                             });
98                         });
99                         if (typeof scope.eventError !== 'undefined') dz.on('error', scope.eventError);
100                         dz.on('error', function (file, errorMessage, xhr) {
101                             console.log(errorMessage);
102                             console.log(xhr);
103                             function setMessage(message) {
104                                 $(file.previewElement).find('[data-dz-errormessage]').text(message);
105                             }
106
107                             if (xhr.status === 413) setMessage(trans('errors.server_upload_limit'));
108                             if (errorMessage.file) setMessage(errorMessage.file[0]);
109
110                         });
111                     }
112                 });
113             }
114         };
115     }]);
116
117     /**
118      * TinyMCE
119      * An angular wrapper around the tinyMCE editor.
120      */
121     ngApp.directive('tinymce', ['$timeout', function ($timeout) {
122         return {
123             restrict: 'A',
124             scope: {
125                 tinymce: '=',
126                 mceModel: '=',
127                 mceChange: '='
128             },
129             link: function (scope, element, attrs) {
130
131                 function tinyMceSetup(editor) {
132                     editor.on('ExecCommand change NodeChange ObjectResized', (e) => {
133                         let content = editor.getContent();
134                         $timeout(() => {
135                             scope.mceModel = content;
136                         });
137                         scope.mceChange(content);
138                     });
139
140                     editor.on('keydown', (event) => {
141                         scope.$emit('editor-keydown', event);
142                     });
143
144                     editor.on('init', (e) => {
145                         scope.mceModel = editor.getContent();
146                     });
147
148                     scope.$on('html-update', (event, value) => {
149                         editor.setContent(value);
150                         editor.selection.select(editor.getBody(), true);
151                         editor.selection.collapse(false);
152                         scope.mceModel = editor.getContent();
153                     });
154                 }
155
156                 scope.tinymce.extraSetups.push(tinyMceSetup);
157                 tinymce.init(scope.tinymce);
158             }
159         }
160     }]);
161
162     const md = new MarkdownIt({html: true});
163     md.use(mdTasksLists, {label: true});
164
165     /**
166      * Markdown input
167      * Handles the logic for just the editor input field.
168      */
169     ngApp.directive('markdownInput', ['$timeout', function ($timeout) {
170         return {
171             restrict: 'A',
172             scope: {
173                 mdModel: '=',
174                 mdChange: '='
175             },
176             link: function (scope, element, attrs) {
177
178                 // Codemirror Setup
179                 element = element.find('textarea').first();
180                 let cm = code.markdownEditor(element[0]);
181
182                 // Custom key commands
183                 let metaKey = code.getMetaKey();
184                 const extraKeys = {};
185                 // Insert Image shortcut
186                 extraKeys[`${metaKey}-Alt-I`] = function(cm) {
187                     let selectedText = cm.getSelection();
188                     let newText = `![${selectedText}](http://)`;
189                     let cursorPos = cm.getCursor('from');
190                     cm.replaceSelection(newText);
191                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length -1);
192                 };
193                 // Save draft
194                 extraKeys[`${metaKey}-S`] = function(cm) {scope.$emit('save-draft');};
195                 // Show link selector
196                 extraKeys[`Shift-${metaKey}-K`] = function(cm) {showLinkSelector()};
197                 // Insert Link
198                 extraKeys[`${metaKey}-K`] = function(cm) {insertLink()};
199                 // FormatShortcuts
200                 extraKeys[`${metaKey}-1`] = function(cm) {replaceLineStart('##');};
201                 extraKeys[`${metaKey}-2`] = function(cm) {replaceLineStart('###');};
202                 extraKeys[`${metaKey}-3`] = function(cm) {replaceLineStart('####');};
203                 extraKeys[`${metaKey}-4`] = function(cm) {replaceLineStart('#####');};
204                 extraKeys[`${metaKey}-5`] = function(cm) {replaceLineStart('');};
205                 extraKeys[`${metaKey}-d`] = function(cm) {replaceLineStart('');};
206                 extraKeys[`${metaKey}-6`] = function(cm) {replaceLineStart('>');};
207                 extraKeys[`${metaKey}-q`] = function(cm) {replaceLineStart('>');};
208                 extraKeys[`${metaKey}-7`] = function(cm) {wrapSelection('\n```\n', '\n```');};
209                 extraKeys[`${metaKey}-8`] = function(cm) {wrapSelection('`', '`');};
210                 extraKeys[`Shift-${metaKey}-E`] = function(cm) {wrapSelection('`', '`');};
211                 extraKeys[`${metaKey}-9`] = function(cm) {wrapSelection('<p class="callout info">', '</div>');};
212                 cm.setOption('extraKeys', extraKeys);
213
214                 // Update data on content change
215                 cm.on('change', (instance, changeObj) => {
216                     update(instance);
217                 });
218
219                 // Handle scroll to sync display view
220                 cm.on('scroll', instance => {
221                     // Thanks to http://liuhao.im/english/2015/11/10/the-sync-scroll-of-markdown-editor-in-javascript.html
222                     let scroll = instance.getScrollInfo();
223                     let atEnd = scroll.top + scroll.clientHeight === scroll.height;
224                     if (atEnd) {
225                         scope.$emit('markdown-scroll', -1);
226                         return;
227                     }
228                     let lineNum = instance.lineAtHeight(scroll.top, 'local');
229                     let range = instance.getRange({line: 0, ch: null}, {line: lineNum, ch: null});
230                     let parser = new DOMParser();
231                     let doc = parser.parseFromString(md.render(range), 'text/html');
232                     let totalLines = doc.documentElement.querySelectorAll('body > *');
233                     scope.$emit('markdown-scroll', totalLines.length);
234                 });
235
236                 // Handle image paste
237                 cm.on('paste', (cm, event) => {
238                     if (!event.clipboardData || !event.clipboardData.items) return;
239                     for (let i = 0; i < event.clipboardData.items.length; i++) {
240                         uploadImage(event.clipboardData.items[i].getAsFile());
241                     }
242                 });
243
244                 // Handle images on drag-drop
245                 cm.on('drop', (cm, event) => {
246                     event.stopPropagation();
247                     event.preventDefault();
248                     let cursorPos = cm.coordsChar({left: event.pageX, top: event.pageY});
249                     cm.setCursor(cursorPos);
250                     if (!event.dataTransfer || !event.dataTransfer.files) return;
251                     for (let i = 0; i < event.dataTransfer.files.length; i++) {
252                         uploadImage(event.dataTransfer.files[i]);
253                     }
254                 });
255
256                 // Helper to replace editor content
257                 function replaceContent(search, replace) {
258                     let text = cm.getValue();
259                     let cursor = cm.listSelections();
260                     cm.setValue(text.replace(search, replace));
261                     cm.setSelections(cursor);
262                 }
263
264                 // Helper to replace the start of the line
265                 function replaceLineStart(newStart) {
266                     let cursor = cm.getCursor();
267                     let lineContent = cm.getLine(cursor.line);
268                     let lineLen = lineContent.length;
269                     let lineStart = lineContent.split(' ')[0];
270
271                     // Remove symbol if already set
272                     if (lineStart === newStart) {
273                         lineContent = lineContent.replace(`${newStart} `, '');
274                         cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
275                         cm.setCursor({line: cursor.line, ch: cursor.ch - (newStart.length + 1)});
276                         return;
277                     }
278
279                     let alreadySymbol = /^[#>`]/.test(lineStart);
280                     let posDif = 0;
281                     if (alreadySymbol) {
282                         posDif = newStart.length - lineStart.length;
283                         lineContent = lineContent.replace(lineStart, newStart).trim();
284                     } else if (newStart !== '') {
285                         posDif = newStart.length + 1;
286                         lineContent = newStart + ' ' + lineContent;
287                     }
288                     cm.replaceRange(lineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
289                     cm.setCursor({line: cursor.line, ch: cursor.ch + posDif});
290                 }
291
292                 function wrapLine(start, end) {
293                     let cursor = cm.getCursor();
294                     let lineContent = cm.getLine(cursor.line);
295                     let lineLen = lineContent.length;
296                     let newLineContent = lineContent;
297
298                     if (lineContent.indexOf(start) === 0 && lineContent.slice(-end.length) === end) {
299                         newLineContent = lineContent.slice(start.length, lineContent.length - end.length);
300                     } else {
301                         newLineContent = `${start}${lineContent}${end}`;
302                     }
303
304                     cm.replaceRange(newLineContent, {line: cursor.line, ch: 0}, {line: cursor.line, ch: lineLen});
305                     cm.setCursor({line: cursor.line, ch: cursor.ch + (newLineContent.length - lineLen)});
306                 }
307
308                 function wrapSelection(start, end) {
309                     let selection = cm.getSelection();
310                     if (selection === '') return wrapLine(start, end);
311                     let newSelection = selection;
312                     let frontDiff = 0;
313                     let endDiff = 0;
314
315                     if (selection.indexOf(start) === 0 && selection.slice(-end.length) === end) {
316                         newSelection = selection.slice(start.length, selection.length - end.length);
317                         endDiff = -(end.length + start.length);
318                     } else {
319                         newSelection = `${start}${selection}${end}`;
320                         endDiff = start.length + end.length;
321                     }
322
323                     let selections = cm.listSelections()[0];
324                     cm.replaceSelection(newSelection);
325                     let headFirst = selections.head.ch <= selections.anchor.ch;
326                     selections.head.ch += headFirst ? frontDiff : endDiff;
327                     selections.anchor.ch += headFirst ? endDiff : frontDiff;
328                     cm.setSelections([selections]);
329                 }
330
331                 // Handle image upload and add image into markdown content
332                 function uploadImage(file) {
333                     if (file === null || file.type.indexOf('image') !== 0) return;
334                     let ext = 'png';
335
336                     if (file.name) {
337                         let fileNameMatches = file.name.match(/\.(.+)$/);
338                         if (fileNameMatches.length > 1) ext = fileNameMatches[1];
339                     }
340
341                     // Insert image into markdown
342                     let id = "image-" + Math.random().toString(16).slice(2);
343                     let placeholderImage = window.baseUrl(`/loading.gif#upload${id}`);
344                     let selectedText = cm.getSelection();
345                     let placeHolderText = `![${selectedText}](${placeholderImage})`;
346                     cm.replaceSelection(placeHolderText);
347
348                     let remoteFilename = "image-" + Date.now() + "." + ext;
349                     let formData = new FormData();
350                     formData.append('file', file, remoteFilename);
351
352                     window.$http.post('/images/gallery/upload', formData).then(resp => {
353                         replaceContent(placeholderImage, resp.data.thumbs.display);
354                     }).catch(err => {
355                         events.emit('error', trans('errors.image_upload_error'));
356                         replaceContent(placeHolderText, selectedText);
357                         console.log(err);
358                     });
359                 }
360
361                 // Show the popup link selector and insert a link when finished
362                 function showLinkSelector() {
363                     let cursorPos = cm.getCursor('from');
364                     window.showEntityLinkSelector(entity => {
365                         let selectedText = cm.getSelection() || entity.name;
366                         let newText = `[${selectedText}](${entity.link})`;
367                         cm.focus();
368                         cm.replaceSelection(newText);
369                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
370                     });
371                 }
372
373                 function insertLink() {
374                     let cursorPos = cm.getCursor('from');
375                     let selectedText = cm.getSelection() || '';
376                     let newText = `[${selectedText}]()`;
377                     cm.focus();
378                     cm.replaceSelection(newText);
379                     let cursorPosDiff = (selectedText === '') ? -3 : -1;
380                     cm.setCursor(cursorPos.line, cursorPos.ch + newText.length+cursorPosDiff);
381                 }
382
383                 // Show the image manager and handle image insertion
384                 function showImageManager() {
385                     let cursorPos = cm.getCursor('from');
386                     window.ImageManager.show(image => {
387                         let selectedText = cm.getSelection();
388                         let newText = "![" + (selectedText || image.name) + "](" + image.thumbs.display + ")";
389                         cm.focus();
390                         cm.replaceSelection(newText);
391                         cm.setCursor(cursorPos.line, cursorPos.ch + newText.length);
392                     });
393                 }
394
395                 // Update the data models and rendered output
396                 function update(instance) {
397                     let content = instance.getValue();
398                     element.val(content);
399                     $timeout(() => {
400                         scope.mdModel = content;
401                         scope.mdChange(md.render(content));
402                     });
403                 }
404                 update(cm);
405
406                 // Listen to commands from parent scope
407                 scope.$on('md-insert-link', showLinkSelector);
408                 scope.$on('md-insert-image', showImageManager);
409                 scope.$on('markdown-update', (event, value) => {
410                     cm.setValue(value);
411                     element.val(value);
412                     scope.mdModel = value;
413                     scope.mdChange(md.render(value));
414                 });
415
416             }
417         }
418     }]);
419
420     /**
421      * Markdown Editor
422      * Handles all functionality of the markdown editor.
423      */
424     ngApp.directive('markdownEditor', ['$timeout', '$rootScope', function ($timeout, $rootScope) {
425         return {
426             restrict: 'A',
427             link: function (scope, element, attrs) {
428
429                 // Editor Elements
430                 const $display = element.find('.markdown-display').first();
431                 const $insertImage = element.find('button[data-action="insertImage"]');
432                 const $insertEntityLink = element.find('button[data-action="insertEntityLink"]');
433
434                 // Prevent markdown display link click redirect
435                 $display.on('click', 'a', function(event) {
436                     event.preventDefault();
437                     window.open(this.getAttribute('href'));
438                 });
439
440                 // Editor UI Actions
441                 $insertEntityLink.click(e => {scope.$broadcast('md-insert-link');});
442                 $insertImage.click(e => {scope.$broadcast('md-insert-image');});
443
444                 // Handle scroll sync event from editor scroll
445                 $rootScope.$on('markdown-scroll', (event, lineCount) => {
446                     let elems = $display[0].children[0].children;
447                     if (elems.length > lineCount) {
448                         let topElem = (lineCount === -1) ? elems[elems.length-1] : elems[lineCount];
449                         $display.animate({
450                             scrollTop: topElem.offsetTop
451                         }, {queue: false, duration: 200, easing: 'linear'});
452                     }
453                 });
454             }
455         }
456     }]);
457
458     /**
459      * Page Editor Toolbox
460      * Controls all functionality for the sliding toolbox
461      * on the page edit view.
462      */
463     ngApp.directive('toolbox', [function () {
464         return {
465             restrict: 'A',
466             link: function (scope, elem, attrs) {
467
468                 // Get common elements
469                 const $buttons = elem.find('[toolbox-tab-button]');
470                 const $content = elem.find('[toolbox-tab-content]');
471                 const $toggle = elem.find('[toolbox-toggle]');
472
473                 // Handle toolbox toggle click
474                 $toggle.click((e) => {
475                     elem.toggleClass('open');
476                 });
477
478                 // Set an active tab/content by name
479                 function setActive(tabName, openToolbox) {
480                     $buttons.removeClass('active');
481                     $content.hide();
482                     $buttons.filter(`[toolbox-tab-button="${tabName}"]`).addClass('active');
483                     $content.filter(`[toolbox-tab-content="${tabName}"]`).show();
484                     if (openToolbox) elem.addClass('open');
485                 }
486
487                 // Set the first tab content active on load
488                 setActive($content.first().attr('toolbox-tab-content'), false);
489
490                 // Handle tab button click
491                 $buttons.click(function (e) {
492                     let name = $(this).attr('toolbox-tab-button');
493                     setActive(name, true);
494                 });
495             }
496         }
497     }]);
498
499     ngApp.directive('entityLinkSelector', [function($http) {
500         return {
501             restrict: 'A',
502             link: function(scope, element, attrs) {
503
504                 const selectButton = element.find('.entity-link-selector-confirm');
505                 let callback = false;
506                 let entitySelection = null;
507
508                 // Handle entity selection change, Stores the selected entity locally
509                 function entitySelectionChange(entity) {
510                     entitySelection = entity;
511                     if (entity === null) {
512                         selectButton.attr('disabled', 'true');
513                     } else {
514                         selectButton.removeAttr('disabled');
515                     }
516                 }
517                 events.listen('entity-select-change', entitySelectionChange);
518
519                 // Handle selection confirm button click
520                 selectButton.click(event => {
521                     hide();
522                     if (entitySelection !== null) callback(entitySelection);
523                 });
524
525                 // Show selector interface
526                 function show() {
527                     element.fadeIn(240);
528                 }
529
530                 // Hide selector interface
531                 function hide() {
532                     element.fadeOut(240);
533                 }
534                 scope.hide = hide;
535
536                 // Listen to confirmation of entity selections (doubleclick)
537                 events.listen('entity-select-confirm', entity => {
538                     hide();
539                     callback(entity);
540                 });
541
542                 // Show entity selector, Accessible globally, and store the callback
543                 window.showEntityLinkSelector = function(passedCallback) {
544                     show();
545                     callback = passedCallback;
546                 };
547
548             }
549         };
550     }]);
551
552
553     ngApp.directive('entitySelector', ['$http', '$sce', function ($http, $sce) {
554         return {
555             restrict: 'A',
556             scope: true,
557             link: function (scope, element, attrs) {
558                 scope.loading = true;
559                 scope.entityResults = false;
560                 scope.search = '';
561
562                 // Add input for forms
563                 const input = element.find('[entity-selector-input]').first();
564
565                 // Detect double click events
566                 let lastClick = 0;
567                 function isDoubleClick() {
568                     let now = Date.now();
569                     let answer = now - lastClick < 300;
570                     lastClick = now;
571                     return answer;
572                 }
573
574                 // Listen to entity item clicks
575                 element.on('click', '.entity-list a', function(event) {
576                     event.preventDefault();
577                     event.stopPropagation();
578                     let item = $(this).closest('[data-entity-type]');
579                     itemSelect(item, isDoubleClick());
580                 });
581                 element.on('click', '[data-entity-type]', function(event) {
582                     itemSelect($(this), isDoubleClick());
583                 });
584
585                 // Select entity action
586                 function itemSelect(item, doubleClick) {
587                     let entityType = item.attr('data-entity-type');
588                     let entityId = item.attr('data-entity-id');
589                     let isSelected = !item.hasClass('selected') || doubleClick;
590                     element.find('.selected').removeClass('selected').removeClass('primary-background');
591                     if (isSelected) item.addClass('selected').addClass('primary-background');
592                     let newVal = isSelected ? `${entityType}:${entityId}` : '';
593                     input.val(newVal);
594
595                     if (!isSelected) {
596                         events.emit('entity-select-change', null);
597                     }
598
599                     if (!doubleClick && !isSelected) return;
600
601                     let link = item.find('.entity-list-item-link').attr('href');
602                     let name = item.find('.entity-list-item-name').text();
603
604                     if (doubleClick) {
605                         events.emit('entity-select-confirm', {
606                             id: Number(entityId),
607                             name: name,
608                             link: link
609                         });
610                     }
611
612                     if (isSelected) {
613                         events.emit('entity-select-change', {
614                             id: Number(entityId),
615                             name: name,
616                             link: link
617                         });
618                     }
619                 }
620
621                 // Get search url with correct types
622                 function getSearchUrl() {
623                     let types = (attrs.entityTypes) ? encodeURIComponent(attrs.entityTypes) : encodeURIComponent('page,book,chapter');
624                     return window.baseUrl(`/ajax/search/entities?types=${types}`);
625                 }
626
627                 // Get initial contents
628                 $http.get(getSearchUrl()).then(resp => {
629                     scope.entityResults = $sce.trustAsHtml(resp.data);
630                     scope.loading = false;
631                 });
632
633                 // Search when typing
634                 scope.searchEntities = function() {
635                     scope.loading = true;
636                     input.val('');
637                     let url = getSearchUrl() + '&term=' + encodeURIComponent(scope.search);
638                     $http.get(url).then(resp => {
639                         scope.entityResults = $sce.trustAsHtml(resp.data);
640                         scope.loading = false;
641                     });
642                 };
643             }
644         };
645     }]);
646
647     ngApp.directive('commentReply', [function () {
648         return {
649             restrict: 'E',
650             templateUrl: 'comment-reply.html',
651             scope: {
652               pageId: '=',
653               parentId: '=',
654               parent: '='
655             },
656             link: function (scope, element) {
657                 scope.isReply = true;
658                 element.find('textarea').focus();
659                 scope.$on('evt.comment-success', function (event) {
660                     // no need for the event to do anything more.
661                     event.stopPropagation();
662                     event.preventDefault();
663                     scope.closeBox();
664                 });
665
666                 scope.closeBox = function () {
667                     element.remove();
668                     scope.$destroy();
669                 };
670             }
671         };
672     }]);
673
674     ngApp.directive('commentEdit', [function () {
675          return {
676             restrict: 'E',
677             templateUrl: 'comment-reply.html',
678             scope: {
679               comment: '='
680             },
681             link: function (scope, element) {
682                 scope.isEdit = true;
683                 element.find('textarea').focus();
684                 scope.$on('evt.comment-success', function (event, commentId) {
685                    // no need for the event to do anything more.
686                    event.stopPropagation();
687                    event.preventDefault();
688                    if (commentId === scope.comment.id && !scope.isNew) {
689                        scope.closeBox();
690                    }
691                 });
692
693                 scope.closeBox = function () {
694                     element.remove();
695                     scope.$destroy();
696                 };
697             }
698         };
699     }]);
700
701
702     ngApp.directive('commentReplyLink', ['$document', '$compile', function ($document, $compile) {
703         return {
704             scope: {
705                 comment: '='
706             },
707             link: function (scope, element, attr) {
708                 element.on('$destroy', function () {
709                     element.off('click');
710                     scope.$destroy();
711                 });
712
713                 element.on('click', function (e) {
714                     e.preventDefault();
715                     var $container = element.parents('.comment-actions').first();
716                     if (!$container.length) {
717                         console.error('commentReplyLink directive should be placed inside a container with class comment-box!');
718                         return;
719                     }
720                     if (attr.noCommentReplyDupe) {
721                         removeDupe();
722                     }
723
724                     compileHtml($container, scope, attr.isReply === 'true');
725                 });
726             }
727         };
728
729         function compileHtml($container, scope, isReply) {
730             let lnkFunc = null;
731             if (isReply) {
732                 lnkFunc = $compile('<comment-reply page-id="comment.pageId" parent-id="comment.id" parent="comment"></comment-reply>');
733             } else {
734                 lnkFunc = $compile('<comment-edit comment="comment"></comment-add>');
735             }
736             var compiledHTML = lnkFunc(scope);
737             $container.append(compiledHTML);
738         }
739
740         function removeDupe() {
741             let $existingElement = $document.find('.comments-list comment-reply, .comments-list comment-edit');
742             if (!$existingElement.length) {
743                 return;
744             }
745
746             $existingElement.remove();
747         }
748     }]);
749
750     ngApp.directive('commentDeleteLink', ['$window', function ($window) {
751         return {
752             controller: 'CommentDeleteController',
753             scope: {
754                 comment: '='
755             },
756             link: function (scope, element, attr, ctrl) {
757
758                 element.on('click', function(e) {
759                     e.preventDefault();
760                     var resp = $window.confirm(trans('entities.comment_delete_confirm'));
761                     if (!resp) {
762                         return;
763                     }
764
765                     ctrl.delete(scope.comment);
766                 });
767             }
768         };
769     }]);
770 };