ade5d933399ce6c9c3b761525b481df424e91c00
[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', href: event.formData.href }},
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             event.success();
284             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
285         }, {
286             metadata: {
287                 description: action.getState().description
288             },
289             success: callback
290         });
291     });
292     dialog.show();
293 };
294
295 var editLink = function(callback, params) {
296     var doc = params.fragment.document,
297         link = params.fragment.node.getParent('link'),
298         dialog = Dialog.create({
299             title: gettext('Edit link'),
300             executeButtonText: gettext('Apply'),
301             cancelButtonText: gettext('Cancel'),
302             fields: [
303                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
304             ]
305         }),
306         action = this;
307     
308     dialog.on('execute', function(event) {
309         doc.transaction(function() {
310             link.setAttr('href', event.formData.href);
311             event.success();
312             return params.fragment;
313         }, {
314             metadata: {
315                 description: action.getState().description
316             },
317             success: callback
318         });
319     });
320     dialog.show();
321 };
322
323 var linkAction = {
324     name: 'link',
325     params: {
326         fragment: {type: 'context', name: 'fragment'}
327     },
328     stateDefaults: {
329         label: gettext('link')
330     },
331     getState: function(params) {
332         if(!params.fragment || !params.fragment.isValid()) {
333             return {allowed: false};
334         }
335
336         if(params.fragment instanceof params.fragment.TextRangeFragment) {
337             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
338                 return {allowed: false};
339             }
340             return {
341                 allowed: true,
342                 description: gettext('Create link from selection'),
343                 execute: createLinkFromSelection
344             };
345         }
346
347         if(params.fragment instanceof params.fragment.CaretFragment) {
348             if(params.fragment.node.isInside('link')) {
349                 return {
350                     allowed: true,
351                     toggled: true,
352                     description: gettext('Edit link'),
353                     execute: editLink
354                 };
355             }
356         }
357         return {allowed: false};
358     }
359 };
360
361
362 plugin.actions = [
363     undoRedoAction('undo'),
364     undoRedoAction('redo'),
365     commentAction,
366     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
367     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
368     linkAction
369 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
370
371
372
373 plugin.config = function(config) {
374     // templates.actions[0].config(config.templates);
375     templates.actions[0].params.template.options = config.templates;
376 };
377
378 plugin.canvasElements = canvasElements;
379
380 return plugin;
381
382 });