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