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