smartxml: TextNodes don't contain other nodes - let them state that
[fnpeditor.git] / src / editor / plugins / core / switch.js
1 define(function(require) {
2     
3 'use strict';
4 /* globals gettext */
5
6 var _ = require('libs/underscore');
7
8
9 var createSwitchAction = function(createParams) {
10     return  {
11         name: createParams.name,
12         params: {
13             fragment: {type: 'context', name: 'fragment'},
14         },
15         getState: function(params) {
16             var state = {
17                     label: this.config.label
18                 },
19                 f = params.fragment;
20
21
22             if(
23                 !(f && f.isValid()) ||
24                 !((f instanceof f.CaretFragment) || (f instanceof f.TextRangeFragment && f.getCommonParent()))
25             ) {
26                 return _.extend(state, {
27                     allowed: false,
28                     description: 'wrong or no selection'
29                 });
30             }
31
32             var node = f instanceof f.CaretFragment ? f.node.parent() : f.getCommonParent(),
33                 alreadyInTarget = node.isInside(createParams.to),
34                 toSwitch = node;
35
36             if(!toSwitch.is(createParams.from)) {
37                 toSwitch = toSwitch.getParent(createParams.from);
38             }
39
40             return _.extend(state, {
41                 allowed: !!toSwitch,
42                 toggled: alreadyInTarget,
43                 description: 'Switch to ' + createParams.to.name,
44                 execute: alreadyInTarget ? function() {} : function() {
45                     f.document.transaction(function() {
46                         if(createParams.to.tagName) {
47                             toSwitch = toSwitch.setTag(createParams.to.tagName);
48                         }
49                         if(!_.isUndefined(createParams.to.klass)) {
50                             toSwitch.setClass(createParams.to.klass);
51                         }
52                     });
53                 }
54             });
55         }
56     };
57 };
58
59
60 return {
61     actions: [
62         createSwitchAction({name: 'switchToHeader', from: {tagName: 'div', klass: 'p'}, to: {tagName: 'header', klass: '', name: gettext('header')}}),
63         createSwitchAction({name: 'switchToParagraph', from: {tagName: 'header'}, to: {tagName: 'div', klass: 'p', name: gettext('paragraf')}})
64     ]
65 };
66
67 });