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