minor code style
[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 };
322
323 var undoRedoAction = function(dir) {
324     return {
325         name: dir,
326         params: {
327             document: {type: 'context', name: 'document'},
328         },
329         stateDefaults: {
330             label: dir === 'undo' ? '<-' : '->',
331             icon: 'share-alt',
332             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
333             execute: function(callback, params) {
334                 var metadata = _.last(params.document[dir+'Stack']).metadata,
335                     fragment = metadata && metadata.fragment;
336                 params.document[dir]();
337                 if(fragment) {
338                     if(!fragment.isValid()) {
339                         fragment.restoreFromPaths();
340                     }
341                     if(fragment.isValid()) {
342                         callback(fragment);
343                     }
344                 }
345                 callback();
346             },
347         },
348         getState: function(params) {
349             var allowed = params.document && !!(params.document[dir+'Stack'].length),
350                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
351                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
352             if(allowed) {
353                 var metadata = _.last(params.document[dir+'Stack']).metadata;
354                 if(metadata) {
355                     desc += ': ' + (metadata.description || gettext('unknown operation'));
356                 }
357             }
358             return {
359                 allowed: allowed,
360                 description: allowed ? desc : descEmpty
361             };
362         }
363     };
364 };
365
366 var pad = function(number) {
367     if(number < 10) {
368         number = '0' + number;
369     }
370     return number;
371 };
372
373 var commentAction = {
374     name: 'comment',
375     params: {
376         fragment: {type: 'context', name: 'fragment'}
377     },
378     stateDefaults: {
379         icon: 'comment',
380         execute: function(callback, params, editor) {
381             /* globals Node */
382             var node = params.fragment.node,
383                 action = this;
384             if(node.nodeType === Node.TEXT_NODE) {
385                 node = node.parent();
386             }
387             node.document.transaction(function() {
388                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
389                 comment.append({text:''});
390                 var user = editor.getUser(), creator;
391                 if(user) {
392                     creator = user.name;
393                     if(user.email) {
394                         creator += ' (' + user.email + ')';
395                     }
396                 } else {
397                     creator = 'anonymous';
398                 }
399
400                 var currentDate = new Date(),
401                     dt = pad(currentDate.getDate()) + '-' +
402                                 pad((currentDate.getMonth() + 1))  + '-' +
403                                 pad(currentDate.getFullYear()) + ' ' +
404                                 pad(currentDate.getHours()) + ':' +
405                                 pad(currentDate.getMinutes()) + ':' +
406                                 pad(currentDate.getSeconds());
407
408                 var metadata = comment.getMetadata();
409                 metadata.add({key: 'creator', value: creator});
410                 metadata.add({key: 'date', value: dt});
411             }, {
412                 metadata: {
413                     description: action.getState().description
414                 },
415                 success: callback
416             });
417         },
418     },
419     getState: function(params) {
420         var state = {
421             allowed: params.fragment && params.fragment.isValid() &&
422                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
423         };
424         if(state.allowed) {
425             state.description = gettext('Insert comment');
426         }
427         return state;
428     }
429 };
430
431
432 var createWrapTextAction = function(createParams) {
433     return {
434         name: createParams.name,
435         params: {
436             fragment: {type: 'context', name: 'fragment'},
437         },
438         getState: function(params) {
439             var state = {
440                     label: this.config.label
441                 },
442                 parent;
443             
444             if(!params.fragment || !params.fragment.isValid()) {
445                 return _.extend(state, {allowed: false});
446             }
447
448             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
449                 return _.extend(state, {
450                     allowed: true,
451                     toggled: true,
452                     description: createParams.unwrapDescription,
453                     execute: function(callback, params) {
454                         var node = params.fragment.node,
455                             doc = node.document,
456                             toRemove = node.getParent(createParams.klass),
457                             prefLen = 0;
458
459                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
460                             prefLen = toRemove.prev().getText().length;
461                         }
462
463                         doc.transaction(function() {
464                             var ret = toRemove.unwrapContent(),
465                                 newFragment = params.fragment;
466                             if(!newFragment.isValid()) {
467                                 newFragment =  doc.createFragment(doc.CaretFragment, {
468                                     node: ret.element1,
469                                     offset: prefLen + params.fragment.offset
470                                 });
471                             }
472                             return newFragment;
473                         }, {
474                             metadata: {
475                                 description: createParams.unwrapDescription,
476                                 fragment: params.fragment
477                             },
478                             success: callback
479                         });
480                     }
481                 });
482             }
483
484             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
485                 parent = params.fragment.startNode.parent();
486                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
487                     return _.extend(state, {allowed: false});
488                 }
489
490                 return _.extend(state, {
491                     allowed: true,
492                     description: createParams.wrapDescription,
493                     execute: function(callback, params) {
494                         params.fragment.document.transaction(function() {
495                             var parent = params.fragment.startNode.parent(),
496                                 doc = params.fragment.document,
497                                 wrapper, lastTextNode;
498                             
499                             wrapper = parent.wrapText({
500                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
501                                 offsetStart: params.fragment.startOffset,
502                                 offsetEnd: params.fragment.endOffset,
503                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
504                             });
505                                 
506                             lastTextNode = wrapper.getLastTextNode();
507                             if(lastTextNode) {
508                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
509                             }
510                         }, {
511                             metadata: {
512                                 description: createParams.wrapDescription,
513                                 fragment: params.fragment
514                             },
515                             success: callback
516                         });
517                     }
518                 });
519             }
520             return _.extend(state, {allowed: false});
521         }
522     };
523 };
524
525
526
527 var createLinkFromSelection = function(callback, params) {
528     var doc = params.fragment.document,
529         dialog = Dialog.create({
530             title: gettext('Create link'),
531             executeButtonText: gettext('Apply'),
532             cancelButtonText: gettext('Cancel'),
533             fields: [
534                 {label: gettext('Link'), name: 'href', type: 'input',
535                 prePasteHandler: function(text) {
536                                     return params.fragment.document.getLinkForUrl(text);
537                                 }.bind(this),
538                 description: '<a href="#-" class="attachment-library">attachment library</a>'
539                 }
540             ]
541         }),
542         action = this;
543     
544     dialog.on('execute', function(event) {
545         doc.transaction(function() {
546             var span =  action.params.fragment.startNode.parent().wrapText({
547                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
548                 offsetStart: params.fragment.startOffset,
549                 offsetEnd: params.fragment.endOffset,
550                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
551             }),
552                 doc = params.fragment.document;
553             event.success();
554             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
555         }, {
556             metadata: {
557                 description: action.getState().description,
558                 fragment: params.fragment
559             },
560             success: callback
561         });
562     });
563     dialog.show();
564     $(".attachment-library", dialog.$el).on('click', function() {
565         attachments.select(function(v) {$("input", dialog.$el).val(v);});
566     });
567 };
568
569 var editLink = function(callback, params) {
570     var doc = params.fragment.document,
571         link = params.fragment.node.getParent('link'),
572         dialog = Dialog.create({
573             title: gettext('Edit link'),
574             executeButtonText: gettext('Apply'),
575             cancelButtonText: gettext('Cancel'),
576             fields: [
577                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
578             ]
579         }),
580         action = this;
581     
582     dialog.on('execute', function(event) {
583         doc.transaction(function() {
584             link.setAttr('href', event.formData.href);
585             event.success();
586             return params.fragment;
587         }, {
588             metadata: {
589                 description: action.getState().description,
590                 fragment: params.fragment
591             },
592             success: callback
593         });
594     });
595     dialog.show();
596 };
597
598 var linkAction = {
599     name: 'link',
600     params: {
601         fragment: {type: 'context', name: 'fragment'}
602     },
603     stateDefaults: {
604         label: gettext('link')
605     },
606     getState: function(params) {
607         if(!params.fragment || !params.fragment.isValid()) {
608             return {allowed: false};
609         }
610
611         if(params.fragment instanceof params.fragment.TextRangeFragment) {
612             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
613                 return {allowed: false};
614             }
615             return {
616                 allowed: true,
617                 description: gettext('Create link from selection'),
618                 execute: createLinkFromSelection
619             };
620         }
621
622         if(params.fragment instanceof params.fragment.CaretFragment) {
623             if(params.fragment.node.isInside('link')) {
624                 return {
625                     allowed: true,
626                     toggled: true,
627                     description: gettext('Edit link'),
628                     execute: editLink
629                 };
630             }
631         }
632         return {allowed: false};
633     }
634 };
635
636
637 var metadataParams = {};
638
639 plugin.actions = [
640     undoRedoAction('undo'),
641     undoRedoAction('redo'),
642     commentAction,
643     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
644     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
645     linkAction,
646     metadataEditor.action(metadataParams)
647 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions, edumed.actions);
648
649
650 plugin.config = function(config) {
651     // templates.actions[0].config(config.templates);
652     templates.actions[0].params.template.options = config.templates;
653     metadataParams.config = (config.metadata || []).sort(function(configRow1, configRow2) {
654         if(configRow1.key < configRow2.key) {
655             return -1;
656         }
657         if(configRow1.key > configRow2.key) {
658             return 1;
659         }
660         return 0;
661     });
662 };
663
664 plugin.canvasElements = canvasElements.concat(edumed.canvasElements);
665
666 return plugin;
667
668 });