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