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