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