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