don't ask on unload unless document is dirty
[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             }
126
127             return _.extend(newNodes, {emptyText: emptyText});
128         }
129     },
130     mergeContentUp: function() {
131         /* globals Node */
132         var myPrev = this,
133             base = this,
134             ret;
135
136         if(myPrev.nodeType === Node.TEXT_NODE) {
137             if(myPrev.getIndex() > 0) {
138                 return;
139             }
140             myPrev = base = myPrev.parent();
141         }
142
143         myPrev = myPrev && myPrev.prev();
144
145         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
146             var ptr = this,
147                 next;
148             while(ptr) {
149                 next = ptr.next();
150                 if(!ret) {
151                     ret = myPrev.append(ptr);
152                 } else {
153                     myPrev.append(ptr);
154                 }
155                 
156                 ptr = next;
157             }
158             if(base !== this) {
159                 base.detach();
160             }
161             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
162         }
163     }
164 };
165
166 plugin.documentExtension.documentNode.transformations = {
167     moveUp: function() {
168         var toMerge = this,
169             prev = toMerge.prev();
170
171         var merge = function(from, to) {
172             var toret;
173             from.contents().forEach(function(node, idx) {
174                 var len, ret;
175                 if(idx === 0 && node.nodeType === Node.TEXT_NODE) {
176                     len = node.getText().length;
177                 }
178                 ret = to.append(node);
179                 
180                 if(idx === 0 && ret.nodeType === Node.TEXT_NODE) {
181                     toret = {
182                         node: ret,
183                         offset: ret.getText().length - len
184                     };
185                 } else if(!toret) {
186                     toret = {
187                         node: ret.getFirstTextNode(),
188                         offset: 0
189                     };
190                 }
191             });
192             from.detach();
193             return toret;
194         };
195
196         var strategies = [
197             {
198                 applies: function() {
199                     return toMerge.nodeType === Node.TEXT_NODE && prev.is({tagName: 'span'});
200                 },
201                 run: function() {
202                     var textNode = prev.getLastTextNode(),
203                         txt, prevText, prevTextLen;
204                     if(textNode) {
205                         txt = textNode.getText();
206                         if(txt.length > 1) {
207                             textNode.setText(txt.substr(0, txt.length-1));
208                             return {node: toMerge, offset: 0};
209                         } else {
210                             if((prevText = prev.prev()) && prevText.nodeType === Node.TEXT_NODE) {
211                                 prevTextLen = prevText.getText().length;
212                             }
213                             prev.detach();
214                             return {
215                                 node: prevText ? prevText : toMerge,
216                                 offset : prevText ? prevTextLen : 0
217                             };
218                         }
219                     }
220                 }
221             },
222             {
223                 applies: function() {
224                     return toMerge.is({tagName: 'div', 'klass': 'p'}) || (toMerge.is({tagName: 'div'}) && toMerge.getClass() === '');
225                 },
226                 run: function() {
227                     if(prev && (prev.is('p') || prev.is({tagName: 'header'}))) {
228                         return merge(toMerge, prev);
229                     }
230                     if(prev && prev.is('list')) {
231                         var items = prev.contents().filter(function(n) { return n.is('item');});
232                         return merge(toMerge, items[items.length-1]);
233                     }
234                 }
235             },
236             {
237                 applies: function() {
238                     return toMerge.is({tagName: 'span'});
239                 },
240                 run: function() {
241                     /* globals Node */
242                     var toret = {node: toMerge.contents()[0] , offset: 0},
243                         txt, txtNode, parent;
244                     if(!prev) {
245                         toMerge.parents().some(function(p) {
246                             if(p.is({tagName: 'span'})) {
247                                 parent = prev = p;
248                             } else {
249                                 if(!parent) {
250                                     parent = p;
251                                 }
252                                 prev = prev && prev.prev();
253                                 return true;
254                             }
255                         });
256                     }
257                     if(!prev) {
258                         return parent.moveUp();
259                     }
260                     else if(prev.nodeType === Node.TEXT_NODE && (txt = prev.getText())) {
261                         prev.setText(txt.substr(0, txt.length-1));
262                         return toret;
263                     } else if(prev.is({tagName: 'span'})) {
264                         if((txtNode = prev.getLastTextNode())) {
265                             txt = txtNode.getText();
266                             if(txt.length > 1) {
267                                 txtNode.setText(txt.substr(0, txt.length-1));
268                             } else {
269                                 if(txtNode.parent().contents().length === 1) {
270                                     txtNode.parent().detach();
271                                 } else {
272                                     txtNode.detach();
273                                 }
274
275                             }
276                             return toret;
277                         }
278                     }
279
280                 }
281             },
282             {
283                 applies: function() {
284                     return toMerge.is({tagName: 'header'});
285                 },
286                 run: function() {
287                     if(prev && prev.is('p') || prev.is({tagName: 'header'})) {
288                         return merge(toMerge, prev);
289                     }
290                 }
291             },
292             {
293                 applies: function() {
294                     return toMerge.is('item');
295                 },
296                 run: function() {
297                     var list;
298                     if(prev && prev.is('item')) {
299                         return merge(toMerge, prev);
300                     } else if(!prev && (list = toMerge.parent()) && list.is('list')) {
301                         list.before(toMerge);
302                         toMerge.setClass('p');
303                         if(!list.contents().length) {
304                             list.detach();
305                         }
306                         return {node: toMerge.contents()[0], offset:0};
307                     }
308                 }
309             }
310         ];
311
312         var toret;
313         strategies.some(function(strategy) {
314             if(strategy.applies()) {
315                 toret = strategy.run();
316                 return true;
317             }
318         });
319         return toret;
320     },
321     insertNewNode: function () {
322         var node = this;
323         var newElement = this.document.createDocumentNode({tagName: 'div', attrs: {class: 'p'}});
324         node.after(newElement);
325         newElement.append({text: ''});
326         return newElement;
327     }
328 };
329
330 var undoRedoAction = function(dir) {
331     return {
332         name: dir,
333         params: {
334             document: {type: 'context', name: 'document'},
335         },
336         stateDefaults: {
337             label: dir === 'undo' ? '<-' : '->',
338             icon: 'share-alt',
339             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
340             execute: function(callback, params) {
341                 var metadata = _.last(params.document[dir+'Stack']).metadata,
342                     fragment = metadata && metadata.fragment;
343                 params.document[dir]();
344                 if(fragment) {
345                     if(!fragment.isValid()) {
346                         fragment.restoreFromPaths();
347                     }
348                     if(fragment.isValid()) {
349                         callback(fragment);
350                     }
351                 }
352                 callback();
353             },
354         },
355         getState: function(params) {
356             var allowed = params.document && !!(params.document[dir+'Stack'].length),
357                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
358                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
359             if(allowed) {
360                 var metadata = _.last(params.document[dir+'Stack']).metadata;
361                 if(metadata) {
362                     desc += ': ' + (metadata.description || gettext('unknown operation'));
363                 }
364             }
365             return {
366                 allowed: allowed,
367                 description: allowed ? desc : descEmpty
368             };
369         }
370     };
371 };
372
373 var pad = function(number) {
374     if(number < 10) {
375         number = '0' + number;
376     }
377     return number;
378 };
379
380 var commentAction = {
381     name: 'comment',
382     params: {
383         fragment: {type: 'context', name: 'fragment'}
384     },
385     stateDefaults: {
386         icon: 'comment',
387         execute: function(callback, params, editor) {
388             /* globals Node */
389             var node = params.fragment.node,
390                 action = this;
391             if(node.nodeType === Node.TEXT_NODE) {
392                 node = node.parent();
393             }
394             node.document.transaction(function() {
395                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
396                 comment.append({text:''});
397                 var user = editor.getUser(), creator;
398                 if(user) {
399                     creator = user.name;
400                     if(user.email) {
401                         creator += ' (' + user.email + ')';
402                     }
403                 } else {
404                     creator = 'anonymous';
405                 }
406
407                 var currentDate = new Date(),
408                     dt = pad(currentDate.getDate()) + '-' +
409                                 pad((currentDate.getMonth() + 1))  + '-' +
410                                 pad(currentDate.getFullYear()) + ' ' +
411                                 pad(currentDate.getHours()) + ':' +
412                                 pad(currentDate.getMinutes()) + ':' +
413                                 pad(currentDate.getSeconds());
414
415                 var metadata = comment.getMetadata();
416                 metadata.add({key: 'creator', value: creator});
417                 metadata.add({key: 'date', value: dt});
418             }, {
419                 metadata: {
420                     description: action.getState().description
421                 },
422                 success: callback
423             });
424         },
425     },
426     getState: function(params) {
427         var state = {
428             allowed: params.fragment && params.fragment.isValid() &&
429                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
430         };
431         if(state.allowed) {
432             state.description = gettext('Insert comment');
433         }
434         return state;
435     }
436 };
437
438
439 var createWrapTextAction = function(createParams) {
440     return {
441         name: createParams.name,
442         params: {
443             fragment: {type: 'context', name: 'fragment'},
444         },
445         getState: function(params) {
446             var state = {
447                     label: this.config.label
448                 },
449                 parent;
450             
451             if(!params.fragment || !params.fragment.isValid()) {
452                 return _.extend(state, {allowed: false});
453             }
454
455             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
456                 return _.extend(state, {
457                     allowed: true,
458                     toggled: true,
459                     description: createParams.unwrapDescription,
460                     execute: function(callback, params) {
461                         var node = params.fragment.node,
462                             doc = node.document,
463                             toRemove = node.getParent(createParams.klass),
464                             prefLen = 0;
465
466                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
467                             prefLen = toRemove.prev().getText().length;
468                         }
469
470                         doc.transaction(function() {
471                             var ret = toRemove.unwrapContent(),
472                                 newFragment = params.fragment;
473                             if(!newFragment.isValid()) {
474                                 newFragment =  doc.createFragment(doc.CaretFragment, {
475                                     node: ret.element1,
476                                     offset: prefLen + params.fragment.offset
477                                 });
478                             }
479                             return newFragment;
480                         }, {
481                             metadata: {
482                                 description: createParams.unwrapDescription,
483                                 fragment: params.fragment
484                             },
485                             success: callback
486                         });
487                     }
488                 });
489             }
490
491             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
492                 parent = params.fragment.startNode.parent();
493                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
494                     return _.extend(state, {allowed: false});
495                 }
496
497                 return _.extend(state, {
498                     allowed: true,
499                     description: createParams.wrapDescription,
500                     execute: function(callback, params) {
501                         params.fragment.document.transaction(function() {
502                             var parent = params.fragment.startNode.parent(),
503                                 doc = params.fragment.document,
504                                 wrapper, lastTextNode;
505                             
506                             wrapper = parent.wrapText({
507                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
508                                 offsetStart: params.fragment.startOffset,
509                                 offsetEnd: params.fragment.endOffset,
510                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
511                             });
512                                 
513                             lastTextNode = wrapper.getLastTextNode();
514                             if(lastTextNode) {
515                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
516                             }
517                         }, {
518                             metadata: {
519                                 description: createParams.wrapDescription,
520                                 fragment: params.fragment
521                             },
522                             success: callback
523                         });
524                     }
525                 });
526             }
527             return _.extend(state, {allowed: false});
528         }
529     };
530 };
531
532
533
534 var createLinkFromSelection = function(callback, params) {
535     var doc = params.fragment.document,
536         dialog = Dialog.create({
537             title: gettext('Create link'),
538             executeButtonText: gettext('Apply'),
539             cancelButtonText: gettext('Cancel'),
540             fields: [
541                 {label: gettext('Link'), name: 'href', type: 'input',
542                 prePasteHandler: function(text) {
543                                     return params.fragment.document.getLinkForUrl(text);
544                                 }.bind(this),
545                 description: '<a href="#-" class="attachment-library">' + gettext('attachment library') + '</a>'
546                 }
547             ]
548         }),
549         action = this;
550     
551     dialog.on('execute', function(event) {
552         doc.transaction(function() {
553             var span =  action.params.fragment.startNode.parent().wrapText({
554                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
555                 offsetStart: params.fragment.startOffset,
556                 offsetEnd: params.fragment.endOffset,
557                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
558             }),
559                 doc = params.fragment.document;
560             event.success();
561             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
562         }, {
563             metadata: {
564                 description: action.getState().description,
565                 fragment: params.fragment
566             },
567             success: callback
568         });
569     });
570     dialog.show();
571     $(".attachment-library", dialog.$el).on('click', function() {
572         attachments.select(function(v) {$("input", dialog.$el).val(v);});
573     });
574 };
575
576 var editLink = function(callback, params) {
577     var doc = params.fragment.document,
578         link = params.fragment.node.getParent('link'),
579         dialog = Dialog.create({
580             title: gettext('Edit link'),
581             executeButtonText: gettext('Apply'),
582             cancelButtonText: gettext('Cancel'),
583             fields: [
584                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
585             ]
586         }),
587         action = this;
588     
589     dialog.on('execute', function(event) {
590         doc.transaction(function() {
591             link.setAttr('href', event.formData.href);
592             event.success();
593             return params.fragment;
594         }, {
595             metadata: {
596                 description: action.getState().description,
597                 fragment: params.fragment
598             },
599             success: callback
600         });
601     });
602     dialog.show();
603 };
604
605 var linkAction = {
606     name: 'link',
607     params: {
608         fragment: {type: 'context', name: 'fragment'}
609     },
610     stateDefaults: {
611         label: gettext('link')
612     },
613     getState: function(params) {
614         if(!params.fragment || !params.fragment.isValid()) {
615             return {allowed: false};
616         }
617
618         if(params.fragment instanceof params.fragment.TextRangeFragment) {
619             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
620                 return {allowed: false};
621             }
622             return {
623                 allowed: true,
624                 description: gettext('Create link from selection'),
625                 execute: createLinkFromSelection
626             };
627         }
628
629         if(params.fragment instanceof params.fragment.CaretFragment) {
630             if(params.fragment.node.isInside('link')) {
631                 return {
632                     allowed: true,
633                     toggled: true,
634                     description: gettext('Edit link'),
635                     execute: editLink
636                 };
637             }
638         }
639         return {allowed: false};
640     }
641 };
642
643
644 var metadataParams = {};
645
646 plugin.actions = [
647     undoRedoAction('undo'),
648     undoRedoAction('redo'),
649     commentAction,
650     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
651     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
652     linkAction,
653     metadataEditor.action(metadataParams)
654 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
655
656
657 plugin.config = function(config) {
658     // templates.actions[0].config(config.templates);
659     templates.actions[0].params.template.options = config.templates;
660     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
661         if(configRow1.key < configRow2.key) {
662             return -1;
663         }
664         if(configRow1.key > configRow2.key) {
665             return 1;
666         }
667         return 0;
668     });
669 };
670
671 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);
672
673 return plugin;
674
675 });