editor: fix - better handle node removal in various views
[fnpeditor.git] / src / editor / plugins / core / core.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals gettext */
5
6 var _ = require('libs/underscore'),
7     templates = require('plugins/core/templates'),
8     footnote = require('plugins/core/footnote'),
9     switchTo = require('plugins/core/switch'),
10     lists = require('plugins/core/lists'),
11     plugin = {name: 'core', actions: [], canvas: {}, documentExtension: {textNode: {}}},
12     Dialog = require('views/dialog/dialog');
13
14
15 plugin.documentExtension.textNode.transformations = {
16     breakContent: {
17         impl: function(args) {
18             var node = this,
19                 newNodes, emptyText;
20             newNodes = node.split({offset: args.offset});
21             [newNodes.first, newNodes.second].some(function(newNode) {
22                 if(!(newNode.contents().length)) {
23                     emptyText = newNode.append({text: ''});
24                     return true; // break
25                 }
26             });
27             return _.extend(newNodes, {emptyText: emptyText});
28         },
29         getChangeRoot: function() {
30             return this.context.parent().parent();
31         }
32     },
33     mergeContentUp: function() {
34         var myPrev = this.prev(),
35             ret;
36
37         if(myPrev) {
38             ret = myPrev.append(this);
39             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
40         } else {
41             var range = this.parent().unwrapContent();
42             return {node: range.element1, offset: 0};
43         }
44     }
45 };
46
47 var undoRedoAction = function(dir) {
48     return {
49         name: dir,
50         params: {
51             document: {type: 'context', name: 'document'},
52         },
53         stateDefaults: {
54             label: dir === 'undo' ? '<-' : '->',
55             icon: 'share-alt',
56             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
57             execute: function(params) {
58                 params.document[dir]();
59             },
60         },
61         getState: function(params) {
62             var allowed = params.document && !!(params.document[dir+'Stack'].length),
63                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
64                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
65             if(allowed) {
66                 desc += ': ' + (_.last(params.document[dir+'Stack']).metadata || gettext('unknown operation'));
67             }
68             return {
69                 allowed: allowed,
70                 description: allowed ? desc : descEmpty
71             };
72         }
73     };
74 };
75
76 var pad = function(number) {
77     if(number < 10) {
78         number = '0' + number;
79     }
80     return number;
81 };
82
83 var commentAction = {
84     name: 'comment',
85     params: {
86         fragment: {type: 'context', name: 'fragment'}
87     },
88     stateDefaults: {
89         icon: 'comment',
90         execute: function(params, editor) {
91             /* globals Node */
92             var node = params.fragment.node;
93             if(node.nodeType === Node.TEXT_NODE) {
94                 node = node.parent();
95             }
96             node.document.transaction(function() {
97                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
98                 comment.append({text:''});
99                 var user = editor.getUser(), creator;
100                 if(user) {
101                     creator = user.name;
102                     if(user.email) {
103                         creator += ' (' + user.email + ')';
104                     }
105                 } else {
106                     creator = 'anonymous';
107                 }
108
109                 var currentDate = new Date(),
110                     dt = pad(currentDate.getDate()) + '-' +
111                                 pad((currentDate.getMonth() + 1))  + '-' +
112                                 pad(currentDate.getFullYear()) + ' ' +
113                                 pad(currentDate.getHours()) + ':' +
114                                 pad(currentDate.getMinutes()) + ':' +
115                                 pad(currentDate.getSeconds());
116
117                 var metadata = comment.getMetadata();
118                 metadata.add({key: 'creator', value: creator});
119                 metadata.add({key: 'date', value: dt});
120             });
121         },
122     },
123     getState: function(params) {
124         var state = {
125             allowed: params.fragment && params.fragment.isValid() &&
126                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
127         };
128         if(state.allowed) {
129             state.description = gettext('Insert comment after current node');
130         }
131         return state;
132     }
133 };
134
135
136 var createWrapTextAction = function(createParams) {
137     return {
138         name: createParams.name,
139         params: {
140             fragment: {type: 'context', name: 'fragment'},
141         },
142         getState: function(params) {
143             var state = {
144                     label: this.config.label
145                 },
146                 parent;
147             
148             if(
149                 !params.fragment || !params.fragment.isValid() ||
150                 !(params.fragment instanceof params.fragment.TextRangeFragment) ||
151                 !params.fragment.hasSiblingBoundries()) {
152                     return _.extend(state, {allowed: false});
153             }
154             
155             parent = params.fragment.startNode.parent();
156             if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
157                 return _.extend(state, {allowed: false});
158             }
159
160             return _.extend(state, {
161                 allowed: true,
162                 execute: function(params) {
163                     params.fragment.document.transaction(function() {
164                         var parent = params.fragment.startNode.parent();
165                         return parent.wrapText({
166                             _with: {tagName: 'span', attrs: {'class': createParams.klass}},
167                             offsetStart: params.fragment.startOffset,
168                             offsetEnd: params.fragment.endOffset,
169                             textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
170                         });
171                     });
172                 }
173             });
174         }
175     };
176 };
177
178
179 var createLinkFromSelection = function(params) {
180     var doc = params.fragment.document,
181         dialog = Dialog.create({
182             title: gettext('Create link'),
183             executeButtonText: gettext('Apply'),
184             cancelButtonText: gettext('Cancel'),
185             fields: [
186                 {label: gettext('Link'), name: 'href', type: 'input'}
187             ]
188         });
189     
190     dialog.on('execute', function(event) {
191         doc.transaction(function() {
192             var span =  params.fragment.startNode.parent().wrapText({
193                 _with: {tagName: 'span', attrs: {'class': 'link'}},
194                 offsetStart: params.fragment.startOffset,
195                 offsetEnd: params.fragment.endOffset,
196                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
197             });
198             span.setAttr('href', event.formData.href);
199             event.success();
200             return span;
201         });
202     });
203     dialog.show();
204 };
205
206 var editLink = function(params) {
207     var doc = params.fragment.document,
208         link = params.fragment.node.getParent('link'),
209         dialog = Dialog.create({
210             title: gettext('Edit link'),
211             executeButtonText: gettext('Apply'),
212             cancelButtonText: gettext('Cancel'),
213             fields: [
214                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
215             ]
216         });
217     
218     dialog.on('execute', function(event) {
219         doc.transaction(function() {
220             link.setAttr('href', event.formData.href);
221             event.success();
222         });
223     });
224     dialog.show();
225 };
226
227 var linkAction = {
228     name: 'link',
229     params: {
230         fragment: {type: 'context', name: 'fragment'}
231     },
232     stateDefaults: {
233         label: gettext('link')
234     },
235     getState: function(params) {
236         if(!params.fragment || !params.fragment.isValid()) {
237             return {allowed: false};
238         }
239
240         if(params.fragment instanceof params.fragment.TextRangeFragment) {
241             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
242                 return {allowed: false};
243             }
244             return {
245                 allowed: true,
246                 description: gettext('Create link from selection'),
247                 execute: createLinkFromSelection
248             };
249         }
250
251         if(params.fragment instanceof params.fragment.CaretFragment) {
252             if(params.fragment.node.isInside('link')) {
253                 return {allowed: true, toggled: true, execute: editLink};
254             }
255         }
256         return {allowed: false};
257     }
258 };
259
260
261 plugin.actions = [
262     undoRedoAction('undo'),
263     undoRedoAction('redo'),
264     commentAction,
265     createWrapTextAction({name: 'emphasis', klass: 'emp'}),
266     createWrapTextAction({name: 'cite', klass: 'cite'}),
267     linkAction
268 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
269
270
271
272 plugin.config = function(config) {
273     // templates.actions[0].config(config.templates);
274     templates.actions[0].params.template.options = config.templates;
275 };
276
277 return plugin;
278
279 });