fourth batch: fixing blocking span - passing all tests, linting
[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: {}}},
12     Dialog = require('views/dialog/dialog'),
13     canvasElements = require('plugins/core/canvasElements');
14
15
16
17 plugin.documentExtension.textNode.transformations = {
18     breakContent: {
19         impl: function(args) {
20             var node = this,
21                 newNodes, emptyText;
22             newNodes = node.split({offset: args.offset});
23             [newNodes.first, newNodes.second].some(function(newNode) {
24                 if(!(newNode.contents().length)) {
25                     emptyText = newNode.append({text: ''});
26                     return true; // break
27                 }
28             });
29             return _.extend(newNodes, {emptyText: emptyText});
30         },
31         getChangeRoot: function() {
32             return this.context.parent().parent();
33         }
34     },
35     mergeContentUp: function() {
36         /* globals Node */
37         var myPrev = this,
38             base = this,
39             ret;
40
41         if(myPrev.nodeType === Node.TEXT_NODE) {
42             if(myPrev.getIndex() > 0) {
43                 return;
44             }
45             myPrev = base = myPrev.parent();
46         }
47
48         myPrev = myPrev && myPrev.prev();
49
50         if(myPrev && myPrev.nodeType === Node.ELEMENT_NODE)  {
51             var ptr = this,
52                 next;
53             while(ptr) {
54                 next = ptr.next();
55                 if(!ret) {
56                     ret = myPrev.append(ptr);
57                 } else {
58                     myPrev.append(ptr);
59                 }
60                 
61                 ptr = next;
62             }
63             if(base !== this) {
64                 base.detach();
65             }
66             return {node: ret, offset: ret.sameNode(this) ? null : ret.getText().length - this.getText().length};
67         }
68     }
69 };
70
71 var undoRedoAction = function(dir) {
72     return {
73         name: dir,
74         params: {
75             document: {type: 'context', name: 'document'},
76         },
77         stateDefaults: {
78             label: dir === 'undo' ? '<-' : '->',
79             icon: 'share-alt',
80             iconStyle: dir === 'undo' ? '-webkit-transform: scale(-1,1); transform: scale(-1, 1)' : '',
81             execute: function(callback, params) {
82                 params.document[dir]();
83                 callback();
84             },
85         },
86         getState: function(params) {
87             var allowed = params.document && !!(params.document[dir+'Stack'].length),
88                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
89                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
90             if(allowed) {
91                 var metadata = _.last(params.document[dir+'Stack']).metadata;
92                 if(metadata) {
93                     desc += ': ' + (metadata.description || gettext('unknown operation'));
94                 }
95             }
96             return {
97                 allowed: allowed,
98                 description: allowed ? desc : descEmpty
99             };
100         }
101     };
102 };
103
104 var pad = function(number) {
105     if(number < 10) {
106         number = '0' + number;
107     }
108     return number;
109 };
110
111 var commentAction = {
112     name: 'comment',
113     params: {
114         fragment: {type: 'context', name: 'fragment'}
115     },
116     stateDefaults: {
117         icon: 'comment',
118         execute: function(callback, params, editor) {
119             /* globals Node */
120             var node = params.fragment.node,
121                 action = this;
122             if(node.nodeType === Node.TEXT_NODE) {
123                 node = node.parent();
124             }
125             node.document.transaction(function() {
126                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
127                 comment.append({text:''});
128                 var user = editor.getUser(), creator;
129                 if(user) {
130                     creator = user.name;
131                     if(user.email) {
132                         creator += ' (' + user.email + ')';
133                     }
134                 } else {
135                     creator = 'anonymous';
136                 }
137
138                 var currentDate = new Date(),
139                     dt = pad(currentDate.getDate()) + '-' +
140                                 pad((currentDate.getMonth() + 1))  + '-' +
141                                 pad(currentDate.getFullYear()) + ' ' +
142                                 pad(currentDate.getHours()) + ':' +
143                                 pad(currentDate.getMinutes()) + ':' +
144                                 pad(currentDate.getSeconds());
145
146                 var metadata = comment.getMetadata();
147                 metadata.add({key: 'creator', value: creator});
148                 metadata.add({key: 'date', value: dt});
149             }, {
150                 metadata: {
151                     description: action.getState().description
152                 },
153                 success: callback
154             });
155         },
156     },
157     getState: function(params) {
158         var state = {
159             allowed: params.fragment && params.fragment.isValid() &&
160                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
161         };
162         if(state.allowed) {
163             state.description = gettext('Insert comment');
164         }
165         return state;
166     }
167 };
168
169
170 var createWrapTextAction = function(createParams) {
171     return {
172         name: createParams.name,
173         params: {
174             fragment: {type: 'context', name: 'fragment'},
175         },
176         getState: function(params) {
177             var state = {
178                     label: this.config.label
179                 },
180                 parent;
181             
182             if(!params.fragment || !params.fragment.isValid()) {
183                 return _.extend(state, {allowed: false});
184             }
185
186             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
187                 return _.extend(state, {
188                     allowed: true,
189                     toggled: true,
190                     description: createParams.unwrapDescription,
191                     execute: function(callback, params) {
192                         var node = params.fragment.node,
193                             doc = node.document,
194                             toRemove = node.getParent(createParams.klass),
195                             prefLen = 0;
196
197                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
198                             prefLen = toRemove.prev().getText().length;
199                         }
200
201                         doc.transaction(function() {
202                             var ret = toRemove.unwrapContent(),
203                                 newFragment = params.fragment;
204                             if(!newFragment.isValid()) {
205                                 newFragment =  doc.createFragment(doc.CaretFragment, {
206                                     node: ret.element1,
207                                     offset: prefLen + params.fragment.offset
208                                 });
209                             }
210                             return newFragment;
211                         }, {
212                             metadata: {
213                                 description: createParams.unwrapDescription
214                             },
215                             success: callback
216                         });
217                     }
218                 });
219             }
220
221             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
222                 parent = params.fragment.startNode.parent();
223                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
224                     return _.extend(state, {allowed: false});
225                 }
226
227                 return _.extend(state, {
228                     allowed: true,
229                     description: createParams.wrapDescription,
230                     execute: function(callback, params) {
231                         params.fragment.document.transaction(function() {
232                             var parent = params.fragment.startNode.parent(),
233                                 doc = params.fragment.document,
234                                 wrapper, lastTextNode;
235                             
236                             wrapper = parent.wrapText({
237                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
238                                 offsetStart: params.fragment.startOffset,
239                                 offsetEnd: params.fragment.endOffset,
240                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
241                             });
242                                 
243                             lastTextNode = wrapper.getLastTextNode();
244                             if(lastTextNode) {
245                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
246                             }
247                         }, {
248                             metadata: {
249                                 description: createParams.wrapDescription
250                             },
251                             success: callback
252                         });
253                     }
254                 });
255             }
256             return _.extend(state, {allowed: false});
257         }
258     };
259 };
260
261
262 var createLinkFromSelection = function(callback, params) {
263     var doc = params.fragment.document,
264         dialog = Dialog.create({
265             title: gettext('Create link'),
266             executeButtonText: gettext('Apply'),
267             cancelButtonText: gettext('Cancel'),
268             fields: [
269                 {label: gettext('Link'), name: 'href', type: 'input'}
270             ]
271         }),
272         action = this;
273     
274     dialog.on('execute', function(event) {
275         doc.transaction(function() {
276             var span =  action.params.fragment.startNode.parent().wrapText({
277                 _with: {tagName: 'span', attrs: {'class': 'link'}},
278                 offsetStart: params.fragment.startOffset,
279                 offsetEnd: params.fragment.endOffset,
280                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
281             }),
282                 doc = params.fragment.document;
283             span.setAttr('href', event.formData.href);
284             event.success();
285             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
286         }, {
287             metadata: {
288                 description: action.getState().description
289             },
290             success: callback
291         });
292     });
293     dialog.show();
294 };
295
296 var editLink = function(callback, params) {
297     var doc = params.fragment.document,
298         link = params.fragment.node.getParent('link'),
299         dialog = Dialog.create({
300             title: gettext('Edit link'),
301             executeButtonText: gettext('Apply'),
302             cancelButtonText: gettext('Cancel'),
303             fields: [
304                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
305             ]
306         }),
307         action = this;
308     
309     dialog.on('execute', function(event) {
310         doc.transaction(function() {
311             link.setAttr('href', event.formData.href);
312             event.success();
313             return params.fragment;
314         }, {
315             metadata: {
316                 description: action.getState().description
317             },
318             success: callback
319         });
320     });
321     dialog.show();
322 };
323
324 var linkAction = {
325     name: 'link',
326     params: {
327         fragment: {type: 'context', name: 'fragment'}
328     },
329     stateDefaults: {
330         label: gettext('link')
331     },
332     getState: function(params) {
333         if(!params.fragment || !params.fragment.isValid()) {
334             return {allowed: false};
335         }
336
337         if(params.fragment instanceof params.fragment.TextRangeFragment) {
338             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
339                 return {allowed: false};
340             }
341             return {
342                 allowed: true,
343                 description: gettext('Create link from selection'),
344                 execute: createLinkFromSelection
345             };
346         }
347
348         if(params.fragment instanceof params.fragment.CaretFragment) {
349             if(params.fragment.node.isInside('link')) {
350                 return {
351                     allowed: true,
352                     toggled: true,
353                     description: gettext('Edit link'),
354                     execute: editLink
355                 };
356             }
357         }
358         return {allowed: false};
359     }
360 };
361
362
363 plugin.actions = [
364     undoRedoAction('undo'),
365     undoRedoAction('redo'),
366     commentAction,
367     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
368     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
369     linkAction
370 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
371
372
373
374 plugin.config = function(config) {
375     // templates.actions[0].config(config.templates);
376     templates.actions[0].params.template.options = config.templates;
377 };
378
379 plugin.canvasElements = canvasElements;
380
381 return plugin;
382
383 });