fdb60e1c26435bec06d34307894972c8438fc24f
[fnpeditor.git] / src / editor / plugins / core / links / linkElement.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals gettext */
5
6
7 var $ = require('libs/jquery'),
8     _ = require('libs/underscore'),
9     genericElement = require('modules/documentCanvas/canvas/genericElement'),
10     Dialog = require('views/dialog/dialog'),
11     boxTemplate = require('libs/text!./box.html'),
12     linkElement = Object.create(genericElement);
13
14
15 _.extend(linkElement, {
16     init: function() {
17         genericElement.init.call(this);
18         _.bindAll(this, 'changeLink', 'deleteLink');
19
20         var linkText = this.wlxmlNode.getAttr('href'),
21             linkUrl = this.getUrl(linkText);
22
23         this.box = $(_.template(boxTemplate)({text: linkText, url: linkUrl}));
24         this.box.find('.change').on('click', this.changeLink);
25         this.box.find('.delete').on('click', this.deleteLink);
26         this.box.hide();
27         this.addWidget(this.box);
28     },
29     markAsCurrent: function(toggle) {
30         this.box.toggle(toggle);
31     },
32     onNodeAttrChange: function(event) {
33         if(event.meta.attr === 'href') {
34             var link = this.box.find('[link]');
35             link.text(event.meta.newVal);
36             link.attr('href', this.getUrl(event.meta.newVal));
37         }
38     },
39
40     changeLink: function(e) {
41         var el = this,
42             dialog = Dialog.create({
43             title: gettext('Edit link'),
44             executeButtonText: gettext('Apply'),
45             cancelButtonText: gettext('Cancel'),
46             fields: [
47                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: el.wlxmlNode.getAttr('href')}
48             ]
49         });
50         e.preventDefault();
51         e.stopPropagation();
52
53         dialog.on('execute', function(event) {
54             el.wlxmlNode.document.transaction(function() {
55                 el.wlxmlNode.setAttr('href', event.formData.href);
56                 event.success();
57             }, {
58                 metadata: {
59                     description: gettext('Edit link')
60                 }
61             });
62         });
63         dialog.show();
64     },
65
66     deleteLink: function() {
67         var el = this;
68         el.wlxmlNode.document.transaction(function() {
69             el.wlxmlNode.unwrapContent();
70         }, {
71             metadata: {
72                 description: gettext('Remove link')
73             }
74         });
75     },
76
77     getUrl: function(link) {
78         var pattern = /^[a-z]*:\/\//g;
79         if(!pattern.test(link)) {
80             link = 'http://' + link;
81         }
82         return this.wlxmlNode.document.getUrlForLink(link);
83     }
84 });
85
86 return linkElement;
87
88 });