smartxml: fix for Document.deleteText
[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     canvasElements = require('plugins/core/canvasElements');
14
15
16
17 plugin.documentExtension.textNode.transformations = {
18     breakContent: {
19         impl: function(args) {
20             var node = this,
21                 parentDescribingNodes = [],
22                 newNodes, emptyText;
23             newNodes = node.split({offset: args.offset});
24             newNodes.second.contents()
25                 .filter(function(child) {
26                     return child.object.describesParent;
27                 })
28                 .forEach(function(child) {
29                     //child.detach();
30                     parentDescribingNodes.push(child);
31                     child.detach();
32                 });
33             [newNodes.first, newNodes.second].some(function(newNode) {
34                 if(!(newNode.contents().length)) {
35                     emptyText = newNode.append({text: ''});
36                     return true; // break
37                 }
38             });
39             parentDescribingNodes.forEach(function(node) {
40                 newNodes.first.append(node);
41             });
42             return _.extend(newNodes, {emptyText: emptyText});
43         },
44         getChangeRoot: function() {
45             return this.context.parent().parent();
46         }
47     },
48     mergeContentUp: function() {
49         /* globals Node */
50         var myPrev = this,
51             base = this,
52             ret;
53
54         if(myPrev.nodeType === Node.TEXT_NODE) {
55             if(myPrev.getIndex() > 0) {
56                 return;
57             }
58             myPrev = base = myPrev.parent();
59         }
60
61         myPrev = myPrev && myPrev.prev();
62
63         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
64             var ptr = this,
65                 next;
66             while(ptr) {
67                 next = ptr.next();
68                 if(!ret) {
69                     ret = myPrev.append(ptr);
70                 } else {
71                     myPrev.append(ptr);
72                 }
73                 
74                 ptr = next;
75             }
76             if(base !== this) {
77                 base.detach();
78             }
79             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
80         }
81     }
82 };
83
84 var undoRedoAction = function(dir) {
85     return {
86         name: dir,
87         params: {
88             document: {type: 'context', name: 'document'},
89         },
90         stateDefaults: {
91             label: dir === 'undo' ? '<-' : '->',
92             icon: 'share-alt',
93             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
94             execute: function(callback, params) {
95                 var metadata = _.last(params.document[dir+'Stack']).metadata,
96                     fragment = metadata && metadata.fragment;
97                 params.document[dir]();
98                 if(fragment) {
99                     if(!fragment.isValid()) {
100                         fragment.restoreFromPaths();
101                     }
102                     if(fragment.isValid()) {
103                         callback(fragment);
104                     }
105                 }
106                 callback();
107             },
108         },
109         getState: function(params) {
110             var allowed = params.document && !!(params.document[dir+'Stack'].length),
111                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
112                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
113             if(allowed) {
114                 var metadata = _.last(params.document[dir+'Stack']).metadata;
115                 if(metadata) {
116                     desc += ': ' + (metadata.description || gettext('unknown operation'));
117                 }
118             }
119             return {
120                 allowed: allowed,
121                 description: allowed ? desc : descEmpty
122             };
123         }
124     };
125 };
126
127 var pad = function(number) {
128     if(number < 10) {
129         number = '0' + number;
130     }
131     return number;
132 };
133
134 var commentAction = {
135     name: 'comment',
136     params: {
137         fragment: {type: 'context', name: 'fragment'}
138     },
139     stateDefaults: {
140         icon: 'comment',
141         execute: function(callback, params, editor) {
142             /* globals Node */
143             var node = params.fragment.node,
144                 action = this;
145             if(node.nodeType === Node.TEXT_NODE) {
146                 node = node.parent();
147             }
148             node.document.transaction(function() {
149                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
150                 comment.append({text:''});
151                 var user = editor.getUser(), creator;
152                 if(user) {
153                     creator = user.name;
154                     if(user.email) {
155                         creator += ' (' + user.email + ')';
156                     }
157                 } else {
158                     creator = 'anonymous';
159                 }
160
161                 var currentDate = new Date(),
162                     dt = pad(currentDate.getDate()) + '-' +
163                                 pad((currentDate.getMonth() + 1))  + '-' +
164                                 pad(currentDate.getFullYear()) + ' ' +
165                                 pad(currentDate.getHours()) + ':' +
166                                 pad(currentDate.getMinutes()) + ':' +
167                                 pad(currentDate.getSeconds());
168
169                 var metadata = comment.getMetadata();
170                 metadata.add({key: 'creator', value: creator});
171                 metadata.add({key: 'date', value: dt});
172             }, {
173                 metadata: {
174                     description: action.getState().description
175                 },
176                 success: callback
177             });
178         },
179     },
180     getState: function(params) {
181         var state = {
182             allowed: params.fragment && params.fragment.isValid() &&
183                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
184         };
185         if(state.allowed) {
186             state.description = gettext('Insert comment');
187         }
188         return state;
189     }
190 };
191
192
193 var createWrapTextAction = function(createParams) {
194     return {
195         name: createParams.name,
196         params: {
197             fragment: {type: 'context', name: 'fragment'},
198         },
199         getState: function(params) {
200             var state = {
201                     label: this.config.label
202                 },
203                 parent;
204             
205             if(!params.fragment || !params.fragment.isValid()) {
206                 return _.extend(state, {allowed: false});
207             }
208
209             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
210                 return _.extend(state, {
211                     allowed: true,
212                     toggled: true,
213                     description: createParams.unwrapDescription,
214                     execute: function(callback, params) {
215                         var node = params.fragment.node,
216                             doc = node.document,
217                             toRemove = node.getParent(createParams.klass),
218                             prefLen = 0;
219
220                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
221                             prefLen = toRemove.prev().getText().length;
222                         }
223
224                         doc.transaction(function() {
225                             var ret = toRemove.unwrapContent(),
226                                 newFragment = params.fragment;
227                             if(!newFragment.isValid()) {
228                                 newFragment =  doc.createFragment(doc.CaretFragment, {
229                                     node: ret.element1,
230                                     offset: prefLen + params.fragment.offset
231                                 });
232                             }
233                             return newFragment;
234                         }, {
235                             metadata: {
236                                 description: createParams.unwrapDescription,
237                                 fragment: params.fragment
238                             },
239                             success: callback
240                         });
241                     }
242                 });
243             }
244
245             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
246                 parent = params.fragment.startNode.parent();
247                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
248                     return _.extend(state, {allowed: false});
249                 }
250
251                 return _.extend(state, {
252                     allowed: true,
253                     description: createParams.wrapDescription,
254                     execute: function(callback, params) {
255                         params.fragment.document.transaction(function() {
256                             var parent = params.fragment.startNode.parent(),
257                                 doc = params.fragment.document,
258                                 wrapper, lastTextNode;
259                             
260                             wrapper = parent.wrapText({
261                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
262                                 offsetStart: params.fragment.startOffset,
263                                 offsetEnd: params.fragment.endOffset,
264                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
265                             });
266                                 
267                             lastTextNode = wrapper.getLastTextNode();
268                             if(lastTextNode) {
269                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
270                             }
271                         }, {
272                             metadata: {
273                                 description: createParams.wrapDescription,
274                                 fragment: params.fragment
275                             },
276                             success: callback
277                         });
278                     }
279                 });
280             }
281             return _.extend(state, {allowed: false});
282         }
283     };
284 };
285
286
287 var createLinkFromSelection = function(callback, params) {
288     var doc = params.fragment.document,
289         dialog = Dialog.create({
290             title: gettext('Create link'),
291             executeButtonText: gettext('Apply'),
292             cancelButtonText: gettext('Cancel'),
293             fields: [
294                 {label: gettext('Link'), name: 'href', type: 'input',
295                 prePasteHandler: function(text) {
296                                     return params.fragment.document.getLinkForUrl(text);
297                                 }.bind(this)
298                 }
299             ]
300         }),
301         action = this;
302     
303     dialog.on('execute', function(event) {
304         doc.transaction(function() {
305             var span =  action.params.fragment.startNode.parent().wrapText({
306                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
307                 offsetStart: params.fragment.startOffset,
308                 offsetEnd: params.fragment.endOffset,
309                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
310             }),
311                 doc = params.fragment.document;
312             event.success();
313             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
314         }, {
315             metadata: {
316                 description: action.getState().description,
317                 fragment: params.fragment
318             },
319             success: callback
320         });
321     });
322     dialog.show();
323 };
324
325 var editLink = function(callback, params) {
326     var doc = params.fragment.document,
327         link = params.fragment.node.getParent('link'),
328         dialog = Dialog.create({
329             title: gettext('Edit link'),
330             executeButtonText: gettext('Apply'),
331             cancelButtonText: gettext('Cancel'),
332             fields: [
333                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
334             ]
335         }),
336         action = this;
337     
338     dialog.on('execute', function(event) {
339         doc.transaction(function() {
340             link.setAttr('href', event.formData.href);
341             event.success();
342             return params.fragment;
343         }, {
344             metadata: {
345                 description: action.getState().description,
346                 fragment: params.fragment
347             },
348             success: callback
349         });
350     });
351     dialog.show();
352 };
353
354 var linkAction = {
355     name: 'link',
356     params: {
357         fragment: {type: 'context', name: 'fragment'}
358     },
359     stateDefaults: {
360         label: gettext('link')
361     },
362     getState: function(params) {
363         if(!params.fragment || !params.fragment.isValid()) {
364             return {allowed: false};
365         }
366
367         if(params.fragment instanceof params.fragment.TextRangeFragment) {
368             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
369                 return {allowed: false};
370             }
371             return {
372                 allowed: true,
373                 description: gettext('Create link from selection'),
374                 execute: createLinkFromSelection
375             };
376         }
377
378         if(params.fragment instanceof params.fragment.CaretFragment) {
379             if(params.fragment.node.isInside('link')) {
380                 return {
381                     allowed: true,
382                     toggled: true,
383                     description: gettext('Edit link'),
384                     execute: editLink
385                 };
386             }
387         }
388         return {allowed: false};
389     }
390 };
391
392
393 plugin.actions = [
394     undoRedoAction('undo'),
395     undoRedoAction('redo'),
396     commentAction,
397     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
398     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
399     linkAction
400 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
401
402
403
404 plugin.config = function(config) {
405     // templates.actions[0].config(config.templates);
406     templates.actions[0].params.template.options = config.templates;
407 };
408
409 plugin.canvasElements = canvasElements;
410
411 return plugin;
412
413 });