38675fbb1db50e5ab06935c154b4ab5adcc11bcf
[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');
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(!params.fragment || !params.fragment.isValid()) {
181                 return _.extend(state, {allowed: false});
182             }
183
184             if(params.fragment instanceof params.fragment.CaretFragment && params.fragment.node.isInside(createParams.klass)) {
185                 return _.extend(state, {
186                     allowed: true,
187                     toggled: true,
188                     description: createParams.unwrapDescription,
189                     execute: function(callback, params) {
190                         var node = params.fragment.node,
191                             doc = node.document,
192                             toRemove = node.getParent(createParams.klass),
193                             prefLen = 0;
194
195                         if(node.sameNode(toRemove.contents()[0]) && toRemove.isPrecededByTextNode()) {
196                             prefLen = toRemove.prev().getText().length;
197                         }
198
199                         doc.transaction(function() {
200                             var ret = toRemove.unwrapContent(),
201                                 newFragment = params.fragment;
202                             if(!newFragment.isValid()) {
203                                 newFragment =  doc.createFragment(doc.CaretFragment, {
204                                     node: ret.element1,
205                                     offset: prefLen + params.fragment.offset
206                                 });
207                             }
208                             return newFragment;
209                         }, {
210                             metadata: {
211                                 description: createParams.unwrapDescription
212                             },
213                             success: callback
214                         });
215                     }
216                 });
217             }
218
219             if(params.fragment instanceof params.fragment.TextRangeFragment && params.fragment.hasSiblingBoundries()) {
220                 parent = params.fragment.startNode.parent();
221                 if(parent && parent.is(createParams.klass) || parent.isInside(createParams.klass)) {
222                     return _.extend(state, {allowed: false});
223                 }
224
225                 return _.extend(state, {
226                     allowed: true,
227                     description: createParams.wrapDescription,
228                     execute: function(callback, params) {
229                         params.fragment.document.transaction(function() {
230                             var parent = params.fragment.startNode.parent(),
231                                 doc = params.fragment.document,
232                                 wrapper, lastTextNode;
233                             
234                             wrapper = parent.wrapText({
235                                 _with: {tagName: 'span', attrs: {'class': createParams.klass}},
236                                 offsetStart: params.fragment.startOffset,
237                                 offsetEnd: params.fragment.endOffset,
238                                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
239                             });
240                                 
241                             lastTextNode = wrapper.getLastTextNode();
242                             if(lastTextNode) {
243                                 return doc.createFragment(doc.CaretFragment, {node: lastTextNode, offset: lastTextNode.getText().length});
244                             }
245                         }, {
246                             metadata: {
247                                 description: createParams.wrapDescription
248                             },
249                             success: callback
250                         });
251                     }
252                 });
253             }
254             return _.extend(state, {allowed: false});
255         }
256     };
257 };
258
259
260 var createLinkFromSelection = function(callback, params) {
261     var doc = params.fragment.document,
262         dialog = Dialog.create({
263             title: gettext('Create link'),
264             executeButtonText: gettext('Apply'),
265             cancelButtonText: gettext('Cancel'),
266             fields: [
267                 {label: gettext('Link'), name: 'href', type: 'input'}
268             ]
269         }),
270         action = this;
271     
272     dialog.on('execute', function(event) {
273         doc.transaction(function() {
274             var span =  action.params.fragment.startNode.parent().wrapText({
275                 _with: {tagName: 'span', attrs: {'class': 'link'}},
276                 offsetStart: params.fragment.startOffset,
277                 offsetEnd: params.fragment.endOffset,
278                 textNodeIdx: [params.fragment.startNode.getIndex(), params.fragment.endNode.getIndex()]
279             }),
280                 doc = params.fragment.document;
281             span.setAttr('href', event.formData.href);
282             event.success();
283             return doc.createFragment(doc.CaretFragment, {node: span.contents()[0], offset:0});
284         }, {
285             metadata: {
286                 description: action.getState().description
287             },
288             success: callback
289         });
290     });
291     dialog.show();
292 };
293
294 var editLink = function(callback, params) {
295     var doc = params.fragment.document,
296         link = params.fragment.node.getParent('link'),
297         dialog = Dialog.create({
298             title: gettext('Edit link'),
299             executeButtonText: gettext('Apply'),
300             cancelButtonText: gettext('Cancel'),
301             fields: [
302                 {label: gettext('Link'), name: 'href', type: 'input', initialValue: link.getAttr('href')}
303             ]
304         }),
305         action = this;
306     
307     dialog.on('execute', function(event) {
308         doc.transaction(function() {
309             link.setAttr('href', event.formData.href);
310             event.success();
311             return params.fragment;
312         }, {
313             metadata: {
314                 description: action.getState().description
315             },
316             success: callback
317         });
318     });
319     dialog.show();
320 };
321
322 var linkAction = {
323     name: 'link',
324     params: {
325         fragment: {type: 'context', name: 'fragment'}
326     },
327     stateDefaults: {
328         label: gettext('link')
329     },
330     getState: function(params) {
331         if(!params.fragment || !params.fragment.isValid()) {
332             return {allowed: false};
333         }
334
335         if(params.fragment instanceof params.fragment.TextRangeFragment) {
336             if(!params.fragment.hasSiblingBoundries() || params.fragment.startNode.parent().is('link')) {
337                 return {allowed: false};
338             }
339             return {
340                 allowed: true,
341                 description: gettext('Create link from selection'),
342                 execute: createLinkFromSelection
343             };
344         }
345
346         if(params.fragment instanceof params.fragment.CaretFragment) {
347             if(params.fragment.node.isInside('link')) {
348                 return {
349                     allowed: true,
350                     toggled: true,
351                     description: gettext('Edit link'),
352                     execute: editLink
353                 };
354             }
355         }
356         return {allowed: false};
357     }
358 };
359
360
361 plugin.actions = [
362     undoRedoAction('undo'),
363     undoRedoAction('redo'),
364     commentAction,
365     createWrapTextAction({name: 'emphasis', klass: 'emp', wrapDescription: gettext('Mark as emphasized'), unwrapDescription: gettext('Remove emphasis')}),
366     createWrapTextAction({name: 'cite', klass: 'cite', wrapDescription: gettext('Mark as citation'), unwrapDescription: gettext('Remove citation')}),
367     linkAction
368 ].concat(plugin.actions, templates.actions, footnote.actions, switchTo.actions, lists.actions);
369
370
371
372 plugin.config = function(config) {
373     // templates.actions[0].config(config.templates);
374     templates.actions[0].params.template.options = config.templates;
375 };
376
377 return plugin;
378
379 });