ba6229f0b416e6b8959106c74174e529d026735e
[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                 var metadata = _.last(params.document[dir+'Stack']).metadata,
83                     fragment = metadata && metadata.fragment;
84                 params.document[dir]();
85                 if(fragment) {
86                     if(!fragment.isValid()) {
87                         fragment.restoreFromPaths();
88                     }
89                     if(fragment.isValid()) {
90                         callback(fragment);
91                     }
92                 }
93                 callback();
94             },
95         },
96         getState: function(params) {
97             var allowed = params.document && !!(params.document[dir+'Stack'].length),
98                 desc = dir === 'undo' ? gettext('Undo') : gettext('Redo'),
99                 descEmpty = dir === 'undo' ? gettext('There is nothing to undo') : gettext('There is nothing to redo');
100             if(allowed) {
101                 var metadata = _.last(params.document[dir+'Stack']).metadata;
102                 if(metadata) {
103                     desc += ': ' + (metadata.description || gettext('unknown operation'));
104                 }
105             }
106             return {
107                 allowed: allowed,
108                 description: allowed ? desc : descEmpty
109             };
110         }
111     };
112 };
113
114 var pad = function(number) {
115     if(number < 10) {
116         number = '0' + number;
117     }
118     return number;
119 };
120
121 var commentAction = {
122     name: 'comment',
123     params: {
124         fragment: {type: 'context', name: 'fragment'}
125     },
126     stateDefaults: {
127         icon: 'comment',
128         execute: function(callback, params, editor) {
129             /* globals Node */
130             var node = params.fragment.node,
131                 action = this;
132             if(node.nodeType === Node.TEXT_NODE) {
133                 node = node.parent();
134             }
135             node.document.transaction(function() {
136                 var comment =  node.after({tagName: 'aside', attrs: {'class': 'comment'}});
137                 comment.append({text:''});
138                 var user = editor.getUser(), creator;
139                 if(user) {
140                     creator = user.name;
141                     if(user.email) {
142                         creator += ' (' + user.email + ')';
143                     }
144                 } else {
145                     creator = 'anonymous';
146                 }
147
148                 var currentDate = new Date(),
149                     dt = pad(currentDate.getDate()) + '-' +
150                                 pad((currentDate.getMonth() + 1))  + '-' +
151                                 pad(currentDate.getFullYear()) + ' ' +
152                                 pad(currentDate.getHours()) + ':' +
153                                 pad(currentDate.getMinutes()) + ':' +
154                                 pad(currentDate.getSeconds());
155
156                 var metadata = comment.getMetadata();
157                 metadata.add({key: 'creator', value: creator});
158                 metadata.add({key: 'date', value: dt});
159             }, {
160                 metadata: {
161                     description: action.getState().description
162                 },
163                 success: callback
164             });
165         },
166     },
167     getState: function(params) {
168         var state = {
169             allowed: params.fragment && params.fragment.isValid() &&
170                         params.fragment instanceof params.fragment.NodeFragment && !params.fragment.node.isRoot()
171         };
172         if(state.allowed) {
173             state.description = gettext('Insert comment');
174         }
175         return state;
176     }
177 };
178
179
180 var createWrapTextAction = function(createParams) {
181     return {
182         name: createParams.name,
183         params: {
184             fragment: {type: 'context', name: 'fragment'},
185         },
186         getState: function(params) {
187             var state = {
188                     label: this.config.label
189                 },
190                 parent;
191             
192             if(!params.fragment || !params.fragment.isValid()) {
193                 return _.extend(state, {allowed: false});
194             }
195
196             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
197                 return _.extend(state, {
198                     allowed: true,
199                     toggled: true,
200                     description: createParams.unwrapDescription,
201                     execute: function(callback, params) {
202                         var node = params.fragment.node,
203                             doc = node.document,
204                             toRemove = node.getParent(createParams.klass),
205                             prefLen = 0;
206
207                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
208                             prefLen = toRemove.prev().getText().length;
209                         }
210
211                         doc.transaction(function() {
212                             var ret = toRemove.unwrapContent(),
213                                 newFragment = params.fragment;
214                             if(!newFragment.isValid()) {
215                                 newFragment =  doc.createFragment(doc.CaretFragment, {
216                                     node: ret.element1,
217                                     offset: prefLen + params.fragment.offset
218                                 });
219                             }
220                             return newFragment;
221                         }, {
222                             metadata: {
223                                 description: createParams.unwrapDescription
224                             },
225                             success: callback
226                         });
227                     }
228                 });
229             }
230
231             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
232                 parent = params.fragment.startNode.parent();
233                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
234                     return _.extend(state, {allowed: false});
235                 }
236
237                 return _.extend(state, {
238                     allowed: true,
239                     description: createParams.wrapDescription,
240                     execute: function(callback, params) {
241                         params.fragment.document.transaction(function() {
242                             var parent = params.fragment.startNode.parent(),
243                                 doc = params.fragment.document,
244                                 wrapper, lastTextNode;
245                             
246                             wrapper = parent.wrapText({
247                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
248                                 offsetStart: params.fragment.startOffset,
249                                 offsetEnd: params.fragment.endOffset,
250                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
251                             });
252                                 
253                             lastTextNode = wrapper.getLastTextNode();
254                             if(lastTextNode) {
255                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
256                             }
257                         }, {
258                             metadata: {
259                                 description: createParams.wrapDescription
260                             },
261                             success: callback
262                         });
263                     }
264                 });
265             }
266             return _.extend(state, {allowed: false});
267         }
268     };
269 };
270
271
272 var createLinkFromSelection = function(callback, params) {
273     var doc = params.fragment.document,
274         dialog = Dialog.create({
275             title: gettext('Create link'),
276             executeButtonText: gettext('Apply'),
277             cancelButtonText: gettext('Cancel'),
278             fields: [
279                 {label: gettext('Link'), name: 'href', type: 'input',
280                 prePasteHandler: function(text) {
281                                     return params.fragment.document.getLinkForUrl(text);
282                                 }.bind(this)
283                 }
284             ]
285         }),
286         action = this;
287     
288     dialog.on('execute', function(event) {
289         doc.transaction(function() {
290             var span =  action.params.fragment.startNode.parent().wrapText({
291                 _with: {tagName: 'span', attrs: {'class': 'link', href: event.formData.href }},
292                 offsetStart: params.fragment.startOffset,
293                 offsetEnd: params.fragment.endOffset,
294                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
295             }),
296                 doc = params.fragment.document;
297             event.success();
298             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
299         }, {
300             metadata: {
301                 description: action.getState().description
302             },
303             success: callback
304         });
305     });
306     dialog.show();
307 };
308
309 var editLink = function(callback, params) {
310     var doc = params.fragment.document,
311         link = params.fragment.node.getParent('link'),
312         dialog = Dialog.create({
313             title: gettext('Edit link'),
314             executeButtonText: gettext('Apply'),
315             cancelButtonText: gettext('Cancel'),
316             fields: [
317                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
318             ]
319         }),
320         action = this;
321     
322     dialog.on('execute', function(event) {
323         doc.transaction(function() {
324             link.setAttr('href', event.formData.href);
325             event.success();
326             return params.fragment;
327         }, {
328             metadata: {
329                 description: action.getState().description
330             },
331             success: callback
332         });
333     });
334     dialog.show();
335 };
336
337 var linkAction = {
338     name: 'link',
339     params: {
340         fragment: {type: 'context', name: 'fragment'}
341     },
342     stateDefaults: {
343         label: gettext('link')
344     },
345     getState: function(params) {
346         if(!params.fragment || !params.fragment.isValid()) {
347             return {allowed: false};
348         }
349
350         if(params.fragment instanceof params.fragment.TextRangeFragment) {
351             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
352                 return {allowed: false};
353             }
354             return {
355                 allowed: true,
356                 description: gettext('Create link from selection'),
357                 execute: createLinkFromSelection
358             };
359         }
360
361         if(params.fragment instanceof params.fragment.CaretFragment) {
362             if(params.fragment.node.isInside('link')) {
363                 return {
364                     allowed: true,
365                     toggled: true,
366                     description: gettext('Edit link'),
367                     execute: editLink
368                 };
369             }
370         }
371         return {allowed: false};
372     }
373 };
374
375
376 plugin.actions = [
377     undoRedoAction('undo'),
378     undoRedoAction('redo'),
379     commentAction,
380     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
381     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
382     linkAction
383 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
384
385
386
387 plugin.config = function(config) {
388     // templates.actions[0].config(config.templates);
389     templates.actions[0].params.template.options = config.templates;
390 };
391
392 plugin.canvasElements = canvasElements;
393
394 return plugin;
395
396 });