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