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