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